metamodel.class.php 138 KB

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