metamodel.class.php 176 KB

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