metamodel.class.php 197 KB

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