metamodel.class.php 108 KB

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