cmdbabstract.class.inc.php 155 KB

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