metamodel.class.php 164 KB

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