metamodel.class.php 110 KB

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