metamodel.class.php 181 KB

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