metamodel.class.php 112 KB

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