metamodel.class.php 130 KB

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