metamodel.class.php 108 KB

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