cmdbabstract.class.inc.php 137 KB

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