cmdbabstract.class.inc.php 150 KB

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