metamodel.class.php 157 KB

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