metamodel.class.php 157 KB

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