metamodel.class.php 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434
  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. // Warning: using directly the query string as the key to the hash array can FAIL if the string
  1310. // is long and the differences are only near the end... so it's safer (but not bullet proof?)
  1311. // to use a hash (like md5) of the string as the key !
  1312. //
  1313. // Example of two queries that were found as similar by the hash array:
  1314. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTO' AND CustomerContract.customer_id = 2
  1315. // and
  1316. // SELECT SLT JOIN lnkSLTToSLA AS L1 ON L1.slt_id=SLT.id JOIN SLA ON L1.sla_id = SLA.id JOIN lnkContractToSLA AS L2 ON L2.sla_id = SLA.id JOIN CustomerContract ON L2.contract_id = CustomerContract.id WHERE SLT.ticket_priority = 1 AND SLA.service_id = 3 AND SLT.metric = 'TTR' AND CustomerContract.customer_id = 2
  1317. // the only difference is R instead or O at position 285 (TTR instead of TTO)...
  1318. //
  1319. if (array_key_exists(md5($sOqlQuery), self::$m_aQueryStructCache))
  1320. {
  1321. // hit!
  1322. $oSelect = clone self::$m_aQueryStructCache[$sOqlQuery];
  1323. }
  1324. }
  1325. if (!isset($oSelect))
  1326. {
  1327. $aTranslation = array();
  1328. $aClassAliases = array();
  1329. $aTableAliases = array();
  1330. $oConditionTree = $oFilter->GetCriteria();
  1331. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1332. self::$m_aQueryStructCache[$sOqlQuery] = clone $oSelect;
  1333. }
  1334. // Check the order by specification, and prefix with the class alias
  1335. //
  1336. $aOrderSpec = array();
  1337. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1338. {
  1339. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetFirstJoinedClass()));
  1340. if (!is_bool($bAscending))
  1341. {
  1342. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1343. }
  1344. $aOrderSpec[$oFilter->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1345. }
  1346. // By default, force the name attribute to be the ordering key
  1347. //
  1348. if (empty($aOrderSpec))
  1349. {
  1350. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1351. {
  1352. $sNameAttCode = self::GetNameAttributeCode($sSelectedClass);
  1353. if (!empty($sNameAttCode))
  1354. {
  1355. // By default, simply order on the "name" attribute, ascending
  1356. $aOrderSpec[$sSelectedAlias.$sNameAttCode] = true;
  1357. }
  1358. }
  1359. }
  1360. // Go
  1361. //
  1362. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1363. try
  1364. {
  1365. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs);
  1366. }
  1367. catch (MissingQueryArgument $e)
  1368. {
  1369. // Add some information...
  1370. $e->addInfo('OQL', $sOqlQuery);
  1371. throw $e;
  1372. }
  1373. if (self::$m_bTraceQueries)
  1374. {
  1375. $aParams = array();
  1376. if (!array_key_exists($sOqlQuery, self::$m_aQueriesLog))
  1377. {
  1378. self::$m_aQueriesLog[$sOqlQuery] = array(
  1379. 'sql' => array(),
  1380. 'count' => 0,
  1381. );
  1382. }
  1383. self::$m_aQueriesLog[$sOqlQuery]['count']++;
  1384. self::$m_aQueriesLog[$sOqlQuery]['sql'][] = $sRes;
  1385. }
  1386. return $sRes;
  1387. }
  1388. public static function ShowQueryTrace()
  1389. {
  1390. $iTotal = 0;
  1391. foreach (self::$m_aQueriesLog as $sOql => $aQueryData)
  1392. {
  1393. echo "<h2>$sOql</h2>\n";
  1394. $iTotal += $aQueryData['count'];
  1395. echo '<p>'.$aQueryData['count'].'</p>';
  1396. echo '<p>Example: '.$aQueryData['sql'][0].'</p>';
  1397. }
  1398. echo "<h2>Total</h2>\n";
  1399. echo "<p>Count of executed queries: $iTotal</p>";
  1400. echo "<p>Count of built queries: ".count(self::$m_aQueriesLog)."</p>";
  1401. }
  1402. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1403. {
  1404. $aTranslation = array();
  1405. $aClassAliases = array();
  1406. $aTableAliases = array();
  1407. $oConditionTree = $oFilter->GetCriteria();
  1408. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1409. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1410. return $oSelect->RenderDelete($aScalarArgs);
  1411. }
  1412. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1413. {
  1414. // $aValues is an array of $sAttCode => $value
  1415. $aTranslation = array();
  1416. $aClassAliases = array();
  1417. $aTableAliases = array();
  1418. $oConditionTree = $oFilter->GetCriteria();
  1419. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues);
  1420. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1421. return $oSelect->RenderUpdate($aScalarArgs);
  1422. }
  1423. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array())
  1424. {
  1425. // Note: query class might be different than the class of the filter
  1426. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1427. // $aExpectedAtts is an array of sAttCode=>array of columns
  1428. $sClass = $oFilter->GetFirstJoinedClass();
  1429. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1430. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1431. if ($bIsOnQueriedClass)
  1432. {
  1433. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1434. }
  1435. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1436. $sRootClass = self::GetRootClass($sClass);
  1437. $sKeyField = self::DBGetKey($sClass);
  1438. if ($bIsOnQueriedClass)
  1439. {
  1440. // default to the whole list of attributes + the very std id/finalclass
  1441. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1442. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1443. {
  1444. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1445. }
  1446. }
  1447. // Compute a clear view of external keys, and external attributes
  1448. // Build the list of external keys:
  1449. // -> ext keys required by a closed join ???
  1450. // -> ext keys mentionned in a 'pointing to' condition
  1451. // -> ext keys required for an external field
  1452. //
  1453. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1454. //
  1455. // Optimization: could be computed once for all (cached)
  1456. // Could be done in MakeQuerySingleTable ???
  1457. //
  1458. if ($bIsOnQueriedClass)
  1459. {
  1460. // Get all Ext keys for the queried class (??)
  1461. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1462. {
  1463. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1464. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1465. }
  1466. }
  1467. // Get all Ext keys used by the filter
  1468. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1469. {
  1470. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1471. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1472. }
  1473. // Add the ext fields used in the select (eventually adds an external key)
  1474. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1475. {
  1476. if ($oAttDef->IsExternalField())
  1477. {
  1478. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1479. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1480. {
  1481. // Add the external attribute
  1482. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1483. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1484. }
  1485. }
  1486. }
  1487. // First query built upon on the leaf (ie current) class
  1488. //
  1489. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1490. if (self::HasTable($sClass))
  1491. {
  1492. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1493. }
  1494. else
  1495. {
  1496. $oSelectBase = null;
  1497. // As the join will not filter on the expected classes, we have to specify it explicitely
  1498. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1499. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1500. $oConditionTree = $oConditionTree->LogAnd($oFinalClassRestriction);
  1501. }
  1502. // Then we join the queries of the eventual parent classes (compound model)
  1503. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1504. {
  1505. if (self::DBGetTable($sParentClass) == "") continue;
  1506. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1507. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1508. if (is_null($oSelectBase))
  1509. {
  1510. $oSelectBase = $oSelectParentTable;
  1511. }
  1512. else
  1513. {
  1514. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1515. }
  1516. }
  1517. // Filter on objects referencing me
  1518. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1519. {
  1520. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1521. {
  1522. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1523. // We don't want any attribute from the foreign class, just filter on an inner join
  1524. $aExpAtts = array();
  1525. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1526. //self::DbgTrace($oForeignFilter);
  1527. //self::DbgTrace($oForeignFilter->ToOQL());
  1528. //self::DbgTrace($oSelectForeign);
  1529. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1530. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1531. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1532. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1533. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1534. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1535. }
  1536. }
  1537. // Filter on related objects
  1538. //
  1539. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1540. {
  1541. $oSubFilter = $aCritInfo['flt'];
  1542. $sRelCode = $aCritInfo['relcode'];
  1543. $iMaxDepth = $aCritInfo['maxdepth'];
  1544. // Get the starting point objects
  1545. $oStartSet = new CMDBObjectSet($oSubFilter);
  1546. // Get the objects related to those objects... recursively...
  1547. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1548. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1549. // #@# todo - related objects and expressions...
  1550. // Create condition
  1551. if (count($aRestriction) > 0)
  1552. {
  1553. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1554. }
  1555. else
  1556. {
  1557. // Quick N'dirty -> generate an empty set
  1558. $oSelectBase->AddCondition('false');
  1559. }
  1560. }
  1561. // Translate the conditions... and go
  1562. //
  1563. if ($bIsOnQueriedClass)
  1564. {
  1565. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1566. $oSelectBase->SetCondition($oConditionTranslated);
  1567. }
  1568. // That's all... cross fingers and we'll get some working query
  1569. //MyHelpers::var_dump_html($oSelectBase, true);
  1570. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1571. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1572. return $oSelectBase;
  1573. }
  1574. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1575. {
  1576. // $aExpectedAtts is an array of sAttCode=>sAlias
  1577. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1578. // Prepare the query for a single table (compound objects)
  1579. // Ignores the items (attributes/filters) that are not on the target table
  1580. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1581. //
  1582. // Returns an SQLQuery
  1583. //
  1584. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1585. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1586. $sTable = self::DBGetTable($sTableClass);
  1587. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1588. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1589. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1590. // 1 - SELECT and UPDATE
  1591. //
  1592. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1593. //
  1594. $aSelect = array();
  1595. $aUpdateValues = array();
  1596. // 1/a - Get the key
  1597. //
  1598. if ($bIsOnQueriedClass)
  1599. {
  1600. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1601. }
  1602. // We need one pkey to be the key, let's take the one corresponding to the root class
  1603. // (used to be based on the leaf, but it may happen that this one has no table defined)
  1604. $sRootClass = self::GetRootClass($sTargetClass);
  1605. if ($sTableClass == $sRootClass)
  1606. {
  1607. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1608. }
  1609. // 1/b - Get the other attributes
  1610. //
  1611. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1612. {
  1613. // Skip this attribute if not defined in this table
  1614. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1615. // Skip this attribute if not writable (means that it does not correspond
  1616. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1617. // Update...
  1618. //
  1619. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1620. {
  1621. assert ($oAttDef->IsDirectField());
  1622. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1623. {
  1624. $aUpdateValues[$sColumn] = $sValue;
  1625. }
  1626. }
  1627. // Select...
  1628. //
  1629. // Skip, if a list of fields has been specified and it is not there
  1630. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1631. if ($oAttDef->IsExternalField())
  1632. {
  1633. // skip, this will be handled in the joined tables
  1634. }
  1635. else
  1636. {
  1637. // standard field, or external key
  1638. // add it to the output
  1639. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1640. {
  1641. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1642. {
  1643. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. // 2 - WHERE
  1649. //
  1650. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1651. {
  1652. // Skip this filter if not defined in this table
  1653. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1654. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1655. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1656. {
  1657. // Note: I did not test it with filters relying on several expressions...
  1658. // as long as sColdID is empty, this is working, otherwise... ?
  1659. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1660. }
  1661. }
  1662. // #@# todo - See what a full text search condition should be
  1663. // 2' - WHERE / Full text search condition
  1664. //
  1665. if ($bIsOnQueriedClass)
  1666. {
  1667. $aFullText = $oFilter->GetCriteria_FullText();
  1668. }
  1669. else
  1670. {
  1671. // Pourquoi ???
  1672. $aFullText = array();
  1673. }
  1674. // 3 - The whole stuff, for this table only
  1675. //
  1676. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1677. // 4 - The external keys -> joins...
  1678. //
  1679. if (array_key_exists($sTableClass, $aExtKeys))
  1680. {
  1681. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1682. {
  1683. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1684. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1685. // In case the join was not explicitely defined in the filter,
  1686. // we need to do it now
  1687. if (empty($oExtFilter))
  1688. {
  1689. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1690. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1691. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1692. }
  1693. else
  1694. {
  1695. // The aliases should not conflict because normalization occured while building the filter
  1696. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1697. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1698. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1699. }
  1700. // Specify expected attributes for the target class query
  1701. // ... and use the current alias !
  1702. $aExpAtts = array();
  1703. $aIntermediateTranslation = array();
  1704. foreach($aExtFields as $sAttCode => $oAtt)
  1705. {
  1706. $sExtAttCode = $oAtt->GetExtAttCode();
  1707. if (array_key_exists($sAttCode, $aExpectedAtts))
  1708. {
  1709. // Request this attribute... transmit the alias !
  1710. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1711. }
  1712. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1713. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1714. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1715. {
  1716. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1717. }
  1718. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1719. }
  1720. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1721. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1722. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1723. $sLocalKeyField = current($oKeyAttDef->GetSQLExpressions()); // get the first column for an external key
  1724. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1725. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1726. if ($oKeyAttDef->IsNullAllowed())
  1727. {
  1728. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1729. }
  1730. else
  1731. {
  1732. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1733. }
  1734. }
  1735. }
  1736. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1737. return $oSelectBase;
  1738. }
  1739. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1740. {
  1741. if (!array_key_exists($sNewName, $aAliases))
  1742. {
  1743. $aAliases[$sNewName] = $sRealName;
  1744. return $sNewName;
  1745. }
  1746. for ($i = 1 ; $i < 100 ; $i++)
  1747. {
  1748. $sAnAlias = $sNewName.$i;
  1749. if (!array_key_exists($sAnAlias, $aAliases))
  1750. {
  1751. // Create that new alias
  1752. $aAliases[$sAnAlias] = $sRealName;
  1753. return $sAnAlias;
  1754. }
  1755. }
  1756. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1757. }
  1758. public static function CheckDefinitions()
  1759. {
  1760. if (count(self::GetClasses()) == 0)
  1761. {
  1762. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1763. }
  1764. $aErrors = array();
  1765. $aSugFix = array();
  1766. foreach (self::GetClasses() as $sClass)
  1767. {
  1768. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1769. if (empty($sNameAttCode))
  1770. {
  1771. // let's try this !!!
  1772. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1773. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1774. }
  1775. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1776. {
  1777. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1778. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1779. }
  1780. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1781. {
  1782. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1783. {
  1784. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1785. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1786. }
  1787. }
  1788. $bHasWritableAttribute = false;
  1789. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1790. {
  1791. // It makes no sense to check the attributes again and again in the subclasses
  1792. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1793. if ($oAttDef->IsExternalKey())
  1794. {
  1795. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1796. {
  1797. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1798. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1799. }
  1800. }
  1801. elseif ($oAttDef->IsExternalField())
  1802. {
  1803. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1804. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1805. {
  1806. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1807. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1808. }
  1809. else
  1810. {
  1811. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1812. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1813. $sExtAttCode = $oAttDef->GetExtAttCode();
  1814. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1815. {
  1816. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1817. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1818. }
  1819. }
  1820. }
  1821. else // standard attributes
  1822. {
  1823. // Check that the default values definition is a valid object!
  1824. $oValSetDef = $oAttDef->GetValuesDef();
  1825. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1826. {
  1827. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1828. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1829. }
  1830. else
  1831. {
  1832. // Default value must be listed in the allowed values (if defined)
  1833. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1834. if (!is_null($aAllowedValues))
  1835. {
  1836. $sDefaultValue = $oAttDef->GetDefaultValue();
  1837. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  1838. {
  1839. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  1840. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  1841. }
  1842. }
  1843. }
  1844. }
  1845. // Check dependencies
  1846. if ($oAttDef->IsWritable())
  1847. {
  1848. $bHasWritableAttribute = true;
  1849. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  1850. {
  1851. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  1852. {
  1853. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  1854. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1855. }
  1856. }
  1857. }
  1858. }
  1859. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  1860. {
  1861. if (method_exists($oFilterDef, '__GetRefAttribute'))
  1862. {
  1863. $oAttDef = $oFilterDef->__GetRefAttribute();
  1864. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  1865. {
  1866. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  1867. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1868. }
  1869. }
  1870. }
  1871. // Lifecycle
  1872. //
  1873. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1874. if (strlen($sStateAttCode) > 0)
  1875. {
  1876. // Lifecycle - check that the state attribute does exist as an attribute
  1877. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  1878. {
  1879. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  1880. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1881. }
  1882. else
  1883. {
  1884. // Lifecycle - check that there is a value set constraint on the state attribute
  1885. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  1886. $aStates = array_keys(self::EnumStates($sClass));
  1887. if (is_null($aAllowedValuesRaw))
  1888. {
  1889. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  1890. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  1891. }
  1892. else
  1893. {
  1894. $aAllowedValues = array_keys($aAllowedValuesRaw);
  1895. // Lifecycle - check the the state attribute allowed values are defined states
  1896. foreach($aAllowedValues as $sValue)
  1897. {
  1898. if (!in_array($sValue, $aStates))
  1899. {
  1900. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  1901. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1902. }
  1903. }
  1904. // Lifecycle - check that defined states are allowed values
  1905. foreach($aStates as $sStateValue)
  1906. {
  1907. if (!in_array($sStateValue, $aAllowedValues))
  1908. {
  1909. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  1910. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1911. }
  1912. }
  1913. }
  1914. // Lifcycle - check that the action handlers are defined
  1915. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  1916. {
  1917. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  1918. {
  1919. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1920. {
  1921. if (!method_exists($sClass, $sActionHandler))
  1922. {
  1923. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  1924. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  1925. }
  1926. }
  1927. }
  1928. }
  1929. }
  1930. }
  1931. if ($bHasWritableAttribute)
  1932. {
  1933. if (!self::HasTable($sClass))
  1934. {
  1935. $aErrors[$sClass][] = "No table has been defined for this class";
  1936. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  1937. }
  1938. }
  1939. // ZList
  1940. //
  1941. foreach(self::EnumZLists() as $sListCode)
  1942. {
  1943. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  1944. {
  1945. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  1946. {
  1947. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  1948. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1949. }
  1950. }
  1951. }
  1952. }
  1953. if (count($aErrors) > 0)
  1954. {
  1955. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  1956. echo "<h3>Business model inconsistencies have been found</h3>\n";
  1957. // #@# later -> this is the responsibility of the caller to format the output
  1958. foreach ($aErrors as $sClass => $aMessages)
  1959. {
  1960. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  1961. echo "<ul class=\"treeview\">\n";
  1962. $i = 0;
  1963. foreach ($aMessages as $sMsg)
  1964. {
  1965. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  1966. $i++;
  1967. }
  1968. echo "</ul>\n";
  1969. }
  1970. echo "<p>Aborting...</p>\n";
  1971. echo "</div>\n";
  1972. exit;
  1973. }
  1974. }
  1975. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  1976. {
  1977. if (empty($sRepairUrl)) return;
  1978. // By design, some queries might be blank, we have to ignore them
  1979. $aCleanFixes = array();
  1980. foreach($aSQLFixes as $sSQLFix)
  1981. {
  1982. if (!empty($sSQLFix))
  1983. {
  1984. $aCleanFixes[] = $sSQLFix;
  1985. }
  1986. }
  1987. if (count($aCleanFixes) == 0) return;
  1988. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  1989. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes))."\">\n";
  1990. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  1991. echo "</form>\n";
  1992. }
  1993. public static function DBExists($bMustBeComplete = true)
  1994. {
  1995. // returns true if at least one table exists
  1996. //
  1997. if (!CMDBSource::IsDB(self::$m_sDBName))
  1998. {
  1999. return false;
  2000. }
  2001. CMDBSource::SelectDB(self::$m_sDBName);
  2002. $aFound = array();
  2003. $aMissing = array();
  2004. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2005. {
  2006. if (CMDBSource::IsTable($sTable))
  2007. {
  2008. $aFound[] = $sTable;
  2009. }
  2010. else
  2011. {
  2012. $aMissing[] = $sTable;
  2013. }
  2014. }
  2015. if (count($aFound) == 0)
  2016. {
  2017. // no expected table has been found
  2018. return false;
  2019. }
  2020. else
  2021. {
  2022. if (count($aMissing) == 0)
  2023. {
  2024. // the database is complete (still, could be some fields missing!)
  2025. return true;
  2026. }
  2027. else
  2028. {
  2029. // not all the tables, could be an older version
  2030. if ($bMustBeComplete)
  2031. {
  2032. return false;
  2033. }
  2034. else
  2035. {
  2036. return true;
  2037. }
  2038. }
  2039. }
  2040. }
  2041. public static function DBDrop()
  2042. {
  2043. $bDropEntireDB = true;
  2044. if (!empty(self::$m_sTablePrefix))
  2045. {
  2046. // Do drop only tables corresponding to the sub-database (table prefix)
  2047. // then possibly drop the DB itself (if no table remain)
  2048. foreach (CMDBSource::EnumTables() as $sTable)
  2049. {
  2050. // perform a case insensitive test because on Windows the table names become lowercase :-(
  2051. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  2052. {
  2053. CMDBSource::DropTable($sTable);
  2054. }
  2055. else
  2056. {
  2057. // There is at least one table which is out of the scope of the current application
  2058. $bDropEntireDB = false;
  2059. }
  2060. }
  2061. }
  2062. if ($bDropEntireDB)
  2063. {
  2064. CMDBSource::DropDB(self::$m_sDBName);
  2065. }
  2066. }
  2067. public static function DBCreate()
  2068. {
  2069. // Note: we have to check if the DB does exist, because we may share the DB
  2070. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  2071. if (!CMDBSource::IsDB(self::$m_sDBName))
  2072. {
  2073. CMDBSource::CreateDB(self::$m_sDBName);
  2074. }
  2075. self::DBCreateTables();
  2076. self::DBCreateViews();
  2077. }
  2078. protected static function DBCreateTables()
  2079. {
  2080. list($aErrors, $aSugFix) = self::DBCheckFormat();
  2081. $aSQL = array();
  2082. foreach ($aSugFix as $sClass => $aTarget)
  2083. {
  2084. foreach ($aTarget as $aQueries)
  2085. {
  2086. foreach ($aQueries as $sQuery)
  2087. {
  2088. if (!empty($sQuery))
  2089. {
  2090. //$aSQL[] = $sQuery;
  2091. // forces a refresh of cached information
  2092. CMDBSource::CreateTable($sQuery);
  2093. }
  2094. }
  2095. }
  2096. }
  2097. // does not work -how to have multiple statements in a single query?
  2098. // $sDoCreateAll = implode(" ; ", $aSQL);
  2099. }
  2100. protected static function DBCreateViews()
  2101. {
  2102. list($aErrors, $aSugFix) = self::DBCheckViews();
  2103. $aSQL = array();
  2104. foreach ($aSugFix as $sClass => $aTarget)
  2105. {
  2106. foreach ($aTarget as $aQueries)
  2107. {
  2108. foreach ($aQueries as $sQuery)
  2109. {
  2110. if (!empty($sQuery))
  2111. {
  2112. //$aSQL[] = $sQuery;
  2113. // forces a refresh of cached information
  2114. CMDBSource::CreateTable($sQuery);
  2115. }
  2116. }
  2117. }
  2118. }
  2119. }
  2120. public static function DBDump()
  2121. {
  2122. $aDataDump = array();
  2123. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2124. {
  2125. $aRows = CMDBSource::DumpTable($sTable);
  2126. $aDataDump[$sTable] = $aRows;
  2127. }
  2128. return $aDataDump;
  2129. }
  2130. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  2131. {
  2132. $sValue = Dict::S($sKey, 'x-no-nothing');
  2133. if ($sValue == 'x-no-nothing')
  2134. {
  2135. $bNotInDico = true;
  2136. $sValue = $sValueFromOldSystem;
  2137. if (strlen($sValue) == 0)
  2138. {
  2139. $sValue = $sDefaultValue;
  2140. }
  2141. }
  2142. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  2143. }
  2144. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  2145. {
  2146. $sRes = '';
  2147. $sRes .= "// Dictionnay conventions\n";
  2148. $sRes .= htmlentities("// Class:<class_name>\n");
  2149. $sRes .= htmlentities("// Class:<class_name>+\n");
  2150. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n");
  2151. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n");
  2152. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n");
  2153. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n");
  2154. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n");
  2155. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n");
  2156. $sRes .= "\n";
  2157. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  2158. // Need to invent the "module", to characterize the origins of a class
  2159. if (strlen($sModules) == 0)
  2160. {
  2161. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  2162. }
  2163. else
  2164. {
  2165. $aModules = explode(', ', $sModules);
  2166. }
  2167. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2168. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  2169. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2170. foreach ($aModules as $sCategory)
  2171. {
  2172. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2173. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  2174. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2175. $sRes .= "//\n";
  2176. $sRes .= "\n";
  2177. foreach (self::GetClasses($sCategory) as $sClass)
  2178. {
  2179. if (!self::HasTable($sClass)) continue;
  2180. $bNotInDico = false;
  2181. $sClassRes = "//\n";
  2182. $sClassRes .= "// Class: $sClass\n";
  2183. $sClassRes .= "//\n";
  2184. $sClassRes .= "\n";
  2185. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  2186. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  2187. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  2188. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2189. {
  2190. // Skip this attribute if not originaly defined in this class
  2191. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2192. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  2193. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  2194. if ($oAttDef instanceof AttributeEnum)
  2195. {
  2196. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  2197. {
  2198. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  2199. {
  2200. if (array_key_exists('label', $aStateData))
  2201. {
  2202. $sValue = $aStateData['label'];
  2203. }
  2204. else
  2205. {
  2206. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  2207. }
  2208. if (array_key_exists('description', $aStateData))
  2209. {
  2210. $sValuePlus = $aStateData['description'];
  2211. }
  2212. else
  2213. {
  2214. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  2215. }
  2216. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  2217. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  2218. }
  2219. }
  2220. else
  2221. {
  2222. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  2223. {
  2224. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  2225. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  2226. }
  2227. }
  2228. }
  2229. }
  2230. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  2231. {
  2232. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  2233. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  2234. }
  2235. $sClassRes .= "));\n";
  2236. $sClassRes .= "\n";
  2237. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  2238. {
  2239. $sRes .= $sClassRes;
  2240. }
  2241. }
  2242. }
  2243. return $sRes;
  2244. }
  2245. public static function DBCheckFormat()
  2246. {
  2247. $aErrors = array();
  2248. $aSugFix = array();
  2249. foreach (self::GetClasses() as $sClass)
  2250. {
  2251. if (!self::HasTable($sClass)) continue;
  2252. // Check that the table exists
  2253. //
  2254. $sTable = self::DBGetTable($sClass);
  2255. $sKeyField = self::DBGetKey($sClass);
  2256. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  2257. if (!CMDBSource::IsTable($sTable))
  2258. {
  2259. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  2260. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  2261. }
  2262. // Check that the key field exists
  2263. //
  2264. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  2265. {
  2266. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  2267. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  2268. }
  2269. else
  2270. {
  2271. // Check the key field properties
  2272. //
  2273. if (!CMDBSource::IsKey($sTable, $sKeyField))
  2274. {
  2275. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  2276. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  2277. }
  2278. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  2279. {
  2280. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  2281. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  2282. }
  2283. }
  2284. // Check that any defined field exists
  2285. //
  2286. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  2287. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2288. {
  2289. // Skip this attribute if not originaly defined in this class
  2290. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2291. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2292. {
  2293. $bIndexNeeded = $oAttDef->RequiresIndex();
  2294. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  2295. if (!CMDBSource::IsField($sTable, $sField))
  2296. {
  2297. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  2298. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  2299. if ($bIndexNeeded)
  2300. {
  2301. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2302. }
  2303. }
  2304. else
  2305. {
  2306. // The field already exists, does it have the relevant properties?
  2307. //
  2308. $bToBeChanged = false;
  2309. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  2310. {
  2311. $bToBeChanged = true;
  2312. if ($oAttDef->IsNullAllowed())
  2313. {
  2314. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  2315. }
  2316. else
  2317. {
  2318. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  2319. }
  2320. }
  2321. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  2322. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  2323. {
  2324. $bToBeChanged = true;
  2325. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  2326. }
  2327. if ($bToBeChanged)
  2328. {
  2329. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  2330. }
  2331. // Create indexes (external keys only... so far)
  2332. //
  2333. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField))
  2334. {
  2335. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  2336. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2337. }
  2338. }
  2339. }
  2340. }
  2341. }
  2342. return array($aErrors, $aSugFix);
  2343. }
  2344. public static function DBCheckViews()
  2345. {
  2346. $aErrors = array();
  2347. $aSugFix = array();
  2348. // Reporting views (must be created after any other table)
  2349. //
  2350. foreach (self::GetClasses('bizmodel') as $sClass)
  2351. {
  2352. $sView = "view_$sClass";
  2353. if (CMDBSource::IsTable($sView))
  2354. {
  2355. // Check that the view is complete
  2356. //
  2357. $bIsComplete = true;
  2358. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2359. {
  2360. foreach($oAttDef->GetSQLExpressions() as $sSuffix => $sTrash)
  2361. {
  2362. $sCol = $sAttCode.$sSuffix;
  2363. if (!CMDBSource::IsField($sView, $sCol))
  2364. {
  2365. $bIsComplete = false;
  2366. $aErrors[$sClass][$sAttCode][] = "field '$sCol' could not be found in view '$sView'";
  2367. $aSugFix[$sClass][$sAttCode][] = "";
  2368. }
  2369. }
  2370. }
  2371. if (!$bIsComplete)
  2372. {
  2373. // Rework the view
  2374. //
  2375. $oFilter = new DBObjectSearch($sClass, '');
  2376. $sSQL = self::MakeSelectQuery($oFilter);
  2377. $aErrors[$sClass]['*'][] = "View '$sView' is currently not complete";
  2378. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  2379. }
  2380. }
  2381. else
  2382. {
  2383. // Create the view
  2384. //
  2385. $oFilter = new DBObjectSearch($sClass, '');
  2386. $sSQL = self::MakeSelectQuery($oFilter);
  2387. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  2388. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  2389. }
  2390. }
  2391. return array($aErrors, $aSugFix);
  2392. }
  2393. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  2394. {
  2395. $sRootClass = self::GetRootClass($sClass);
  2396. $sTable = self::DBGetTable($sClass);
  2397. $sKeyField = self::DBGetKey($sClass);
  2398. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2399. {
  2400. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2401. }
  2402. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2403. if (count($aWrongRecords) == 0) return;
  2404. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2405. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2406. foreach ($aWrongRecords as $iRecordId)
  2407. {
  2408. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2409. {
  2410. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2411. {
  2412. case 'Delete':
  2413. // Already planned for a deletion
  2414. // Let's concatenate the errors description together
  2415. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2416. break;
  2417. case 'Update':
  2418. // Let's plan a deletion
  2419. break;
  2420. }
  2421. }
  2422. else
  2423. {
  2424. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2425. }
  2426. if (!$bProcessingFriends)
  2427. {
  2428. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2429. {
  2430. // Something new to be deleted...
  2431. $iNewDelCount++;
  2432. }
  2433. }
  2434. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2435. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2436. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2437. $aPlannedDel[$sTable][] = $iRecordId;
  2438. }
  2439. // Now make sure that we would delete the records of the other tables for that class
  2440. //
  2441. if (!$bProcessingFriends)
  2442. {
  2443. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2444. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2445. {
  2446. $sFriendTable = self::DBGetTable($sFriendClass);
  2447. $sFriendKey = self::DBGetKey($sFriendClass);
  2448. // skip the current table
  2449. if ($sFriendTable == $sTable) continue;
  2450. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2451. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2452. }
  2453. }
  2454. }
  2455. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2456. {
  2457. $sRootClass = self::GetRootClass($sClass);
  2458. $sTable = self::DBGetTable($sClass);
  2459. $sKeyField = self::DBGetKey($sClass);
  2460. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2461. {
  2462. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2463. }
  2464. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2465. if (count($aWrongRecords) == 0) return;
  2466. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2467. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2468. foreach ($aWrongRecords as $iRecordId)
  2469. {
  2470. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2471. {
  2472. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2473. {
  2474. case 'Delete':
  2475. // No need to update, the record will be deleted!
  2476. break;
  2477. case 'Update':
  2478. // Already planned for an update
  2479. // Add this new update spec to the list
  2480. $bFoundSameSpec = false;
  2481. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2482. {
  2483. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2484. {
  2485. $bFoundSameSpec = true;
  2486. }
  2487. }
  2488. if (!$bFoundSameSpec)
  2489. {
  2490. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2491. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2492. }
  2493. break;
  2494. }
  2495. }
  2496. else
  2497. {
  2498. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2499. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2500. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2501. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2502. }
  2503. }
  2504. }
  2505. // returns the count of records found for deletion
  2506. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2507. {
  2508. foreach (self::GetClasses() as $sClass)
  2509. {
  2510. if (!self::HasTable($sClass)) continue;
  2511. $sRootClass = self::GetRootClass($sClass);
  2512. $sTable = self::DBGetTable($sClass);
  2513. $sKeyField = self::DBGetKey($sClass);
  2514. if (!self::IsStandaloneClass($sClass))
  2515. {
  2516. if (self::IsRootClass($sClass))
  2517. {
  2518. // Check that the final class field contains the name of a class which inherited from the current class
  2519. //
  2520. $sFinalClassField = self::DBGetClassField($sClass);
  2521. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2522. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2523. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2524. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2525. }
  2526. else
  2527. {
  2528. $sRootTable = self::DBGetTable($sRootClass);
  2529. $sRootKey = self::DBGetKey($sRootClass);
  2530. $sFinalClassField = self::DBGetClassField($sRootClass);
  2531. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2532. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2533. // Check that any record found here has its counterpart in the root table
  2534. // and which refers to a child class
  2535. //
  2536. $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";
  2537. 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);
  2538. // Check that any record found in the root table and referring to a child class
  2539. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2540. //
  2541. $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)";
  2542. 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);
  2543. }
  2544. }
  2545. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2546. {
  2547. // Skip this attribute if not defined in this table
  2548. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2549. if ($oAttDef->IsExternalKey())
  2550. {
  2551. // Check that any external field is pointing to an existing object
  2552. //
  2553. $sRemoteClass = $oAttDef->GetTargetClass();
  2554. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2555. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2556. $sExtKeyField = current($oAttDef->GetSQLExpressions()); // get the first column for an external key
  2557. // Note: a class/table may have an external key on itself
  2558. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2559. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2560. if ($oAttDef->IsNullAllowed())
  2561. {
  2562. // Exclude the records pointing to 0/null from the errors
  2563. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2564. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2565. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2566. }
  2567. else
  2568. {
  2569. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2570. }
  2571. // Do almost the same, taking into account the records planned for deletion
  2572. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2573. {
  2574. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2575. // but in that case you won't be able to track the root cause (cascading)
  2576. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2577. if ($oAttDef->IsNullAllowed())
  2578. {
  2579. // Exclude the records pointing to 0/null from the errors
  2580. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2581. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2582. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2583. }
  2584. else
  2585. {
  2586. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2587. }
  2588. }
  2589. }
  2590. else if ($oAttDef->IsDirectField())
  2591. {
  2592. // Check that the values fit the allowed values
  2593. //
  2594. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2595. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2596. {
  2597. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2598. $sMyAttributeField = current($oAttDef->GetSQLExpressions()); // get the first column for the moment
  2599. $sDefaultValue = $oAttDef->GetDefaultValue();
  2600. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2601. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2602. }
  2603. }
  2604. }
  2605. }
  2606. }
  2607. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2608. {
  2609. // Records in error, and action to be taken: delete or update
  2610. // by RootClass/Table/Record
  2611. $aErrorsAndFixes = array();
  2612. // Records to be ignored in the current/next pass
  2613. // by Table = array of RecordId
  2614. $aPlannedDel = array();
  2615. // Count of errors in the next pass: no error means that we can leave...
  2616. $iErrorCount = 0;
  2617. // Limit in case of a bug in the algorythm
  2618. $iLoopCount = 0;
  2619. $iNewDelCount = 1; // startup...
  2620. while ($iNewDelCount > 0)
  2621. {
  2622. $iNewDelCount = 0;
  2623. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2624. $iErrorCount += $iNewDelCount;
  2625. // Safety net #1 - limit the planned deletions
  2626. //
  2627. $iMaxDel = 1000;
  2628. $iPlannedDel = 0;
  2629. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2630. {
  2631. $iPlannedDel += count($aPlannedDelOnTable);
  2632. }
  2633. if ($iPlannedDel > $iMaxDel)
  2634. {
  2635. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2636. break;
  2637. }
  2638. // Safety net #2 - limit the iterations
  2639. //
  2640. $iLoopCount++;
  2641. $iMaxLoops = 10;
  2642. if ($iLoopCount > $iMaxLoops)
  2643. {
  2644. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2645. break;
  2646. }
  2647. }
  2648. // Display the results
  2649. //
  2650. $iIssueCount = 0;
  2651. $aFixesDelete = array();
  2652. $aFixesUpdate = array();
  2653. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2654. {
  2655. foreach ($aTables as $sTable => $aRecords)
  2656. {
  2657. foreach ($aRecords as $iRecord => $aError)
  2658. {
  2659. $sAction = $aError['Action'];
  2660. $sReason = $aError['Reason'];
  2661. $iPass = $aError['Pass'];
  2662. switch ($sAction)
  2663. {
  2664. case 'Delete':
  2665. $sActionDetails = "";
  2666. $aFixesDelete[$sTable][] = $iRecord;
  2667. break;
  2668. case 'Update':
  2669. $aUpdateDesc = array();
  2670. foreach($aError['Action_Details'] as $aUpdateSpec)
  2671. {
  2672. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2673. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2674. }
  2675. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2676. break;
  2677. default:
  2678. $sActionDetails = "bug: unknown action '$sAction'";
  2679. }
  2680. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2681. $iIssueCount++;
  2682. }
  2683. }
  2684. }
  2685. if ($iIssueCount > 0)
  2686. {
  2687. // Build the queries to fix in the database
  2688. //
  2689. // First step, be able to get class data out of the table name
  2690. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2691. $aTable2ClassProp = array();
  2692. foreach (self::GetClasses() as $sClass)
  2693. {
  2694. if (!self::HasTable($sClass)) continue;
  2695. $sRootClass = self::GetRootClass($sClass);
  2696. $sTable = self::DBGetTable($sClass);
  2697. $sKeyField = self::DBGetKey($sClass);
  2698. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2699. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2700. }
  2701. // Second step, build a flat list of SQL queries
  2702. $aSQLFixes = array();
  2703. $iPlannedUpdate = 0;
  2704. foreach ($aFixesUpdate as $sTable => $aColumns)
  2705. {
  2706. foreach ($aColumns as $sColumn => $aNewValues)
  2707. {
  2708. foreach ($aNewValues as $sNewValue => $aRecords)
  2709. {
  2710. $iPlannedUpdate += count($aRecords);
  2711. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2712. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2713. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2714. }
  2715. }
  2716. }
  2717. $iPlannedDel = 0;
  2718. foreach ($aFixesDelete as $sTable => $aRecords)
  2719. {
  2720. $iPlannedDel += count($aRecords);
  2721. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2722. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2723. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2724. }
  2725. // Report the results
  2726. //
  2727. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2728. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2729. // #@# later -> this is the responsibility of the caller to format the output
  2730. echo "<ul class=\"treeview\">\n";
  2731. foreach ($aIssues as $sIssueDesc)
  2732. {
  2733. echo "<li>$sIssueDesc</li>\n";
  2734. }
  2735. echo "</ul>\n";
  2736. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2737. echo "<p>Aborting...</p>\n";
  2738. echo "</div>\n";
  2739. exit;
  2740. }
  2741. }
  2742. public static function Startup($sConfigFile, $bAllowMissingDB = false)
  2743. {
  2744. self::LoadConfig($sConfigFile);
  2745. if (self::DBExists())
  2746. // !!!! #@#
  2747. //if (true)
  2748. {
  2749. CMDBSource::SelectDB(self::$m_sDBName);
  2750. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2751. self::InitPlugins();
  2752. }
  2753. else
  2754. {
  2755. if (!$bAllowMissingDB)
  2756. {
  2757. throw new CoreException('Database not found, check your configuration file', array('config_file'=>$sConfigFile, 'db_name'=>self::$m_sDBName));
  2758. }
  2759. }
  2760. }
  2761. public static function LoadConfig($sConfigFile)
  2762. {
  2763. $oConfig = new Config($sConfigFile);
  2764. // Set log ASAP
  2765. if ($oConfig->GetLogGlobal())
  2766. {
  2767. if ($oConfig->GetLogIssue())
  2768. {
  2769. self::$m_bLogIssue = true;
  2770. IssueLog::Enable('../error.log');
  2771. }
  2772. self::$m_bLogNotification = $oConfig->GetLogNotification();
  2773. self::$m_bLogWebService = $oConfig->GetLogWebService();
  2774. }
  2775. else
  2776. {
  2777. self::$m_bLogIssue = false;
  2778. self::$m_bLogNotification = false;
  2779. self::$m_bLogWebService = false;
  2780. }
  2781. // Note: load the dictionary as soon as possible, because it might be
  2782. // needed when some error occur
  2783. foreach ($oConfig->GetDictionaries() as $sModule => $sToInclude)
  2784. {
  2785. self::Plugin($sConfigFile, 'dictionaries', $sToInclude);
  2786. }
  2787. // Set the language... after the dictionaries have been loaded!
  2788. Dict::SetDefaultLanguage($oConfig->GetDefaultLanguage());
  2789. foreach ($oConfig->GetAppModules() as $sModule => $sToInclude)
  2790. {
  2791. self::Plugin($sConfigFile, 'application', $sToInclude);
  2792. }
  2793. foreach ($oConfig->GetDataModels() as $sModule => $sToInclude)
  2794. {
  2795. self::Plugin($sConfigFile, 'business', $sToInclude);
  2796. }
  2797. foreach ($oConfig->GetAddons() as $sModule => $sToInclude)
  2798. {
  2799. self::Plugin($sConfigFile, 'addons', $sToInclude);
  2800. }
  2801. $sServer = $oConfig->GetDBHost();
  2802. $sUser = $oConfig->GetDBUser();
  2803. $sPwd = $oConfig->GetDBPwd();
  2804. $sSource = $oConfig->GetDBName();
  2805. $sTablePrefix = $oConfig->GetDBSubname();
  2806. // The include have been included, let's browse the existing classes and
  2807. // develop some data based on the proposed model
  2808. self::InitClasses($sTablePrefix);
  2809. self::$m_sDBName = $sSource;
  2810. self::$m_sTablePrefix = $sTablePrefix;
  2811. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  2812. }
  2813. protected static $m_aPlugins = array();
  2814. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  2815. {
  2816. self::$m_aPlugins[$sName] = array(
  2817. 'type' => $sType,
  2818. 'init' => $aInitCallSpec,
  2819. );
  2820. }
  2821. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  2822. {
  2823. if (!file_exists($sToInclude))
  2824. {
  2825. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sToInclude));
  2826. }
  2827. require_once($sToInclude);
  2828. }
  2829. protected static function InitPlugins()
  2830. {
  2831. foreach(self::$m_aPlugins as $sName => $aData)
  2832. {
  2833. $aCallSpec = @$aData['init'];
  2834. if (count($aCallSpec) == 2)
  2835. {
  2836. if (!is_callable($aCallSpec))
  2837. {
  2838. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  2839. }
  2840. call_user_func($aCallSpec);
  2841. }
  2842. }
  2843. }
  2844. // Building an object
  2845. //
  2846. //
  2847. private static $aQueryCacheGetObject = array();
  2848. private static $aQueryCacheGetObjectHits = array();
  2849. public static function GetQueryCacheStatus()
  2850. {
  2851. $aRes = array();
  2852. $iTotalHits = 0;
  2853. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  2854. {
  2855. $aRes[] = "$sClass: $iHits";
  2856. $iTotalHits += $iHits;
  2857. }
  2858. return $iTotalHits.' ('.implode(', ', $aRes).')';
  2859. }
  2860. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true)
  2861. {
  2862. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  2863. {
  2864. // NOTE: Quick and VERY dirty caching mechanism which relies on
  2865. // the fact that the string '987654321' will never appear in the
  2866. // standard query
  2867. // This will be replaced for sure with a prepared statement
  2868. // or a view... next optimization to come!
  2869. $oFilter = new DBObjectSearch($sClass);
  2870. $oFilter->AddCondition('id', 987654321, '=');
  2871. $sSQL = self::MakeSelectQuery($oFilter);
  2872. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  2873. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  2874. }
  2875. else
  2876. {
  2877. $sSQL = self::$aQueryCacheGetObject[$sClass];
  2878. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  2879. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  2880. }
  2881. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  2882. $res = CMDBSource::Query($sSQL);
  2883. $aRow = CMDBSource::FetchArray($res);
  2884. CMDBSource::FreeResult($res);
  2885. if ($bMustBeFound && empty($aRow))
  2886. {
  2887. throw new CoreException("No result for the single row query: '$sSQL'");
  2888. }
  2889. return $aRow;
  2890. }
  2891. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  2892. {
  2893. self::_check_subclass($sClass);
  2894. if (strlen($sClassAlias) == 0)
  2895. {
  2896. $sClassAlias = $sClass;
  2897. }
  2898. // Compound objects: if available, get the final object class
  2899. //
  2900. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  2901. {
  2902. // Either this is a bug (forgot to specify a root class with a finalclass field
  2903. // Or this is the expected behavior, because the object is not made of several tables
  2904. }
  2905. elseif (empty($aRow[$sClassAlias."finalclass"]))
  2906. {
  2907. // The data is missing in the DB
  2908. // @#@ possible improvement: check that the class is valid !
  2909. $sRootClass = self::GetRootClass($sClass);
  2910. $sFinalClassField = self::DBGetClassField($sRootClass);
  2911. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  2912. }
  2913. else
  2914. {
  2915. // do the job for the real target class
  2916. $sClass = $aRow[$sClassAlias."finalclass"];
  2917. }
  2918. return new $sClass($aRow, $sClassAlias);
  2919. }
  2920. public static function GetObject($sClass, $iKey, $bMustBeFound = true)
  2921. {
  2922. self::_check_subclass($sClass);
  2923. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound);
  2924. if (empty($aRow))
  2925. {
  2926. return null;
  2927. }
  2928. return self::GetObjectByRow($sClass, $aRow);
  2929. }
  2930. public static function GetHyperLink($sTargetClass, $iKey)
  2931. {
  2932. if ($iKey < 0)
  2933. {
  2934. return "$sTargetClass: $iKey (invalid value)";
  2935. }
  2936. $oObj = self::GetObject($sTargetClass, $iKey, false);
  2937. if (is_null($oObj))
  2938. {
  2939. return "$sTargetClass: $iKey (not found)";
  2940. }
  2941. return $oObj->GetHyperLink();
  2942. }
  2943. public static function NewObject($sClass)
  2944. {
  2945. self::_check_subclass($sClass);
  2946. return new $sClass();
  2947. }
  2948. public static function GetNextKey($sClass)
  2949. {
  2950. $sRootClass = MetaModel::GetRootClass($sClass);
  2951. $sRootTable = MetaModel::DBGetTable($sRootClass);
  2952. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  2953. return $iNextKey;
  2954. }
  2955. public static function BulkDelete(DBObjectSearch $oFilter)
  2956. {
  2957. $sSQL = self::MakeDeleteQuery($oFilter);
  2958. CMDBSource::Query($sSQL);
  2959. }
  2960. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  2961. {
  2962. // $aValues is an array of $sAttCode => $value
  2963. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  2964. CMDBSource::Query($sSQL);
  2965. }
  2966. // Links
  2967. //
  2968. //
  2969. public static function EnumReferencedClasses($sClass)
  2970. {
  2971. self::_check_subclass($sClass);
  2972. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  2973. $aResult = array();
  2974. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  2975. {
  2976. if ($oAttDef->IsExternalKey())
  2977. {
  2978. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  2979. }
  2980. }
  2981. return $aResult;
  2982. }
  2983. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  2984. {
  2985. self::_check_subclass($sClass);
  2986. if ($bSkipLinkingClasses)
  2987. {
  2988. $aLinksClasses = self::EnumLinksClasses();
  2989. }
  2990. // 1-N links (referencing my class), array of sClass => array of sAttcode
  2991. $aResult = array();
  2992. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2993. {
  2994. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  2995. $aExtKeys = array();
  2996. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2997. {
  2998. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2999. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  3000. {
  3001. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  3002. // Ok, I want this one
  3003. $aExtKeys[$sAttCode] = $oAttDef;
  3004. }
  3005. }
  3006. if (count($aExtKeys) != 0)
  3007. {
  3008. $aResult[$sSomeClass] = $aExtKeys;
  3009. }
  3010. }
  3011. return $aResult;
  3012. }
  3013. public static function EnumLinksClasses()
  3014. {
  3015. // Returns a flat array of classes having at least two external keys
  3016. $aResult = array();
  3017. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  3018. {
  3019. $iExtKeyCount = 0;
  3020. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3021. {
  3022. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3023. if ($oAttDef->IsExternalKey())
  3024. {
  3025. $iExtKeyCount++;
  3026. }
  3027. }
  3028. if ($iExtKeyCount >= 2)
  3029. {
  3030. $aResult[] = $sSomeClass;
  3031. }
  3032. }
  3033. return $aResult;
  3034. }
  3035. public static function EnumLinkingClasses($sClass = "")
  3036. {
  3037. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  3038. $aResult = array();
  3039. foreach (self::EnumLinksClasses() as $sSomeClass)
  3040. {
  3041. $aTargets = array();
  3042. $bFoundClass = false;
  3043. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  3044. {
  3045. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3046. if ($oAttDef->IsExternalKey())
  3047. {
  3048. $sRemoteClass = $oAttDef->GetTargetClass();
  3049. if (empty($sClass))
  3050. {
  3051. $aTargets[$sAttCode] = $sRemoteClass;
  3052. }
  3053. elseif ($sClass == $sRemoteClass)
  3054. {
  3055. $bFoundClass = true;
  3056. }
  3057. else
  3058. {
  3059. $aTargets[$sAttCode] = $sRemoteClass;
  3060. }
  3061. }
  3062. }
  3063. if (empty($sClass) || $bFoundClass)
  3064. {
  3065. $aResult[$sSomeClass] = $aTargets;
  3066. }
  3067. }
  3068. return $aResult;
  3069. }
  3070. public static function GetLinkLabel($sLinkClass, $sAttCode)
  3071. {
  3072. self::_check_subclass($sLinkClass);
  3073. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  3074. return self::GetLabel($sLinkClass, $sAttCode);
  3075. }
  3076. /**
  3077. * Replaces all the parameters by the values passed in the hash array
  3078. */
  3079. static public function ApplyParams($aInput, $aParams)
  3080. {
  3081. $aSearches = array();
  3082. $aReplacements = array();
  3083. foreach($aParams as $sSearch => $sReplace)
  3084. {
  3085. $aSearches[] = '$'.$sSearch.'$';
  3086. $aReplacements[] = $sReplace;
  3087. }
  3088. return str_replace($aSearches, $aReplacements, $aInput);
  3089. }
  3090. } // class MetaModel
  3091. // Standard attribute lists
  3092. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  3093. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  3094. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  3095. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  3096. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  3097. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  3098. ?>