metamodel.class.php 112 KB

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