metamodel.class.php 167 KB

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