metamodel.class.php 200 KB

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