cmdbabstract.class.inc.php 128 KB

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