cmdbabstract.class.inc.php 160 KB

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