metamodel.class.php 115 KB

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