metamodel.class.php 120 KB

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