cmdbabstract.class.inc.php 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488
  1. <?php
  2. // Copyright (C) 2010-2012 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Abstract class that implements some common and useful methods for displaying
  20. * the objects
  21. *
  22. * @copyright Copyright (C) 2010-2012 Combodo SARL
  23. * @license http://opensource.org/licenses/AGPL-3.0
  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. /**
  87. * Set a message diplayed to the end-user next time this object will be displayed
  88. * Messages are uniquely identified so that plugins can override standard messages (the final work is given to the last plugin to set the message for a given message id)
  89. * In practice, standard messages are recorded at the end but they will not overwrite existing messages
  90. *
  91. * @param string $sClass The class of the object (must be the final class)
  92. * @param int $iKey The identifier of the object
  93. * @param string $sMessageId Your id or one of the well-known ids: 'create', 'update' and 'apply_stimulus'
  94. * @param string $sMessage The HTML message (must be correctly escaped)
  95. * @param string $sSeverity Any of the following: ok, info, error.
  96. * @param float $fRank Ordering of the message: smallest displayed first (can be negative)
  97. * @param bool $bMustNotExist Do not alter any existing message (considering the id)
  98. *
  99. */
  100. public static function SetSessionMessage($sClass, $iKey, $sMessageId, $sMessage, $sSeverity, $fRank, $bMustNotExist = false)
  101. {
  102. $sMessageKey = $sClass.'::'.$iKey;
  103. if (!isset($_SESSION['obj_messages'][$sMessageKey]))
  104. {
  105. $_SESSION['obj_messages'][$sMessageKey] = array();
  106. }
  107. if (!$bMustNotExist || !array_key_exists($sMessageId, $_SESSION['obj_messages'][$sMessageKey]))
  108. {
  109. $_SESSION['obj_messages'][$sMessageKey][$sMessageId] = array(
  110. 'rank' => $fRank,
  111. 'severity' => $sSeverity,
  112. 'message' => $sMessage
  113. );
  114. }
  115. }
  116. function DisplayBareHeader(WebPage $oPage, $bEditMode = false)
  117. {
  118. // Standard Header with name, actions menu and history block
  119. //
  120. // Is there a message for this object ??
  121. $sMessageKey = get_class($this).'::'.$this->GetKey();
  122. if (array_key_exists('obj_messages', $_SESSION) && array_key_exists($sMessageKey, $_SESSION['obj_messages']))
  123. {
  124. $aMessages = array();
  125. $aRanks = array();
  126. foreach ($_SESSION['obj_messages'][$sMessageKey] as $sMessageId => $aMessageData)
  127. {
  128. $sMsgClass = 'message_'.$aMessageData['severity'];
  129. $aMessages[] = "<div class=\"header_message $sMsgClass\">".$aMessageData['message']."</div>";
  130. $aRanks[] = $aMessageData['rank'];
  131. }
  132. array_multisort($aRanks, $aMessages);
  133. foreach ($aMessages as $sMessage)
  134. {
  135. $oPage->add($sMessage);
  136. }
  137. unset($_SESSION['obj_messages'][$sMessageKey]);
  138. }
  139. // action menu
  140. $oSingletonFilter = new DBObjectSearch(get_class($this));
  141. $oSingletonFilter->AddCondition('id', $this->GetKey(), '=');
  142. $oBlock = new MenuBlock($oSingletonFilter, 'details', false);
  143. $oBlock->Display($oPage, -1);
  144. // Master data sources
  145. $sSynchroIcon = '';
  146. $oReplicaSet = $this->GetMasterReplica();
  147. $bSynchronized = false;
  148. $oCreatorTask = null;
  149. $bCanBeDeletedByTask = false;
  150. $bCanBeDeletedByUser = true;
  151. $aMasterSources = array();
  152. if ($oReplicaSet->Count() > 0)
  153. {
  154. $bSynchronized = true;
  155. while($aData = $oReplicaSet->FetchAssoc())
  156. {
  157. // Assumption: $aData['datasource'] will not be null because the data source id is always set...
  158. $sApplicationURL = $aData['datasource']->GetApplicationUrl($this, $aData['replica']);
  159. $sLink = $aData['datasource']->GetName();
  160. if (!empty($sApplicationURL))
  161. {
  162. $sLink = "<a href=\"$sApplicationURL\" target=\"_blank\">".$aData['datasource']->GetName()."</a>";
  163. }
  164. if ($aData['replica']->Get('status_dest_creator') == 1)
  165. {
  166. $oCreatorTask = $aData['datasource'];
  167. $bCreatedByTask = true;
  168. }
  169. else
  170. {
  171. $bCreatedByTask = false;
  172. }
  173. if ($bCreatedByTask)
  174. {
  175. $sDeletePolicy = $aData['datasource']->Get('delete_policy');
  176. if (($sDeletePolicy == 'delete') || ($sDeletePolicy == 'update_then_delete'))
  177. {
  178. $bCanBeDeletedByTask = true;
  179. }
  180. $sUserDeletePolicy = $aData['datasource']->Get('user_delete_policy');
  181. if ($sUserDeletePolicy == 'nobody')
  182. {
  183. $bCanBeDeletedByUser = false;
  184. }
  185. elseif (($sUserDeletePolicy == 'administrators') && !UserRights::IsAdministrator())
  186. {
  187. $bCanBeDeletedByUser = false;
  188. }
  189. else // everybody...
  190. {
  191. }
  192. }
  193. $aMasterSources[$aData['datasource']->GetKey()]['datasource'] = $aData['datasource'];
  194. $aMasterSources[$aData['datasource']->GetKey()]['url'] = $sLink;
  195. $aMasterSources[$aData['datasource']->GetKey()]['last_synchro'] = $aData['replica']->Get('status_last_seen');
  196. }
  197. if (is_object($oCreatorTask))
  198. {
  199. $sTaskUrl = $aMasterSources[$oCreatorTask->GetKey()]['url'];
  200. if (!$bCanBeDeletedByUser)
  201. {
  202. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectCannotBeDeletedByUser_Source', $sTaskUrl)."</p>";
  203. }
  204. else
  205. {
  206. $sTip = "<p>".Dict::Format('Core:Synchro:TheObjectWasCreatedBy_Source', $sTaskUrl)."</p>";
  207. }
  208. if ($bCanBeDeletedByTask)
  209. {
  210. $sTip .= "<p>".Dict::Format('Core:Synchro:TheObjectCanBeDeletedBy_Source', $sTaskUrl)."</p>";
  211. }
  212. }
  213. else
  214. {
  215. $sTip = "<p>".Dict::S('Core:Synchro:ThisObjectIsSynchronized')."</p>";
  216. }
  217. $sTip .= "<p><b>".Dict::S('Core:Synchro:ListOfDataSources')."</b></p>";
  218. foreach($aMasterSources as $aStruct)
  219. {
  220. $oDataSource = $aStruct['datasource'];
  221. $sLink = $aStruct['url'];
  222. $sTip .= "<p style=\"white-space:nowrap\">".$oDataSource->GetIcon(true, 'style="vertical-align:middle"')."&nbsp;$sLink<br/>";
  223. $sTip .= Dict::S('Core:Synchro:LastSynchro').'<br/>'.$aStruct['last_synchro']."</p>";
  224. }
  225. $sSynchroIcon = '&nbsp;<img style="vertical-align:middle;" id="synchro_icon" src="../images/locked.png"/>';
  226. $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' }} } );");
  227. }
  228. $oPage->add("<div class=\"page_header\"><h1>".$this->GetIcon()."&nbsp;\n");
  229. $sRefreshIcon = '';
  230. if ($_SERVER['REQUEST_METHOD'] == 'GET')
  231. {
  232. $sRefreshIcon = '<img src="../images/reload.png" style="cursor:pointer;vertical-align:middle;margin-left:1em;" onclick="window.location.reload();" title="'.htmlentities(Dict::S('UI:Button:Refresh'), ENT_QUOTES, 'UTF-8').'"/>';
  233. }
  234. $oPage->add(MetaModel::GetName(get_class($this)).": <span class=\"hilite\">".$this->GetName()."</span>$sRefreshIcon $sSynchroIcon</h1>\n");
  235. $oPage->add("</div>\n");
  236. }
  237. function DisplayBareHistory(WebPage $oPage, $bEditMode = false)
  238. {
  239. // history block (with as a tab)
  240. $oHistoryFilter = new DBObjectSearch('CMDBChangeOp');
  241. $oHistoryFilter->AddCondition('objkey', $this->GetKey(), '=');
  242. $oHistoryFilter->AddCondition('objclass', get_class($this), '=');
  243. $oBlock = new HistoryBlock($oHistoryFilter, 'table', false);
  244. $oBlock->Display($oPage, -1);
  245. }
  246. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  247. {
  248. $aFieldsMap = $this->GetBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  249. if (!isset($aExtraParams['disable_plugins']) || !$aExtraParams['disable_plugins'])
  250. {
  251. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  252. {
  253. $oExtensionInstance->OnDisplayProperties($this, $oPage, $bEditMode);
  254. }
  255. }
  256. // Special case to display the case log, if any...
  257. // WARNING: if you modify the loop below, also check the corresponding code in UpdateObject and DisplayModifyForm
  258. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  259. {
  260. if ($oAttDef instanceof AttributeCaseLog)
  261. {
  262. $sComment = (isset($aExtraParams['fieldsComments'][$sAttCode])) ? $aExtraParams['fieldsComments'][$sAttCode] : '';
  263. $this->DisplayCaseLog($oPage, $sAttCode, $sComment, $sPrefix, $bEditMode);
  264. }
  265. }
  266. return $aFieldsMap;
  267. }
  268. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  269. {
  270. // Related objects: display all the linkset attributes, each as a separate tab
  271. // In the order described by the 'display' ZList
  272. $aList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  273. if (count($aList) == 0)
  274. {
  275. // Empty ZList defined, display all the linkedset attributes defined
  276. $aList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  277. }
  278. $sClass = get_class($this);
  279. foreach($aList as $sAttCode)
  280. {
  281. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  282. // Display mode
  283. if (!$oAttDef->IsLinkset()) continue; // Process only linkset attributes...
  284. // $oSet = new DBObjectSet($this->Get($sAttCode)->GetFilter()); // Why do something so useless ?
  285. $oSet = $this->Get($sAttCode);
  286. $iCount = $oSet->Count();
  287. $sCount = '';
  288. if ($iCount != 0)
  289. {
  290. $sCount = " ($iCount)";
  291. }
  292. $oPage->SetCurrentTab($oAttDef->GetLabel().$sCount);
  293. if ($this->IsNew())
  294. {
  295. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  296. }
  297. else
  298. {
  299. $iFlags = $this->GetAttributeFlags($sAttCode);
  300. }
  301. $bReadOnly = ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE));
  302. if ($bEditMode && (!$bReadOnly))
  303. {
  304. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  305. $sLinkedClass = $oAttDef->GetLinkedClass();
  306. if ($oAttDef->IsIndirect())
  307. {
  308. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  309. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  310. }
  311. else
  312. {
  313. $sTargetClass = $sLinkedClass;
  314. }
  315. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription().'<span id="busy_'.$sInputId.'"></span>');
  316. $oValue = $this->Get($sAttCode);
  317. $sDisplayValue = ''; // not used
  318. $aArgs = array('this' => $this);
  319. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $oValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  320. $aFieldsMap[$sAttCode] = $sInputId;
  321. $oPage->add($sHTMLValue);
  322. }
  323. else
  324. {
  325. // Display mode
  326. if (!$oAttDef->IsIndirect())
  327. {
  328. // 1:n links
  329. $sTargetClass = $oAttDef->GetLinkedClass();
  330. $aDefaults = array($oAttDef->GetExtKeyToMe() => $this->GetKey());
  331. $oAppContext = new ApplicationContext();
  332. foreach($oAppContext->GetNames() as $sKey)
  333. {
  334. // The linked object inherits the parent's value for the context
  335. if (MetaModel::IsValidAttCode($sClass, $sKey))
  336. {
  337. $aDefaults[$sKey] = $this->Get($sKey);
  338. }
  339. }
  340. $aParams = array(
  341. 'target_attr' => $oAttDef->GetExtKeyToMe(),
  342. 'object_id' => $this->GetKey(),
  343. 'menu' => false,
  344. 'default' => $aDefaults,
  345. 'table_id' => $sClass.'_'.$sAttCode,
  346. );
  347. }
  348. else
  349. {
  350. // n:n links
  351. $sLinkedClass = $oAttDef->GetLinkedClass();
  352. $oLinkingAttDef = MetaModel::GetAttributeDef($sLinkedClass, $oAttDef->GetExtKeyToRemote());
  353. $sTargetClass = $oLinkingAttDef->GetTargetClass();
  354. $bMenu = ($this->Get($sAttCode)->Count() > 0); // The menu is enabled only if there are already some elements...
  355. $aParams = array(
  356. 'link_attr' => $oAttDef->GetExtKeyToMe(),
  357. 'object_id' => $this->GetKey(),
  358. 'target_attr' => $oAttDef->GetExtKeyToRemote(),
  359. 'view_link' => false,
  360. 'menu' => false,
  361. 'display_limit' => true, // By default limit the list to speed up the initial load & display
  362. 'table_id' => $sClass.'_'.$sAttCode,
  363. );
  364. }
  365. $oPage->p(MetaModel::GetClassIcon($sTargetClass)."&nbsp;".$oAttDef->GetDescription());
  366. $oBlock = new DisplayBlock($this->Get($sAttCode)->GetFilter(), 'list', false);
  367. $oBlock->Display($oPage, 'rel_'.$sAttCode, $aParams);
  368. }
  369. }
  370. $oPage->SetCurrentTab('');
  371. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  372. {
  373. $oExtensionInstance->OnDisplayRelations($this, $oPage, $bEditMode);
  374. }
  375. // Display Notifications after the other tabs since this tab disappears in edition
  376. if (!$bEditMode)
  377. {
  378. // Get the actual class of the current object
  379. // And look for triggers referring to it
  380. // If any trigger has been found then display a tab with notifications
  381. //
  382. $sClass = get_class($this);
  383. $sClassList = implode("', '", MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
  384. $oTriggerSet = new CMDBObjectSet(DBObjectSearch::FromOQL("SELECT TriggerOnObject AS T WHERE T.target_class IN ('$sClassList')"));
  385. if ($oTriggerSet->Count() > 0)
  386. {
  387. // Display notifications regarding the object
  388. $iId = $this->GetKey();
  389. $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");
  390. $oNotifSet = new DBObjectSet($oNotifSearch);
  391. $sCount = ($oNotifSet->Count() > 0) ? ' ('.$oNotifSet->Count().')' : '';
  392. $oPage->SetCurrentTab(Dict::S('UI:NotificationsTab').$sCount);
  393. $oBlock = new DisplayBlock($oNotifSearch, 'list', false);
  394. $oBlock->Display($oPage, 'notifications', array('menu' => false));
  395. }
  396. }
  397. }
  398. function GetBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix, $aExtraParams = array())
  399. {
  400. $sHtml = '';
  401. $oAppContext = new ApplicationContext();
  402. $sStateAttCode = MetaModel::GetStateAttributeCode(get_class($this));
  403. $aDetails = array();
  404. $sClass = get_class($this);
  405. $aDetailsList = MetaModel::GetZListItems($sClass, 'details');
  406. $aDetailsStruct = self::ProcessZlist($aDetailsList, array('UI:PropertiesTab' => array()), 'UI:PropertiesTab', 'col1', '');
  407. // Compute the list of properties to display, first the attributes in the 'details' list, then
  408. // all the remaining attributes that are not external fields
  409. $sHtml = '';
  410. $aDetails = array();
  411. $iInputId = 0;
  412. $aFieldsMap = array();
  413. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  414. $aExtraFlags = (isset($aExtraParams['fieldsFlags'])) ? $aExtraParams['fieldsFlags'] : array();
  415. $bFieldComments = (count($aFieldsComments) > 0);
  416. foreach($aDetailsStruct as $sTab => $aCols )
  417. {
  418. $aDetails[$sTab] = array();
  419. ksort($aCols);
  420. $oPage->SetCurrentTab(Dict::S($sTab));
  421. $oPage->add('<table style="vertical-align:top"><tr>');
  422. foreach($aCols as $sColIndex => $aFieldsets)
  423. {
  424. $oPage->add('<td style="vertical-align:top">');
  425. //$aDetails[$sTab][$sColIndex] = array();
  426. $sLabel = '';
  427. $sPreviousLabel = '';
  428. $aDetails[$sTab][$sColIndex] = array();
  429. foreach($aFieldsets as $sFieldsetName => $aFields)
  430. {
  431. if (!empty($sFieldsetName) && ($sFieldsetName[0] != '_'))
  432. {
  433. $sLabel = $sFieldsetName;
  434. }
  435. else
  436. {
  437. $sLabel = '';
  438. }
  439. if ($sLabel != $sPreviousLabel)
  440. {
  441. if (!empty($sPreviousLabel))
  442. {
  443. $oPage->add('<fieldset>');
  444. $oPage->add('<legend>'.Dict::S($sPreviousLabel).'</legend>');
  445. }
  446. $oPage->Details($aDetails[$sTab][$sColIndex]);
  447. if (!empty($sPreviousLabel))
  448. {
  449. $oPage->add('</fieldset>');
  450. }
  451. $aDetails[$sTab][$sColIndex] = array();
  452. $sPreviousLabel = $sLabel;
  453. }
  454. foreach($aFields as $sAttCode)
  455. {
  456. if ($bEditMode)
  457. {
  458. $sComments = isset($aFieldsComments[$sAttCode]) ? $aFieldsComments[$sAttCode] : '&nbsp;';
  459. $sInfos = '&nbsp;';
  460. if ($this->IsNew())
  461. {
  462. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  463. }
  464. else
  465. {
  466. $iFlags = $this->GetAttributeFlags($sAttCode);
  467. }
  468. if (($iFlags & OPT_ATT_MANDATORY) && $this->IsNew())
  469. {
  470. $iFlags = $iFlags & ~OPT_ATT_READONLY; // Mandatory fields cannot be read-only when creating an object
  471. }
  472. if (array_key_exists($sAttCode, $aExtraFlags))
  473. {
  474. // the caller may override some flags if needed
  475. $iFlags = $iFlags | $aExtraFlags[$sAttCode];
  476. }
  477. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  478. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0))
  479. {
  480. if ($oAttDef->IsWritable())
  481. {
  482. if ($sStateAttCode == $sAttCode)
  483. {
  484. // State attribute is always read-only from the UI
  485. $sHTMLValue = $this->GetStateLabel();
  486. $val = array('label' => '<span>'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  487. }
  488. else
  489. {
  490. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  491. if ($iFlags & OPT_ATT_HIDDEN)
  492. {
  493. // Attribute is hidden, add a hidden input
  494. $oPage->add('<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>');
  495. $aFieldsMap[$sAttCode] = $sInputId;
  496. }
  497. else
  498. {
  499. if ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE))
  500. {
  501. // Check if the attribute is not read-only because of a synchro...
  502. $aReasons = array();
  503. $sSynchroIcon = '';
  504. if ($iFlags & OPT_ATT_SLAVE)
  505. {
  506. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  507. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  508. $sTip = '';
  509. foreach($aReasons as $aRow)
  510. {
  511. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  512. }
  513. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  514. }
  515. // Attribute is read-only
  516. $sHTMLValue = "<span id=\"field_{$sInputId}\">".$this->GetAsHTML($sAttCode);
  517. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/></span>';
  518. $aFieldsMap[$sAttCode] = $sInputId;
  519. $sComments = $sSynchroIcon;
  520. }
  521. else
  522. {
  523. $sValue = $this->Get($sAttCode);
  524. $sDisplayValue = $this->GetEditValue($sAttCode);
  525. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  526. $sHTMLValue = "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  527. $aFieldsMap[$sAttCode] = $sInputId;
  528. }
  529. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  530. }
  531. }
  532. }
  533. else
  534. {
  535. $val = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $this->GetAsHTML($sAttCode), 'comments' => $sComments, 'infos' => $sInfos);
  536. }
  537. }
  538. else
  539. {
  540. $val = null; // Skip this field
  541. }
  542. }
  543. else
  544. {
  545. // !bEditMode
  546. $val = $this->GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode);
  547. }
  548. if ($val != null)
  549. {
  550. // The field is visible, add it to the current column
  551. $aDetails[$sTab][$sColIndex][] = $val;
  552. $iInputId++;
  553. }
  554. }
  555. }
  556. if (!empty($sPreviousLabel))
  557. {
  558. $oPage->add('<fieldset>');
  559. $oPage->add('<legend>'.Dict::S($sFieldsetName).'</legend>');
  560. }
  561. $oPage->Details($aDetails[$sTab][$sColIndex]);
  562. if (!empty($sPreviousLabel))
  563. {
  564. $oPage->add('</fieldset>');
  565. }
  566. $oPage->add('</td>');
  567. }
  568. $oPage->add('</tr></table>');
  569. }
  570. return $aFieldsMap;
  571. }
  572. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  573. {
  574. $sTemplate = Utils::ReadFromFile(MetaModel::GetDisplayTemplate(get_class($this)));
  575. if (!empty($sTemplate))
  576. {
  577. $oTemplate = new DisplayTemplate($sTemplate);
  578. // Note: to preserve backward compatibility with home-made templates, the placeholder '$pkey$' has been preserved
  579. // but the preferred method is to use '$id$'
  580. $oTemplate->Render($oPage, array('class_name'=> MetaModel::GetName(get_class($this)),'class'=> get_class($this), 'pkey'=> $this->GetKey(), 'id'=> $this->GetKey(), 'name' => $this->GetName()));
  581. }
  582. else
  583. {
  584. // Object's details
  585. // template not found display the object using the *old style*
  586. $this->DisplayBareHeader($oPage, $bEditMode);
  587. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  588. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  589. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  590. $this->DisplayBareProperties($oPage, $bEditMode);
  591. $this->DisplayBareRelations($oPage, $bEditMode);
  592. $oPage->SetCurrentTab(Dict::S('UI:HistoryTab'));
  593. $this->DisplayBareHistory($oPage, $bEditMode);
  594. }
  595. }
  596. function DisplayPreview(WebPage $oPage)
  597. {
  598. $aDetails = array();
  599. $sClass = get_class($this);
  600. $aList = MetaModel::GetZListItems($sClass, 'preview');
  601. foreach($aList as $sAttCode)
  602. {
  603. $aDetails[] = array('label' => MetaModel::GetLabel($sClass, $sAttCode), 'value' =>$this->GetAsHTML($sAttCode));
  604. }
  605. $oPage->details($aDetails);
  606. }
  607. public static function DisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  608. {
  609. $oPage->add(self::GetDisplaySet($oPage, $oSet, $aExtraParams));
  610. }
  611. /**
  612. * Get the HTML fragment corresponding to the display of a table representing a set of objects
  613. * @param WebPage $oPage The page object is used for out-of-band information (mostly scripts) output
  614. * @param CMDBObjectSet The set of objects to display
  615. * @param Hash $aExtraParams Some extra configuration parameters to tweak the behavior of the display
  616. * @return String The HTML fragment representing the table of objects
  617. */
  618. public static function GetDisplaySet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  619. {
  620. if (empty($aExtraParams['currentId']))
  621. {
  622. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  623. }
  624. else
  625. {
  626. $iListId = $aExtraParams['currentId'];
  627. }
  628. // Initialize and check the parameters
  629. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  630. $sLinkageAttribute = isset($aExtraParams['link_attr']) ? $aExtraParams['link_attr'] : '';
  631. $iLinkedObjectId = isset($aExtraParams['object_id']) ? $aExtraParams['object_id'] : 0;
  632. $sTargetAttr = isset($aExtraParams['target_attr']) ? $aExtraParams['target_attr'] : '';
  633. if (!empty($sLinkageAttribute))
  634. {
  635. if($iLinkedObjectId == 0)
  636. {
  637. // if 'links' mode is requested the id of the object to link to must be specified
  638. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_object_id'));
  639. }
  640. if($sTargetAttr == '')
  641. {
  642. // if 'links' mode is requested the d of the object to link to must be specified
  643. throw new ApplicationException(Dict::S('UI:Error:MandatoryTemplateParameter_target_attr'));
  644. }
  645. }
  646. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  647. $bTruncated = isset($aExtraParams['truncated']) ? $aExtraParams['truncated'] == true : true;
  648. $bSelectMode = isset($aExtraParams['selection_mode']) ? $aExtraParams['selection_mode'] == true : false;
  649. $bSingleSelectMode = isset($aExtraParams['selection_type']) ? ($aExtraParams['selection_type'] == 'single') : false;
  650. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  651. $aExtraFields = array();
  652. foreach ($aExtraFieldsRaw as $sFieldName)
  653. {
  654. // Ignore attributes not of the main queried class
  655. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  656. {
  657. $sClassAlias = $aMatches[1];
  658. $sAttCode = $aMatches[2];
  659. if ($sClassAlias == $oSet->GetFilter()->GetClassAlias())
  660. {
  661. $aExtraFields[] = $sAttCode;
  662. }
  663. }
  664. else
  665. {
  666. $aExtraFields[] = $sFieldName;
  667. }
  668. }
  669. $sHtml = '';
  670. $oAppContext = new ApplicationContext();
  671. $sClassName = $oSet->GetFilter()->GetClass();
  672. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  673. if ($sZListName !== false)
  674. {
  675. $aList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  676. $aList = array_merge($aList, $aExtraFields);
  677. }
  678. else
  679. {
  680. $aList = $aExtraFields;
  681. }
  682. // Filter the list to removed linked set since we are not able to display them here
  683. foreach($aList as $index => $sAttCode)
  684. {
  685. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  686. if ($oAttDef instanceof AttributeLinkedSet)
  687. {
  688. // Removed from the display list
  689. unset($aList[$index]);
  690. }
  691. }
  692. if (!empty($sLinkageAttribute))
  693. {
  694. // The set to display is in fact a set of links between the object specified in the $sLinkageAttribute
  695. // and other objects...
  696. // The display will then group all the attributes related to the link itself:
  697. // | Link_attr1 | link_attr2 | ... || Object_attr1 | Object_attr2 | Object_attr3 | .. | Object_attr_n |
  698. $aDisplayList = array();
  699. $aAttDefs = MetaModel::ListAttributeDefs($sClassName);
  700. assert(isset($aAttDefs[$sLinkageAttribute]));
  701. $oAttDef = $aAttDefs[$sLinkageAttribute];
  702. assert($oAttDef->IsExternalKey());
  703. // First display all the attributes specific to the link record
  704. foreach($aList as $sLinkAttCode)
  705. {
  706. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  707. if ( (!$oLinkAttDef->IsExternalKey()) && (!$oLinkAttDef->IsExternalField()) )
  708. {
  709. $aDisplayList[] = $sLinkAttCode;
  710. }
  711. }
  712. // Then display all the attributes neither specific to the link record nor to the 'linkage' object (because the latter are constant)
  713. foreach($aList as $sLinkAttCode)
  714. {
  715. $oLinkAttDef = $aAttDefs[$sLinkAttCode];
  716. if (($oLinkAttDef->IsExternalKey() && ($sLinkAttCode != $sLinkageAttribute))
  717. || ($oLinkAttDef->IsExternalField() && ($oLinkAttDef->GetKeyAttCode()!=$sLinkageAttribute)) )
  718. {
  719. $aDisplayList[] = $sLinkAttCode;
  720. }
  721. }
  722. // First display all the attributes specific to the link
  723. // Then display all the attributes linked to the other end of the relationship
  724. $aList = $aDisplayList;
  725. }
  726. $sSelectMode = 'none';
  727. if ($bSelectMode)
  728. {
  729. $sSelectMode = $bSingleSelectMode ? 'single' : 'multiple';
  730. }
  731. $sClassAlias = $oSet->GetClassAlias();
  732. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  733. // Load only the requested columns
  734. $oSet->OptimizeColumnLoad(array($sClassAlias => $aList));
  735. $sTableId = isset($aExtraParams['table_id']) ? $aExtraParams['table_id'] : null;
  736. $aClassAliases = array( $sClassAlias => $sClassName);
  737. $oDataTable = new DataTable($iListId, $oSet, $aClassAliases, $sTableId);
  738. $oSettings = DataTableSettings::GetDataModelSettings($aClassAliases, $bViewLink, array($sClassAlias => $aList));
  739. if ($bDisplayLimit)
  740. {
  741. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  742. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  743. }
  744. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  745. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  746. }
  747. public static function GetDisplayExtendedSet(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  748. {
  749. if (empty($aExtraParams['currentId']))
  750. {
  751. $iListId = $oPage->GetUniqueId(); // Works only if not in an Ajax page !!
  752. }
  753. else
  754. {
  755. $iListId = $aExtraParams['currentId'];
  756. }
  757. $aList = array();
  758. // Initialize and check the parameters
  759. $bViewLink = isset($aExtraParams['view_link']) ? $aExtraParams['view_link'] : true;
  760. $bDisplayMenu = isset($aExtraParams['menu']) ? $aExtraParams['menu'] == true : true;
  761. // Check if there is a list of aliases to limit the display to...
  762. $aDisplayAliases = isset($aExtraParams['display_aliases']) ? explode(',', $aExtraParams['display_aliases']) : array();
  763. $sZListName = isset($aExtraParams['zlist']) ? ($aExtraParams['zlist']) : 'list';
  764. $aExtraFieldsRaw = isset($aExtraParams['extra_fields']) ? explode(',', trim($aExtraParams['extra_fields'])) : array();
  765. $aExtraFields = array();
  766. foreach ($aExtraFieldsRaw as $sFieldName)
  767. {
  768. // Ignore attributes not of the main queried class
  769. if (preg_match('/^(.*)\.(.*)$/', $sFieldName, $aMatches))
  770. {
  771. $sClassAlias = $aMatches[1];
  772. $sAttCode = $aMatches[2];
  773. if (array_key_exists($sClassAlias, $oSet->GetSelectedClasses()))
  774. {
  775. $aExtraFields[$sClassAlias][] = $sAttCode;
  776. }
  777. }
  778. else
  779. {
  780. $aExtraFields['*'] = $sAttCode;
  781. }
  782. }
  783. $sHtml = '';
  784. $oAppContext = new ApplicationContext();
  785. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  786. $aAuthorizedClasses = array();
  787. foreach($aClasses as $sAlias => $sClassName)
  788. {
  789. if ( (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS)) &&
  790. ( (count($aDisplayAliases) == 0) || (in_array($sAlias, $aDisplayAliases))) )
  791. {
  792. $aAuthorizedClasses[$sAlias] = $sClassName;
  793. }
  794. }
  795. $aAttribs = array();
  796. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  797. {
  798. if (array_key_exists($sAlias, $aExtraFields))
  799. {
  800. $aList[$sAlias] = $aExtraFields[$sAlias];
  801. }
  802. else
  803. {
  804. $aList[$sAlias] = array();
  805. }
  806. if ($sZListName !== false)
  807. {
  808. $aDefaultList = self::FlattenZList(MetaModel::GetZListItems($sClassName, $sZListName));
  809. $aList[$sAlias] = array_merge($aDefaultList, $aList[$sAlias]);
  810. }
  811. // Filter the list to removed linked set since we are not able to display them here
  812. foreach($aList[$sAlias] as $index => $sAttCode)
  813. {
  814. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sAttCode);
  815. if ($oAttDef instanceof AttributeLinkedSet)
  816. {
  817. // Removed from the display list
  818. unset($aList[$sAlias][$index]);
  819. }
  820. }
  821. }
  822. // Load only the requested columns
  823. $aAttToLoad = array(); // attributes to load
  824. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  825. {
  826. foreach($aList[$sAlias] as $sAttCode)
  827. {
  828. $aAttToLoad[$sAlias][] = $sAttCode;
  829. }
  830. }
  831. $oSet->OptimizeColumnLoad($aAttToLoad);
  832. $sSelectMode = 'none';
  833. $sClassAlias = $oSet->GetClassAlias();
  834. $oDataTable = new DataTable($iListId, $oSet, $aAuthorizedClasses);
  835. $oSettings = DataTableSettings::GetDataModelSettings($aAuthorizedClasses, $bViewLink, $aList);
  836. $bDisplayLimit = isset($aExtraParams['display_limit']) ? $aExtraParams['display_limit'] : true;
  837. if ($bDisplayLimit)
  838. {
  839. $iDefaultPageSize = appUserPreferences::GetPref('default_page_size', MetaModel::GetConfig()->GetMinDisplayLimit());
  840. $oSettings->iDefaultPageSize = $iDefaultPageSize;
  841. }
  842. $oSettings->aSortOrder = MetaModel::GetOrderByDefault($sClassName);
  843. return $oDataTable->Display($oPage, $oSettings, $bDisplayMenu, $sSelectMode, $bViewLink, $aExtraParams);
  844. }
  845. static function DisplaySetAsCSV(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  846. {
  847. $oPage->add(self::GetSetAsCSV($oSet, $aParams));
  848. }
  849. static function GetSetAsCSV(DBObjectSet $oSet, $aParams = array())
  850. {
  851. $sSeparator = isset($aParams['separator']) ? $aParams['separator'] : ','; // default separator is comma
  852. $sTextQualifier = isset($aParams['text_qualifier']) ? $aParams['text_qualifier'] : '"'; // default text qualifier is double quote
  853. $aFields = null;
  854. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  855. {
  856. $aFields = explode(',', $aParams['fields']);
  857. }
  858. $bFieldsAdvanced = false;
  859. if (isset($aParams['fields_advanced']))
  860. {
  861. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  862. }
  863. $bLocalize = true;
  864. if (isset($aParams['localize_values']))
  865. {
  866. $bLocalize = (bool) $aParams['localize_values'];
  867. }
  868. $aList = array();
  869. $oAppContext = new ApplicationContext();
  870. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  871. $aAuthorizedClasses = array();
  872. foreach($aClasses as $sAlias => $sClassName)
  873. {
  874. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  875. {
  876. $aAuthorizedClasses[$sAlias] = $sClassName;
  877. }
  878. }
  879. $aAttribs = array();
  880. $aHeader = array();
  881. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  882. {
  883. $aList[$sAlias] = array();
  884. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  885. {
  886. if (is_null($aFields) || (count($aFields) == 0))
  887. {
  888. // Standard list of attributes (no link sets)
  889. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  890. {
  891. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  892. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  893. {
  894. if ($bFieldsAdvanced)
  895. {
  896. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  897. if ($oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  898. {
  899. $sRemoteClass = $oAttDef->GetTargetClass();
  900. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  901. {
  902. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  903. }
  904. }
  905. }
  906. }
  907. else
  908. {
  909. // Any other attribute
  910. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  911. }
  912. }
  913. }
  914. else
  915. {
  916. // User defined list of attributes
  917. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  918. {
  919. $aList[$sAlias][$sAttCode] = $oAttDef;
  920. }
  921. }
  922. }
  923. if ($bFieldsAdvanced)
  924. {
  925. $aHeader[] = 'id';
  926. }
  927. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  928. {
  929. $sStar = '';
  930. if (!$oAttDef->IsNullAllowed() && isset($aParams['showMandatoryFields']))
  931. {
  932. $sStar = '*';
  933. }
  934. $aHeader[] = ($bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx).$sStar;
  935. }
  936. }
  937. $sHtml = implode($sSeparator, $aHeader)."\n";
  938. $oSet->Seek(0);
  939. while ($aObjects = $oSet->FetchAssoc())
  940. {
  941. $aRow = array();
  942. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  943. {
  944. $oObj = $aObjects[$sAlias];
  945. if ($bFieldsAdvanced)
  946. {
  947. if (is_null($oObj))
  948. {
  949. $aRow[] = '';
  950. }
  951. else
  952. {
  953. $aRow[] = $oObj->GetKey();
  954. }
  955. }
  956. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  957. {
  958. if (is_null($oObj))
  959. {
  960. $aRow[] = '';
  961. }
  962. else
  963. {
  964. $value = $oObj->Get($sAttCodeEx);
  965. $aRow[] = $oAttDef->GetAsCSV($value, $sSeparator, $sTextQualifier, $oObj, $bLocalize);
  966. }
  967. }
  968. }
  969. $sHtml .= implode($sSeparator, $aRow)."\n";
  970. }
  971. return $sHtml;
  972. }
  973. static function DisplaySetAsHTMLSpreadsheet(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  974. {
  975. $oPage->add(self::GetSetAsHTMLSpreadsheet($oSet, $aParams));
  976. }
  977. /**
  978. * Spreadsheet output: designed for end users doing some reporting
  979. * Then the ids are excluded and replaced by the corresponding friendlyname
  980. */
  981. static function GetSetAsHTMLSpreadsheet(DBObjectSet $oSet, $aParams = array())
  982. {
  983. $aFields = null;
  984. if (isset($aParams['fields']) && (strlen($aParams['fields']) > 0))
  985. {
  986. $aFields = explode(',', $aParams['fields']);
  987. }
  988. $bFieldsAdvanced = false;
  989. if (isset($aParams['fields_advanced']))
  990. {
  991. $bFieldsAdvanced = (bool) $aParams['fields_advanced'];
  992. }
  993. $bLocalize = true;
  994. if (isset($aParams['localize_values']))
  995. {
  996. $bLocalize = (bool) $aParams['localize_values'];
  997. }
  998. $aList = array();
  999. $oAppContext = new ApplicationContext();
  1000. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1001. $aAuthorizedClasses = array();
  1002. foreach($aClasses as $sAlias => $sClassName)
  1003. {
  1004. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1005. {
  1006. $aAuthorizedClasses[$sAlias] = $sClassName;
  1007. }
  1008. }
  1009. $aAttribs = array();
  1010. $aHeader = array();
  1011. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1012. {
  1013. $aList[$sAlias] = array();
  1014. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode => $oAttDef)
  1015. {
  1016. if (is_null($aFields) || (count($aFields) == 0))
  1017. {
  1018. // Standard list of attributes (no link sets)
  1019. if ($oAttDef->IsScalar() && ($oAttDef->IsWritable() || $oAttDef->IsExternalField()))
  1020. {
  1021. $sAttCodeEx = $oAttDef->IsExternalField() ? $oAttDef->GetKeyAttCode().'->'.$oAttDef->GetExtAttCode() : $sAttCode;
  1022. $aList[$sAlias][$sAttCodeEx] = $oAttDef;
  1023. if ($bFieldsAdvanced && $oAttDef->IsExternalKey(EXTKEY_RELATIVE))
  1024. {
  1025. $sRemoteClass = $oAttDef->GetTargetClass();
  1026. foreach(MetaModel::GetReconcKeys($sRemoteClass) as $sRemoteAttCode)
  1027. {
  1028. $aList[$sAlias][$sAttCode.'->'.$sRemoteAttCode] = MetaModel::GetAttributeDef($sRemoteClass, $sRemoteAttCode);
  1029. }
  1030. }
  1031. }
  1032. }
  1033. else
  1034. {
  1035. // User defined list of attributes
  1036. if (in_array($sAttCode, $aFields) || in_array($sAlias.'.'.$sAttCode, $aFields))
  1037. {
  1038. $aList[$sAlias][$sAttCode] = $oAttDef;
  1039. }
  1040. }
  1041. }
  1042. // Replace external key by the corresponding friendly name (if not already in the list)
  1043. foreach($aList[$sAlias] as $sAttCode => $oAttDef)
  1044. {
  1045. if ($oAttDef->IsExternalKey())
  1046. {
  1047. unset($aList[$sAlias][$sAttCode]);
  1048. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1049. if (!array_key_exists($sFriendlyNameAttCode, $aList[$sAlias]) && MetaModel::IsValidAttCode($sClassName, $sFriendlyNameAttCode))
  1050. {
  1051. $oFriendlyNameAtt = MetaModel::GetAttributeDef($sClassName, $sFriendlyNameAttCode);
  1052. $aList[$sAlias][$sFriendlyNameAttCode] = $oFriendlyNameAtt;
  1053. }
  1054. }
  1055. }
  1056. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1057. {
  1058. $sColLabel = $bLocalize ? MetaModel::GetLabel($sClassName, $sAttCodeEx) : $sAttCodeEx;
  1059. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1060. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1061. {
  1062. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Date').')';
  1063. $aHeader[] = $sColLabel.' ('.Dict::S('UI:SplitDateTime-Time').')';
  1064. }
  1065. else
  1066. {
  1067. $aHeader[] = $sColLabel;
  1068. }
  1069. }
  1070. }
  1071. $sHtml = "<table border=\"1\">\n";
  1072. $sHtml .= "<tr>\n";
  1073. $sHtml .= "<td>".implode("</td><td>", $aHeader)."</td>\n";
  1074. $sHtml .= "</tr>\n";
  1075. $oSet->Seek(0);
  1076. while ($aObjects = $oSet->FetchAssoc())
  1077. {
  1078. $aRow = array();
  1079. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1080. {
  1081. $oObj = $aObjects[$sAlias];
  1082. foreach($aList[$sAlias] as $sAttCodeEx => $oAttDef)
  1083. {
  1084. if (is_null($oObj))
  1085. {
  1086. $aRow[] = '<td></td>';
  1087. }
  1088. else
  1089. {
  1090. $oFinalAttDef = $oAttDef->GetFinalAttDef();
  1091. if (get_class($oFinalAttDef) == 'AttributeDateTime')
  1092. {
  1093. $iDate = AttributeDateTime::GetAsUnixSeconds($oObj->Get($sAttCodeEx));
  1094. $aRow[] = '<td>'.date('Y-m-d', $iDate).'</td>';
  1095. $aRow[] = '<td>'.date('H:i:s', $iDate).'</td>';
  1096. }
  1097. else
  1098. {
  1099. $rawValue = $oObj->Get($sAttCodeEx);
  1100. if ($oAttDef instanceof AttributeFriendlyName)
  1101. {
  1102. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1103. if ($oObj->Get($sKeyAttCode) == 0)
  1104. {
  1105. $rawValue = '';
  1106. }
  1107. }
  1108. if ($bLocalize)
  1109. {
  1110. $outputValue = htmlentities($oFinalAttDef->GetEditValue($rawValue), ENT_QUOTES, 'UTF-8');
  1111. }
  1112. else
  1113. {
  1114. $outputValue = htmlentities($rawValue, ENT_QUOTES, 'UTF-8');
  1115. }
  1116. $aRow[] = '<td>'.$outputValue.'</td>';
  1117. }
  1118. }
  1119. }
  1120. }
  1121. $sHtml .= implode("\n", $aRow);
  1122. $sHtml .= "</tr>\n";
  1123. }
  1124. $sHtml .= "</table>\n";
  1125. return $sHtml;
  1126. }
  1127. static function DisplaySetAsXML(WebPage $oPage, CMDBObjectSet $oSet, $aParams = array())
  1128. {
  1129. $bLocalize = true;
  1130. if (isset($aParams['localize_values']))
  1131. {
  1132. $bLocalize = (bool) $aParams['localize_values'];
  1133. }
  1134. $oAppContext = new ApplicationContext();
  1135. $aClasses = $oSet->GetFilter()->GetSelectedClasses();
  1136. $aAuthorizedClasses = array();
  1137. foreach($aClasses as $sAlias => $sClassName)
  1138. {
  1139. if (UserRights::IsActionAllowed($sClassName, UR_ACTION_READ, $oSet) && (UR_ALLOWED_YES || UR_ALLOWED_DEPENDS))
  1140. {
  1141. $aAuthorizedClasses[$sAlias] = $sClassName;
  1142. }
  1143. }
  1144. $aAttribs = array();
  1145. $aList = array();
  1146. $aList[$sAlias] = MetaModel::GetZListItems($sClassName, 'details');
  1147. $oPage->add("<Set>\n");
  1148. $oSet->Seek(0);
  1149. while ($aObjects = $oSet->FetchAssoc())
  1150. {
  1151. if (count($aAuthorizedClasses) > 1)
  1152. {
  1153. $oPage->add("<Row>\n");
  1154. }
  1155. foreach($aAuthorizedClasses as $sAlias => $sClassName)
  1156. {
  1157. $oObj = $aObjects[$sAlias];
  1158. if (is_null($oObj))
  1159. {
  1160. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"null\">\n");
  1161. }
  1162. else
  1163. {
  1164. $sClassName = get_class($oObj);
  1165. $oPage->add("<$sClassName alias=\"$sAlias\" id=\"".$oObj->GetKey()."\">\n");
  1166. }
  1167. foreach(MetaModel::ListAttributeDefs($sClassName) as $sAttCode=>$oAttDef)
  1168. {
  1169. if (is_null($oObj))
  1170. {
  1171. $oPage->add("<$sAttCode>null</$sAttCode>\n");
  1172. }
  1173. else
  1174. {
  1175. if ($oAttDef->IsWritable())
  1176. {
  1177. if (!$oAttDef->IsLinkSet())
  1178. {
  1179. $sValue = $oObj->GetAsXML($sAttCode, $bLocalize);
  1180. $oPage->add("<$sAttCode>$sValue</$sAttCode>\n");
  1181. }
  1182. }
  1183. }
  1184. }
  1185. $oPage->add("</$sClassName>\n");
  1186. }
  1187. if (count($aAuthorizedClasses) > 1)
  1188. {
  1189. $oPage->add("</Row>\n");
  1190. }
  1191. }
  1192. $oPage->add("</Set>\n");
  1193. }
  1194. public static function DisplaySearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1195. {
  1196. $oPage->add(self::GetSearchForm($oPage, $oSet, $aExtraParams));
  1197. }
  1198. public static function GetSearchForm(WebPage $oPage, CMDBObjectSet $oSet, $aExtraParams = array())
  1199. {
  1200. static $iSearchFormId = 0;
  1201. $bMultiSelect = false;
  1202. $oAppContext = new ApplicationContext();
  1203. $sHtml = '';
  1204. $numCols=4;
  1205. $sClassName = $oSet->GetFilter()->GetClass();
  1206. // Romain: temporarily removed the tab "OQL query" because it was not finalized
  1207. // (especially when used to add a link)
  1208. /*
  1209. $sHtml .= "<div class=\"mini_tabs\" id=\"mini_tabs{$iSearchFormId}\"><ul>
  1210. <li><a href=\"#\" onClick=\"$('div.mini_tab{$iSearchFormId}').toggle();$('#mini_tabs{$iSearchFormId} ul li a').toggleClass('selected');\">".Dict::S('UI:OQLQueryTab')."</a></li>
  1211. <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>
  1212. </ul></div>\n";
  1213. */
  1214. // Simple search form
  1215. if (isset($aExtraParams['currentId']))
  1216. {
  1217. $sSearchFormId = $aExtraParams['currentId'];
  1218. }
  1219. else
  1220. {
  1221. $iSearchFormId = $oPage->GetUniqueId();
  1222. $sSearchFormId = 'SimpleSearchForm'.$iSearchFormId;
  1223. $sHtml .= "<div id=\"ds_$sSearchFormId\" class=\"mini_tab{$iSearchFormId}\">\n";
  1224. }
  1225. // Check if the current class has some sub-classes
  1226. if (isset($aExtraParams['baseClass']))
  1227. {
  1228. $sRootClass = $aExtraParams['baseClass'];
  1229. }
  1230. else
  1231. {
  1232. $sRootClass = $sClassName;
  1233. }
  1234. $aSubClasses = MetaModel::GetSubclasses($sRootClass);
  1235. if (count($aSubClasses) > 0)
  1236. {
  1237. $aOptions = array();
  1238. $aOptions[MetaModel::GetName($sRootClass)] = "<option value=\"$sRootClass\">".MetaModel::GetName($sRootClass)."</options>\n";
  1239. foreach($aSubClasses as $sSubclassName)
  1240. {
  1241. $aOptions[MetaModel::GetName($sSubclassName)] = "<option value=\"$sSubclassName\">".MetaModel::GetName($sSubclassName)."</options>\n";
  1242. }
  1243. $aOptions[MetaModel::GetName($sClassName)] = "<option selected value=\"$sClassName\">".MetaModel::GetName($sClassName)."</options>\n";
  1244. ksort($aOptions);
  1245. $sContext = $oAppContext->GetForLink();
  1246. $sClassesCombo = "<select name=\"class\" onChange=\"ReloadSearchForm('$sSearchFormId', this.value, '$sRootClass', '$sContext')\">\n".implode('', $aOptions)."</select>\n";
  1247. }
  1248. else
  1249. {
  1250. $sClassesCombo = MetaModel::GetName($sClassName);
  1251. }
  1252. $oUnlimitedFilter = new DBObjectSearch($sClassName);
  1253. $sAction = (isset($aExtraParams['action'])) ? $aExtraParams['action'] : utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1254. $sHtml .= "<form id=\"fs_{$sSearchFormId}\" action=\"{$sAction}\">\n"; // Don't use $_SERVER['SCRIPT_NAME'] since the form may be called asynchronously (from ajax.php)
  1255. $sHtml .= "<h2>".Dict::Format('UI:SearchFor_Class_Objects', $sClassesCombo)."</h2>\n";
  1256. $index = 0;
  1257. $sHtml .= "<p>\n";
  1258. $aFilterCriteria = $oSet->GetFilter()->GetCriteria();
  1259. $aMapCriteria = array();
  1260. foreach($aFilterCriteria as $aCriteria)
  1261. {
  1262. $aMapCriteria[$aCriteria['filtercode']][] = array('value' => $aCriteria['value'], 'opcode' => $aCriteria['opcode']);
  1263. }
  1264. $aList = MetaModel::GetZListItems($sClassName, 'standard_search');
  1265. $aConsts = $oSet->ListConstantFields(); // Some fields are constants based on the query/context
  1266. $sClassAlias = $oSet->GetFilter()->GetClassAlias();
  1267. foreach($aList as $sFilterCode)
  1268. {
  1269. //$oAppContext->Reset($sFilterCode); // Make sure the same parameter will not be passed twice
  1270. $sHtml .= '<span style="white-space: nowrap;padding:5px;display:inline-block;">';
  1271. $sFilterValue = isset($aConsts[$sClassAlias][$sFilterCode]) ? $aConsts[$sClassAlias][$sFilterCode] : '';
  1272. $sFilterValue = utils::ReadParam($sFilterCode, $sFilterValue, false, 'raw_data');
  1273. $sFilterOpCode = null; // Use the default 'loose' OpCode
  1274. if (empty($sFilterValue))
  1275. {
  1276. if (isset($aMapCriteria[$sFilterCode]))
  1277. {
  1278. if (count($aMapCriteria[$sFilterCode]) > 1)
  1279. {
  1280. $sFilterValue = Dict::S('UI:SearchValue:Mixed');
  1281. }
  1282. else
  1283. {
  1284. $sFilterValue = $aMapCriteria[$sFilterCode][0]['value'];
  1285. $sFilterOpCode = $aMapCriteria[$sFilterCode][0]['opcode'];
  1286. }
  1287. if ($sFilterCode != 'company')
  1288. {
  1289. $oUnlimitedFilter->AddCondition($sFilterCode, $sFilterValue, $sFilterOpCode);
  1290. }
  1291. }
  1292. }
  1293. $oAttDef = MetaModel::GetAttributeDef($sClassName, $sFilterCode);
  1294. if ($oAttDef->IsExternalKey())
  1295. {
  1296. $sTargetClass = $oAttDef->GetTargetClass();
  1297. $oSearch = new DBObjectSearch($sTargetClass);
  1298. $oSearch->SetModifierProperty('UserRightsGetSelectFilter', 'bSearchMode', true);
  1299. $oAllowedValues = new DBObjectSet($oSearch);
  1300. $iFieldSize = $oAttDef->GetMaxSize();
  1301. $iMaxComboLength = $oAttDef->GetMaximumComboLength();
  1302. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;";
  1303. $aExtKeyParams = $aExtraParams;
  1304. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1305. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1306. $sHtml .= UIExtKeyWidget::DisplayFromAttCode($oPage, $sFilterCode, $sClassName, $oAttDef->GetLabel(), $oAllowedValues, $sFilterValue, $sSearchFormId.'search_'.$sFilterCode, false, $sFilterCode, '', $aExtKeyParams, true);
  1307. }
  1308. else
  1309. {
  1310. $aAllowedValues = MetaModel::GetAllowedValues_flt($sClassName, $sFilterCode, $aExtraParams);
  1311. if (is_null($aAllowedValues))
  1312. {
  1313. // Any value is possible, display an input box
  1314. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;<input class=\"textSearch\" name=\"$sFilterCode\" value=\"".htmlentities($sFilterValue, ENT_QUOTES, 'utf-8')."\"/>\n";
  1315. }
  1316. else
  1317. {
  1318. //Enum field, display a multi-select combo
  1319. $sValue = "<select class=\"multiselect\" size=\"1\" name=\"{$sFilterCode}[]\" multiple>\n";
  1320. $bMultiSelect = true;
  1321. //$sValue .= "<option value=\"\">".Dict::S('UI:SearchValue:Any')."</option>\n";
  1322. foreach($aAllowedValues as $key => $value)
  1323. {
  1324. if (is_array($sFilterValue) && in_array($key, $sFilterValue))
  1325. {
  1326. $sSelected = ' selected';
  1327. }
  1328. else if ($sFilterValue == $key)
  1329. {
  1330. $sSelected = ' selected';
  1331. }
  1332. else
  1333. {
  1334. $sSelected = '';
  1335. }
  1336. $sValue .= "<option value=\"$key\"$sSelected>$value</option>\n";
  1337. }
  1338. $sValue .= "</select>\n";
  1339. $sHtml .= "<label>".MetaModel::GetFilterLabel($sClassName, $sFilterCode).":</label>&nbsp;$sValue\n";
  1340. }
  1341. }
  1342. unset($aExtraParams[$sFilterCode]);
  1343. // Finally, add a tooltip if one is defined for this attribute definition
  1344. $sTip = $oAttDef->GetHelpOnSmartSearch();
  1345. if (strlen($sTip) > 0)
  1346. {
  1347. $sTip = addslashes($sTip);
  1348. $sTip = str_replace(array("\n", "\r"), " ", $sTip);
  1349. // :input does represent in form visible input (INPUT, SELECT, TEXTAREA)
  1350. $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' }} } );");
  1351. }
  1352. $index++;
  1353. $sHtml .= '</span> ';
  1354. }
  1355. $sHtml .= "</p>\n";
  1356. $sHtml .= "<p align=\"right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Search')."\"></p>\n";
  1357. if (isset($aExtraParams['table_id']))
  1358. {
  1359. // Rename to avoid collisions...
  1360. $aExtraParams['_table_id_'] = $aExtraParams['table_id'];
  1361. unset($aExtraParams['table_id']);
  1362. }
  1363. foreach($aExtraParams as $sName => $sValue)
  1364. {
  1365. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1366. }
  1367. $sHtml .= "<input type=\"hidden\" name=\"class\" value=\"$sClassName\" />\n";
  1368. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1369. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_form\" />\n";
  1370. $sHtml .= $oAppContext->GetForForm();
  1371. $sHtml .= "</form>\n";
  1372. if (!isset($aExtraParams['currentId']))
  1373. {
  1374. $sHtml .= "</div><!-- Simple search form -->\n";
  1375. }
  1376. if ($bMultiSelect)
  1377. {
  1378. $oPage->add_ready_script("$('.multiselect').multiselect({header: false, noneSelectedText: '".addslashes(Dict::S('UI:SearchValue:Any'))."', selectedList: 1, selectedText:'".addslashes(Dict::S('UI:SearchValue:NbSelected'))."'});");
  1379. }
  1380. /*
  1381. // OQL query builder
  1382. $sHtml .= "<div id=\"OQLQuery{$iSearchFormId}\" style=\"display:none\" class=\"mini_tab{$iSearchFormId}\">\n";
  1383. $sHtml .= "<h1>".Dict::S('UI:OQLQueryBuilderTitle')."</h1>\n";
  1384. $sHtml .= "<form id=\"formOQL{$iSearchFormId}\"><table style=\"width:80%;\"><tr style=\"vertical-align:top\">\n";
  1385. $sHtml .= "<td style=\"text-align:right\"><label>SELECT&nbsp;</label><select name=\"oql_class\">";
  1386. $aClasses = MetaModel::EnumChildClasses($sClassName, ENUM_CHILD_CLASSES_ALL);
  1387. $sSelectedClass = utils::ReadParam('oql_class', $sClassName, false, 'class');
  1388. $sOQLClause = utils::ReadParam('oql_clause', '', false, 'raw_data');
  1389. asort($aClasses);
  1390. foreach($aClasses as $sChildClass)
  1391. {
  1392. $sSelected = ($sChildClass == $sSelectedClass) ? 'selected' : '';
  1393. $sHtml.= "<option value=\"$sChildClass\" $sSelected>".MetaModel::GetName($sChildClass)."</option>\n";
  1394. }
  1395. $sHtml .= "</select>&nbsp;</td><td>\n";
  1396. $sHtml .= "<textarea name=\"oql_clause\" style=\"width:100%\">$sOQLClause</textarea></td></tr>\n";
  1397. $sHtml .= "<tr><td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"".Dict::S('UI:Button:Query')."\"></td></tr>\n";
  1398. $sHtml .= "<input type=\"hidden\" name=\"dosearch\" value=\"1\" />\n";
  1399. foreach($aExtraParams as $sName => $sValue)
  1400. {
  1401. $sHtml .= "<input type=\"hidden\" name=\"$sName\" value=\"$sValue\" />\n";
  1402. }
  1403. $sHtml .= "<input type=\"hidden\" name=\"operation\" value=\"search_oql\" />\n";
  1404. $sHtml .= $oAppContext->GetForForm();
  1405. $sHtml .= "</table></form>\n";
  1406. $sHtml .= "</div><!-- OQL query form -->\n";
  1407. */
  1408. return $sHtml;
  1409. }
  1410. public static function GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $value = '', $sDisplayValue = '', $iId = '', $sNameSuffix = '', $iFlags = 0, $aArgs = array())
  1411. {
  1412. static $iInputId = 0;
  1413. $sFieldPrefix = '';
  1414. $sFormPrefix = isset($aArgs['formPrefix']) ? $aArgs['formPrefix'] : '';
  1415. $sFieldPrefix = isset($aArgs['prefix']) ? $sFormPrefix.$aArgs['prefix'] : $sFormPrefix;
  1416. if ($sDisplayValue == '')
  1417. {
  1418. $sDisplayValue = $value;
  1419. }
  1420. if (isset($aArgs[$sAttCode]) && empty($value))
  1421. {
  1422. // default value passed by the context (either the app context of the operation)
  1423. $value = $aArgs[$sAttCode];
  1424. }
  1425. if (!empty($iId))
  1426. {
  1427. $iInputId = $iId;
  1428. }
  1429. else
  1430. {
  1431. $iInputId = $oPage->GetUniqueId();
  1432. }
  1433. if (!$oAttDef->IsExternalField())
  1434. {
  1435. $bMandatory = 'false';
  1436. if ( (!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1437. {
  1438. $bMandatory = 'true';
  1439. }
  1440. $sValidationField = "<span class=\"form_validation\" id=\"v_{$iId}\"></span>";
  1441. $sHelpText = $oAttDef->GetHelpOnEdition();
  1442. $aEventsList = array();
  1443. switch($oAttDef->GetEditClass())
  1444. {
  1445. case 'Date':
  1446. $aEventsList[] ='validate';
  1447. $aEventsList[] ='keyup';
  1448. $aEventsList[] ='change';
  1449. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1450. {
  1451. $sDisplayValue = date($oAttDef->GetDateFormat());
  1452. }
  1453. $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}";
  1454. break;
  1455. case 'DateTime':
  1456. $aEventsList[] ='validate';
  1457. $aEventsList[] ='keyup';
  1458. $aEventsList[] ='change';
  1459. if (($iFlags & OPT_ATT_MANDATORY) && (empty($sDisplayValue)))
  1460. {
  1461. $sDisplayValue = date($oAttDef->GetDateFormat());
  1462. }
  1463. $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}";
  1464. break;
  1465. case 'Duration':
  1466. $aEventsList[] ='validate';
  1467. $aEventsList[] ='change';
  1468. $oPage->add_ready_script("$('#{$iId}_d').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1469. $oPage->add_ready_script("$('#{$iId}_h').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1470. $oPage->add_ready_script("$('#{$iId}_m').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1471. $oPage->add_ready_script("$('#{$iId}_s').bind('keyup change', function(evt, sFormId) { return UpdateDuration('$iId'); });");
  1472. $aVal = AttributeDuration::SplitDuration($value);
  1473. $sDays = "<input title=\"$sHelpText\" type=\"text\" size=\"3\" name=\"attr_{$sFieldPrefix}{$sAttCode}[d]{$sNameSuffix}\" value=\"{$aVal['days']}\" id=\"{$iId}_d\"/>";
  1474. $sHours = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[h]{$sNameSuffix}\" value=\"{$aVal['hours']}\" id=\"{$iId}_h\"/>";
  1475. $sMinutes = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[m]{$sNameSuffix}\" value=\"{$aVal['minutes']}\" id=\"{$iId}_m\"/>";
  1476. $sSeconds = "<input title=\"$sHelpText\" type=\"text\" size=\"2\" name=\"attr_{$sFieldPrefix}{$sAttCode}[s]{$sNameSuffix}\" value=\"{$aVal['seconds']}\" id=\"{$iId}_s\"/>";
  1477. $sHidden = "<input type=\"hidden\" id=\"{$iId}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\"/>";
  1478. $sHTMLValue = Dict::Format('UI:DurationForm_Days_Hours_Minutes_Seconds', $sDays, $sHours, $sMinutes, $sSeconds).$sHidden."&nbsp;".$sValidationField;
  1479. $oPage->add_ready_script("$('#{$iId}').bind('update', function(evt, sFormId) { return ToggleDurationField('$iId'); });");
  1480. break;
  1481. case 'Password':
  1482. $aEventsList[] ='validate';
  1483. $aEventsList[] ='keyup';
  1484. $aEventsList[] ='change';
  1485. $sHTMLValue = "<input title=\"$sHelpText\" type=\"password\" size=\"30\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" value=\"".htmlentities($value, ENT_QUOTES, 'UTF-8')."\" id=\"$iId\"/>&nbsp;{$sValidationField}";
  1486. break;
  1487. case 'OQLExpression':
  1488. case 'Text':
  1489. $aEventsList[] ='validate';
  1490. $aEventsList[] ='keyup';
  1491. $aEventsList[] ='change';
  1492. $sEditValue = $oAttDef->GetEditValue($value);
  1493. $aStyles = array();
  1494. $sStyle = '';
  1495. $sWidth = $oAttDef->GetWidth('width', '');
  1496. if (!empty($sWidth))
  1497. {
  1498. $aStyles[] = 'width:'.$sWidth;
  1499. }
  1500. $sHeight = $oAttDef->GetHeight('height', '');
  1501. if (!empty($sHeight))
  1502. {
  1503. $aStyles[] = 'height:'.$sHeight;
  1504. }
  1505. if (count($aStyles) > 0)
  1506. {
  1507. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1508. }
  1509. if ($oAttDef->GetEditClass() == 'OQLExpression')
  1510. {
  1511. $sTestResId = 'query_res_'.$sFieldPrefix.$sAttCode.$sNameSuffix; //$oPage->GetUniqueId();
  1512. $sBaseUrl = utils::GetAbsoluteUrlAppRoot().'pages/run_query.php?expression=';
  1513. $sInitialUrl = $sBaseUrl.urlencode($sEditValue);
  1514. $sAdditionalStuff = "<a id=\"$sTestResId\" target=\"_blank\" href=\"$sInitialUrl\">".Dict::S('UI:Edit:TestQuery')."</a>";
  1515. $oPage->add_ready_script("$('#$iId').bind('change keyup', function(evt, sFormId) { $('#$sTestResId').attr('href', '$sBaseUrl'+encodeURIComponent($(this).val())); } );");
  1516. }
  1517. else
  1518. {
  1519. $sAdditionalStuff = "";
  1520. }
  1521. // Ok, the text area is drawn here
  1522. $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>";
  1523. break;
  1524. case 'CaseLog':
  1525. $aStyles = array();
  1526. $sStyle = '';
  1527. $sWidth = $oAttDef->GetWidth('width', '');
  1528. if (!empty($sWidth))
  1529. {
  1530. $aStyles[] = 'width:'.$sWidth;
  1531. }
  1532. $sHeight = $oAttDef->GetHeight('height', '');
  1533. if (!empty($sHeight))
  1534. {
  1535. $aStyles[] = 'height:'.$sHeight;
  1536. }
  1537. if (count($aStyles) > 0)
  1538. {
  1539. $sStyle = 'style="'.implode('; ', $aStyles).'"';
  1540. }
  1541. $sHeader = '<div class="caselog_input_header">&nbsp;'.Dict::S('UI:CaseLogTypeYourTextHere').'</div>';
  1542. $sEditValue = $oAttDef->GetEditValue($value);
  1543. $sPreviousLog = is_object($value) ? $value->GetAsHTML($oPage, true /* bEditMode */, array('AttributeText', 'RenderWikiHtml')) : '';
  1544. $iEntriesCount = is_object($value) ? count($value->GetIndex()) : 0;
  1545. $sHidden = "<input type=\"hidden\" id=\"{$iId}_count\" value=\"$iEntriesCount\"/>"; // To know how many entries the case log already contains
  1546. $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>";
  1547. $oPage->add_ready_script("$('#$iId').bind('keyup change validate', function(evt, sFormId) { return ValidateCaseLogField('$iId', $bMandatory, sFormId) } );"); // Custom validation function
  1548. break;
  1549. case 'HTML':
  1550. $oWidget = new UIHTMLEditorWidget($iId, $sAttCode, $sNameSuffix, $sFieldPrefix, $sHelpText, $sValidationField, $value, $bMandatory);
  1551. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1552. break;
  1553. case 'LinkedSet':
  1554. if ($oAttDef->IsIndirect())
  1555. {
  1556. $oWidget = new UILinksWidget($sClass, $sAttCode, $iId, $sNameSuffix, $oAttDef->DuplicatesAllowed(), $aArgs);
  1557. }
  1558. else
  1559. {
  1560. $oWidget = new UILinksWidgetDirect($sClass, $sAttCode, $iId, $sNameSuffix, $aArgs);
  1561. }
  1562. $aEventsList[] ='validate';
  1563. $aEventsList[] ='change';
  1564. $oObj = isset($aArgs['this']) ? $aArgs['this'] : null;
  1565. $sHTMLValue = $oWidget->Display($oPage, $value, array(), $sFormPrefix, $oObj);
  1566. break;
  1567. case 'Document':
  1568. $aEventsList[] ='validate';
  1569. $aEventsList[] ='change';
  1570. $oDocument = $value; // Value is an ormDocument object
  1571. $sFileName = '';
  1572. if (is_object($oDocument))
  1573. {
  1574. $sFileName = $oDocument->GetFileName();
  1575. }
  1576. $iMaxFileSize = utils::ConvertToBytes(ini_get('upload_max_filesize'));
  1577. $sHTMLValue = "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"$iMaxFileSize\" />\n";
  1578. $sHTMLValue .= "<input name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[filename]\" type=\"hidden\" id=\"$iId\" \" value=\"".htmlentities($sFileName, ENT_QUOTES, 'UTF-8')."\"/>\n";
  1579. $sHTMLValue .= "<span id=\"name_$iInputId\">$sFileName</span><br/>\n";
  1580. $sHTMLValue .= "<input title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}[fcontents]\" type=\"file\" id=\"file_$iId\" onChange=\"UpdateFileName('$iId', this.value)\"/>&nbsp;{$sValidationField}\n";
  1581. break;
  1582. case 'StopWatch':
  1583. $sHTMLValue = "The edition of a stopwatch is not allowed!!!";
  1584. break;
  1585. case 'List':
  1586. // Not editable for now...
  1587. $sHTMLValue = '';
  1588. break;
  1589. case 'One Way Password':
  1590. $aEventsList[] ='validate';
  1591. $oWidget = new UIPasswordWidget($sAttCode, $iId, $sNameSuffix);
  1592. $sHTMLValue = $oWidget->Display($oPage, $aArgs);
  1593. // Event list & validation is handled directly by the widget
  1594. break;
  1595. case 'ExtKey':
  1596. $aEventsList[] ='validate';
  1597. $aEventsList[] ='change';
  1598. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1599. $sFieldName = $sFieldPrefix.$sAttCode.$sNameSuffix;
  1600. $aExtKeyParams = $aArgs;
  1601. $aExtKeyParams['iFieldSize'] = $oAttDef->GetMaxSize();
  1602. $aExtKeyParams['iMinChars'] = $oAttDef->GetMinAutoCompleteChars();
  1603. $sHTMLValue = UIExtKeyWidget::DisplayFromAttCode($oPage, $sAttCode, $sClass, $oAttDef->GetLabel(), $oAllowedValues, $value, $iId, $bMandatory, $sFieldName, $sFormPrefix, $aExtKeyParams);
  1604. $sHTMLValue .= "<!-- iFlags: $iFlags bMandatory: $bMandatory -->\n";
  1605. break;
  1606. case 'String':
  1607. default:
  1608. $aEventsList[] ='validate';
  1609. // #@# todo - add context information (depending on dimensions)
  1610. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1611. $iFieldSize = $oAttDef->GetMaxSize();
  1612. if ($aAllowedValues !== null)
  1613. {
  1614. // Discrete list of values, use a SELECT or RADIO buttons depending on the config
  1615. $sDisplayStyle = $oAttDef->GetDisplayStyle();
  1616. switch($sDisplayStyle)
  1617. {
  1618. case 'radio':
  1619. case 'radio_horizontal':
  1620. case 'radio_vertical':
  1621. $sHTMLValue = '';
  1622. $bVertical = ($sDisplayStyle != 'radio_horizontal');
  1623. $sHTMLValue = $oPage->GetRadioButtons($aAllowedValues, $value, $iId, "attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}", $bMandatory, $bVertical, $sValidationField);
  1624. $aEventsList[] ='change';
  1625. break;
  1626. case 'select':
  1627. default:
  1628. $sHTMLValue = "<select title=\"$sHelpText\" name=\"attr_{$sFieldPrefix}{$sAttCode}{$sNameSuffix}\" id=\"$iId\">\n";
  1629. $sHTMLValue .= "<option value=\"\">".Dict::S('UI:SelectOne')."</option>\n";
  1630. foreach($aAllowedValues as $key => $display_value)
  1631. {
  1632. if ((count($aAllowedValues) == 1) && ($bMandatory == 'true') )
  1633. {
  1634. // When there is only once choice, select it by default
  1635. $sSelected = ' selected';
  1636. }
  1637. else
  1638. {
  1639. $sSelected = ($value == $key) ? ' selected' : '';
  1640. }
  1641. $sHTMLValue .= "<option value=\"$key\"$sSelected>$display_value</option>\n";
  1642. }
  1643. $sHTMLValue .= "</select>&nbsp;{$sValidationField}\n";
  1644. $aEventsList[] ='change';
  1645. }
  1646. }
  1647. else
  1648. {
  1649. $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}";
  1650. $aEventsList[] ='keyup';
  1651. $aEventsList[] ='change';
  1652. }
  1653. break;
  1654. }
  1655. $sPattern = addslashes($oAttDef->GetValidationPattern()); //'^([0-9]+)$';
  1656. if (!empty($aEventsList))
  1657. {
  1658. $sNullValue = $oAttDef->GetNullValue();
  1659. if (!is_numeric($sNullValue))
  1660. {
  1661. $sNullValue = "'$sNullValue'"; // Add quotes to turn this into a JS string if it's not a number
  1662. }
  1663. $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
  1664. }
  1665. $aDependencies = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that depend on the current one
  1666. if (count($aDependencies) > 0)
  1667. {
  1668. $oPage->add_ready_script("$('#$iId').bind('change', function(evt, sFormId) { return oWizardHelper{$sFormPrefix}.UpdateDependentFields(['".implode("','", $aDependencies)."']) } );\n"); // Bind to a custom event: validate
  1669. }
  1670. }
  1671. return "<div>{$sHTMLValue}</div>";
  1672. }
  1673. public function DisplayModifyForm(WebPage $oPage, $aExtraParams = array())
  1674. {
  1675. self::$iGlobalFormId++;
  1676. $sPrefix = '';
  1677. if (isset($aExtraParams['formPrefix']))
  1678. {
  1679. $sPrefix = $aExtraParams['formPrefix'];
  1680. }
  1681. $aFieldsComments = (isset($aExtraParams['fieldsComments'])) ? $aExtraParams['fieldsComments'] : array();
  1682. $this->m_iFormId = $sPrefix.self::$iGlobalFormId;
  1683. $sClass = get_class($this);
  1684. $oAppContext = new ApplicationContext();
  1685. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1686. $iKey = $this->GetKey();
  1687. $aDetails = array();
  1688. $aFieldsMap = array();
  1689. if (!isset($aExtraParams['action']))
  1690. {
  1691. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  1692. }
  1693. else
  1694. {
  1695. $sFormAction = $aExtraParams['action'];
  1696. }
  1697. // Custom label for the apply button ?
  1698. if (isset($aExtraParams['custom_button']))
  1699. {
  1700. $sApplyButton = $aExtraParams['custom_button'];
  1701. }
  1702. else if ($iKey > 0)
  1703. {
  1704. $sApplyButton = Dict::S('UI:Button:Apply');
  1705. }
  1706. else
  1707. {
  1708. $sApplyButton = Dict::S('UI:Button:Create');
  1709. }
  1710. // Custom operation for the form ?
  1711. if (isset($aExtraParams['custom_operation']))
  1712. {
  1713. $sOperation = $aExtraParams['custom_operation'];
  1714. }
  1715. else if ($iKey > 0)
  1716. {
  1717. $sOperation = 'apply_modify';
  1718. }
  1719. else
  1720. {
  1721. $sOperation = 'apply_new';
  1722. }
  1723. if ($iKey > 0)
  1724. {
  1725. // The object already exists in the database, it's a modification
  1726. $sButtons = "<input id=\"{$sPrefix}_id\" type=\"hidden\" name=\"id\" value=\"$iKey\">\n";
  1727. $sButtons .= "<input type=\"hidden\" name=\"operation\" value=\"{$sOperation}\">\n";
  1728. $sButtons .= "<button type=\"button\" class=\"action cancel\"><span>".Dict::S('UI:Button:Cancel')."</span></button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1729. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1730. }
  1731. else
  1732. {
  1733. // The object does not exist in the database it's a creation
  1734. $sButtons = "<input type=\"hidden\" name=\"operation\" value=\"$sOperation\">\n";
  1735. $sButtons .= "<button type=\"button\" class=\"action cancel\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n";
  1736. $sButtons .= "<button type=\"submit\" class=\"action\"><span>{$sApplyButton}</span></button>\n";
  1737. }
  1738. $aTransitions = $this->EnumTransitions();
  1739. if (!isset($aExtraParams['custom_operation']) && count($aTransitions))
  1740. {
  1741. // transitions are displayed only for the standard new/modify actions, not for modify_all or any other case...
  1742. $oSetToCheckRights = DBObjectSet::FromObject($this);
  1743. $aStimuli = Metamodel::EnumStimuli($sClass);
  1744. foreach($aTransitions as $sStimulusCode => $aTransitionDef)
  1745. {
  1746. $iActionAllowed = (get_class($aStimuli[$sStimulusCode]) == 'StimulusUserAction') ? UserRights::IsStimulusAllowed($sClass, $sStimulusCode, $oSetToCheckRights) : UR_ALLOWED_NO;
  1747. switch($iActionAllowed)
  1748. {
  1749. case UR_ALLOWED_YES:
  1750. $sButtons .= "<button type=\"submit\" name=\"next_action\" value=\"{$sStimulusCode}\" class=\"action\"><span>".$aStimuli[$sStimulusCode]->GetLabel()."</span></button>\n";
  1751. break;
  1752. default:
  1753. // Do nothing
  1754. }
  1755. }
  1756. }
  1757. $sButtonsPosition = MetaModel::GetConfig()->Get('buttons_position');
  1758. $iTransactionId = isset($aExtraParams['transaction_id']) ? $aExtraParams['transaction_id'] : utils::GetNewTransactionId();
  1759. $oPage->SetTransactionId($iTransactionId);
  1760. $oPage->add("<form action=\"$sFormAction\" id=\"form_{$this->m_iFormId}\" enctype=\"multipart/form-data\" method=\"post\" onSubmit=\"return OnSubmit('form_{$this->m_iFormId}');\">\n");
  1761. $sStatesSelection = '';
  1762. if (!isset($aExtraParams['custom_operation']) && $this->IsNew())
  1763. {
  1764. $aInitialStates = MetaModel::EnumInitialStates($sClass);
  1765. //$aInitialStates = array('new' => 'foo', 'closed' => 'bar');
  1766. if (count($aInitialStates) > 1)
  1767. {
  1768. $sStatesSelection = Dict::Format('UI:Create_Class_InState', MetaModel::GetName($sClass)).'<select name="obj_state" class="state_select_'.$this->m_iFormId.'">';
  1769. foreach($aInitialStates as $sStateCode => $sStateData)
  1770. {
  1771. $sSelected = '';
  1772. if ($sStateCode == $this->GetState())
  1773. {
  1774. $sSelected = ' selected';
  1775. }
  1776. $sStatesSelection .= '<option value="'.$sStateCode.'"'.$sSelected.'>'.MetaModel::GetStateLabel($sClass, $sStateCode).'</option>';
  1777. }
  1778. $sStatesSelection .= '</select>';
  1779. $oPage->add_ready_script("$('.state_select_{$this->m_iFormId}').change( function() { oWizardHelper$sPrefix.ReloadObjectCreationForm('form_{$this->m_iFormId}', $(this).val()); } );");
  1780. }
  1781. }
  1782. $sConfirmationMessage = addslashes(Dict::S('UI:NavigateAwayConfirmationMessage'));
  1783. $oPage->add_ready_script(
  1784. <<<EOF
  1785. $(window).unload(function() { return OnUnload('$iTransactionId') } );
  1786. window.onbeforeunload = function() {
  1787. if (!window.bInSubmit && !window.bInCancel)
  1788. {
  1789. return '$sConfirmationMessage';
  1790. }
  1791. // return nothing ! safer for IE
  1792. };
  1793. EOF
  1794. );
  1795. if ($sButtonsPosition != 'bottom')
  1796. {
  1797. // top or both, display the buttons here
  1798. $oPage->p($sStatesSelection);
  1799. $oPage->add($sButtons);
  1800. }
  1801. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB, $sPrefix);
  1802. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1803. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1804. $aFieldsMap = $this->DisplayBareProperties($oPage, true, $sPrefix, $aExtraParams);
  1805. if ($iKey > 0)
  1806. {
  1807. $aFieldsMap['id'] = $sPrefix.'_id';
  1808. }
  1809. // Now display the relations, one tab per relation
  1810. if (!isset($aExtraParams['noRelations']))
  1811. {
  1812. $this->DisplayBareRelations($oPage, true); // Edit mode
  1813. }
  1814. $oPage->SetCurrentTab('');
  1815. $oPage->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  1816. $oPage->add("<input type=\"hidden\" name=\"transaction_id\" value=\"$iTransactionId\">\n");
  1817. foreach($aExtraParams as $sName => $value)
  1818. {
  1819. $oPage->add("<input type=\"hidden\" name=\"$sName\" value=\"$value\">\n");
  1820. }
  1821. $oPage->add($oAppContext->GetForForm());
  1822. if ($sButtonsPosition != 'top')
  1823. {
  1824. // bottom or both: display the buttons here
  1825. $oPage->p($sStatesSelection);
  1826. $oPage->add($sButtons);
  1827. }
  1828. // Hook the cancel button via jQuery so that it can be unhooked easily as well if needed
  1829. $sDefaultUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=cancel&'.$oAppContext->GetForLink();
  1830. $oPage->add_ready_script("$('#form_{$this->m_iFormId} button.cancel').click( function() { BackToDetails('$sClass', $iKey, '$sDefaultUrl')} );");
  1831. $oPage->add("</form>\n");
  1832. $iFieldsCount = count($aFieldsMap);
  1833. $sJsonFieldsMap = json_encode($aFieldsMap);
  1834. $sState = $this->GetState();
  1835. $oPage->add_script(
  1836. <<<EOF
  1837. // Create the object once at the beginning of the page...
  1838. var oWizardHelper$sPrefix = new WizardHelper('$sClass', '$sPrefix', '$sState');
  1839. oWizardHelper$sPrefix.SetFieldsMap($sJsonFieldsMap);
  1840. oWizardHelper$sPrefix.SetFieldsCount($iFieldsCount);
  1841. EOF
  1842. );
  1843. $oPage->add_ready_script(
  1844. <<<EOF
  1845. oWizardHelper$sPrefix.UpdateWizard();
  1846. // Starts the validation when the page is ready
  1847. CheckFields('form_{$this->m_iFormId}', false);
  1848. EOF
  1849. );
  1850. }
  1851. public static function DisplayCreationForm(WebPage $oPage, $sClass, $oObjectToClone = null, $aArgs = array(), $aExtraParams = array())
  1852. {
  1853. $oAppContext = new ApplicationContext();
  1854. $sClass = ($oObjectToClone == null) ? $sClass : get_class($oObjectToClone);
  1855. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  1856. $aStates = MetaModel::EnumStates($sClass);
  1857. $sStatesSelection = '';
  1858. if ($oObjectToClone == null)
  1859. {
  1860. $oObj = MetaModel::NewObject($sClass);
  1861. if (!empty($sStateAttCode))
  1862. {
  1863. $sTargetState = MetaModel::GetDefaultState($sClass);
  1864. $oObj->Set($sStateAttCode, $sTargetState);
  1865. }
  1866. }
  1867. else
  1868. {
  1869. $oObj = clone $oObjectToClone;
  1870. }
  1871. // Pre-fill the object with default values, when there is only on possible choice
  1872. // AND the field is mandatory (otherwise there is always the possiblity to let it empty)
  1873. $aArgs['this'] = $oObj;
  1874. $aDetailsList = self::FLattenZList(MetaModel::GetZListItems($sClass, 'details'));
  1875. // Order the fields based on their dependencies
  1876. $aDeps = array();
  1877. foreach($aDetailsList as $sAttCode)
  1878. {
  1879. $aDeps[$sAttCode] = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode);
  1880. }
  1881. $aList = self::OrderDependentFields($aDeps);
  1882. // Now fill-in the fields with default/supplied values
  1883. foreach($aList as $sAttCode)
  1884. {
  1885. if (isset($aArgs['default'][$sAttCode]))
  1886. {
  1887. $oObj->Set($sAttCode, $aArgs['default'][$sAttCode]);
  1888. }
  1889. else
  1890. {
  1891. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1892. // If the field is mandatory, set it to the only possible value
  1893. $iFlags = $oObj->GetInitialStateAttributeFlags($sAttCode);
  1894. if ((!$oAttDef->IsNullAllowed()) || ($iFlags & OPT_ATT_MANDATORY))
  1895. {
  1896. if ($oAttDef->IsExternalKey())
  1897. {
  1898. $oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs);
  1899. if ($oAllowedValues->Count() == 1)
  1900. {
  1901. $oRemoteObj = $oAllowedValues->Fetch();
  1902. $oObj->Set($sAttCode, $oRemoteObj->GetKey());
  1903. }
  1904. }
  1905. else
  1906. {
  1907. $aAllowedValues = MetaModel::GetAllowedValues_att($sClass, $sAttCode, $aArgs);
  1908. if (count($aAllowedValues) == 1)
  1909. {
  1910. $aValues = array_keys($aAllowedValues);
  1911. $oObj->Set($sAttCode, $aValues[0]);
  1912. }
  1913. }
  1914. }
  1915. }
  1916. }
  1917. return $oObj->DisplayModifyForm( $oPage, $aExtraParams);
  1918. }
  1919. public static function ProcessZlist($aList, $aDetails, $sCurrentTab, $sCurrentCol, $sCurrentSet)
  1920. {
  1921. //echo "<pre>ZList: ";
  1922. //print_r($aList);
  1923. //echo "</pre>\n";
  1924. $index = 0;
  1925. foreach($aList as $sKey => $value)
  1926. {
  1927. if (is_array($value))
  1928. {
  1929. if (preg_match('/^(.*):(.*)$/U', $sKey, $aMatches))
  1930. {
  1931. $sCode = $aMatches[1];
  1932. $sName = $aMatches[2];
  1933. switch($sCode)
  1934. {
  1935. case 'tab':
  1936. //echo "<p>Found a tab: $sName ($sKey)</p>\n";
  1937. if(!isset($aDetails[$sName]))
  1938. {
  1939. $aDetails[$sName] = array('col1' => array());
  1940. }
  1941. $aDetails = self::ProcessZlist($value, $aDetails, $sName, 'col1', '');
  1942. break;
  1943. case 'fieldset':
  1944. //echo "<p>Found a fieldset: $sName ($sKey)</p>\n";
  1945. if(!isset($aDetailsStruct[$sCurrentTab][$sCurrentCol][$sName]))
  1946. {
  1947. $aDetails[$sCurrentTab][$sCurrentCol][$sName] = array();
  1948. }
  1949. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sCurrentCol, $sName);
  1950. break;
  1951. default:
  1952. case 'col':
  1953. //echo "<p>Found a column: $sName ($sKey)</p>\n";
  1954. if(!isset($aDetails[$sCurrentTab][$sName]))
  1955. {
  1956. $aDetails[$sCurrentTab][$sName] = array();
  1957. }
  1958. $aDetails = self::ProcessZlist($value, $aDetails, $sCurrentTab, $sName, '');
  1959. break;
  1960. }
  1961. }
  1962. }
  1963. else
  1964. {
  1965. //echo "<p>Scalar value: $value, in [$sCurrentTab][$sCurrentCol][$sCurrentSet][]</p>\n";
  1966. if (empty($sCurrentSet))
  1967. {
  1968. $aDetails[$sCurrentTab][$sCurrentCol]['_'.$index][] = $value;
  1969. }
  1970. else
  1971. {
  1972. $aDetails[$sCurrentTab][$sCurrentCol][$sCurrentSet][] = $value;
  1973. }
  1974. }
  1975. $index++;
  1976. }
  1977. return $aDetails;
  1978. }
  1979. static function FlattenZList($aList)
  1980. {
  1981. $aResult = array();
  1982. foreach($aList as $value)
  1983. {
  1984. if (!is_array($value))
  1985. {
  1986. $aResult[] = $value;
  1987. }
  1988. else
  1989. {
  1990. $aResult = array_merge($aResult,self::FlattenZList($value));
  1991. }
  1992. }
  1993. return $aResult;
  1994. }
  1995. protected function GetFieldAsHtml($sClass, $sAttCode, $sStateAttCode)
  1996. {
  1997. $retVal = null;
  1998. if ($this->IsNew())
  1999. {
  2000. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2001. }
  2002. else
  2003. {
  2004. $iFlags = $this->GetAttributeFlags($sAttCode);
  2005. }
  2006. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  2007. if ( (!$oAttDef->IsLinkSet()) && (($iFlags & OPT_ATT_HIDDEN) == 0) )
  2008. {
  2009. // The field is visible in the current state of the object
  2010. if ($sStateAttCode == $sAttCode)
  2011. {
  2012. // Special display for the 'state' attribute itself
  2013. $sDisplayValue = $this->GetStateLabel();
  2014. }
  2015. else if ($oAttDef->GetEditClass() == 'Document')
  2016. {
  2017. $oDocument = $this->Get($sAttCode);
  2018. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2019. $sDisplayValue .= "<br/>".Dict::Format('UI:OpenDocumentInNewWindow_', $oDocument->GetDisplayLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2020. $sDisplayValue .= "<br/>".Dict::Format('UI:DownloadDocument_', $oDocument->GetDownloadLink(get_class($this), $this->GetKey(), $sAttCode)).", \n";
  2021. }
  2022. else
  2023. {
  2024. $sDisplayValue = $this->GetAsHTML($sAttCode);
  2025. }
  2026. $retVal = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  2027. }
  2028. return $retVal;
  2029. }
  2030. /**
  2031. * Displays a blob document *inline* (if possible, depending on the type of the document)
  2032. * @return string
  2033. */
  2034. public function DisplayDocumentInline(WebPage $oPage, $sAttCode)
  2035. {
  2036. $oDoc = $this->Get($sAttCode);
  2037. $sClass = get_class($this);
  2038. $Id = $this->GetKey();
  2039. switch ($oDoc->GetMainMimeType())
  2040. {
  2041. case 'text':
  2042. case 'html':
  2043. $data = $oDoc->GetData();
  2044. switch($oDoc->GetMimeType())
  2045. {
  2046. case 'text/html':
  2047. case 'text/xml':
  2048. $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");
  2049. break;
  2050. default:
  2051. $oPage->add("<pre>".htmlentities(MyHelpers::beautifulstr($data, 1000, true), ENT_QUOTES, 'UTF-8')."</pre>\n");
  2052. }
  2053. break;
  2054. case 'application':
  2055. switch($oDoc->GetMimeType())
  2056. {
  2057. case 'application/pdf':
  2058. $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");
  2059. break;
  2060. default:
  2061. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2062. }
  2063. break;
  2064. case 'image':
  2065. $oPage->add("<img src=\"".utils::GetAbsoluteUrlAppRoot()."pages/ajax.render.php?operation=display_document&class=$sClass&id=$Id&field=$sAttCode\" />\n");
  2066. break;
  2067. default:
  2068. $oPage->add(Dict::S('UI:Document:NoPreview'));
  2069. }
  2070. }
  2071. // $m_highlightComparison[previous][new] => next value
  2072. protected static $m_highlightComparison = array(
  2073. HILIGHT_CLASS_CRITICAL => array(
  2074. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2075. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_CRITICAL,
  2076. HILIGHT_CLASS_OK => HILIGHT_CLASS_CRITICAL,
  2077. HILIGHT_CLASS_NONE => HILIGHT_CLASS_CRITICAL,
  2078. ),
  2079. HILIGHT_CLASS_WARNING => array(
  2080. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2081. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2082. HILIGHT_CLASS_OK => HILIGHT_CLASS_WARNING,
  2083. HILIGHT_CLASS_NONE => HILIGHT_CLASS_WARNING,
  2084. ),
  2085. HILIGHT_CLASS_OK => array(
  2086. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2087. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2088. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2089. HILIGHT_CLASS_NONE => HILIGHT_CLASS_OK,
  2090. ),
  2091. HILIGHT_CLASS_NONE => array(
  2092. HILIGHT_CLASS_CRITICAL => HILIGHT_CLASS_CRITICAL,
  2093. HILIGHT_CLASS_WARNING => HILIGHT_CLASS_WARNING,
  2094. HILIGHT_CLASS_OK => HILIGHT_CLASS_OK,
  2095. HILIGHT_CLASS_NONE => HILIGHT_CLASS_NONE,
  2096. ),
  2097. );
  2098. /**
  2099. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  2100. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  2101. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2102. * To Be overridden by derived classes
  2103. * @param void
  2104. * @return String The desired higlight class for the object/row
  2105. */
  2106. public function GetHilightClass()
  2107. {
  2108. // Possible return values are:
  2109. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  2110. $current = HILIGHT_CLASS_NONE; // Not hilighted by default
  2111. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2112. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2113. {
  2114. $new = $oExtensionInstance->GetHilightClass($this);
  2115. @$current = self::$m_highlightComparison[$current][$new];
  2116. }
  2117. return $current;
  2118. }
  2119. /**
  2120. * Re-order the fields based on their inter-dependencies
  2121. * @params hash @aFields field_code => array_of_depencies
  2122. * @return array Ordered array of fields or throws an exception
  2123. */
  2124. public static function OrderDependentFields($aFields)
  2125. {
  2126. $bCircular = false;
  2127. $aResult = array();
  2128. $iCount = 0;
  2129. do
  2130. {
  2131. $bSet = false;
  2132. $iCount++;
  2133. foreach($aFields as $sFieldCode => $aDeps)
  2134. {
  2135. foreach($aDeps as $key => $sDependency)
  2136. {
  2137. if (in_array($sDependency, $aResult))
  2138. {
  2139. // Dependency is resolved, remove it
  2140. unset($aFields[$sFieldCode][$key]);
  2141. }
  2142. }
  2143. if (count($aFields[$sFieldCode]) == 0)
  2144. {
  2145. // No more pending depencies for this field, add it to the list
  2146. $aResult[] = $sFieldCode;
  2147. unset($aFields[$sFieldCode]);
  2148. $bSet = true;
  2149. }
  2150. }
  2151. }
  2152. while($bSet && (count($aFields) > 0));
  2153. if (count($aFields) > 0)
  2154. {
  2155. $sMessage = "Error: Circular dependencies between the fields (or field missing in ZList) ! <pre>".print_r($aFields, true)."</pre>";
  2156. throw(new Exception($sMessage));
  2157. }
  2158. return $aResult;
  2159. }
  2160. /**
  2161. * Get the list of actions to be displayed as 'shortcuts' (i.e buttons) instead of inside the Actions popup menu
  2162. * @param $sFinalClass string The actual class of the objects for which to display the menu
  2163. * @return Array the list of menu codes (i.e dictionary entries) that can be displayed as shortcuts next to the actions menu
  2164. */
  2165. public static function GetShortcutActions($sFinalClass)
  2166. {
  2167. $sShortcutActions = MetaModel::GetConfig()->Get('shortcut_actions');
  2168. $aShortcutActions = explode(',', $sShortcutActions);
  2169. return $aShortcutActions;
  2170. }
  2171. /**
  2172. * Maps the given context parameter name to the appropriate filter/search code for this class
  2173. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  2174. * @return string Filter code, i.e. 'customer_id'
  2175. */
  2176. public static function MapContextParam($sContextParam)
  2177. {
  2178. if ($sContextParam == 'menu')
  2179. {
  2180. return null;
  2181. }
  2182. else
  2183. {
  2184. return $sContextParam;
  2185. }
  2186. }
  2187. /**
  2188. * Updates the object from a flat array of values
  2189. * @param $aAttList array $aAttList array of attcode
  2190. * @param $aErrors array Returns information about slave attributes
  2191. * @param $sTargetState string Target state for which to evaluate the writeable attributes (=current state is empty)
  2192. * @return array of attcodes that can be used for writing on the current object
  2193. */
  2194. public function GetWriteableAttList($aAttList, &$aErrors, $sTargetState = '')
  2195. {
  2196. if (!is_array($aAttList))
  2197. {
  2198. $aAttList = $this->FlattenZList(MetaModel::GetZListItems(get_class($this), 'details'));
  2199. // Special case to process the case log, if any...
  2200. // WARNING: if you change this also check the functions DisplayModifyForm and DisplayCaseLog
  2201. foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef)
  2202. {
  2203. if ($this->IsNew())
  2204. {
  2205. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2206. }
  2207. else
  2208. {
  2209. $aVoid = array();
  2210. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2211. }
  2212. if ($oAttDef instanceof AttributeCaseLog)
  2213. {
  2214. if (!($iFlags & (OPT_ATT_HIDDEN|OPT_ATT_SLAVE|OPT_ATT_READONLY)))
  2215. {
  2216. // The case log is editable, append it to the list of fields to retrieve
  2217. $aAttList[] = $sAttCode;
  2218. }
  2219. }
  2220. }
  2221. }
  2222. $aWriteableAttList = array();
  2223. foreach($aAttList as $sAttCode)
  2224. {
  2225. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2226. if ($this->IsNew())
  2227. {
  2228. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2229. }
  2230. else
  2231. {
  2232. $aVoid = array();
  2233. $iFlags = $this->GetAttributeFlags($sAttCode, $aVoid, $sTargetState);
  2234. }
  2235. if ($oAttDef->IsWritable())
  2236. {
  2237. if ( $iFlags & (OPT_ATT_HIDDEN | OPT_ATT_READONLY))
  2238. {
  2239. // Non-visible, or read-only attribute, do nothing
  2240. }
  2241. elseif($iFlags & OPT_ATT_SLAVE)
  2242. {
  2243. $aErrors[$sAttCode] = Dict::Format('UI:AttemptingToSetASlaveAttribute_Name', $oAttDef->GetLabel());
  2244. }
  2245. else
  2246. {
  2247. $aWriteableAttList[$sAttCode] = $oAttDef;
  2248. }
  2249. }
  2250. }
  2251. return $aWriteableAttList;
  2252. }
  2253. /**
  2254. * Updates the object from a flat array of values
  2255. * @param string $aValues array of attcode => scalar or array (N-N links)
  2256. * @return void
  2257. */
  2258. public function UpdateObjectFromArray($aValues)
  2259. {
  2260. foreach($aValues as $sAttCode => $value)
  2261. {
  2262. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2263. if ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  2264. {
  2265. $aLinks = $value;
  2266. $sLinkedClass = $oAttDef->GetLinkedClass();
  2267. $sExtKeyToRemote = $oAttDef->GetExtKeyToRemote();
  2268. $sExtKeyToMe = $oAttDef->GetExtKeyToMe();
  2269. $oLinkedSet = DBObjectSet::FromScratch($sLinkedClass);
  2270. if (is_array($aLinks))
  2271. {
  2272. foreach($aLinks as $id => $aData)
  2273. {
  2274. if (is_numeric($id))
  2275. {
  2276. if ($id < 0)
  2277. {
  2278. // New link to be created, the opposite of the id (-$id) is the ID of the remote object
  2279. $oLink = MetaModel::NewObject($sLinkedClass);
  2280. $oLink->Set($sExtKeyToRemote, -$id);
  2281. $oLink->Set($sExtKeyToMe, $this->GetKey());
  2282. }
  2283. else
  2284. {
  2285. // Existing link, potentially to be updated...
  2286. $oLink = MetaModel::GetObject($sLinkedClass, $id);
  2287. }
  2288. // Now populate the attributes
  2289. foreach($aData as $sName => $value)
  2290. {
  2291. if (MetaModel::IsValidAttCode($sLinkedClass, $sName))
  2292. {
  2293. $oLinkAttDef = MetaModel::GetAttributeDef($sLinkedClass, $sName);
  2294. if ($oLinkAttDef->IsWritable())
  2295. {
  2296. $oLink->Set($sName, $value);
  2297. }
  2298. }
  2299. }
  2300. $oLinkedSet->AddObject($oLink);
  2301. }
  2302. }
  2303. }
  2304. $this->Set($sAttCode, $oLinkedSet);
  2305. }
  2306. elseif ($oAttDef->GetEditClass() == 'Document')
  2307. {
  2308. // There should be an uploaded file with the named attr_<attCode>
  2309. $oDocument = $value['fcontents'];
  2310. if (!$oDocument->IsEmpty())
  2311. {
  2312. // A new file has been uploaded
  2313. $this->Set($sAttCode, $oDocument);
  2314. }
  2315. }
  2316. elseif ($oAttDef->GetEditClass() == 'One Way Password')
  2317. {
  2318. // Check if the password was typed/changed
  2319. $aPwdData = $value;
  2320. if (!is_null($aPwdData) && $aPwdData['changed'])
  2321. {
  2322. // The password has been changed or set
  2323. $this->Set($sAttCode, $aPwdData['value']);
  2324. }
  2325. }
  2326. elseif ($oAttDef->GetEditClass() == 'Duration')
  2327. {
  2328. $aDurationData = $value;
  2329. if (!is_array($aDurationData)) continue;
  2330. $iValue = (((24*$aDurationData['d'])+$aDurationData['h'])*60 +$aDurationData['m'])*60 + $aDurationData['s'];
  2331. $this->Set($sAttCode, $iValue);
  2332. $previousValue = $this->Get($sAttCode);
  2333. if ($previousValue !== $iValue)
  2334. {
  2335. $this->Set($sAttCode, $iValue);
  2336. }
  2337. }
  2338. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE))
  2339. {
  2340. $oLinkset = $this->Get($sAttCode);
  2341. $sLinkedClass = $oLinkset->GetClass();
  2342. $aObjSet = array();
  2343. $oLinkset->Rewind();
  2344. $bModified = false;
  2345. while($oLink = $oLinkset->Fetch())
  2346. {
  2347. if (in_array($oLink->GetKey(), $value['to_be_deleted']))
  2348. {
  2349. // The link is to be deleted, don't copy it in the array
  2350. $bModified = true;
  2351. }
  2352. else
  2353. {
  2354. $aObjSet[] = $oLink;
  2355. }
  2356. }
  2357. if (array_key_exists('to_be_created', $value) && (count($value['to_be_created']) > 0))
  2358. {
  2359. // Now handle the lniks to be created
  2360. foreach($value['to_be_created'] as $aData)
  2361. {
  2362. $sSubClass = $aData['class'];
  2363. if ( ($sLinkedClass == $sSubClass) || (is_subclass_of($sSubClass, $sLinkedClass)) )
  2364. {
  2365. $aObjData = $aData['data'];
  2366. $oLink = new $sSubClass;
  2367. $oLink->UpdateObjectFromArray($aObjData);
  2368. $aObjSet[] = $oLink;
  2369. $bModified = true;
  2370. }
  2371. }
  2372. }
  2373. if ($bModified)
  2374. {
  2375. $oNewSet = DBObjectSet::FromArray($oLinkset->GetClass(), $aObjSet);
  2376. $this->Set($sAttCode, $oNewSet);
  2377. }
  2378. }
  2379. else
  2380. {
  2381. if (!is_null($value))
  2382. {
  2383. $aAttributes[$sAttCode] = trim($value);
  2384. $previousValue = $this->Get($sAttCode);
  2385. if ($previousValue !== $aAttributes[$sAttCode])
  2386. {
  2387. $this->Set($sAttCode, $aAttributes[$sAttCode]);
  2388. }
  2389. }
  2390. }
  2391. }
  2392. }
  2393. /**
  2394. * Updates the object from the POSTed parameters (form)
  2395. */
  2396. public function UpdateObjectFromPostedForm($sFormPrefix = '', $aAttList = null, $sTargetState = '')
  2397. {
  2398. if (is_null($aAttList))
  2399. {
  2400. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2401. }
  2402. $aValues = array();
  2403. foreach($aAttList as $sAttCode)
  2404. {
  2405. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2406. if ($oAttDef->GetEditClass() == 'Document')
  2407. {
  2408. $value = array('fcontents' => utils::ReadPostedDocument("attr_{$sFormPrefix}{$sAttCode}", 'fcontents'));
  2409. }
  2410. else if (($oAttDef->GetEditClass() == 'LinkedSet') && !$oAttDef->IsIndirect() && ($oAttDef->GetEditMode() == LINKSET_EDITMODE_INPLACE))
  2411. {
  2412. $aRawToBeCreated = json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbc", '{}', 'raw_data'), true);
  2413. $aToBeCreated = array();
  2414. foreach($aRawToBeCreated as $aData)
  2415. {
  2416. $sSubFormPrefix = $aData['formPrefix'];
  2417. $sObjClass = $aData['class'];
  2418. $aObjData = array();
  2419. foreach($aData as $sKey => $value)
  2420. {
  2421. if (preg_match("/^attr_$sSubFormPrefix(.*)$/", $sKey, $aMatches))
  2422. {
  2423. $aObjData[$aMatches[1]] = $value;
  2424. }
  2425. }
  2426. $aToBeCreated[] = array('class' => $sObjClass, 'data' => $aObjData);
  2427. }
  2428. $value = array('to_be_created' => $aToBeCreated,
  2429. 'to_be_deleted' => json_decode(utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}_tbd", '[]', 'raw_data'), true) );
  2430. }
  2431. else
  2432. {
  2433. $value = utils::ReadPostedParam("attr_{$sFormPrefix}{$sAttCode}", null, 'raw_data');
  2434. }
  2435. if (!is_null($value))
  2436. {
  2437. $aValues[$sAttCode] = $value;
  2438. }
  2439. }
  2440. $aErrors = array();
  2441. $aFinalValues = array();
  2442. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2443. {
  2444. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2445. }
  2446. $this->UpdateObjectFromArray($aFinalValues);
  2447. // Invoke extensions after the update of the object from the form
  2448. foreach (MetaModel::EnumPlugins('iApplicationUIExtension') as $oExtensionInstance)
  2449. {
  2450. $oExtensionInstance->OnFormSubmit($this, $sFormPrefix);
  2451. }
  2452. return $aErrors;
  2453. }
  2454. /**
  2455. * Updates the object from a given page argument
  2456. */
  2457. public function UpdateObjectFromArg($sArgName, $aAttList = null, $sTargetState = '')
  2458. {
  2459. if (is_null($aAttList))
  2460. {
  2461. $aAttList = array_keys(MetaModel::ListAttributeDefs(get_class($this)));
  2462. }
  2463. $aRawValues = utils::ReadParam($sArgName, array(), '', 'raw_data');
  2464. $aValues = array();
  2465. foreach($aAttList as $sAttCode)
  2466. {
  2467. if (isset($aRawValues[$sAttCode]))
  2468. {
  2469. $aValues[$sAttCode] = $aRawValues[$sAttCode];
  2470. }
  2471. }
  2472. $aErrors = array();
  2473. $aFinalValues = array();
  2474. foreach($this->GetWriteableAttList(array_keys($aValues), $aErrors, $sTargetState) as $sAttCode => $oAttDef)
  2475. {
  2476. $aFinalValues[$sAttCode] = $aValues[$sAttCode];
  2477. }
  2478. $this->UpdateObjectFromArray($aFinalValues);
  2479. return $aErrors;
  2480. }
  2481. public function DBInsertNoReload()
  2482. {
  2483. $res = parent::DBInsertNoReload();
  2484. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2485. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2486. {
  2487. $oExtensionInstance->OnDBInsert($this, self::GetCurrentChange());
  2488. }
  2489. return $res;
  2490. }
  2491. protected function DBCloneTracked_Internal($newKey = null)
  2492. {
  2493. $oNewObj = parent::DBCloneTracked_Internal($newKey);
  2494. // Invoke extensions after insertion (the object must exist, have an id, etc.)
  2495. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2496. {
  2497. $oExtensionInstance->OnDBInsert($oNewObj, self::GetCurrentChange());
  2498. }
  2499. return $oNewObj;
  2500. }
  2501. public function DBUpdate()
  2502. {
  2503. $res = parent::DBUpdate();
  2504. // Invoke extensions after the update (could be before)
  2505. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2506. {
  2507. $oExtensionInstance->OnDBUpdate($this, self::GetCurrentChange());
  2508. }
  2509. return $res;
  2510. }
  2511. protected static function BulkUpdateTracked_Internal(DBObjectSearch $oFilter, array $aValues)
  2512. {
  2513. // Todo - invoke the extension
  2514. return parent::BulkUpdateTracked_Internal($oFilter, $aValues);
  2515. }
  2516. protected function DBDeleteTracked_Internal(&$oDeletionPlan = null)
  2517. {
  2518. // Invoke extensions before the deletion (the deletion will do some cleanup and we might loose some information
  2519. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2520. {
  2521. $oExtensionInstance->OnDBDelete($this, self::GetCurrentChange());
  2522. }
  2523. return parent::DBDeleteTracked_Internal($oDeletionPlan);
  2524. }
  2525. public function IsModified()
  2526. {
  2527. if (parent::IsModified())
  2528. {
  2529. return true;
  2530. }
  2531. // Plugins
  2532. //
  2533. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2534. {
  2535. if ($oExtensionInstance->OnIsModified($this))
  2536. {
  2537. return true;
  2538. }
  2539. }
  2540. return false;
  2541. }
  2542. public function DoCheckToWrite()
  2543. {
  2544. parent::DoCheckToWrite();
  2545. // Plugins
  2546. //
  2547. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2548. {
  2549. $aNewIssues = $oExtensionInstance->OnCheckToWrite($this);
  2550. if (count($aNewIssues) > 0)
  2551. {
  2552. $this->m_aCheckIssues = array_merge($this->m_aCheckIssues, $aNewIssues);
  2553. }
  2554. }
  2555. // User rights
  2556. //
  2557. $aChanges = $this->ListChanges();
  2558. if (count($aChanges) > 0)
  2559. {
  2560. $aForbiddenFields = array();
  2561. foreach ($this->ListChanges() as $sAttCode => $value)
  2562. {
  2563. $bUpdateAllowed = UserRights::IsActionAllowedOnAttribute(get_class($this), $sAttCode, UR_ACTION_MODIFY, DBObjectSet::FromObject($this));
  2564. if (!$bUpdateAllowed)
  2565. {
  2566. $oAttCode = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2567. $aForbiddenFields[] = $oAttCode->GetLabel();
  2568. }
  2569. }
  2570. if (count($aForbiddenFields) > 0)
  2571. {
  2572. // Security issue
  2573. $this->m_bSecurityIssue = true;
  2574. $this->m_aCheckIssues[] = Dict::Format('UI:Delete:NotAllowedToUpdate_Fields',implode(', ', $aForbiddenFields));
  2575. }
  2576. }
  2577. }
  2578. protected function DoCheckToDelete(&$oDeletionPlan)
  2579. {
  2580. parent::DoCheckToDelete($oDeletionPlan);
  2581. // Plugins
  2582. //
  2583. foreach (MetaModel::EnumPlugins('iApplicationObjectExtension') as $oExtensionInstance)
  2584. {
  2585. $aNewIssues = $oExtensionInstance->OnCheckToDelete($this);
  2586. if (count($aNewIssues) > 0)
  2587. {
  2588. $this->m_aDeleteIssues = array_merge($this->m_aDeleteIssues, $aNewIssues);
  2589. }
  2590. }
  2591. // User rights
  2592. //
  2593. $bDeleteAllowed = UserRights::IsActionAllowed(get_class($this), UR_ACTION_DELETE, DBObjectSet::FromObject($this));
  2594. if (!$bDeleteAllowed)
  2595. {
  2596. // Security issue
  2597. $this->m_bSecurityIssue = true;
  2598. $this->m_aDeleteIssues[] = Dict::S('UI:Delete:NotAllowedToDelete');
  2599. }
  2600. }
  2601. /**
  2602. * Special display where the case log uses the whole "screen" at the bottom of the "Properties" tab
  2603. */
  2604. public function DisplayCaseLog(WebPage $oPage, $sAttCode, $sComment = '', $sPrefix = '', $bEditMode = false)
  2605. {
  2606. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  2607. $sClass = get_class($this);
  2608. if ($this->IsNew())
  2609. {
  2610. $iFlags = $this->GetInitialStateAttributeFlags($sAttCode);
  2611. }
  2612. else
  2613. {
  2614. $iFlags = $this->GetAttributeFlags($sAttCode);
  2615. }
  2616. if ( $iFlags & OPT_ATT_HIDDEN)
  2617. {
  2618. // The case log is hidden do nothing
  2619. }
  2620. else
  2621. {
  2622. $oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
  2623. $sInputId = $this->m_iFormId.'_'.$sAttCode;
  2624. if ((!$bEditMode) || ($iFlags & (OPT_ATT_READONLY|OPT_ATT_SLAVE)))
  2625. {
  2626. // Check if the attribute is not read-only because of a synchro...
  2627. $aReasons = array();
  2628. $sSynchroIcon = '';
  2629. if ($iFlags & OPT_ATT_SLAVE)
  2630. {
  2631. $iSynchroFlags = $this->GetSynchroReplicaFlags($sAttCode, $aReasons);
  2632. $sSynchroIcon = "&nbsp;<img id=\"synchro_$sInputId\" src=\"../images/transp-lock.png\" style=\"vertical-align:middle\"/>";
  2633. $sTip = '';
  2634. foreach($aReasons as $aRow)
  2635. {
  2636. $sTip .= "<p>Synchronized with {$aRow['name']} - {$aRow['description']}</p>";
  2637. }
  2638. $oPage->add_ready_script("$('#synchro_$sInputId').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
  2639. }
  2640. // Attribute is read-only
  2641. $sHTMLValue = $this->GetAsHTML($sAttCode);
  2642. $sHTMLValue .= '<input type="hidden" id="'.$sInputId.'" name="attr_'.$sPrefix.$sAttCode.'" value="'.htmlentities($this->Get($sAttCode), ENT_QUOTES, 'UTF-8').'"/>';
  2643. $aFieldsMap[$sAttCode] = $sInputId;
  2644. $sComment .= $sSynchroIcon;
  2645. }
  2646. else
  2647. {
  2648. $sValue = $this->Get($sAttCode);
  2649. $sDisplayValue = $this->GetEditValue($sAttCode);
  2650. $aArgs = array('this' => $this, 'formPrefix' => $sPrefix);
  2651. $sHTMLValue = '';
  2652. if ($sComment != '')
  2653. {
  2654. $sHTMLValue = '<span>'.$sComment.'</span><br/>';
  2655. }
  2656. $sHTMLValue .= "<span id=\"field_{$sInputId}\">".self::GetFormElementForField($oPage, $sClass, $sAttCode, $oAttDef, $sValue, $sDisplayValue, $sInputId, '', $iFlags, $aArgs).'</span>';
  2657. $aFieldsMap[$sAttCode] = $sInputId;
  2658. }
  2659. //$aVal = array('label' => '<span title="'.$oAttDef->GetDescription().'">'.$oAttDef->GetLabel().'</span>', 'value' => $sHTMLValue, 'comments' => $sComments, 'infos' => $sInfos);
  2660. $oPage->add('<fieldset><legend>'.$oAttDef->GetLabel().'</legend>');
  2661. $oPage->add($sHTMLValue);
  2662. $oPage->add('</fieldset>');
  2663. }
  2664. }
  2665. public function GetExpectedAttributes($sCurrentState, $sStimulus, $bOnlyNewOnes)
  2666. {
  2667. $aTransitions = $this->EnumTransitions();
  2668. $aStimuli = MetaModel::EnumStimuli(get_class($this));
  2669. if (!isset($aTransitions[$sStimulus]))
  2670. {
  2671. // Invalid stimulus
  2672. throw new ApplicationException(Dict::Format('UI:Error:Invalid_Stimulus_On_Object_In_State', $sStimulus, $oObj->GetName(), $oObj->GetStateLabel()));
  2673. }
  2674. $aTransition = $aTransitions[$sStimulus];
  2675. $sTargetState = $aTransition['target_state'];
  2676. $aTargetStates = MetaModel::EnumStates(get_class($this));
  2677. $aTargetState = $aTargetStates[$sTargetState];
  2678. $aCurrentState = $aTargetStates[$this->GetState()];
  2679. $aExpectedAttributes = $aTargetState['attribute_list'];
  2680. $aCurrentAttributes = $aCurrentState['attribute_list'];
  2681. $aComputedAttributes = array();
  2682. foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
  2683. {
  2684. if (!array_key_exists($sAttCode, $aCurrentAttributes))
  2685. {
  2686. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2687. }
  2688. else
  2689. {
  2690. if ( !($aCurrentAttributes[$sAttCode] & (OPT_ATT_HIDDEN|OPT_ATT_READONLY)) )
  2691. {
  2692. $iExpectCode = $iExpectCode & ~(OPT_ATT_MUSTPROMPT|OPT_ATT_MUSTCHANGE); // Already prompted/changed, reset the flags
  2693. }
  2694. //TODO: better check if the attribute is not *null*
  2695. if ( ($iExpectCode & OPT_ATT_MANDATORY) && ($this->Get($sAttCode) != ''))
  2696. {
  2697. $iExpectCode = $iExpectCode & ~(OPT_ATT_MANDATORY); // If the attribute is present, then no need to request its presence
  2698. }
  2699. $aComputedAttributes[$sAttCode] = $iExpectCode;
  2700. }
  2701. $aComputedAttributes[$sAttCode] = $aComputedAttributes[$sAttCode] & ~(OPT_ATT_READONLY|OPT_ATT_HIDDEN); // Don't care about this form now
  2702. if ($aComputedAttributes[$sAttCode] == 0)
  2703. {
  2704. unset($aComputedAttributes[$sAttCode]);
  2705. }
  2706. }
  2707. return $aComputedAttributes;
  2708. }
  2709. /**
  2710. * Display a form for modifying several objects at once
  2711. * The form will be submitted to the current page, with the specified additional values
  2712. */
  2713. public static function DisplayBulkModifyForm($oP, $sClass, $aSelectedObj, $sCustomOperation, $sCancelUrl, $aExcludeAttributes = array(), $aContextData = array())
  2714. {
  2715. if (count($aSelectedObj) > 0)
  2716. {
  2717. $iAllowedCount = count($aSelectedObj);
  2718. $sSelectedObj = implode(',', $aSelectedObj);
  2719. $sOQL = "SELECT $sClass WHERE id IN (".$sSelectedObj.")";
  2720. $oSet = new CMDBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2721. // Compute the distribution of the values for each field to determine which of the "scalar" fields are homogenous
  2722. $aList = MetaModel::ListAttributeDefs($sClass);
  2723. $aValues = array();
  2724. foreach($aList as $sAttCode => $oAttDef)
  2725. {
  2726. if ($oAttDef->IsScalar())
  2727. {
  2728. $aValues[$sAttCode] = array();
  2729. }
  2730. }
  2731. while($oObj = $oSet->Fetch())
  2732. {
  2733. foreach($aList as $sAttCode => $oAttDef)
  2734. {
  2735. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2736. {
  2737. $currValue = $oObj->Get($sAttCode);
  2738. if ($oAttDef instanceof AttributeCaseLog)
  2739. {
  2740. $currValue = ' '; // Don't put an empty string, in case the field would be considered as mandatory...
  2741. }
  2742. if (is_object($currValue)) continue; // Skip non scalar values...
  2743. if(!array_key_exists($currValue, $aValues[$sAttCode]))
  2744. {
  2745. $aValues[$sAttCode][$currValue] = array('count' => 1, 'display' => $oObj->GetAsHTML($sAttCode));
  2746. }
  2747. else
  2748. {
  2749. $aValues[$sAttCode][$currValue]['count']++;
  2750. }
  2751. }
  2752. }
  2753. }
  2754. // Now create an object that has values for the homogenous values only
  2755. $oDummyObj = new $sClass(); // @@ What if the class is abstract ?
  2756. $aComments = array();
  2757. function MyComparison($a, $b) // Sort descending
  2758. {
  2759. if ($a['count'] == $b['count'])
  2760. {
  2761. return 0;
  2762. }
  2763. return ($a['count'] > $b['count']) ? -1 : 1;
  2764. }
  2765. $iFormId = cmdbAbstractObject::GetNextFormId(); // Identifier that prefixes all the form fields
  2766. $sReadyScript = '';
  2767. $aDependsOn = array();
  2768. $sFormPrefix = '2_';
  2769. foreach($aList as $sAttCode => $oAttDef)
  2770. {
  2771. $aPrerequisites = MetaModel::GetPrequisiteAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  2772. if (count($aPrerequisites) > 0)
  2773. {
  2774. // When 'enabling' a field, all its prerequisites must be enabled too
  2775. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aPrerequisites)."']";
  2776. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, true); } );\n");
  2777. }
  2778. $aDependents = MetaModel::GetDependentAttributes($sClass, $sAttCode); // List of attributes that are needed for the current one
  2779. if (count($aDependents) > 0)
  2780. {
  2781. // When 'disabling' a field, all its dependent fields must be disabled too
  2782. $sFieldList = "['{$sFormPrefix}".implode("','{$sFormPrefix}", $aDependents)."']";
  2783. $oP->add_ready_script("$('#enable_{$sFormPrefix}{$sAttCode}').bind('change', function(evt, sFormId) { return PropagateCheckBox( this.checked, $sFieldList, false); } );\n");
  2784. }
  2785. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  2786. {
  2787. if ($oAttDef->GetEditClass() == 'One Way Password')
  2788. {
  2789. $sTip = "Unknown values";
  2790. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  2791. $oDummyObj->Set($sAttCode, null);
  2792. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2793. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'"> ? </div>';
  2794. $sReadyScript .= 'ToogleField(false, \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  2795. }
  2796. else
  2797. {
  2798. $iCount = count($aValues[$sAttCode]);
  2799. if ($iCount == 1)
  2800. {
  2801. // Homogenous value
  2802. reset($aValues[$sAttCode]);
  2803. $aKeys = array_keys($aValues[$sAttCode]);
  2804. $currValue = $aKeys[0]; // The only value is the first key
  2805. //echo "<p>current value for $sAttCode : $currValue</p>";
  2806. $oDummyObj->Set($sAttCode, $currValue);
  2807. $aComments[$sAttCode] = '<input type="checkbox" checked id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2808. $aComments[$sAttCode] .= '<div class="mono_value">1</div>';
  2809. }
  2810. else
  2811. {
  2812. // Non-homogenous value
  2813. $aMultiValues = $aValues[$sAttCode];
  2814. uasort($aMultiValues, 'MyComparison');
  2815. $iMaxCount = 5;
  2816. $sTip = "<p><b>".Dict::Format('UI:BulkModify_Count_DistinctValues', $iCount)."</b><ul>";
  2817. $index = 0;
  2818. foreach($aMultiValues as $sCurrValue => $aVal)
  2819. {
  2820. $sDisplayValue = empty($aVal['display']) ? '<i>'.Dict::S('Enum:Undefined').'</i>' : str_replace(array("\n", "\r"), " ", $aVal['display']);
  2821. $sTip .= "<li>".Dict::Format('UI:BulkModify:Value_Exists_N_Times', $sDisplayValue, $aVal['count'])."</li>";
  2822. $index++;
  2823. if ($iMaxCount == $index)
  2824. {
  2825. $sTip .= "<li>".Dict::Format('UI:BulkModify:N_MoreValues', count($aMultiValues) - $iMaxCount)."</li>";
  2826. break;
  2827. }
  2828. }
  2829. $sTip .= "</ul></p>";
  2830. $sTip = addslashes($sTip);
  2831. $sReadyScript .= "$('#multi_values_$sAttCode').qtip( { content: '$sTip', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );";
  2832. $oDummyObj->Set($sAttCode, null);
  2833. $aComments[$sAttCode] = '<input type="checkbox" id="enable_'.$iFormId.'_'.$sAttCode.'" onClick="ToogleField(this.checked, \''.$iFormId.'_'.$sAttCode.'\')"/>';
  2834. $aComments[$sAttCode] .= '<div class="multi_values" id="multi_values_'.$sAttCode.'">'.$iCount.'</div>';
  2835. }
  2836. $sReadyScript .= 'ToogleField('.(($iCount == 1) ? 'true': 'false').', \''.$iFormId.'_'.$sAttCode.'\');'."\n";
  2837. }
  2838. }
  2839. }
  2840. $sStateAttCode = MetaModel::GetStateAttributeCode($sClass);
  2841. if (($sStateAttCode != '') && ($oDummyObj->GetState() == ''))
  2842. {
  2843. // Hmmm, it's not gonna work like this ! Set a default value for the "state"
  2844. // Maybe we should use the "state" that is the most common among the objects...
  2845. $aMultiValues = $aValues[$sStateAttCode];
  2846. uasort($aMultiValues, 'MyComparison');
  2847. foreach($aMultiValues as $sCurrValue => $aVal)
  2848. {
  2849. $oDummyObj->Set($sStateAttCode, $sCurrValue);
  2850. break;
  2851. }
  2852. //$oStateAtt = MetaModel::GetAttributeDef($sClass, $sStateAttCode);
  2853. //$oDummyObj->Set($sStateAttCode, $oStateAtt->GetDefaultValue());
  2854. }
  2855. $oP->add("<div class=\"page_header\">\n");
  2856. $oP->add("<h1>".$oDummyObj->GetIcon()."&nbsp;".Dict::Format('UI:Modify_M_ObjectsOf_Class_OutOf_N', $iAllowedCount, $sClass, $iAllowedCount)."</h1>\n");
  2857. $oP->add("</div>\n");
  2858. $oP->add("<div class=\"wizContainer\">\n");
  2859. $sDisableFields = json_encode($aExcludeAttributes);
  2860. $aParams = array
  2861. (
  2862. 'fieldsComments' => $aComments,
  2863. 'noRelations' => true,
  2864. 'custom_operation' => $sCustomOperation,
  2865. 'custom_button' => Dict::S('UI:Button:PreviewModifications'),
  2866. 'selectObj' => $sSelectedObj,
  2867. 'preview_mode' => true,
  2868. 'disabled_fields' => $sDisableFields,
  2869. 'disable_plugins' => true
  2870. );
  2871. $aParams = $aParams + $aContextData; // merge keeping associations
  2872. $oDummyObj->DisplayModifyForm($oP, $aParams);
  2873. $oP->add("</div>\n");
  2874. $oP->add_ready_script($sReadyScript);
  2875. $oP->add_ready_script(
  2876. <<<EOF
  2877. $('.wizContainer button.cancel').unbind('click');
  2878. $('.wizContainer button.cancel').click( function() { window.location.href = '$sCancelUrl'; } );
  2879. EOF
  2880. );
  2881. } // Else no object selected ???
  2882. else
  2883. {
  2884. $oP->p("No object selected !, nothing to do");
  2885. }
  2886. }
  2887. /**
  2888. * Process the reply made from a form built with DisplayBulkModifyForm
  2889. */
  2890. public static function DoBulkModify($oP, $sClass, $aSelectedObj, $sCustomOperation, $bPreview, $sCancelUrl, $aContextData = array())
  2891. {
  2892. $aHeaders = array(
  2893. 'form::select' => array('label' => "<input type=\"checkbox\" onClick=\"CheckAll('.selectList:not(:disabled)', this.checked);\"></input>", 'description' => Dict::S('UI:SelectAllToggle+')),
  2894. 'object' => array('label' => MetaModel::GetName($sClass), 'description' => Dict::S('UI:ModifiedObject')),
  2895. 'status' => array('label' => Dict::S('UI:BulkModifyStatus'), 'description' => Dict::S('UI:BulkModifyStatus+')),
  2896. 'errors' => array('label' => Dict::S('UI:BulkModifyErrors'), 'description' => Dict::S('UI:BulkModifyErrors+')),
  2897. );
  2898. $aRows = array();
  2899. $oP->add("<div class=\"page_header\">\n");
  2900. $oP->add("<h1>".MetaModel::GetClassIcon($sClass)."&nbsp;".Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass)."</h1>\n");
  2901. $oP->add("</div>\n");
  2902. $oP->set_title(Dict::Format('UI:Modify_N_ObjectsOf_Class', count($aSelectedObj), $sClass));
  2903. if (!$bPreview)
  2904. {
  2905. // Not in preview mode, do the update for real
  2906. $sTransactionId = utils::ReadPostedParam('transaction_id', '');
  2907. if (!utils::IsTransactionValid($sTransactionId, false))
  2908. {
  2909. throw new Exception(Dict::S('UI:Error:ObjectAlreadyUpdated'));
  2910. }
  2911. utils::RemoveTransaction($sTransactionId);
  2912. }
  2913. foreach($aSelectedObj as $iId)
  2914. {
  2915. $oObj = MetaModel::GetObject($sClass, $iId);
  2916. $aErrors = $oObj->UpdateObjectFromPostedForm('');
  2917. $bResult = (count($aErrors) == 0);
  2918. if ($bResult)
  2919. {
  2920. list($bResult, $aErrors) = $oObj->CheckToWrite(true /* Enforce Read-only fields */);
  2921. }
  2922. if ($bPreview)
  2923. {
  2924. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusOk') : Dict::S('UI:BulkModifyStatusError');
  2925. }
  2926. else
  2927. {
  2928. $sStatus = $bResult ? Dict::S('UI:BulkModifyStatusModified') : Dict::S('UI:BulkModifyStatusSkipped');
  2929. }
  2930. $sCSSClass = $bResult ? HILIGHT_CLASS_NONE : HILIGHT_CLASS_CRITICAL;
  2931. $sChecked = $bResult ? 'checked' : '';
  2932. $sDisabled = $bResult ? '' : 'disabled';
  2933. $aRows[] = array(
  2934. 'form::select' => "<input type=\"checkbox\" class=\"selectList\" $sChecked $sDisabled\"></input>",
  2935. 'object' => $oObj->GetHyperlink(),
  2936. 'status' => $sStatus,
  2937. 'errors' => '<p>'.($bResult ? '': implode('</p><p>', $aErrors)).'</p>',
  2938. '@class' => $sCSSClass,
  2939. );
  2940. if ($bResult && (!$bPreview))
  2941. {
  2942. $oObj->DBUpdate();
  2943. }
  2944. }
  2945. $oP->Table($aHeaders, $aRows);
  2946. if ($bPreview)
  2947. {
  2948. $sFormAction = $_SERVER['SCRIPT_NAME']; // No parameter in the URL, the only parameter will be the ones passed through the form
  2949. // Form to submit:
  2950. $oP->add("<form method=\"post\" action=\"$sFormAction\" enctype=\"multipart/form-data\">\n");
  2951. $aDefaults = utils::ReadParam('default', array());
  2952. $oAppContext = new ApplicationContext();
  2953. $oP->add($oAppContext->GetForForm());
  2954. foreach ($aContextData as $sKey => $value)
  2955. {
  2956. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  2957. }
  2958. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  2959. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  2960. $oP->add("<input type=\"hidden\" name=\"preview_mode\" value=\"0\">\n");
  2961. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  2962. $oP->add("<button type=\"button\" class=\"action cancel\" onClick=\"window.location.href='$sCancelUrl'\">".Dict::S('UI:Button:Cancel')."</button>&nbsp;&nbsp;&nbsp;&nbsp;\n");
  2963. $oP->add("<button type=\"submit\" class=\"action\"><span>".Dict::S('UI:Button:ModifyAll')."</span></button>\n");
  2964. foreach($_POST as $sKey => $value)
  2965. {
  2966. if (preg_match('/attr_(.+)/', $sKey, $aMatches))
  2967. {
  2968. // Beware: some values (like durations) are passed as arrays
  2969. if (is_array($value))
  2970. {
  2971. foreach($value as $vKey => $vValue)
  2972. {
  2973. $oP->add("<input type=\"hidden\" name=\"{$sKey}[$vKey]\" value=\"$vValue\">\n");
  2974. }
  2975. }
  2976. else
  2977. {
  2978. $oP->add("<input type=\"hidden\" name=\"$sKey\" value=\"$value\">\n");
  2979. }
  2980. }
  2981. }
  2982. $oP->add("</form>\n");
  2983. }
  2984. else
  2985. {
  2986. $oP->add("<button type=\"button\" onClick=\"window.location.href='$sCancelUrl'\" class=\"action\"><span>".Dict::S('UI:Button:Done')."</span></button>\n");
  2987. }
  2988. }
  2989. /**
  2990. * Perform all the needed checks to delete one (or more) objects
  2991. */
  2992. public static function DeleteObjects(WebPage $oP, $sClass, $aObjects, $bPreview, $sCustomOperation, $aContextData = array())
  2993. {
  2994. $oDeletionPlan = new DeletionPlan();
  2995. foreach($aObjects as $oObj)
  2996. {
  2997. if ($bPreview)
  2998. {
  2999. $oObj->CheckToDelete($oDeletionPlan);
  3000. }
  3001. else
  3002. {
  3003. $oObj->DBDeleteTracked(CMDBObject::GetCurrentChange(), null, $oDeletionPlan);
  3004. }
  3005. }
  3006. if ($bPreview)
  3007. {
  3008. if (count($aObjects) == 1)
  3009. {
  3010. $oObj = $aObjects[0];
  3011. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Name', $oObj->GetName())."</h1>\n");
  3012. }
  3013. else
  3014. {
  3015. $oP->add("<h1>".Dict::Format('UI:Delete:ConfirmDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3016. }
  3017. // Explain what should be done
  3018. //
  3019. $aDisplayData = array();
  3020. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3021. {
  3022. foreach ($aDeletes as $iId => $aData)
  3023. {
  3024. $oToDelete = $aData['to_delete'];
  3025. $bAutoDel = (($aData['mode'] == DEL_SILENT) || ($aData['mode'] == DEL_AUTO));
  3026. if (array_key_exists('issue', $aData))
  3027. {
  3028. if ($bAutoDel)
  3029. {
  3030. if (isset($aData['requested_explicitely']))
  3031. {
  3032. $sConsequence = Dict::Format('UI:Delete:CannotDeleteBecause', $aData['issue']);
  3033. }
  3034. else
  3035. {
  3036. $sConsequence = Dict::Format('UI:Delete:ShouldBeDeletedAtomaticallyButNotPossible', $aData['issue']);
  3037. }
  3038. }
  3039. else
  3040. {
  3041. $sConsequence = Dict::Format('UI:Delete:MustBeDeletedManuallyButNotPossible', $aData['issue']);
  3042. }
  3043. }
  3044. else
  3045. {
  3046. if ($bAutoDel)
  3047. {
  3048. if (isset($aData['requested_explicitely']))
  3049. {
  3050. $sConsequence = ''; // not applicable
  3051. }
  3052. else
  3053. {
  3054. $sConsequence = Dict::S('UI:Delete:WillBeDeletedAutomatically');
  3055. }
  3056. }
  3057. else
  3058. {
  3059. $sConsequence = Dict::S('UI:Delete:MustBeDeletedManually');
  3060. }
  3061. }
  3062. $aDisplayData[] = array(
  3063. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3064. 'object' => $oToDelete->GetHyperLink(),
  3065. 'consequence' => $sConsequence,
  3066. );
  3067. }
  3068. }
  3069. foreach ($oDeletionPlan->ListUpdates() as $sRemoteClass => $aToUpdate)
  3070. {
  3071. foreach ($aToUpdate as $iId => $aData)
  3072. {
  3073. $oToUpdate = $aData['to_reset'];
  3074. if (array_key_exists('issue', $aData))
  3075. {
  3076. $sConsequence = Dict::Format('UI:Delete:CannotUpdateBecause_Issue', $aData['issue']);
  3077. }
  3078. else
  3079. {
  3080. $sConsequence = Dict::Format('UI:Delete:WillAutomaticallyUpdate_Fields', $aData['attributes_list']);
  3081. }
  3082. $aDisplayData[] = array(
  3083. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3084. 'object' => $oToUpdate->GetHyperLink(),
  3085. 'consequence' => $sConsequence,
  3086. );
  3087. }
  3088. }
  3089. $iImpactedIndirectly = $oDeletionPlan->GetTargetCount() - count($aObjects);
  3090. if ($iImpactedIndirectly > 0)
  3091. {
  3092. if (count($aObjects) == 1)
  3093. {
  3094. $oObj = $aObjects[0];
  3095. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencing_Object', $iImpactedIndirectly, $oObj->GetName()));
  3096. }
  3097. else
  3098. {
  3099. $oP->p(Dict::Format('UI:Delete:Count_Objects/LinksReferencingTheObjects', $iImpactedIndirectly));
  3100. }
  3101. $oP->p(Dict::S('UI:Delete:ReferencesMustBeDeletedToEnsureIntegrity'));
  3102. }
  3103. if (($iImpactedIndirectly > 0) || $oDeletionPlan->FoundStopper())
  3104. {
  3105. $aDisplayConfig = array();
  3106. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3107. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3108. $aDisplayConfig['consequence'] = array('label' => 'Consequence', 'description' => Dict::S('UI:Delete:Consequence+'));
  3109. $oP->table($aDisplayConfig, $aDisplayData);
  3110. }
  3111. if ($oDeletionPlan->FoundStopper())
  3112. {
  3113. if ($oDeletionPlan->FoundSecurityIssue())
  3114. {
  3115. $oP->p(Dict::S('UI:Delete:SorryDeletionNotAllowed'));
  3116. }
  3117. elseif ($oDeletionPlan->FoundManualOperation())
  3118. {
  3119. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3120. }
  3121. else // $bFoundManualOp
  3122. {
  3123. $oP->p(Dict::S('UI:Delete:PleaseDoTheManualOperations'));
  3124. }
  3125. $oAppContext = new ApplicationContext();
  3126. $oP->add("<form method=\"post\">\n");
  3127. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::ReadParam('transaction_id')."\">\n");
  3128. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3129. $oP->add("<input DISABLED type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3130. $oP->add($oAppContext->GetForForm());
  3131. $oP->add("</form>\n");
  3132. }
  3133. else
  3134. {
  3135. if (count($aObjects) == 1)
  3136. {
  3137. $oObj = $aObjects[0];
  3138. $id = $oObj->GetKey();
  3139. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Object', $oObj->GetHyperLink()).'</h1>');
  3140. }
  3141. else
  3142. {
  3143. $oP->p('<h1>'.Dict::Format('UI:Delect:Confirm_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)).'</h1>');
  3144. }
  3145. foreach($aObjects as $oObj)
  3146. {
  3147. $aKeys[] = $oObj->GetKey();
  3148. }
  3149. $oFilter = new DBObjectSearch($sClass);
  3150. $oFilter->AddCondition('id', $aKeys, 'IN');
  3151. $oSet = new CMDBobjectSet($oFilter);
  3152. $oP->add('<div id="0">');
  3153. CMDBAbstractObject::DisplaySet($oP, $oSet, array('display_limit' => false, 'menu' => false));
  3154. $oP->add("</div>\n");
  3155. $oP->add("<form method=\"post\">\n");
  3156. foreach ($aContextData as $sKey => $value)
  3157. {
  3158. $oP->add("<input type=\"hidden\" name=\"{$sKey}\" value=\"$value\">\n");
  3159. }
  3160. $oP->add("<input type=\"hidden\" name=\"transaction_id\" value=\"".utils::GetNewTransactionId()."\">\n");
  3161. $oP->add("<input type=\"hidden\" name=\"operation\" value=\"$sCustomOperation\">\n");
  3162. $oP->add("<input type=\"hidden\" name=\"filter\" value=\"".$oFilter->Serialize()."\">\n");
  3163. $oP->add("<input type=\"hidden\" name=\"class\" value=\"$sClass\">\n");
  3164. foreach($aObjects as $oObj)
  3165. {
  3166. $oP->add("<input type=\"hidden\" name=\"selectObject[]\" value=\"".$oObj->GetKey()."\">\n");
  3167. }
  3168. $oP->add("<input type=\"button\" onclick=\"window.history.back();\" value=\"".Dict::S('UI:Button:Back')."\">\n");
  3169. $oP->add("<input type=\"submit\" name=\"\" value=\"".Dict::S('UI:Button:Delete')."\">\n");
  3170. $oAppContext = new ApplicationContext();
  3171. $oP->add($oAppContext->GetForForm());
  3172. $oP->add("</form>\n");
  3173. }
  3174. }
  3175. else // if ($bPreview)...
  3176. {
  3177. // Execute the deletion
  3178. //
  3179. if (count($aObjects) == 1)
  3180. {
  3181. $oObj = $aObjects[0];
  3182. $oP->add("<h1>".Dict::Format('UI:Title:DeletionOf_Object', $oObj->GetName())."</h1>\n");
  3183. }
  3184. else
  3185. {
  3186. $oP->add("<h1>".Dict::Format('UI:Title:BulkDeletionOf_Count_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass))."</h1>\n");
  3187. }
  3188. // Security - do not allow the user to force a forbidden delete by the mean of page arguments...
  3189. if ($oDeletionPlan->FoundSecurityIssue())
  3190. {
  3191. throw new CoreException(Dict::S('UI:Error:NotEnoughRightsToDelete'));
  3192. }
  3193. if ($oDeletionPlan->FoundManualOperation())
  3194. {
  3195. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseManualOpNeeded'));
  3196. }
  3197. if ($oDeletionPlan->FoundManualDelete())
  3198. {
  3199. throw new CoreException(Dict::S('UI:Error:CannotDeleteBecauseOfDepencies'));
  3200. }
  3201. // Report deletions
  3202. //
  3203. $aDisplayData = array();
  3204. foreach ($oDeletionPlan->ListDeletes() as $sTargetClass => $aDeletes)
  3205. {
  3206. foreach ($aDeletes as $iId => $aData)
  3207. {
  3208. $oToDelete = $aData['to_delete'];
  3209. if (isset($aData['requested_explicitely']))
  3210. {
  3211. $sMessage = Dict::S('UI:Delete:Deleted');
  3212. }
  3213. else
  3214. {
  3215. $sMessage = Dict::S('UI:Delete:AutomaticallyDeleted');
  3216. }
  3217. $aDisplayData[] = array(
  3218. 'class' => MetaModel::GetName(get_class($oToDelete)),
  3219. 'object' => $oToDelete->GetName(),
  3220. 'consequence' => $sMessage,
  3221. );
  3222. }
  3223. }
  3224. // Report updates
  3225. //
  3226. foreach ($oDeletionPlan->ListUpdates() as $sTargetClass => $aToUpdate)
  3227. {
  3228. foreach ($aToUpdate as $iId => $aData)
  3229. {
  3230. $oToUpdate = $aData['to_reset'];
  3231. $aDisplayData[] = array(
  3232. 'class' => MetaModel::GetName(get_class($oToUpdate)),
  3233. 'object' => $oToUpdate->GetHyperLink(),
  3234. 'consequence' => Dict::Format('UI:Delete:AutomaticResetOf_Fields', $aData['attributes_list']),
  3235. );
  3236. }
  3237. }
  3238. // Report automatic jobs
  3239. //
  3240. if ($oDeletionPlan->GetTargetCount() > 0)
  3241. {
  3242. if (count($aObjects) == 1)
  3243. {
  3244. $oObj = $aObjects[0];
  3245. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Object', $oObj->GetName()));
  3246. }
  3247. else
  3248. {
  3249. $oP->p(Dict::Format('UI:Delete:CleaningUpRefencesTo_Several_ObjectsOf_Class', count($aObjects), MetaModel::GetName($sClass)));
  3250. }
  3251. $aDisplayConfig = array();
  3252. $aDisplayConfig['class'] = array('label' => 'Class', 'description' => '');
  3253. $aDisplayConfig['object'] = array('label' => 'Object', 'description' => '');
  3254. $aDisplayConfig['consequence'] = array('label' => 'Done', 'description' => Dict::S('UI:Delete:Done+'));
  3255. $oP->table($aDisplayConfig, $aDisplayData);
  3256. }
  3257. }
  3258. }
  3259. }
  3260. ?>