metamodel.class.php 105 KB

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