metamodel.class.php 96 KB

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