metamodel.class.php 200 KB

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