metamodel.class.php 97 KB

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