metamodel.class.php 162 KB

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