metamodel.class.php 178 KB

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