cmdbabstract.class.inc.php 150 KB

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