metamodel.class.php 109 KB

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