metamodel.class.php 162 KB

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