metamodel.class.php 115 KB

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