metamodel.class.php 122 KB

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