metamodel.class.php 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823
  1. <?php
  2. // #@# todo: change into class const (see Doctrine)
  3. // Doctrine example
  4. // class toto
  5. // {
  6. // /**
  7. // * VERSION
  8. // */
  9. // const VERSION = '1.0.0';
  10. // }
  11. /**
  12. * add some description here...
  13. *
  14. * @package iTopORM
  15. */
  16. define('ENUM_CHILD_CLASSES_EXCLUDETOP', 1);
  17. /**
  18. * add some description here...
  19. *
  20. * @package iTopORM
  21. */
  22. define('ENUM_CHILD_CLASSES_ALL', 2);
  23. /**
  24. * Specifies that this attribute is hidden in that state
  25. *
  26. * @package iTopORM
  27. */
  28. define('OPT_ATT_HIDDEN', 1);
  29. /**
  30. * Specifies that this attribute is not editable in that state
  31. *
  32. * @package iTopORM
  33. */
  34. define('OPT_ATT_READONLY', 2);
  35. /**
  36. * Specifieds that the attribute must be set (different than default value?) when arriving into that state
  37. *
  38. * @package iTopORM
  39. */
  40. define('OPT_ATT_MANDATORY', 4);
  41. /**
  42. * Specifies that the attribute must change when arriving into that state
  43. *
  44. * @package iTopORM
  45. */
  46. define('OPT_ATT_MUSTCHANGE', 8);
  47. /**
  48. * Specifies that the attribute must be proposed when arriving into that state
  49. *
  50. * @package iTopORM
  51. */
  52. define('OPT_ATT_MUSTPROMPT', 16);
  53. /**
  54. * (API) The objects definitions as well as their mapping to the database
  55. *
  56. * @package iTopORM
  57. * @author Romain Quetiez <romainquetiez@yahoo.fr>
  58. * @author Denis Flaven <denisflave@free.fr>
  59. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  60. * @link www.itop.com
  61. * @since 1.0
  62. * @version 1.1.1.1 $
  63. */
  64. abstract class MetaModel
  65. {
  66. ///////////////////////////////////////////////////////////////////////////
  67. //
  68. // STATIC Members
  69. //
  70. ///////////////////////////////////////////////////////////////////////////
  71. // Purpose: workaround the following limitation = PHP5 does not allow to know the class (derived from the current one)
  72. // from which a static function is called (__CLASS__ and self are interpreted during parsing)
  73. private static function GetCallersPHPClass($sExpectedFunctionName = null)
  74. {
  75. //var_dump(debug_backtrace());
  76. $aBacktrace = debug_backtrace();
  77. // $aBacktrace[0] is where we are
  78. // $aBacktrace[1] is the caller of GetCallersPHPClass
  79. // $aBacktrace[1] is the info we want
  80. if (!empty($sExpectedFunctionName))
  81. {
  82. assert('$aBacktrace[2]["function"] == $sExpectedFunctionName');
  83. }
  84. return $aBacktrace[2]["class"];
  85. }
  86. // Static init -why and how it works
  87. //
  88. // We found the following limitations:
  89. //- it is not possible to define non scalar constants
  90. //- it is not possible to declare a static variable as '= new myclass()'
  91. // Then we had do propose this model, in which a derived (non abstract)
  92. // class should implement Init(), to call InheritAttributes or AddAttribute.
  93. private static function _check_subclass($sClass)
  94. {
  95. // See also IsValidClass()... ???? #@#
  96. // class is mandatory
  97. // (it is not possible to guess it when called as myderived::...)
  98. if (!array_key_exists($sClass, self::$m_aClassParams))
  99. {
  100. throw new CoreException("Unknown class '$sClass', expected a value in {".implode(', ', array_keys(self::$m_aClassParams))."}");
  101. }
  102. }
  103. public static function static_var_dump()
  104. {
  105. var_dump(get_class_vars(__CLASS__));
  106. }
  107. private static $m_bDebugQuery = false;
  108. private static $m_iStackDepthRef = 0;
  109. public static function StartDebugQuery()
  110. {
  111. $aBacktrace = debug_backtrace();
  112. self::$m_iStackDepthRef = count($aBacktrace);
  113. self::$m_bDebugQuery = true;
  114. }
  115. public static function StopDebugQuery()
  116. {
  117. self::$m_bDebugQuery = false;
  118. }
  119. public static function DbgTrace($value)
  120. {
  121. if (!self::$m_bDebugQuery) return;
  122. $aBacktrace = debug_backtrace();
  123. $iCallStackPos = count($aBacktrace) - self::$m_bDebugQuery;
  124. $sIndent = "";
  125. for ($i = 0 ; $i < $iCallStackPos ; $i++)
  126. {
  127. $sIndent .= " .-=^=-. ";
  128. }
  129. $aCallers = array();
  130. foreach($aBacktrace as $aStackInfo)
  131. {
  132. $aCallers[] = $aStackInfo["function"];
  133. }
  134. $sCallers = "Callstack: ".implode(', ', $aCallers);
  135. $sFunction = "<b title=\"$sCallers\">".$aBacktrace[1]["function"]."</b>";
  136. if (is_string($value))
  137. {
  138. echo "$sIndent$sFunction: $value<br/>\n";
  139. }
  140. else if (is_object($value))
  141. {
  142. echo "$sIndent$sFunction:\n<pre>\n";
  143. print_r($value);
  144. echo "</pre>\n";
  145. }
  146. else
  147. {
  148. echo "$sIndent$sFunction: $value<br/>\n";
  149. }
  150. }
  151. private static $m_bTraceQueries = true;
  152. private static $m_aQueriesLog = array();
  153. private static $m_sDBName = "";
  154. private static $m_sTablePrefix = ""; // table prefix for the current application instance (allow several applications on the same DB)
  155. private static $m_Category2Class = array();
  156. private static $m_aRootClasses = array(); // array of "classname" => "rootclass"
  157. private static $m_aParentClasses = array(); // array of ("classname" => array of "parentclass")
  158. private static $m_aChildClasses = array(); // array of ("classname" => array of "childclass")
  159. private static $m_aClassParams = array(); // array of ("classname" => array of class information)
  160. static public function GetParentPersistentClass($sRefClass)
  161. {
  162. $sClass = get_parent_class($sRefClass);
  163. if (!$sClass) return '';
  164. if ($sClass == 'DBObject') return ''; // Warning: __CLASS__ is lower case in my version of PHP
  165. // Note: the UI/business model may implement pure PHP classes (intermediate layers)
  166. if (array_key_exists($sClass, self::$m_aClassParams))
  167. {
  168. return $sClass;
  169. }
  170. return self::GetParentPersistentClass($sClass);
  171. }
  172. final static public function GetName($sClass)
  173. {
  174. self::_check_subclass($sClass);
  175. return self::$m_aClassParams[$sClass]["name"];
  176. }
  177. final static public function GetCategory($sClass)
  178. {
  179. self::_check_subclass($sClass);
  180. return self::$m_aClassParams[$sClass]["category"];
  181. }
  182. final static public function HasCategory($sClass, $sCategory)
  183. {
  184. self::_check_subclass($sClass);
  185. return (strpos(self::$m_aClassParams[$sClass]["category"], $sCategory) !== false);
  186. }
  187. final static public function GetClassDescription($sClass)
  188. {
  189. self::_check_subclass($sClass);
  190. return self::$m_aClassParams[$sClass]["description"];
  191. }
  192. final static public function IsAutoIncrementKey($sClass)
  193. {
  194. self::_check_subclass($sClass);
  195. return (self::$m_aClassParams[$sClass]["key_type"] == "autoincrement");
  196. }
  197. final static public function GetKeyLabel($sClass)
  198. {
  199. self::_check_subclass($sClass);
  200. return self::$m_aClassParams[$sClass]["key_label"];
  201. }
  202. final static public function GetNameAttributeCode($sClass)
  203. {
  204. self::_check_subclass($sClass);
  205. return self::$m_aClassParams[$sClass]["name_attcode"];
  206. }
  207. final static public function GetStateAttributeCode($sClass)
  208. {
  209. self::_check_subclass($sClass);
  210. return self::$m_aClassParams[$sClass]["state_attcode"];
  211. }
  212. final static public function GetDefaultState($sClass)
  213. {
  214. $sDefaultState = '';
  215. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  216. if (!empty($sStateAttrCode))
  217. {
  218. $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  219. $sDefaultState = $oStateAttrDef->GetDefaultValue();
  220. }
  221. return $sDefaultState;
  222. }
  223. final static public function GetReconcKeys($sClass)
  224. {
  225. self::_check_subclass($sClass);
  226. return self::$m_aClassParams[$sClass]["reconc_keys"];
  227. }
  228. final static public function GetDisplayTemplate($sClass)
  229. {
  230. self::_check_subclass($sClass);
  231. return self::$m_aClassParams[$sClass]["display_template"];
  232. }
  233. final static public function GetAttributeOrigin($sClass, $sAttCode)
  234. {
  235. self::_check_subclass($sClass);
  236. return self::$m_aAttribOrigins[$sClass][$sAttCode];
  237. }
  238. final static public function GetPrequisiteAttributes($sClass, $sAttCode)
  239. {
  240. self::_check_subclass($sClass);
  241. $oAtt = self::GetAttributeDef($sClass, $sAttCode);
  242. // Temporary implementation: later, we might be able to compute
  243. // the dependencies, based on the attributes definition
  244. // (allowed values and default values)
  245. if ($oAtt->IsWritable())
  246. {
  247. return $oAtt->GetPrerequisiteAttributes();
  248. }
  249. else
  250. {
  251. return array();
  252. }
  253. }
  254. // #@# restore to private ?
  255. final static public function DBGetTable($sClass, $sAttCode = null)
  256. {
  257. self::_check_subclass($sClass);
  258. if (empty($sAttCode) || ($sAttCode == "id"))
  259. {
  260. $sTableRaw = self::$m_aClassParams[$sClass]["db_table"];
  261. if (empty($sTableRaw))
  262. {
  263. // return an empty string whenever the table is undefined, meaning that there is no table associated to this 'abstract' class
  264. return '';
  265. }
  266. else
  267. {
  268. return self::$m_sTablePrefix.$sTableRaw;
  269. }
  270. }
  271. // This attribute has been inherited (compound objects)
  272. return self::DBGetTable(self::$m_aAttribOrigins[$sClass][$sAttCode]);
  273. }
  274. final static public function DBGetKey($sClass)
  275. {
  276. self::_check_subclass($sClass);
  277. return self::$m_aClassParams[$sClass]["db_key_field"];
  278. }
  279. final static public function DBGetClassField($sClass)
  280. {
  281. self::_check_subclass($sClass);
  282. return self::$m_aClassParams[$sClass]["db_finalclass_field"];
  283. }
  284. final static public function HasFinalClassField($sClass)
  285. {
  286. self::_check_subclass($sClass);
  287. if (!array_key_exists("db_finalclass_field", self::$m_aClassParams[$sClass])) return false;
  288. return (self::$m_aClassParams[$sClass]["db_finalclass_field"]);
  289. }
  290. final static public function IsStandaloneClass($sClass)
  291. {
  292. self::_check_subclass($sClass);
  293. $sRootClass = self::GetRootClass($sClass);
  294. return (!self::HasFinalClassField($sRootClass));
  295. }
  296. final static public function IsParentClass($sParentClass, $sChildClass)
  297. {
  298. self::_check_subclass($sChildClass);
  299. self::_check_subclass($sParentClass);
  300. if (in_array($sParentClass, self::$m_aParentClasses[$sChildClass])) return true;
  301. if ($sChildClass == $sParentClass) return true;
  302. return false;
  303. }
  304. final static public function IsSameFamilyBranch($sClassA, $sClassB)
  305. {
  306. self::_check_subclass($sClassA);
  307. self::_check_subclass($sClassB);
  308. if (in_array($sClassA, self::$m_aParentClasses[$sClassB])) return true;
  309. if (in_array($sClassB, self::$m_aParentClasses[$sClassA])) return true;
  310. if ($sClassA == $sClassB) return true;
  311. return false;
  312. }
  313. final static public function IsSameFamily($sClassA, $sClassB)
  314. {
  315. self::_check_subclass($sClassA);
  316. self::_check_subclass($sClassB);
  317. return (self::GetRootClass($sClassA) == self::GetRootClass($sClassB));
  318. }
  319. // Attributes of a given class may contain attributes defined in a parent class
  320. // - Some attributes are a copy of the definition
  321. // - Some attributes correspond to the upper class table definition (compound objects)
  322. // (see also filters definition)
  323. private static $m_aAttribDefs = array(); // array of ("classname" => array of attributes)
  324. private static $m_aAttribOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  325. private static $m_aExtKeyFriends = array(); // array of ("classname" => array of ("indirect ext key attcode"=> array of ("relative ext field")))
  326. final static public function ListAttributeDefs($sClass)
  327. {
  328. self::_check_subclass($sClass);
  329. return self::$m_aAttribDefs[$sClass];
  330. }
  331. final public static function GetAttributesList($sClass)
  332. {
  333. self::_check_subclass($sClass);
  334. return array_keys(self::$m_aAttribDefs[$sClass]);
  335. }
  336. final public static function GetFiltersList($sClass)
  337. {
  338. self::_check_subclass($sClass);
  339. return array_keys(self::$m_aFilterDefs[$sClass]);
  340. }
  341. final public static function GetKeysList($sClass)
  342. {
  343. self::_check_subclass($sClass);
  344. $aExtKeys = array();
  345. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  346. {
  347. if ($oAttDef->IsExternalKey())
  348. {
  349. $aExtKeys[] = $sAttCode;
  350. }
  351. }
  352. return $aExtKeys;
  353. }
  354. final static public function IsValidKeyAttCode($sClass, $sAttCode)
  355. {
  356. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  357. if (!array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass])) return false;
  358. return (self::$m_aAttribDefs[$sClass][$sAttCode]->IsExternalKey());
  359. }
  360. final static public function IsValidAttCode($sClass, $sAttCode)
  361. {
  362. if (!array_key_exists($sClass, self::$m_aAttribDefs)) return false;
  363. return (array_key_exists($sAttCode, self::$m_aAttribDefs[$sClass]));
  364. }
  365. final static public function IsAttributeOrigin($sClass, $sAttCode)
  366. {
  367. return (self::$m_aAttribOrigins[$sClass][$sAttCode] == $sClass);
  368. }
  369. final static public function IsValidFilterCode($sClass, $sFilterCode)
  370. {
  371. if (!array_key_exists($sClass, self::$m_aFilterDefs)) return false;
  372. return (array_key_exists($sFilterCode, self::$m_aFilterDefs[$sClass]));
  373. }
  374. public static function IsValidClass($sClass)
  375. {
  376. return (array_key_exists($sClass, self::$m_aAttribDefs));
  377. }
  378. public static function IsValidObject($oObject)
  379. {
  380. if (!is_object($oObject)) return false;
  381. return (self::IsValidClass(get_class($oObject)));
  382. }
  383. public static function IsReconcKey($sClass, $sAttCode)
  384. {
  385. return (in_array($sAttCode, self::GetReconcKeys($sClass)));
  386. }
  387. final static public function GetAttributeDef($sClass, $sAttCode)
  388. {
  389. self::_check_subclass($sClass);
  390. return self::$m_aAttribDefs[$sClass][$sAttCode];
  391. }
  392. final static public function GetExternalKeys($sClass)
  393. {
  394. $aExtKeys = array();
  395. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  396. {
  397. if ($oAtt->IsExternalKey())
  398. {
  399. $aExtKeys[$sAttCode] = $oAtt;
  400. }
  401. }
  402. return $aExtKeys;
  403. }
  404. final static public function GetExternalFields($sClass, $sKeyAttCode)
  405. {
  406. $aExtFields = array();
  407. foreach (self::ListAttributeDefs($sClass) as $sAttCode => $oAtt)
  408. {
  409. if ($oAtt->IsExternalField() && ($oAtt->GetKeyAttCode() == $sKeyAttCode))
  410. {
  411. $aExtFields[] = $oAtt;
  412. }
  413. }
  414. return $aExtFields;
  415. }
  416. final static public function GetExtKeyFriends($sClass, $sExtKeyAttCode)
  417. {
  418. if (array_key_exists($sExtKeyAttCode, self::$m_aExtKeyFriends[$sClass]))
  419. {
  420. return self::$m_aExtKeyFriends[$sClass][$sExtKeyAttCode];
  421. }
  422. else
  423. {
  424. return array();
  425. }
  426. }
  427. public static function GetLabel($sClass, $sAttCode)
  428. {
  429. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  430. if ($oAttDef) return $oAttDef->GetLabel();
  431. return "";
  432. }
  433. public static function GetDescription($sClass, $sAttCode)
  434. {
  435. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  436. if ($oAttDef) return $oAttDef->GetDescription();
  437. return "";
  438. }
  439. // Filters of a given class may contain filters defined in a parent class
  440. // - Some filters are a copy of the definition
  441. // - Some filters correspond to the upper class table definition (compound objects)
  442. // (see also attributes definition)
  443. private static $m_aFilterDefs = array(); // array of ("classname" => array filterdef)
  444. private static $m_aFilterOrigins = array(); // array of ("classname" => array of ("attcode"=>"sourceclass"))
  445. public static function GetClassFilterDefs($sClass)
  446. {
  447. self::_check_subclass($sClass);
  448. return self::$m_aFilterDefs[$sClass];
  449. }
  450. final static public function GetClassFilterDef($sClass, $sFilterCode)
  451. {
  452. self::_check_subclass($sClass);
  453. return self::$m_aFilterDefs[$sClass][$sFilterCode];
  454. }
  455. public static function GetFilterLabel($sClass, $sFilterCode)
  456. {
  457. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  458. if ($oFilter) return $oFilter->GetLabel();
  459. return "";
  460. }
  461. public static function GetFilterDescription($sClass, $sFilterCode)
  462. {
  463. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  464. if ($oFilter) return $oFilter->GetDescription();
  465. return "";
  466. }
  467. // returns an array of opcode=>oplabel (e.g. "differs from")
  468. public static function GetFilterOperators($sClass, $sFilterCode)
  469. {
  470. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  471. if ($oFilter) return $oFilter->GetOperators();
  472. return array();
  473. }
  474. // returns an opcode
  475. public static function GetFilterLooseOperator($sClass, $sFilterCode)
  476. {
  477. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  478. if ($oFilter) return $oFilter->GetLooseOperator();
  479. return array();
  480. }
  481. public static function GetFilterOpDescription($sClass, $sFilterCode, $sOpCode)
  482. {
  483. $oFilter = self::GetClassFilterDef($sClass, $sFilterCode);
  484. if ($oFilter) return $oFilter->GetOpDescription($sOpCode);
  485. return "";
  486. }
  487. public static function GetFilterHTMLInput($sFilterCode)
  488. {
  489. return "<INPUT name=\"$sFilterCode\">";
  490. }
  491. // Lists of attributes/search filters
  492. //
  493. private static $m_aListInfos = array(); // array of ("listcode" => various info on the list, common to every classes)
  494. private static $m_aListData = array(); // array of ("classname" => array of "listcode" => list)
  495. // list may be an array of attcode / fltcode
  496. // list may be an array of "groupname" => (array of attcode / fltcode)
  497. public static function EnumZLists()
  498. {
  499. return array_keys(self::$m_aListInfos);
  500. }
  501. final static public function GetZListInfo($sListCode)
  502. {
  503. return self::$m_aListInfos[$sListCode];
  504. }
  505. public static function GetZListItems($sClass, $sListCode)
  506. {
  507. if (array_key_exists($sClass, self::$m_aListData))
  508. {
  509. if (array_key_exists($sListCode, self::$m_aListData[$sClass]))
  510. {
  511. return self::$m_aListData[$sClass][$sListCode];
  512. }
  513. }
  514. $sParentClass = self::GetParentPersistentClass($sClass);
  515. if (empty($sParentClass)) return array(); // nothing for the mother of all classes
  516. // Dig recursively
  517. return self::GetZListItems($sParentClass, $sListCode);
  518. }
  519. public static function IsAttributeInZList($sClass, $sListCode, $sAttCodeOrFltCode, $sGroup = null)
  520. {
  521. $aZList = self::GetZListItems($sClass, $sListCode);
  522. if (!$sGroup)
  523. {
  524. return (in_array($sAttCodeOrFltCode, $aZList));
  525. }
  526. return (in_array($sAttCodeOrFltCode, $aZList[$sGroup]));
  527. }
  528. //
  529. // Relations
  530. //
  531. private static $m_aRelationInfos = array(); // array of ("relcode" => various info on the list, common to every classes)
  532. public static function EnumRelations()
  533. {
  534. return array_keys(self::$m_aRelationInfos);
  535. }
  536. public static function EnumRelationProperties($sRelCode)
  537. {
  538. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  539. return self::$m_aRelationInfos[$sRelCode];
  540. }
  541. final static public function GetRelationProperty($sRelCode, $sProperty)
  542. {
  543. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  544. MyHelpers::CheckKeyInArray('relation property', $sProperty, self::$m_aRelationInfos[$sRelCode]);
  545. return self::$m_aRelationInfos[$sRelCode][$sProperty];
  546. }
  547. public static function EnumRelationQueries($sClass, $sRelCode)
  548. {
  549. MyHelpers::CheckKeyInArray('relation code', $sRelCode, self::$m_aRelationInfos);
  550. return call_user_func_array(array($sClass, 'GetRelationQueries'), array($sRelCode));
  551. }
  552. //
  553. // Object lifecycle model
  554. //
  555. private static $m_aStates = array(); // array of ("classname" => array of "statecode"=>array('label'=>..., 'description'=>..., attribute_inherit=> attribute_list=>...))
  556. private static $m_aStimuli = array(); // array of ("classname" => array of ("stimuluscode"=>array('label'=>..., 'description'=>...)))
  557. 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)))
  558. public static function EnumStates($sClass)
  559. {
  560. if (array_key_exists($sClass, self::$m_aStates))
  561. {
  562. return self::$m_aStates[$sClass];
  563. }
  564. else
  565. {
  566. return array();
  567. }
  568. }
  569. public static function EnumStimuli($sClass)
  570. {
  571. if (array_key_exists($sClass, self::$m_aStimuli))
  572. {
  573. return self::$m_aStimuli[$sClass];
  574. }
  575. else
  576. {
  577. return array();
  578. }
  579. }
  580. public static function EnumTransitions($sClass, $sStateCode)
  581. {
  582. if (array_key_exists($sClass, self::$m_aTransitions))
  583. {
  584. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  585. {
  586. return self::$m_aTransitions[$sClass][$sStateCode];
  587. }
  588. }
  589. return array();
  590. }
  591. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  592. {
  593. $iFlags = 0; // By default (if no life cycle) no flag at all
  594. $sStateAttCode = self::GetStateAttributeCode($sClass);
  595. if (!empty($sStateAttCode))
  596. {
  597. $aStates = MetaModel::EnumStates($sClass);
  598. if (!array_key_exists($sState, $aStates))
  599. {
  600. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  601. }
  602. $aCurrentState = $aStates[$sState];
  603. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  604. {
  605. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  606. }
  607. }
  608. return $iFlags;
  609. }
  610. //
  611. // Allowed values
  612. //
  613. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sBeginsWith = '')
  614. {
  615. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  616. return $oAttDef->GetAllowedValues($aArgs, $sBeginsWith);
  617. }
  618. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sBeginsWith = '')
  619. {
  620. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  621. return $oFltDef->GetAllowedValues($aArgs, $sBeginsWith);
  622. }
  623. //
  624. // Businezz model declaration verbs (should be static)
  625. //
  626. public static function RegisterZList($sListCode, $aListInfo)
  627. {
  628. // Check mandatory params
  629. $aMandatParams = array(
  630. "description" => "detailed (though one line) description of the list",
  631. "type" => "attributes | filters",
  632. );
  633. foreach($aMandatParams as $sParamName=>$sParamDesc)
  634. {
  635. if (!array_key_exists($sParamName, $aListInfo))
  636. {
  637. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  638. }
  639. }
  640. self::$m_aListInfos[$sListCode] = $aListInfo;
  641. }
  642. public static function RegisterRelation($sRelCode, $aRelationInfo)
  643. {
  644. // Check mandatory params
  645. $aMandatParams = array(
  646. "description" => "detailed (though one line) description of the list",
  647. "verb_down" => "e.g.: 'impacts'",
  648. "verb_up" => "e.g.: 'is impacted by'",
  649. );
  650. foreach($aMandatParams as $sParamName=>$sParamDesc)
  651. {
  652. if (!array_key_exists($sParamName, $aRelationInfo))
  653. {
  654. throw new CoreException("Declaration of relation $sRelCode - missing parameter $sParamName");
  655. }
  656. }
  657. self::$m_aRelationInfos[$sRelCode] = $aRelationInfo;
  658. }
  659. // Must be called once and only once...
  660. public static function InitClasses($sTablePrefix)
  661. {
  662. if (count(self::GetClasses()) > 0)
  663. {
  664. throw new CoreException("InitClasses should not be called more than once -skipped");
  665. return;
  666. }
  667. self::$m_sTablePrefix = $sTablePrefix;
  668. foreach(get_declared_classes() as $sPHPClass) {
  669. if (is_subclass_of($sPHPClass, 'DBObject'))
  670. {
  671. if (method_exists($sPHPClass, 'Init'))
  672. {
  673. call_user_func(array($sPHPClass, 'Init'));
  674. }
  675. }
  676. }
  677. foreach (self::GetClasses() as $sClass)
  678. {
  679. // Compute the fields that will be used to display a pointer to another object
  680. //
  681. self::$m_aExtKeyFriends[$sClass] = array();
  682. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  683. {
  684. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  685. {
  686. // oAttDef is either
  687. // - an external KEY / FIELD (direct),
  688. // - an external field pointing to an external KEY / FIELD
  689. // - an external field pointing to an external field pointing to....
  690. // Get the real external key attribute
  691. // It will be our reference to determine the other ext fields related to the same ext key
  692. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  693. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  694. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  695. {
  696. // skip : those extfields will be processed as external keys
  697. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  698. // Note: I could not compare the objects by the mean of '==='
  699. // because they are copied for the inheritance, and the internal references are NOT updated
  700. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  701. {
  702. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  703. }
  704. }
  705. }
  706. }
  707. // Add a 'id' filter
  708. //
  709. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  710. {
  711. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  712. }
  713. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  714. {
  715. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  716. }
  717. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  718. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  719. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  720. // Add a 'class' attribute/filter to the root classes and their children
  721. //
  722. if (!self::IsStandaloneClass($sClass))
  723. {
  724. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sClass]))
  725. {
  726. throw new CoreException("Class $sClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  727. }
  728. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sClass]))
  729. {
  730. throw new CoreException("Class $sClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  731. }
  732. $sClassAttCode = 'finalclass';
  733. $sRootClass = self::GetRootClass($sClass);
  734. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  735. $oClassAtt = new AttributeString($sClassAttCode, array(
  736. "label"=>"Class",
  737. "description"=>"Real (final) object class",
  738. "allowed_values"=>null,
  739. "sql"=>$sDbFinalClassField,
  740. "default_value"=>$sClass,
  741. "is_null_allowed"=>false,
  742. "depends_on"=>array()
  743. ));
  744. self::$m_aAttribDefs[$sClass][$sClassAttCode] = $oClassAtt;
  745. self::$m_aAttribOrigins[$sClass][$sClassAttCode] = $sRootClass;
  746. $oClassFlt = new FilterFromAttribute($oClassAtt);
  747. self::$m_aFilterDefs[$sClass][$sClassAttCode] = $oClassFlt;
  748. self::$m_aFilterOrigins[$sClass][$sClassAttCode] = self::GetRootClass($sClass);
  749. }
  750. // Define defaults values for the standard ZLists
  751. //
  752. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  753. //{
  754. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  755. // {
  756. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  757. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  758. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  759. // }
  760. //}
  761. }
  762. }
  763. // To be overriden, must be called for any object class (optimization)
  764. public static function Init()
  765. {
  766. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  767. }
  768. // To be overloaded by biz model declarations
  769. public static function GetRelationQueries($sRelCode)
  770. {
  771. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  772. return array();
  773. }
  774. public static function Init_Params($aParams)
  775. {
  776. // Check mandatory params
  777. $aMandatParams = array(
  778. "category" => "group classes by modules defining their visibility in the UI",
  779. "name" => "internal class name, may be different than the PHP class name",
  780. "description" => "detailed (though one line) description of the class",
  781. "key_type" => "autoincrement | string",
  782. "key_label" => "if set, then display the key as an attribute",
  783. "name_attcode" => "define wich attribute is the class name, may be an inherited attribute",
  784. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  785. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  786. "db_table" => "database table",
  787. "db_key_field" => "database field which is the key",
  788. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  789. );
  790. $sClass = self::GetCallersPHPClass("Init");
  791. if (!array_key_exists("name", $aParams))
  792. {
  793. throw new CoreException("Declaration of class $sClass: missing name ({$aMandatParams["name"]})");
  794. }
  795. foreach($aMandatParams as $sParamName=>$sParamDesc)
  796. {
  797. if (!array_key_exists($sParamName, $aParams))
  798. {
  799. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  800. }
  801. }
  802. $aCategories = explode(',', $aParams['category']);
  803. foreach ($aCategories as $sCategory)
  804. {
  805. self::$m_Category2Class[$sCategory][] = $sClass;
  806. }
  807. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  808. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  809. self::$m_aParentClasses[$sClass] = array();
  810. self::$m_aChildClasses[$sClass] = array();
  811. self::$m_aClassParams[$sClass]= $aParams;
  812. self::$m_aAttribDefs[$sClass] = array();
  813. self::$m_aAttribOrigins[$sClass] = array();
  814. self::$m_aExtKeyFriends[$sClass] = array();
  815. self::$m_aFilterDefs[$sClass] = array();
  816. self::$m_aFilterOrigins[$sClass] = array();
  817. }
  818. protected static function object_array_mergeclone($aSource1, $aSource2)
  819. {
  820. $aRes = array();
  821. foreach ($aSource1 as $key=>$object)
  822. {
  823. $aRes[$key] = clone $object;
  824. }
  825. foreach ($aSource2 as $key=>$object)
  826. {
  827. $aRes[$key] = clone $object;
  828. }
  829. return $aRes;
  830. }
  831. public static function Init_InheritAttributes($sSourceClass = null)
  832. {
  833. $sTargetClass = self::GetCallersPHPClass("Init");
  834. if (empty($sSourceClass))
  835. {
  836. // Default: inherit from parent class
  837. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  838. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  839. }
  840. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  841. {
  842. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  843. {
  844. self::$m_aAttribDefs[$sTargetClass] = array();
  845. self::$m_aAttribOrigins[$sTargetClass] = array();
  846. }
  847. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  848. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  849. }
  850. // later on, we might consider inheritance in different ways !!!
  851. //if (strlen(self::DBGetTable($sSourceClass)) != 0)
  852. if (self::HasFinalClassField(self::$m_aRootClasses[$sSourceClass]))
  853. {
  854. // Inherit the root class
  855. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  856. }
  857. else
  858. {
  859. // I am a root class, standalone as well !
  860. // ????
  861. //self::$m_aRootClasses[$sTargetClass] = $sTargetClass;
  862. }
  863. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  864. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  865. // I am the child of each and every parent...
  866. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  867. {
  868. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  869. }
  870. }
  871. public static function Init_OverloadAttributeParams($sAttCode, $aParams)
  872. {
  873. $sTargetClass = self::GetCallersPHPClass("Init");
  874. if (!self::IsValidAttCode($sTargetClass, $sAttCode))
  875. {
  876. throw new CoreException("Could not overload '$sAttCode', expecting a code from {".implode(", ", self::GetAttributesList($sTargetClass))."}");
  877. }
  878. self::$m_aAttribDefs[$sTargetClass][$sAttCode]->OverloadParams($aParams);
  879. }
  880. public static function Init_AddAttribute(AttributeDefinition $oAtt)
  881. {
  882. $sTargetClass = self::GetCallersPHPClass("Init");
  883. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  884. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  885. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  886. // Specific case of external fields:
  887. // I wanted to simplify the syntax of the declaration of objects in the biz model
  888. // Therefore, the reference to the host class is set there
  889. $oAtt->SetHostClass($sTargetClass);
  890. }
  891. public static function Init_InheritFilters($sSourceClass = null)
  892. {
  893. $sTargetClass = self::GetCallersPHPClass("Init");
  894. if (empty($sSourceClass))
  895. {
  896. // Default: inherit from parent class
  897. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  898. if (empty($sSourceClass)) return; // no filters for the mother of all classes
  899. }
  900. if (isset(self::$m_aFilterDefs[$sSourceClass]))
  901. {
  902. if (!isset(self::$m_aFilterDefs[$sTargetClass]))
  903. {
  904. self::$m_aFilterDefs[$sTargetClass] = array();
  905. self::$m_aFilterOrigins[$sTargetClass] = array();
  906. }
  907. foreach (self::$m_aFilterDefs[$sSourceClass] as $sFltCode=>$oFilter)
  908. {
  909. if ($oFilter instanceof FilterFromAttribute)
  910. {
  911. // In that case, cloning is not enough:
  912. // we must ensure that we will point to the correct
  913. // attribute definition (in case some properties are overloaded)
  914. $oAttDef1 = $oFilter->__GetRefAttribute();
  915. $oAttDef2 = self::GetAttributeDef($sTargetClass, $oAttDef1->GetCode());
  916. $oNewFilter = new FilterFromAttribute($oAttDef2);
  917. }
  918. else
  919. {
  920. $oNewFilter = clone $oFilter;
  921. }
  922. self::$m_aFilterDefs[$sTargetClass][$sFltCode] = $oNewFilter;
  923. }
  924. self::$m_aFilterOrigins[$sTargetClass] = array_merge(self::$m_aFilterOrigins[$sTargetClass], self::$m_aFilterOrigins[$sSourceClass]);
  925. }
  926. }
  927. public static function Init_OverloadFilterParams($sFltCode, $aParams)
  928. {
  929. $sTargetClass = self::GetCallersPHPClass("Init");
  930. if (!self::IsValidFilterCode($sTargetClass, $sFltCode))
  931. {
  932. throw new CoreException("Could not overload '$sFltCode', expecting a code from {".implode(", ", self::GetFiltersList($sTargetClass))."}");
  933. }
  934. self::$m_aFilterDefs[$sTargetClass][$sFltCode]->OverloadParams($aParams);
  935. }
  936. public static function Init_AddFilter(FilterDefinition $oFilter)
  937. {
  938. $sTargetClass = self::GetCallersPHPClass("Init");
  939. self::$m_aFilterDefs[$sTargetClass][$oFilter->GetCode()] = $oFilter;
  940. self::$m_aFilterOrigins[$sTargetClass][$oFilter->GetCode()] = $sTargetClass;
  941. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  942. }
  943. public static function Init_AddFilterFromAttribute($sAttCode)
  944. {
  945. $sTargetClass = self::GetCallersPHPClass("Init");
  946. $oAttDef = self::GetAttributeDef($sTargetClass, $sAttCode);
  947. $sFilterCode = $sAttCode;
  948. $oNewFilter = new FilterFromAttribute($oAttDef);
  949. self::$m_aFilterDefs[$sTargetClass][$sFilterCode] = $oNewFilter;
  950. if ($oAttDef->IsExternalField())
  951. {
  952. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  953. $oKeyDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  954. self::$m_aFilterOrigins[$sTargetClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  955. }
  956. else
  957. {
  958. self::$m_aFilterOrigins[$sTargetClass][$sFilterCode] = $sTargetClass;
  959. }
  960. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  961. }
  962. public static function Init_SetZListItems($sListCode, $aItems)
  963. {
  964. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  965. $sTargetClass = self::GetCallersPHPClass("Init");
  966. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  967. }
  968. public static function Init_DefineState($sStateCode, $aStateDef)
  969. {
  970. $sTargetClass = self::GetCallersPHPClass("Init");
  971. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  972. $sParentState = $aStateDef['attribute_inherit'];
  973. if (!empty($sParentState))
  974. {
  975. // Inherit from the given state (must be defined !)
  976. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  977. // The inherited configuration could be overriden
  978. $aStateDef['attribute_list'] = array_merge($aToInherit, $aStateDef['attribute_list']);
  979. }
  980. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  981. // by default, create an empty set of transitions associated to that state
  982. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  983. }
  984. public static function Init_DefineStimulus($sStimulusCode, $oStimulus)
  985. {
  986. $sTargetClass = self::GetCallersPHPClass("Init");
  987. self::$m_aStimuli[$sTargetClass][$sStimulusCode] = $oStimulus;
  988. }
  989. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  990. {
  991. $sTargetClass = self::GetCallersPHPClass("Init");
  992. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  993. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  994. }
  995. public static function Init_InheritLifecycle($sSourceClass = '')
  996. {
  997. $sTargetClass = self::GetCallersPHPClass("Init");
  998. if (empty($sSourceClass))
  999. {
  1000. // Default: inherit from parent class
  1001. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1002. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1003. }
  1004. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1005. self::$m_aStates[$sTargetClass] = clone self::$m_aStates[$sSourceClass];
  1006. self::$m_aStimuli[$sTargetClass] = clone self::$m_aStimuli[$sSourceClass];
  1007. self::$m_aTransitions[$sTargetClass] = clone self::$m_aTransitions[$sSourceClass];
  1008. }
  1009. //
  1010. // Static API
  1011. //
  1012. public static function GetRootClass($sClass = null)
  1013. {
  1014. self::_check_subclass($sClass);
  1015. return self::$m_aRootClasses[$sClass];
  1016. }
  1017. public static function IsRootClass($sClass)
  1018. {
  1019. self::_check_subclass($sClass);
  1020. return (self::GetRootClass($sClass) == $sClass);
  1021. }
  1022. public static function EnumParentClasses($sClass)
  1023. {
  1024. self::_check_subclass($sClass);
  1025. return self::$m_aParentClasses[$sClass];
  1026. }
  1027. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1028. {
  1029. self::_check_subclass($sClass);
  1030. $aRes = self::$m_aChildClasses[$sClass];
  1031. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1032. {
  1033. // Add it to the list
  1034. $aRes[] = $sClass;
  1035. }
  1036. return $aRes;
  1037. }
  1038. public static function EnumCategories()
  1039. {
  1040. return array_keys(self::$m_Category2Class);
  1041. }
  1042. // Note: use EnumChildClasses to take the compound objects into account
  1043. public static function GetSubclasses($sClass)
  1044. {
  1045. self::_check_subclass($sClass);
  1046. $aSubClasses = array();
  1047. foreach(get_declared_classes() as $sSubClass) {
  1048. if (is_subclass_of($sSubClass, $sClass))
  1049. {
  1050. $aSubClasses[] = $sSubClass;
  1051. }
  1052. }
  1053. return $aSubClasses;
  1054. }
  1055. public static function GetClasses($sCategory = '')
  1056. {
  1057. if (array_key_exists($sCategory, self::$m_Category2Class))
  1058. {
  1059. return self::$m_Category2Class[$sCategory];
  1060. }
  1061. if (count(self::$m_Category2Class) > 0)
  1062. {
  1063. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1064. }
  1065. return array();
  1066. }
  1067. public static function IsAbstract($sClass)
  1068. {
  1069. if (strlen(self::DBGetTable($sClass)) == 0) return true;
  1070. return false;
  1071. }
  1072. protected static $m_aQueryStructCache = array();
  1073. protected static function PrepareQueryArguments($aArgs)
  1074. {
  1075. // Translate any object into scalars
  1076. //
  1077. $aScalarArgs = array();
  1078. foreach($aArgs as $sArgName => $value)
  1079. {
  1080. if (self::IsValidObject($value))
  1081. {
  1082. $aScalarArgs[$sArgName] = $value->GetKey();
  1083. $aScalarArgs[$sArgName.'->id'] = $value->GetKey();
  1084. $sClass = get_class($value);
  1085. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1086. {
  1087. $aScalarArgs[$sArgName.'->'.$sAttCode] = $value->Get($sAttCode);
  1088. }
  1089. }
  1090. else
  1091. {
  1092. $aScalarArgs[$sArgName] = (string) $value;
  1093. }
  1094. }
  1095. // Add standard contextual arguments
  1096. //
  1097. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1098. return $aScalarArgs;
  1099. }
  1100. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array())
  1101. {
  1102. // Query caching
  1103. //
  1104. $bQueryCacheEnabled = true;
  1105. $aParams = array();
  1106. $sOqlQuery = $oFilter->ToOql($aParams); // Render with arguments in clear
  1107. if ($bQueryCacheEnabled)
  1108. {
  1109. if (array_key_exists($sOqlQuery, self::$m_aQueryStructCache))
  1110. {
  1111. // hit!
  1112. $oSelect = clone self::$m_aQueryStructCache[$sOqlQuery];
  1113. }
  1114. }
  1115. if (!isset($oSelect))
  1116. {
  1117. $aTranslation = array();
  1118. $aClassAliases = array();
  1119. $aTableAliases = array();
  1120. $oConditionTree = $oFilter->GetCriteria();
  1121. $oSelect = self::MakeQuery($oFilter->GetClassAlias(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1122. self::$m_aQueryStructCache[$sOqlQuery] = clone $oSelect;
  1123. }
  1124. // Check the order by specification
  1125. //
  1126. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1127. {
  1128. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetClass()));
  1129. if (!is_bool($bAscending))
  1130. {
  1131. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1132. }
  1133. }
  1134. if (empty($aOrderBy))
  1135. {
  1136. $sNameAttCode = self::GetNameAttributeCode($oFilter->GetClass());
  1137. if (!empty($sNameAttCode))
  1138. {
  1139. // By default, simply order on the "name" attribute, ascending
  1140. $aOrderBy = array($sNameAttCode => true);
  1141. }
  1142. }
  1143. // Go
  1144. //
  1145. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1146. try
  1147. {
  1148. $sRes = $oSelect->RenderSelect($aOrderBy, $aScalarArgs);
  1149. }
  1150. catch (MissingQueryArgument $e)
  1151. {
  1152. // Add some information...
  1153. $e->addInfo('OQL', $sOqlQuery);
  1154. throw $e;
  1155. }
  1156. if (self::$m_bTraceQueries)
  1157. {
  1158. $aParams = array();
  1159. if (!array_key_exists($sOqlQuery, self::$m_aQueriesLog))
  1160. {
  1161. self::$m_aQueriesLog[$sOqlQuery] = array(
  1162. 'sql' => array(),
  1163. 'count' => 0,
  1164. );
  1165. }
  1166. self::$m_aQueriesLog[$sOqlQuery]['count']++;
  1167. self::$m_aQueriesLog[$sOqlQuery]['sql'][] = $sRes;
  1168. }
  1169. return $sRes;
  1170. }
  1171. public static function ShowQueryTrace()
  1172. {
  1173. $iTotal = 0;
  1174. foreach (self::$m_aQueriesLog as $sOql => $aQueryData)
  1175. {
  1176. echo "<h2>$sOql</h2>\n";
  1177. $iTotal += $aQueryData['count'];
  1178. echo '<p>'.$aQueryData['count'].'</p>';
  1179. echo '<p>Example: '.$aQueryData['sql'][0].'</p>';
  1180. }
  1181. echo "<h2>Total</h2>\n";
  1182. echo "<p>Count of executed queries: $iTotal</p>";
  1183. echo "<p>Count of built queries: ".count(self::$m_aQueriesLog)."</p>";
  1184. }
  1185. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1186. {
  1187. $aTranslation = array();
  1188. $aClassAliases = array();
  1189. $aTableAliases = array();
  1190. $oConditionTree = $oFilter->GetCriteria();
  1191. $oSelect = self::MakeQuery($oFilter->GetClassAlias(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1192. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1193. return $oSelect->RenderDelete($aScalarArgs);
  1194. }
  1195. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1196. {
  1197. // $aValues is an array of $sAttCode => $value
  1198. $aTranslation = array();
  1199. $aClassAliases = array();
  1200. $aTableAliases = array();
  1201. $oConditionTree = $oFilter->GetCriteria();
  1202. $oSelect = self::MakeQuery($oFilter->GetClassAlias(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues);
  1203. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1204. return $oSelect->RenderUpdate($aScalarArgs);
  1205. }
  1206. private static function MakeQuery($sGlobalTargetAlias, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array())
  1207. {
  1208. // Note: query class might be different than the class of the filter
  1209. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1210. // $aExpectedAtts is an array of sAttCode=>sAlias
  1211. $sClass = $oFilter->GetClass();
  1212. $sClassAlias = $oFilter->GetClassAlias();
  1213. $bIsOnQueriedClass = ($sClassAlias == $sGlobalTargetAlias);
  1214. if ($bIsOnQueriedClass)
  1215. {
  1216. $aClassAliases = array_merge($aClassAliases, $oFilter->GetClasses());
  1217. }
  1218. self::DbgTrace("Entering: ".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", $aExpectedAtts));
  1219. $sRootClass = self::GetRootClass($sClass);
  1220. $sKeyField = self::DBGetKey($sClass);
  1221. if (empty($aExpectedAtts) && $bIsOnQueriedClass)
  1222. {
  1223. // default to the whole list of attributes + the very std id/finalclass
  1224. $aExpectedAtts['id'] = 'id';
  1225. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1226. {
  1227. $aExpectedAtts[$sAttCode] = $sAttCode; // alias == attcode
  1228. }
  1229. }
  1230. // Compute a clear view of external keys, and external attributes
  1231. // Build the list of external keys:
  1232. // -> ext keys required by a closed join ???
  1233. // -> ext keys mentionned in a 'pointing to' condition
  1234. // -> ext keys required for an external field
  1235. //
  1236. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1237. //
  1238. // Optimization: could be computed once for all (cached)
  1239. // Could be done in MakeQuerySingleTable ???
  1240. //
  1241. if ($bIsOnQueriedClass)
  1242. {
  1243. // Get all Ext keys for the queried class (??)
  1244. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1245. {
  1246. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1247. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1248. }
  1249. }
  1250. // Get all Ext keys used by the filter
  1251. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1252. {
  1253. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1254. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1255. }
  1256. // Add the ext fields used in the select (eventually adds an external key)
  1257. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1258. {
  1259. if ($oAttDef->IsExternalField())
  1260. {
  1261. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1262. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1263. {
  1264. // Add the external attribute
  1265. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1266. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1267. }
  1268. }
  1269. }
  1270. // First query built upon on the leaf (ie current) class
  1271. //
  1272. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1273. $oSelectBase = self::MakeQuerySingleTable($sGlobalTargetAlias, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1274. // Then we join the queries of the eventual parent classes (compound model)
  1275. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1276. {
  1277. if (self::DBGetTable($sParentClass) == "") continue;
  1278. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1279. $oSelectParentTable = self::MakeQuerySingleTable($sGlobalTargetAlias, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1280. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1281. }
  1282. // Filter on objects referencing me
  1283. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1284. {
  1285. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1286. {
  1287. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1288. // We don't want any attribute from the foreign class, just filter on an inner join
  1289. $aExpAtts = array();
  1290. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1291. //self::DbgTrace($oForeignFilter);
  1292. //self::DbgTrace($oForeignFilter->ToSibuSQL());
  1293. //self::DbgTrace($oSelectForeign);
  1294. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1295. $oSelectForeign = self::MakeQuery($sGlobalTargetAlias, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1296. $sForeignClassAlias = $oForeignFilter->GetClassAlias();
  1297. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1298. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1299. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1300. }
  1301. }
  1302. // Filter on related objects
  1303. //
  1304. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1305. {
  1306. $oSubFilter = $aCritInfo['flt'];
  1307. $sRelCode = $aCritInfo['relcode'];
  1308. $iMaxDepth = $aCritInfo['maxdepth'];
  1309. // Get the starting point objects
  1310. $oStartSet = new CMDBObjectSet($oSubFilter);
  1311. // Get the objects related to those objects... recursively...
  1312. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1313. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1314. // #@# todo - related objects and expressions...
  1315. // Create condition
  1316. if (count($aRestriction) > 0)
  1317. {
  1318. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1319. }
  1320. else
  1321. {
  1322. // Quick N'dirty -> generate an empty set
  1323. $oSelectBase->AddCondition('false');
  1324. }
  1325. }
  1326. // Translate the conditions... and go
  1327. //
  1328. if ($bIsOnQueriedClass)
  1329. {
  1330. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1331. $oSelectBase->SetCondition($oConditionTranslated);
  1332. }
  1333. // That's all... cross fingers and we'll get some working query
  1334. //MyHelpers::var_dump_html($oSelectBase, true);
  1335. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1336. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1337. return $oSelectBase;
  1338. }
  1339. protected static function MakeQuerySingleTable($sGlobalTargetAlias, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1340. {
  1341. // $aExpectedAtts is an array of sAttCode=>sAlias
  1342. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1343. // Prepare the query for a single table (compound objects)
  1344. // Ignores the items (attributes/filters) that are not on the target table
  1345. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1346. //
  1347. // Returns an SQLQuery
  1348. //
  1349. $sTargetClass = $oFilter->GetClass();
  1350. $sTargetAlias = $oFilter->GetClassAlias();
  1351. $sTable = self::DBGetTable($sTableClass);
  1352. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1353. $bIsOnQueriedClass = ($sTargetAlias == $sGlobalTargetAlias);
  1354. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", $aExpectedAtts));
  1355. // 1 - SELECT and UPDATE
  1356. //
  1357. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1358. //
  1359. $aSelect = array();
  1360. $aUpdateValues = array();
  1361. // 1/a - Get the key
  1362. //
  1363. if ($bIsOnQueriedClass)
  1364. {
  1365. $aSelect[$aExpectedAtts['id']] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1366. }
  1367. // We need one pkey to be the key, let's take the one corresponding to the leaf
  1368. if ($sTableClass == $sTargetClass)
  1369. {
  1370. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1371. }
  1372. // 1/b - Get the other attributes
  1373. //
  1374. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1375. {
  1376. // Skip this attribute if not defined in this table
  1377. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1378. // Skip this attribute if not writable (means that it does not correspond
  1379. if (count($oAttDef->DBGetUsedFields()) == 0) continue;
  1380. // Update...
  1381. //
  1382. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1383. {
  1384. assert ($oAttDef->IsDirectField());
  1385. // Later, we'll have to use $oAttDef->GetDBField();
  1386. $aUpdateValues[$oAttDef->GetSQLExpr()] = $oAttDef->RealValueToSQLValue($aValues[$sAttCode]);
  1387. }
  1388. // Select...
  1389. //
  1390. // Skip, if a list of fields has been specified and it is not there
  1391. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1392. $sAttAlias = $aExpectedAtts[$sAttCode];
  1393. if ($oAttDef->IsExternalField())
  1394. {
  1395. // skip, this will be handled in the joined tables
  1396. }
  1397. else
  1398. {
  1399. // standard field, or external key
  1400. // add it to the output
  1401. $aSelect[$sAttAlias] = new FieldExpression($oAttDef->GetSQLExpr(), $sTableAlias);
  1402. }
  1403. }
  1404. // 2 - WHERE
  1405. //
  1406. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1407. {
  1408. // Skip this filter if not defined in this table
  1409. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1410. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1411. // non-sens: $aTranslation[$sTargetAlias][$sFltCode] = array($sTableAlias, $oFltAtt->GetFilterSQLExpr(opcode, operand));
  1412. $aTranslation[$sTargetAlias][$sFltCode] = array($sTableAlias, $oFltAtt->TemporaryGetSQLCol());
  1413. }
  1414. // #@# todo - See what a full text search condition should be
  1415. // 2' - WHERE / Full text search condition
  1416. //
  1417. if ($bIsOnQueriedClass)
  1418. {
  1419. $aFullText = $oFilter->GetCriteria_FullText();
  1420. }
  1421. else
  1422. {
  1423. // Pourquoi ???
  1424. $aFullText = array();
  1425. }
  1426. // 3 - The whole stuff, for this table only
  1427. //
  1428. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1429. // 4 - The external keys -> joins...
  1430. //
  1431. if (array_key_exists($sTableClass, $aExtKeys))
  1432. {
  1433. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1434. {
  1435. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1436. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1437. // In case the join was not explicitely defined in the filter,
  1438. // we need to do it now
  1439. if (empty($oExtFilter))
  1440. {
  1441. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1442. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1443. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1444. }
  1445. else
  1446. {
  1447. // The aliases should not conflict because normalization occured while building the filter
  1448. $sKeyClass = $oExtFilter->GetClass();
  1449. $sKeyClassAlias = $oExtFilter->GetClassAlias();
  1450. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1451. }
  1452. // Specify expected attributes for the target class query
  1453. // ... and use the current alias !
  1454. $aExpAtts = array();
  1455. $aIntermediateTranslation = array();
  1456. foreach($aExtFields as $sAttCode => $oAtt)
  1457. {
  1458. $sExtAttCode = $oAtt->GetExtAttCode();
  1459. if (array_key_exists($sAttCode, $aExpectedAtts))
  1460. {
  1461. // Request this attribute... transmit the alias !
  1462. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1463. }
  1464. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1465. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1466. $sRemoteAttExpr = $oRemoteAttDef->GetSQLExpr();
  1467. $aIntermediateTranslation[$sTargetAlias][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1468. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1469. }
  1470. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1471. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1472. $oSelectExtKey = self::MakeQuery($sGlobalTargetAlias, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1473. $sLocalKeyField = $oKeyAttDef->GetSQLExpr();
  1474. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1475. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1476. if ($oKeyAttDef->IsNullAllowed())
  1477. {
  1478. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1479. }
  1480. else
  1481. {
  1482. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1483. }
  1484. }
  1485. }
  1486. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1487. return $oSelectBase;
  1488. }
  1489. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1490. {
  1491. if (!array_key_exists($sNewName, $aAliases))
  1492. {
  1493. $aAliases[$sNewName] = $sRealName;
  1494. return $sNewName;
  1495. }
  1496. for ($i = 1 ; $i < 100 ; $i++)
  1497. {
  1498. $sAnAlias = $sNewName.$i;
  1499. if (!array_key_exists($sAnAlias, $aAliases))
  1500. {
  1501. // Create that new alias
  1502. $aAliases[$sAnAlias] = $sRealName;
  1503. return $sAnAlias;
  1504. }
  1505. }
  1506. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1507. }
  1508. public static function CheckDefinitions()
  1509. {
  1510. if (count(self::GetClasses()) == 0)
  1511. {
  1512. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1513. }
  1514. $aErrors = array();
  1515. $aSugFix = array();
  1516. foreach (self::GetClasses() as $sClass)
  1517. {
  1518. if (self::IsAbstract($sClass)) continue;
  1519. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1520. if (empty($sNameAttCode))
  1521. {
  1522. // let's try this !!!
  1523. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1524. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1525. }
  1526. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1527. {
  1528. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1529. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1530. }
  1531. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1532. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1533. {
  1534. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1535. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1536. }
  1537. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1538. {
  1539. // It makes no sense to check the attributes again and again in the subclasses
  1540. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1541. if ($oAttDef->IsExternalKey())
  1542. {
  1543. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1544. {
  1545. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1546. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1547. }
  1548. }
  1549. elseif ($oAttDef->IsExternalField())
  1550. {
  1551. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1552. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1553. {
  1554. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1555. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1556. }
  1557. else
  1558. {
  1559. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1560. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1561. $sExtAttCode = $oAttDef->GetExtAttCode();
  1562. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1563. {
  1564. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1565. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1566. }
  1567. }
  1568. }
  1569. else // standard attributes
  1570. {
  1571. // Check that the default values definition is a valid object!
  1572. $oValSetDef = $oAttDef->GetValuesDef();
  1573. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1574. {
  1575. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1576. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1577. }
  1578. else
  1579. {
  1580. // Default value must be listed in the allowed values (if defined)
  1581. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1582. if (!is_null($aAllowedValues))
  1583. {
  1584. $sDefaultValue = $oAttDef->GetDefaultValue();
  1585. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  1586. {
  1587. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  1588. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  1589. }
  1590. }
  1591. }
  1592. }
  1593. // Check dependencies
  1594. if ($oAttDef->IsWritable())
  1595. {
  1596. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  1597. {
  1598. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  1599. {
  1600. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  1601. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1602. }
  1603. }
  1604. }
  1605. }
  1606. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  1607. {
  1608. if (method_exists($oFilterDef, '__GetRefAttribute'))
  1609. {
  1610. $oAttDef = $oFilterDef->__GetRefAttribute();
  1611. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  1612. {
  1613. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  1614. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1615. }
  1616. }
  1617. }
  1618. // Lifecycle
  1619. //
  1620. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1621. if (strlen($sStateAttCode) > 0)
  1622. {
  1623. // Lifecycle - check that the state attribute does exist as an attribute
  1624. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  1625. {
  1626. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  1627. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1628. }
  1629. else
  1630. {
  1631. // Lifecycle - check that there is a value set constraint on the state attribute
  1632. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  1633. $aStates = array_keys(self::EnumStates($sClass));
  1634. if (is_null($aAllowedValuesRaw))
  1635. {
  1636. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  1637. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  1638. }
  1639. else
  1640. {
  1641. $aAllowedValues = array_keys($aAllowedValuesRaw);
  1642. // Lifecycle - check the the state attribute allowed values are defined states
  1643. foreach($aAllowedValues as $sValue)
  1644. {
  1645. if (!in_array($sValue, $aStates))
  1646. {
  1647. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  1648. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1649. }
  1650. }
  1651. // Lifecycle - check that defined states are allowed values
  1652. foreach($aStates as $sStateValue)
  1653. {
  1654. if (!in_array($sStateValue, $aAllowedValues))
  1655. {
  1656. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  1657. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1658. }
  1659. }
  1660. }
  1661. // Lifcycle - check that the action handlers are defined
  1662. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  1663. {
  1664. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  1665. {
  1666. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1667. {
  1668. if (!method_exists($sClass, $sActionHandler))
  1669. {
  1670. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  1671. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  1672. }
  1673. }
  1674. }
  1675. }
  1676. }
  1677. }
  1678. // ZList
  1679. //
  1680. foreach(self::EnumZLists() as $sListCode)
  1681. {
  1682. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  1683. {
  1684. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  1685. {
  1686. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  1687. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1688. }
  1689. }
  1690. }
  1691. }
  1692. if (count($aErrors) > 0)
  1693. {
  1694. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  1695. echo "<h3>Business model inconsistencies have been found</h3>\n";
  1696. // #@# later -> this is the responsibility of the caller to format the output
  1697. foreach ($aErrors as $sClass => $aMessages)
  1698. {
  1699. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  1700. echo "<ul class=\"treeview\">\n";
  1701. $i = 0;
  1702. foreach ($aMessages as $sMsg)
  1703. {
  1704. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  1705. $i++;
  1706. }
  1707. echo "</ul>\n";
  1708. }
  1709. echo "<p>Aborting...</p>\n";
  1710. echo "</div>\n";
  1711. exit;
  1712. }
  1713. }
  1714. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  1715. {
  1716. if (empty($sRepairUrl)) return;
  1717. if (count($aSQLFixes) == 0) return;
  1718. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  1719. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aSQLFixes))."\">\n";
  1720. echo " <input type=\"submit\" value=\" Apply the changes (".count($aSQLFixes)." queries) \">\n";
  1721. echo "</form>\n";
  1722. }
  1723. public static function DBExists()
  1724. {
  1725. // returns true if at least one table exists (taking into account the DB sharing)
  1726. // then some tables might be missing, but that is made in DBCheckFormat
  1727. //
  1728. if (empty(self::$m_sTablePrefix))
  1729. {
  1730. return CMDBSource::IsDB(self::$m_sDBName);
  1731. }
  1732. // DB sharing
  1733. // Check if there is at least one table with the prefix
  1734. //
  1735. if (!CMDBSource::IsDB(self::$m_sDBName))
  1736. {
  1737. return false;
  1738. }
  1739. CMDBSource::SelectDB(self::$m_sDBName);
  1740. // If a table matches the prefix, then consider that the database already exists
  1741. $sSQL = "SHOW TABLES LIKE '".strtolower(self::$m_sTablePrefix)."%' ";
  1742. $result = CMDBSource::Query($sSQL);
  1743. return (CMDBSource::NbRows($result) > 0);
  1744. }
  1745. public static function DBDrop()
  1746. {
  1747. $bDropEntireDB = true;
  1748. if (!empty(self::$m_sTablePrefix))
  1749. {
  1750. // Do drop only tables corresponding to the sub-database (table prefix)
  1751. // then possibly drop the DB itself (if no table remain)
  1752. foreach (CMDBSource::EnumTables() as $sTable)
  1753. {
  1754. // perform a case insensitive test because on Windows the table names become lowercase :-(
  1755. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  1756. {
  1757. CMDBSource::DropTable($sTable);
  1758. }
  1759. else
  1760. {
  1761. // There is at least one table which is out of the scope of the current application
  1762. $bDropEntireDB = false;
  1763. }
  1764. }
  1765. }
  1766. if ($bDropEntireDB)
  1767. {
  1768. CMDBSource::DropDB(self::$m_sDBName);
  1769. }
  1770. }
  1771. public static function DBCreate()
  1772. {
  1773. // Note: we have to check if the DB does exist, because we may share the DB
  1774. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  1775. if (!CMDBSource::IsDB(self::$m_sDBName))
  1776. {
  1777. CMDBSource::CreateDB(self::$m_sDBName);
  1778. }
  1779. self::DBCreateTables();
  1780. }
  1781. protected static function DBCreateTables()
  1782. {
  1783. list($aErrors, $aSugFix) = self::DBCheckFormat();
  1784. $aSQL = array();
  1785. foreach ($aSugFix as $sClass => $aQueries)
  1786. {
  1787. foreach ($aQueries as $sQuery)
  1788. {
  1789. //$aSQL[] = $sQuery;
  1790. // forces a refresh of cached information
  1791. CMDBSource::CreateTable($sQuery);
  1792. }
  1793. }
  1794. // does not work -how to have multiple statements in a single query?
  1795. // $sDoCreateAll = implode(" ; ", $aSQL);
  1796. }
  1797. public static function DBCheckFormat()
  1798. {
  1799. $aErrors = array();
  1800. $aSugFix = array();
  1801. foreach (self::GetClasses() as $sClass)
  1802. {
  1803. if (self::IsAbstract($sClass)) continue;
  1804. // Check that the table exists
  1805. //
  1806. $sTable = self::DBGetTable($sClass);
  1807. $sKeyField = self::DBGetKey($sClass);
  1808. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  1809. if (!CMDBSource::IsTable($sTable))
  1810. {
  1811. $aErrors[$sClass][] = "table '$sTable' could not be found into the DB";
  1812. $aSugFix[$sClass][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = innodb";
  1813. }
  1814. // Check that the key field exists
  1815. //
  1816. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  1817. {
  1818. $aErrors[$sClass][] = "key '$sKeyField' (table $sTable) could not be found";
  1819. $aSugFix[$sClass][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  1820. }
  1821. else
  1822. {
  1823. // Check the key field properties
  1824. //
  1825. if (!CMDBSource::IsKey($sTable, $sKeyField))
  1826. {
  1827. $aErrors[$sClass][] = "key '$sKeyField' is not a key for table '$sTable'";
  1828. $aSugFix[$sClass][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  1829. }
  1830. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  1831. {
  1832. $aErrors[$sClass][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  1833. $aSugFix[$sClass][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  1834. }
  1835. }
  1836. // Check that any defined field exists
  1837. //
  1838. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  1839. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1840. {
  1841. // Skip this attribute if not originaly defined in this class
  1842. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1843. foreach($oAttDef->DBGetUsedFields() as $sField)
  1844. {
  1845. $sDBFieldType = $oAttDef->GetDBFieldType();
  1846. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  1847. if (!CMDBSource::IsField($sTable, $sField))
  1848. {
  1849. $aErrors[$sClass][] = "field '$sField' could not be found in table '$sTable'";
  1850. $aSugFix[$sClass][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  1851. }
  1852. elseif ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  1853. {
  1854. if ($oAttDef->IsNullAllowed())
  1855. {
  1856. $aErrors[$sClass][] = "field '$sField' in table '$sTable' could be NULL";
  1857. $aSugFix[$sClass][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  1858. }
  1859. else
  1860. {
  1861. $aErrors[$sClass][] = "field '$sField' in table '$sTable' could NOT be NULL";
  1862. $aSugFix[$sClass][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  1863. }
  1864. }
  1865. }
  1866. }
  1867. }
  1868. return array($aErrors, $aSugFix);
  1869. }
  1870. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  1871. {
  1872. $sRootClass = self::GetRootClass($sClass);
  1873. $sTable = self::DBGetTable($sClass);
  1874. $sKeyField = self::DBGetKey($sClass);
  1875. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  1876. {
  1877. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  1878. }
  1879. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  1880. if (count($aWrongRecords) == 0) return;
  1881. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  1882. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  1883. foreach ($aWrongRecords as $iRecordId)
  1884. {
  1885. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  1886. {
  1887. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  1888. {
  1889. case 'Delete':
  1890. // Already planned for a deletion
  1891. // Let's concatenate the errors description together
  1892. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  1893. break;
  1894. case 'Update':
  1895. // Let's plan a deletion
  1896. break;
  1897. }
  1898. }
  1899. else
  1900. {
  1901. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  1902. }
  1903. if (!$bProcessingFriends)
  1904. {
  1905. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  1906. {
  1907. // Something new to be deleted...
  1908. $iNewDelCount++;
  1909. }
  1910. }
  1911. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  1912. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  1913. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  1914. $aPlannedDel[$sTable][] = $iRecordId;
  1915. }
  1916. // Now make sure that we would delete the records of the other tables for that class
  1917. //
  1918. if (!$bProcessingFriends)
  1919. {
  1920. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  1921. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  1922. {
  1923. $sFriendTable = self::DBGetTable($sFriendClass);
  1924. $sFriendKey = self::DBGetKey($sFriendClass);
  1925. // skip the current table
  1926. if ($sFriendTable == $sTable) continue;
  1927. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  1928. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  1929. }
  1930. }
  1931. }
  1932. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  1933. {
  1934. $sRootClass = self::GetRootClass($sClass);
  1935. $sTable = self::DBGetTable($sClass);
  1936. $sKeyField = self::DBGetKey($sClass);
  1937. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  1938. {
  1939. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  1940. }
  1941. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  1942. if (count($aWrongRecords) == 0) return;
  1943. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  1944. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  1945. foreach ($aWrongRecords as $iRecordId)
  1946. {
  1947. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  1948. {
  1949. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  1950. {
  1951. case 'Delete':
  1952. // No need to update, the record will be deleted!
  1953. break;
  1954. case 'Update':
  1955. // Already planned for an update
  1956. // Add this new update spec to the list
  1957. $bFoundSameSpec = false;
  1958. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  1959. {
  1960. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  1961. {
  1962. $bFoundSameSpec = true;
  1963. }
  1964. }
  1965. if (!$bFoundSameSpec)
  1966. {
  1967. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  1968. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  1969. }
  1970. break;
  1971. }
  1972. }
  1973. else
  1974. {
  1975. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  1976. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  1977. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  1978. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  1979. }
  1980. }
  1981. }
  1982. // returns the count of records found for deletion
  1983. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  1984. {
  1985. foreach (self::GetClasses() as $sClass)
  1986. {
  1987. if (self::IsAbstract($sClass)) continue;
  1988. $sRootClass = self::GetRootClass($sClass);
  1989. $sTable = self::DBGetTable($sClass);
  1990. $sKeyField = self::DBGetKey($sClass);
  1991. // Check that the final class field contains the name of a class which inherited from the current class
  1992. //
  1993. if (self::HasFinalClassField($sClass))
  1994. {
  1995. $sFinalClassField = self::DBGetClassField($sClass);
  1996. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  1997. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  1998. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  1999. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2000. }
  2001. // Compound objects model - node/leaf classes (not the root itself)
  2002. //
  2003. if (!self::IsStandaloneClass($sClass) && !self::HasFinalClassField($sClass))
  2004. {
  2005. $sRootTable = self::DBGetTable($sRootClass);
  2006. $sRootKey = self::DBGetKey($sRootClass);
  2007. $sFinalClassField = self::DBGetClassField($sRootClass);
  2008. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2009. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2010. // Check that any record found here has its counterpart in the root table
  2011. // and which refers to a child class
  2012. //
  2013. $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";
  2014. 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);
  2015. // Check that any record found in the root table and referring to a child class
  2016. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2017. //
  2018. $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)";
  2019. 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);
  2020. }
  2021. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2022. {
  2023. // Skip this attribute if not defined in this table
  2024. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2025. if ($oAttDef->IsExternalKey())
  2026. {
  2027. // Check that any external field is pointing to an existing object
  2028. //
  2029. $sRemoteClass = $oAttDef->GetTargetClass();
  2030. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2031. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2032. $sExtKeyField = $oAttDef->GetSQLExpr();
  2033. // Note: a class/table may have an external key on itself
  2034. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2035. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2036. if ($oAttDef->IsNullAllowed())
  2037. {
  2038. // Exclude the records pointing to 0/null from the errors
  2039. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2040. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2041. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2042. }
  2043. else
  2044. {
  2045. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2046. }
  2047. // Do almost the same, taking into account the records planned for deletion
  2048. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2049. {
  2050. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2051. // but in that case you won't be able to track the root cause (cascading)
  2052. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2053. if ($oAttDef->IsNullAllowed())
  2054. {
  2055. // Exclude the records pointing to 0/null from the errors
  2056. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2057. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2058. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2059. }
  2060. else
  2061. {
  2062. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2063. }
  2064. }
  2065. }
  2066. else if ($oAttDef->IsDirectField())
  2067. {
  2068. // Check that the values fit the allowed values
  2069. //
  2070. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2071. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2072. {
  2073. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2074. $sMyAttributeField = $oAttDef->GetSQLExpr();
  2075. $sDefaultValue = $oAttDef->GetDefaultValue();
  2076. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2077. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2078. }
  2079. }
  2080. }
  2081. }
  2082. }
  2083. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2084. {
  2085. // Records in error, and action to be taken: delete or update
  2086. // by RootClass/Table/Record
  2087. $aErrorsAndFixes = array();
  2088. // Records to be ignored in the current/next pass
  2089. // by Table = array of RecordId
  2090. $aPlannedDel = array();
  2091. // Count of errors in the next pass: no error means that we can leave...
  2092. $iErrorCount = 0;
  2093. // Limit in case of a bug in the algorythm
  2094. $iLoopCount = 0;
  2095. $iNewDelCount = 1; // startup...
  2096. while ($iNewDelCount > 0)
  2097. {
  2098. $iNewDelCount = 0;
  2099. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2100. $iErrorCount += $iNewDelCount;
  2101. // Safety net #1 - limit the planned deletions
  2102. //
  2103. $iMaxDel = 1000;
  2104. $iPlannedDel = 0;
  2105. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2106. {
  2107. $iPlannedDel += count($aPlannedDelOnTable);
  2108. }
  2109. if ($iPlannedDel > $iMaxDel)
  2110. {
  2111. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2112. break;
  2113. }
  2114. // Safety net #2 - limit the iterations
  2115. //
  2116. $iLoopCount++;
  2117. $iMaxLoops = 10;
  2118. if ($iLoopCount > $iMaxLoops)
  2119. {
  2120. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2121. break;
  2122. }
  2123. }
  2124. // Display the results
  2125. //
  2126. $iIssueCount = 0;
  2127. $aFixesDelete = array();
  2128. $aFixesUpdate = array();
  2129. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2130. {
  2131. foreach ($aTables as $sTable => $aRecords)
  2132. {
  2133. foreach ($aRecords as $iRecord => $aError)
  2134. {
  2135. $sAction = $aError['Action'];
  2136. $sReason = $aError['Reason'];
  2137. $iPass = $aError['Pass'];
  2138. switch ($sAction)
  2139. {
  2140. case 'Delete':
  2141. $sActionDetails = "";
  2142. $aFixesDelete[$sTable][] = $iRecord;
  2143. break;
  2144. case 'Update':
  2145. $aUpdateDesc = array();
  2146. foreach($aError['Action_Details'] as $aUpdateSpec)
  2147. {
  2148. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2149. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2150. }
  2151. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2152. break;
  2153. default:
  2154. $sActionDetails = "bug: unknown action '$sAction'";
  2155. }
  2156. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2157. $iIssueCount++;
  2158. }
  2159. }
  2160. }
  2161. if ($iIssueCount > 0)
  2162. {
  2163. // Build the queries to fix in the database
  2164. //
  2165. // First step, be able to get class data out of the table name
  2166. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2167. $aTable2ClassProp = array();
  2168. foreach (self::GetClasses() as $sClass)
  2169. {
  2170. if (self::IsAbstract($sClass)) continue;
  2171. $sRootClass = self::GetRootClass($sClass);
  2172. $sTable = self::DBGetTable($sClass);
  2173. $sKeyField = self::DBGetKey($sClass);
  2174. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2175. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2176. }
  2177. // Second step, build a flat list of SQL queries
  2178. $aSQLFixes = array();
  2179. $iPlannedUpdate = 0;
  2180. foreach ($aFixesUpdate as $sTable => $aColumns)
  2181. {
  2182. foreach ($aColumns as $sColumn => $aNewValues)
  2183. {
  2184. foreach ($aNewValues as $sNewValue => $aRecords)
  2185. {
  2186. $iPlannedUpdate += count($aRecords);
  2187. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2188. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2189. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2190. }
  2191. }
  2192. }
  2193. $iPlannedDel = 0;
  2194. foreach ($aFixesDelete as $sTable => $aRecords)
  2195. {
  2196. $iPlannedDel += count($aRecords);
  2197. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2198. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2199. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2200. }
  2201. // Report the results
  2202. //
  2203. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2204. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2205. // #@# later -> this is the responsibility of the caller to format the output
  2206. echo "<ul class=\"treeview\">\n";
  2207. foreach ($aIssues as $sIssueDesc)
  2208. {
  2209. echo "<li>$sIssueDesc</li>\n";
  2210. }
  2211. echo "</ul>\n";
  2212. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2213. echo "<p>Aborting...</p>\n";
  2214. echo "</div>\n";
  2215. exit;
  2216. }
  2217. }
  2218. public static function Startup($sConfigFile, $bAllowMissingDB = false)
  2219. {
  2220. self::LoadConfig($sConfigFile);
  2221. if (self::DBExists())
  2222. {
  2223. CMDBSource::SelectDB(self::$m_sDBName);
  2224. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2225. self::InitPlugins();
  2226. }
  2227. else
  2228. {
  2229. if (!$bAllowMissingDB)
  2230. {
  2231. throw new CoreException('Database not found, check your configuration file', array('config_file'=>$sConfigFile, 'db_name'=>self::$m_sDBName));
  2232. }
  2233. }
  2234. }
  2235. public static function LoadConfig($sConfigFile)
  2236. {
  2237. $oConfig = new Config($sConfigFile);
  2238. foreach ($oConfig->GetAppModules() as $sModule => $sToInclude)
  2239. {
  2240. self::Plugin($sConfigFile, 'application', $sToInclude);
  2241. }
  2242. foreach ($oConfig->GetDataModels() as $sModule => $sToInclude)
  2243. {
  2244. self::Plugin($sConfigFile, 'business', $sToInclude);
  2245. }
  2246. foreach ($oConfig->GetAddons() as $sModule => $sToInclude)
  2247. {
  2248. self::Plugin($sConfigFile, 'addons', $sToInclude);
  2249. }
  2250. $sServer = $oConfig->GetDBHost();
  2251. $sUser = $oConfig->GetDBUser();
  2252. $sPwd = $oConfig->GetDBPwd();
  2253. $sSource = $oConfig->GetDBName();
  2254. $sTablePrefix = $oConfig->GetDBSubname();
  2255. // The include have been included, let's browse the existing classes and
  2256. // develop some data based on the proposed model
  2257. self::InitClasses($sTablePrefix);
  2258. self::$m_sDBName = $sSource;
  2259. self::$m_sTablePrefix = $sTablePrefix;
  2260. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  2261. }
  2262. protected static $m_aPlugins = array();
  2263. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  2264. {
  2265. self::$m_aPlugins[$sName] = array(
  2266. 'type' => $sType,
  2267. 'init' => $aInitCallSpec,
  2268. );
  2269. }
  2270. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  2271. {
  2272. if (!file_exists($sToInclude))
  2273. {
  2274. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sToInclude));
  2275. }
  2276. require_once($sToInclude);
  2277. }
  2278. protected static function InitPlugins()
  2279. {
  2280. foreach(self::$m_aPlugins as $sName => $aData)
  2281. {
  2282. $aCallSpec = @$aData['init'];
  2283. if (count($aCallSpec) == 2)
  2284. {
  2285. if (!is_callable($aCallSpec))
  2286. {
  2287. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  2288. }
  2289. call_user_func($aCallSpec);
  2290. }
  2291. }
  2292. }
  2293. // Building an object
  2294. //
  2295. //
  2296. private static $aQueryCacheGetObject = array();
  2297. private static $aQueryCacheGetObjectHits = array();
  2298. public static function GetQueryCacheStatus()
  2299. {
  2300. $aRes = array();
  2301. $iTotalHits = 0;
  2302. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  2303. {
  2304. $aRes[] = "$sClass: $iHits";
  2305. $iTotalHits += $iHits;
  2306. }
  2307. return $iTotalHits.' ('.implode(', ', $aRes).')';
  2308. }
  2309. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true)
  2310. {
  2311. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  2312. {
  2313. // NOTE: Quick and VERY dirty caching mechanism which relies on
  2314. // the fact that the string '987654321' will never appear in the
  2315. // standard query
  2316. // This will be replaced for sure with a prepared statement
  2317. // or a view... next optimization to come!
  2318. $oFilter = new DBObjectSearch($sClass);
  2319. $oFilter->AddCondition('id', 987654321, '=');
  2320. $sSQL = self::MakeSelectQuery($oFilter);
  2321. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  2322. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  2323. }
  2324. else
  2325. {
  2326. $sSQL = self::$aQueryCacheGetObject[$sClass];
  2327. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  2328. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  2329. }
  2330. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  2331. $res = CMDBSource::Query($sSQL);
  2332. $aRow = CMDBSource::FetchArray($res);
  2333. CMDBSource::FreeResult($res);
  2334. if ($bMustBeFound && empty($aRow))
  2335. {
  2336. throw new CoreException("No result for the single row query: '$sSQL'");
  2337. }
  2338. return $aRow;
  2339. }
  2340. public static function GetObjectByRow($sClass, $aRow)
  2341. {
  2342. self::_check_subclass($sClass);
  2343. // Compound objects: if available, get the final object class
  2344. //
  2345. if (!array_key_exists("finalclass", $aRow))
  2346. {
  2347. // Either this is a bug (forgot to specify a root class with a finalclass field
  2348. // Or this is the expected behavior, because the object is not made of several tables
  2349. }
  2350. elseif (empty($aRow["finalclass"]))
  2351. {
  2352. // The data is missing in the DB
  2353. // @#@ possible improvement: check that the class is valid !
  2354. $sRootClass = self::GetRootClass($sClass);
  2355. $sFinalClassField = self::DBGetClassField($sRootClass);
  2356. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  2357. }
  2358. else
  2359. {
  2360. // do the job for the real target class
  2361. $sClass = $aRow["finalclass"];
  2362. }
  2363. return new $sClass($aRow);
  2364. }
  2365. public static function GetObject($sClass, $iKey, $bMustBeFound = true)
  2366. {
  2367. self::_check_subclass($sClass);
  2368. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound);
  2369. if (empty($aRow))
  2370. {
  2371. return null;
  2372. }
  2373. return self::GetObjectByRow($sClass, $aRow);
  2374. }
  2375. public static function GetHyperLink($sTargetClass, $iKey)
  2376. {
  2377. if ($iKey < 0)
  2378. {
  2379. return "$sTargetClass: $iKey (invalid value)";
  2380. }
  2381. $oObj = self::GetObject($sTargetClass, $iKey, false);
  2382. if (is_null($oObj))
  2383. {
  2384. return "$sTargetClass: $iKey (not found)";
  2385. }
  2386. return $oObj->GetHyperLink();
  2387. }
  2388. public static function NewObject($sClass)
  2389. {
  2390. self::_check_subclass($sClass);
  2391. return new $sClass();
  2392. }
  2393. public static function GetNextKey($sClass)
  2394. {
  2395. $sRootClass = MetaModel::GetRootClass($sClass);
  2396. $sRootTable = MetaModel::DBGetTable($sRootClass);
  2397. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  2398. return $iNextKey;
  2399. }
  2400. public static function BulkDelete(DBObjectSearch $oFilter)
  2401. {
  2402. $sSQL = self::MakeDeleteQuery($oFilter);
  2403. CMDBSource::Query($sSQL);
  2404. }
  2405. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  2406. {
  2407. // $aValues is an array of $sAttCode => $value
  2408. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  2409. CMDBSource::Query($sSQL);
  2410. }
  2411. // Links
  2412. //
  2413. //
  2414. public static function EnumReferencedClasses($sClass)
  2415. {
  2416. self::_check_subclass($sClass);
  2417. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  2418. $aResult = array();
  2419. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  2420. {
  2421. if ($oAttDef->IsExternalKey())
  2422. {
  2423. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  2424. }
  2425. }
  2426. return $aResult;
  2427. }
  2428. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  2429. {
  2430. self::_check_subclass($sClass);
  2431. if ($bSkipLinkingClasses)
  2432. {
  2433. $aLinksClasses = self::EnumLinksClasses();
  2434. }
  2435. // 1-N links (referencing my class), array of sClass => array of sAttcode
  2436. $aResult = array();
  2437. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2438. {
  2439. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  2440. $aExtKeys = array();
  2441. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2442. {
  2443. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2444. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  2445. {
  2446. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  2447. // Ok, I want this one
  2448. $aExtKeys[$sAttCode] = $oAttDef;
  2449. }
  2450. }
  2451. if (count($aExtKeys) != 0)
  2452. {
  2453. $aResult[$sSomeClass] = $aExtKeys;
  2454. }
  2455. }
  2456. return $aResult;
  2457. }
  2458. public static function EnumLinksClasses()
  2459. {
  2460. // Returns a flat array of classes having at least two external keys
  2461. $aResult = array();
  2462. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2463. {
  2464. $iExtKeyCount = 0;
  2465. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2466. {
  2467. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2468. if ($oAttDef->IsExternalKey())
  2469. {
  2470. $iExtKeyCount++;
  2471. }
  2472. }
  2473. if ($iExtKeyCount >= 2)
  2474. {
  2475. $aResult[] = $sSomeClass;
  2476. }
  2477. }
  2478. return $aResult;
  2479. }
  2480. public static function EnumLinkingClasses($sClass = "")
  2481. {
  2482. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  2483. $aResult = array();
  2484. foreach (self::EnumLinksClasses() as $sSomeClass)
  2485. {
  2486. $aTargets = array();
  2487. $bFoundClass = false;
  2488. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  2489. {
  2490. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2491. if ($oAttDef->IsExternalKey())
  2492. {
  2493. $sRemoteClass = $oAttDef->GetTargetClass();
  2494. if (empty($sClass))
  2495. {
  2496. $aTargets[$sAttCode] = $sRemoteClass;
  2497. }
  2498. elseif ($sClass == $sRemoteClass)
  2499. {
  2500. $bFoundClass = true;
  2501. }
  2502. else
  2503. {
  2504. $aTargets[$sAttCode] = $sRemoteClass;
  2505. }
  2506. }
  2507. }
  2508. if (empty($sClass) || $bFoundClass)
  2509. {
  2510. $aResult[$sSomeClass] = $aTargets;
  2511. }
  2512. }
  2513. return $aResult;
  2514. }
  2515. public static function GetLinkLabel($sLinkClass, $sAttCode)
  2516. {
  2517. self::_check_subclass($sLinkClass);
  2518. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  2519. return self::GetLabel($sLinkClass, $sAttCode);
  2520. }
  2521. } // class MetaModel
  2522. // Standard attribute lists
  2523. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  2524. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  2525. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  2526. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  2527. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  2528. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  2529. ?>