cmdbabstract.class.inc.php 127 KB

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