metamodel.class.php 180 KB

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