metamodel.class.php 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135
  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. "key_type" => "autoincrement | string",
  855. "key_label" => "if set, then display the key as an attribute",
  856. "name_attcode" => "define wich attribute is the class name, may be an inherited attribute",
  857. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  858. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  859. "db_table" => "database table",
  860. "db_key_field" => "database field which is the key",
  861. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  862. );
  863. $sClass = self::GetCallersPHPClass("Init");
  864. foreach($aMandatParams as $sParamName=>$sParamDesc)
  865. {
  866. if (!array_key_exists($sParamName, $aParams))
  867. {
  868. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  869. }
  870. }
  871. $aCategories = explode(',', $aParams['category']);
  872. foreach ($aCategories as $sCategory)
  873. {
  874. self::$m_Category2Class[$sCategory][] = $sClass;
  875. }
  876. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  877. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  878. self::$m_aParentClasses[$sClass] = array();
  879. self::$m_aChildClasses[$sClass] = array();
  880. self::$m_aClassParams[$sClass]= $aParams;
  881. self::$m_aAttribDefs[$sClass] = array();
  882. self::$m_aAttribOrigins[$sClass] = array();
  883. self::$m_aExtKeyFriends[$sClass] = array();
  884. self::$m_aFilterDefs[$sClass] = array();
  885. self::$m_aFilterOrigins[$sClass] = array();
  886. }
  887. protected static function object_array_mergeclone($aSource1, $aSource2)
  888. {
  889. $aRes = array();
  890. foreach ($aSource1 as $key=>$object)
  891. {
  892. $aRes[$key] = clone $object;
  893. }
  894. foreach ($aSource2 as $key=>$object)
  895. {
  896. $aRes[$key] = clone $object;
  897. }
  898. return $aRes;
  899. }
  900. public static function Init_InheritAttributes($sSourceClass = null)
  901. {
  902. $sTargetClass = self::GetCallersPHPClass("Init");
  903. if (empty($sSourceClass))
  904. {
  905. // Default: inherit from parent class
  906. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  907. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  908. }
  909. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  910. {
  911. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  912. {
  913. self::$m_aAttribDefs[$sTargetClass] = array();
  914. self::$m_aAttribOrigins[$sTargetClass] = array();
  915. }
  916. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  917. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  918. }
  919. // later on, we might consider inheritance in different ways !!!
  920. //if (strlen(self::DBGetTable($sSourceClass)) != 0)
  921. if (self::HasFinalClassField(self::$m_aRootClasses[$sSourceClass]))
  922. {
  923. // Inherit the root class
  924. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  925. }
  926. else
  927. {
  928. // I am a root class, standalone as well !
  929. // ????
  930. //self::$m_aRootClasses[$sTargetClass] = $sTargetClass;
  931. }
  932. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  933. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  934. // I am the child of each and every parent...
  935. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  936. {
  937. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  938. }
  939. }
  940. public static function Init_OverloadAttributeParams($sAttCode, $aParams)
  941. {
  942. $sTargetClass = self::GetCallersPHPClass("Init");
  943. if (!self::IsValidAttCode($sTargetClass, $sAttCode))
  944. {
  945. throw new CoreException("Could not overload '$sAttCode', expecting a code from {".implode(", ", self::GetAttributesList($sTargetClass))."}");
  946. }
  947. self::$m_aAttribDefs[$sTargetClass][$sAttCode]->OverloadParams($aParams);
  948. }
  949. public static function Init_AddAttribute(AttributeDefinition $oAtt)
  950. {
  951. $sTargetClass = self::GetCallersPHPClass("Init");
  952. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  953. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  954. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  955. // Specific case of external fields:
  956. // I wanted to simplify the syntax of the declaration of objects in the biz model
  957. // Therefore, the reference to the host class is set there
  958. $oAtt->SetHostClass($sTargetClass);
  959. }
  960. public static function Init_InheritFilters($sSourceClass = null)
  961. {
  962. $sTargetClass = self::GetCallersPHPClass("Init");
  963. if (empty($sSourceClass))
  964. {
  965. // Default: inherit from parent class
  966. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  967. if (empty($sSourceClass)) return; // no filters for the mother of all classes
  968. }
  969. if (isset(self::$m_aFilterDefs[$sSourceClass]))
  970. {
  971. if (!isset(self::$m_aFilterDefs[$sTargetClass]))
  972. {
  973. self::$m_aFilterDefs[$sTargetClass] = array();
  974. self::$m_aFilterOrigins[$sTargetClass] = array();
  975. }
  976. foreach (self::$m_aFilterDefs[$sSourceClass] as $sFltCode=>$oFilter)
  977. {
  978. if ($oFilter instanceof FilterFromAttribute)
  979. {
  980. // In that case, cloning is not enough:
  981. // we must ensure that we will point to the correct
  982. // attribute definition (in case some properties are overloaded)
  983. $oAttDef1 = $oFilter->__GetRefAttribute();
  984. $oAttDef2 = self::GetAttributeDef($sTargetClass, $oAttDef1->GetCode());
  985. $oNewFilter = new FilterFromAttribute($oAttDef2);
  986. }
  987. else
  988. {
  989. $oNewFilter = clone $oFilter;
  990. }
  991. self::$m_aFilterDefs[$sTargetClass][$sFltCode] = $oNewFilter;
  992. }
  993. self::$m_aFilterOrigins[$sTargetClass] = array_merge(self::$m_aFilterOrigins[$sTargetClass], self::$m_aFilterOrigins[$sSourceClass]);
  994. }
  995. }
  996. public static function Init_OverloadFilterParams($sFltCode, $aParams)
  997. {
  998. $sTargetClass = self::GetCallersPHPClass("Init");
  999. if (!self::IsValidFilterCode($sTargetClass, $sFltCode))
  1000. {
  1001. throw new CoreException("Could not overload '$sFltCode', expecting a code from {".implode(", ", self::GetFiltersList($sTargetClass))."}");
  1002. }
  1003. self::$m_aFilterDefs[$sTargetClass][$sFltCode]->OverloadParams($aParams);
  1004. }
  1005. public static function Init_AddFilter(FilterDefinition $oFilter)
  1006. {
  1007. $sTargetClass = self::GetCallersPHPClass("Init");
  1008. self::$m_aFilterDefs[$sTargetClass][$oFilter->GetCode()] = $oFilter;
  1009. self::$m_aFilterOrigins[$sTargetClass][$oFilter->GetCode()] = $sTargetClass;
  1010. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1011. }
  1012. public static function Init_AddFilterFromAttribute($sAttCode)
  1013. {
  1014. $sTargetClass = self::GetCallersPHPClass("Init");
  1015. $oAttDef = self::GetAttributeDef($sTargetClass, $sAttCode);
  1016. $sFilterCode = $sAttCode;
  1017. $oNewFilter = new FilterFromAttribute($oAttDef);
  1018. self::$m_aFilterDefs[$sTargetClass][$sFilterCode] = $oNewFilter;
  1019. if ($oAttDef->IsExternalField())
  1020. {
  1021. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1022. $oKeyDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1023. self::$m_aFilterOrigins[$sTargetClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  1024. }
  1025. else
  1026. {
  1027. self::$m_aFilterOrigins[$sTargetClass][$sFilterCode] = $sTargetClass;
  1028. }
  1029. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1030. }
  1031. public static function Init_SetZListItems($sListCode, $aItems)
  1032. {
  1033. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1034. $sTargetClass = self::GetCallersPHPClass("Init");
  1035. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1036. }
  1037. public static function Init_DefineState($sStateCode, $aStateDef)
  1038. {
  1039. $sTargetClass = self::GetCallersPHPClass("Init");
  1040. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1041. $sParentState = $aStateDef['attribute_inherit'];
  1042. if (!empty($sParentState))
  1043. {
  1044. // Inherit from the given state (must be defined !)
  1045. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1046. // The inherited configuration could be overriden
  1047. $aStateDef['attribute_list'] = array_merge($aToInherit, $aStateDef['attribute_list']);
  1048. }
  1049. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1050. // by default, create an empty set of transitions associated to that state
  1051. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1052. }
  1053. public static function Init_DefineStimulus($oStimulus)
  1054. {
  1055. $sTargetClass = self::GetCallersPHPClass("Init");
  1056. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  1057. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1058. // Therefore, the reference to the host class is set there
  1059. $oStimulus->SetHostClass($sTargetClass);
  1060. }
  1061. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1062. {
  1063. $sTargetClass = self::GetCallersPHPClass("Init");
  1064. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1065. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1066. }
  1067. public static function Init_InheritLifecycle($sSourceClass = '')
  1068. {
  1069. $sTargetClass = self::GetCallersPHPClass("Init");
  1070. if (empty($sSourceClass))
  1071. {
  1072. // Default: inherit from parent class
  1073. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1074. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1075. }
  1076. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1077. self::$m_aStates[$sTargetClass] = clone self::$m_aStates[$sSourceClass];
  1078. self::$m_aStimuli[$sTargetClass] = clone self::$m_aStimuli[$sSourceClass];
  1079. self::$m_aTransitions[$sTargetClass] = clone self::$m_aTransitions[$sSourceClass];
  1080. }
  1081. //
  1082. // Static API
  1083. //
  1084. public static function GetRootClass($sClass = null)
  1085. {
  1086. self::_check_subclass($sClass);
  1087. return self::$m_aRootClasses[$sClass];
  1088. }
  1089. public static function IsRootClass($sClass)
  1090. {
  1091. self::_check_subclass($sClass);
  1092. return (self::GetRootClass($sClass) == $sClass);
  1093. }
  1094. public static function EnumParentClasses($sClass)
  1095. {
  1096. self::_check_subclass($sClass);
  1097. return self::$m_aParentClasses[$sClass];
  1098. }
  1099. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1100. {
  1101. self::_check_subclass($sClass);
  1102. $aRes = self::$m_aChildClasses[$sClass];
  1103. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1104. {
  1105. // Add it to the list
  1106. $aRes[] = $sClass;
  1107. }
  1108. return $aRes;
  1109. }
  1110. public static function EnumCategories()
  1111. {
  1112. return array_keys(self::$m_Category2Class);
  1113. }
  1114. // Note: use EnumChildClasses to take the compound objects into account
  1115. public static function GetSubclasses($sClass)
  1116. {
  1117. self::_check_subclass($sClass);
  1118. $aSubClasses = array();
  1119. foreach(get_declared_classes() as $sSubClass) {
  1120. if (is_subclass_of($sSubClass, $sClass))
  1121. {
  1122. $aSubClasses[] = $sSubClass;
  1123. }
  1124. }
  1125. return $aSubClasses;
  1126. }
  1127. public static function GetClasses($sCategory = '')
  1128. {
  1129. if (array_key_exists($sCategory, self::$m_Category2Class))
  1130. {
  1131. return self::$m_Category2Class[$sCategory];
  1132. }
  1133. if (count(self::$m_Category2Class) > 0)
  1134. {
  1135. throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1136. }
  1137. return array();
  1138. }
  1139. public static function IsAbstract($sClass)
  1140. {
  1141. if (strlen(self::DBGetTable($sClass)) == 0) return true;
  1142. return false;
  1143. }
  1144. protected static $m_aQueryStructCache = array();
  1145. protected static function PrepareQueryArguments($aArgs)
  1146. {
  1147. // Translate any object into scalars
  1148. //
  1149. $aScalarArgs = array();
  1150. foreach($aArgs as $sArgName => $value)
  1151. {
  1152. if (self::IsValidObject($value))
  1153. {
  1154. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1155. }
  1156. else
  1157. {
  1158. $aScalarArgs[$sArgName] = (string) $value;
  1159. }
  1160. }
  1161. // Add standard contextual arguments
  1162. //
  1163. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1164. return $aScalarArgs;
  1165. }
  1166. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array())
  1167. {
  1168. // Query caching
  1169. //
  1170. $bQueryCacheEnabled = true;
  1171. $aParams = array();
  1172. $sOqlQuery = $oFilter->ToOql($aParams); // Render with arguments in clear
  1173. if ($bQueryCacheEnabled)
  1174. {
  1175. if (array_key_exists($sOqlQuery, self::$m_aQueryStructCache))
  1176. {
  1177. // hit!
  1178. $oSelect = clone self::$m_aQueryStructCache[$sOqlQuery];
  1179. }
  1180. }
  1181. if (!isset($oSelect))
  1182. {
  1183. $aTranslation = array();
  1184. $aClassAliases = array();
  1185. $aTableAliases = array();
  1186. $oConditionTree = $oFilter->GetCriteria();
  1187. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1188. self::$m_aQueryStructCache[$sOqlQuery] = clone $oSelect;
  1189. }
  1190. // Check the order by specification, and prefix with the class alias
  1191. //
  1192. $aOrderSpec = array();
  1193. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1194. {
  1195. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetFirstJoinedClass()));
  1196. if (!is_bool($bAscending))
  1197. {
  1198. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1199. }
  1200. $aOrderSpec[$oFilter->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1201. }
  1202. // By default, force the name attribute to be the ordering key
  1203. //
  1204. if (empty($aOrderSpec))
  1205. {
  1206. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1207. {
  1208. $sNameAttCode = self::GetNameAttributeCode($sSelectedClass);
  1209. if (!empty($sNameAttCode))
  1210. {
  1211. // By default, simply order on the "name" attribute, ascending
  1212. $aOrderSpec[$sSelectedAlias.$sNameAttCode] = true;
  1213. }
  1214. }
  1215. }
  1216. // Go
  1217. //
  1218. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1219. try
  1220. {
  1221. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs);
  1222. }
  1223. catch (MissingQueryArgument $e)
  1224. {
  1225. // Add some information...
  1226. $e->addInfo('OQL', $sOqlQuery);
  1227. throw $e;
  1228. }
  1229. if (self::$m_bTraceQueries)
  1230. {
  1231. $aParams = array();
  1232. if (!array_key_exists($sOqlQuery, self::$m_aQueriesLog))
  1233. {
  1234. self::$m_aQueriesLog[$sOqlQuery] = array(
  1235. 'sql' => array(),
  1236. 'count' => 0,
  1237. );
  1238. }
  1239. self::$m_aQueriesLog[$sOqlQuery]['count']++;
  1240. self::$m_aQueriesLog[$sOqlQuery]['sql'][] = $sRes;
  1241. }
  1242. return $sRes;
  1243. }
  1244. public static function ShowQueryTrace()
  1245. {
  1246. $iTotal = 0;
  1247. foreach (self::$m_aQueriesLog as $sOql => $aQueryData)
  1248. {
  1249. echo "<h2>$sOql</h2>\n";
  1250. $iTotal += $aQueryData['count'];
  1251. echo '<p>'.$aQueryData['count'].'</p>';
  1252. echo '<p>Example: '.$aQueryData['sql'][0].'</p>';
  1253. }
  1254. echo "<h2>Total</h2>\n";
  1255. echo "<p>Count of executed queries: $iTotal</p>";
  1256. echo "<p>Count of built queries: ".count(self::$m_aQueriesLog)."</p>";
  1257. }
  1258. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1259. {
  1260. $aTranslation = array();
  1261. $aClassAliases = array();
  1262. $aTableAliases = array();
  1263. $oConditionTree = $oFilter->GetCriteria();
  1264. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1265. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1266. return $oSelect->RenderDelete($aScalarArgs);
  1267. }
  1268. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1269. {
  1270. // $aValues is an array of $sAttCode => $value
  1271. $aTranslation = array();
  1272. $aClassAliases = array();
  1273. $aTableAliases = array();
  1274. $oConditionTree = $oFilter->GetCriteria();
  1275. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues);
  1276. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1277. return $oSelect->RenderUpdate($aScalarArgs);
  1278. }
  1279. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array())
  1280. {
  1281. // Note: query class might be different than the class of the filter
  1282. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1283. // $aExpectedAtts is an array of sAttCode=>array of columns
  1284. $sClass = $oFilter->GetFirstJoinedClass();
  1285. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1286. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1287. if ($bIsOnQueriedClass)
  1288. {
  1289. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1290. }
  1291. self::DbgTrace("Entering: ".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1292. $sRootClass = self::GetRootClass($sClass);
  1293. $sKeyField = self::DBGetKey($sClass);
  1294. if ($bIsOnQueriedClass)
  1295. {
  1296. // default to the whole list of attributes + the very std id/finalclass
  1297. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1298. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1299. {
  1300. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1301. }
  1302. }
  1303. // Compute a clear view of external keys, and external attributes
  1304. // Build the list of external keys:
  1305. // -> ext keys required by a closed join ???
  1306. // -> ext keys mentionned in a 'pointing to' condition
  1307. // -> ext keys required for an external field
  1308. //
  1309. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1310. //
  1311. // Optimization: could be computed once for all (cached)
  1312. // Could be done in MakeQuerySingleTable ???
  1313. //
  1314. if ($bIsOnQueriedClass)
  1315. {
  1316. // Get all Ext keys for the queried class (??)
  1317. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1318. {
  1319. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1320. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1321. }
  1322. }
  1323. // Get all Ext keys used by the filter
  1324. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1325. {
  1326. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1327. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1328. }
  1329. // Add the ext fields used in the select (eventually adds an external key)
  1330. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1331. {
  1332. if ($oAttDef->IsExternalField())
  1333. {
  1334. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1335. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1336. {
  1337. // Add the external attribute
  1338. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1339. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1340. }
  1341. }
  1342. }
  1343. // First query built upon on the leaf (ie current) class
  1344. //
  1345. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1346. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1347. // Then we join the queries of the eventual parent classes (compound model)
  1348. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1349. {
  1350. if (self::DBGetTable($sParentClass) == "") continue;
  1351. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1352. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1353. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1354. }
  1355. // Filter on objects referencing me
  1356. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1357. {
  1358. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1359. {
  1360. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1361. // We don't want any attribute from the foreign class, just filter on an inner join
  1362. $aExpAtts = array();
  1363. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1364. //self::DbgTrace($oForeignFilter);
  1365. //self::DbgTrace($oForeignFilter->ToSibuSQL());
  1366. //self::DbgTrace($oSelectForeign);
  1367. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1368. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1369. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1370. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1371. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1372. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1373. }
  1374. }
  1375. // Filter on related objects
  1376. //
  1377. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1378. {
  1379. $oSubFilter = $aCritInfo['flt'];
  1380. $sRelCode = $aCritInfo['relcode'];
  1381. $iMaxDepth = $aCritInfo['maxdepth'];
  1382. // Get the starting point objects
  1383. $oStartSet = new CMDBObjectSet($oSubFilter);
  1384. // Get the objects related to those objects... recursively...
  1385. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1386. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1387. // #@# todo - related objects and expressions...
  1388. // Create condition
  1389. if (count($aRestriction) > 0)
  1390. {
  1391. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1392. }
  1393. else
  1394. {
  1395. // Quick N'dirty -> generate an empty set
  1396. $oSelectBase->AddCondition('false');
  1397. }
  1398. }
  1399. // Translate the conditions... and go
  1400. //
  1401. if ($bIsOnQueriedClass)
  1402. {
  1403. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1404. $oSelectBase->SetCondition($oConditionTranslated);
  1405. }
  1406. // That's all... cross fingers and we'll get some working query
  1407. //MyHelpers::var_dump_html($oSelectBase, true);
  1408. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1409. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1410. return $oSelectBase;
  1411. }
  1412. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1413. {
  1414. // $aExpectedAtts is an array of sAttCode=>sAlias
  1415. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1416. // Prepare the query for a single table (compound objects)
  1417. // Ignores the items (attributes/filters) that are not on the target table
  1418. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1419. //
  1420. // Returns an SQLQuery
  1421. //
  1422. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1423. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1424. $sTable = self::DBGetTable($sTableClass);
  1425. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1426. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1427. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToSibuSQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1428. // 1 - SELECT and UPDATE
  1429. //
  1430. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1431. //
  1432. $aSelect = array();
  1433. $aUpdateValues = array();
  1434. // 1/a - Get the key
  1435. //
  1436. if ($bIsOnQueriedClass)
  1437. {
  1438. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1439. }
  1440. // We need one pkey to be the key, let's take the one corresponding to the leaf
  1441. if ($sTableClass == $sTargetClass)
  1442. {
  1443. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1444. }
  1445. // 1/b - Get the other attributes
  1446. //
  1447. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1448. {
  1449. // Skip this attribute if not defined in this table
  1450. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1451. // Skip this attribute if not writable (means that it does not correspond
  1452. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1453. // Update...
  1454. //
  1455. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1456. {
  1457. assert ($oAttDef->IsDirectField());
  1458. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1459. {
  1460. $aUpdateValues[$sColumn] = $sValue;
  1461. }
  1462. }
  1463. // Select...
  1464. //
  1465. // Skip, if a list of fields has been specified and it is not there
  1466. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1467. if ($oAttDef->IsExternalField())
  1468. {
  1469. // skip, this will be handled in the joined tables
  1470. }
  1471. else
  1472. {
  1473. // standard field, or external key
  1474. // add it to the output
  1475. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1476. {
  1477. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1478. {
  1479. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1480. }
  1481. }
  1482. }
  1483. }
  1484. // 2 - WHERE
  1485. //
  1486. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1487. {
  1488. // Skip this filter if not defined in this table
  1489. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1490. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1491. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1492. {
  1493. // Note: I did not test it with filters relying on several expressions...
  1494. // as long as sColdID is empty, this is working, otherwise... ?
  1495. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1496. }
  1497. }
  1498. // #@# todo - See what a full text search condition should be
  1499. // 2' - WHERE / Full text search condition
  1500. //
  1501. if ($bIsOnQueriedClass)
  1502. {
  1503. $aFullText = $oFilter->GetCriteria_FullText();
  1504. }
  1505. else
  1506. {
  1507. // Pourquoi ???
  1508. $aFullText = array();
  1509. }
  1510. // 3 - The whole stuff, for this table only
  1511. //
  1512. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1513. // 4 - The external keys -> joins...
  1514. //
  1515. if (array_key_exists($sTableClass, $aExtKeys))
  1516. {
  1517. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1518. {
  1519. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1520. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1521. // In case the join was not explicitely defined in the filter,
  1522. // we need to do it now
  1523. if (empty($oExtFilter))
  1524. {
  1525. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1526. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1527. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1528. }
  1529. else
  1530. {
  1531. // The aliases should not conflict because normalization occured while building the filter
  1532. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1533. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1534. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1535. }
  1536. // Specify expected attributes for the target class query
  1537. // ... and use the current alias !
  1538. $aExpAtts = array();
  1539. $aIntermediateTranslation = array();
  1540. foreach($aExtFields as $sAttCode => $oAtt)
  1541. {
  1542. $sExtAttCode = $oAtt->GetExtAttCode();
  1543. if (array_key_exists($sAttCode, $aExpectedAtts))
  1544. {
  1545. // Request this attribute... transmit the alias !
  1546. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1547. }
  1548. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1549. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1550. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1551. {
  1552. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1553. }
  1554. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1555. }
  1556. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1557. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1558. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1559. $sLocalKeyField = current($oKeyAttDef->GetSQLExpressions()); // get the first column for an external key
  1560. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1561. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1562. if ($oKeyAttDef->IsNullAllowed())
  1563. {
  1564. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1565. }
  1566. else
  1567. {
  1568. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1569. }
  1570. }
  1571. }
  1572. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1573. return $oSelectBase;
  1574. }
  1575. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1576. {
  1577. if (!array_key_exists($sNewName, $aAliases))
  1578. {
  1579. $aAliases[$sNewName] = $sRealName;
  1580. return $sNewName;
  1581. }
  1582. for ($i = 1 ; $i < 100 ; $i++)
  1583. {
  1584. $sAnAlias = $sNewName.$i;
  1585. if (!array_key_exists($sAnAlias, $aAliases))
  1586. {
  1587. // Create that new alias
  1588. $aAliases[$sAnAlias] = $sRealName;
  1589. return $sAnAlias;
  1590. }
  1591. }
  1592. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1593. }
  1594. public static function CheckDefinitions()
  1595. {
  1596. if (count(self::GetClasses()) == 0)
  1597. {
  1598. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1599. }
  1600. $aErrors = array();
  1601. $aSugFix = array();
  1602. foreach (self::GetClasses() as $sClass)
  1603. {
  1604. if (self::IsAbstract($sClass)) continue;
  1605. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1606. if (empty($sNameAttCode))
  1607. {
  1608. // let's try this !!!
  1609. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1610. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1611. }
  1612. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1613. {
  1614. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1615. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1616. }
  1617. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1618. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1619. {
  1620. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1621. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1622. }
  1623. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1624. {
  1625. // It makes no sense to check the attributes again and again in the subclasses
  1626. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1627. if ($oAttDef->IsExternalKey())
  1628. {
  1629. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1630. {
  1631. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1632. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1633. }
  1634. }
  1635. elseif ($oAttDef->IsExternalField())
  1636. {
  1637. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1638. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1639. {
  1640. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1641. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1642. }
  1643. else
  1644. {
  1645. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1646. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1647. $sExtAttCode = $oAttDef->GetExtAttCode();
  1648. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1649. {
  1650. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1651. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1652. }
  1653. }
  1654. }
  1655. else // standard attributes
  1656. {
  1657. // Check that the default values definition is a valid object!
  1658. $oValSetDef = $oAttDef->GetValuesDef();
  1659. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1660. {
  1661. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1662. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1663. }
  1664. else
  1665. {
  1666. // Default value must be listed in the allowed values (if defined)
  1667. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1668. if (!is_null($aAllowedValues))
  1669. {
  1670. $sDefaultValue = $oAttDef->GetDefaultValue();
  1671. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  1672. {
  1673. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  1674. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  1675. }
  1676. }
  1677. }
  1678. }
  1679. // Check dependencies
  1680. if ($oAttDef->IsWritable())
  1681. {
  1682. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  1683. {
  1684. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  1685. {
  1686. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  1687. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1688. }
  1689. }
  1690. }
  1691. }
  1692. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  1693. {
  1694. if (method_exists($oFilterDef, '__GetRefAttribute'))
  1695. {
  1696. $oAttDef = $oFilterDef->__GetRefAttribute();
  1697. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  1698. {
  1699. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  1700. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1701. }
  1702. }
  1703. }
  1704. // Lifecycle
  1705. //
  1706. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1707. if (strlen($sStateAttCode) > 0)
  1708. {
  1709. // Lifecycle - check that the state attribute does exist as an attribute
  1710. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  1711. {
  1712. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  1713. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1714. }
  1715. else
  1716. {
  1717. // Lifecycle - check that there is a value set constraint on the state attribute
  1718. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  1719. $aStates = array_keys(self::EnumStates($sClass));
  1720. if (is_null($aAllowedValuesRaw))
  1721. {
  1722. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  1723. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  1724. }
  1725. else
  1726. {
  1727. $aAllowedValues = array_keys($aAllowedValuesRaw);
  1728. // Lifecycle - check the the state attribute allowed values are defined states
  1729. foreach($aAllowedValues as $sValue)
  1730. {
  1731. if (!in_array($sValue, $aStates))
  1732. {
  1733. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  1734. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1735. }
  1736. }
  1737. // Lifecycle - check that defined states are allowed values
  1738. foreach($aStates as $sStateValue)
  1739. {
  1740. if (!in_array($sStateValue, $aAllowedValues))
  1741. {
  1742. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  1743. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1744. }
  1745. }
  1746. }
  1747. // Lifcycle - check that the action handlers are defined
  1748. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  1749. {
  1750. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  1751. {
  1752. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1753. {
  1754. if (!method_exists($sClass, $sActionHandler))
  1755. {
  1756. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  1757. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  1758. }
  1759. }
  1760. }
  1761. }
  1762. }
  1763. }
  1764. // ZList
  1765. //
  1766. foreach(self::EnumZLists() as $sListCode)
  1767. {
  1768. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  1769. {
  1770. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  1771. {
  1772. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  1773. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1774. }
  1775. }
  1776. }
  1777. }
  1778. if (count($aErrors) > 0)
  1779. {
  1780. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  1781. echo "<h3>Business model inconsistencies have been found</h3>\n";
  1782. // #@# later -> this is the responsibility of the caller to format the output
  1783. foreach ($aErrors as $sClass => $aMessages)
  1784. {
  1785. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  1786. echo "<ul class=\"treeview\">\n";
  1787. $i = 0;
  1788. foreach ($aMessages as $sMsg)
  1789. {
  1790. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  1791. $i++;
  1792. }
  1793. echo "</ul>\n";
  1794. }
  1795. echo "<p>Aborting...</p>\n";
  1796. echo "</div>\n";
  1797. exit;
  1798. }
  1799. }
  1800. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  1801. {
  1802. if (empty($sRepairUrl)) return;
  1803. if (count($aSQLFixes) == 0) return;
  1804. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  1805. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aSQLFixes))."\">\n";
  1806. echo " <input type=\"submit\" value=\" Apply the changes (".count($aSQLFixes)." queries) \">\n";
  1807. echo "</form>\n";
  1808. }
  1809. public static function DBExists($bMustBeComplete = true)
  1810. {
  1811. // returns true if at least one table exists
  1812. //
  1813. if (!CMDBSource::IsDB(self::$m_sDBName))
  1814. {
  1815. return false;
  1816. }
  1817. CMDBSource::SelectDB(self::$m_sDBName);
  1818. $aFound = array();
  1819. $aMissing = array();
  1820. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1821. {
  1822. if (CMDBSource::IsTable($sTable))
  1823. {
  1824. $aFound[] = $sTable;
  1825. }
  1826. else
  1827. {
  1828. $aMissing[] = $sTable;
  1829. }
  1830. }
  1831. if (count($aFound) == 0)
  1832. {
  1833. // no expected table has been found
  1834. return false;
  1835. }
  1836. else
  1837. {
  1838. if (count($aMissing) == 0)
  1839. {
  1840. // the database is complete (still, could be some fields missing!)
  1841. return true;
  1842. }
  1843. else
  1844. {
  1845. // not all the tables, could be an older version
  1846. if ($bMustBeComplete)
  1847. {
  1848. return false;
  1849. }
  1850. else
  1851. {
  1852. return true;
  1853. }
  1854. }
  1855. }
  1856. }
  1857. public static function DBDrop()
  1858. {
  1859. $bDropEntireDB = true;
  1860. if (!empty(self::$m_sTablePrefix))
  1861. {
  1862. // Do drop only tables corresponding to the sub-database (table prefix)
  1863. // then possibly drop the DB itself (if no table remain)
  1864. foreach (CMDBSource::EnumTables() as $sTable)
  1865. {
  1866. // perform a case insensitive test because on Windows the table names become lowercase :-(
  1867. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  1868. {
  1869. CMDBSource::DropTable($sTable);
  1870. }
  1871. else
  1872. {
  1873. // There is at least one table which is out of the scope of the current application
  1874. $bDropEntireDB = false;
  1875. }
  1876. }
  1877. }
  1878. if ($bDropEntireDB)
  1879. {
  1880. CMDBSource::DropDB(self::$m_sDBName);
  1881. }
  1882. }
  1883. public static function DBCreate()
  1884. {
  1885. // Note: we have to check if the DB does exist, because we may share the DB
  1886. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  1887. if (!CMDBSource::IsDB(self::$m_sDBName))
  1888. {
  1889. CMDBSource::CreateDB(self::$m_sDBName);
  1890. }
  1891. self::DBCreateTables();
  1892. }
  1893. protected static function DBCreateTables()
  1894. {
  1895. list($aErrors, $aSugFix) = self::DBCheckFormat();
  1896. $aSQL = array();
  1897. foreach ($aSugFix as $sClass => $aTarget)
  1898. {
  1899. foreach ($aTarget as $aQueries)
  1900. {
  1901. foreach ($aQueries as $sQuery)
  1902. {
  1903. //$aSQL[] = $sQuery;
  1904. // forces a refresh of cached information
  1905. CMDBSource::CreateTable($sQuery);
  1906. }
  1907. }
  1908. }
  1909. // does not work -how to have multiple statements in a single query?
  1910. // $sDoCreateAll = implode(" ; ", $aSQL);
  1911. }
  1912. public static function DBDump()
  1913. {
  1914. $aDataDump = array();
  1915. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1916. {
  1917. $aRows = CMDBSource::DumpTable($sTable);
  1918. $aDataDump[$sTable] = $aRows;
  1919. }
  1920. return $aDataDump;
  1921. }
  1922. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  1923. {
  1924. $sValue = Dict::S($sKey, 'x-no-nothing');
  1925. if ($sValue == 'x-no-nothing')
  1926. {
  1927. $bNotInDico = true;
  1928. $sValue = $sValueFromOldSystem;
  1929. if (strlen($sValue) == 0)
  1930. {
  1931. $sValue = $sDefaultValue;
  1932. }
  1933. }
  1934. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  1935. }
  1936. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  1937. {
  1938. $sRes = '';
  1939. $sRes .= "// Dictionnay conventions\n";
  1940. $sRes .= htmlentities("// Class:<class_name>\n");
  1941. $sRes .= htmlentities("// Class:<class_name>+\n");
  1942. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n");
  1943. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n");
  1944. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n");
  1945. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n");
  1946. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n");
  1947. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n");
  1948. $sRes .= "\n";
  1949. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  1950. // Need to invent the "module", to characterize the origins of a class
  1951. if (strlen($sModules) == 0)
  1952. {
  1953. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  1954. }
  1955. else
  1956. {
  1957. $aModules = explode(', ', $sModules);
  1958. }
  1959. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  1960. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  1961. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  1962. foreach ($aModules as $sCategory)
  1963. {
  1964. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  1965. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  1966. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  1967. $sRes .= "//\n";
  1968. $sRes .= "\n";
  1969. foreach (self::GetClasses($sCategory) as $sClass)
  1970. {
  1971. if (self::IsAbstract($sClass)) continue;
  1972. $bNotInDico = false;
  1973. $sClassRes = "//\n";
  1974. $sClassRes .= "// Class: $sClass\n";
  1975. $sClassRes .= "//\n";
  1976. $sClassRes .= "\n";
  1977. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  1978. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  1979. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  1980. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1981. {
  1982. // Skip this attribute if not originaly defined in this class
  1983. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1984. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  1985. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  1986. if ($oAttDef instanceof AttributeEnum)
  1987. {
  1988. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  1989. {
  1990. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  1991. {
  1992. if (array_key_exists('label', $aStateData))
  1993. {
  1994. $sValue = $aStateData['label'];
  1995. }
  1996. else
  1997. {
  1998. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  1999. }
  2000. if (array_key_exists('description', $aStateData))
  2001. {
  2002. $sValuePlus = $aStateData['description'];
  2003. }
  2004. else
  2005. {
  2006. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  2007. }
  2008. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  2009. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  2010. }
  2011. }
  2012. else
  2013. {
  2014. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  2015. {
  2016. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  2017. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  2018. }
  2019. }
  2020. }
  2021. }
  2022. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  2023. {
  2024. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  2025. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  2026. }
  2027. $sClassRes .= "));\n";
  2028. $sClassRes .= "\n";
  2029. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  2030. {
  2031. $sRes .= $sClassRes;
  2032. }
  2033. }
  2034. }
  2035. return $sRes;
  2036. }
  2037. public static function DBCheckFormat()
  2038. {
  2039. $aErrors = array();
  2040. $aSugFix = array();
  2041. foreach (self::GetClasses() as $sClass)
  2042. {
  2043. if (self::IsAbstract($sClass)) continue;
  2044. // Check that the table exists
  2045. //
  2046. $sTable = self::DBGetTable($sClass);
  2047. $sKeyField = self::DBGetKey($sClass);
  2048. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  2049. if (!CMDBSource::IsTable($sTable))
  2050. {
  2051. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  2052. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  2053. }
  2054. // Check that the key field exists
  2055. //
  2056. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  2057. {
  2058. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  2059. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  2060. }
  2061. else
  2062. {
  2063. // Check the key field properties
  2064. //
  2065. if (!CMDBSource::IsKey($sTable, $sKeyField))
  2066. {
  2067. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  2068. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  2069. }
  2070. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  2071. {
  2072. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  2073. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  2074. }
  2075. }
  2076. // Check that any defined field exists
  2077. //
  2078. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  2079. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2080. {
  2081. // Skip this attribute if not originaly defined in this class
  2082. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2083. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2084. {
  2085. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  2086. if (!CMDBSource::IsField($sTable, $sField))
  2087. {
  2088. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  2089. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  2090. if ($oAttDef->IsExternalKey())
  2091. {
  2092. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2093. }
  2094. }
  2095. else
  2096. {
  2097. // The field already exists, does it have the relevant properties?
  2098. //
  2099. $bToBeChanged = false;
  2100. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  2101. {
  2102. $bToBeChanged = true;
  2103. if ($oAttDef->IsNullAllowed())
  2104. {
  2105. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  2106. }
  2107. else
  2108. {
  2109. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  2110. }
  2111. }
  2112. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  2113. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  2114. {
  2115. $bToBeChanged = true;
  2116. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  2117. }
  2118. if ($bToBeChanged)
  2119. {
  2120. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  2121. }
  2122. // Create indexes (external keys only... so far)
  2123. //
  2124. if ($oAttDef->IsExternalKey() && !CMDBSource::HasIndex($sTable, $sField))
  2125. {
  2126. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  2127. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2128. }
  2129. }
  2130. }
  2131. }
  2132. }
  2133. return array($aErrors, $aSugFix);
  2134. }
  2135. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  2136. {
  2137. $sRootClass = self::GetRootClass($sClass);
  2138. $sTable = self::DBGetTable($sClass);
  2139. $sKeyField = self::DBGetKey($sClass);
  2140. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2141. {
  2142. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2143. }
  2144. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2145. if (count($aWrongRecords) == 0) return;
  2146. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2147. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2148. foreach ($aWrongRecords as $iRecordId)
  2149. {
  2150. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2151. {
  2152. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2153. {
  2154. case 'Delete':
  2155. // Already planned for a deletion
  2156. // Let's concatenate the errors description together
  2157. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2158. break;
  2159. case 'Update':
  2160. // Let's plan a deletion
  2161. break;
  2162. }
  2163. }
  2164. else
  2165. {
  2166. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2167. }
  2168. if (!$bProcessingFriends)
  2169. {
  2170. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2171. {
  2172. // Something new to be deleted...
  2173. $iNewDelCount++;
  2174. }
  2175. }
  2176. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2177. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2178. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2179. $aPlannedDel[$sTable][] = $iRecordId;
  2180. }
  2181. // Now make sure that we would delete the records of the other tables for that class
  2182. //
  2183. if (!$bProcessingFriends)
  2184. {
  2185. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2186. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2187. {
  2188. $sFriendTable = self::DBGetTable($sFriendClass);
  2189. $sFriendKey = self::DBGetKey($sFriendClass);
  2190. // skip the current table
  2191. if ($sFriendTable == $sTable) continue;
  2192. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2193. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2194. }
  2195. }
  2196. }
  2197. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2198. {
  2199. $sRootClass = self::GetRootClass($sClass);
  2200. $sTable = self::DBGetTable($sClass);
  2201. $sKeyField = self::DBGetKey($sClass);
  2202. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2203. {
  2204. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2205. }
  2206. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2207. if (count($aWrongRecords) == 0) return;
  2208. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2209. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2210. foreach ($aWrongRecords as $iRecordId)
  2211. {
  2212. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2213. {
  2214. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2215. {
  2216. case 'Delete':
  2217. // No need to update, the record will be deleted!
  2218. break;
  2219. case 'Update':
  2220. // Already planned for an update
  2221. // Add this new update spec to the list
  2222. $bFoundSameSpec = false;
  2223. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2224. {
  2225. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2226. {
  2227. $bFoundSameSpec = true;
  2228. }
  2229. }
  2230. if (!$bFoundSameSpec)
  2231. {
  2232. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2233. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2234. }
  2235. break;
  2236. }
  2237. }
  2238. else
  2239. {
  2240. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2241. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2242. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2243. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2244. }
  2245. }
  2246. }
  2247. // returns the count of records found for deletion
  2248. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2249. {
  2250. foreach (self::GetClasses() as $sClass)
  2251. {
  2252. if (self::IsAbstract($sClass)) continue;
  2253. $sRootClass = self::GetRootClass($sClass);
  2254. $sTable = self::DBGetTable($sClass);
  2255. $sKeyField = self::DBGetKey($sClass);
  2256. // Check that the final class field contains the name of a class which inherited from the current class
  2257. //
  2258. if (self::HasFinalClassField($sClass))
  2259. {
  2260. $sFinalClassField = self::DBGetClassField($sClass);
  2261. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2262. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2263. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2264. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2265. }
  2266. // Compound objects model - node/leaf classes (not the root itself)
  2267. //
  2268. if (!self::IsStandaloneClass($sClass) && !self::HasFinalClassField($sClass))
  2269. {
  2270. $sRootTable = self::DBGetTable($sRootClass);
  2271. $sRootKey = self::DBGetKey($sRootClass);
  2272. $sFinalClassField = self::DBGetClassField($sRootClass);
  2273. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2274. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2275. // Check that any record found here has its counterpart in the root table
  2276. // and which refers to a child class
  2277. //
  2278. $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";
  2279. 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);
  2280. // Check that any record found in the root table and referring to a child class
  2281. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2282. //
  2283. $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)";
  2284. 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);
  2285. }
  2286. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2287. {
  2288. // Skip this attribute if not defined in this table
  2289. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2290. if ($oAttDef->IsExternalKey())
  2291. {
  2292. // Check that any external field is pointing to an existing object
  2293. //
  2294. $sRemoteClass = $oAttDef->GetTargetClass();
  2295. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2296. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2297. $sExtKeyField = current($oAttDef->GetSQLExpressions()); // get the first column for an external key
  2298. // Note: a class/table may have an external key on itself
  2299. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2300. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2301. if ($oAttDef->IsNullAllowed())
  2302. {
  2303. // Exclude the records pointing to 0/null from the errors
  2304. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2305. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2306. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2307. }
  2308. else
  2309. {
  2310. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2311. }
  2312. // Do almost the same, taking into account the records planned for deletion
  2313. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2314. {
  2315. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2316. // but in that case you won't be able to track the root cause (cascading)
  2317. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2318. if ($oAttDef->IsNullAllowed())
  2319. {
  2320. // Exclude the records pointing to 0/null from the errors
  2321. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2322. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2323. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2324. }
  2325. else
  2326. {
  2327. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2328. }
  2329. }
  2330. }
  2331. else if ($oAttDef->IsDirectField())
  2332. {
  2333. // Check that the values fit the allowed values
  2334. //
  2335. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2336. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2337. {
  2338. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2339. $sMyAttributeField = current($oAttDef->GetSQLExpressions()); // get the first column for the moment
  2340. $sDefaultValue = $oAttDef->GetDefaultValue();
  2341. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2342. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2343. }
  2344. }
  2345. }
  2346. }
  2347. }
  2348. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2349. {
  2350. // Records in error, and action to be taken: delete or update
  2351. // by RootClass/Table/Record
  2352. $aErrorsAndFixes = array();
  2353. // Records to be ignored in the current/next pass
  2354. // by Table = array of RecordId
  2355. $aPlannedDel = array();
  2356. // Count of errors in the next pass: no error means that we can leave...
  2357. $iErrorCount = 0;
  2358. // Limit in case of a bug in the algorythm
  2359. $iLoopCount = 0;
  2360. $iNewDelCount = 1; // startup...
  2361. while ($iNewDelCount > 0)
  2362. {
  2363. $iNewDelCount = 0;
  2364. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2365. $iErrorCount += $iNewDelCount;
  2366. // Safety net #1 - limit the planned deletions
  2367. //
  2368. $iMaxDel = 1000;
  2369. $iPlannedDel = 0;
  2370. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2371. {
  2372. $iPlannedDel += count($aPlannedDelOnTable);
  2373. }
  2374. if ($iPlannedDel > $iMaxDel)
  2375. {
  2376. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2377. break;
  2378. }
  2379. // Safety net #2 - limit the iterations
  2380. //
  2381. $iLoopCount++;
  2382. $iMaxLoops = 10;
  2383. if ($iLoopCount > $iMaxLoops)
  2384. {
  2385. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2386. break;
  2387. }
  2388. }
  2389. // Display the results
  2390. //
  2391. $iIssueCount = 0;
  2392. $aFixesDelete = array();
  2393. $aFixesUpdate = array();
  2394. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2395. {
  2396. foreach ($aTables as $sTable => $aRecords)
  2397. {
  2398. foreach ($aRecords as $iRecord => $aError)
  2399. {
  2400. $sAction = $aError['Action'];
  2401. $sReason = $aError['Reason'];
  2402. $iPass = $aError['Pass'];
  2403. switch ($sAction)
  2404. {
  2405. case 'Delete':
  2406. $sActionDetails = "";
  2407. $aFixesDelete[$sTable][] = $iRecord;
  2408. break;
  2409. case 'Update':
  2410. $aUpdateDesc = array();
  2411. foreach($aError['Action_Details'] as $aUpdateSpec)
  2412. {
  2413. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2414. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2415. }
  2416. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2417. break;
  2418. default:
  2419. $sActionDetails = "bug: unknown action '$sAction'";
  2420. }
  2421. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2422. $iIssueCount++;
  2423. }
  2424. }
  2425. }
  2426. if ($iIssueCount > 0)
  2427. {
  2428. // Build the queries to fix in the database
  2429. //
  2430. // First step, be able to get class data out of the table name
  2431. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2432. $aTable2ClassProp = array();
  2433. foreach (self::GetClasses() as $sClass)
  2434. {
  2435. if (self::IsAbstract($sClass)) continue;
  2436. $sRootClass = self::GetRootClass($sClass);
  2437. $sTable = self::DBGetTable($sClass);
  2438. $sKeyField = self::DBGetKey($sClass);
  2439. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2440. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2441. }
  2442. // Second step, build a flat list of SQL queries
  2443. $aSQLFixes = array();
  2444. $iPlannedUpdate = 0;
  2445. foreach ($aFixesUpdate as $sTable => $aColumns)
  2446. {
  2447. foreach ($aColumns as $sColumn => $aNewValues)
  2448. {
  2449. foreach ($aNewValues as $sNewValue => $aRecords)
  2450. {
  2451. $iPlannedUpdate += count($aRecords);
  2452. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2453. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2454. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2455. }
  2456. }
  2457. }
  2458. $iPlannedDel = 0;
  2459. foreach ($aFixesDelete as $sTable => $aRecords)
  2460. {
  2461. $iPlannedDel += count($aRecords);
  2462. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2463. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2464. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2465. }
  2466. // Report the results
  2467. //
  2468. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2469. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2470. // #@# later -> this is the responsibility of the caller to format the output
  2471. echo "<ul class=\"treeview\">\n";
  2472. foreach ($aIssues as $sIssueDesc)
  2473. {
  2474. echo "<li>$sIssueDesc</li>\n";
  2475. }
  2476. echo "</ul>\n";
  2477. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2478. echo "<p>Aborting...</p>\n";
  2479. echo "</div>\n";
  2480. exit;
  2481. }
  2482. }
  2483. public static function Startup($sConfigFile, $bAllowMissingDB = false)
  2484. {
  2485. self::LoadConfig($sConfigFile);
  2486. if (self::DBExists())
  2487. {
  2488. CMDBSource::SelectDB(self::$m_sDBName);
  2489. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2490. self::InitPlugins();
  2491. }
  2492. else
  2493. {
  2494. if (!$bAllowMissingDB)
  2495. {
  2496. throw new CoreException('Database not found, check your configuration file', array('config_file'=>$sConfigFile, 'db_name'=>self::$m_sDBName));
  2497. }
  2498. }
  2499. }
  2500. public static function LoadConfig($sConfigFile)
  2501. {
  2502. $oConfig = new Config($sConfigFile);
  2503. foreach ($oConfig->GetAppModules() as $sModule => $sToInclude)
  2504. {
  2505. self::Plugin($sConfigFile, 'application', $sToInclude);
  2506. }
  2507. foreach ($oConfig->GetDataModels() as $sModule => $sToInclude)
  2508. {
  2509. self::Plugin($sConfigFile, 'business', $sToInclude);
  2510. }
  2511. foreach ($oConfig->GetAddons() as $sModule => $sToInclude)
  2512. {
  2513. self::Plugin($sConfigFile, 'addons', $sToInclude);
  2514. }
  2515. foreach ($oConfig->GetDictionaries() as $sModule => $sToInclude)
  2516. {
  2517. self::Plugin($sConfigFile, 'dictionaries', $sToInclude);
  2518. }
  2519. // Set the language... after the dictionaries have been loaded!
  2520. Dict::SetLanguage($oConfig->GetDefaultLanguage());
  2521. $sServer = $oConfig->GetDBHost();
  2522. $sUser = $oConfig->GetDBUser();
  2523. $sPwd = $oConfig->GetDBPwd();
  2524. $sSource = $oConfig->GetDBName();
  2525. $sTablePrefix = $oConfig->GetDBSubname();
  2526. // The include have been included, let's browse the existing classes and
  2527. // develop some data based on the proposed model
  2528. self::InitClasses($sTablePrefix);
  2529. self::$m_sDBName = $sSource;
  2530. self::$m_sTablePrefix = $sTablePrefix;
  2531. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  2532. }
  2533. protected static $m_aPlugins = array();
  2534. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  2535. {
  2536. self::$m_aPlugins[$sName] = array(
  2537. 'type' => $sType,
  2538. 'init' => $aInitCallSpec,
  2539. );
  2540. }
  2541. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  2542. {
  2543. if (!file_exists($sToInclude))
  2544. {
  2545. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sToInclude));
  2546. }
  2547. require_once($sToInclude);
  2548. }
  2549. protected static function InitPlugins()
  2550. {
  2551. foreach(self::$m_aPlugins as $sName => $aData)
  2552. {
  2553. $aCallSpec = @$aData['init'];
  2554. if (count($aCallSpec) == 2)
  2555. {
  2556. if (!is_callable($aCallSpec))
  2557. {
  2558. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  2559. }
  2560. call_user_func($aCallSpec);
  2561. }
  2562. }
  2563. }
  2564. // Building an object
  2565. //
  2566. //
  2567. private static $aQueryCacheGetObject = array();
  2568. private static $aQueryCacheGetObjectHits = array();
  2569. public static function GetQueryCacheStatus()
  2570. {
  2571. $aRes = array();
  2572. $iTotalHits = 0;
  2573. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  2574. {
  2575. $aRes[] = "$sClass: $iHits";
  2576. $iTotalHits += $iHits;
  2577. }
  2578. return $iTotalHits.' ('.implode(', ', $aRes).')';
  2579. }
  2580. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true)
  2581. {
  2582. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  2583. {
  2584. // NOTE: Quick and VERY dirty caching mechanism which relies on
  2585. // the fact that the string '987654321' will never appear in the
  2586. // standard query
  2587. // This will be replaced for sure with a prepared statement
  2588. // or a view... next optimization to come!
  2589. $oFilter = new DBObjectSearch($sClass);
  2590. $oFilter->AddCondition('id', 987654321, '=');
  2591. $sSQL = self::MakeSelectQuery($oFilter);
  2592. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  2593. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  2594. }
  2595. else
  2596. {
  2597. $sSQL = self::$aQueryCacheGetObject[$sClass];
  2598. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  2599. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  2600. }
  2601. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  2602. $res = CMDBSource::Query($sSQL);
  2603. $aRow = CMDBSource::FetchArray($res);
  2604. CMDBSource::FreeResult($res);
  2605. if ($bMustBeFound && empty($aRow))
  2606. {
  2607. throw new CoreException("No result for the single row query: '$sSQL'");
  2608. }
  2609. return $aRow;
  2610. }
  2611. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  2612. {
  2613. self::_check_subclass($sClass);
  2614. if (strlen($sClassAlias) == 0)
  2615. {
  2616. $sClassAlias = $sClass;
  2617. }
  2618. // Compound objects: if available, get the final object class
  2619. //
  2620. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  2621. {
  2622. // Either this is a bug (forgot to specify a root class with a finalclass field
  2623. // Or this is the expected behavior, because the object is not made of several tables
  2624. }
  2625. elseif (empty($aRow[$sClassAlias."finalclass"]))
  2626. {
  2627. // The data is missing in the DB
  2628. // @#@ possible improvement: check that the class is valid !
  2629. $sRootClass = self::GetRootClass($sClass);
  2630. $sFinalClassField = self::DBGetClassField($sRootClass);
  2631. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  2632. }
  2633. else
  2634. {
  2635. // do the job for the real target class
  2636. $sClass = $aRow[$sClassAlias."finalclass"];
  2637. }
  2638. return new $sClass($aRow, $sClassAlias);
  2639. }
  2640. public static function GetObject($sClass, $iKey, $bMustBeFound = true)
  2641. {
  2642. self::_check_subclass($sClass);
  2643. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound);
  2644. if (empty($aRow))
  2645. {
  2646. return null;
  2647. }
  2648. return self::GetObjectByRow($sClass, $aRow);
  2649. }
  2650. public static function GetHyperLink($sTargetClass, $iKey)
  2651. {
  2652. if ($iKey < 0)
  2653. {
  2654. return "$sTargetClass: $iKey (invalid value)";
  2655. }
  2656. $oObj = self::GetObject($sTargetClass, $iKey, false);
  2657. if (is_null($oObj))
  2658. {
  2659. return "$sTargetClass: $iKey (not found)";
  2660. }
  2661. return $oObj->GetHyperLink();
  2662. }
  2663. public static function NewObject($sClass)
  2664. {
  2665. self::_check_subclass($sClass);
  2666. return new $sClass();
  2667. }
  2668. public static function GetNextKey($sClass)
  2669. {
  2670. $sRootClass = MetaModel::GetRootClass($sClass);
  2671. $sRootTable = MetaModel::DBGetTable($sRootClass);
  2672. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  2673. return $iNextKey;
  2674. }
  2675. public static function BulkDelete(DBObjectSearch $oFilter)
  2676. {
  2677. $sSQL = self::MakeDeleteQuery($oFilter);
  2678. CMDBSource::Query($sSQL);
  2679. }
  2680. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  2681. {
  2682. // $aValues is an array of $sAttCode => $value
  2683. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  2684. CMDBSource::Query($sSQL);
  2685. }
  2686. // Links
  2687. //
  2688. //
  2689. public static function EnumReferencedClasses($sClass)
  2690. {
  2691. self::_check_subclass($sClass);
  2692. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  2693. $aResult = array();
  2694. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  2695. {
  2696. if ($oAttDef->IsExternalKey())
  2697. {
  2698. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  2699. }
  2700. }
  2701. return $aResult;
  2702. }
  2703. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  2704. {
  2705. self::_check_subclass($sClass);
  2706. if ($bSkipLinkingClasses)
  2707. {
  2708. $aLinksClasses = self::EnumLinksClasses();
  2709. }
  2710. // 1-N links (referencing my class), array of sClass => array of sAttcode
  2711. $aResult = array();
  2712. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2713. {
  2714. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  2715. $aExtKeys = array();
  2716. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2717. {
  2718. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2719. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  2720. {
  2721. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  2722. // Ok, I want this one
  2723. $aExtKeys[$sAttCode] = $oAttDef;
  2724. }
  2725. }
  2726. if (count($aExtKeys) != 0)
  2727. {
  2728. $aResult[$sSomeClass] = $aExtKeys;
  2729. }
  2730. }
  2731. return $aResult;
  2732. }
  2733. public static function EnumLinksClasses()
  2734. {
  2735. // Returns a flat array of classes having at least two external keys
  2736. $aResult = array();
  2737. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2738. {
  2739. $iExtKeyCount = 0;
  2740. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2741. {
  2742. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2743. if ($oAttDef->IsExternalKey())
  2744. {
  2745. $iExtKeyCount++;
  2746. }
  2747. }
  2748. if ($iExtKeyCount >= 2)
  2749. {
  2750. $aResult[] = $sSomeClass;
  2751. }
  2752. }
  2753. return $aResult;
  2754. }
  2755. public static function EnumLinkingClasses($sClass = "")
  2756. {
  2757. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  2758. $aResult = array();
  2759. foreach (self::EnumLinksClasses() as $sSomeClass)
  2760. {
  2761. $aTargets = array();
  2762. $bFoundClass = false;
  2763. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  2764. {
  2765. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2766. if ($oAttDef->IsExternalKey())
  2767. {
  2768. $sRemoteClass = $oAttDef->GetTargetClass();
  2769. if (empty($sClass))
  2770. {
  2771. $aTargets[$sAttCode] = $sRemoteClass;
  2772. }
  2773. elseif ($sClass == $sRemoteClass)
  2774. {
  2775. $bFoundClass = true;
  2776. }
  2777. else
  2778. {
  2779. $aTargets[$sAttCode] = $sRemoteClass;
  2780. }
  2781. }
  2782. }
  2783. if (empty($sClass) || $bFoundClass)
  2784. {
  2785. $aResult[$sSomeClass] = $aTargets;
  2786. }
  2787. }
  2788. return $aResult;
  2789. }
  2790. public static function GetLinkLabel($sLinkClass, $sAttCode)
  2791. {
  2792. self::_check_subclass($sLinkClass);
  2793. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  2794. return self::GetLabel($sLinkClass, $sAttCode);
  2795. }
  2796. /**
  2797. * Replaces all the parameters by the values passed in the hash array
  2798. */
  2799. static public function ApplyParams($aInput, $aParams)
  2800. {
  2801. $aSearches = array();
  2802. $aReplacements = array();
  2803. foreach($aParams as $sSearch => $sReplace)
  2804. {
  2805. $aSearches[] = '$'.$sSearch.'$';
  2806. $aReplacements[] = $sReplace;
  2807. }
  2808. return str_replace($aSearches, $aReplacements, $aInput);
  2809. }
  2810. } // class MetaModel
  2811. // Standard attribute lists
  2812. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  2813. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  2814. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  2815. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  2816. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  2817. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  2818. ?>