metamodel.class.php 100 KB

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