cmdbabstract.class.inc.php 129 KB

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