metamodel.class.php 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038
  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 do 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. }
  1167. // To be overriden, must be called for any object class (optimization)
  1168. public static function Init()
  1169. {
  1170. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1171. }
  1172. // To be overloaded by biz model declarations
  1173. public static function GetRelationQueries($sRelCode)
  1174. {
  1175. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  1176. return array();
  1177. }
  1178. public static function Init_Params($aParams)
  1179. {
  1180. // Check mandatory params
  1181. $aMandatParams = array(
  1182. "category" => "group classes by modules defining their visibility in the UI",
  1183. "key_type" => "autoincrement | string",
  1184. "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...'",
  1185. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  1186. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  1187. "db_table" => "database table",
  1188. "db_key_field" => "database field which is the key",
  1189. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  1190. );
  1191. $sClass = self::GetCallersPHPClass("Init");
  1192. foreach($aMandatParams as $sParamName=>$sParamDesc)
  1193. {
  1194. if (!array_key_exists($sParamName, $aParams))
  1195. {
  1196. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  1197. }
  1198. }
  1199. $aCategories = explode(',', $aParams['category']);
  1200. foreach ($aCategories as $sCategory)
  1201. {
  1202. self::$m_Category2Class[$sCategory][] = $sClass;
  1203. }
  1204. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  1205. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  1206. self::$m_aParentClasses[$sClass] = array();
  1207. self::$m_aChildClasses[$sClass] = array();
  1208. self::$m_aClassParams[$sClass]= $aParams;
  1209. self::$m_aAttribDefs[$sClass] = array();
  1210. self::$m_aAttribOrigins[$sClass] = array();
  1211. self::$m_aExtKeyFriends[$sClass] = array();
  1212. self::$m_aFilterDefs[$sClass] = array();
  1213. self::$m_aFilterOrigins[$sClass] = array();
  1214. }
  1215. protected static function object_array_mergeclone($aSource1, $aSource2)
  1216. {
  1217. $aRes = array();
  1218. foreach ($aSource1 as $key=>$object)
  1219. {
  1220. $aRes[$key] = clone $object;
  1221. }
  1222. foreach ($aSource2 as $key=>$object)
  1223. {
  1224. $aRes[$key] = clone $object;
  1225. }
  1226. return $aRes;
  1227. }
  1228. public static function Init_InheritAttributes($sSourceClass = null)
  1229. {
  1230. $sTargetClass = self::GetCallersPHPClass("Init");
  1231. if (empty($sSourceClass))
  1232. {
  1233. // Default: inherit from parent class
  1234. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1235. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1236. }
  1237. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1238. {
  1239. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1240. {
  1241. self::$m_aAttribDefs[$sTargetClass] = array();
  1242. self::$m_aAttribOrigins[$sTargetClass] = array();
  1243. }
  1244. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1245. // Note: while investigating on some issues related to attribute inheritance,
  1246. // I found out that the notion of "host class" is unclear
  1247. // For stability reasons, and also because a workaround has been found
  1248. // I leave it unchanged, but later it could be a good thing to force
  1249. // attribute host class to the new class (See code below)
  1250. // In that case, we will have to review the attribute labels
  1251. // (currently relying on host class => the original declaration
  1252. // of the attribute)
  1253. // See TRAC #148
  1254. // foreach(self::$m_aAttribDefs[$sTargetClass] as $sAttCode => $oAttDef)
  1255. // {
  1256. // $oAttDef->SetHostClass($sTargetClass);
  1257. // }
  1258. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1259. }
  1260. // Build root class information
  1261. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1262. {
  1263. // Inherit...
  1264. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1265. }
  1266. else
  1267. {
  1268. // This class will be the root class
  1269. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1270. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1271. }
  1272. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1273. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1274. // I am the child of each and every parent...
  1275. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1276. {
  1277. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1278. }
  1279. }
  1280. public static function Init_OverloadAttributeParams($sAttCode, $aParams)
  1281. {
  1282. $sTargetClass = self::GetCallersPHPClass("Init");
  1283. if (!self::IsValidAttCode($sTargetClass, $sAttCode))
  1284. {
  1285. throw new CoreException("Could not overload '$sAttCode', expecting a code from {".implode(", ", self::GetAttributesList($sTargetClass))."}");
  1286. }
  1287. self::$m_aAttribDefs[$sTargetClass][$sAttCode]->OverloadParams($aParams);
  1288. }
  1289. protected static function Init_IsKnownClass($sClass)
  1290. {
  1291. // Differs from self::IsValidClass()
  1292. // because it is being called before all the classes have been initialized
  1293. if (!class_exists($sClass)) return false;
  1294. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1295. return true;
  1296. }
  1297. public static function Init_AddAttribute(AttributeDefinition $oAtt)
  1298. {
  1299. $sAttCode = $oAtt->GetCode();
  1300. if ($sAttCode == 'finalclass') throw new Exception('Using a reserved keyword in metamodel declaration: '.$sAttCode);
  1301. if ($sAttCode == 'friendlyname') throw new Exception('Using a reserved keyword in metamodel declaration: '.$sAttCode);
  1302. $sTargetClass = self::GetCallersPHPClass("Init");
  1303. // Some attributes could refer to a class
  1304. // declared in a module which is currently not installed/active
  1305. // We simply discard those attributes
  1306. //
  1307. if ($oAtt->IsLinkSet())
  1308. {
  1309. $sRemoteClass = $oAtt->GetLinkedClass();
  1310. if (!self::Init_IsKnownClass($sRemoteClass))
  1311. {
  1312. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1313. return;
  1314. }
  1315. }
  1316. elseif($oAtt->IsExternalKey())
  1317. {
  1318. $sRemoteClass = $oAtt->GetTargetClass();
  1319. if (!self::Init_IsKnownClass($sRemoteClass))
  1320. {
  1321. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1322. return;
  1323. }
  1324. }
  1325. elseif($oAtt->IsExternalField())
  1326. {
  1327. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1328. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1329. {
  1330. // The corresponding external key has already been ignored
  1331. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1332. return;
  1333. }
  1334. // #@# todo - Check if the target attribute is still there
  1335. // this is not simple to implement because is involves
  1336. // several passes (the load order has a significant influence on that)
  1337. }
  1338. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1339. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1340. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1341. // Specific case of external fields:
  1342. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1343. // Therefore, the reference to the host class is set there
  1344. $oAtt->SetHostClass($sTargetClass);
  1345. }
  1346. public static function Init_SetZListItems($sListCode, $aItems)
  1347. {
  1348. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1349. $sTargetClass = self::GetCallersPHPClass("Init");
  1350. // Discard attributes that do not make sense
  1351. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1352. //
  1353. self::Init_CheckZListItems($aItems, $sTargetClass);
  1354. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1355. }
  1356. protected static function Init_CheckZListItems(&$aItems, $sTargetClass)
  1357. {
  1358. foreach($aItems as $iFoo => $attCode)
  1359. {
  1360. if (is_array($attCode))
  1361. {
  1362. self::Init_CheckZListItems($attCode, $sTargetClass);
  1363. }
  1364. else if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$attCode]))
  1365. {
  1366. unset($aItems[$iFoo]);
  1367. }
  1368. }
  1369. }
  1370. public static function FlattenZList($aList)
  1371. {
  1372. $aResult = array();
  1373. foreach($aList as $value)
  1374. {
  1375. if (!is_array($value))
  1376. {
  1377. $aResult[] = $value;
  1378. }
  1379. else
  1380. {
  1381. $aResult = array_merge($aResult, self::FlattenZList($value));
  1382. }
  1383. }
  1384. return $aResult;
  1385. }
  1386. public static function Init_DefineState($sStateCode, $aStateDef)
  1387. {
  1388. $sTargetClass = self::GetCallersPHPClass("Init");
  1389. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1390. $sParentState = $aStateDef['attribute_inherit'];
  1391. if (!empty($sParentState))
  1392. {
  1393. // Inherit from the given state (must be defined !)
  1394. //
  1395. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1396. // Reset the constraint when it was mandatory to set the value at the previous state
  1397. //
  1398. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  1399. {
  1400. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  1401. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  1402. $aToInherit['attribute_list'][$sState] = $iFlags;
  1403. }
  1404. // The inherited configuration could be overriden
  1405. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  1406. }
  1407. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  1408. {
  1409. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1410. {
  1411. unset($aStateDef['attribute_list'][$sAttCode]);
  1412. }
  1413. }
  1414. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1415. // by default, create an empty set of transitions associated to that state
  1416. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1417. }
  1418. public static function Init_OverloadStateAttribute($sStateCode, $sAttCode, $iFlags)
  1419. {
  1420. // Warning: this is not sufficient: the flags have to be copied to the states that are inheriting from this state
  1421. $sTargetClass = self::GetCallersPHPClass("Init");
  1422. self::$m_aStates[$sTargetClass][$sStateCode]['attribute_list'][$sAttCode] = $iFlags;
  1423. }
  1424. public static function Init_DefineStimulus($oStimulus)
  1425. {
  1426. $sTargetClass = self::GetCallersPHPClass("Init");
  1427. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  1428. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1429. // Therefore, the reference to the host class is set there
  1430. $oStimulus->SetHostClass($sTargetClass);
  1431. }
  1432. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1433. {
  1434. $sTargetClass = self::GetCallersPHPClass("Init");
  1435. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1436. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1437. }
  1438. public static function Init_InheritLifecycle($sSourceClass = '')
  1439. {
  1440. $sTargetClass = self::GetCallersPHPClass("Init");
  1441. if (empty($sSourceClass))
  1442. {
  1443. // Default: inherit from parent class
  1444. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1445. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1446. }
  1447. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1448. self::$m_aStates[$sTargetClass] = self::$m_aStates[$sSourceClass];
  1449. // #@# Note: the aim is to clone the data, could be an issue if the simuli objects are changed
  1450. self::$m_aStimuli[$sTargetClass] = self::$m_aStimuli[$sSourceClass];
  1451. self::$m_aTransitions[$sTargetClass] = self::$m_aTransitions[$sSourceClass];
  1452. }
  1453. //
  1454. // Static API
  1455. //
  1456. public static function GetRootClass($sClass = null)
  1457. {
  1458. self::_check_subclass($sClass);
  1459. return self::$m_aRootClasses[$sClass];
  1460. }
  1461. public static function IsRootClass($sClass)
  1462. {
  1463. self::_check_subclass($sClass);
  1464. return (self::GetRootClass($sClass) == $sClass);
  1465. }
  1466. public static function EnumRootClasses()
  1467. {
  1468. return array_unique(self::$m_aRootClasses);
  1469. }
  1470. public static function EnumParentClasses($sClass, $iOption = ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1471. {
  1472. self::_check_subclass($sClass);
  1473. if ($iOption == ENUM_PARENT_CLASSES_EXCLUDELEAF)
  1474. {
  1475. return self::$m_aParentClasses[$sClass];
  1476. }
  1477. $aRes = self::$m_aParentClasses[$sClass];
  1478. $aRes[] = $sClass;
  1479. return $aRes;
  1480. }
  1481. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1482. {
  1483. self::_check_subclass($sClass);
  1484. $aRes = self::$m_aChildClasses[$sClass];
  1485. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1486. {
  1487. // Add it to the list
  1488. $aRes[] = $sClass;
  1489. }
  1490. return $aRes;
  1491. }
  1492. public static function HasChildrenClasses($sClass)
  1493. {
  1494. return (count(self::$m_aChildClasses[$sClass]) > 0);
  1495. }
  1496. public static function EnumCategories()
  1497. {
  1498. return array_keys(self::$m_Category2Class);
  1499. }
  1500. // Note: use EnumChildClasses to take the compound objects into account
  1501. public static function GetSubclasses($sClass)
  1502. {
  1503. self::_check_subclass($sClass);
  1504. $aSubClasses = array();
  1505. foreach(get_declared_classes() as $sSubClass) {
  1506. if (is_subclass_of($sSubClass, $sClass))
  1507. {
  1508. $aSubClasses[] = $sSubClass;
  1509. }
  1510. }
  1511. return $aSubClasses;
  1512. }
  1513. public static function GetClasses($sCategories = '', $bStrict = false)
  1514. {
  1515. $aCategories = explode(',', $sCategories);
  1516. $aClasses = array();
  1517. foreach($aCategories as $sCategory)
  1518. {
  1519. $sCategory = trim($sCategory);
  1520. if (strlen($sCategory) == 0)
  1521. {
  1522. return array_keys(self::$m_aClassParams);
  1523. }
  1524. if (array_key_exists($sCategory, self::$m_Category2Class))
  1525. {
  1526. $aClasses = array_merge($aClasses, self::$m_Category2Class[$sCategory]);
  1527. }
  1528. elseif ($bStrict)
  1529. {
  1530. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1531. }
  1532. }
  1533. return array_unique($aClasses);
  1534. }
  1535. public static function HasTable($sClass)
  1536. {
  1537. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  1538. return true;
  1539. }
  1540. public static function IsAbstract($sClass)
  1541. {
  1542. $oReflection = new ReflectionClass($sClass);
  1543. return $oReflection->isAbstract();
  1544. }
  1545. protected static $m_aQueryStructCache = array();
  1546. protected static function PrepareQueryArguments($aArgs)
  1547. {
  1548. // Translate any object into scalars
  1549. //
  1550. $aScalarArgs = array();
  1551. foreach($aArgs as $sArgName => $value)
  1552. {
  1553. if (self::IsValidObject($value))
  1554. {
  1555. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1556. }
  1557. else
  1558. {
  1559. $aScalarArgs[$sArgName] = (string) $value;
  1560. }
  1561. }
  1562. // Add standard contextual arguments
  1563. //
  1564. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1565. return $aScalarArgs;
  1566. }
  1567. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array(), $aExtendedDataSpec = null, $iLimitCount = 0, $iLimitStart = 0, $bGetCount = false)
  1568. {
  1569. // Hide objects that are not visible to the current user
  1570. //
  1571. if (!$oFilter->IsAllDataAllowed())
  1572. {
  1573. $oVisibleObjects = UserRights::GetSelectFilter($oFilter->GetClass());
  1574. if ($oVisibleObjects === false)
  1575. {
  1576. // Make sure this is a valid search object, saying NO for all
  1577. $oVisibleObjects = DBObjectSearch::FromEmptySet($oFilter->GetClass());
  1578. }
  1579. if (is_object($oVisibleObjects))
  1580. {
  1581. $oFilter->MergeWith($oVisibleObjects);
  1582. }
  1583. else
  1584. {
  1585. // should be true at this point, meaning that no additional filtering
  1586. // is required
  1587. }
  1588. }
  1589. if (self::$m_bQueryCacheEnabled || self::$m_bTraceQueries)
  1590. {
  1591. // Need to identify the query
  1592. $sOqlQuery = $oFilter->ToOql();
  1593. $sOqlId = md5($sOqlQuery);
  1594. }
  1595. else
  1596. {
  1597. $sOqlQuery = "SELECTING... ".$oFilter->GetClass();
  1598. $sOqlId = "query id ? n/a";
  1599. }
  1600. // Query caching
  1601. //
  1602. if (self::$m_bQueryCacheEnabled)
  1603. {
  1604. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  1605. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  1606. // to use a hash (like md5) of the string as the key !
  1607. //
  1608. // Example of two queries that were found as similar by the hash array:
  1609. // 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
  1610. // and
  1611. // 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
  1612. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  1613. //
  1614. if (array_key_exists($sOqlId, self::$m_aQueryStructCache))
  1615. {
  1616. // hit!
  1617. $oSelect = clone self::$m_aQueryStructCache[$sOqlId];
  1618. }
  1619. }
  1620. if (!isset($oSelect))
  1621. {
  1622. $aClassAliases = array();
  1623. $aTableAliases = array();
  1624. $oQBExpr = new QueryBuilderExpressions(array(), $oFilter->GetCriteria());
  1625. $oKPI = new ExecutionKPI();
  1626. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oQBExpr, $aClassAliases, $aTableAliases, $oFilter, array(), true /* main query */);
  1627. $oKPI->ComputeStats('MakeQuery (select)', $sOqlQuery);
  1628. self::$m_aQueryStructCache[$sOqlId] = clone $oSelect;
  1629. }
  1630. // Check the order by specification, and prefix with the class alias
  1631. //
  1632. $aOrderSpec = array();
  1633. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1634. {
  1635. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetFirstJoinedClass()));
  1636. if (!is_bool($bAscending))
  1637. {
  1638. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1639. }
  1640. $aOrderSpec[$oFilter->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1641. }
  1642. // By default, force the name attribute to be the ordering key
  1643. //
  1644. if (empty($aOrderSpec))
  1645. {
  1646. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1647. {
  1648. // By default, simply order on the "friendlyname" attribute, ascending
  1649. $aOrderSpec[$sSelectedAlias."friendlyname"] = true;
  1650. }
  1651. }
  1652. // Join to an additional table, if required...
  1653. //
  1654. if ($aExtendedDataSpec != null)
  1655. {
  1656. $sTableAlias = '_extended_data_';
  1657. $aExtendedFields = array();
  1658. foreach($aExtendedDataSpec['fields'] as $sColumn)
  1659. {
  1660. $sColRef = $oFilter->GetClassAlias().'_extdata_'.$sColumn;
  1661. $aExtendedFields[$sColRef] = new FieldExpressionResolved($sColumn, $sTableAlias);;
  1662. }
  1663. $oSelectExt = new SQLQuery($aExtendedDataSpec['table'], $sTableAlias, $aExtendedFields);
  1664. $oSelect->AddInnerJoin($oSelectExt, 'id', $aExtendedDataSpec['join_key'] /*, $sTableAlias*/);
  1665. }
  1666. // Go
  1667. //
  1668. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1669. try
  1670. {
  1671. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs, $iLimitCount, $iLimitStart, $bGetCount);
  1672. }
  1673. catch (MissingQueryArgument $e)
  1674. {
  1675. // Add some information...
  1676. $e->addInfo('OQL', $sOqlQuery);
  1677. throw $e;
  1678. }
  1679. if (self::$m_bTraceQueries)
  1680. {
  1681. $sQueryId = md5($sRes);
  1682. if(!isset(self::$m_aQueriesLog[$sOqlId]))
  1683. {
  1684. self::$m_aQueriesLog[$sOqlId]['oql'] = $sOqlQuery;
  1685. self::$m_aQueriesLog[$sOqlId]['hits'] = 1;
  1686. }
  1687. else
  1688. {
  1689. self::$m_aQueriesLog[$sOqlId]['hits']++;
  1690. }
  1691. if(!isset(self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]))
  1692. {
  1693. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['sql'] = $sRes;
  1694. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['count'] = 1;
  1695. }
  1696. else
  1697. {
  1698. self::$m_aQueriesLog[$sOqlId]['queries'][$sQueryId]['count']++;
  1699. }
  1700. }
  1701. return $sRes;
  1702. }
  1703. public static function ShowQueryTrace()
  1704. {
  1705. if (!self::$m_bTraceQueries) return;
  1706. $iOqlCount = count(self::$m_aQueriesLog);
  1707. if ($iOqlCount == 0)
  1708. {
  1709. echo "<p>Trace activated, but no query found</p>\n";
  1710. return;
  1711. }
  1712. $iSqlCount = 0;
  1713. foreach (self::$m_aQueriesLog as $aOqlData)
  1714. {
  1715. $iSqlCount += $aOqlData['hits'];
  1716. }
  1717. echo "<h2>Stats on SELECT queries: OQL=$iOqlCount, SQL=$iSqlCount</h2>\n";
  1718. foreach (self::$m_aQueriesLog as $aOqlData)
  1719. {
  1720. $sOql = $aOqlData['oql'];
  1721. $sHits = $aOqlData['hits'];
  1722. echo "<p><b>$sHits</b> hits for OQL query: $sOql</p>\n";
  1723. echo "<ul id=\"ClassesRelationships\" class=\"treeview\">\n";
  1724. foreach($aOqlData['queries'] as $aSqlData)
  1725. {
  1726. $sQuery = $aSqlData['sql'];
  1727. $sSqlHits = $aSqlData['count'];
  1728. echo "<li><b>$sSqlHits</b> hits for SQL: <span style=\"font-size:60%\">$sQuery</span><li>\n";
  1729. }
  1730. echo "</ul>\n";
  1731. }
  1732. }
  1733. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1734. {
  1735. $aClassAliases = array();
  1736. $aTableAliases = array();
  1737. $oQBExpr = new QueryBuilderExpressions(array(), $oFilter->GetCriteria());
  1738. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oQBExpr, $aClassAliases, $aTableAliases, $oFilter, array(), true /* main query */);
  1739. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1740. return $oSelect->RenderDelete($aScalarArgs);
  1741. }
  1742. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1743. {
  1744. // $aValues is an array of $sAttCode => $value
  1745. $aClassAliases = array();
  1746. $aTableAliases = array();
  1747. $oQBExpr = new QueryBuilderExpressions(array(), $oFilter->GetCriteria());
  1748. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oQBExpr, $aClassAliases, $aTableAliases, $oFilter, $aValues, true /* main query */);
  1749. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1750. return $oSelect->RenderUpdate($aScalarArgs);
  1751. }
  1752. private static function MakeQuery($aSelectedClasses, &$oQBExpr, &$aClassAliases, &$aTableAliases, DBObjectSearch $oFilter, $aValues = array(), $bIsMainQuery = false)
  1753. {
  1754. // Note: query class might be different than the class of the filter
  1755. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1756. $sClass = $oFilter->GetFirstJoinedClass();
  1757. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1758. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1759. if ($bIsOnQueriedClass)
  1760. {
  1761. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1762. }
  1763. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1764. $sRootClass = self::GetRootClass($sClass);
  1765. $sKeyField = self::DBGetKey($sClass);
  1766. if ($bIsOnQueriedClass)
  1767. {
  1768. // default to the whole list of attributes + the very std id/finalclass
  1769. $oQBExpr->AddSelect($sClassAlias.'id', new FieldExpression('id', $sClassAlias));
  1770. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1771. {
  1772. if (!$oAttDef->IsScalar()) continue;
  1773. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1774. {
  1775. $oQBExpr->AddSelect($sClassAlias.$sAttCode.$sColId, new FieldExpression($sAttCode.$sColId, $sClassAlias));
  1776. }
  1777. }
  1778. }
  1779. $aExpectedAtts = array(); // array of (attcode => fieldexpression)
  1780. $oQBExpr->GetUnresolvedFields($sClassAlias, $aExpectedAtts);
  1781. // Compute a clear view of required joins (from the current class)
  1782. // Build the list of external keys:
  1783. // -> ext keys required by an explicit join
  1784. // -> ext keys mentionned in a 'pointing to' condition
  1785. // -> ext keys required for an external field
  1786. // -> ext keys required for a friendly name
  1787. //
  1788. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1789. //
  1790. // Optimization: could be partially computed once for all (cached) ?
  1791. //
  1792. if ($bIsOnQueriedClass)
  1793. {
  1794. // Get all Ext keys for the queried class (??)
  1795. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1796. {
  1797. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1798. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1799. }
  1800. }
  1801. // Get all Ext keys used by the filter
  1802. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1803. {
  1804. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1805. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1806. }
  1807. if (array_key_exists('friendlyname', $aExpectedAtts))
  1808. {
  1809. $aTranslateNow = array();
  1810. $aTranslateNow[$sClassAlias]['friendlyname'] = self::GetNameExpression($sClass, $sClassAlias);
  1811. $oQBExpr->Translate($aTranslateNow, false);
  1812. $aNameSpec = self::GetNameSpec($sClass);
  1813. foreach($aNameSpec[1] as $i => $sAttCode)
  1814. {
  1815. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  1816. if ($oAttDef->IsExternalKey())
  1817. {
  1818. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sAttCode];
  1819. $aExtKeys[$sKeyTableClass][$sAttCode] = array();
  1820. }
  1821. elseif ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  1822. {
  1823. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1824. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1825. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1826. }
  1827. }
  1828. }
  1829. // Add the ext fields used in the select (eventually adds an external key)
  1830. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1831. {
  1832. if ($oAttDef->IsExternalField() || ($oAttDef instanceof AttributeFriendlyName))
  1833. {
  1834. if (array_key_exists($sAttCode, $aExpectedAtts))
  1835. {
  1836. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1837. if ($sKeyAttCode != 'id')
  1838. {
  1839. // Add the external attribute
  1840. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1841. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1842. }
  1843. }
  1844. }
  1845. }
  1846. // First query built upon on the leaf (ie current) class
  1847. //
  1848. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1849. if (self::HasTable($sClass))
  1850. {
  1851. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oQBExpr, $aClassAliases, $aTableAliases, $oFilter, $sClass, $aExtKeys, $aValues);
  1852. }
  1853. else
  1854. {
  1855. $oSelectBase = null;
  1856. // As the join will not filter on the expected classes, we have to specify it explicitely
  1857. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1858. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1859. $oQBExpr->AddCondition($oFinalClassRestriction);
  1860. }
  1861. // Then we join the queries of the eventual parent classes (compound model)
  1862. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1863. {
  1864. if (!self::HasTable($sParentClass)) continue;
  1865. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1866. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oQBExpr, $aClassAliases, $aTableAliases, $oFilter, $sParentClass, $aExtKeys, $aValues);
  1867. if (is_null($oSelectBase))
  1868. {
  1869. $oSelectBase = $oSelectParentTable;
  1870. }
  1871. else
  1872. {
  1873. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1874. }
  1875. }
  1876. // Filter on objects referencing me
  1877. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1878. {
  1879. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1880. {
  1881. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1882. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1883. //self::DbgTrace($oForeignFilter);
  1884. //self::DbgTrace($oForeignFilter->ToOQL());
  1885. //self::DbgTrace($oSelectForeign);
  1886. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1887. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1888. $oQBExpr->PushJoinField(new FieldExpression($sForeignKeyAttCode, $sForeignClassAlias));
  1889. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oQBExpr, $aClassAliases, $aTableAliases, $oForeignFilter);
  1890. $oJoinExpr = $oQBExpr->PopJoinField();
  1891. $sForeignKeyTable = $oJoinExpr->GetParent();
  1892. $sForeignKeyColumn = $oJoinExpr->GetName();
  1893. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1894. }
  1895. }
  1896. // Filter on related objects
  1897. //
  1898. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1899. {
  1900. $oSubFilter = $aCritInfo['flt'];
  1901. $sRelCode = $aCritInfo['relcode'];
  1902. $iMaxDepth = $aCritInfo['maxdepth'];
  1903. // Get the starting point objects
  1904. $oStartSet = new CMDBObjectSet($oSubFilter);
  1905. // Get the objects related to those objects... recursively...
  1906. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1907. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1908. // #@# todo - related objects and expressions...
  1909. // Create condition
  1910. if (count($aRestriction) > 0)
  1911. {
  1912. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1913. }
  1914. else
  1915. {
  1916. // Quick N'dirty -> generate an empty set
  1917. $oSelectBase->AddCondition('false');
  1918. }
  1919. }
  1920. // Translate the conditions... and go
  1921. //
  1922. if ($bIsMainQuery)
  1923. {
  1924. $oSelectBase->SetCondition($oQBExpr->GetCondition());
  1925. $oSelectBase->SetSelect($oQBExpr->GetSelect());
  1926. }
  1927. // That's all... cross fingers and we'll get some working query
  1928. //MyHelpers::var_dump_html($oSelectBase, true);
  1929. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1930. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1931. return $oSelectBase;
  1932. }
  1933. protected static function MakeQuerySingleTable($aSelectedClasses, &$oQBExpr, &$aClassAliases, &$aTableAliases, $oFilter, $sTableClass, $aExtKeys, $aValues)
  1934. {
  1935. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1936. // Prepare the query for a single table (compound objects)
  1937. // Ignores the items (attributes/filters) that are not on the target table
  1938. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1939. //
  1940. // Returns an SQLQuery
  1941. //
  1942. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1943. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1944. $sTable = self::DBGetTable($sTableClass);
  1945. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1946. $aTranslation = array();
  1947. $aExpectedAtts = array();
  1948. $oQBExpr->GetUnresolvedFields($sTargetAlias, $aExpectedAtts);
  1949. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1950. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY"));
  1951. // 1 - SELECT and UPDATE
  1952. //
  1953. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1954. //
  1955. $aUpdateValues = array();
  1956. // 1/a - Get the key and friendly name
  1957. //
  1958. // We need one pkey to be the key, let's take the one corresponding to the root class
  1959. // (used to be based on the leaf, but it may happen that this one has no table defined)
  1960. $sRootClass = self::GetRootClass($sTargetClass);
  1961. $oSelectedIdField = null;
  1962. if ($sTableClass == $sRootClass)
  1963. {
  1964. $oIdField = new FieldExpressionResolved(self::DBGetKey($sTableClass), $sTableAlias);
  1965. $aTranslation[$sTargetAlias]['id'] = $oIdField;
  1966. if ($bIsOnQueriedClass)
  1967. {
  1968. // Add this field to the list of queried fields (required for the COUNT to work fine)
  1969. $oSelectedIdField = $oIdField;
  1970. }
  1971. }
  1972. // 1/b - Get the other attributes
  1973. //
  1974. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1975. {
  1976. // Skip this attribute if not defined in this table
  1977. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1978. // Skip this attribute if not made of SQL columns
  1979. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1980. // Update...
  1981. //
  1982. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1983. {
  1984. assert ($oAttDef->IsDirectField());
  1985. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1986. {
  1987. $aUpdateValues[$sColumn] = $sValue;
  1988. }
  1989. }
  1990. // Select...
  1991. //
  1992. if ($oAttDef->IsExternalField())
  1993. {
  1994. // skip, this will be handled in the joined tables (done hereabove)
  1995. }
  1996. else
  1997. {
  1998. // standard field, or external key
  1999. // add it to the output
  2000. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  2001. {
  2002. if (array_key_exists($sAttCode, $aExpectedAtts))
  2003. {
  2004. $aTranslation[$sTargetAlias][$sAttCode.$sColId] = new FieldExpressionResolved($sSQLExpr, $sTableAlias);
  2005. }
  2006. }
  2007. }
  2008. }
  2009. // #@# todo - See what a full text search condition should be
  2010. // 2 - WHERE / Full text search condition
  2011. //
  2012. if ($bIsOnQueriedClass)
  2013. {
  2014. $aFullText = $oFilter->GetCriteria_FullText();
  2015. }
  2016. else
  2017. {
  2018. // Pourquoi ???
  2019. $aFullText = array();
  2020. }
  2021. // 3 - The whole stuff, for this table only
  2022. //
  2023. $oSelectBase = new SQLQuery($sTable, $sTableAlias, array(), $aFullText, $bIsOnQueriedClass, $aUpdateValues, $oSelectedIdField);
  2024. // 4 - The external keys -> joins...
  2025. //
  2026. if (array_key_exists($sTableClass, $aExtKeys))
  2027. {
  2028. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  2029. {
  2030. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  2031. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  2032. // In case the join was not explicitely defined in the filter,
  2033. // we need to do it now
  2034. if (empty($oExtFilter))
  2035. {
  2036. $sKeyClass = $oKeyAttDef->GetTargetClass();
  2037. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  2038. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  2039. }
  2040. else
  2041. {
  2042. // The aliases should not conflict because normalization occured while building the filter
  2043. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  2044. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  2045. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  2046. }
  2047. // Specify expected attributes for the target class query
  2048. // ... and use the current alias !
  2049. $aTranslateNow = array(); // Translation for external fields - must be performed before the join is done (recursion...)
  2050. foreach($aExtFields as $sAttCode => $oAtt)
  2051. {
  2052. if ($oAtt instanceof AttributeFriendlyName)
  2053. {
  2054. // Note: for a given ext key, there is one single attribute "friendly name"
  2055. $aTranslateNow[$sTargetAlias][$sAttCode] = new FieldExpression('friendlyname', $sKeyClassAlias);
  2056. }
  2057. else
  2058. {
  2059. $sExtAttCode = $oAtt->GetExtAttCode();
  2060. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  2061. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  2062. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  2063. {
  2064. $aTranslateNow[$sTargetAlias][$sAttCode.$sColId] = new FieldExpression($sExtAttCode, $sKeyClassAlias);
  2065. }
  2066. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  2067. }
  2068. }
  2069. // Translate prior to recursing
  2070. //
  2071. $oQBExpr->Translate($aTranslateNow, false);
  2072. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  2073. $oQBExpr->PushJoinField(new FieldExpression('id', $sKeyClassAlias));
  2074. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oQBExpr, $aClassAliases, $aTableAliases, $oExtFilter);
  2075. $oJoinExpr = $oQBExpr->PopJoinField();
  2076. $sExternalKeyTable = $oJoinExpr->GetParent();
  2077. $sExternalKeyField = $oJoinExpr->GetName();
  2078. $aCols = $oKeyAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2079. $sLocalKeyField = current($aCols); // get the first column for an external key
  2080. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  2081. if ($oKeyAttDef->IsNullAllowed())
  2082. {
  2083. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  2084. }
  2085. else
  2086. {
  2087. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField, $sExternalKeyTable);
  2088. }
  2089. }
  2090. }
  2091. // Translate the selected columns
  2092. //
  2093. $oQBExpr->Translate($aTranslation, false);
  2094. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  2095. return $oSelectBase;
  2096. }
  2097. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  2098. {
  2099. if (!array_key_exists($sNewName, $aAliases))
  2100. {
  2101. $aAliases[$sNewName] = $sRealName;
  2102. return $sNewName;
  2103. }
  2104. for ($i = 1 ; $i < 100 ; $i++)
  2105. {
  2106. $sAnAlias = $sNewName.$i;
  2107. if (!array_key_exists($sAnAlias, $aAliases))
  2108. {
  2109. // Create that new alias
  2110. $aAliases[$sAnAlias] = $sRealName;
  2111. return $sAnAlias;
  2112. }
  2113. }
  2114. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  2115. }
  2116. public static function CheckDefinitions()
  2117. {
  2118. if (count(self::GetClasses()) == 0)
  2119. {
  2120. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  2121. }
  2122. $aErrors = array();
  2123. $aSugFix = array();
  2124. foreach (self::GetClasses() as $sClass)
  2125. {
  2126. $aNameSpec = self::GetNameSpec($sClass);
  2127. foreach($aNameSpec[1] as $i => $sAttCode)
  2128. {
  2129. if(!self::IsValidAttCode($sClass, $sAttCode))
  2130. {
  2131. $aErrors[$sClass][] = "Unkown attribute code '".$sAttCode."' for the name definition";
  2132. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2133. }
  2134. }
  2135. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  2136. {
  2137. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  2138. {
  2139. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  2140. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2141. }
  2142. }
  2143. $bHasWritableAttribute = false;
  2144. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2145. {
  2146. // It makes no sense to check the attributes again and again in the subclasses
  2147. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2148. if ($oAttDef->IsExternalKey())
  2149. {
  2150. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  2151. {
  2152. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  2153. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  2154. }
  2155. }
  2156. elseif ($oAttDef->IsExternalField())
  2157. {
  2158. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  2159. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  2160. {
  2161. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  2162. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  2163. }
  2164. else
  2165. {
  2166. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  2167. $sTargetClass = $oKeyAttDef->GetTargetClass();
  2168. $sExtAttCode = $oAttDef->GetExtAttCode();
  2169. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  2170. {
  2171. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  2172. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  2173. }
  2174. }
  2175. }
  2176. else // standard attributes
  2177. {
  2178. // Check that the default values definition is a valid object!
  2179. $oValSetDef = $oAttDef->GetValuesDef();
  2180. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  2181. {
  2182. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  2183. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  2184. }
  2185. else
  2186. {
  2187. // Default value must be listed in the allowed values (if defined)
  2188. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2189. if (!is_null($aAllowedValues))
  2190. {
  2191. $sDefaultValue = $oAttDef->GetDefaultValue();
  2192. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  2193. {
  2194. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  2195. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  2196. }
  2197. }
  2198. }
  2199. }
  2200. // Check dependencies
  2201. if ($oAttDef->IsWritable())
  2202. {
  2203. $bHasWritableAttribute = true;
  2204. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  2205. {
  2206. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  2207. {
  2208. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  2209. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  2210. }
  2211. }
  2212. }
  2213. }
  2214. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  2215. {
  2216. if (method_exists($oFilterDef, '__GetRefAttribute'))
  2217. {
  2218. $oAttDef = $oFilterDef->__GetRefAttribute();
  2219. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  2220. {
  2221. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  2222. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2223. }
  2224. }
  2225. }
  2226. // Lifecycle
  2227. //
  2228. $sStateAttCode = self::GetStateAttributeCode($sClass);
  2229. if (strlen($sStateAttCode) > 0)
  2230. {
  2231. // Lifecycle - check that the state attribute does exist as an attribute
  2232. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  2233. {
  2234. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  2235. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2236. }
  2237. else
  2238. {
  2239. // Lifecycle - check that there is a value set constraint on the state attribute
  2240. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  2241. $aStates = array_keys(self::EnumStates($sClass));
  2242. if (is_null($aAllowedValuesRaw))
  2243. {
  2244. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  2245. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  2246. }
  2247. else
  2248. {
  2249. $aAllowedValues = array_keys($aAllowedValuesRaw);
  2250. // Lifecycle - check the the state attribute allowed values are defined states
  2251. foreach($aAllowedValues as $sValue)
  2252. {
  2253. if (!in_array($sValue, $aStates))
  2254. {
  2255. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  2256. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2257. }
  2258. }
  2259. // Lifecycle - check that defined states are allowed values
  2260. foreach($aStates as $sStateValue)
  2261. {
  2262. if (!in_array($sStateValue, $aAllowedValues))
  2263. {
  2264. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  2265. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  2266. }
  2267. }
  2268. }
  2269. // Lifcycle - check that the action handlers are defined
  2270. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  2271. {
  2272. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  2273. {
  2274. foreach ($aTransitionDef['actions'] as $sActionHandler)
  2275. {
  2276. if (!method_exists($sClass, $sActionHandler))
  2277. {
  2278. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  2279. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  2280. }
  2281. }
  2282. }
  2283. }
  2284. }
  2285. }
  2286. if ($bHasWritableAttribute)
  2287. {
  2288. if (!self::HasTable($sClass))
  2289. {
  2290. $aErrors[$sClass][] = "No table has been defined for this class";
  2291. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  2292. }
  2293. }
  2294. // ZList
  2295. //
  2296. foreach(self::EnumZLists() as $sListCode)
  2297. {
  2298. foreach (self::FlattenZList(self::GetZListItems($sClass, $sListCode)) as $sMyAttCode)
  2299. {
  2300. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  2301. {
  2302. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  2303. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  2304. }
  2305. }
  2306. }
  2307. }
  2308. if (count($aErrors) > 0)
  2309. {
  2310. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2311. echo "<h3>Business model inconsistencies have been found</h3>\n";
  2312. // #@# later -> this is the responsibility of the caller to format the output
  2313. foreach ($aErrors as $sClass => $aMessages)
  2314. {
  2315. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  2316. echo "<ul class=\"treeview\">\n";
  2317. $i = 0;
  2318. foreach ($aMessages as $sMsg)
  2319. {
  2320. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  2321. $i++;
  2322. }
  2323. echo "</ul>\n";
  2324. }
  2325. echo "<p>Aborting...</p>\n";
  2326. echo "</div>\n";
  2327. exit;
  2328. }
  2329. }
  2330. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  2331. {
  2332. if (empty($sRepairUrl)) return;
  2333. // By design, some queries might be blank, we have to ignore them
  2334. $aCleanFixes = array();
  2335. foreach($aSQLFixes as $sSQLFix)
  2336. {
  2337. if (!empty($sSQLFix))
  2338. {
  2339. $aCleanFixes[] = $sSQLFix;
  2340. }
  2341. }
  2342. if (count($aCleanFixes) == 0) return;
  2343. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  2344. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes), ENT_QUOTES, 'UTF-8')."\">\n";
  2345. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  2346. echo "</form>\n";
  2347. }
  2348. public static function DBExists($bMustBeComplete = true)
  2349. {
  2350. // returns true if at least one table exists
  2351. //
  2352. if (!CMDBSource::IsDB(self::$m_sDBName))
  2353. {
  2354. return false;
  2355. }
  2356. CMDBSource::SelectDB(self::$m_sDBName);
  2357. $aFound = array();
  2358. $aMissing = array();
  2359. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2360. {
  2361. if (CMDBSource::IsTable($sTable))
  2362. {
  2363. $aFound[] = $sTable;
  2364. }
  2365. else
  2366. {
  2367. $aMissing[] = $sTable;
  2368. }
  2369. }
  2370. if (count($aFound) == 0)
  2371. {
  2372. // no expected table has been found
  2373. return false;
  2374. }
  2375. else
  2376. {
  2377. if (count($aMissing) == 0)
  2378. {
  2379. // the database is complete (still, could be some fields missing!)
  2380. return true;
  2381. }
  2382. else
  2383. {
  2384. // not all the tables, could be an older version
  2385. if ($bMustBeComplete)
  2386. {
  2387. return false;
  2388. }
  2389. else
  2390. {
  2391. return true;
  2392. }
  2393. }
  2394. }
  2395. }
  2396. public static function DBDrop()
  2397. {
  2398. $bDropEntireDB = true;
  2399. if (!empty(self::$m_sTablePrefix))
  2400. {
  2401. // Do drop only tables corresponding to the sub-database (table prefix)
  2402. // then possibly drop the DB itself (if no table remain)
  2403. foreach (CMDBSource::EnumTables() as $sTable)
  2404. {
  2405. // perform a case insensitive test because on Windows the table names become lowercase :-(
  2406. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  2407. {
  2408. CMDBSource::DropTable($sTable);
  2409. }
  2410. else
  2411. {
  2412. // There is at least one table which is out of the scope of the current application
  2413. $bDropEntireDB = false;
  2414. }
  2415. }
  2416. }
  2417. if ($bDropEntireDB)
  2418. {
  2419. CMDBSource::DropDB(self::$m_sDBName);
  2420. }
  2421. }
  2422. public static function DBCreate()
  2423. {
  2424. // Note: we have to check if the DB does exist, because we may share the DB
  2425. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  2426. if (!CMDBSource::IsDB(self::$m_sDBName))
  2427. {
  2428. CMDBSource::CreateDB(self::$m_sDBName);
  2429. }
  2430. self::DBCreateTables();
  2431. self::DBCreateViews();
  2432. }
  2433. protected static function DBCreateTables()
  2434. {
  2435. list($aErrors, $aSugFix) = self::DBCheckFormat();
  2436. $aSQL = array();
  2437. foreach ($aSugFix as $sClass => $aTarget)
  2438. {
  2439. foreach ($aTarget as $aQueries)
  2440. {
  2441. foreach ($aQueries as $sQuery)
  2442. {
  2443. if (!empty($sQuery))
  2444. {
  2445. //$aSQL[] = $sQuery;
  2446. // forces a refresh of cached information
  2447. CMDBSource::CreateTable($sQuery);
  2448. }
  2449. }
  2450. }
  2451. }
  2452. // does not work -how to have multiple statements in a single query?
  2453. // $sDoCreateAll = implode(" ; ", $aSQL);
  2454. }
  2455. protected static function DBCreateViews()
  2456. {
  2457. list($aErrors, $aSugFix) = self::DBCheckViews();
  2458. $aSQL = array();
  2459. foreach ($aSugFix as $sClass => $aTarget)
  2460. {
  2461. foreach ($aTarget as $aQueries)
  2462. {
  2463. foreach ($aQueries as $sQuery)
  2464. {
  2465. if (!empty($sQuery))
  2466. {
  2467. //$aSQL[] = $sQuery;
  2468. // forces a refresh of cached information
  2469. CMDBSource::CreateTable($sQuery);
  2470. }
  2471. }
  2472. }
  2473. }
  2474. }
  2475. public static function DBDump()
  2476. {
  2477. $aDataDump = array();
  2478. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2479. {
  2480. $aRows = CMDBSource::DumpTable($sTable);
  2481. $aDataDump[$sTable] = $aRows;
  2482. }
  2483. return $aDataDump;
  2484. }
  2485. /*
  2486. * Determines wether the target DB is frozen or not
  2487. */
  2488. public static function DBIsReadOnly()
  2489. {
  2490. // Improvement: check the mySQL variable -> Read-only
  2491. if (UserRights::IsAdministrator())
  2492. {
  2493. return (!self::DBHasAccess(ACCESS_ADMIN_WRITE));
  2494. }
  2495. else
  2496. {
  2497. return (!self::DBHasAccess(ACCESS_USER_WRITE));
  2498. }
  2499. }
  2500. public static function DBHasAccess($iRequested = ACCESS_FULL)
  2501. {
  2502. $iMode = self::$m_oConfig->Get('access_mode');
  2503. if (($iMode & $iRequested) == 0) return false;
  2504. return true;
  2505. }
  2506. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  2507. {
  2508. $sValue = Dict::S($sKey, 'x-no-nothing');
  2509. if ($sValue == 'x-no-nothing')
  2510. {
  2511. $bNotInDico = true;
  2512. $sValue = $sValueFromOldSystem;
  2513. if (strlen($sValue) == 0)
  2514. {
  2515. $sValue = $sDefaultValue;
  2516. }
  2517. }
  2518. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  2519. }
  2520. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  2521. {
  2522. $sRes = '';
  2523. $sRes .= "// Dictionnay conventions\n";
  2524. $sRes .= htmlentities("// Class:<class_name>\n", ENT_QUOTES, 'UTF-8');
  2525. $sRes .= htmlentities("// Class:<class_name>+\n", ENT_QUOTES, 'UTF-8');
  2526. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n", ENT_QUOTES, 'UTF-8');
  2527. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n", ENT_QUOTES, 'UTF-8');
  2528. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n", ENT_QUOTES, 'UTF-8');
  2529. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n", ENT_QUOTES, 'UTF-8');
  2530. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n", ENT_QUOTES, 'UTF-8');
  2531. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n", ENT_QUOTES, 'UTF-8');
  2532. $sRes .= "\n";
  2533. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  2534. // Need to invent the "module", to characterize the origins of a class
  2535. if (strlen($sModules) == 0)
  2536. {
  2537. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  2538. }
  2539. else
  2540. {
  2541. $aModules = explode(', ', $sModules);
  2542. }
  2543. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2544. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  2545. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2546. foreach ($aModules as $sCategory)
  2547. {
  2548. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2549. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  2550. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2551. $sRes .= "//\n";
  2552. $sRes .= "\n";
  2553. foreach (self::GetClasses($sCategory) as $sClass)
  2554. {
  2555. if (!self::HasTable($sClass)) continue;
  2556. $bNotInDico = false;
  2557. $sClassRes = "//\n";
  2558. $sClassRes .= "// Class: $sClass\n";
  2559. $sClassRes .= "//\n";
  2560. $sClassRes .= "\n";
  2561. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  2562. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  2563. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  2564. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2565. {
  2566. // Skip this attribute if not originaly defined in this class
  2567. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2568. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  2569. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  2570. if ($oAttDef instanceof AttributeEnum)
  2571. {
  2572. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  2573. {
  2574. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  2575. {
  2576. if (array_key_exists('label', $aStateData))
  2577. {
  2578. $sValue = $aStateData['label'];
  2579. }
  2580. else
  2581. {
  2582. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  2583. }
  2584. if (array_key_exists('description', $aStateData))
  2585. {
  2586. $sValuePlus = $aStateData['description'];
  2587. }
  2588. else
  2589. {
  2590. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  2591. }
  2592. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  2593. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  2594. }
  2595. }
  2596. else
  2597. {
  2598. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  2599. {
  2600. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  2601. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  2602. }
  2603. }
  2604. }
  2605. }
  2606. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  2607. {
  2608. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  2609. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  2610. }
  2611. $sClassRes .= "));\n";
  2612. $sClassRes .= "\n";
  2613. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  2614. {
  2615. $sRes .= $sClassRes;
  2616. }
  2617. }
  2618. }
  2619. return $sRes;
  2620. }
  2621. public static function DBCheckFormat()
  2622. {
  2623. $aErrors = array();
  2624. $aSugFix = array();
  2625. foreach (self::GetClasses() as $sClass)
  2626. {
  2627. if (!self::HasTable($sClass)) continue;
  2628. // Check that the table exists
  2629. //
  2630. $sTable = self::DBGetTable($sClass);
  2631. $sKeyField = self::DBGetKey($sClass);
  2632. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  2633. if (!CMDBSource::IsTable($sTable))
  2634. {
  2635. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  2636. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  2637. }
  2638. // Check that the key field exists
  2639. //
  2640. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  2641. {
  2642. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  2643. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  2644. }
  2645. else
  2646. {
  2647. // Check the key field properties
  2648. //
  2649. if (!CMDBSource::IsKey($sTable, $sKeyField))
  2650. {
  2651. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  2652. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  2653. }
  2654. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  2655. {
  2656. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  2657. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  2658. }
  2659. }
  2660. // Check that any defined field exists
  2661. //
  2662. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  2663. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2664. {
  2665. // Skip this attribute if not originaly defined in this class
  2666. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2667. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2668. {
  2669. $bIndexNeeded = $oAttDef->RequiresIndex();
  2670. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  2671. if (!CMDBSource::IsField($sTable, $sField))
  2672. {
  2673. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  2674. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  2675. if ($bIndexNeeded)
  2676. {
  2677. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2678. }
  2679. }
  2680. else
  2681. {
  2682. // The field already exists, does it have the relevant properties?
  2683. //
  2684. $bToBeChanged = false;
  2685. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  2686. {
  2687. $bToBeChanged = true;
  2688. if ($oAttDef->IsNullAllowed())
  2689. {
  2690. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  2691. }
  2692. else
  2693. {
  2694. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  2695. }
  2696. }
  2697. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  2698. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  2699. {
  2700. $bToBeChanged = true;
  2701. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  2702. }
  2703. if ($bToBeChanged)
  2704. {
  2705. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  2706. }
  2707. // Create indexes (external keys only... so far)
  2708. //
  2709. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField))
  2710. {
  2711. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  2712. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2713. }
  2714. }
  2715. }
  2716. }
  2717. }
  2718. return array($aErrors, $aSugFix);
  2719. }
  2720. public static function DBCheckViews()
  2721. {
  2722. $aErrors = array();
  2723. $aSugFix = array();
  2724. // Reporting views (must be created after any other table)
  2725. //
  2726. foreach (self::GetClasses('bizmodel') as $sClass)
  2727. {
  2728. $sView = self::DBGetView($sClass);
  2729. if (CMDBSource::IsTable($sView))
  2730. {
  2731. // Check that the view is complete
  2732. //
  2733. $bIsComplete = true;
  2734. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2735. {
  2736. foreach($oAttDef->GetSQLExpressions() as $sSuffix => $sTrash)
  2737. {
  2738. $sCol = $sAttCode.$sSuffix;
  2739. if (!CMDBSource::IsField($sView, $sCol))
  2740. {
  2741. $bIsComplete = false;
  2742. $aErrors[$sClass][$sAttCode][] = "field '$sCol' could not be found in view '$sView'";
  2743. $aSugFix[$sClass][$sAttCode][] = "";
  2744. }
  2745. }
  2746. }
  2747. if (!$bIsComplete)
  2748. {
  2749. // Rework the view
  2750. //
  2751. $oFilter = new DBObjectSearch($sClass, '');
  2752. $oFilter->AllowAllData();
  2753. $sSQL = self::MakeSelectQuery($oFilter);
  2754. $aErrors[$sClass]['*'][] = "View '$sView' is currently not complete";
  2755. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  2756. }
  2757. }
  2758. else
  2759. {
  2760. // Create the view
  2761. //
  2762. $oFilter = new DBObjectSearch($sClass, '');
  2763. $oFilter->AllowAllData();
  2764. $sSQL = self::MakeSelectQuery($oFilter);
  2765. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  2766. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  2767. }
  2768. }
  2769. return array($aErrors, $aSugFix);
  2770. }
  2771. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  2772. {
  2773. $sRootClass = self::GetRootClass($sClass);
  2774. $sTable = self::DBGetTable($sClass);
  2775. $sKeyField = self::DBGetKey($sClass);
  2776. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2777. {
  2778. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2779. }
  2780. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2781. if (count($aWrongRecords) == 0) return;
  2782. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2783. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2784. foreach ($aWrongRecords as $iRecordId)
  2785. {
  2786. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2787. {
  2788. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2789. {
  2790. case 'Delete':
  2791. // Already planned for a deletion
  2792. // Let's concatenate the errors description together
  2793. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2794. break;
  2795. case 'Update':
  2796. // Let's plan a deletion
  2797. break;
  2798. }
  2799. }
  2800. else
  2801. {
  2802. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2803. }
  2804. if (!$bProcessingFriends)
  2805. {
  2806. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2807. {
  2808. // Something new to be deleted...
  2809. $iNewDelCount++;
  2810. }
  2811. }
  2812. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2813. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2814. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2815. $aPlannedDel[$sTable][] = $iRecordId;
  2816. }
  2817. // Now make sure that we would delete the records of the other tables for that class
  2818. //
  2819. if (!$bProcessingFriends)
  2820. {
  2821. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2822. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2823. {
  2824. $sFriendTable = self::DBGetTable($sFriendClass);
  2825. $sFriendKey = self::DBGetKey($sFriendClass);
  2826. // skip the current table
  2827. if ($sFriendTable == $sTable) continue;
  2828. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2829. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2830. }
  2831. }
  2832. }
  2833. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2834. {
  2835. $sRootClass = self::GetRootClass($sClass);
  2836. $sTable = self::DBGetTable($sClass);
  2837. $sKeyField = self::DBGetKey($sClass);
  2838. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2839. {
  2840. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2841. }
  2842. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2843. if (count($aWrongRecords) == 0) return;
  2844. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2845. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2846. foreach ($aWrongRecords as $iRecordId)
  2847. {
  2848. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2849. {
  2850. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2851. {
  2852. case 'Delete':
  2853. // No need to update, the record will be deleted!
  2854. break;
  2855. case 'Update':
  2856. // Already planned for an update
  2857. // Add this new update spec to the list
  2858. $bFoundSameSpec = false;
  2859. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2860. {
  2861. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2862. {
  2863. $bFoundSameSpec = true;
  2864. }
  2865. }
  2866. if (!$bFoundSameSpec)
  2867. {
  2868. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2869. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2870. }
  2871. break;
  2872. }
  2873. }
  2874. else
  2875. {
  2876. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2877. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2878. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2879. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2880. }
  2881. }
  2882. }
  2883. // returns the count of records found for deletion
  2884. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2885. {
  2886. foreach (self::GetClasses() as $sClass)
  2887. {
  2888. if (!self::HasTable($sClass)) continue;
  2889. $sRootClass = self::GetRootClass($sClass);
  2890. $sTable = self::DBGetTable($sClass);
  2891. $sKeyField = self::DBGetKey($sClass);
  2892. if (!self::IsStandaloneClass($sClass))
  2893. {
  2894. if (self::IsRootClass($sClass))
  2895. {
  2896. // Check that the final class field contains the name of a class which inherited from the current class
  2897. //
  2898. $sFinalClassField = self::DBGetClassField($sClass);
  2899. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2900. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2901. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2902. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2903. }
  2904. else
  2905. {
  2906. $sRootTable = self::DBGetTable($sRootClass);
  2907. $sRootKey = self::DBGetKey($sRootClass);
  2908. $sFinalClassField = self::DBGetClassField($sRootClass);
  2909. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2910. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2911. // Check that any record found here has its counterpart in the root table
  2912. // and which refers to a child class
  2913. //
  2914. $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";
  2915. 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);
  2916. // Check that any record found in the root table and referring to a child class
  2917. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2918. //
  2919. $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)";
  2920. 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);
  2921. }
  2922. }
  2923. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2924. {
  2925. // Skip this attribute if not defined in this table
  2926. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2927. if ($oAttDef->IsExternalKey())
  2928. {
  2929. // Check that any external field is pointing to an existing object
  2930. //
  2931. $sRemoteClass = $oAttDef->GetTargetClass();
  2932. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2933. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2934. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2935. $sExtKeyField = current($aCols); // get the first column for an external key
  2936. // Note: a class/table may have an external key on itself
  2937. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2938. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2939. if ($oAttDef->IsNullAllowed())
  2940. {
  2941. // Exclude the records pointing to 0/null from the errors
  2942. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2943. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2944. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2945. }
  2946. else
  2947. {
  2948. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2949. }
  2950. // Do almost the same, taking into account the records planned for deletion
  2951. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2952. {
  2953. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2954. // but in that case you won't be able to track the root cause (cascading)
  2955. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2956. if ($oAttDef->IsNullAllowed())
  2957. {
  2958. // Exclude the records pointing to 0/null from the errors
  2959. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2960. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2961. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2962. }
  2963. else
  2964. {
  2965. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2966. }
  2967. }
  2968. }
  2969. else if ($oAttDef->IsDirectField())
  2970. {
  2971. // Check that the values fit the allowed values
  2972. //
  2973. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2974. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2975. {
  2976. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2977. $aCols = $oAttDef->GetSQLExpressions(); // Workaround a PHP bug: sometimes issuing a Notice if invoking current(somefunc())
  2978. $sMyAttributeField = current($aCols); // get the first column for the moment
  2979. $sDefaultValue = $oAttDef->GetDefaultValue();
  2980. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2981. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2982. }
  2983. }
  2984. }
  2985. }
  2986. }
  2987. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2988. {
  2989. // Records in error, and action to be taken: delete or update
  2990. // by RootClass/Table/Record
  2991. $aErrorsAndFixes = array();
  2992. // Records to be ignored in the current/next pass
  2993. // by Table = array of RecordId
  2994. $aPlannedDel = array();
  2995. // Count of errors in the next pass: no error means that we can leave...
  2996. $iErrorCount = 0;
  2997. // Limit in case of a bug in the algorythm
  2998. $iLoopCount = 0;
  2999. $iNewDelCount = 1; // startup...
  3000. while ($iNewDelCount > 0)
  3001. {
  3002. $iNewDelCount = 0;
  3003. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  3004. $iErrorCount += $iNewDelCount;
  3005. // Safety net #1 - limit the planned deletions
  3006. //
  3007. $iMaxDel = 1000;
  3008. $iPlannedDel = 0;
  3009. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  3010. {
  3011. $iPlannedDel += count($aPlannedDelOnTable);
  3012. }
  3013. if ($iPlannedDel > $iMaxDel)
  3014. {
  3015. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  3016. break;
  3017. }
  3018. // Safety net #2 - limit the iterations
  3019. //
  3020. $iLoopCount++;
  3021. $iMaxLoops = 10;
  3022. if ($iLoopCount > $iMaxLoops)
  3023. {
  3024. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  3025. break;
  3026. }
  3027. }
  3028. // Display the results
  3029. //
  3030. $iIssueCount = 0;
  3031. $aFixesDelete = array();
  3032. $aFixesUpdate = array();
  3033. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  3034. {
  3035. foreach ($aTables as $sTable => $aRecords)
  3036. {
  3037. foreach ($aRecords as $iRecord => $aError)
  3038. {
  3039. $sAction = $aError['Action'];
  3040. $sReason = $aError['Reason'];
  3041. $iPass = $aError['Pass'];
  3042. switch ($sAction)
  3043. {
  3044. case 'Delete':
  3045. $sActionDetails = "";
  3046. $aFixesDelete[$sTable][] = $iRecord;
  3047. break;
  3048. case 'Update':
  3049. $aUpdateDesc = array();
  3050. foreach($aError['Action_Details'] as $aUpdateSpec)
  3051. {
  3052. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  3053. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  3054. }
  3055. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  3056. break;
  3057. default:
  3058. $sActionDetails = "bug: unknown action '$sAction'";
  3059. }
  3060. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  3061. $iIssueCount++;
  3062. }
  3063. }
  3064. }
  3065. if ($iIssueCount > 0)
  3066. {
  3067. // Build the queries to fix in the database
  3068. //
  3069. // First step, be able to get class data out of the table name
  3070. // Could be optimized, because we've made the job earlier... but few benefits, so...
  3071. $aTable2ClassProp = array();
  3072. foreach (self::GetClasses() as $sClass)
  3073. {
  3074. if (!self::HasTable($sClass)) continue;
  3075. $sRootClass = self::GetRootClass($sClass);
  3076. $sTable = self::DBGetTable($sClass);
  3077. $sKeyField = self::DBGetKey($sClass);
  3078. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  3079. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  3080. }
  3081. // Second step, build a flat list of SQL queries
  3082. $aSQLFixes = array();
  3083. $iPlannedUpdate = 0;
  3084. foreach ($aFixesUpdate as $sTable => $aColumns)
  3085. {
  3086. foreach ($aColumns as $sColumn => $aNewValues)
  3087. {
  3088. foreach ($aNewValues as $sNewValue => $aRecords)
  3089. {
  3090. $iPlannedUpdate += count($aRecords);
  3091. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3092. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3093. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  3094. }
  3095. }
  3096. }
  3097. $iPlannedDel = 0;
  3098. foreach ($aFixesDelete as $sTable => $aRecords)
  3099. {
  3100. $iPlannedDel += count($aRecords);
  3101. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  3102. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  3103. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  3104. }
  3105. // Report the results
  3106. //
  3107. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  3108. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  3109. // #@# later -> this is the responsibility of the caller to format the output
  3110. echo "<ul class=\"treeview\">\n";
  3111. foreach ($aIssues as $sIssueDesc)
  3112. {
  3113. echo "<li>$sIssueDesc</li>\n";
  3114. }
  3115. echo "</ul>\n";
  3116. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  3117. echo "<p>Aborting...</p>\n";
  3118. echo "</div>\n";
  3119. exit;
  3120. }
  3121. }
  3122. public static function Startup($sConfigFile, $bModelOnly = false)
  3123. {
  3124. self::LoadConfig($sConfigFile);
  3125. $aInterfaces = array('iApplicationUIExtension', 'iApplicationObjectExtension');
  3126. foreach($aInterfaces as $sInterface)
  3127. {
  3128. self::$m_aExtensionClasses[$sInterface] = array();
  3129. }
  3130. foreach(get_declared_classes() as $sPHPClass)
  3131. {
  3132. $oRefClass = new ReflectionClass($sPHPClass);
  3133. $oExtensionInstance = null;
  3134. foreach($aInterfaces as $sInterface)
  3135. {
  3136. if ($oRefClass->implementsInterface($sInterface))
  3137. {
  3138. if (is_null($oExtensionInstance))
  3139. {
  3140. $oExtensionInstance = new $sPHPClass;
  3141. }
  3142. self::$m_aExtensionClasses[$sInterface][] = $oExtensionInstance;
  3143. }
  3144. }
  3145. }
  3146. if ($bModelOnly) return;
  3147. CMDBSource::SelectDB(self::$m_sDBName);
  3148. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  3149. // To be deprecated
  3150. self::InitPlugins();
  3151. foreach(get_declared_classes() as $sPHPClass)
  3152. {
  3153. if (is_subclass_of($sPHPClass, 'ModuleHandlerAPI'))
  3154. {
  3155. $aCallSpec = array($sPHPClass, 'OnMetaModelStarted');
  3156. call_user_func_array($aCallSpec, array());
  3157. }
  3158. }
  3159. if (false)
  3160. {
  3161. echo "Debug<br/>\n";
  3162. self::static_var_dump();
  3163. }
  3164. }
  3165. public static function LoadConfig($sConfigFile)
  3166. {
  3167. self::$m_oConfig = new Config($sConfigFile);
  3168. // Set log ASAP
  3169. if (self::$m_oConfig->GetLogGlobal())
  3170. {
  3171. if (self::$m_oConfig->GetLogIssue())
  3172. {
  3173. self::$m_bLogIssue = true;
  3174. IssueLog::Enable(APPROOT.'/error.log');
  3175. }
  3176. self::$m_bLogNotification = self::$m_oConfig->GetLogNotification();
  3177. self::$m_bLogWebService = self::$m_oConfig->GetLogWebService();
  3178. ToolsLog::Enable(APPROOT.'/tools.log');
  3179. }
  3180. else
  3181. {
  3182. self::$m_bLogIssue = false;
  3183. self::$m_bLogNotification = false;
  3184. self::$m_bLogWebService = false;
  3185. }
  3186. if (self::$m_oConfig->GetLogKPIDuration())
  3187. {
  3188. ExecutionKPI::EnableDuration();
  3189. }
  3190. if (self::$m_oConfig->GetLogKPIMemory())
  3191. {
  3192. ExecutionKPI::EnableMemory();
  3193. }
  3194. self::$m_bTraceQueries = self::$m_oConfig->GetDebugQueries();
  3195. self::$m_bQueryCacheEnabled = self::$m_oConfig->GetQueryCacheEnabled();
  3196. self::$m_bSkipCheckToWrite = self::$m_oConfig->Get('skip_check_to_write');
  3197. self::$m_bSkipCheckExtKeys = self::$m_oConfig->Get('skip_check_ext_keys');
  3198. // Note: load the dictionary as soon as possible, because it might be
  3199. // needed when some error occur
  3200. if (!Dict::InCache())
  3201. {
  3202. foreach (self::$m_oConfig->GetDictionaries() as $sModule => $sToInclude)
  3203. {
  3204. self::Plugin($sConfigFile, 'dictionaries', $sToInclude);
  3205. }
  3206. Dict::InitCache();
  3207. }
  3208. // Set the language... after the dictionaries have been loaded!
  3209. Dict::SetDefaultLanguage(self::$m_oConfig->GetDefaultLanguage());
  3210. // Romain: this is the only way I've found to cope with the fact that
  3211. // classes have to be derived from cmdbabstract (to be editable in the UI)
  3212. require_once(APPROOT.'/application/cmdbabstract.class.inc.php');
  3213. foreach (self::$m_oConfig->GetAppModules() as $sModule => $sToInclude)
  3214. {
  3215. self::Plugin($sConfigFile, 'application', $sToInclude);
  3216. }
  3217. foreach (self::$m_oConfig->GetDataModels() as $sModule => $sToInclude)
  3218. {
  3219. self::Plugin($sConfigFile, 'business', $sToInclude);
  3220. }
  3221. foreach (self::$m_oConfig->GetWebServiceCategories() as $sModule => $sToInclude)
  3222. {
  3223. self::Plugin($sConfigFile, 'webservice', $sToInclude);
  3224. }
  3225. foreach (self::$m_oConfig->GetAddons() as $sModule => $sToInclude)
  3226. {
  3227. self::Plugin($sConfigFile, 'addons', $sToInclude);
  3228. }
  3229. $sServer = self::$m_oConfig->GetDBHost();
  3230. $sUser = self::$m_oConfig->GetDBUser();
  3231. $sPwd = self::$m_oConfig->GetDBPwd();
  3232. $sSource = self::$m_oConfig->GetDBName();
  3233. $sTablePrefix = self::$m_oConfig->GetDBSubname();
  3234. $sCharacterSet = self::$m_oConfig->GetDBCharacterSet();
  3235. $sCollation = self::$m_oConfig->GetDBCollation();
  3236. $oKPI = new ExecutionKPI();
  3237. // The include have been included, let's browse the existing classes and
  3238. // develop some data based on the proposed model
  3239. self::InitClasses($sTablePrefix);
  3240. $oKPI->ComputeAndReport('Initialization of Data model structures');
  3241. self::$m_sDBName = $sSource;
  3242. self::$m_sTablePrefix = $sTablePrefix;
  3243. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  3244. CMDBSource::SetCharacterSet($sCharacterSet, $sCollation);
  3245. }
  3246. public static function GetModuleSetting($sModule, $sProperty, $defaultvalue = null)
  3247. {
  3248. return self::$m_oConfig->GetModuleSetting($sModule, $sProperty, $defaultvalue);
  3249. }
  3250. public static function GetConfig()
  3251. {
  3252. return self::$m_oConfig;
  3253. }
  3254. protected static $m_aExtensionClasses = array();
  3255. protected static $m_aPlugins = array();
  3256. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  3257. {
  3258. self::$m_aPlugins[$sName] = array(
  3259. 'type' => $sType,
  3260. 'init' => $aInitCallSpec,
  3261. );
  3262. }
  3263. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  3264. {
  3265. $sFirstChar = substr($sToInclude, 0, 1);
  3266. $sSecondChar = substr($sToInclude, 1, 1);
  3267. if (($sFirstChar != '/') && ($sFirstChar != '\\') && ($sSecondChar != ':'))
  3268. {
  3269. // It is a relative path, prepend APPROOT
  3270. if (substr($sToInclude, 0, 3) == '../')
  3271. {
  3272. // Preserve compatibility with config files written before 1.0.1
  3273. // Replace '../' by '<root>/'
  3274. $sFile = APPROOT.'/'.substr($sToInclude, 3);
  3275. }
  3276. else
  3277. {
  3278. $sFile = APPROOT.'/'.$sToInclude;
  3279. }
  3280. }
  3281. else
  3282. {
  3283. // Leave as is - should be an absolute path
  3284. $sFile = $sToInclude;
  3285. }
  3286. if (!file_exists($sFile))
  3287. {
  3288. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sFile));
  3289. }
  3290. require_once($sFile);
  3291. }
  3292. // #@# to be deprecated!
  3293. //
  3294. protected static function InitPlugins()
  3295. {
  3296. foreach(self::$m_aPlugins as $sName => $aData)
  3297. {
  3298. $aCallSpec = @$aData['init'];
  3299. if (count($aCallSpec) == 2)
  3300. {
  3301. if (!is_callable($aCallSpec))
  3302. {
  3303. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  3304. }
  3305. call_user_func($aCallSpec);
  3306. }
  3307. }
  3308. }
  3309. // Building an object
  3310. //
  3311. //
  3312. private static $aQueryCacheGetObject = array();
  3313. private static $aQueryCacheGetObjectHits = array();
  3314. public static function GetQueryCacheStatus()
  3315. {
  3316. $aRes = array();
  3317. $iTotalHits = 0;
  3318. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  3319. {
  3320. $aRes[] = "$sClass: $iHits";
  3321. $iTotalHits += $iHits;
  3322. }
  3323. return $iTotalHits.' ('.implode(', ', $aRes).')';
  3324. }
  3325. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false)
  3326. {
  3327. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  3328. {
  3329. // NOTE: Quick and VERY dirty caching mechanism which relies on
  3330. // the fact that the string '987654321' will never appear in the
  3331. // standard query
  3332. // This will be replaced for sure with a prepared statement
  3333. // or a view... next optimization to come!
  3334. $oFilter = new DBObjectSearch($sClass);
  3335. $oFilter->AddCondition('id', 987654321, '=');
  3336. if ($bAllowAllData)
  3337. {
  3338. $oFilter->AllowAllData();
  3339. }
  3340. $sSQL = self::MakeSelectQuery($oFilter);
  3341. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  3342. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  3343. }
  3344. else
  3345. {
  3346. $sSQL = self::$aQueryCacheGetObject[$sClass];
  3347. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  3348. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  3349. }
  3350. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  3351. $res = CMDBSource::Query($sSQL);
  3352. $aRow = CMDBSource::FetchArray($res);
  3353. CMDBSource::FreeResult($res);
  3354. if ($bMustBeFound && empty($aRow))
  3355. {
  3356. throw new CoreException("No result for the single row query: '$sSQL'");
  3357. }
  3358. return $aRow;
  3359. }
  3360. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '', $aExtendedDataSpec = null)
  3361. {
  3362. self::_check_subclass($sClass);
  3363. if (strlen($sClassAlias) == 0)
  3364. {
  3365. $sClassAlias = $sClass;
  3366. }
  3367. // Compound objects: if available, get the final object class
  3368. //
  3369. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  3370. {
  3371. // Either this is a bug (forgot to specify a root class with a finalclass field
  3372. // Or this is the expected behavior, because the object is not made of several tables
  3373. }
  3374. elseif (empty($aRow[$sClassAlias."finalclass"]))
  3375. {
  3376. // The data is missing in the DB
  3377. // @#@ possible improvement: check that the class is valid !
  3378. $sRootClass = self::GetRootClass($sClass);
  3379. $sFinalClassField = self::DBGetClassField($sRootClass);
  3380. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  3381. }
  3382. else
  3383. {
  3384. // do the job for the real target class
  3385. $sClass = $aRow[$sClassAlias."finalclass"];
  3386. }
  3387. return new $sClass($aRow, $sClassAlias, $aExtendedDataSpec);
  3388. }
  3389. public static function GetObject($sClass, $iKey, $bMustBeFound = true, $bAllowAllData = false)
  3390. {
  3391. self::_check_subclass($sClass);
  3392. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound, $bAllowAllData);
  3393. if (empty($aRow))
  3394. {
  3395. return null;
  3396. }
  3397. return self::GetObjectByRow($sClass, $aRow);
  3398. }
  3399. public static function GetObjectByName($sClass, $sName, $bMustBeFound = true)
  3400. {
  3401. self::_check_subclass($sClass);
  3402. $oObjSearch = new DBObjectSearch($sClass);
  3403. $oObjSearch->AddNameCondition($sName);
  3404. $oSet = new DBObjectSet($oObjSearch);
  3405. if ($oSet->Count() != 1)
  3406. {
  3407. if ($bMustBeFound) throw new CoreException('Failed to get an object by its name', array('class'=>$sClass, 'name'=>$sName));
  3408. return null;
  3409. }
  3410. $oObj = $oSet->fetch();
  3411. return $oObj;
  3412. }
  3413. static protected $m_aCacheObjectByColumn = array();
  3414. public static function GetObjectByColumn($sClass, $sAttCode, $value, $bMustBeFoundUnique = true)
  3415. {
  3416. if (!isset(self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value]))
  3417. {
  3418. self::_check_subclass($sClass);
  3419. $oObjSearch = new DBObjectSearch($sClass);
  3420. $oObjSearch->AddCondition($sAttCode, $value, '=');
  3421. $oSet = new DBObjectSet($oObjSearch);
  3422. if ($oSet->Count() == 1)
  3423. {
  3424. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = $oSet->fetch();
  3425. }
  3426. else
  3427. {
  3428. if ($bMustBeFoundUnique) throw new CoreException('Failed to get an object by column', array('class'=>$sClass, 'attcode'=>$sAttCode, 'value'=>$value, 'matches' => $oSet->Count()));
  3429. self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value] = null;
  3430. }
  3431. }
  3432. return self::$m_aCacheObjectByColumn[$sClass][$sAttCode][$value];
  3433. }
  3434. public static function GetObjectFromOQL($sQuery, $aParams = null, $bAllowAllData = false)
  3435. {
  3436. $oFilter = DBObjectSearch::FromOQL($sQuery, $aParams);
  3437. if ($bAllowAllData)
  3438. {
  3439. $oFilter->AllowAllData();
  3440. }
  3441. $oSet = new DBObjectSet($oFilter);
  3442. $oObject = $oSet->Fetch();
  3443. return $oObject;
  3444. }
  3445. public static function GetHyperLink($sTargetClass, $iKey)
  3446. {
  3447. if ($iKey < 0)
  3448. {
  3449. return "$sTargetClass: $iKey (invalid value)";
  3450. }
  3451. $oObj = self::GetObject($sTargetClass, $iKey, false);
  3452. if (is_null($oObj))
  3453. {
  3454. return "$sTargetClass: $iKey (not found)";
  3455. }
  3456. return $oObj->GetHyperLink();
  3457. }
  3458. public static function NewObject($sClass)
  3459. {
  3460. self::_check_subclass($sClass);
  3461. return new $sClass();
  3462. }
  3463. public static function GetNextKey($sClass)
  3464. {
  3465. $sRootClass = MetaModel::GetRootClass($sClass);
  3466. $sRootTable = MetaModel::DBGetTable($sRootClass);
  3467. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  3468. return $iNextKey;
  3469. }
  3470. public static function BulkDelete(DBObjectSearch $oFilter)
  3471. {
  3472. $sSQL = self::MakeDeleteQuery($oFilter);
  3473. if (!self::DBIsReadOnly())
  3474. {
  3475. CMDBSource::Query($sSQL);
  3476. }
  3477. }
  3478. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  3479. {
  3480. // $aValues is an array of $sAttCode => $value
  3481. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  3482. if (!self::DBIsReadOnly())
  3483. {
  3484. CMDBSource::Query($sSQL);
  3485. }
  3486. }
  3487. // Links
  3488. //
  3489. //
  3490. public static function EnumReferencedClasses($sClass)
  3491. {
  3492. self::_check_subclass($sClass);
  3493. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  3494. $aResult = array();
  3495. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  3496. {
  3497. if ($oAttDef->IsExternalKey())
  3498. {
  3499. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  3500. }
  3501. }
  3502. return $aResult;
  3503. }
  3504. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  3505. {
  3506. self::_check_subclass($sClass);
  3507. if ($bSkipLinkingClasses)
  3508. {
  3509. $aLinksClasses = self::EnumLinksClasses();
  3510. }
  3511. // 1-N links (referencing my class), array of sClass => array of sAttcode
  3512. $aResult = array();
  3513. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3514. {
  3515. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  3516. $aExtKeys = array();
  3517. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3518. {
  3519. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3520. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  3521. {
  3522. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  3523. // Ok, I want this one
  3524. $aExtKeys[$sAttCode] = $oAttDef;
  3525. }
  3526. }
  3527. if (count($aExtKeys) != 0)
  3528. {
  3529. $aResult[$sSomeClass] = $aExtKeys;
  3530. }
  3531. }
  3532. return $aResult;
  3533. }
  3534. public static function EnumLinksClasses()
  3535. {
  3536. // Returns a flat array of classes having at least two external keys
  3537. $aResult = array();
  3538. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3539. {
  3540. $iExtKeyCount = 0;
  3541. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3542. {
  3543. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3544. if ($oAttDef->IsExternalKey())
  3545. {
  3546. $iExtKeyCount++;
  3547. }
  3548. }
  3549. if ($iExtKeyCount >= 2)
  3550. {
  3551. $aResult[] = $sSomeClass;
  3552. }
  3553. }
  3554. return $aResult;
  3555. }
  3556. public static function EnumLinkingClasses($sClass = "")
  3557. {
  3558. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  3559. $aResult = array();
  3560. foreach (self::EnumLinksClasses() as $sSomeClass)
  3561. {
  3562. $aTargets = array();
  3563. $bFoundClass = false;
  3564. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  3565. {
  3566. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3567. if ($oAttDef->IsExternalKey())
  3568. {
  3569. $sRemoteClass = $oAttDef->GetTargetClass();
  3570. if (empty($sClass))
  3571. {
  3572. $aTargets[$sAttCode] = $sRemoteClass;
  3573. }
  3574. elseif ($sClass == $sRemoteClass)
  3575. {
  3576. $bFoundClass = true;
  3577. }
  3578. else
  3579. {
  3580. $aTargets[$sAttCode] = $sRemoteClass;
  3581. }
  3582. }
  3583. }
  3584. if (empty($sClass) || $bFoundClass)
  3585. {
  3586. $aResult[$sSomeClass] = $aTargets;
  3587. }
  3588. }
  3589. return $aResult;
  3590. }
  3591. public static function GetLinkLabel($sLinkClass, $sAttCode)
  3592. {
  3593. self::_check_subclass($sLinkClass);
  3594. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  3595. return self::GetLabel($sLinkClass, $sAttCode);
  3596. }
  3597. /**
  3598. * Replaces all the parameters by the values passed in the hash array
  3599. */
  3600. static public function ApplyParams($aInput, $aParams)
  3601. {
  3602. $aSearches = array();
  3603. $aReplacements = array();
  3604. foreach($aParams as $sSearch => $replace)
  3605. {
  3606. // Some environment parameters are objects, we just need scalars
  3607. if (is_object($replace)) continue;
  3608. $aSearches[] = '$'.$sSearch.'$';
  3609. $aReplacements[] = (string) $replace;
  3610. }
  3611. return str_replace($aSearches, $aReplacements, $aInput);
  3612. }
  3613. /**
  3614. * Returns an array of classes implementing the given interface
  3615. */
  3616. public static function EnumPlugins($sInterface)
  3617. {
  3618. if (array_key_exists($sInterface, self::$m_aExtensionClasses))
  3619. {
  3620. return self::$m_aExtensionClasses[$sInterface];
  3621. }
  3622. else
  3623. {
  3624. return array();
  3625. }
  3626. }
  3627. } // class MetaModel
  3628. // Standard attribute lists
  3629. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  3630. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  3631. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  3632. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  3633. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  3634. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  3635. ?>