metamodel.class.php 175 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198
  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. require_once(APPROOT.'core/modulehandler.class.inc.php');
  19. require_once(APPROOT.'core/querybuildercontext.class.inc.php');
  20. require_once(APPROOT.'core/querymodifier.class.inc.php');
  21. require_once(APPROOT.'core/metamodelmodifier.inc.php');
  22. require_once(APPROOT.'core/computing.inc.php');
  23. /**
  24. * Metamodel
  25. *
  26. * @copyright Copyright (C) 2010-2012 Combodo SARL
  27. * @license http://opensource.org/licenses/AGPL-3.0
  28. */
  29. // #@# todo: change into class const (see Doctrine)
  30. // Doctrine example
  31. // class toto
  32. // {
  33. // /**
  34. // * VERSION
  35. // */
  36. // const VERSION = '1.0.0';
  37. // }
  38. /**
  39. * add some description here...
  40. *
  41. * @package iTopORM
  42. */
  43. define('ENUM_CHILD_CLASSES_EXCLUDETOP', 1);
  44. /**
  45. * add some description here...
  46. *
  47. * @package iTopORM
  48. */
  49. define('ENUM_CHILD_CLASSES_ALL', 2);
  50. /**
  51. * add some description here...
  52. *
  53. * @package iTopORM
  54. */
  55. define('ENUM_PARENT_CLASSES_EXCLUDELEAF', 1);
  56. /**
  57. * add some description here...
  58. *
  59. * @package iTopORM
  60. */
  61. define('ENUM_PARENT_CLASSES_ALL', 2);
  62. /**
  63. * Specifies that this attribute is visible/editable.... normal (default config)
  64. *
  65. * @package iTopORM
  66. */
  67. define('OPT_ATT_NORMAL', 0);
  68. /**
  69. * Specifies that this attribute is hidden in that state
  70. *
  71. * @package iTopORM
  72. */
  73. define('OPT_ATT_HIDDEN', 1);
  74. /**
  75. * Specifies that this attribute is not editable in that state
  76. *
  77. * @package iTopORM
  78. */
  79. define('OPT_ATT_READONLY', 2);
  80. /**
  81. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  82. *
  83. * @package iTopORM
  84. */
  85. define('OPT_ATT_MANDATORY', 4);
  86. /**
  87. * Specifies that the attribute must change when arriving into that state
  88. *
  89. * @package iTopORM
  90. */
  91. define('OPT_ATT_MUSTCHANGE', 8);
  92. /**
  93. * Specifies that the attribute must be proposed when arriving into that state
  94. *
  95. * @package iTopORM
  96. */
  97. define('OPT_ATT_MUSTPROMPT', 16);
  98. /**
  99. * Specifies that the attribute is in 'slave' mode compared to one data exchange task:
  100. * it should not be edited inside iTop anymore
  101. *
  102. * @package iTopORM
  103. */
  104. define('OPT_ATT_SLAVE', 32);
  105. /**
  106. * DB Engine -should be moved into CMDBSource
  107. *
  108. * @package iTopORM
  109. */
  110. define('MYSQL_ENGINE', 'innodb');
  111. //define('MYSQL_ENGINE', 'myisam');
  112. /**
  113. * (API) The objects definitions as well as their mapping to the database
  114. *
  115. * @package iTopORM
  116. */
  117. abstract class MetaModel
  118. {
  119. ///////////////////////////////////////////////////////////////////////////
  120. //
  121. // STATIC Members
  122. //
  123. ///////////////////////////////////////////////////////////////////////////
  124. private static $m_bTraceSourceFiles = false;
  125. private static $m_aClassToFile = array();
  126. public static function GetClassFiles()
  127. {
  128. return self::$m_aClassToFile;
  129. }
  130. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  131. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  132. private static function GetCallersPHPClass($sExpectedFunctionName = null, $bRecordSourceFile = false)
  133. {
  134. //var_dump(debug_backtrace());
  135. $aBacktrace = debug_backtrace();
  136. // $aBacktrace[0] is where we are
  137. // $aBacktrace[1] is the caller of GetCallersPHPClass
  138. // $aBacktrace[1] is the info we want
  139. if (!empty($sExpectedFunctionName))
  140. {
  141. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  142. }
  143. if ($bRecordSourceFile)
  144. {
  145. self::$m_aClassToFile[$aBacktrace[2]["class"]] = $aBacktrace[1]["file"];
  146. }
  147. return $aBacktrace[2]["class"];
  148. }
  149. // Static init -why and how it works
  150. //
  151. // We found the following limitations:
  152. //- it is not possible to define non scalar constants
  153. //- it is not possible to declare a static variable as '= new myclass()'
  154. // Then we had do propose this model, in which a derived (non abstract)
  155. // class should implement Init(), to call InheritAttributes or AddAttribute.
  156. private static function _check_subclass($sClass)
  157. {
  158. // See also IsValidClass()... ???? #@#
  159. // class is mandatory
  160. // (it is not possible to guess it when called as myderived::...)
  161. if (!array_key_exists($sClass, self::$m_aClassParams))
  162. {
  163. throw new CoreException("Unknown class '$sClass', expected a value in {".implode(', ', array_keys(self::$m_aClassParams))."}");
  164. }
  165. }
  166. public static function static_var_dump()
  167. {
  168. var_dump(get_class_vars(__CLASS__));
  169. }
  170. private static $m_bDebugQuery = false;
  171. private static $m_iStackDepthRef = 0;
  172. public static function StartDebugQuery()
  173. {
  174. $aBacktrace = debug_backtrace();
  175. self::$m_iStackDepthRef = count($aBacktrace);
  176. self::$m_bDebugQuery = true;
  177. }
  178. public static function StopDebugQuery()
  179. {
  180. self::$m_bDebugQuery = false;
  181. }
  182. public static function DbgTrace($value)
  183. {
  184. if (!self::$m_bDebugQuery) return;
  185. $aBacktrace = debug_backtrace();
  186. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  187. $sIndent = "";
  188. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  189. {
  190. $sIndent .= " .-=^=-. ";
  191. }
  192. $aCallers = array();
  193. foreach($aBacktrace as $aStackInfo)
  194. {
  195. $aCallers[] = $aStackInfo["function"];
  196. }
  197. $sCallers = "Callstack: ".implode(', ', $aCallers);
  198. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  199. if (is_string($value))
  200. {
  201. echo "$sIndent$sFunction: $value<br/>\n";
  202. }
  203. else if (is_object($value))
  204. {
  205. echo "$sIndent$sFunction:\n<pre>\n";
  206. print_r($value);
  207. echo "</pre>\n";
  208. }
  209. else
  210. {
  211. echo "$sIndent$sFunction: $value<br/>\n";
  212. }
  213. }
  214. private static $m_oConfig = null;
  215. private static $m_bSkipCheckToWrite = false;
  216. private static $m_bSkipCheckExtKeys = false;
  217. private static $m_bUseAPCCache = false;
  218. private static $m_iQueryCacheTTL = 3600;
  219. private static $m_bQueryCacheEnabled = false;
  220. private static $m_bTraceQueries = false;
  221. private static $m_bIndentQueries = false;
  222. private static $m_bOptimizeQueries = false;
  223. private static $m_aQueriesLog = array();
  224. private static $m_bLogIssue = false;
  225. private static $m_bLogNotification = false;
  226. private static $m_bLogWebService = false;
  227. public static function SkipCheckToWrite()
  228. {
  229. return self::$m_bSkipCheckToWrite;
  230. }
  231. public static function SkipCheckExtKeys()
  232. {
  233. return self::$m_bSkipCheckExtKeys;
  234. }
  235. public static function IsLogEnabledIssue()
  236. {
  237. return self::$m_bLogIssue;
  238. }
  239. public static function IsLogEnabledNotification()
  240. {
  241. return self::$m_bLogNotification;
  242. }
  243. public static function IsLogEnabledWebService()
  244. {
  245. return self::$m_bLogWebService;
  246. }
  247. private static $m_sDBName = "";
  248. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  249. private static $m_Category2Class = array();
  250. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  251. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  252. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  253. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  254. static public function GetParentPersistentClass($sRefClass)
  255. {
  256. $sClass = get_parent_class($sRefClass);
  257. if (!$sClass) return '';
  258. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  259. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  260. if (array_key_exists($sClass, self::$m_aClassParams))
  261. {
  262. return $sClass;
  263. }
  264. return self::GetParentPersistentClass($sClass);
  265. }
  266. final static public function GetName($sClass)
  267. {
  268. self::_check_subclass($sClass);
  269. $sStringCode = 'Class:'.$sClass;
  270. return Dict::S($sStringCode, str_replace('_', ' ', $sClass));
  271. }
  272. final static public function GetName_Obsolete($sClass)
  273. {
  274. // Written for compatibility with a data model written prior to version 0.9.1
  275. self::_check_subclass($sClass);
  276. if (array_key_exists('name', self::$m_aClassParams[$sClass]))
  277. {
  278. return self::$m_aClassParams[$sClass]['name'];
  279. }
  280. else
  281. {
  282. return self::GetName($sClass);
  283. }
  284. }
  285. final static public function GetClassFromLabel($sClassLabel, $bCaseSensitive = true)
  286. {
  287. foreach(self::GetClasses() as $sClass)
  288. {
  289. if ($bCaseSensitive)
  290. {
  291. if (self::GetName($sClass) == $sClassLabel)
  292. {
  293. return $sClass;
  294. }
  295. }
  296. else
  297. {
  298. if (strcasecmp(self::GetName($sClass), $sClassLabel) == 0)
  299. {
  300. return $sClass;
  301. }
  302. }
  303. }
  304. return null;
  305. }
  306. final static public function GetCategory($sClass)
  307. {
  308. self::_check_subclass($sClass);
  309. return self::$m_aClassParams[$sClass]["category"];
  310. }
  311. final static public function HasCategory($sClass, $sCategory)
  312. {
  313. self::_check_subclass($sClass);
  314. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  315. }
  316. final static public function GetClassDescription($sClass)
  317. {
  318. self::_check_subclass($sClass);
  319. $sStringCode = 'Class:'.$sClass.'+';
  320. return Dict::S($sStringCode, '');
  321. }
  322. final static public function GetClassDescription_Obsolete($sClass)
  323. {
  324. // Written for compatibility with a data model written prior to version 0.9.1
  325. self::_check_subclass($sClass);
  326. if (array_key_exists('description', self::$m_aClassParams[$sClass]))
  327. {
  328. return self::$m_aClassParams[$sClass]['description'];
  329. }
  330. else
  331. {
  332. return self::GetClassDescription($sClass);
  333. }
  334. }
  335. final static public function GetClassIcon($sClass, $bImgTag = true, $sMoreStyles = '')
  336. {
  337. self::_check_subclass($sClass);
  338. $sIcon = '';
  339. if (array_key_exists('icon', self::$m_aClassParams[$sClass]))
  340. {
  341. $sIcon = self::$m_aClassParams[$sClass]['icon'];
  342. }
  343. if (strlen($sIcon) == 0)
  344. {
  345. $sParentClass = self::GetParentPersistentClass($sClass);
  346. if (strlen($sParentClass) > 0)
  347. {
  348. return self::GetClassIcon($sParentClass, $bImgTag, $sMoreStyles);
  349. }
  350. }
  351. $sIcon = str_replace('/modules/', '/env-'.utils::GetCurrentEnvironment().'/', $sIcon); // Support of pre-2.0 modules
  352. if ($bImgTag && ($sIcon != ''))
  353. {
  354. $sIcon = "<img src=\"$sIcon\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  355. }
  356. return $sIcon;
  357. }
  358. final static public function IsAutoIncrementKey($sClass)
  359. {
  360. self::_check_subclass($sClass);
  361. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  362. }
  363. final static public function GetNameSpec($sClass)
  364. {
  365. self::_check_subclass($sClass);
  366. $nameRawSpec = self::$m_aClassParams[$sClass]["name_attcode"];
  367. if (is_array($nameRawSpec))
  368. {
  369. $sFormat = Dict::S("Class:$sClass/Name", '');
  370. if (strlen($sFormat) == 0)
  371. {
  372. // Default to "%1$s %2$s..."
  373. for($i = 1 ; $i <= count($nameRawSpec) ; $i++)
  374. {
  375. if (empty($sFormat))
  376. {
  377. $sFormat .= '%'.$i.'$s';
  378. }
  379. else
  380. {
  381. $sFormat .= ' %'.$i.'$s';
  382. }
  383. }
  384. }
  385. return array($sFormat, $nameRawSpec);
  386. }
  387. elseif (empty($nameRawSpec))
  388. {
  389. //return array($sClass.' %s', array('id'));
  390. return array($sClass, array());
  391. }
  392. else
  393. {
  394. // string -> attcode
  395. return array('%1$s', array($nameRawSpec));
  396. }
  397. }
  398. /**
  399. * Get the friendly name expression for a given class
  400. */
  401. final static public function GetNameExpression($sClass)
  402. {
  403. $aNameSpec = self::GetNameSpec($sClass);
  404. $sFormat = $aNameSpec[0];
  405. $aAttributes = $aNameSpec[1];
  406. $aPieces = preg_split('/%([0-9])\\$s/', $sFormat, -1, PREG_SPLIT_DELIM_CAPTURE);
  407. $aExpressions = array();
  408. foreach($aPieces as $i => $sPiece)
  409. {
  410. if ($i & 1)
  411. {
  412. // $i is ODD - sPiece is a delimiter
  413. //
  414. $iReplacement = (int)$sPiece - 1;
  415. if (isset($aAttributes[$iReplacement]))
  416. {
  417. $sAttCode = $aAttributes[$iReplacement];
  418. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  419. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  420. {
  421. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  422. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sKeyAttCode);
  423. }
  424. else
  425. {
  426. $sClassOfAttribute = self::GetAttributeOrigin($sClass, $sAttCode);
  427. }
  428. $aExpressions[] = new FieldExpression($sAttCode, $sClassOfAttribute);
  429. }
  430. }
  431. else
  432. {
  433. // $i is EVEN - sPiece is a literal
  434. //
  435. if (strlen($sPiece) > 0)
  436. {
  437. $aExpressions[] = new ScalarExpression($sPiece);
  438. }
  439. }
  440. }
  441. $oNameExpr = new CharConcatExpression($aExpressions);
  442. return $oNameExpr;
  443. }
  444. /**
  445. * Get the friendly name for the class and its subclasses (if finalclass = 'subclass' ...)
  446. * Simplifies the final expression by grouping classes having the same name expression
  447. * Used when querying a parent class
  448. */
  449. final static protected function GetExtendedNameExpression($sClass)
  450. {
  451. // 1st step - get all of the required expressions (instantiable classes)
  452. // and group them using their OQL representation
  453. //
  454. $aFNExpressions = array(); // signature => array('expression' => oExp, 'classes' => array of classes)
  455. foreach (self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL) as $sSubClass)
  456. {
  457. if (($sSubClass != $sClass) && self::IsAbstract($sSubClass)) continue;
  458. $oSubClassName = self::GetNameExpression($sSubClass);
  459. $sSignature = $oSubClassName->Render();
  460. if (!array_key_exists($sSignature, $aFNExpressions))
  461. {
  462. $aFNExpressions[$sSignature] = array(
  463. 'expression' => $oSubClassName,
  464. 'classes' => array(),
  465. );
  466. }
  467. $aFNExpressions[$sSignature]['classes'][] = $sSubClass;
  468. }
  469. // 2nd step - build the final name expression depending on the finalclass
  470. //
  471. if (count($aFNExpressions) == 1)
  472. {
  473. $aExpData = reset($aFNExpressions);
  474. $oNameExpression = $aExpData['expression'];
  475. }
  476. else
  477. {
  478. $oNameExpression = null;
  479. foreach ($aFNExpressions as $sSignature => $aExpData)
  480. {
  481. $oClassListExpr = ListExpression::FromScalars($aExpData['classes']);
  482. $oClassExpr = new FieldExpression('finalclass', $sClass);
  483. $oClassInList = new BinaryExpression($oClassExpr, 'IN', $oClassListExpr);
  484. if (is_null($oNameExpression))
  485. {
  486. $oNameExpression = $aExpData['expression'];
  487. }
  488. else
  489. {
  490. $oNameExpression = new FunctionExpression('IF', array($oClassInList, $aExpData['expression'], $oNameExpression));
  491. }
  492. }
  493. }
  494. return $oNameExpression;
  495. }
  496. final static public function GetStateAttributeCode($sClass)
  497. {
  498. self::_check_subclass($sClass);
  499. return self::$m_aClassParams[$sClass]["state_attcode"];
  500. }
  501. final static public function GetDefaultState($sClass)
  502. {
  503. $sDefaultState = '';
  504. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  505. if (!empty($sStateAttrCode))
  506. {
  507. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  508. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  509. }
  510. return $sDefaultState;
  511. }
  512. final static public function GetReconcKeys($sClass)
  513. {
  514. self::_check_subclass($sClass);
  515. return self::$m_aClassParams[$sClass]["reconc_keys"];
  516. }
  517. final static public function GetDisplayTemplate($sClass)
  518. {
  519. self::_check_subclass($sClass);
  520. return array_key_exists("display_template", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["display_template"]: '';
  521. }
  522. final static public function GetOrderByDefault($sClass, $bOnlyDeclared = false)
  523. {
  524. self::_check_subclass($sClass);
  525. $aOrderBy = array_key_exists("order_by_default", self::$m_aClassParams[$sClass]) ? self::$m_aClassParams[$sClass]["order_by_default"]: array();
  526. if ($bOnlyDeclared)
  527. {
  528. // Used to reverse engineer the declaration of the data model
  529. return $aOrderBy;
  530. }
  531. else
  532. {
  533. if (count($aOrderBy) == 0)
  534. {
  535. $aOrderBy['friendlyname'] = true;
  536. }
  537. return $aOrderBy;
  538. }
  539. }
  540. final static public function GetAttributeOrigin($sClass, $sAttCode)
  541. {
  542. self::_check_subclass($sClass);
  543. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  544. }
  545. final static public function GetPrequisiteAttributes($sClass, $sAttCode)
  546. {
  547. self::_check_subclass($sClass);
  548. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  549. // Temporary implementation: later, we might be able to compute
  550. // the dependencies, based on the attributes definition
  551. // (allowed values and default values)
  552. if ($oAtt->IsWritable())
  553. {
  554. return $oAtt->GetPrerequisiteAttributes();
  555. }
  556. else
  557. {
  558. return array();
  559. }
  560. }
  561. /**
  562. * Find all attributes that depend on the specified one (reverse of GetPrequisiteAttributes)
  563. * @param string $sClass Name of the class
  564. * @param string $sAttCode Code of the attributes
  565. * @return Array List of attribute codes that depend on the given attribute, empty array if none.
  566. */
  567. final static public function GetDependentAttributes($sClass, $sAttCode)
  568. {
  569. $aResults = array();
  570. self::_check_subclass($sClass);
  571. foreach (self::ListAttributeDefs($sClass) as $sDependentAttCode=>$void)
  572. {
  573. $aPrerequisites = self::GetPrequisiteAttributes($sClass, $sDependentAttCode);
  574. if (in_array($sAttCode, $aPrerequisites))
  575. {
  576. $aResults[] = $sDependentAttCode;
  577. }
  578. }
  579. return $aResults;
  580. }
  581. // #@# restore to private ?
  582. final static public function DBGetTable($sClass, $sAttCode = null)
  583. {
  584. self::_check_subclass($sClass);
  585. if (empty($sAttCode) || ($sAttCode == "id"))
  586. {
  587. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  588. if (empty($sTableRaw))
  589. {
  590. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  591. return '';
  592. }
  593. else
  594. {
  595. // If the format changes here, do not forget to update the setup index page (detection of installed modules)
  596. return self::$m_sTablePrefix.$sTableRaw;
  597. }
  598. }
  599. // This attribute has been inherited (compound objects)
  600. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  601. }
  602. final static public function DBGetView($sClass)
  603. {
  604. return self::$m_sTablePrefix."view_".$sClass;
  605. }
  606. final static public function DBEnumTables()
  607. {
  608. // This API does not rely on our capability to query the DB and retrieve
  609. // the list of existing tables
  610. // Rather, it uses the list of expected tables, corresponding to the data model
  611. $aTables = array();
  612. foreach (self::GetClasses() as $sClass)
  613. {
  614. if (!self::HasTable($sClass)) continue;
  615. $sTable = self::DBGetTable($sClass);
  616. // Could be completed later with all the classes that are using a given table
  617. if (!array_key_exists($sTable, $aTables))
  618. {
  619. $aTables[$sTable] = array();
  620. }
  621. $aTables[$sTable][] = $sClass;
  622. }
  623. return $aTables;
  624. }
  625. final static public function DBGetKey($sClass)
  626. {
  627. self::_check_subclass($sClass);
  628. return self::$m_aClassParams[$sClass]["db_key_field"];
  629. }
  630. final static public function DBGetClassField($sClass)
  631. {
  632. self::_check_subclass($sClass);
  633. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  634. }
  635. final static public function IsStandaloneClass($sClass)
  636. {
  637. self::_check_subclass($sClass);
  638. if (count(self::$m_aChildClasses[$sClass]) == 0)
  639. {
  640. if (count(self::$m_aParentClasses[$sClass]) == 0)
  641. {
  642. return true;
  643. }
  644. }
  645. return false;
  646. }
  647. final static public function IsParentClass($sParentClass, $sChildClass)
  648. {
  649. self::_check_subclass($sChildClass);
  650. self::_check_subclass($sParentClass);
  651. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  652. if ($sChildClass == $sParentClass) return true;
  653. return false;
  654. }
  655. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  656. {
  657. self::_check_subclass($sClassA);
  658. self::_check_subclass($sClassB);
  659. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  660. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  661. if ($sClassA == $sClassB) return true;
  662. return false;
  663. }
  664. final static public function IsSameFamily($sClassA, $sClassB)
  665. {
  666. self::_check_subclass($sClassA);
  667. self::_check_subclass($sClassB);
  668. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  669. }
  670. // Attributes of a given class may contain attributes defined in a parent class
  671. // - Some attributes are a copy of the definition
  672. // - Some attributes correspond to the upper class table definition (compound objects)
  673. // (see also filters definition)
  674. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  675. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  676. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  677. private static $m_aIgnoredAttributes = array(); //array of ("classname" => array of ("attcode")
  678. final static public function ListAttributeDefs($sClass)
  679. {
  680. self::_check_subclass($sClass);
  681. return self::$m_aAttribDefs[$sClass];
  682. }
  683. final public static function GetAttributesList($sClass)
  684. {
  685. self::_check_subclass($sClass);
  686. return array_keys(self::$m_aAttribDefs[$sClass]);
  687. }
  688. final public static function GetFiltersList($sClass)
  689. {
  690. self::_check_subclass($sClass);
  691. return array_keys(self::$m_aFilterDefs[$sClass]);
  692. }
  693. final public static function GetKeysList($sClass)
  694. {
  695. self::_check_subclass($sClass);
  696. $aExtKeys = array();
  697. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  698. {
  699. if ($oAttDef->IsExternalKey())
  700. {
  701. $aExtKeys[] = $sAttCode;
  702. }
  703. }
  704. return $aExtKeys;
  705. }
  706. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  707. {
  708. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  709. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  710. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  711. }
  712. final static public function IsValidAttCode($sClass, $sAttCode, $bExtended = false)
  713. {
  714. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  715. if ($bExtended)
  716. {
  717. if (($iPos = strpos($sAttCode, '->')) === false)
  718. {
  719. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  720. }
  721. else
  722. {
  723. $sExtKeyAttCode = substr($sAttCode, 0, $iPos);
  724. $sRemoteAttCode = substr($sAttCode, $iPos + 2);
  725. if (MetaModel::IsValidAttCode($sClass, $sExtKeyAttCode))
  726. {
  727. $oKeyAttDef = MetaModel::GetAttributeDef($sClass, $sExtKeyAttCode);
  728. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  729. $bRes = MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode, true);
  730. }
  731. else
  732. {
  733. $bRes = false;
  734. }
  735. }
  736. }
  737. else
  738. {
  739. $bRes = array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]);
  740. }
  741. return $bRes;
  742. }
  743. final static public function IsAttributeOrigin($sClass, $sAttCode)
  744. {
  745. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  746. }
  747. final static public function IsValidFilterCode($sClass, $sFilterCode)
  748. {
  749. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  750. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  751. }
  752. public static function IsValidClass($sClass)
  753. {
  754. return (array_key_exists($sClass, self::$m_aAttribDefs));
  755. }
  756. public static function IsValidObject($oObject)
  757. {
  758. if (!is_object($oObject)) return false;
  759. return (self::IsValidClass(get_class($oObject)));
  760. }
  761. public static function IsReconcKey($sClass, $sAttCode)
  762. {
  763. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  764. }
  765. final static public function GetAttributeDef($sClass, $sAttCode)
  766. {
  767. self::_check_subclass($sClass);
  768. return self::$m_aAttribDefs[$sClass][$sAttCode];
  769. }
  770. final static public function GetExternalKeys($sClass)
  771. {
  772. $aExtKeys = array();
  773. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  774. {
  775. if ($oAtt->IsExternalKey())
  776. {
  777. $aExtKeys[$sAttCode] = $oAtt;
  778. }
  779. }
  780. return $aExtKeys;
  781. }
  782. final static public function GetLinkedSets($sClass)
  783. {
  784. $aLinkedSets = array();
  785. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  786. {
  787. if (is_subclass_of($oAtt, 'AttributeLinkedSet'))
  788. {
  789. $aLinkedSets[$sAttCode] = $oAtt;
  790. }
  791. }
  792. return $aLinkedSets;
  793. }
  794. final static public function GetExternalFields($sClass, $sKeyAttCode)
  795. {
  796. $aExtFields = array();
  797. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  798. {
  799. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  800. {
  801. $aExtFields[] = $oAtt;
  802. }
  803. }
  804. return $aExtFields;
  805. }
  806. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  807. {
  808. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  809. {
  810. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  811. }
  812. else
  813. {
  814. return array();
  815. }
  816. }
  817. protected static $m_aTrackForwardCache = array();
  818. /**
  819. * List external keys for which there is a LinkSet (direct or indirect) on the other end
  820. * For those external keys, a change will have a special meaning on the other end
  821. * in term of change tracking
  822. */
  823. final static public function GetTrackForwardExternalKeys($sClass)
  824. {
  825. if (!isset(self::$m_aTrackForwardCache[$sClass]))
  826. {
  827. $aRes = array();
  828. foreach (MetaModel::GetExternalKeys($sClass) as $sAttCode => $oAttDef)
  829. {
  830. $sRemoteClass = $oAttDef->GetTargetClass();
  831. foreach (MetaModel::ListAttributeDefs($sRemoteClass) as $sRemoteAttCode => $oRemoteAttDef)
  832. {
  833. if (!$oRemoteAttDef->IsLinkSet()) continue;
  834. if (!is_subclass_of($sClass, $oRemoteAttDef->GetLinkedClass()) && $oRemoteAttDef->GetLinkedClass() != $sClass) continue;
  835. if ($oRemoteAttDef->GetExtKeyToMe() != $sAttCode) continue;
  836. $aRes[$sAttCode] = $oRemoteAttDef;
  837. }
  838. }
  839. self::$m_aTrackForwardCache[$sClass] = $aRes;
  840. }
  841. return self::$m_aTrackForwardCache[$sClass];
  842. }
  843. /**
  844. * Get the attribute label
  845. * @param string sClass Persistent class
  846. * @param string sAttCodeEx Extended attribute code: attcode[->attcode]
  847. * @return string A user friendly format of the string: AttributeName or AttributeName->ExtAttributeName
  848. */
  849. public static function GetLabel($sClass, $sAttCodeEx)
  850. {
  851. $sLabel = '';
  852. if (preg_match('/(.+)->(.+)/', $sAttCodeEx, $aMatches) > 0)
  853. {
  854. $sAttribute = $aMatches[1];
  855. $sField = $aMatches[2];
  856. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttribute);
  857. if ($oAttDef->IsExternalKey())
  858. {
  859. $sTargetClass = $oAttDef->GetTargetClass();
  860. $oTargetAttDef = MetaModel::GetAttributeDef($sTargetClass, $sField);
  861. $sLabel = $oAttDef->GetLabel().'->'.$oTargetAttDef->GetLabel();
  862. }
  863. else
  864. {
  865. // Let's return something displayable... but this should never happen!
  866. $sLabel = $oAttDef->GetLabel().'->'.$aMatches[2];
  867. }
  868. }
  869. else
  870. {
  871. if ($sAttCodeEx == 'id')
  872. {
  873. $sLabel = Dict::S('UI:CSVImport:idField');
  874. }
  875. else
  876. {
  877. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCodeEx);
  878. $sLabel = $oAttDef->GetLabel();
  879. }
  880. }
  881. return $sLabel;
  882. }
  883. public static function GetDescription($sClass, $sAttCode)
  884. {
  885. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  886. if ($oAttDef) return $oAttDef->GetDescription();
  887. return "";
  888. }
  889. // Filters of a given class may contain filters defined in a parent class
  890. // - Some filters are a copy of the definition
  891. // - Some filters correspond to the upper class table definition (compound objects)
  892. // (see also attributes definition)
  893. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  894. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  895. public static function GetClassFilterDefs($sClass)
  896. {
  897. self::_check_subclass($sClass);
  898. return self::$m_aFilterDefs[$sClass];
  899. }
  900. final static public function GetClassFilterDef($sClass, $sFilterCode)
  901. {
  902. self::_check_subclass($sClass);
  903. if (!array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]))
  904. {
  905. throw new CoreException("Unknown filter code '$sFilterCode' for class '$sClass'");
  906. }
  907. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  908. }
  909. public static function GetFilterLabel($sClass, $sFilterCode)
  910. {
  911. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  912. if ($oFilter) return $oFilter->GetLabel();
  913. return "";
  914. }
  915. public static function GetFilterDescription($sClass, $sFilterCode)
  916. {
  917. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  918. if ($oFilter) return $oFilter->GetDescription();
  919. return "";
  920. }
  921. // returns an array of opcode=>oplabel (e.g. "differs from")
  922. public static function GetFilterOperators($sClass, $sFilterCode)
  923. {
  924. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  925. if ($oFilter) return $oFilter->GetOperators();
  926. return array();
  927. }
  928. // returns an opcode
  929. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  930. {
  931. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  932. if ($oFilter) return $oFilter->GetLooseOperator();
  933. return array();
  934. }
  935. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  936. {
  937. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  938. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  939. return "";
  940. }
  941. public static function GetFilterHTMLInput($sFilterCode)
  942. {
  943. return "<INPUT name=\"$sFilterCode\">";
  944. }
  945. // Lists of attributes/search filters
  946. //
  947. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  948. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  949. // list may be an array of attcode / fltcode
  950. // list may be an array of "groupname" => (array of attcode / fltcode)
  951. public static function EnumZLists()
  952. {
  953. return array_keys(self::$m_aListInfos);
  954. }
  955. final static public function GetZListInfo($sListCode)
  956. {
  957. return self::$m_aListInfos[$sListCode];
  958. }
  959. public static function GetZListItems($sClass, $sListCode)
  960. {
  961. if (array_key_exists($sClass, self::$m_aListData))
  962. {
  963. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  964. {
  965. return self::$m_aListData[$sClass][$sListCode];
  966. }
  967. }
  968. $sParentClass = self::GetParentPersistentClass($sClass);
  969. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  970. // Dig recursively
  971. return self::GetZListItems($sParentClass, $sListCode);
  972. }
  973. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  974. {
  975. $aZList = self::FlattenZlist(self::GetZListItems($sClass, $sListCode));
  976. if (!$sGroup)
  977. {
  978. return (in_array($sAttCodeOrFltCode, $aZList));
  979. }
  980. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  981. }
  982. //
  983. // Relations
  984. //
  985. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  986. public static function EnumRelations($sClass = '')
  987. {
  988. $aResult = array_keys(self::$m_aRelationInfos);
  989. if (!empty($sClass))
  990. {
  991. // Return only the relations that have a meaning (i.e. for which at least one query is defined)
  992. // for the specified class
  993. $aClassRelations = array();
  994. foreach($aResult as $sRelCode)
  995. {
  996. $aQueries = self::EnumRelationQueries($sClass, $sRelCode);
  997. if (count($aQueries) > 0)
  998. {
  999. $aClassRelations[] = $sRelCode;
  1000. }
  1001. }
  1002. return $aClassRelations;
  1003. }
  1004. return $aResult;
  1005. }
  1006. public static function EnumRelationProperties($sRelCode)
  1007. {
  1008. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  1009. return self::$m_aRelationInfos[$sRelCode];
  1010. }
  1011. final static public function GetRelationDescription($sRelCode)
  1012. {
  1013. return Dict::S("Relation:$sRelCode/Description");
  1014. }
  1015. final static public function GetRelationVerbUp($sRelCode)
  1016. {
  1017. return Dict::S("Relation:$sRelCode/VerbUp");
  1018. }
  1019. final static public function GetRelationVerbDown($sRelCode)
  1020. {
  1021. return Dict::S("Relation:$sRelCode/VerbDown");
  1022. }
  1023. public static function EnumRelationQueries($sClass, $sRelCode)
  1024. {
  1025. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  1026. return call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  1027. }
  1028. //
  1029. // Object lifecycle model
  1030. //
  1031. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  1032. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  1033. private static $m_aTransitions = array(); // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  1034. public static function EnumStates($sClass)
  1035. {
  1036. if (array_key_exists($sClass, self::$m_aStates))
  1037. {
  1038. return self::$m_aStates[$sClass];
  1039. }
  1040. else
  1041. {
  1042. return array();
  1043. }
  1044. }
  1045. /*
  1046. * Enumerate all possible initial states, including the default one
  1047. */
  1048. public static function EnumInitialStates($sClass)
  1049. {
  1050. if (array_key_exists($sClass, self::$m_aStates))
  1051. {
  1052. $aRet = array();
  1053. // Add the states for which the flag 'is_initial_state' is set to <true>
  1054. foreach(self::$m_aStates[$sClass] as $aStateCode => $aProps)
  1055. {
  1056. if (isset($aProps['initial_state_path']))
  1057. {
  1058. $aRet[$aStateCode] = $aProps['initial_state_path'];
  1059. }
  1060. }
  1061. // Add the default initial state
  1062. $sMainInitialState = self::GetDefaultState($sClass);
  1063. if (!isset($aRet[$sMainInitialState]))
  1064. {
  1065. $aRet[$sMainInitialState] = array();
  1066. }
  1067. return $aRet;
  1068. }
  1069. else
  1070. {
  1071. return array();
  1072. }
  1073. }
  1074. public static function EnumStimuli($sClass)
  1075. {
  1076. if (array_key_exists($sClass, self::$m_aStimuli))
  1077. {
  1078. return self::$m_aStimuli[$sClass];
  1079. }
  1080. else
  1081. {
  1082. return array();
  1083. }
  1084. }
  1085. public static function GetStateLabel($sClass, $sStateValue)
  1086. {
  1087. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1088. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1089. return $oAttDef->GetValueLabel($sStateValue);
  1090. }
  1091. public static function GetStateDescription($sClass, $sStateValue)
  1092. {
  1093. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  1094. $oAttDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  1095. return $oAttDef->GetValueDescription($sStateValue);
  1096. }
  1097. public static function EnumTransitions($sClass, $sStateCode)
  1098. {
  1099. if (array_key_exists($sClass, self::$m_aTransitions))
  1100. {
  1101. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  1102. {
  1103. return self::$m_aTransitions[$sClass][$sStateCode];
  1104. }
  1105. }
  1106. return array();
  1107. }
  1108. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  1109. {
  1110. $iFlags = 0; // By default (if no life cycle) no flag at all
  1111. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1112. if (!empty($sStateAttCode))
  1113. {
  1114. $aStates = MetaModel::EnumStates($sClass);
  1115. if (!array_key_exists($sState, $aStates))
  1116. {
  1117. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  1118. }
  1119. $aCurrentState = $aStates[$sState];
  1120. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  1121. {
  1122. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  1123. }
  1124. }
  1125. return $iFlags;
  1126. }
  1127. /**
  1128. * Combines the flags from the all states that compose the initial_state_path
  1129. */
  1130. public static function GetInitialStateAttributeFlags($sClass, $sState, $sAttCode)
  1131. {
  1132. $iFlags = self::GetAttributeFlags($sClass, $sState, $sAttCode); // Be default set the same flags as the 'target' state
  1133. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1134. if (!empty($sStateAttCode))
  1135. {
  1136. $aStates = MetaModel::EnumInitialStates($sClass);
  1137. if (array_key_exists($sState, $aStates))
  1138. {
  1139. $bReadOnly = (($iFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY);
  1140. $bHidden = (($iFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN);
  1141. foreach($aStates[$sState] as $sPrevState)
  1142. {
  1143. $iPrevFlags = self::GetAttributeFlags($sClass, $sPrevState, $sAttCode);
  1144. if (($iPrevFlags & OPT_ATT_HIDDEN) != OPT_ATT_HIDDEN)
  1145. {
  1146. $bReadOnly = $bReadOnly && (($iPrevFlags & OPT_ATT_READONLY) == OPT_ATT_READONLY); // if it is/was not readonly => then it's not
  1147. }
  1148. $bHidden = $bHidden && (($iPrevFlags & OPT_ATT_HIDDEN) == OPT_ATT_HIDDEN); // if it is/was not hidden => then it's not
  1149. }
  1150. if ($bReadOnly)
  1151. {
  1152. $iFlags = $iFlags | OPT_ATT_READONLY;
  1153. }
  1154. else
  1155. {
  1156. $iFlags = $iFlags & ~OPT_ATT_READONLY;
  1157. }
  1158. if ($bHidden)
  1159. {
  1160. $iFlags = $iFlags | OPT_ATT_HIDDEN;
  1161. }
  1162. else
  1163. {
  1164. $iFlags = $iFlags & ~OPT_ATT_HIDDEN;
  1165. }
  1166. }
  1167. }
  1168. return $iFlags;
  1169. }
  1170. //
  1171. // Allowed values
  1172. //
  1173. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1174. {
  1175. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1176. return $oAttDef->GetAllowedValues($aArgs, $sContains);
  1177. }
  1178. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sContains = '')
  1179. {
  1180. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  1181. return $oFltDef->GetAllowedValues($aArgs, $sContains);
  1182. }
  1183. public static function GetAllowedValuesAsObjectSet($sClass, $sAttCode, $aArgs = array(), $sContains = '')
  1184. {
  1185. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1186. return $oAttDef->GetAllowedValuesAsObjectSet($aArgs, $sContains);
  1187. }
  1188. //
  1189. // Businezz model declaration verbs (should be static)
  1190. //
  1191. public static function RegisterZList($sListCode, $aListInfo)
  1192. {
  1193. // Check mandatory params
  1194. $aMandatParams = array(
  1195. "description" => "detailed (though one line) description of the list",
  1196. "type" => "attributes | filters",
  1197. );
  1198. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1199. {
  1200. if (!array_key_exists($sParamName, $aListInfo))
  1201. {
  1202. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  1203. }
  1204. }
  1205. self::$m_aListInfos[$sListCode] = $aListInfo;
  1206. }
  1207. public static function RegisterRelation($sRelCode)
  1208. {
  1209. // Each item used to be an array of properties...
  1210. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  1211. }
  1212. // Must be called once and only once...
  1213. public static function InitClasses($sTablePrefix)
  1214. {
  1215. if (count(self::GetClasses()) > 0)
  1216. {
  1217. throw new CoreException("InitClasses should not be called more than once -skipped");
  1218. return;
  1219. }
  1220. self::$m_sTablePrefix = $sTablePrefix;
  1221. // Build the list of available extensions
  1222. //
  1223. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension', 'iQueryModifier', 'iOnClassInitialization', 'iPopupMenuExtension', 'iPageUIExtension');
  1224. foreach($aInterfaces as $sInterface)
  1225. {
  1226. self::$m_aExtensionClasses[$sInterface] = array();
  1227. }
  1228. foreach(get_declared_classes() as $sPHPClass)
  1229. {
  1230. $oRefClass = new ReflectionClass($sPHPClass);
  1231. $oExtensionInstance = null;
  1232. foreach($aInterfaces as $sInterface)
  1233. {
  1234. if ($oRefClass->implementsInterface($sInterface))
  1235. {
  1236. if (is_null($oExtensionInstance))
  1237. {
  1238. $oExtensionInstance = new $sPHPClass;
  1239. }
  1240. self::$m_aExtensionClasses[$sInterface][$sPHPClass] = $oExtensionInstance;
  1241. }
  1242. }
  1243. }
  1244. // Initialize the classes (declared attributes, etc.)
  1245. //
  1246. foreach(get_declared_classes() as $sPHPClass)
  1247. {
  1248. if (is_subclass_of($sPHPClass, 'DBObject'))
  1249. {
  1250. $sParent = get_parent_class($sPHPClass);
  1251. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  1252. {
  1253. // Inherit info about attributes to ignore
  1254. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  1255. }
  1256. try
  1257. {
  1258. $oMethod = new ReflectionMethod($sPHPClass, 'Init');
  1259. if ($oMethod->getDeclaringClass()->name == $sPHPClass)
  1260. {
  1261. call_user_func(array($sPHPClass, 'Init'));
  1262. foreach (MetaModel::EnumPlugins('iOnClassInitialization') as $sPluginClass => $oClassInit)
  1263. {
  1264. $oClassInit->OnAfterClassInitialization($sPHPClass);
  1265. }
  1266. }
  1267. }
  1268. catch (ReflectionException $e)
  1269. {
  1270. // This class is only implementing methods, ignore it from the MetaModel perspective
  1271. }
  1272. }
  1273. }
  1274. // Add a 'class' attribute/filter to the root classes and their children
  1275. //
  1276. foreach(self::EnumRootClasses() as $sRootClass)
  1277. {
  1278. if (self::IsStandaloneClass($sRootClass)) continue;
  1279. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  1280. if (strlen($sDbFinalClassField) == 0)
  1281. {
  1282. $sDbFinalClassField = 'finalclass';
  1283. self::$m_aClassParams[$sRootClass]["db_finalclass_field"] = 'finalclass';
  1284. }
  1285. $oClassAtt = new AttributeFinalClass('finalclass', array(
  1286. "sql"=>$sDbFinalClassField,
  1287. "default_value"=>$sRootClass,
  1288. "is_null_allowed"=>false,
  1289. "depends_on"=>array()
  1290. ));
  1291. $oClassAtt->SetHostClass($sRootClass);
  1292. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  1293. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1294. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1295. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  1296. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  1297. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  1298. {
  1299. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  1300. {
  1301. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  1302. }
  1303. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  1304. {
  1305. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  1306. }
  1307. $oCloned = clone $oClassAtt;
  1308. $oCloned->SetFixedValue($sChildClass);
  1309. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  1310. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  1311. $oClassFlt = new FilterFromAttribute($oClassAtt);
  1312. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  1313. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  1314. }
  1315. }
  1316. // Prepare external fields and filters
  1317. // Add final class to external keys
  1318. //
  1319. foreach (self::GetClasses() as $sClass)
  1320. {
  1321. // Create the friendly name attribute
  1322. $sFriendlyNameAttCode = 'friendlyname';
  1323. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, 'id');
  1324. $oFriendlyName->SetHostClass($sClass);
  1325. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1326. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1327. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1328. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1329. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sClass;
  1330. self::$m_aExtKeyFriends[$sClass] = array();
  1331. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  1332. {
  1333. // Compute the filter codes
  1334. //
  1335. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  1336. {
  1337. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  1338. if ($oAttDef->IsExternalField())
  1339. {
  1340. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1341. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1342. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1343. }
  1344. else
  1345. {
  1346. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1347. }
  1348. }
  1349. // Compute the fields that will be used to display a pointer to another object
  1350. //
  1351. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  1352. {
  1353. // oAttDef is either
  1354. // - an external KEY / FIELD (direct),
  1355. // - an external field pointing to an external KEY / FIELD
  1356. // - an external field pointing to an external field pointing to....
  1357. $sRemoteClass = $oAttDef->GetTargetClass();
  1358. if ($oAttDef->IsExternalField())
  1359. {
  1360. // This is a key, but the value comes from elsewhere
  1361. // Create an external field pointing to the remote friendly name attribute
  1362. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1363. $sRemoteAttCode = $oAttDef->GetExtAttCode()."_friendlyname";
  1364. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1365. // propagate "is_null_allowed" ?
  1366. $oFriendlyName = new AttributeExternalField($sFriendlyNameAttCode, array("allowed_values"=>null, "extkey_attcode"=>$sKeyAttCode, "target_attcode"=>$sRemoteAttCode, "depends_on"=>array()));
  1367. $oFriendlyName->SetHostClass($sClass);
  1368. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1369. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1370. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1371. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1372. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1373. }
  1374. else
  1375. {
  1376. // Create the friendly name attribute
  1377. $sFriendlyNameAttCode = $sAttCode.'_friendlyname';
  1378. $oFriendlyName = new AttributeFriendlyName($sFriendlyNameAttCode, $sAttCode);
  1379. $oFriendlyName->SetHostClass($sClass);
  1380. self::$m_aAttribDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyName;
  1381. self::$m_aAttribOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1382. $oFriendlyNameFlt = new FilterFromAttribute($oFriendlyName);
  1383. self::$m_aFilterDefs[$sClass][$sFriendlyNameAttCode] = $oFriendlyNameFlt;
  1384. self::$m_aFilterOrigins[$sClass][$sFriendlyNameAttCode] = $sRemoteClass;
  1385. if (self::HasChildrenClasses($sRemoteClass))
  1386. {
  1387. // First, create an external field attribute, that gets the final class
  1388. $sClassRecallAttCode = $sAttCode.'_finalclass_recall';
  1389. $oClassRecall = new AttributeExternalField($sClassRecallAttCode, array(
  1390. "allowed_values"=>null,
  1391. "extkey_attcode"=>$sAttCode,
  1392. "target_attcode"=>"finalclass",
  1393. "is_null_allowed"=>true,
  1394. "depends_on"=>array()
  1395. ));
  1396. $oClassRecall->SetHostClass($sClass);
  1397. self::$m_aAttribDefs[$sClass][$sClassRecallAttCode] = $oClassRecall;
  1398. self::$m_aAttribOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1399. $oClassFlt = new FilterFromAttribute($oClassRecall);
  1400. self::$m_aFilterDefs[$sClass][$sClassRecallAttCode] = $oClassFlt;
  1401. self::$m_aFilterOrigins[$sClass][$sClassRecallAttCode] = $sRemoteClass;
  1402. // Add it to the ZLists where the external key is present
  1403. //foreach(self::$m_aListData[$sClass] as $sListCode => $aAttributes)
  1404. $sListCode = 'list';
  1405. if (isset(self::$m_aListData[$sClass][$sListCode]))
  1406. {
  1407. $aAttributes = self::$m_aListData[$sClass][$sListCode];
  1408. // temporary.... no loop
  1409. {
  1410. if (in_array($sAttCode, $aAttributes))
  1411. {
  1412. $aNewList = array();
  1413. foreach($aAttributes as $iPos => $sAttToDisplay)
  1414. {
  1415. if (is_string($sAttToDisplay) && ($sAttToDisplay == $sAttCode))
  1416. {
  1417. // Insert the final class right before
  1418. $aNewList[] = $sClassRecallAttCode;
  1419. }
  1420. $aNewList[] = $sAttToDisplay;
  1421. }
  1422. self::$m_aListData[$sClass][$sListCode] = $aNewList;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. // Get the real external key attribute
  1429. // It will be our reference to determine the other ext fields related to the same ext key
  1430. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  1431. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  1432. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  1433. {
  1434. // skip : those extfields will be processed as external keys
  1435. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  1436. // Note: I could not compare the objects by the mean of '==='
  1437. // because they are copied for the inheritance, and the internal references are NOT updated
  1438. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  1439. {
  1440. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  1441. }
  1442. }
  1443. }
  1444. }
  1445. // Add a 'id' filter
  1446. //
  1447. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  1448. {
  1449. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  1450. }
  1451. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  1452. {
  1453. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  1454. }
  1455. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  1456. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  1457. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  1458. // Define defaults values for the standard ZLists
  1459. //
  1460. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  1461. //{
  1462. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  1463. // {
  1464. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  1465. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  1466. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  1467. // }
  1468. //}
  1469. }
  1470. }
  1471. // To be overriden, must be called for any object class (optimization)
  1472. public static function Init()
  1473. {
  1474. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1475. }
  1476. // To be overloaded by biz model declarations
  1477. public static function GetRelationQueries($sRelCode)
  1478. {
  1479. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1480. return array();
  1481. }
  1482. public static function Init_Params($aParams)
  1483. {
  1484. // Check mandatory params
  1485. $aMandatParams = array(
  1486. "category" => "group classes by modules defining their visibility in the UI",
  1487. "key_type" => "autoincrement | string",
  1488. "name_attcode" => "define wich attribute is the class name, may be an array of attributes (format specified in the dictionary as 'Class:myclass/Name' => '%1\$s %2\$s...'",
  1489. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1490. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1491. "db_table" => "database table",
  1492. "db_key_field" => "database field which is the key",
  1493. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1494. );
  1495. $sClass = self::GetCallersPHPClass("Init", self::$m_bTraceSourceFiles);
  1496. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1497. {
  1498. if (!array_key_exists($sParamName, $aParams))
  1499. {
  1500. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1501. }
  1502. }
  1503. $aCategories = explode(',', $aParams['category']);
  1504. foreach ($aCategories as $sCategory)
  1505. {
  1506. self::$m_Category2Class[$sCategory][] = $sClass;
  1507. }
  1508. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1509. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1510. self::$m_aParentClasses[$sClass] = array();
  1511. self::$m_aChildClasses[$sClass] = array();
  1512. self::$m_aClassParams[$sClass]= $aParams;
  1513. self::$m_aAttribDefs[$sClass] = array();
  1514. self::$m_aAttribOrigins[$sClass] = array();
  1515. self::$m_aExtKeyFriends[$sClass] = array();
  1516. self::$m_aFilterDefs[$sClass] = array();
  1517. self::$m_aFilterOrigins[$sClass] = array();
  1518. }
  1519. protected static function object_array_mergeclone($aSource1, $aSource2)
  1520. {
  1521. $aRes = array();
  1522. foreach ($aSource1 as $key=>$object)
  1523. {
  1524. $aRes[$key] = clone $object;
  1525. }
  1526. foreach ($aSource2 as $key=>$object)
  1527. {
  1528. $aRes[$key] = clone $object;
  1529. }
  1530. return $aRes;
  1531. }
  1532. public static function Init_InheritAttributes($sSourceClass = null)
  1533. {
  1534. $sTargetClass = self::GetCallersPHPClass("Init");
  1535. if (empty($sSourceClass))
  1536. {
  1537. // Default: inherit from parent class
  1538. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1539. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1540. }
  1541. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1542. {
  1543. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1544. {
  1545. self::$m_aAttribDefs[$sTargetClass] = array();
  1546. self::$m_aAttribOrigins[$sTargetClass] = array();
  1547. }
  1548. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1549. foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1550. {
  1551. $oAttDef->SetHostClass($sTargetClass);
  1552. }
  1553. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1554. }
  1555. // Build root class information
  1556. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1557. {
  1558. // Inherit...
  1559. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1560. }
  1561. else
  1562. {
  1563. // This class will be the root class
  1564. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1565. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1566. }
  1567. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1568. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1569. // I am the child of each and every parent...
  1570. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1571. {
  1572. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1573. }
  1574. }
  1575. protected static function Init_IsKnownClass($sClass)
  1576. {
  1577. // Differs from self::IsValidClass()
  1578. // because it is being called before all the classes have been initialized
  1579. if (!class_exists($sClass)) return false;
  1580. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1581. return true;
  1582. }
  1583. public static function Init_AddAttribute(AttributeDefinition $oAtt, $sTargetClass = null)
  1584. {
  1585. if (!$sTargetClass)
  1586. {
  1587. $sTargetClass = self::GetCallersPHPClass("Init");
  1588. }
  1589. $sAttCode = $oAtt->GetCode();
  1590. if ($sAttCode == 'finalclass')
  1591. {
  1592. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1593. }
  1594. if ($sAttCode == 'friendlyname')
  1595. {
  1596. throw new Exception("Declaration of $sTargetClass: using the reserved keyword '$sAttCode' in attribute declaration");
  1597. }
  1598. if (array_key_exists($sAttCode, self::$m_aAttribDefs[$sTargetClass]))
  1599. {
  1600. throw new Exception("Declaration of $sTargetClass: attempting to redeclare the inherited attribute '$sAttCode', originaly declared in ".self::$m_aAttribOrigins[$sTargetClass][$sAttCode]);
  1601. }
  1602. // Set the "host class" as soon as possible, since HierarchicalKeys use it for their 'target class' as well
  1603. // and this needs to be know early (for Init_IsKnowClass 19 lines below)
  1604. $oAtt->SetHostClass($sTargetClass);
  1605. // Some attributes could refer to a class
  1606. // declared in a module which is currently not installed/active
  1607. // We simply discard those attributes
  1608. //
  1609. if ($oAtt->IsLinkSet())
  1610. {
  1611. $sRemoteClass = $oAtt->GetLinkedClass();
  1612. if (!self::Init_IsKnownClass($sRemoteClass))
  1613. {
  1614. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1615. return;
  1616. }
  1617. }
  1618. elseif($oAtt->IsExternalKey())
  1619. {
  1620. $sRemoteClass = $oAtt->GetTargetClass();
  1621. if (!self::Init_IsKnownClass($sRemoteClass))
  1622. {
  1623. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1624. return;
  1625. }
  1626. }
  1627. elseif($oAtt->IsExternalField())
  1628. {
  1629. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1630. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1631. {
  1632. // The corresponding external key has already been ignored
  1633. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1634. return;
  1635. }
  1636. // #@# todo - Check if the target attribute is still there
  1637. // this is not simple to implement because is involves
  1638. // several passes (the load order has a significant influence on that)
  1639. }
  1640. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1641. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1642. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1643. }
  1644. public static function Init_SetZListItems($sListCode, $aItems, $sTargetClass = null)
  1645. {
  1646. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1647. if (!$sTargetClass)
  1648. {
  1649. $sTargetClass = self::GetCallersPHPClass("Init");
  1650. }
  1651. // Discard attributes that do not make sense
  1652. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1653. //
  1654. self::Init_CheckZListItems($aItems, $sTargetClass);
  1655. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1656. }
  1657. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  1658. {
  1659. foreach($aItems as $iFoo => $attCode)
  1660. {
  1661. if (is_array($attCode))
  1662. {
  1663. // Note: to make sure that the values will be updated recursively,
  1664. // do not pass $attCode, but $aItems[$iFoo] instead
  1665. self::Init_CheckZListItems($aItems[$iFoo], $sTargetClass);
  1666. if (count($aItems[$iFoo]) == 0)
  1667. {
  1668. unset($aItems[$iFoo]);
  1669. }
  1670. }
  1671. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  1672. {
  1673. unset($aItems[$iFoo]);
  1674. }
  1675. }
  1676. }
  1677. public static function FlattenZList($aList)
  1678. {
  1679. $aResult = array();
  1680. foreach($aList as $value)
  1681. {
  1682. if (!is_array($value))
  1683. {
  1684. $aResult[] = $value;
  1685. }
  1686. else
  1687. {
  1688. $aResult = array_merge($aResult, self::FlattenZList($value));
  1689. }
  1690. }
  1691. return $aResult;
  1692. }
  1693. public static function Init_DefineState($sStateCode, $aStateDef)
  1694. {
  1695. $sTargetClass = self::GetCallersPHPClass("Init");
  1696. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1697. $sParentState = $aStateDef['attribute_inherit'];
  1698. if (!empty($sParentState))
  1699. {
  1700. // Inherit from the given state (must be defined !)
  1701. //
  1702. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1703. // Reset the constraint when it was mandatory to set the value at the previous state
  1704. //
  1705. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  1706. {
  1707. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  1708. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  1709. $aToInherit['attribute_list'][$sState] = $iFlags;
  1710. }
  1711. // The inherited configuration could be overriden
  1712. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  1713. }
  1714. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  1715. {
  1716. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1717. {
  1718. unset($aStateDef['attribute_list'][$sAttCode]);
  1719. }
  1720. }
  1721. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1722. // by default, create an empty set of transitions associated to that state
  1723. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1724. }
  1725. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  1726. {
  1727. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  1728. $sTargetClass = self::GetCallersPHPClass("Init");
  1729. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  1730. }
  1731. public static function Init_DefineStimulus($oStimulus)
  1732. {
  1733. $sTargetClass = self::GetCallersPHPClass("Init");
  1734. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  1735. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1736. // Therefore, the reference to the host class is set there
  1737. $oStimulus->SetHostClass($sTargetClass);
  1738. }
  1739. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1740. {
  1741. $sTargetClass = self::GetCallersPHPClass("Init");
  1742. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1743. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1744. }
  1745. public static function Init_InheritLifecycle($sSourceClass = '')
  1746. {
  1747. $sTargetClass = self::GetCallersPHPClass("Init");
  1748. if (empty($sSourceClass))
  1749. {
  1750. // Default: inherit from parent class
  1751. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1752. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1753. }
  1754. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1755. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  1756. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  1757. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  1758. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  1759. }
  1760. //
  1761. // Static API
  1762. //
  1763. public static function GetRootClass($sClass = null)
  1764. {
  1765. self::_check_subclass($sClass);
  1766. return self::$m_aRootClasses[$sClass];
  1767. }
  1768. public static function IsRootClass($sClass)
  1769. {
  1770. self::_check_subclass($sClass);
  1771. return (self::GetRootClass($sClass) == $sClass);
  1772. }
  1773. public static function GetParentClass($sClass)
  1774. {
  1775. if (count(self::$m_aParentClasses[$sClass]) == 0)
  1776. {
  1777. return null;
  1778. }
  1779. else
  1780. {
  1781. return end(self::$m_aParentClasses[$sClass]);
  1782. }
  1783. }
  1784. /**
  1785. * Tells if a class contains a hierarchical key, and if so what is its AttCode
  1786. * @return mixed String = sAttCode or false if the class is not part of a hierarchy
  1787. */
  1788. public static function IsHierarchicalClass($sClass)
  1789. {
  1790. $sHierarchicalKeyCode = false;
  1791. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  1792. {
  1793. if ($oAtt->IsHierarchicalKey())
  1794. {
  1795. $sHierarchicalKeyCode = $sAttCode; // Found the hierarchical key, no need to continue
  1796. break;
  1797. }
  1798. }
  1799. return $sHierarchicalKeyCode;
  1800. }
  1801. public static function EnumRootClasses()
  1802. {
  1803. return array_unique(self::$m_aRootClasses);
  1804. }
  1805. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1806. {
  1807. self::_check_subclass($sClass);
  1808. if ($iOption == ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1809. {
  1810. return self::$m_aParentClasses[$sClass];
  1811. }
  1812. $aRes = self::$m_aParentClasses[$sClass];
  1813. $aRes[] = $sClass;
  1814. return $aRes;
  1815. }
  1816. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1817. {
  1818. self::_check_subclass($sClass);
  1819. $aRes = self::$m_aChildClasses[$sClass];
  1820. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1821. {
  1822. // Add it to the list
  1823. $aRes[] = $sClass;
  1824. }
  1825. return $aRes;
  1826. }
  1827. public static function HasChildrenClasses($sClass)
  1828. {
  1829. return (count(self::$m_aChildClasses[$sClass]) > 0);
  1830. }
  1831. public static function EnumCategories()
  1832. {
  1833. return array_keys(self::$m_Category2Class);
  1834. }
  1835. // Note: use EnumChildClasses to take the compound objects into account
  1836. public static function GetSubclasses($sClass)
  1837. {
  1838. self::_check_subclass($sClass);
  1839. $aSubClasses = array();
  1840. foreach(self::$m_aClassParams as $sSubClass => $foo)
  1841. {
  1842. if (is_subclass_of($sSubClass, $sClass))
  1843. {
  1844. $aSubClasses[] = $sSubClass;
  1845. }
  1846. }
  1847. return $aSubClasses;
  1848. }
  1849. public static function GetClasses($sCategories = '', $bStrict = false)
  1850. {
  1851. $aCategories = explode(',', $sCategories);
  1852. $aClasses = array();
  1853. foreach($aCategories as $sCategory)
  1854. {
  1855. $sCategory = trim($sCategory);
  1856. if (strlen($sCategory) == 0)
  1857. {
  1858. return array_keys(self::$m_aClassParams);
  1859. }
  1860. if (array_key_exists($sCategory, self::$m_Category2Class))
  1861. {
  1862. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  1863. }
  1864. elseif ($bStrict)
  1865. {
  1866. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1867. }
  1868. }
  1869. return array_unique($aClasses);
  1870. }
  1871. public static function HasTable($sClass)
  1872. {
  1873. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  1874. return true;
  1875. }
  1876. public static function IsAbstract($sClass)
  1877. {
  1878. $oReflection = new ReflectionClass($sClass);
  1879. return $oReflection->isAbstract();
  1880. }
  1881. protected static $m_aQueryStructCache = array();
  1882. public static function PrepareQueryArguments($aArgs)
  1883. {
  1884. // Translate any object into scalars
  1885. //
  1886. $aScalarArgs = array();
  1887. foreach($aArgs as $sArgName => $value)
  1888. {
  1889. if (self::IsValidObject($value))
  1890. {
  1891. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1892. }
  1893. else
  1894. {
  1895. $aScalarArgs[$sArgName] = (string) $value;
  1896. }
  1897. }
  1898. // Add standard contextual arguments
  1899. //
  1900. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1901. return $aScalarArgs;
  1902. }
  1903. public static function MakeGroupByQuery(DBObjectSearch $oFilter, $aArgs, $aGroupByExpr)
  1904. {
  1905. $aAttToLoad = array();
  1906. $oSelect = self::MakeSelectStructure($oFilter, array(), $aArgs, $aAttToLoad, null, 0, 0, false, $aGroupByExpr);
  1907. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1908. try
  1909. {
  1910. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  1911. $sRes = $oSelect->RenderGroupBy($aScalarArgs, $bBeautifulSQL);
  1912. }
  1913. catch (MissingQueryArgument $e)
  1914. {
  1915. // Add some information...
  1916. $e->addInfo('OQL', $oFilter->ToOQL());
  1917. throw $e;
  1918. }
  1919. self::AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sRes);
  1920. return $sRes;
  1921. }
  1922. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aAttToLoad = null, $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  1923. {
  1924. // Check the order by specification, and prefix with the class alias
  1925. // and make sure that the ordering columns are going to be selected
  1926. //
  1927. $sClass = $oFilter->GetClass();
  1928. $sClassAlias = $oFilter->GetClassAlias();
  1929. $aOrderSpec = array();
  1930. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1931. {
  1932. if ($sFieldAlias != 'id')
  1933. {
  1934. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($sClass));
  1935. }
  1936. if (!is_bool($bAscending))
  1937. {
  1938. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1939. }
  1940. if (self::IsValidAttCode($sClass, $sFieldAlias))
  1941. {
  1942. $oAttDef = self::GetAttributeDef($sClass, $sFieldAlias);
  1943. foreach($oAttDef->GetOrderBySQLExpressions($sClassAlias) as $sSQLExpression)
  1944. {
  1945. $aOrderSpec[$sSQLExpression] = $bAscending;
  1946. }
  1947. }
  1948. else
  1949. {
  1950. $aOrderSpec['`'.$sClassAlias.$sFieldAlias.'`'] = $bAscending;
  1951. }
  1952. // Make sure that the columns used for sorting are present in the loaded columns
  1953. if (!is_null($aAttToLoad) && !isset($aAttToLoad[$sClassAlias][$sFieldAlias]))
  1954. {
  1955. $aAttToLoad[$sClassAlias][$sFieldAlias] = MetaModel::GetAttributeDef($sClass, $sFieldAlias);
  1956. }
  1957. }
  1958. $oSelect = self::MakeSelectStructure($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount);
  1959. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1960. try
  1961. {
  1962. $bBeautifulSQL = self::$m_bTraceQueries || self::$m_bDebugQuery || self::$m_bIndentQueries;
  1963. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount, $bBeautifulSQL);
  1964. if ($sClassAlias == '_itop_')
  1965. {
  1966. echo $sRes."<br/>\n";
  1967. }
  1968. }
  1969. catch (MissingQueryArgument $e)
  1970. {
  1971. // Add some information...
  1972. $e->addInfo('OQL', $oFilter->ToOQL());
  1973. throw $e;
  1974. }
  1975. self::AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sRes);
  1976. return $sRes;
  1977. }
  1978. protected static function MakeSelectStructure(DBObjectSearch $oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $aGroupByExpr = null)
  1979. {
  1980. // Hide objects that are not visible to the current user
  1981. //
  1982. if (!$oFilter->IsAllDataAllowed() && !$oFilter->IsDataFiltered())
  1983. {
  1984. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass(), $oFilter->GetModifierProperties('UserRightsGetSelectFilter'));
  1985. if ($oVisibleObjects === false)
  1986. {
  1987. // Make sure this is a valid search object, saying NO for all
  1988. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  1989. }
  1990. if (is_object($oVisibleObjects))
  1991. {
  1992. $oFilter->MergeWith($oVisibleObjects);
  1993. $oFilter->SetDataFiltered();
  1994. }
  1995. else
  1996. {
  1997. // should be true at this point, meaning that no additional filtering
  1998. // is required
  1999. }
  2000. }
  2001. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2002. //
  2003. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2004. // Create a unique cache id
  2005. //
  2006. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  2007. {
  2008. // Need to identify the query
  2009. $sOqlQuery = $oFilter->ToOql();
  2010. if (count($aModifierProperties))
  2011. {
  2012. array_multisort($aModifierProperties);
  2013. $sModifierProperties = json_encode($aModifierProperties);
  2014. }
  2015. else
  2016. {
  2017. $sModifierProperties = '';
  2018. }
  2019. $sRawId = $sOqlQuery.$sModifierProperties;
  2020. if (!is_null($aAttToLoad))
  2021. {
  2022. $sRawId .= json_encode($aAttToLoad);
  2023. }
  2024. if (!is_null($aGroupByExpr))
  2025. {
  2026. foreach($aGroupByExpr as $sAlias => $oExpr)
  2027. {
  2028. $sRawId .= 'g:'.$sAlias.'!'.$oExpr->Render();
  2029. }
  2030. }
  2031. $sRawId .= $bGetCount;
  2032. $sOqlId = md5($sRawId);
  2033. }
  2034. else
  2035. {
  2036. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  2037. $sOqlId = "query id ? n/a";
  2038. }
  2039. // Query caching
  2040. //
  2041. if (self::$m_bQueryCacheEnabled)
  2042. {
  2043. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  2044. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  2045. // to use a hash (like md5) of the string as the key !
  2046. //
  2047. // Example of two queries that were found as similar by the hash array:
  2048. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTO' AND CustomerContract.customer_id = 2
  2049. // and
  2050. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
  2051. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  2052. //
  2053. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  2054. {
  2055. // hit!
  2056. $oSelect = unserialize(serialize(self::$m_aQueryStructCache[$sOqlId]));
  2057. // Note: cloning is not enough because the subtree is made of objects
  2058. }
  2059. elseif (self::$m_bUseAPCCache)
  2060. {
  2061. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  2062. //
  2063. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-query-cache-'.$sOqlId;
  2064. $oKPI = new ExecutionKPI();
  2065. $result = apc_fetch($sOqlAPCCacheId);
  2066. $oKPI->ComputeStats('Query APC (fetch)', $sOqlQuery);
  2067. if (is_object($result))
  2068. {
  2069. $oSelect = $result;
  2070. self::$m_aQueryStructCache[$sOqlId] = $oSelect;
  2071. }
  2072. }
  2073. }
  2074. if (!isset($oSelect))
  2075. {
  2076. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties, $aGroupByExpr);
  2077. $oKPI = new ExecutionKPI();
  2078. $oSelect = self::MakeQuery($oBuild, $oFilter, $aAttToLoad, array(), true /* main query */);
  2079. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2080. $oSelect->SetSourceOQL($sOqlQuery);
  2081. if ($aGroupByExpr)
  2082. {
  2083. $aCols = $oBuild->m_oQBExpressions->GetGroupBy();
  2084. $oSelect->SetGroupBy($aCols);
  2085. $oSelect->SetSelect($aCols);
  2086. }
  2087. else
  2088. {
  2089. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2090. }
  2091. if (self::$m_bOptimizeQueries)
  2092. {
  2093. if ($bGetCount)
  2094. {
  2095. // Simplify the query if just getting the count
  2096. $oSelect->SetSelect(array());
  2097. }
  2098. $oBuild->m_oQBExpressions->GetMandatoryTables($aMandatoryTables);
  2099. $oSelect->OptimizeJoins($aMandatoryTables);
  2100. }
  2101. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  2102. if (self::$m_bQueryCacheEnabled)
  2103. {
  2104. if (self::$m_bUseAPCCache)
  2105. {
  2106. $oKPI = new ExecutionKPI();
  2107. apc_store($sOqlAPCCacheId, $oSelect, self::$m_iQueryCacheTTL);
  2108. $oKPI->ComputeStats('Query APC (store)', $sOqlQuery);
  2109. }
  2110. self::$m_aQueryStructCache[$sOqlId] = $oSelect->DeepClone();
  2111. }
  2112. }
  2113. // Join to an additional table, if required...
  2114. //
  2115. if ($aExtendedDataSpec != null)
  2116. {
  2117. $sTableAlias = '_extended_data_';
  2118. $aExtendedFields = array();
  2119. foreach($aExtendedDataSpec['fields'] as $sColumn)
  2120. {
  2121. $sColRef = $oFilter->GetClassAlias().'_extdata_'.$sColumn;
  2122. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);
  2123. }
  2124. $oSelectExt = new SQLQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  2125. $oSelect->AddInnerJoin($oSelectExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  2126. }
  2127. return $oSelect;
  2128. }
  2129. protected static function AddQueryTraceSelect($oFilter, $aOrderBy, $aArgs, $aAttToLoad, $aExtendedDataSpec, $iLimitCount, $iLimitStart, $bGetCount, $sSql)
  2130. {
  2131. if (self::$m_bTraceQueries)
  2132. {
  2133. $aQueryData = array(
  2134. 'type' => 'select',
  2135. 'filter' => $oFilter,
  2136. 'order_by' => $aOrderBy,
  2137. 'args' => $aArgs,
  2138. 'att_to_load' => $aAttToLoad,
  2139. 'extended_data_spec' => $aExtendedDataSpec,
  2140. 'limit_count' => $iLimitCount,
  2141. 'limit_start' => $iLimitStart,
  2142. 'is_count' => $bGetCount
  2143. );
  2144. $sOql = $oFilter->ToOQL(true, $aArgs);
  2145. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2146. }
  2147. }
  2148. protected static function AddQueryTraceGroupBy($oFilter, $aArgs, $aGroupByExpr, $sSql)
  2149. {
  2150. if (self::$m_bTraceQueries)
  2151. {
  2152. $aQueryData = array(
  2153. 'type' => 'group_by',
  2154. 'filter' => $oFilter,
  2155. 'args' => $aArgs,
  2156. 'group_by_expr' => $aGroupByExpr
  2157. );
  2158. $sOql = $oFilter->ToOQL(true, $aArgs);
  2159. self::AddQueryTrace($aQueryData, $sOql, $sSql);
  2160. }
  2161. }
  2162. protected static function AddQueryTrace($aQueryData, $sOql, $sSql)
  2163. {
  2164. if (self::$m_bTraceQueries)
  2165. {
  2166. $sQueryId = md5(serialize($aQueryData));
  2167. $sMySQLQueryId = md5($sSql);
  2168. if(!isset(self::$m_aQueriesLog[$sQueryId]))
  2169. {
  2170. self::$m_aQueriesLog[$sQueryId]['data'] = serialize($aQueryData);
  2171. self::$m_aQueriesLog[$sQueryId]['oql'] = $sOql;
  2172. self::$m_aQueriesLog[$sQueryId]['hits'] = 1;
  2173. }
  2174. else
  2175. {
  2176. self::$m_aQueriesLog[$sQueryId]['hits']++;
  2177. }
  2178. if(!isset(self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]))
  2179. {
  2180. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['sql'] = $sSql;
  2181. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count'] = 1;
  2182. $iTableCount = count(CMDBSource::ExplainQuery($sSql));
  2183. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['table_count'] = $iTableCount;
  2184. }
  2185. else
  2186. {
  2187. self::$m_aQueriesLog[$sQueryId]['queries'][$sMySQLQueryId]['count']++;
  2188. }
  2189. }
  2190. }
  2191. public static function RecordQueryTrace()
  2192. {
  2193. if (!self::$m_bTraceQueries) return;
  2194. $iOqlCount = count(self::$m_aQueriesLog);
  2195. $iSqlCount = 0;
  2196. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2197. {
  2198. $iSqlCount += $aOqlData['hits'];
  2199. }
  2200. $sHtml = "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  2201. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2202. {
  2203. $sOql = $aOqlData['oql'];
  2204. $sHits = $aOqlData['hits'];
  2205. $sHtml .= "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  2206. $sHtml .= "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  2207. foreach($aOqlData['queries'] as $aSqlData)
  2208. {
  2209. $sQuery = $aSqlData['sql'];
  2210. $sSqlHits = $aSqlData['count'];
  2211. $iTableCount = $aSqlData['table_count'];
  2212. $sHtml .= "<li><b>$sSqlHits</b> hits for SQL ($iTableCount tables): <pre style=\"font-size:60%\">$sQuery</pre></li>\n";
  2213. }
  2214. $sHtml .= "</ul>\n";
  2215. }
  2216. $sLogFile = 'queries.latest';
  2217. file_put_contents(APPROOT.'data/'.$sLogFile.'.html', $sHtml);
  2218. $sLog = "<?php\n\$aQueriesLog = ".var_export(self::$m_aQueriesLog, true).";";
  2219. file_put_contents(APPROOT.'data/'.$sLogFile.'.log', $sLog);
  2220. // Cumulate the queries
  2221. $sAllQueries = APPROOT.'data/queries.log';
  2222. if (file_exists($sAllQueries))
  2223. {
  2224. // Merge the new queries into the existing log
  2225. include($sAllQueries);
  2226. foreach (self::$m_aQueriesLog as $sQueryId => $aOqlData)
  2227. {
  2228. if (!array_key_exists($sQueryId, $aQueriesLog))
  2229. {
  2230. $aQueriesLog[$sQueryId] = $aOqlData;
  2231. }
  2232. }
  2233. }
  2234. else
  2235. {
  2236. $aQueriesLog = self::$m_aQueriesLog;
  2237. }
  2238. $sLog = "<?php\n\$aQueriesLog = ".var_export($aQueriesLog, true).";";
  2239. file_put_contents($sAllQueries, $sLog);
  2240. }
  2241. protected static function MakeModifierProperties($oFilter)
  2242. {
  2243. // Compute query modifiers properties (can be set in the search itself, by the context, etc.)
  2244. //
  2245. $aModifierProperties = array();
  2246. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2247. {
  2248. // Lowest precedence: the application context
  2249. $aPluginProps = ApplicationContext::GetPluginProperties($sPluginClass);
  2250. // Highest precedence: programmatically specified (or OQL)
  2251. foreach($oFilter->GetModifierProperties($sPluginClass) as $sProp => $value)
  2252. {
  2253. $aPluginProps[$sProp] = $value;
  2254. }
  2255. if (count($aPluginProps) > 0)
  2256. {
  2257. $aModifierProperties[$sPluginClass] = $aPluginProps;
  2258. }
  2259. }
  2260. return $aModifierProperties;
  2261. }
  2262. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  2263. {
  2264. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2265. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2266. $oSelect = self::MakeQuery($oBuild, $oFilter, null, array(), true /* main query */);
  2267. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2268. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2269. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2270. return $oSelect->RenderDelete($aScalarArgs);
  2271. }
  2272. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  2273. {
  2274. // $aValues is an array of $sAttCode => $value
  2275. $aModifierProperties = self::MakeModifierProperties($oFilter);
  2276. $oBuild = new QueryBuilderContext($oFilter, $aModifierProperties);
  2277. $oSelect = self::MakeQuery($oBuild, $oFilter, null, $aValues, true /* main query */);
  2278. $oSelect->SetCondition($oBuild->m_oQBExpressions->GetCondition());
  2279. $oSelect->SetSelect($oBuild->m_oQBExpressions->GetSelect());
  2280. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  2281. return $oSelect->RenderUpdate($aScalarArgs);
  2282. }
  2283. private static function MakeQuery(&$oBuild, DBObjectSearch $oFilter, $aAttToLoad = null, $aValues = array(), $bIsMainQueryUNUSED = false)
  2284. {
  2285. // Note: query class might be different than the class of the filter
  2286. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  2287. $sClass = $oFilter->GetFirstJoinedClass();
  2288. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  2289. $bIsOnQueriedClass = array_key_exists($sClassAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  2290. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  2291. $sRootClass = self::GetRootClass($sClass);
  2292. $sKeyField = self::DBGetKey($sClass);
  2293. if ($bIsOnQueriedClass)
  2294. {
  2295. // default to the whole list of attributes + the very std id/finalclass
  2296. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  2297. if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
  2298. {
  2299. $aAttList = self::ListAttributeDefs($sClass);
  2300. }
  2301. else
  2302. {
  2303. $aAttList = $aAttToLoad[$sClassAlias];
  2304. }
  2305. foreach ($aAttList as $sAttCode => $oAttDef)
  2306. {
  2307. if (!$oAttDef->IsScalar()) continue;
  2308. // keep because it can be used for sorting - if (!$oAttDef->LoadInObject()) continue;
  2309. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2310. {
  2311. $oBuild->m_oQBExpressions->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  2312. }
  2313. }
  2314. // Transform the full text condition into additional condition expression
  2315. $aFullText = $oFilter->GetCriteria_FullText();
  2316. if (count($aFullText) > 0)
  2317. {
  2318. $aFullTextFields = array();
  2319. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2320. {
  2321. if (!$oAttDef->IsScalar()) continue;
  2322. if ($oAttDef->IsExternalKey()) continue;
  2323. $aFullTextFields[] = new FieldExpression($sAttCode, $sClassAlias);
  2324. }
  2325. $oTextFields = new CharConcatWSExpression(' ', $aFullTextFields);
  2326. foreach($aFullText as $sFTNeedle)
  2327. {
  2328. $oNewCond = new BinaryExpression($oTextFields, 'LIKE', new ScalarExpression("%$sFTNeedle%"));
  2329. $oBuild->m_oQBExpressions->AddCondition($oNewCond);
  2330. }
  2331. }
  2332. }
  2333. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2334. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  2335. //echo "<p>".__LINE__.": GetUnresolvedFields($sClassAlias, ...)</p>\n";
  2336. $oBuild->m_oQBExpressions->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  2337. // Compute a clear view of required joins (from the current class)
  2338. // Build the list of external keys:
  2339. // -> ext keys required by an explicit join
  2340. // -> ext keys mentionned in a 'pointing to' condition
  2341. // -> ext keys required for an external field
  2342. // -> ext keys required for a friendly name
  2343. //
  2344. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  2345. //
  2346. // Optimization: could be partially computed once for all (cached) ?
  2347. //
  2348. if ($bIsOnQueriedClass)
  2349. {
  2350. // Get all Ext keys for the queried class (??)
  2351. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  2352. {
  2353. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2354. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2355. }
  2356. }
  2357. // Get all Ext keys used by the filter
  2358. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $aPointingTo)
  2359. {
  2360. if (array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  2361. {
  2362. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2363. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  2364. }
  2365. }
  2366. $aFNJoinAlias = array(); // array of (subclass => alias)
  2367. if (array_key_exists('friendlyname', $aExpectedAtts))
  2368. {
  2369. // To optimize: detect a restriction on child classes in the condition expression
  2370. // e.g. SELECT FunctionalCI WHERE finalclass IN ('Server', 'VirtualMachine')
  2371. $oNameExpression = self::GetExtendedNameExpression($sClass);
  2372. $aNameFields = array();
  2373. $oNameExpression->GetUnresolvedFields('', $aNameFields);
  2374. $aTranslateNameFields = array();
  2375. foreach($aNameFields as $sSubClass => $aFields)
  2376. {
  2377. foreach($aFields as $sAttCode => $oField)
  2378. {
  2379. $oAttDef = self::GetAttributeDef($sSubClass, $sAttCode);
  2380. if ($oAttDef->IsExternalKey())
  2381. {
  2382. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sAttCode];
  2383. $aExtKeys[$sClassOfAttribute][$sAttCode] = array();
  2384. }
  2385. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2386. {
  2387. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2388. $sClassOfAttribute = self::$m_aAttribOrigins[$sSubClass][$sKeyAttCode];
  2389. $aExtKeys[$sClassOfAttribute][$sKeyAttCode][$sAttCode] = $oAttDef;
  2390. }
  2391. else
  2392. {
  2393. $sClassOfAttribute = self::GetAttributeOrigin($sSubClass, $sAttCode);
  2394. }
  2395. if (self::IsParentClass($sClassOfAttribute, $sClass))
  2396. {
  2397. // The attribute is part of the standard query
  2398. //
  2399. $sAliasForAttribute = $sClassAlias;
  2400. }
  2401. else
  2402. {
  2403. // The attribute will be available from an additional outer join
  2404. // For each subclass (table) one single join is enough
  2405. //
  2406. if (!array_key_exists($sClassOfAttribute, $aFNJoinAlias))
  2407. {
  2408. $sAliasForAttribute = $oBuild->GenerateClassAlias($sClassAlias.'_fn_'.$sClassOfAttribute, $sClassOfAttribute);
  2409. $aFNJoinAlias[$sClassOfAttribute] = $sAliasForAttribute;
  2410. }
  2411. else
  2412. {
  2413. $sAliasForAttribute = $aFNJoinAlias[$sClassOfAttribute];
  2414. }
  2415. }
  2416. $aTranslateNameFields[$sSubClass][$sAttCode] = new FieldExpression($sAttCode, $sAliasForAttribute);
  2417. }
  2418. }
  2419. $oNameExpression = $oNameExpression->Translate($aTranslateNameFields, false);
  2420. $aTranslateNow = array();
  2421. $aTranslateNow[$sClassAlias]['friendlyname'] = $oNameExpression;
  2422. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  2423. }
  2424. // Add the ext fields used in the select (eventually adds an external key)
  2425. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2426. {
  2427. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  2428. {
  2429. if (array_key_exists($sAttCode, $aExpectedAtts))
  2430. {
  2431. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2432. if ($sKeyAttCode != 'id')
  2433. {
  2434. // Add the external attribute
  2435. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  2436. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  2437. }
  2438. }
  2439. }
  2440. }
  2441. // First query built upon on the leaf (ie current) class
  2442. //
  2443. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  2444. if (self::HasTable($sClass))
  2445. {
  2446. $oSelectBase = self::MakeQuerySingleTable($oBuild, $oFilter, $sClass, $aExtKeys, $aValues);
  2447. }
  2448. else
  2449. {
  2450. $oSelectBase = null;
  2451. // As the join will not filter on the expected classes, we have to specify it explicitely
  2452. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  2453. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  2454. $oBuild->m_oQBExpressions->AddCondition($oFinalClassRestriction);
  2455. }
  2456. // Then we join the queries of the eventual parent classes (compound model)
  2457. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  2458. {
  2459. if (!self::HasTable($sParentClass)) continue;
  2460. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  2461. $oSelectParentTable = self::MakeQuerySingleTable($oBuild, $oFilter, $sParentClass, $aExtKeys, $aValues);
  2462. if (is_null($oSelectBase))
  2463. {
  2464. $oSelectBase = $oSelectParentTable;
  2465. }
  2466. else
  2467. {
  2468. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  2469. }
  2470. }
  2471. // Filter on objects referencing me
  2472. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  2473. {
  2474. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  2475. {
  2476. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  2477. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  2478. //self::DbgTrace($oForeignFilter);
  2479. //self::DbgTrace($oForeignFilter->ToOQL());
  2480. //self::DbgTrace($oSelectForeign);
  2481. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  2482. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  2483. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  2484. $oSelectForeign = self::MakeQuery($oBuild, $oForeignFilter, $aAttToLoad);
  2485. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2486. $sForeignKeyTable = $oJoinExpr->GetParent();
  2487. $sForeignKeyColumn = $oJoinExpr->GetName();
  2488. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  2489. }
  2490. }
  2491. // Filter on related objects
  2492. //
  2493. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  2494. {
  2495. $oSubFilter = $aCritInfo['flt'];
  2496. $sRelCode = $aCritInfo['relcode'];
  2497. $iMaxDepth = $aCritInfo['maxdepth'];
  2498. // Get the starting point objects
  2499. $oStartSet = new CMDBObjectSet($oSubFilter);
  2500. // Get the objects related to those objects... recursively...
  2501. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  2502. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  2503. // #@# todo - related objects and expressions...
  2504. // Create condition
  2505. if (count($aRestriction) > 0)
  2506. {
  2507. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  2508. }
  2509. else
  2510. {
  2511. // Quick N'dirty -> generate an empty set
  2512. $oSelectBase->AddCondition('false');
  2513. }
  2514. }
  2515. // Additional JOINS for Friendly names
  2516. //
  2517. foreach ($aFNJoinAlias as $sSubClass => $sSubClassAlias)
  2518. {
  2519. $oSubClassFilter = new DBObjectSearch($sSubClass, $sSubClassAlias);
  2520. $oSelectFN = self::MakeQuerySingleTable($oBuild, $oSubClassFilter, $sSubClass, $aExtKeys, array());
  2521. $oSelectBase->AddLeftJoin($oSelectFN, $sKeyField, self::DBGetKey($sSubClass));
  2522. }
  2523. // That's all... cross fingers and we'll get some working query
  2524. //MyHelpers::var_dump_html($oSelectBase, true);
  2525. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  2526. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  2527. return $oSelectBase;
  2528. }
  2529. protected static function MakeQuerySingleTable(&$oBuild, $oFilter, $sTableClass, $aExtKeys, $aValues)
  2530. {
  2531. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  2532. //echo "MAKEQUERY($sTableClass)-liste des clefs externes($sTableClass): <pre>".print_r($aExtKeys, true)."</pre><br/>\n";
  2533. // Prepare the query for a single table (compound objects)
  2534. // Ignores the items (attributes/filters) that are not on the target table
  2535. // Perform an (inner or left) join for every external key (and specify the expected fields)
  2536. //
  2537. // Returns an SQLQuery
  2538. //
  2539. $sTargetClass = $oFilter->GetFirstJoinedClass();
  2540. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  2541. $sTable = self::DBGetTable($sTableClass);
  2542. $sTableAlias = $oBuild->GenerateTableAlias($sTargetAlias.'_'.$sTable, $sTable);
  2543. $aTranslation = array();
  2544. $aExpectedAtts = array();
  2545. $oBuild->m_oQBExpressions->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  2546. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $oBuild->GetRootFilter()->GetSelectedClasses());
  2547. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  2548. // 1 - SELECT and UPDATE
  2549. //
  2550. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  2551. //
  2552. $aUpdateValues = array();
  2553. // 1/a - Get the key and friendly name
  2554. //
  2555. // We need one pkey to be the key, let's take the first one available
  2556. $oSelectedIdField = null;
  2557. $oIdField = new FieldExpressionResolved(self::DBGetKey($sTableClass), $sTableAlias);
  2558. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  2559. if ($bIsOnQueriedClass)
  2560. {
  2561. // Add this field to the list of queried fields (required for the COUNT to work fine)
  2562. $oSelectedIdField = $oIdField;
  2563. }
  2564. // 1/b - Get the other attributes
  2565. //
  2566. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  2567. {
  2568. // Skip this attribute if not defined in this table
  2569. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  2570. // Skip this attribute if not made of SQL columns
  2571. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  2572. // Update...
  2573. //
  2574. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  2575. {
  2576. assert ($oAttDef->IsDirectField());
  2577. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  2578. {
  2579. $aUpdateValues[$sColumn] = $sValue;
  2580. }
  2581. }
  2582. }
  2583. // 2 - The SQL query, for this table only
  2584. //
  2585. $oSelectBase = new SQLQuery($sTable, $sTableAlias, array(), $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  2586. // 3 - Resolve expected expressions (translation table: alias.attcode => table.column)
  2587. //
  2588. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  2589. {
  2590. // Skip this attribute if not defined in this table
  2591. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  2592. // Select...
  2593. //
  2594. if ($oAttDef->IsExternalField())
  2595. {
  2596. // skip, this will be handled in the joined tables (done hereabove)
  2597. }
  2598. else
  2599. {
  2600. //echo "<p>MakeQuerySingleTable: Field $sAttCode is part of the table $sTable (named: $sTableAlias)</p>";
  2601. // standard field, or external key
  2602. // add it to the output
  2603. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2604. {
  2605. if (array_key_exists($sAttCode.$sColId, $aExpectedAtts))
  2606. {
  2607. $oFieldSQLExp = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  2608. foreach (MetaModel::EnumPlugins('iQueryModifier') as $sPluginClass => $oQueryModifier)
  2609. {
  2610. $oFieldSQLExp = $oQueryModifier->GetFieldExpression($oBuild, $sTargetClass, $sAttCode, $sColId, $oFieldSQLExp, $oSelectBase);
  2611. }
  2612. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = $oFieldSQLExp;
  2613. }
  2614. }
  2615. }
  2616. }
  2617. //echo "MAKEQUERY- Classe $sTableClass<br/>\n";
  2618. // 4 - The external keys -> joins...
  2619. //
  2620. $aAllPointingTo = $oFilter->GetCriteria_PointingTo();
  2621. if (array_key_exists($sTableClass, $aExtKeys))
  2622. {
  2623. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  2624. {
  2625. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  2626. $aPointingTo = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  2627. //echo "MAKEQUERY-Cle '$sKeyAttCode'<br/>\n";
  2628. if (!array_key_exists(TREE_OPERATOR_EQUALS, $aPointingTo))
  2629. {
  2630. //echo "MAKEQUERY-Ajoutons l'operateur TREE_OPERATOR_EQUALS pour $sKeyAttCode<br/>\n";
  2631. // The join was not explicitely defined in the filter,
  2632. // we need to do it now
  2633. $sKeyClass = $oKeyAttDef->GetTargetClass();
  2634. $sKeyClassAlias = $oBuild->GenerateClassAlias($sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  2635. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  2636. $aAllPointingTo[$sKeyAttCode][TREE_OPERATOR_EQUALS][$sKeyClassAlias] = $oExtFilter;
  2637. }
  2638. }
  2639. }
  2640. //echo "MAKEQUERY-liste des clefs de jointure: <pre>".print_r(array_keys($aAllPointingTo), true)."</pre><br/>\n";
  2641. foreach ($aAllPointingTo as $sKeyAttCode => $aPointingTo)
  2642. {
  2643. foreach($aPointingTo as $iOperatorCode => $aFilter)
  2644. {
  2645. foreach($aFilter as $oExtFilter)
  2646. {
  2647. if (!MetaModel::IsValidAttCode($sTableClass, $sKeyAttCode)) continue; // Not defined in the class, skip it
  2648. // The aliases should not conflict because normalization occured while building the filter
  2649. $oKeyAttDef = self::GetAttributeDef($sTableClass, $sKeyAttCode);
  2650. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  2651. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  2652. //echo "MAKEQUERY-$sTableClass::$sKeyAttCode Foreach PointingTo($iOperatorCode) <span style=\"color:red\">$sKeyClass (alias:$sKeyClassAlias)</span><br/>\n";
  2653. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  2654. //echo "MAKEQUERY-array_key_exists($sTableClass, \$aExtKeys)<br/>\n";
  2655. if ($iOperatorCode == TREE_OPERATOR_EQUALS)
  2656. {
  2657. if (array_key_exists($sTableClass, $aExtKeys) && array_key_exists($sKeyAttCode, $aExtKeys[$sTableClass]))
  2658. {
  2659. // Specify expected attributes for the target class query
  2660. // ... and use the current alias !
  2661. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  2662. foreach($aExtKeys[$sTableClass][$sKeyAttCode] as $sAttCode => $oAtt)
  2663. {
  2664. //echo "MAKEQUERY aExtKeys[$sTableClass][$sKeyAttCode] => $sAttCode-oAtt: <pre>".print_r($oAtt, true)."</pre><br/>\n";
  2665. if ($oAtt instanceof AttributeFriendlyName)
  2666. {
  2667. // Note: for a given ext key, there is one single attribute "friendly name"
  2668. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  2669. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);</b></p>\n";
  2670. }
  2671. else
  2672. {
  2673. $sExtAttCode = $oAtt->GetExtAttCode();
  2674. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  2675. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  2676. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  2677. {
  2678. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  2679. //echo "<p><b>aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);</b></p>\n";
  2680. }
  2681. //echo "<p><b>ExtAttr2: $sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</b></p>\n";
  2682. }
  2683. }
  2684. // Translate prior to recursing
  2685. //
  2686. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."\n".print_r($aTranslateNow, true)."</pre></p>\n";
  2687. $oBuild->m_oQBExpressions->Translate($aTranslateNow, false);
  2688. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2689. //echo "<p>External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()/p>\n";
  2690. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  2691. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  2692. //echo "<p>Recursive MakeQuery ".__LINE__.": <pre>\n".print_r($oBuild->GetRootFilter()->GetSelectedClasses(), true)."</pre></p>\n";
  2693. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  2694. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2695. $sExternalKeyTable = $oJoinExpr->GetParent();
  2696. $sExternalKeyField = $oJoinExpr->GetName();
  2697. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2698. $sLocalKeyField = current($aCols); // get the first column for an external key
  2699. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  2700. if ($oKeyAttDef->IsNullAllowed())
  2701. {
  2702. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  2703. }
  2704. else
  2705. {
  2706. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  2707. }
  2708. }
  2709. }
  2710. elseif(self::$m_aAttribOrigins[$sKeyClass][$sKeyAttCode] == $sTableClass)
  2711. {
  2712. $oBuild->m_oQBExpressions->PushJoinField(new FieldExpression($sKeyAttCode, $sKeyClassAlias));
  2713. $oSelectExtKey = self::MakeQuery($oBuild, $oExtFilter);
  2714. $oJoinExpr = $oBuild->m_oQBExpressions->PopJoinField();
  2715. //echo "MAKEQUERY-PopJoinField pour $sKeyAttCode, $sKeyClassAlias: <pre>".print_r($oJoinExpr, true)."</pre><br/>\n";
  2716. $sExternalKeyTable = $oJoinExpr->GetParent();
  2717. $sExternalKeyField = $oJoinExpr->GetName();
  2718. $sLeftIndex = $sExternalKeyField.'_left'; // TODO use GetSQLLeft()
  2719. $sRightIndex = $sExternalKeyField.'_right'; // TODO use GetSQLRight()
  2720. $LocalKeyLeft = $oKeyAttDef->GetSQLLeft();
  2721. $LocalKeyRight = $oKeyAttDef->GetSQLRight();
  2722. //echo "MAKEQUERY-LocalKeyLeft pour $sKeyAttCode => $LocalKeyLeft<br/>\n";
  2723. $oSelectBase->AddInnerJoinTree($oSelectExtKey, $LocalKeyLeft, $LocalKeyRight, $sLeftIndex, $sRightIndex, $sExternalKeyTable, $iOperatorCode);
  2724. }
  2725. }
  2726. }
  2727. }
  2728. // Translate the selected columns
  2729. //
  2730. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2731. $oBuild->m_oQBExpressions->Translate($aTranslation, false);
  2732. //echo "<p>oQBExpr ".__LINE__.": <pre>\n".print_r($oBuild->m_oQBExpressions, true)."</pre></p>\n";
  2733. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  2734. return $oSelectBase;
  2735. }
  2736. /**
  2737. * Special processing for the hierarchical keys stored as nested sets
  2738. * @param $iId integer The identifier of the parent
  2739. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2740. * @param $stable string The name of the database table containing the hierarchical key
  2741. */
  2742. public static function HKInsertChildUnder($iId, $oAttDef, $sTable)
  2743. {
  2744. // Get the parent id.right value
  2745. if ($iId == 0)
  2746. {
  2747. // No parent, insert completely at the right of the tree
  2748. $sSQL = "SELECT max(`".$oAttDef->GetSQLRight()."`) AS max FROM `$sTable`";
  2749. $aRes = CMDBSource::QueryToArray($sSQL);
  2750. if (count($aRes) == 0)
  2751. {
  2752. $iMyRight = 1;
  2753. }
  2754. else
  2755. {
  2756. $iMyRight = $aRes[0]['max']+1;
  2757. }
  2758. }
  2759. else
  2760. {
  2761. $sSQL = "SELECT `".$oAttDef->GetSQLRight()."` FROM `$sTable` WHERE id=".$iId;
  2762. $iMyRight = CMDBSource::QueryToScalar($sSQL);
  2763. $sSQLUpdateRight = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + 2 WHERE `".$oAttDef->GetSQLRight()."` >= $iMyRight";
  2764. CMDBSource::Query($sSQLUpdateRight);
  2765. $sSQLUpdateLeft = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + 2 WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2766. CMDBSource::Query($sSQLUpdateLeft);
  2767. }
  2768. return array($oAttDef->GetSQLRight() => $iMyRight+1, $oAttDef->GetSQLLeft() => $iMyRight);
  2769. }
  2770. /**
  2771. * Special processing for the hierarchical keys stored as nested sets: temporary remove the branch
  2772. * @param $iId integer The identifier of the parent
  2773. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2774. * @param $sTable string The name of the database table containing the hierarchical key
  2775. */
  2776. public static function HKTemporaryCutBranch($iMyLeft, $iMyRight, $oAttDef, $sTable)
  2777. {
  2778. $iDelta = $iMyRight - $iMyLeft + 1;
  2779. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iMyLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iMyLeft - `".$oAttDef->GetSQLLeft();
  2780. $sSQL .= "` WHERE `".$oAttDef->GetSQLLeft()."`> $iMyLeft AND `".$oAttDef->GetSQLRight()."`< $iMyRight";
  2781. CMDBSource::Query($sSQL);
  2782. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` - $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iMyRight";
  2783. CMDBSource::Query($sSQL);
  2784. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` - $iDelta WHERE `".$oAttDef->GetSQLRight()."` > $iMyRight";
  2785. CMDBSource::Query($sSQL);
  2786. }
  2787. /**
  2788. * Special processing for the hierarchical keys stored as nested sets: replug the temporary removed branch
  2789. * @param $iId integer The identifier of the parent
  2790. * @param $oAttDef AttributeDefinition The attribute corresponding to the hierarchical key
  2791. * @param $sTable string The name of the database table containing the hierarchical key
  2792. */
  2793. public static function HKReplugBranch($iNewLeft, $iNewRight, $oAttDef, $sTable)
  2794. {
  2795. $iDelta = $iNewRight - $iNewLeft + 1;
  2796. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLLeft()."` = `".$oAttDef->GetSQLLeft()."` + $iDelta WHERE `".$oAttDef->GetSQLLeft()."` > $iNewLeft";
  2797. CMDBSource::Query($sSQL);
  2798. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = `".$oAttDef->GetSQLRight()."` + $iDelta WHERE `".$oAttDef->GetSQLRight()."` >= $iNewLeft";
  2799. CMDBSource::Query($sSQL);
  2800. $sSQL = "UPDATE `$sTable` SET `".$oAttDef->GetSQLRight()."` = $iNewLeft - `".$oAttDef->GetSQLRight()."`, `".$oAttDef->GetSQLLeft()."` = $iNewLeft - `".$oAttDef->GetSQLLeft()."` WHERE `".$oAttDef->GetSQLRight()."`< 0";
  2801. CMDBSource::Query($sSQL);
  2802. }
  2803. /**
  2804. * Check (and updates if needed) the hierarchical keys
  2805. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2806. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2807. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2808. */
  2809. public static function CheckHKeys($bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2810. {
  2811. $bChangeNeeded = false;
  2812. foreach (self::GetClasses() as $sClass)
  2813. {
  2814. if (!self::HasTable($sClass)) continue;
  2815. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2816. {
  2817. // Check (once) all the attributes that are hierarchical keys
  2818. if((self::GetAttributeOrigin($sClass, $sAttCode) == $sClass) && $oAttDef->IsHierarchicalKey())
  2819. {
  2820. if ($bVerbose)
  2821. {
  2822. echo "The attribute $sAttCode from $sClass is a hierarchical key.\n";
  2823. }
  2824. $bResult = self::HKInit($sClass, $sAttCode, $bDiagnosticsOnly, $bVerbose, $bForceComputation);
  2825. $bChangeNeeded |= $bResult;
  2826. if ($bVerbose && !$bResult)
  2827. {
  2828. echo "Ok, the attribute $sAttCode from class $sClass seems up to date.\n";
  2829. }
  2830. }
  2831. }
  2832. }
  2833. return $bChangeNeeded;
  2834. }
  2835. /**
  2836. * Initializes (i.e converts) a hierarchy stored using a 'parent_id' external key
  2837. * into a hierarchy stored with a HierarchicalKey, by initializing the _left and _right values
  2838. * to correspond to the existing hierarchy in the database
  2839. * @param $sClass string Name of the class to process
  2840. * @param $sAttCode string Code of the attribute to process
  2841. * @param $bDiagnosticsOnly boolean If true only a diagnostic pass will be run, returning true or false
  2842. * @param $bVerbose boolean Displays some information about what is done/what needs to be done
  2843. * @param $bForceComputation boolean If true, the _left and _right parameters will be recomputed even if some values already exist in the DB
  2844. * @return true if an update is needed (diagnostics only) / was performed
  2845. */
  2846. public static function HKInit($sClass, $sAttCode, $bDiagnosticsOnly = false, $bVerbose = false, $bForceComputation = false)
  2847. {
  2848. $idx = 1;
  2849. $bUpdateNeeded = $bForceComputation;
  2850. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  2851. $sTable = self::DBGetTable($sClass, $sAttCode);
  2852. if ($oAttDef->IsHierarchicalKey())
  2853. {
  2854. // Check if some values already exist in the table for the _right value, if so, do nothing
  2855. $sRight = $oAttDef->GetSQLRight();
  2856. $sSQL = "SELECT MAX(`$sRight`) AS MaxRight FROM `$sTable`";
  2857. $iMaxRight = CMDBSource::QueryToScalar($sSQL);
  2858. $sSQL = "SELECT COUNT(*) AS Count FROM `$sTable`"; // Note: COUNT(field) returns zero if the given field contains only NULLs
  2859. $iCount = CMDBSource::QueryToScalar($sSQL);
  2860. if (!$bForceComputation && ($iCount != 0) && ($iMaxRight == 0))
  2861. {
  2862. $bUpdateNeeded = true;
  2863. if ($bVerbose)
  2864. {
  2865. echo "The table '$sTable' must be updated to compute the fields $sRight and ".$oAttDef->GetSQLLeft()."\n";
  2866. }
  2867. }
  2868. if ($bForceComputation && !$bDiagnosticsOnly)
  2869. {
  2870. echo "Rebuilding the fields $sRight and ".$oAttDef->GetSQLLeft()." from table '$sTable'...\n";
  2871. }
  2872. if ($bUpdateNeeded && !$bDiagnosticsOnly)
  2873. {
  2874. try
  2875. {
  2876. CMDBSource::Query('START TRANSACTION');
  2877. self::HKInitChildren($sTable, $sAttCode, $oAttDef, 0, $idx);
  2878. CMDBSource::Query('COMMIT');
  2879. if ($bVerbose)
  2880. {
  2881. echo "Ok, table '$sTable' successfully updated.\n";
  2882. }
  2883. }
  2884. catch(Exception $e)
  2885. {
  2886. CMDBSource::Query('ROLLBACK');
  2887. throw new Exception("An error occured (".$e->getMessage().") while initializing the hierarchy for ($sClass, $sAttCode). The database was not modified.");
  2888. }
  2889. }
  2890. }
  2891. return $bUpdateNeeded;
  2892. }
  2893. /**
  2894. * Recursive helper function called by HKInit
  2895. */
  2896. protected static function HKInitChildren($sTable, $sAttCode, $oAttDef, $iId, &$iCurrIndex)
  2897. {
  2898. $sSQL = "SELECT id FROM `$sTable` WHERE `$sAttCode` = $iId";
  2899. $aRes = CMDBSource::QueryToArray($sSQL);
  2900. $aTree = array();
  2901. $sLeft = $oAttDef->GetSQLLeft();
  2902. $sRight = $oAttDef->GetSQLRight();
  2903. foreach($aRes as $aValues)
  2904. {
  2905. $iChildId = $aValues['id'];
  2906. $iLeft = $iCurrIndex++;
  2907. $aChildren = self::HKInitChildren($sTable, $sAttCode, $oAttDef, $iChildId, $iCurrIndex);
  2908. $iRight = $iCurrIndex++;
  2909. $sSQL = "UPDATE `$sTable` SET `$sLeft` = $iLeft, `$sRight` = $iRight WHERE id= $iChildId";
  2910. CMDBSource::Query($sSQL);
  2911. }
  2912. }
  2913. public static function CheckDataSources($bDiagnostics, $bVerbose)
  2914. {
  2915. $sOQL = 'SELECT SynchroDataSource';
  2916. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  2917. $bFixNeeded = false;
  2918. if ($bVerbose && $oSet->Count() == 0)
  2919. {
  2920. echo "There are no Data Sources in the database.\n";
  2921. }
  2922. while($oSource = $oSet->Fetch())
  2923. {
  2924. if ($bVerbose)
  2925. {
  2926. echo "Checking Data Source '".$oSource->GetName()."'...\n";
  2927. $bFixNeeded = $bFixNeeded | $oSource->CheckDBConsistency($bDiagnostics, $bVerbose);
  2928. }
  2929. }
  2930. if (!$bFixNeeded && $bVerbose)
  2931. {
  2932. echo "Ok.\n";
  2933. }
  2934. return $bFixNeeded;
  2935. }
  2936. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  2937. {
  2938. if (!array_key_exists($sNewName, $aAliases))
  2939. {
  2940. $aAliases[$sNewName] = $sRealName;
  2941. return $sNewName;
  2942. }
  2943. for ($i = 1 ; $i < 100 ; $i++)
  2944. {
  2945. $sAnAlias = $sNewName.$i;
  2946. if (!array_key_exists($sAnAlias, $aAliases))
  2947. {
  2948. // Create that new alias
  2949. $aAliases[$sAnAlias] = $sRealName;
  2950. return $sAnAlias;
  2951. }
  2952. }
  2953. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  2954. }
  2955. public static function CheckDefinitions($bExitOnError = true)
  2956. {
  2957. if (count(self::GetClasses()) == 0)
  2958. {
  2959. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  2960. }
  2961. $aErrors = array();
  2962. $aSugFix = array();
  2963. foreach (self::GetClasses() as $sClass)
  2964. {
  2965. $sTable = self::DBGetTable($sClass);
  2966. $sTableLowercase = strtolower($sTable);
  2967. if ($sTableLowercase != $sTable)
  2968. {
  2969. $aErrors[$sClass][] = "Table name '".$sTable."' has upper case characters. You might encounter issues when moving your installation between Linux and Windows.";
  2970. $aSugFix[$sClass][] = "Use '$sTableLowercase' instead. Step 1: If already installed, then rename manually in the DB: RENAME TABLE `$sTable` TO `{$sTableLowercase}_tempname`, `{$sTableLowercase}_tempname` TO `$sTableLowercase`; Step 2: Rename the table in the datamodel and compile the application. Note: the MySQL statement provided in step 1 has been designed to be compatible with Windows or Linux.";
  2971. }
  2972. $aNameSpec = self::GetNameSpec($sClass);
  2973. foreach($aNameSpec[1] as $i => $sAttCode)
  2974. {
  2975. if(!self::IsValidAttCode($sClass, $sAttCode))
  2976. {
  2977. $aErrors[$sClass][] = "Unkown attribute code '".$sAttCode."' for the name definition";
  2978. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2979. }
  2980. }
  2981. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  2982. {
  2983. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  2984. {
  2985. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  2986. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2987. }
  2988. }
  2989. $bHasWritableAttribute = false;
  2990. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2991. {
  2992. // It makes no sense to check the attributes again and again in the subclasses
  2993. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2994. if ($oAttDef->IsExternalKey())
  2995. {
  2996. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  2997. {
  2998. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  2999. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  3000. }
  3001. }
  3002. elseif ($oAttDef->IsExternalField())
  3003. {
  3004. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  3005. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  3006. {
  3007. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  3008. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  3009. }
  3010. else
  3011. {
  3012. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  3013. $sTargetClass = $oKeyAttDef->GetTargetClass();
  3014. $sExtAttCode = $oAttDef->GetExtAttCode();
  3015. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  3016. {
  3017. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  3018. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  3019. }
  3020. }
  3021. }
  3022. else // standard attributes
  3023. {
  3024. // Check that the default values definition is a valid object!
  3025. $oValSetDef = $oAttDef->GetValuesDef();
  3026. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  3027. {
  3028. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  3029. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  3030. }
  3031. else
  3032. {
  3033. // Default value must be listed in the allowed values (if defined)
  3034. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3035. if (!is_null($aAllowedValues))
  3036. {
  3037. $sDefaultValue = $oAttDef->GetDefaultValue();
  3038. if (is_string($sDefaultValue) && !array_key_exists($sDefaultValue, $aAllowedValues))
  3039. {
  3040. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  3041. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  3042. }
  3043. }
  3044. }
  3045. }
  3046. // Check dependencies
  3047. if ($oAttDef->IsWritable())
  3048. {
  3049. $bHasWritableAttribute = true;
  3050. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  3051. {
  3052. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  3053. {
  3054. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  3055. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  3056. }
  3057. }
  3058. }
  3059. }
  3060. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  3061. {
  3062. if (method_exists($oFilterDef, '__GetRefAttribute'))
  3063. {
  3064. $oAttDef = $oFilterDef->__GetRefAttribute();
  3065. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  3066. {
  3067. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  3068. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3069. }
  3070. }
  3071. }
  3072. // Lifecycle
  3073. //
  3074. $sStateAttCode = self::GetStateAttributeCode($sClass);
  3075. if (strlen($sStateAttCode) > 0)
  3076. {
  3077. // Lifecycle - check that the state attribute does exist as an attribute
  3078. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  3079. {
  3080. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  3081. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3082. }
  3083. else
  3084. {
  3085. // Lifecycle - check that there is a value set constraint on the state attribute
  3086. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  3087. $aStates = array_keys(self::EnumStates($sClass));
  3088. if (is_null($aAllowedValuesRaw))
  3089. {
  3090. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  3091. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  3092. }
  3093. else
  3094. {
  3095. $aAllowedValues = array_keys($aAllowedValuesRaw);
  3096. // Lifecycle - check the the state attribute allowed values are defined states
  3097. foreach($aAllowedValues as $sValue)
  3098. {
  3099. if (!in_array($sValue, $aStates))
  3100. {
  3101. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  3102. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3103. }
  3104. }
  3105. // Lifecycle - check that defined states are allowed values
  3106. foreach($aStates as $sStateValue)
  3107. {
  3108. if (!in_array($sStateValue, $aAllowedValues))
  3109. {
  3110. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  3111. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  3112. }
  3113. }
  3114. }
  3115. // Lifcycle - check that the action handlers are defined
  3116. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  3117. {
  3118. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  3119. {
  3120. foreach ($aTransitionDef['actions'] as $sActionHandler)
  3121. {
  3122. if (!method_exists($sClass, $sActionHandler))
  3123. {
  3124. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  3125. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  3126. }
  3127. }
  3128. }
  3129. }
  3130. }
  3131. }
  3132. if ($bHasWritableAttribute)
  3133. {
  3134. if (!self::HasTable($sClass))
  3135. {
  3136. $aErrors[$sClass][] = "No table has been defined for this class";
  3137. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  3138. }
  3139. }
  3140. // ZList
  3141. //
  3142. foreach(self::EnumZLists() as $sListCode)
  3143. {
  3144. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  3145. {
  3146. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  3147. {
  3148. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  3149. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  3150. }
  3151. }
  3152. }
  3153. // Check unicity of the SQL columns
  3154. //
  3155. if (self::HasTable($sClass))
  3156. {
  3157. $aTableColumns = array(); // array of column => attcode (the column is used by this attribute)
  3158. $aTableColumns[self::DBGetKey($sClass)] = 'id';
  3159. // Check that SQL columns are declared only once
  3160. //
  3161. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3162. {
  3163. // Skip this attribute if not originaly defined in this class
  3164. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3165. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3166. {
  3167. if (array_key_exists($sField, $aTableColumns))
  3168. {
  3169. $aErrors[$sClass][] = "Column '$sField' declared for attribute $sAttCode, but already used for attribute ".$aTableColumns[$sField];
  3170. $aSugFix[$sClass][] = "Please find another name for the SQL column";
  3171. }
  3172. else
  3173. {
  3174. $aTableColumns[$sField] = $sAttCode;
  3175. }
  3176. }
  3177. }
  3178. }
  3179. } // foreach class
  3180. if (count($aErrors) > 0)
  3181. {
  3182. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3183. echo "<h3>Business model inconsistencies have been found</h3>\n";
  3184. // #@# later -> this is the responsibility of the caller to format the output
  3185. foreach ($aErrors as $sClass => $aMessages)
  3186. {
  3187. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  3188. echo "<ul class=\"treeview\">\n";
  3189. $i = 0;
  3190. foreach ($aMessages as $sMsg)
  3191. {
  3192. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  3193. $i++;
  3194. }
  3195. echo "</ul>\n";
  3196. }
  3197. if ($bExitOnError) echo "<p>Aborting...</p>\n";
  3198. echo "</div>\n";
  3199. if ($bExitOnError) exit;
  3200. }
  3201. }
  3202. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  3203. {
  3204. if (empty($sRepairUrl)) return;
  3205. // By design, some queries might be blank, we have to ignore them
  3206. $aCleanFixes = array();
  3207. foreach($aSQLFixes as $sSQLFix)
  3208. {
  3209. if (!empty($sSQLFix))
  3210. {
  3211. $aCleanFixes[] = $sSQLFix;
  3212. }
  3213. }
  3214. if (count($aCleanFixes) == 0) return;
  3215. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  3216. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  3217. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  3218. echo "</form>\n";
  3219. }
  3220. public static function DBExists($bMustBeComplete = true)
  3221. {
  3222. // returns true if at least one table exists
  3223. //
  3224. if (!CMDBSource::IsDB(self::$m_sDBName))
  3225. {
  3226. return false;
  3227. }
  3228. CMDBSource::SelectDB(self::$m_sDBName);
  3229. $aFound = array();
  3230. $aMissing = array();
  3231. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3232. {
  3233. if (CMDBSource::IsTable($sTable))
  3234. {
  3235. $aFound[] = $sTable;
  3236. }
  3237. else
  3238. {
  3239. $aMissing[] = $sTable;
  3240. }
  3241. }
  3242. if (count($aFound) == 0)
  3243. {
  3244. // no expected table has been found
  3245. return false;
  3246. }
  3247. else
  3248. {
  3249. if (count($aMissing) == 0)
  3250. {
  3251. // the database is complete (still, could be some fields missing!)
  3252. return true;
  3253. }
  3254. else
  3255. {
  3256. // not all the tables, could be an older version
  3257. if ($bMustBeComplete)
  3258. {
  3259. return false;
  3260. }
  3261. else
  3262. {
  3263. return true;
  3264. }
  3265. }
  3266. }
  3267. }
  3268. public static function DBDrop()
  3269. {
  3270. $bDropEntireDB = true;
  3271. if (!empty(self::$m_sTablePrefix))
  3272. {
  3273. // Do drop only tables corresponding to the sub-database (table prefix)
  3274. // then possibly drop the DB itself (if no table remain)
  3275. foreach (CMDBSource::EnumTables() as $sTable)
  3276. {
  3277. // perform a case insensitive test because on Windows the table names become lowercase :-(
  3278. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  3279. {
  3280. CMDBSource::DropTable($sTable);
  3281. }
  3282. else
  3283. {
  3284. // There is at least one table which is out of the scope of the current application
  3285. $bDropEntireDB = false;
  3286. }
  3287. }
  3288. }
  3289. if ($bDropEntireDB)
  3290. {
  3291. CMDBSource::DropDB(self::$m_sDBName);
  3292. }
  3293. }
  3294. public static function DBCreate()
  3295. {
  3296. // Note: we have to check if the DB does exist, because we may share the DB
  3297. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  3298. if (!CMDBSource::IsDB(self::$m_sDBName))
  3299. {
  3300. CMDBSource::CreateDB(self::$m_sDBName);
  3301. }
  3302. self::DBCreateTables();
  3303. self::DBCreateViews();
  3304. }
  3305. protected static function DBCreateTables()
  3306. {
  3307. list($aErrors, $aSugFix, $aCondensedQueries) = self::DBCheckFormat();
  3308. //$sSQL = implode('; ', $aCondensedQueries); Does not work - multiple queries not allowed
  3309. foreach($aCondensedQueries as $sQuery)
  3310. {
  3311. CMDBSource::CreateTable($sQuery);
  3312. }
  3313. }
  3314. protected static function DBCreateViews()
  3315. {
  3316. list($aErrors, $aSugFix) = self::DBCheckViews();
  3317. $aSQL = array();
  3318. foreach ($aSugFix as $sClass => $aTarget)
  3319. {
  3320. foreach ($aTarget as $aQueries)
  3321. {
  3322. foreach ($aQueries as $sQuery)
  3323. {
  3324. if (!empty($sQuery))
  3325. {
  3326. //$aSQL[] = $sQuery;
  3327. // forces a refresh of cached information
  3328. CMDBSource::CreateTable($sQuery);
  3329. }
  3330. }
  3331. }
  3332. }
  3333. }
  3334. public static function DBDump()
  3335. {
  3336. $aDataDump = array();
  3337. foreach (self::DBEnumTables() as $sTable => $aClasses)
  3338. {
  3339. $aRows = CMDBSource::DumpTable($sTable);
  3340. $aDataDump[$sTable] = $aRows;
  3341. }
  3342. return $aDataDump;
  3343. }
  3344. /*
  3345. * Determines wether the target DB is frozen or not
  3346. */
  3347. public static function DBIsReadOnly()
  3348. {
  3349. // Improvement: check the mySQL variable -> Read-only
  3350. if (UserRights::IsAdministrator())
  3351. {
  3352. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  3353. }
  3354. else
  3355. {
  3356. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  3357. }
  3358. }
  3359. public static function DBHasAccess($iRequested = ACCESS_FULL)
  3360. {
  3361. $iMode = self::$m_oConfig->Get('access_mode');
  3362. if (($iMode & $iRequested) == 0) return false;
  3363. return true;
  3364. }
  3365. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  3366. {
  3367. $sValue = Dict::S($sKey, 'x-no-nothing');
  3368. if ($sValue == 'x-no-nothing')
  3369. {
  3370. $bNotInDico = true;
  3371. $sValue = $sValueFromOldSystem;
  3372. if (strlen($sValue) == 0)
  3373. {
  3374. $sValue = $sDefaultValue;
  3375. }
  3376. }
  3377. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  3378. }
  3379. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  3380. {
  3381. $sRes = '';
  3382. $sRes .= "// Dictionnay conventions\n";
  3383. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  3384. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  3385. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  3386. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  3387. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  3388. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  3389. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  3390. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  3391. $sRes .= "\n";
  3392. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  3393. // Need to invent the "module", to characterize the origins of a class
  3394. if (strlen($sModules) == 0)
  3395. {
  3396. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  3397. }
  3398. else
  3399. {
  3400. $aModules = explode(', ', $sModules);
  3401. }
  3402. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3403. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  3404. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3405. foreach ($aModules as $sCategory)
  3406. {
  3407. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3408. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  3409. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  3410. $sRes .= "//\n";
  3411. $sRes .= "\n";
  3412. foreach (self::GetClasses($sCategory) as $sClass)
  3413. {
  3414. if (!self::HasTable($sClass)) continue;
  3415. $bNotInDico = false;
  3416. $sClassRes = "//\n";
  3417. $sClassRes .= "// Class: $sClass\n";
  3418. $sClassRes .= "//\n";
  3419. $sClassRes .= "\n";
  3420. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  3421. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  3422. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  3423. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  3424. {
  3425. // Skip this attribute if not originaly defined in this class
  3426. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3427. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  3428. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  3429. if ($oAttDef instanceof AttributeEnum)
  3430. {
  3431. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  3432. {
  3433. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  3434. {
  3435. if (array_key_exists('label', $aStateData))
  3436. {
  3437. $sValue = $aStateData['label'];
  3438. }
  3439. else
  3440. {
  3441. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  3442. }
  3443. if (array_key_exists('description', $aStateData))
  3444. {
  3445. $sValuePlus = $aStateData['description'];
  3446. }
  3447. else
  3448. {
  3449. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  3450. }
  3451. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  3452. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  3453. }
  3454. }
  3455. else
  3456. {
  3457. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  3458. {
  3459. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  3460. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  3461. }
  3462. }
  3463. }
  3464. }
  3465. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  3466. {
  3467. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  3468. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  3469. }
  3470. $sClassRes .= "));\n";
  3471. $sClassRes .= "\n";
  3472. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  3473. {
  3474. $sRes .= $sClassRes;
  3475. }
  3476. }
  3477. }
  3478. return $sRes;
  3479. }
  3480. public static function DBCheckFormat()
  3481. {
  3482. $aErrors = array();
  3483. $aSugFix = array();
  3484. // A new way of representing things to be done - quicker to execute !
  3485. $aCreateTable = array(); // array of <table> => <table options>
  3486. $aCreateTableItems = array(); // array of <table> => array of <create definition>
  3487. $aAlterTableItems = array(); // array of <table> => <alter specification>
  3488. foreach (self::GetClasses() as $sClass)
  3489. {
  3490. if (!self::HasTable($sClass)) continue;
  3491. // Check that the table exists
  3492. //
  3493. $sTable = self::DBGetTable($sClass);
  3494. $sKeyField = self::DBGetKey($sClass);
  3495. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  3496. $sKeyFieldDefinition = "`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  3497. if (!CMDBSource::IsTable($sTable))
  3498. {
  3499. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  3500. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` ($sKeyFieldDefinition) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3501. $aCreateTable[$sTable] = "ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  3502. $aCreateTableItems[$sTable][$sKeyField] = $sKeyFieldDefinition;
  3503. }
  3504. // Check that the key field exists
  3505. //
  3506. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  3507. {
  3508. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  3509. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD $sKeyFieldDefinition";
  3510. if (!array_key_exists($sTable, $aCreateTable))
  3511. {
  3512. $aAlterTableItems[$sTable][$sKeyField] = "ADD $sKeyFieldDefinition";
  3513. }
  3514. }
  3515. else
  3516. {
  3517. // Check the key field properties
  3518. //
  3519. if (!CMDBSource::IsKey($sTable, $sKeyField))
  3520. {
  3521. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  3522. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  3523. if (!array_key_exists($sTable, $aCreateTable))
  3524. {
  3525. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3526. }
  3527. }
  3528. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  3529. {
  3530. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  3531. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` $sKeyFieldDefinition";
  3532. if (!array_key_exists($sTable, $aCreateTable))
  3533. {
  3534. $aAlterTableItems[$sTable][$sKeyField] = "CHANGE `$sKeyField` $sKeyFieldDefinition";
  3535. }
  3536. }
  3537. }
  3538. // Check that any defined field exists
  3539. //
  3540. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  3541. $aTableInfo['Fields'][$sKeyField]['used'] = true;
  3542. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3543. {
  3544. // Skip this attribute if not originaly defined in this class
  3545. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3546. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  3547. {
  3548. // Keep track of columns used by iTop
  3549. $aTableInfo['Fields'][$sField]['used'] = true;
  3550. $bIndexNeeded = $oAttDef->RequiresIndex();
  3551. $sFieldDefinition = "`$sField` ".($oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL");
  3552. if (!CMDBSource::IsField($sTable, $sField))
  3553. {
  3554. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  3555. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD $sFieldDefinition";
  3556. if ($bIndexNeeded)
  3557. {
  3558. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3559. }
  3560. if (array_key_exists($sTable, $aCreateTable))
  3561. {
  3562. $aCreateTableItems[$sTable][$sField] = $sFieldDefinition;
  3563. if ($bIndexNeeded)
  3564. {
  3565. $aCreateTableItems[$sTable][$sField.'_ix'] = "INDEX (`$sField`)";
  3566. }
  3567. }
  3568. else
  3569. {
  3570. $aAlterTableItems[$sTable][$sField] = "ADD $sFieldDefinition";
  3571. if ($bIndexNeeded)
  3572. {
  3573. $aAlterTableItems[$sTable][$sField.'_ix'] = "ADD INDEX (`$sField`)";
  3574. }
  3575. }
  3576. }
  3577. else
  3578. {
  3579. // The field already exists, does it have the relevant properties?
  3580. //
  3581. $bToBeChanged = false;
  3582. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  3583. {
  3584. $bToBeChanged = true;
  3585. if ($oAttDef->IsNullAllowed())
  3586. {
  3587. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  3588. }
  3589. else
  3590. {
  3591. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  3592. }
  3593. }
  3594. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  3595. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  3596. {
  3597. $bToBeChanged = true;
  3598. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  3599. }
  3600. if ($bToBeChanged)
  3601. {
  3602. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3603. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3604. }
  3605. // Create indexes (external keys only... so far)
  3606. //
  3607. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField))
  3608. {
  3609. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  3610. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  3611. $aAlterTableItems[$sTable][$sField.'_ix'] = "ADD INDEX (`$sField`)";
  3612. }
  3613. }
  3614. }
  3615. }
  3616. // Find out unused columns
  3617. //
  3618. foreach($aTableInfo['Fields'] as $sField => $aFieldData)
  3619. {
  3620. if (!isset($aFieldData['used']) || !$aFieldData['used'])
  3621. {
  3622. $aErrors[$sClass]['*'][] = "Column '$sField' in table '$sTable' is not used";
  3623. if (!CMDBSource::IsNullAllowed($sTable, $sField))
  3624. {
  3625. // Allow null values so that new record can be inserted
  3626. // without specifying the value of this unknown column
  3627. $sFieldDefinition = "`$sField` ".CMDBSource::GetFieldType($sTable, $sField).' NULL';
  3628. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` $sFieldDefinition";
  3629. $aAlterTableItems[$sTable][$sField] = "CHANGE `$sField` $sFieldDefinition";
  3630. }
  3631. }
  3632. }
  3633. }
  3634. $aCondensedQueries = array();
  3635. foreach($aCreateTable as $sTable => $sTableOptions)
  3636. {
  3637. $sTableItems = implode(', ', $aCreateTableItems[$sTable]);
  3638. $aCondensedQueries[] = "CREATE TABLE `$sTable` ($sTableItems) $sTableOptions";
  3639. }
  3640. foreach($aAlterTableItems as $sTable => $aChangeList)
  3641. {
  3642. $sChangeList = implode(', ', $aChangeList);
  3643. $aCondensedQueries[] = "ALTER TABLE `$sTable` $sChangeList";
  3644. }
  3645. return array($aErrors, $aSugFix, $aCondensedQueries);
  3646. }
  3647. public static function DBCheckViews()
  3648. {
  3649. $aErrors = array();
  3650. $aSugFix = array();
  3651. // Reporting views (must be created after any other table)
  3652. //
  3653. foreach (self::GetClasses('bizmodel') as $sClass)
  3654. {
  3655. $sView = self::DBGetView($sClass);
  3656. if (CMDBSource::IsTable($sView))
  3657. {
  3658. // Check that the view is complete
  3659. //
  3660. // Note: checking the list of attributes is not enough because the columns can be stable while the SELECT is not stable
  3661. // Example: new way to compute the friendly name
  3662. // The correct comparison algorithm is to compare the queries,
  3663. // by using "SHOW CREATE VIEW" (MySQL 5.0.1 required) or to look into INFORMATION_SCHEMA/views
  3664. // both requiring some privileges
  3665. // Decision: to simplify, let's consider the views as being wrong anytime
  3666. if (true)
  3667. {
  3668. // Rework the view
  3669. //
  3670. $oFilter = new DBObjectSearch($sClass, '');
  3671. $oFilter->AllowAllData();
  3672. $sSQL = self::MakeSelectQuery($oFilter);
  3673. $aErrors[$sClass]['*'][] = "Redeclare view '$sView' (systematic - to support an eventual change in the friendly name computation)";
  3674. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  3675. }
  3676. }
  3677. else
  3678. {
  3679. // Create the view
  3680. //
  3681. $oFilter = new DBObjectSearch($sClass, '');
  3682. $oFilter->AllowAllData();
  3683. $sSQL = self::MakeSelectQuery($oFilter);
  3684. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  3685. $aSugFix[$sClass]['*'][] = "DROP VIEW IF EXISTS `$sView`";
  3686. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  3687. }
  3688. }
  3689. return array($aErrors, $aSugFix);
  3690. }
  3691. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  3692. {
  3693. $sRootClass = self::GetRootClass($sClass);
  3694. $sTable = self::DBGetTable($sClass);
  3695. $sKeyField = self::DBGetKey($sClass);
  3696. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3697. {
  3698. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3699. }
  3700. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3701. if (count($aWrongRecords) == 0) return;
  3702. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3703. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3704. foreach ($aWrongRecords as $iRecordId)
  3705. {
  3706. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3707. {
  3708. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3709. {
  3710. case 'Delete':
  3711. // Already planned for a deletion
  3712. // Let's concatenate the errors description together
  3713. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3714. break;
  3715. case 'Update':
  3716. // Let's plan a deletion
  3717. break;
  3718. }
  3719. }
  3720. else
  3721. {
  3722. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3723. }
  3724. if (!$bProcessingFriends)
  3725. {
  3726. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  3727. {
  3728. // Something new to be deleted...
  3729. $iNewDelCount++;
  3730. }
  3731. }
  3732. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  3733. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  3734. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3735. $aPlannedDel[$sTable][] = $iRecordId;
  3736. }
  3737. // Now make sure that we would delete the records of the other tables for that class
  3738. //
  3739. if (!$bProcessingFriends)
  3740. {
  3741. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  3742. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  3743. {
  3744. $sFriendTable = self::DBGetTable($sFriendClass);
  3745. $sFriendKey = self::DBGetKey($sFriendClass);
  3746. // skip the current table
  3747. if ($sFriendTable == $sTable) continue;
  3748. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  3749. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  3750. }
  3751. }
  3752. }
  3753. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3754. {
  3755. $sRootClass = self::GetRootClass($sClass);
  3756. $sTable = self::DBGetTable($sClass);
  3757. $sKeyField = self::DBGetKey($sClass);
  3758. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  3759. {
  3760. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  3761. }
  3762. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  3763. if (count($aWrongRecords) == 0) return;
  3764. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  3765. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3766. foreach ($aWrongRecords as $iRecordId)
  3767. {
  3768. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  3769. {
  3770. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  3771. {
  3772. case 'Delete':
  3773. // No need to update, the record will be deleted!
  3774. break;
  3775. case 'Update':
  3776. // Already planned for an update
  3777. // Add this new update spec to the list
  3778. $bFoundSameSpec = false;
  3779. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  3780. {
  3781. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  3782. {
  3783. $bFoundSameSpec = true;
  3784. }
  3785. }
  3786. if (!$bFoundSameSpec)
  3787. {
  3788. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3789. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  3790. }
  3791. break;
  3792. }
  3793. }
  3794. else
  3795. {
  3796. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  3797. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  3798. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  3799. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  3800. }
  3801. }
  3802. }
  3803. // returns the count of records found for deletion
  3804. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  3805. {
  3806. foreach (self::GetClasses() as $sClass)
  3807. {
  3808. if (!self::HasTable($sClass)) continue;
  3809. $sRootClass = self::GetRootClass($sClass);
  3810. $sTable = self::DBGetTable($sClass);
  3811. $sKeyField = self::DBGetKey($sClass);
  3812. if (!self::IsStandaloneClass($sClass))
  3813. {
  3814. if (self::IsRootClass($sClass))
  3815. {
  3816. // Check that the final class field contains the name of a class which inherited from the current class
  3817. //
  3818. $sFinalClassField = self::DBGetClassField($sClass);
  3819. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3820. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  3821. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  3822. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3823. }
  3824. else
  3825. {
  3826. $sRootTable = self::DBGetTable($sRootClass);
  3827. $sRootKey = self::DBGetKey($sRootClass);
  3828. $sFinalClassField = self::DBGetClassField($sRootClass);
  3829. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  3830. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  3831. // Check that any record found here has its counterpart in the root table
  3832. // and which refers to a child class
  3833. //
  3834. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` as maintable LEFT JOIN `$sRootTable` ON maintable.`$sKeyField` = `$sRootTable`.`$sRootKey` AND `$sRootTable`.`$sFinalClassField` IN ($sExpectedClasses) WHERE `$sRootTable`.`$sRootKey` IS NULL";
  3835. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in `<em>$sTable</em>`, but no counterpart in root table `<em>$sRootTable</em>` (inc. records pointing to a class in {".$sExpectedClasses."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3836. // Check that any record found in the root table and referring to a child class
  3837. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  3838. //
  3839. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sRootKey` AS id FROM `$sRootTable` AS maintable LEFT JOIN `$sTable` ON maintable.`$sRootKey` = `$sTable`.`$sKeyField` WHERE `$sTable`.`$sKeyField` IS NULL AND maintable.`$sFinalClassField` IN ($sExpectedClasses)";
  3840. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Found a record in root table `<em>$sRootTable</em>`, but no counterpart in table `<em>$sTable</em>` (root records pointing to a class in {".$sExpectedClasses."})", $sRootClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3841. }
  3842. }
  3843. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  3844. {
  3845. // Skip this attribute if not defined in this table
  3846. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  3847. if ($oAttDef->IsExternalKey())
  3848. {
  3849. // Check that any external field is pointing to an existing object
  3850. //
  3851. $sRemoteClass = $oAttDef->GetTargetClass();
  3852. $sRemoteTable = self::DBGetTable($sRemoteClass);
  3853. $sRemoteKey = self::DBGetKey($sRemoteClass);
  3854. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3855. $sExtKeyField = current($aCols); // get the first column for an external key
  3856. // Note: a class/table may have an external key on itself
  3857. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  3858. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  3859. if ($oAttDef->IsNullAllowed())
  3860. {
  3861. // Exclude the records pointing to 0/null from the errors
  3862. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3863. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3864. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3865. }
  3866. else
  3867. {
  3868. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3869. }
  3870. // Do almost the same, taking into account the records planned for deletion
  3871. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  3872. {
  3873. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  3874. // but in that case you won't be able to track the root cause (cascading)
  3875. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  3876. if ($oAttDef->IsNullAllowed())
  3877. {
  3878. // Exclude the records pointing to 0/null from the errors
  3879. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  3880. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  3881. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3882. }
  3883. else
  3884. {
  3885. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3886. }
  3887. }
  3888. }
  3889. else if ($oAttDef->IsDirectField())
  3890. {
  3891. // Check that the values fit the allowed values
  3892. //
  3893. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  3894. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  3895. {
  3896. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  3897. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  3898. $sMyAttributeField = current($aCols); // get the first column for the moment
  3899. $sDefaultValue = $oAttDef->GetDefaultValue();
  3900. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  3901. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3902. }
  3903. }
  3904. }
  3905. }
  3906. }
  3907. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  3908. {
  3909. // Records in error, and action to be taken: delete or update
  3910. // by RootClass/Table/Record
  3911. $aErrorsAndFixes = array();
  3912. // Records to be ignored in the current/next pass
  3913. // by Table = array of RecordId
  3914. $aPlannedDel = array();
  3915. // Count of errors in the next pass: no error means that we can leave...
  3916. $iErrorCount = 0;
  3917. // Limit in case of a bug in the algorythm
  3918. $iLoopCount = 0;
  3919. $iNewDelCount = 1; // startup...
  3920. while ($iNewDelCount > 0)
  3921. {
  3922. $iNewDelCount = 0;
  3923. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3924. $iErrorCount += $iNewDelCount;
  3925. // Safety net #1 - limit the planned deletions
  3926. //
  3927. $iMaxDel = 1000;
  3928. $iPlannedDel = 0;
  3929. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  3930. {
  3931. $iPlannedDel += count($aPlannedDelOnTable);
  3932. }
  3933. if ($iPlannedDel > $iMaxDel)
  3934. {
  3935. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  3936. break;
  3937. }
  3938. // Safety net #2 - limit the iterations
  3939. //
  3940. $iLoopCount++;
  3941. $iMaxLoops = 10;
  3942. if ($iLoopCount > $iMaxLoops)
  3943. {
  3944. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  3945. break;
  3946. }
  3947. }
  3948. // Display the results
  3949. //
  3950. $iIssueCount = 0;
  3951. $aFixesDelete = array();
  3952. $aFixesUpdate = array();
  3953. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  3954. {
  3955. foreach ($aTables as $sTable => $aRecords)
  3956. {
  3957. foreach ($aRecords as $iRecord => $aError)
  3958. {
  3959. $sAction = $aError['Action'];
  3960. $sReason = $aError['Reason'];
  3961. $iPass = $aError['Pass'];
  3962. switch ($sAction)
  3963. {
  3964. case 'Delete':
  3965. $sActionDetails = "";
  3966. $aFixesDelete[$sTable][] = $iRecord;
  3967. break;
  3968. case 'Update':
  3969. $aUpdateDesc = array();
  3970. foreach($aError['Action_Details'] as $aUpdateSpec)
  3971. {
  3972. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  3973. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  3974. }
  3975. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  3976. break;
  3977. default:
  3978. $sActionDetails = "bug: unknown action '$sAction'";
  3979. }
  3980. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  3981. $iIssueCount++;
  3982. }
  3983. }
  3984. }
  3985. if ($iIssueCount > 0)
  3986. {
  3987. // Build the queries to fix in the database
  3988. //
  3989. // First step, be able to get class data out of the table name
  3990. // Could be optimized, because we've made the job earlier... but few benefits, so...
  3991. $aTable2ClassProp = array();
  3992. foreach (self::GetClasses() as $sClass)
  3993. {
  3994. if (!self::HasTable($sClass)) continue;
  3995. $sRootClass = self::GetRootClass($sClass);
  3996. $sTable = self::DBGetTable($sClass);
  3997. $sKeyField = self::DBGetKey($sClass);
  3998. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3999. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  4000. }
  4001. // Second step, build a flat list of SQL queries
  4002. $aSQLFixes = array();
  4003. $iPlannedUpdate = 0;
  4004. foreach ($aFixesUpdate as $sTable => $aColumns)
  4005. {
  4006. foreach ($aColumns as $sColumn => $aNewValues)
  4007. {
  4008. foreach ($aNewValues as $sNewValue => $aRecords)
  4009. {
  4010. $iPlannedUpdate += count($aRecords);
  4011. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4012. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4013. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  4014. }
  4015. }
  4016. }
  4017. $iPlannedDel = 0;
  4018. foreach ($aFixesDelete as $sTable => $aRecords)
  4019. {
  4020. $iPlannedDel += count($aRecords);
  4021. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  4022. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  4023. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  4024. }
  4025. // Report the results
  4026. //
  4027. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  4028. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  4029. // #@# later -> this is the responsibility of the caller to format the output
  4030. echo "<ul class=\"treeview\">\n";
  4031. foreach ($aIssues as $sIssueDesc)
  4032. {
  4033. echo "<li>$sIssueDesc</li>\n";
  4034. }
  4035. echo "</ul>\n";
  4036. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  4037. echo "<p>Aborting...</p>\n";
  4038. echo "</div>\n";
  4039. exit;
  4040. }
  4041. }
  4042. public static function Startup($config, $bModelOnly = false, $bAllowCache = true, $bTraceSourceFiles = false)
  4043. {
  4044. if (!defined('MODULESROOT'))
  4045. {
  4046. define('MODULESROOT', APPROOT.'env-'.utils::GetCurrentEnvironment().'/');
  4047. self::$m_bTraceSourceFiles = $bTraceSourceFiles;
  4048. // $config can be either a filename, or a Configuration object (volatile!)
  4049. if ($config instanceof Config)
  4050. {
  4051. self::LoadConfig($config, $bAllowCache);
  4052. }
  4053. else
  4054. {
  4055. self::LoadConfig(new Config($config), $bAllowCache);
  4056. }
  4057. if ($bModelOnly) return;
  4058. }
  4059. CMDBSource::SelectDB(self::$m_sDBName);
  4060. foreach(get_declared_classes() as $sPHPClass)
  4061. {
  4062. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  4063. {
  4064. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  4065. call_user_func_array($aCallSpec, array());
  4066. }
  4067. }
  4068. if (false)
  4069. {
  4070. echo "Debug<br/>\n";
  4071. self::static_var_dump();
  4072. }
  4073. }
  4074. public static function LoadConfig($oConfiguration, $bAllowCache = false)
  4075. {
  4076. self::$m_oConfig = $oConfiguration;
  4077. // Set log ASAP
  4078. if (self::$m_oConfig->GetLogGlobal())
  4079. {
  4080. if (self::$m_oConfig->GetLogIssue())
  4081. {
  4082. self::$m_bLogIssue = true;
  4083. IssueLog::Enable(APPROOT.'log/error.log');
  4084. }
  4085. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  4086. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  4087. ToolsLog::Enable(APPROOT.'log/tools.log');
  4088. }
  4089. else
  4090. {
  4091. self::$m_bLogIssue = false;
  4092. self::$m_bLogNotification = false;
  4093. self::$m_bLogWebService = false;
  4094. }
  4095. if (self::$m_oConfig->GetLogKPIDuration())
  4096. {
  4097. ExecutionKPI::EnableDuration();
  4098. }
  4099. if (self::$m_oConfig->GetLogKPIMemory())
  4100. {
  4101. ExecutionKPI::EnableMemory();
  4102. }
  4103. self::$m_bTraceQueries = self::$m_oConfig->GetLogQueries();
  4104. self::$m_bIndentQueries = self::$m_oConfig->Get('query_indentation_enabled');
  4105. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  4106. self::$m_bOptimizeQueries = self::$m_oConfig->Get('query_optimization_enabled');
  4107. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  4108. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  4109. self::$m_bUseAPCCache = $bAllowCache
  4110. && self::$m_oConfig->Get('apc_cache.enabled')
  4111. && function_exists('apc_fetch')
  4112. && function_exists('apc_store');
  4113. self::$m_iQueryCacheTTL = self::$m_oConfig->Get('apc_cache.query_ttl');
  4114. // PHP timezone first...
  4115. //
  4116. $sPHPTimezone = self::$m_oConfig->Get('timezone');
  4117. if ($sPHPTimezone == '')
  4118. {
  4119. // Leave as is... up to the admin to set a value somewhere...
  4120. //$sPHPTimezone = date_default_timezone_get();
  4121. }
  4122. else
  4123. {
  4124. date_default_timezone_set($sPHPTimezone);
  4125. }
  4126. // Note: load the dictionary as soon as possible, because it might be
  4127. // needed when some error occur
  4128. $sAppIdentity = 'itop-'.MetaModel::GetEnvironmentId();
  4129. $bDictInitializedFromData = false;
  4130. if (!self::$m_bUseAPCCache || !Dict::InCache($sAppIdentity))
  4131. {
  4132. $bDictInitializedFromData = true;
  4133. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  4134. {
  4135. self::IncludeModule('dictionaries', $sToInclude);
  4136. }
  4137. }
  4138. // Set the language... after the dictionaries have been loaded!
  4139. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  4140. // Romain: this is the only way I've found to cope with the fact that
  4141. // classes have to be derived from cmdbabstract (to be editable in the UI)
  4142. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  4143. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  4144. {
  4145. self::IncludeModule('application', $sToInclude);
  4146. }
  4147. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  4148. {
  4149. self::IncludeModule('business', $sToInclude);
  4150. }
  4151. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  4152. {
  4153. self::IncludeModule('webservice', $sToInclude);
  4154. }
  4155. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  4156. {
  4157. self::IncludeModule('addons', $sToInclude);
  4158. }
  4159. $sServer = self::$m_oConfig->GetDBHost();
  4160. $sUser = self::$m_oConfig->GetDBUser();
  4161. $sPwd = self::$m_oConfig->GetDBPwd();
  4162. $sSource = self::$m_oConfig->GetDBName();
  4163. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  4164. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  4165. $sCollation = self::$m_oConfig->GetDBCollation();
  4166. if (self::$m_bUseAPCCache)
  4167. {
  4168. $oKPI = new ExecutionKPI();
  4169. // Note: For versions of APC older than 3.0.17, fetch() accepts only one parameter
  4170. //
  4171. $sOqlAPCCacheId = 'itop-'.MetaModel::GetEnvironmentId().'-metamodel';
  4172. $result = apc_fetch($sOqlAPCCacheId);
  4173. if (is_array($result))
  4174. {
  4175. // todo - verifier que toutes les classes mentionnees ici sont chargees dans InitClasses()
  4176. self::$m_aExtensionClasses = $result['m_aExtensionClasses'];
  4177. self::$m_Category2Class = $result['m_Category2Class'];
  4178. self::$m_aRootClasses = $result['m_aRootClasses'];
  4179. self::$m_aParentClasses = $result['m_aParentClasses'];
  4180. self::$m_aChildClasses = $result['m_aChildClasses'];
  4181. self::$m_aClassParams = $result['m_aClassParams'];
  4182. self::$m_aAttribDefs = $result['m_aAttribDefs'];
  4183. self::$m_aAttribOrigins = $result['m_aAttribOrigins'];
  4184. self::$m_aExtKeyFriends = $result['m_aExtKeyFriends'];
  4185. self::$m_aIgnoredAttributes = $result['m_aIgnoredAttributes'];
  4186. self::$m_aFilterDefs = $result['m_aFilterDefs'];
  4187. self::$m_aFilterOrigins = $result['m_aFilterOrigins'];
  4188. self::$m_aListInfos = $result['m_aListInfos'];
  4189. self::$m_aListData = $result['m_aListData'];
  4190. self::$m_aRelationInfos = $result['m_aRelationInfos'];
  4191. self::$m_aStates = $result['m_aStates'];
  4192. self::$m_aStimuli = $result['m_aStimuli'];
  4193. self::$m_aTransitions = $result['m_aTransitions'];
  4194. }
  4195. $oKPI->ComputeAndReport('Metamodel APC (fetch + read)');
  4196. }
  4197. if (count(self::$m_aAttribDefs) == 0)
  4198. {
  4199. // The includes have been included, let's browse the existing classes and
  4200. // develop some data based on the proposed model
  4201. $oKPI = new ExecutionKPI();
  4202. self::InitClasses($sTablePrefix);
  4203. $oKPI->ComputeAndReport('Initialization of Data model structures');
  4204. if (self::$m_bUseAPCCache)
  4205. {
  4206. $oKPI = new ExecutionKPI();
  4207. $aCache = array();
  4208. $aCache['m_aExtensionClasses'] = self::$m_aExtensionClasses;
  4209. $aCache['m_Category2Class'] = self::$m_Category2Class;
  4210. $aCache['m_aRootClasses'] = self::$m_aRootClasses; // array of "classname" => "rootclass"
  4211. $aCache['m_aParentClasses'] = self::$m_aParentClasses; // array of ("classname" => array of "parentclass")
  4212. $aCache['m_aChildClasses'] = self::$m_aChildClasses; // array of ("classname" => array of "childclass")
  4213. $aCache['m_aClassParams'] = self::$m_aClassParams; // array of ("classname" => array of class information)
  4214. $aCache['m_aAttribDefs'] = self::$m_aAttribDefs; // array of ("classname" => array of attributes)
  4215. $aCache['m_aAttribOrigins'] = self::$m_aAttribOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4216. $aCache['m_aExtKeyFriends'] = self::$m_aExtKeyFriends; // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  4217. $aCache['m_aIgnoredAttributes'] = self::$m_aIgnoredAttributes; //array of ("classname" => array of ("attcode")
  4218. $aCache['m_aFilterDefs'] = self::$m_aFilterDefs; // array of ("classname" => array filterdef)
  4219. $aCache['m_aFilterOrigins'] = self::$m_aFilterOrigins; // array of ("classname" => array of ("attcode"=>"sourceclass"))
  4220. $aCache['m_aListInfos'] = self::$m_aListInfos; // array of ("listcode" => various info on the list, common to every classes)
  4221. $aCache['m_aListData'] = self::$m_aListData; // array of ("classname" => array of "listcode" => list)
  4222. $aCache['m_aRelationInfos'] = self::$m_aRelationInfos; // array of ("relcode" => various info on the list, common to every classes)
  4223. $aCache['m_aStates'] = self::$m_aStates; // array of ("classname" => array of "statecode"=>array('label'=>..., attribute_inherit=> attribute_list=>...))
  4224. $aCache['m_aStimuli'] = self::$m_aStimuli; // array of ("classname" => array of ("stimuluscode"=>array('label'=>...)))
  4225. $aCache['m_aTransitions'] = self::$m_aTransitions; // array of ("classname" => array of ("statcode_from"=>array of ("stimuluscode" => array('target_state'=>..., 'actions'=>array of handlers procs, 'user_restriction'=>TBD)))
  4226. apc_store($sOqlAPCCacheId, $aCache);
  4227. $oKPI->ComputeAndReport('Metamodel APC (store)');
  4228. }
  4229. }
  4230. if (self::$m_bUseAPCCache && $bDictInitializedFromData)
  4231. {
  4232. Dict::InitCache($sAppIdentity);
  4233. }
  4234. self::$m_sDBName = $sSource;
  4235. self::$m_sTablePrefix = $sTablePrefix;
  4236. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  4237. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  4238. // Later when timezone implementation is correctly done: CMDBSource::SetTimezone($sDBTimezone);
  4239. }
  4240. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  4241. {
  4242. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  4243. }
  4244. public static function GetConfig()
  4245. {
  4246. return self::$m_oConfig;
  4247. }
  4248. public static function GetEnvironmentId()
  4249. {
  4250. return md5(APPROOT).'-'.utils::GetCurrentEnvironment();
  4251. }
  4252. protected static $m_aExtensionClasses = array();
  4253. protected static function IncludeModule($sModuleType, $sToInclude)
  4254. {
  4255. $sFirstChar = substr($sToInclude, 0, 1);
  4256. $sSecondChar = substr($sToInclude, 1, 1);
  4257. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  4258. {
  4259. // It is a relative path, prepend APPROOT
  4260. if (substr($sToInclude, 0, 3) == '../')
  4261. {
  4262. // Preserve compatibility with config files written before 1.0.1
  4263. // Replace '../' by '<root>/'
  4264. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  4265. }
  4266. else
  4267. {
  4268. $sFile = APPROOT.'/'.$sToInclude;
  4269. }
  4270. }
  4271. else
  4272. {
  4273. // Leave as is - should be an absolute path
  4274. $sFile = $sToInclude;
  4275. }
  4276. if (!file_exists($sFile))
  4277. {
  4278. $sConfigFile = self::$m_oConfig->GetLoadedFile();
  4279. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sFile));
  4280. }
  4281. // Note: We do not expect the modules to output characters while loading them.
  4282. // Therefore, and because unexpected characters can corrupt the output,
  4283. // they must be trashed here.
  4284. // Additionnaly, pages aiming at delivering data in their output can call WebPage::TrashUnexpectedOutput()
  4285. // to get rid of chars that could be generated during the execution of the code
  4286. ob_start();
  4287. require_once($sFile);
  4288. $sPreviousContent = ob_get_clean();
  4289. if (self::$m_oConfig->Get('debug_report_spurious_chars'))
  4290. {
  4291. if ($sPreviousContent != '')
  4292. {
  4293. IssueLog::Error("Spurious characters injected by $sModuleType/$sToInclude");
  4294. }
  4295. }
  4296. }
  4297. // Building an object
  4298. //
  4299. //
  4300. private static $aQueryCacheGetObject = array();
  4301. private static $aQueryCacheGetObjectHits = array();
  4302. public static function GetQueryCacheStatus()
  4303. {
  4304. $aRes = array();
  4305. $iTotalHits = 0;
  4306. foreach(self::$aQueryCacheGetObjectHits as $sClassSign => $iHits)
  4307. {
  4308. $aRes[] = "$sClassSign: $iHits";
  4309. $iTotalHits += $iHits;
  4310. }
  4311. return $iTotalHits.' ('.implode(', ', $aRes).')';
  4312. }
  4313. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4314. {
  4315. // Build the query cache signature
  4316. //
  4317. $sQuerySign = $sClass;
  4318. if($bAllowAllData)
  4319. {
  4320. $sQuerySign .= '_all_';
  4321. }
  4322. if (count($aModifierProperties))
  4323. {
  4324. array_multisort($aModifierProperties);
  4325. $sModifierProperties = json_encode($aModifierProperties);
  4326. $sQuerySign .= '_all_'.md5($sModifierProperties);
  4327. }
  4328. if (!array_key_exists($sQuerySign, self::$aQueryCacheGetObject))
  4329. {
  4330. // NOTE: Quick and VERY dirty caching mechanism which relies on
  4331. // the fact that the string '987654321' will never appear in the
  4332. // standard query
  4333. // This could be simplified a little, relying solely on the query cache,
  4334. // but this would slow down -by how much time?- the application
  4335. $oFilter = new DBObjectSearch($sClass);
  4336. $oFilter->AddCondition('id', 987654321, '=');
  4337. if ($aModifierProperties)
  4338. {
  4339. foreach ($aModifierProperties as $sPluginClass => $aProperties)
  4340. {
  4341. foreach ($aProperties as $sProperty => $value)
  4342. {
  4343. $oFilter->SetModifierProperty($sPluginClass, $sProperty, $value);
  4344. }
  4345. }
  4346. }
  4347. if ($bAllowAllData)
  4348. {
  4349. $oFilter->AllowAllData();
  4350. }
  4351. $sSQL = self::MakeSelectQuery($oFilter);
  4352. self::$aQueryCacheGetObject[$sQuerySign] = $sSQL;
  4353. self::$aQueryCacheGetObjectHits[$sQuerySign] = 0;
  4354. }
  4355. else
  4356. {
  4357. $sSQL = self::$aQueryCacheGetObject[$sQuerySign];
  4358. self::$aQueryCacheGetObjectHits[$sQuerySign] += 1;
  4359. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sQuerySign]."<br/>\n";
  4360. }
  4361. $sSQL = str_replace(CMDBSource::Quote(987654321), CMDBSource::Quote($iKey), $sSQL);
  4362. $res = CMDBSource::Query($sSQL);
  4363. $aRow = CMDBSource::FetchArray($res);
  4364. CMDBSource::FreeResult($res);
  4365. if ($bMustBeFound && empty($aRow))
  4366. {
  4367. throw new CoreException("No result for the single row query: '$sSQL'");
  4368. }
  4369. return $aRow;
  4370. }
  4371. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  4372. {
  4373. self::_check_subclass($sClass);
  4374. if (strlen($sClassAlias) == 0)
  4375. {
  4376. $sClassAlias = $sClass;
  4377. }
  4378. // Compound objects: if available, get the final object class
  4379. //
  4380. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  4381. {
  4382. // Either this is a bug (forgot to specify a root class with a finalclass field
  4383. // Or this is the expected behavior, because the object is not made of several tables
  4384. }
  4385. elseif (empty($aRow[$sClassAlias."finalclass"]))
  4386. {
  4387. // The data is missing in the DB
  4388. // @#@ possible improvement: check that the class is valid !
  4389. $sRootClass = self::GetRootClass($sClass);
  4390. $sFinalClassField = self::DBGetClassField($sRootClass);
  4391. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  4392. }
  4393. else
  4394. {
  4395. // do the job for the real target class
  4396. $sClass = $aRow[$sClassAlias."finalclass"];
  4397. }
  4398. return new $sClass($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  4399. }
  4400. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false, $aModifierProperties = null)
  4401. {
  4402. self::_check_subclass($sClass);
  4403. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData, $aModifierProperties);
  4404. if (empty($aRow))
  4405. {
  4406. return null;
  4407. }
  4408. return self::GetObjectByRow($sClass, $aRow);
  4409. }
  4410. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  4411. {
  4412. self::_check_subclass($sClass);
  4413. $oObjSearch = new DBObjectSearch($sClass);
  4414. $oObjSearch->AddNameCondition($sName);
  4415. $oSet = new DBObjectSet($oObjSearch);
  4416. if ($oSet->Count() != 1)
  4417. {
  4418. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  4419. return null;
  4420. }
  4421. $oObj = $oSet->fetch();
  4422. return $oObj;
  4423. }
  4424. static protected $m_aCacheObjectByColumn = array();
  4425. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  4426. {
  4427. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  4428. {
  4429. self::_check_subclass($sClass);
  4430. $oObjSearch = new DBObjectSearch($sClass);
  4431. $oObjSearch->AddCondition($sAttCode, $value, '=');
  4432. $oSet = new DBObjectSet($oObjSearch);
  4433. if ($oSet->Count() == 1)
  4434. {
  4435. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  4436. }
  4437. else
  4438. {
  4439. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  4440. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  4441. }
  4442. }
  4443. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  4444. }
  4445. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  4446. {
  4447. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  4448. if ($bAllowAllData)
  4449. {
  4450. $oFilter->AllowAllData();
  4451. }
  4452. $oSet = new DBObjectSet($oFilter);
  4453. $oObject = $oSet->Fetch();
  4454. return $oObject;
  4455. }
  4456. public static function GetHyperLink($sTargetClass, $iKey)
  4457. {
  4458. if ($iKey < 0)
  4459. {
  4460. return "$sTargetClass: $iKey (invalid value)";
  4461. }
  4462. $oObj = self::GetObject($sTargetClass, $iKey, false);
  4463. if (is_null($oObj))
  4464. {
  4465. // Whatever we are looking for, the root class is the key to search for
  4466. $sRootClass = self::GetRootClass($sTargetClass);
  4467. $oSearch = DBObjectSearch::FromOQL('SELECT CMDBChangeOpDelete WHERE objclass = :objclass AND objkey = :objkey', array('objclass' => $sRootClass, 'objkey' => $iKey));
  4468. $oSet = new DBObjectSet($oSearch);
  4469. $oRecord = $oSet->Fetch();
  4470. // An empty fname is obtained with iTop < 2.0
  4471. if (is_null($oRecord) || (strlen(trim($oRecord->Get('fname'))) == 0))
  4472. {
  4473. $sName = Dict::Format('Core:UnknownObjectLabel', $sTargetClass, $iKey);
  4474. $sTitle = Dict::S('Core:UnknownObjectTip');
  4475. }
  4476. else
  4477. {
  4478. $sName = $oRecord->Get('fname');
  4479. $sTitle = Dict::Format('Core:DeletedObjectTip', $oRecord->Get('date'), $oRecord->Get('userinfo'));
  4480. }
  4481. return '<span class="itop-deleted-object" title="'.htmlentities($sTitle, ENT_QUOTES, 'UTF-8').'">'.htmlentities($sName, ENT_QUOTES, 'UTF-8').'</span>';
  4482. }
  4483. return $oObj->GetHyperLink();
  4484. }
  4485. public static function NewObject($sClass)
  4486. {
  4487. self::_check_subclass($sClass);
  4488. return new $sClass();
  4489. }
  4490. public static function GetNextKey($sClass)
  4491. {
  4492. $sRootClass = MetaModel::GetRootClass($sClass);
  4493. $sRootTable = MetaModel::DBGetTable($sRootClass);
  4494. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  4495. return $iNextKey;
  4496. }
  4497. /**
  4498. * Deletion of records, bypassing DBObject::DBDelete !!!
  4499. * It is NOT recommended to use this shortcut
  4500. * In particular, it will not work
  4501. * - if the class is not a final class
  4502. * - if the class has a hierarchical key (need to rebuild the indexes)
  4503. * - if the class overload DBDelete !
  4504. * Todo: protect it against forbidden usages (in such a case, delete objects one by one)
  4505. */
  4506. public static function BulkDelete(DBObjectSearch $oFilter)
  4507. {
  4508. $sSQL = self::MakeDeleteQuery($oFilter);
  4509. if (!self::DBIsReadOnly())
  4510. {
  4511. CMDBSource::Query($sSQL);
  4512. }
  4513. }
  4514. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  4515. {
  4516. // $aValues is an array of $sAttCode => $value
  4517. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  4518. if (!self::DBIsReadOnly())
  4519. {
  4520. CMDBSource::Query($sSQL);
  4521. }
  4522. }
  4523. // Links
  4524. //
  4525. //
  4526. public static function EnumReferencedClasses($sClass)
  4527. {
  4528. self::_check_subclass($sClass);
  4529. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  4530. $aResult = array();
  4531. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  4532. {
  4533. if ($oAttDef->IsExternalKey())
  4534. {
  4535. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  4536. }
  4537. }
  4538. return $aResult;
  4539. }
  4540. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  4541. {
  4542. self::_check_subclass($sClass);
  4543. if ($bSkipLinkingClasses)
  4544. {
  4545. $aLinksClasses = self::EnumLinksClasses();
  4546. }
  4547. // 1-N links (referencing my class), array of sClass => array of sAttcode
  4548. $aResult = array();
  4549. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4550. {
  4551. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  4552. $aExtKeys = array();
  4553. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4554. {
  4555. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4556. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  4557. {
  4558. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  4559. // Ok, I want this one
  4560. $aExtKeys[$sAttCode] = $oAttDef;
  4561. }
  4562. }
  4563. if (count($aExtKeys) != 0)
  4564. {
  4565. $aResult[$sSomeClass] = $aExtKeys;
  4566. }
  4567. }
  4568. return $aResult;
  4569. }
  4570. public static function EnumLinksClasses()
  4571. {
  4572. // Returns a flat array of classes having at least two external keys
  4573. $aResult = array();
  4574. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  4575. {
  4576. $iExtKeyCount = 0;
  4577. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  4578. {
  4579. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4580. if ($oAttDef->IsExternalKey())
  4581. {
  4582. $iExtKeyCount++;
  4583. }
  4584. }
  4585. if ($iExtKeyCount >= 2)
  4586. {
  4587. $aResult[] = $sSomeClass;
  4588. }
  4589. }
  4590. return $aResult;
  4591. }
  4592. public static function EnumLinkingClasses($sClass = "")
  4593. {
  4594. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  4595. $aResult = array();
  4596. foreach (self::EnumLinksClasses() as $sSomeClass)
  4597. {
  4598. $aTargets = array();
  4599. $bFoundClass = false;
  4600. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  4601. {
  4602. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  4603. if ($oAttDef->IsExternalKey())
  4604. {
  4605. $sRemoteClass = $oAttDef->GetTargetClass();
  4606. if (empty($sClass))
  4607. {
  4608. $aTargets[$sAttCode] = $sRemoteClass;
  4609. }
  4610. elseif ($sClass == $sRemoteClass)
  4611. {
  4612. $bFoundClass = true;
  4613. }
  4614. else
  4615. {
  4616. $aTargets[$sAttCode] = $sRemoteClass;
  4617. }
  4618. }
  4619. }
  4620. if (empty($sClass) || $bFoundClass)
  4621. {
  4622. $aResult[$sSomeClass] = $aTargets;
  4623. }
  4624. }
  4625. return $aResult;
  4626. }
  4627. public static function GetLinkLabel($sLinkClass, $sAttCode)
  4628. {
  4629. self::_check_subclass($sLinkClass);
  4630. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  4631. return self::GetLabel($sLinkClass, $sAttCode);
  4632. }
  4633. /**
  4634. * Replaces all the parameters by the values passed in the hash array
  4635. */
  4636. static public function ApplyParams($aInput, $aParams)
  4637. {
  4638. // Declare magic parameters
  4639. $aParams['APP_URL'] = utils::GetAbsoluteUrlAppRoot();
  4640. $aParams['MODULES_URL'] = utils::GetAbsoluteUrlModulesRoot();
  4641. $aSearches = array();
  4642. $aReplacements = array();
  4643. foreach($aParams as $sSearch => $replace)
  4644. {
  4645. // Some environment parameters are objects, we just need scalars
  4646. if (is_object($replace)) continue;
  4647. $aSearches[] = '$'.$sSearch.'$';
  4648. $aReplacements[] = (string) $replace;
  4649. }
  4650. return str_replace($aSearches, $aReplacements, $aInput);
  4651. }
  4652. /**
  4653. * Returns an array of classes=>instance implementing the given interface
  4654. */
  4655. public static function EnumPlugins($sInterface)
  4656. {
  4657. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4658. {
  4659. return self::$m_aExtensionClasses[$sInterface];
  4660. }
  4661. else
  4662. {
  4663. return array();
  4664. }
  4665. }
  4666. /**
  4667. * Returns the instance of the specified plug-ins for the given interface
  4668. */
  4669. public static function GetPlugins($sInterface, $sClassName)
  4670. {
  4671. $oInstance = null;
  4672. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  4673. {
  4674. if (array_key_exists($sClassName, self::$m_aExtensionClasses[$sInterface]))
  4675. {
  4676. return self::$m_aExtensionClasses[$sInterface][$sClassName];
  4677. }
  4678. }
  4679. return $oInstance;
  4680. }
  4681. public static function GetCacheEntries($sEnvironment = null)
  4682. {
  4683. if (!function_exists('apc_cache_info')) return array();
  4684. if (is_null($sEnvironment))
  4685. {
  4686. $sEnvironment = MetaModel::GetEnvironmentId();
  4687. }
  4688. $aEntries = array();
  4689. $aCacheUserData = @apc_cache_info('user');
  4690. if (is_array($aCacheUserData))
  4691. {
  4692. $sPrefix = 'itop-'.$sEnvironment.'-';
  4693. foreach($aCacheUserData['cache_list'] as $i => $aEntry)
  4694. {
  4695. $sEntryKey = $aEntry['info'];
  4696. if (strpos($sEntryKey, $sPrefix) === 0)
  4697. {
  4698. $sCleanKey = substr($sEntryKey, strlen($sPrefix));
  4699. $aEntries[$sCleanKey] = $aEntry;
  4700. }
  4701. }
  4702. }
  4703. return $aEntries;
  4704. }
  4705. public static function ResetCache($sEnvironmentId = null)
  4706. {
  4707. if (!function_exists('apc_delete')) return;
  4708. if (is_null($sEnvironmentId))
  4709. {
  4710. $sEnvironmentId = MetaModel::GetEnvironmentId();
  4711. }
  4712. $sAppIdentity = 'itop-'.$sEnvironmentId;
  4713. Dict::ResetCache($sAppIdentity);
  4714. foreach(self::GetCacheEntries($sEnvironmentId) as $sKey => $aAPCInfo)
  4715. {
  4716. $sAPCKey = $aAPCInfo['info'];
  4717. apc_delete($sAPCKey);
  4718. }
  4719. }
  4720. } // class MetaModel
  4721. // Standard attribute lists
  4722. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  4723. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  4724. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  4725. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  4726. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  4727. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  4728. ?>