metamodel.class.php 106 KB

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