metamodel.class.php 164 KB

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