metamodel.class.php 106 KB

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