metamodel.class.php 154 KB

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