metamodel.class.php 112 KB

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