metamodel.class.php 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413
  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. return Dict::S("Class:$sClass/Attribute:$sStateAttrCode/Value:$sStateValue", $sStateValue);
  741. // I've decided the current implementation, because I need
  742. // to get the description as well -GetAllowedValues does not render the description,
  743. // so far...
  744. // Could have been implemented the following way (not tested
  745. // $oStateAttrDef = self::GetAttributeDef($sClass, $sStateAttrCode);
  746. // $aAllowedValues = $oStateAttrDef->GetAllowedValues();
  747. // return $aAllowedValues[$sStateValue];
  748. }
  749. public static function GetStateDescription($sClass, $sStateValue)
  750. {
  751. $sStateAttrCode = self::GetStateAttributeCode($sClass);
  752. return Dict::S("Class:$sClass/Attribute:$sStateAttrCode/Value:$sStateValue+", '');
  753. }
  754. public static function EnumTransitions($sClass, $sStateCode)
  755. {
  756. if (array_key_exists($sClass, self::$m_aTransitions))
  757. {
  758. if (array_key_exists($sStateCode, self::$m_aTransitions[$sClass]))
  759. {
  760. return self::$m_aTransitions[$sClass][$sStateCode];
  761. }
  762. }
  763. return array();
  764. }
  765. public static function GetAttributeFlags($sClass, $sState, $sAttCode)
  766. {
  767. $iFlags = 0; // By default (if no life cycle) no flag at all
  768. $sStateAttCode = self::GetStateAttributeCode($sClass);
  769. if (!empty($sStateAttCode))
  770. {
  771. $aStates = MetaModel::EnumStates($sClass);
  772. if (!array_key_exists($sState, $aStates))
  773. {
  774. throw new CoreException("Invalid state '$sState' for class '$sClass', expecting a value in {".implode(', ', array_keys($aStates))."}");
  775. }
  776. $aCurrentState = $aStates[$sState];
  777. if ( (array_key_exists('attribute_list', $aCurrentState)) && (array_key_exists($sAttCode, $aCurrentState['attribute_list'])) )
  778. {
  779. $iFlags = $aCurrentState['attribute_list'][$sAttCode];
  780. }
  781. }
  782. return $iFlags;
  783. }
  784. //
  785. // Allowed values
  786. //
  787. public static function GetAllowedValues_att($sClass, $sAttCode, $aArgs = array(), $sBeginsWith = '')
  788. {
  789. $oAttDef = self::GetAttributeDef($sClass, $sAttCode);
  790. return $oAttDef->GetAllowedValues($aArgs, $sBeginsWith);
  791. }
  792. public static function GetAllowedValues_flt($sClass, $sFltCode, $aArgs = array(), $sBeginsWith = '')
  793. {
  794. $oFltDef = self::GetClassFilterDef($sClass, $sFltCode);
  795. return $oFltDef->GetAllowedValues($aArgs, $sBeginsWith);
  796. }
  797. //
  798. // Businezz model declaration verbs (should be static)
  799. //
  800. public static function RegisterZList($sListCode, $aListInfo)
  801. {
  802. // Check mandatory params
  803. $aMandatParams = array(
  804. "description" => "detailed (though one line) description of the list",
  805. "type" => "attributes | filters",
  806. );
  807. foreach($aMandatParams as $sParamName=>$sParamDesc)
  808. {
  809. if (!array_key_exists($sParamName, $aListInfo))
  810. {
  811. throw new CoreException("Declaration of list $sListCode - missing parameter $sParamName");
  812. }
  813. }
  814. self::$m_aListInfos[$sListCode] = $aListInfo;
  815. }
  816. public static function RegisterRelation($sRelCode)
  817. {
  818. // Each item used to be an array of properties...
  819. self::$m_aRelationInfos[$sRelCode] = $sRelCode;
  820. }
  821. // Must be called once and only once...
  822. public static function InitClasses($sTablePrefix)
  823. {
  824. if (count(self::GetClasses()) > 0)
  825. {
  826. throw new CoreException("InitClasses should not be called more than once -skipped");
  827. return;
  828. }
  829. self::$m_sTablePrefix = $sTablePrefix;
  830. foreach(get_declared_classes() as $sPHPClass) {
  831. if (is_subclass_of($sPHPClass, 'DBObject'))
  832. {
  833. $sParent = get_parent_class($sPHPClass);
  834. if (array_key_exists($sParent, self::$m_aIgnoredAttributes))
  835. {
  836. // Inherit info about attributes to ignore
  837. self::$m_aIgnoredAttributes[$sPHPClass] = self::$m_aIgnoredAttributes[$sParent];
  838. }
  839. if (method_exists($sPHPClass, 'Init'))
  840. {
  841. call_user_func(array($sPHPClass, 'Init'));
  842. }
  843. }
  844. }
  845. foreach (self::GetClasses() as $sClass)
  846. {
  847. self::$m_aExtKeyFriends[$sClass] = array();
  848. foreach (self::$m_aAttribDefs[$sClass] as $sAttCode => $oAttDef)
  849. {
  850. // Compute the filter codes
  851. //
  852. foreach ($oAttDef->GetFilterDefinitions() as $sFilterCode => $oFilterDef)
  853. {
  854. self::$m_aFilterDefs[$sClass][$sFilterCode] = $oFilterDef;
  855. }
  856. if ($oAttDef->IsExternalField())
  857. {
  858. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  859. $oKeyDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  860. self::$m_aFilterOrigins[$sClass][$sFilterCode] = $oKeyDef->GetTargetClass();
  861. }
  862. else
  863. {
  864. self::$m_aFilterOrigins[$sClass][$sFilterCode] = self::$m_aAttribOrigins[$sClass][$sAttCode];
  865. }
  866. // Compute the fields that will be used to display a pointer to another object
  867. //
  868. if ($oAttDef->IsExternalKey(EXTKEY_ABSOLUTE))
  869. {
  870. // oAttDef is either
  871. // - an external KEY / FIELD (direct),
  872. // - an external field pointing to an external KEY / FIELD
  873. // - an external field pointing to an external field pointing to....
  874. // Get the real external key attribute
  875. // It will be our reference to determine the other ext fields related to the same ext key
  876. $oFinalKeyAttDef = $oAttDef->GetKeyAttDef(EXTKEY_ABSOLUTE);
  877. self::$m_aExtKeyFriends[$sClass][$sAttCode] = array();
  878. foreach (self::GetExternalFields($sClass, $oAttDef->GetKeyAttCode($sAttCode)) as $oExtField)
  879. {
  880. // skip : those extfields will be processed as external keys
  881. if ($oExtField->IsExternalKey(EXTKEY_ABSOLUTE)) continue;
  882. // Note: I could not compare the objects by the mean of '==='
  883. // because they are copied for the inheritance, and the internal references are NOT updated
  884. if ($oExtField->GetKeyAttDef(EXTKEY_ABSOLUTE) == $oFinalKeyAttDef)
  885. {
  886. self::$m_aExtKeyFriends[$sClass][$sAttCode][$oExtField->GetCode()] = $oExtField;
  887. }
  888. }
  889. }
  890. }
  891. // Add a 'id' filter
  892. //
  893. if (array_key_exists('id', self::$m_aAttribDefs[$sClass]))
  894. {
  895. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as an attribute code");
  896. }
  897. if (array_key_exists('id', self::$m_aFilterDefs[$sClass]))
  898. {
  899. throw new CoreException("Class $sClass, 'id' is a reserved keyword, it cannot be used as a filter code");
  900. }
  901. $oFilter = new FilterPrivateKey('id', array('id_field' => self::DBGetKey($sClass)));
  902. self::$m_aFilterDefs[$sClass]['id'] = $oFilter;
  903. self::$m_aFilterOrigins[$sClass]['id'] = $sClass;
  904. // Define defaults values for the standard ZLists
  905. //
  906. //foreach (self::$m_aListInfos as $sListCode => $aListConfig)
  907. //{
  908. // if (!isset(self::$m_aListData[$sClass][$sListCode]))
  909. // {
  910. // $aAllAttributes = array_keys(self::$m_aAttribDefs[$sClass]);
  911. // self::$m_aListData[$sClass][$sListCode] = $aAllAttributes;
  912. // //echo "<p>$sClass: $sListCode (".count($aAllAttributes)." attributes)</p>\n";
  913. // }
  914. //}
  915. }
  916. // Add a 'class' attribute/filter to the root classes and their children
  917. //
  918. foreach(self::EnumRootClasses() as $sRootClass)
  919. {
  920. if (self::IsStandaloneClass($sRootClass)) continue;
  921. $sDbFinalClassField = self::DBGetClassField($sRootClass);
  922. if (strlen($sDbFinalClassField) == 0)
  923. {
  924. $sDbFinalClassField = 'finalclass';
  925. self::$m_aClassParams[$sClass]["db_finalclass_field"] = 'finalclass';
  926. }
  927. $oClassAtt = new AttributeFinalClass('finalclass', array(
  928. "sql"=>$sDbFinalClassField,
  929. "default_value"=>$sRootClass,
  930. "is_null_allowed"=>false,
  931. "depends_on"=>array()
  932. ));
  933. $oClassAtt->SetHostClass($sRootClass);
  934. self::$m_aAttribDefs[$sRootClass]['finalclass'] = $oClassAtt;
  935. self::$m_aAttribOrigins[$sRootClass]['finalclass'] = $sRootClass;
  936. $oClassFlt = new FilterFromAttribute($oClassAtt);
  937. self::$m_aFilterDefs[$sRootClass]['finalclass'] = $oClassFlt;
  938. self::$m_aFilterOrigins[$sRootClass]['finalclass'] = $sRootClass;
  939. foreach(self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_EXCLUDETOP) as $sChildClass)
  940. {
  941. if (array_key_exists('finalclass', self::$m_aAttribDefs[$sChildClass]))
  942. {
  943. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as an attribute code");
  944. }
  945. if (array_key_exists('finalclass', self::$m_aFilterDefs[$sChildClass]))
  946. {
  947. throw new CoreException("Class $sChildClass, 'finalclass' is a reserved keyword, it cannot be used as a filter code");
  948. }
  949. $oCloned = clone $oClassAtt;
  950. $oCloned->SetFixedValue($sChildClass);
  951. self::$m_aAttribDefs[$sChildClass]['finalclass'] = $oCloned;
  952. self::$m_aAttribOrigins[$sChildClass]['finalclass'] = $sRootClass;
  953. $oClassFlt = new FilterFromAttribute($oClassAtt);
  954. self::$m_aFilterDefs[$sChildClass]['finalclass'] = $oClassFlt;
  955. self::$m_aFilterOrigins[$sChildClass]['finalclass'] = self::GetRootClass($sChildClass);
  956. }
  957. }
  958. }
  959. // To be overriden, must be called for any object class (optimization)
  960. public static function Init()
  961. {
  962. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  963. }
  964. // To be overloaded by biz model declarations
  965. public static function GetRelationQueries($sRelCode)
  966. {
  967. // In fact it is an ABSTRACT function, but this is not compatible with the fact that it is STATIC (error in E_STRICT interpretation)
  968. return array();
  969. }
  970. public static function Init_Params($aParams)
  971. {
  972. // Check mandatory params
  973. $aMandatParams = array(
  974. "category" => "group classes by modules defining their visibility in the UI",
  975. "key_type" => "autoincrement | string",
  976. "name_attcode" => "define wich attribute is the class name, may be an inherited attribute",
  977. "state_attcode" => "define wich attribute is representing the state (object lifecycle)",
  978. "reconc_keys" => "define the attributes that will 'almost uniquely' identify an object in batch processes",
  979. "db_table" => "database table",
  980. "db_key_field" => "database field which is the key",
  981. "db_finalclass_field" => "database field wich is the reference to the actual class of the object, considering that this will be a compound class",
  982. );
  983. $sClass = self::GetCallersPHPClass("Init");
  984. foreach($aMandatParams as $sParamName=>$sParamDesc)
  985. {
  986. if (!array_key_exists($sParamName, $aParams))
  987. {
  988. throw new CoreException("Declaration of class $sClass - missing parameter $sParamName");
  989. }
  990. }
  991. $aCategories = explode(',', $aParams['category']);
  992. foreach ($aCategories as $sCategory)
  993. {
  994. self::$m_Category2Class[$sCategory][] = $sClass;
  995. }
  996. self::$m_Category2Class[''][] = $sClass; // all categories, include this one
  997. self::$m_aRootClasses[$sClass] = $sClass; // first, let consider that I am the root... updated on inheritance
  998. self::$m_aParentClasses[$sClass] = array();
  999. self::$m_aChildClasses[$sClass] = array();
  1000. self::$m_aClassParams[$sClass]= $aParams;
  1001. self::$m_aAttribDefs[$sClass] = array();
  1002. self::$m_aAttribOrigins[$sClass] = array();
  1003. self::$m_aExtKeyFriends[$sClass] = array();
  1004. self::$m_aFilterDefs[$sClass] = array();
  1005. self::$m_aFilterOrigins[$sClass] = array();
  1006. }
  1007. protected static function object_array_mergeclone($aSource1, $aSource2)
  1008. {
  1009. $aRes = array();
  1010. foreach ($aSource1 as $key=>$object)
  1011. {
  1012. $aRes[$key] = clone $object;
  1013. }
  1014. foreach ($aSource2 as $key=>$object)
  1015. {
  1016. $aRes[$key] = clone $object;
  1017. }
  1018. return $aRes;
  1019. }
  1020. public static function Init_InheritAttributes($sSourceClass = null)
  1021. {
  1022. $sTargetClass = self::GetCallersPHPClass("Init");
  1023. if (empty($sSourceClass))
  1024. {
  1025. // Default: inherit from parent class
  1026. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1027. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1028. }
  1029. if (isset(self::$m_aAttribDefs[$sSourceClass]))
  1030. {
  1031. if (!isset(self::$m_aAttribDefs[$sTargetClass]))
  1032. {
  1033. self::$m_aAttribDefs[$sTargetClass] = array();
  1034. self::$m_aAttribOrigins[$sTargetClass] = array();
  1035. }
  1036. self::$m_aAttribDefs[$sTargetClass] = self::object_array_mergeclone(self::$m_aAttribDefs[$sTargetClass], self::$m_aAttribDefs[$sSourceClass]);
  1037. self::$m_aAttribOrigins[$sTargetClass] = array_merge(self::$m_aAttribOrigins[$sTargetClass], self::$m_aAttribOrigins[$sSourceClass]);
  1038. }
  1039. // Build root class information
  1040. if (array_key_exists($sSourceClass, self::$m_aRootClasses))
  1041. {
  1042. // Inherit...
  1043. self::$m_aRootClasses[$sTargetClass] = self::$m_aRootClasses[$sSourceClass];
  1044. }
  1045. else
  1046. {
  1047. // This class will be the root class
  1048. self::$m_aRootClasses[$sSourceClass] = $sSourceClass;
  1049. self::$m_aRootClasses[$sTargetClass] = $sSourceClass;
  1050. }
  1051. self::$m_aParentClasses[$sTargetClass] += self::$m_aParentClasses[$sSourceClass];
  1052. self::$m_aParentClasses[$sTargetClass][] = $sSourceClass;
  1053. // I am the child of each and every parent...
  1054. foreach(self::$m_aParentClasses[$sTargetClass] as $sAncestorClass)
  1055. {
  1056. self::$m_aChildClasses[$sAncestorClass][] = $sTargetClass;
  1057. }
  1058. }
  1059. public static function Init_OverloadAttributeParams($sAttCode, $aParams)
  1060. {
  1061. $sTargetClass = self::GetCallersPHPClass("Init");
  1062. if (!self::IsValidAttCode($sTargetClass, $sAttCode))
  1063. {
  1064. throw new CoreException("Could not overload '$sAttCode', expecting a code from {".implode(", ", self::GetAttributesList($sTargetClass))."}");
  1065. }
  1066. self::$m_aAttribDefs[$sTargetClass][$sAttCode]->OverloadParams($aParams);
  1067. }
  1068. protected static function Init_IsKnownClass($sClass)
  1069. {
  1070. // Differs from self::IsValidClass()
  1071. // because it is being called before all the classes have been initialized
  1072. if (!class_exists($sClass)) return false;
  1073. if (!is_subclass_of($sClass, 'DBObject')) return false;
  1074. return true;
  1075. }
  1076. public static function Init_AddAttribute(AttributeDefinition $oAtt)
  1077. {
  1078. $sTargetClass = self::GetCallersPHPClass("Init");
  1079. // Some attributes could refer to a class
  1080. // declared in a module which is currently not installed/active
  1081. // We simply discard those attributes
  1082. //
  1083. if ($oAtt->IsLinkSet())
  1084. {
  1085. $sRemoteClass = $oAtt->GetLinkedClass();
  1086. if (!self::Init_IsKnownClass($sRemoteClass))
  1087. {
  1088. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1089. return;
  1090. }
  1091. }
  1092. elseif($oAtt->IsExternalKey())
  1093. {
  1094. $sRemoteClass = $oAtt->GetTargetClass();
  1095. if (!self::Init_IsKnownClass($sRemoteClass))
  1096. {
  1097. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = $sRemoteClass;
  1098. return;
  1099. }
  1100. }
  1101. elseif($oAtt->IsExternalField())
  1102. {
  1103. $sExtKeyAttCode = $oAtt->GetKeyAttCode();
  1104. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode]))
  1105. {
  1106. // The corresponding external key has already been ignored
  1107. self::$m_aIgnoredAttributes[$sTargetClass][$oAtt->GetCode()] = self::$m_aIgnoredAttributes[$sTargetClass][$sExtKeyAttCode];
  1108. return;
  1109. }
  1110. // #@# todo - Check if the target attribute is still there
  1111. // this is not simple to implement because is involves
  1112. // several passes (the load order has a significant influence on that)
  1113. }
  1114. self::$m_aAttribDefs[$sTargetClass][$oAtt->GetCode()] = $oAtt;
  1115. self::$m_aAttribOrigins[$sTargetClass][$oAtt->GetCode()] = $sTargetClass;
  1116. // Note: it looks redundant to put targetclass there, but a mix occurs when inheritance is used
  1117. // Specific case of external fields:
  1118. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1119. // Therefore, the reference to the host class is set there
  1120. $oAtt->SetHostClass($sTargetClass);
  1121. }
  1122. public static function Init_SetZListItems($sListCode, $aItems)
  1123. {
  1124. MyHelpers::CheckKeyInArray('list code', $sListCode, self::$m_aListInfos);
  1125. $sTargetClass = self::GetCallersPHPClass("Init");
  1126. // Discard attributes that do not make sense
  1127. // (missing classes in the current module combination, resulting in irrelevant ext key or link set)
  1128. //
  1129. foreach($aItems as $iFoo => $sAttCode)
  1130. {
  1131. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1132. {
  1133. unset($aItems[$iFoo]);
  1134. }
  1135. }
  1136. self::$m_aListData[$sTargetClass][$sListCode] = $aItems;
  1137. }
  1138. public static function Init_DefineState($sStateCode, $aStateDef)
  1139. {
  1140. $sTargetClass = self::GetCallersPHPClass("Init");
  1141. if (is_null($aStateDef['attribute_list'])) $aStateDef['attribute_list'] = array();
  1142. $sParentState = $aStateDef['attribute_inherit'];
  1143. if (!empty($sParentState))
  1144. {
  1145. // Inherit from the given state (must be defined !)
  1146. //
  1147. $aToInherit = self::$m_aStates[$sTargetClass][$sParentState];
  1148. // Reset the constraint when it was mandatory to set the value at the previous state
  1149. //
  1150. foreach ($aToInherit['attribute_list'] as $sState => $iFlags)
  1151. {
  1152. $iFlags = $iFlags & ~OPT_ATT_MUSTPROMPT;
  1153. $iFlags = $iFlags & ~OPT_ATT_MUSTCHANGE;
  1154. $aToInherit['attribute_list'][$sState] = $iFlags;
  1155. }
  1156. // The inherited configuration could be overriden
  1157. $aStateDef['attribute_list'] = array_merge($aToInherit['attribute_list'], $aStateDef['attribute_list']);
  1158. }
  1159. foreach($aStateDef['attribute_list'] as $sAttCode => $iFlags)
  1160. {
  1161. if (isset(self::$m_aIgnoredAttributes[$sTargetClass][$sAttCode]))
  1162. {
  1163. unset($aStateDef['attribute_list'][$sAttCode]);
  1164. }
  1165. }
  1166. self::$m_aStates[$sTargetClass][$sStateCode] = $aStateDef;
  1167. // by default, create an empty set of transitions associated to that state
  1168. self::$m_aTransitions[$sTargetClass][$sStateCode] = array();
  1169. }
  1170. public static function Init_DefineStimulus($oStimulus)
  1171. {
  1172. $sTargetClass = self::GetCallersPHPClass("Init");
  1173. self::$m_aStimuli[$sTargetClass][$oStimulus->GetCode()] = $oStimulus;
  1174. // I wanted to simplify the syntax of the declaration of objects in the biz model
  1175. // Therefore, the reference to the host class is set there
  1176. $oStimulus->SetHostClass($sTargetClass);
  1177. }
  1178. public static function Init_DefineTransition($sStateCode, $sStimulusCode, $aTransitionDef)
  1179. {
  1180. $sTargetClass = self::GetCallersPHPClass("Init");
  1181. if (is_null($aTransitionDef['actions'])) $aTransitionDef['actions'] = array();
  1182. self::$m_aTransitions[$sTargetClass][$sStateCode][$sStimulusCode] = $aTransitionDef;
  1183. }
  1184. public static function Init_InheritLifecycle($sSourceClass = '')
  1185. {
  1186. $sTargetClass = self::GetCallersPHPClass("Init");
  1187. if (empty($sSourceClass))
  1188. {
  1189. // Default: inherit from parent class
  1190. $sSourceClass = self::GetParentPersistentClass($sTargetClass);
  1191. if (empty($sSourceClass)) return; // no attributes for the mother of all classes
  1192. }
  1193. self::$m_aClassParams[$sTargetClass]["state_attcode"] = self::$m_aClassParams[$sSourceClass]["state_attcode"];
  1194. self::$m_aStates[$sTargetClass] = clone self::$m_aStates[$sSourceClass];
  1195. self::$m_aStimuli[$sTargetClass] = clone self::$m_aStimuli[$sSourceClass];
  1196. self::$m_aTransitions[$sTargetClass] = clone self::$m_aTransitions[$sSourceClass];
  1197. }
  1198. //
  1199. // Static API
  1200. //
  1201. public static function GetRootClass($sClass = null)
  1202. {
  1203. self::_check_subclass($sClass);
  1204. return self::$m_aRootClasses[$sClass];
  1205. }
  1206. public static function IsRootClass($sClass)
  1207. {
  1208. self::_check_subclass($sClass);
  1209. return (self::GetRootClass($sClass) == $sClass);
  1210. }
  1211. public static function EnumRootClasses()
  1212. {
  1213. return array_unique(self::$m_aRootClasses);
  1214. }
  1215. public static function EnumParentClasses($sClass)
  1216. {
  1217. self::_check_subclass($sClass);
  1218. return self::$m_aParentClasses[$sClass];
  1219. }
  1220. public static function EnumChildClasses($sClass, $iOption = ENUM_CHILD_CLASSES_EXCLUDETOP)
  1221. {
  1222. self::_check_subclass($sClass);
  1223. $aRes = self::$m_aChildClasses[$sClass];
  1224. if ($iOption != ENUM_CHILD_CLASSES_EXCLUDETOP)
  1225. {
  1226. // Add it to the list
  1227. $aRes[] = $sClass;
  1228. }
  1229. return $aRes;
  1230. }
  1231. public static function EnumCategories()
  1232. {
  1233. return array_keys(self::$m_Category2Class);
  1234. }
  1235. // Note: use EnumChildClasses to take the compound objects into account
  1236. public static function GetSubclasses($sClass)
  1237. {
  1238. self::_check_subclass($sClass);
  1239. $aSubClasses = array();
  1240. foreach(get_declared_classes() as $sSubClass) {
  1241. if (is_subclass_of($sSubClass, $sClass))
  1242. {
  1243. $aSubClasses[] = $sSubClass;
  1244. }
  1245. }
  1246. return $aSubClasses;
  1247. }
  1248. public static function GetClasses($sCategory = '')
  1249. {
  1250. if (array_key_exists($sCategory, self::$m_Category2Class))
  1251. {
  1252. return self::$m_Category2Class[$sCategory];
  1253. }
  1254. //if (count(self::$m_Category2Class) > 0)
  1255. //{
  1256. // throw new CoreException("unkown class category '$sCategory', expecting a value in {".implode(', ', array_keys(self::$m_Category2Class))."}");
  1257. //}
  1258. return array();
  1259. }
  1260. public static function HasTable($sClass)
  1261. {
  1262. if (strlen(self::DBGetTable($sClass)) == 0) return false;
  1263. return true;
  1264. }
  1265. public static function IsAbstract($sClass)
  1266. {
  1267. $oReflection = new ReflectionClass($sClass);
  1268. return $oReflection->isAbstract();
  1269. }
  1270. protected static $m_aQueryStructCache = array();
  1271. protected static function PrepareQueryArguments($aArgs)
  1272. {
  1273. // Translate any object into scalars
  1274. //
  1275. $aScalarArgs = array();
  1276. foreach($aArgs as $sArgName => $value)
  1277. {
  1278. if (self::IsValidObject($value))
  1279. {
  1280. $aScalarArgs = array_merge($aScalarArgs, $value->ToArgs($sArgName));
  1281. }
  1282. else
  1283. {
  1284. $aScalarArgs[$sArgName] = (string) $value;
  1285. }
  1286. }
  1287. // Add standard contextual arguments
  1288. //
  1289. $aScalarArgs['current_contact_id'] = UserRights::GetContactId();
  1290. return $aScalarArgs;
  1291. }
  1292. public static function MakeSelectQuery(DBObjectSearch $oFilter, $aOrderBy = array(), $aArgs = array())
  1293. {
  1294. // Query caching
  1295. //
  1296. $bQueryCacheEnabled = true;
  1297. $aParams = array();
  1298. $sOqlQuery = $oFilter->ToOql($aParams); // Render with arguments in clear
  1299. if ($bQueryCacheEnabled)
  1300. {
  1301. if (array_key_exists($sOqlQuery, self::$m_aQueryStructCache))
  1302. {
  1303. // hit!
  1304. $oSelect = clone self::$m_aQueryStructCache[$sOqlQuery];
  1305. }
  1306. }
  1307. if (!isset($oSelect))
  1308. {
  1309. $aTranslation = array();
  1310. $aClassAliases = array();
  1311. $aTableAliases = array();
  1312. $oConditionTree = $oFilter->GetCriteria();
  1313. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1314. self::$m_aQueryStructCache[$sOqlQuery] = clone $oSelect;
  1315. }
  1316. // Check the order by specification, and prefix with the class alias
  1317. //
  1318. $aOrderSpec = array();
  1319. foreach ($aOrderBy as $sFieldAlias => $bAscending)
  1320. {
  1321. MyHelpers::CheckValueInArray('field name in ORDER BY spec', $sFieldAlias, self::GetAttributesList($oFilter->GetFirstJoinedClass()));
  1322. if (!is_bool($bAscending))
  1323. {
  1324. throw new CoreException("Wrong direction in ORDER BY spec, found '$bAscending' and expecting a boolean value");
  1325. }
  1326. $aOrderSpec[$oFilter->GetFirstJoinedClassAlias().$sFieldAlias] = $bAscending;
  1327. }
  1328. // By default, force the name attribute to be the ordering key
  1329. //
  1330. if (empty($aOrderSpec))
  1331. {
  1332. foreach ($oFilter->GetSelectedClasses() as $sSelectedAlias => $sSelectedClass)
  1333. {
  1334. $sNameAttCode = self::GetNameAttributeCode($sSelectedClass);
  1335. if (!empty($sNameAttCode))
  1336. {
  1337. // By default, simply order on the "name" attribute, ascending
  1338. $aOrderSpec[$sSelectedAlias.$sNameAttCode] = true;
  1339. }
  1340. }
  1341. }
  1342. // Go
  1343. //
  1344. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1345. try
  1346. {
  1347. $sRes = $oSelect->RenderSelect($aOrderSpec, $aScalarArgs);
  1348. }
  1349. catch (MissingQueryArgument $e)
  1350. {
  1351. // Add some information...
  1352. $e->addInfo('OQL', $sOqlQuery);
  1353. throw $e;
  1354. }
  1355. if (self::$m_bTraceQueries)
  1356. {
  1357. $aParams = array();
  1358. if (!array_key_exists($sOqlQuery, self::$m_aQueriesLog))
  1359. {
  1360. self::$m_aQueriesLog[$sOqlQuery] = array(
  1361. 'sql' => array(),
  1362. 'count' => 0,
  1363. );
  1364. }
  1365. self::$m_aQueriesLog[$sOqlQuery]['count']++;
  1366. self::$m_aQueriesLog[$sOqlQuery]['sql'][] = $sRes;
  1367. }
  1368. return $sRes;
  1369. }
  1370. public static function ShowQueryTrace()
  1371. {
  1372. $iTotal = 0;
  1373. foreach (self::$m_aQueriesLog as $sOql => $aQueryData)
  1374. {
  1375. echo "<h2>$sOql</h2>\n";
  1376. $iTotal += $aQueryData['count'];
  1377. echo '<p>'.$aQueryData['count'].'</p>';
  1378. echo '<p>Example: '.$aQueryData['sql'][0].'</p>';
  1379. }
  1380. echo "<h2>Total</h2>\n";
  1381. echo "<p>Count of executed queries: $iTotal</p>";
  1382. echo "<p>Count of built queries: ".count(self::$m_aQueriesLog)."</p>";
  1383. }
  1384. public static function MakeDeleteQuery(DBObjectSearch $oFilter, $aArgs = array())
  1385. {
  1386. $aTranslation = array();
  1387. $aClassAliases = array();
  1388. $aTableAliases = array();
  1389. $oConditionTree = $oFilter->GetCriteria();
  1390. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter);
  1391. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1392. return $oSelect->RenderDelete($aScalarArgs);
  1393. }
  1394. public static function MakeUpdateQuery(DBObjectSearch $oFilter, $aValues, $aArgs = array())
  1395. {
  1396. // $aValues is an array of $sAttCode => $value
  1397. $aTranslation = array();
  1398. $aClassAliases = array();
  1399. $aTableAliases = array();
  1400. $oConditionTree = $oFilter->GetCriteria();
  1401. $oSelect = self::MakeQuery($oFilter->GetSelectedClasses(), $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, array(), $aValues);
  1402. $aScalarArgs = array_merge(self::PrepareQueryArguments($aArgs), $oFilter->GetInternalParams());
  1403. return $oSelect->RenderUpdate($aScalarArgs);
  1404. }
  1405. private static function MakeQuery($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, DBObjectSearch $oFilter, $aExpectedAtts = array(), $aValues = array())
  1406. {
  1407. // Note: query class might be different than the class of the filter
  1408. // -> this occurs when we are linking our class to an external class (referenced by, or pointing to)
  1409. // $aExpectedAtts is an array of sAttCode=>array of columns
  1410. $sClass = $oFilter->GetFirstJoinedClass();
  1411. $sClassAlias = $oFilter->GetFirstJoinedClassAlias();
  1412. $bIsOnQueriedClass = array_key_exists($sClassAlias, $aSelectedClasses);
  1413. if ($bIsOnQueriedClass)
  1414. {
  1415. $aClassAliases = array_merge($aClassAliases, $oFilter->GetJoinedClasses());
  1416. }
  1417. self::DbgTrace("Entering: ".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1418. $sRootClass = self::GetRootClass($sClass);
  1419. $sKeyField = self::DBGetKey($sClass);
  1420. if ($bIsOnQueriedClass)
  1421. {
  1422. // default to the whole list of attributes + the very std id/finalclass
  1423. $aExpectedAtts['id'][] = $sClassAlias.'id';
  1424. foreach (self::GetAttributesList($sClass) as $sAttCode)
  1425. {
  1426. $aExpectedAtts[$sAttCode][] = $sClassAlias.$sAttCode; // alias == class and attcode
  1427. }
  1428. }
  1429. // Compute a clear view of external keys, and external attributes
  1430. // Build the list of external keys:
  1431. // -> ext keys required by a closed join ???
  1432. // -> ext keys mentionned in a 'pointing to' condition
  1433. // -> ext keys required for an external field
  1434. //
  1435. $aExtKeys = array(); // array of sTableClass => array of (sAttCode (keys) => array of (sAttCode (fields)=> oAttDef))
  1436. //
  1437. // Optimization: could be computed once for all (cached)
  1438. // Could be done in MakeQuerySingleTable ???
  1439. //
  1440. if ($bIsOnQueriedClass)
  1441. {
  1442. // Get all Ext keys for the queried class (??)
  1443. foreach(self::GetKeysList($sClass) as $sKeyAttCode)
  1444. {
  1445. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1446. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1447. }
  1448. }
  1449. // Get all Ext keys used by the filter
  1450. foreach ($oFilter->GetCriteria_PointingTo() as $sKeyAttCode => $trash)
  1451. {
  1452. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1453. $aExtKeys[$sKeyTableClass][$sKeyAttCode] = array();
  1454. }
  1455. // Add the ext fields used in the select (eventually adds an external key)
  1456. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1457. {
  1458. if ($oAttDef->IsExternalField())
  1459. {
  1460. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1461. if (array_key_exists($sAttCode, $aExpectedAtts) || $oConditionTree->RequiresField($sClassAlias, $sAttCode))
  1462. {
  1463. // Add the external attribute
  1464. $sKeyTableClass = self::$m_aAttribOrigins[$sClass][$sKeyAttCode];
  1465. $aExtKeys[$sKeyTableClass][$sKeyAttCode][$sAttCode] = $oAttDef;
  1466. }
  1467. }
  1468. }
  1469. // First query built upon on the leaf (ie current) class
  1470. //
  1471. self::DbgTrace("Main (=leaf) class, call MakeQuerySingleTable()");
  1472. if (self::HasTable($sClass))
  1473. {
  1474. $oSelectBase = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sClass, $aExpectedAtts, $aExtKeys, $aValues);
  1475. }
  1476. else
  1477. {
  1478. $oSelectBase = null;
  1479. // As the join will not filter on the expected classes, we have to specify it explicitely
  1480. $sExpectedClasses = implode("', '", self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL));
  1481. $oFinalClassRestriction = Expression::FromOQL("`$sClassAlias`.finalclass IN ('$sExpectedClasses')");
  1482. $oConditionTree = $oConditionTree->LogAnd($oFinalClassRestriction);
  1483. }
  1484. // Then we join the queries of the eventual parent classes (compound model)
  1485. foreach(self::EnumParentClasses($sClass) as $sParentClass)
  1486. {
  1487. if (self::DBGetTable($sParentClass) == "") continue;
  1488. self::DbgTrace("Parent class: $sParentClass... let's call MakeQuerySingleTable()");
  1489. $oSelectParentTable = self::MakeQuerySingleTable($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oFilter, $sParentClass, $aExpectedAtts, $aExtKeys, $aValues);
  1490. if (is_null($oSelectBase))
  1491. {
  1492. $oSelectBase = $oSelectParentTable;
  1493. }
  1494. else
  1495. {
  1496. $oSelectBase->AddInnerJoin($oSelectParentTable, $sKeyField, self::DBGetKey($sParentClass));
  1497. }
  1498. }
  1499. // Filter on objects referencing me
  1500. foreach ($oFilter->GetCriteria_ReferencedBy() as $sForeignClass => $aKeysAndFilters)
  1501. {
  1502. foreach ($aKeysAndFilters as $sForeignKeyAttCode => $oForeignFilter)
  1503. {
  1504. $oForeignKeyAttDef = self::GetAttributeDef($sForeignClass, $sForeignKeyAttCode);
  1505. // We don't want any attribute from the foreign class, just filter on an inner join
  1506. $aExpAtts = array();
  1507. self::DbgTrace("Referenced by foreign key: $sForeignKeyAttCode... let's call MakeQuery()");
  1508. //self::DbgTrace($oForeignFilter);
  1509. //self::DbgTrace($oForeignFilter->ToOQL());
  1510. //self::DbgTrace($oSelectForeign);
  1511. //self::DbgTrace($oSelectForeign->RenderSelect(array()));
  1512. $oSelectForeign = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oForeignFilter, $aExpAtts);
  1513. $sForeignClassAlias = $oForeignFilter->GetFirstJoinedClassAlias();
  1514. $sForeignKeyTable = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][0];
  1515. $sForeignKeyColumn = $aTranslation[$sForeignClassAlias][$sForeignKeyAttCode][1];
  1516. $oSelectBase->AddInnerJoin($oSelectForeign, $sKeyField, $sForeignKeyColumn, $sForeignKeyTable);
  1517. }
  1518. }
  1519. // Filter on related objects
  1520. //
  1521. foreach ($oFilter->GetCriteria_RelatedTo() as $aCritInfo)
  1522. {
  1523. $oSubFilter = $aCritInfo['flt'];
  1524. $sRelCode = $aCritInfo['relcode'];
  1525. $iMaxDepth = $aCritInfo['maxdepth'];
  1526. // Get the starting point objects
  1527. $oStartSet = new CMDBObjectSet($oSubFilter);
  1528. // Get the objects related to those objects... recursively...
  1529. $aRelatedObjs = $oStartSet->GetRelatedObjects($sRelCode, $iMaxDepth);
  1530. $aRestriction = array_key_exists($sRootClass, $aRelatedObjs) ? $aRelatedObjs[$sRootClass] : array();
  1531. // #@# todo - related objects and expressions...
  1532. // Create condition
  1533. if (count($aRestriction) > 0)
  1534. {
  1535. $oSelectBase->AddCondition($sKeyField.' IN ('.implode(', ', CMDBSource::Quote(array_keys($aRestriction), true)).')');
  1536. }
  1537. else
  1538. {
  1539. // Quick N'dirty -> generate an empty set
  1540. $oSelectBase->AddCondition('false');
  1541. }
  1542. }
  1543. // Translate the conditions... and go
  1544. //
  1545. if ($bIsOnQueriedClass)
  1546. {
  1547. $oConditionTranslated = $oConditionTree->Translate($aTranslation);
  1548. $oSelectBase->SetCondition($oConditionTranslated);
  1549. }
  1550. // That's all... cross fingers and we'll get some working query
  1551. //MyHelpers::var_dump_html($oSelectBase, true);
  1552. //MyHelpers::var_dump_html($oSelectBase->RenderSelect(), true);
  1553. if (self::$m_bDebugQuery) $oSelectBase->DisplayHtml();
  1554. return $oSelectBase;
  1555. }
  1556. protected static function MakeQuerySingleTable($aSelectedClasses, &$oConditionTree, &$aClassAliases, &$aTableAliases, &$aTranslation, $oFilter, $sTableClass, $aExpectedAtts, $aExtKeys, $aValues)
  1557. {
  1558. // $aExpectedAtts is an array of sAttCode=>sAlias
  1559. // $aExtKeys is an array of sTableClass => array of (sAttCode (keys) => array of sAttCode (fields))
  1560. // Prepare the query for a single table (compound objects)
  1561. // Ignores the items (attributes/filters) that are not on the target table
  1562. // Perform an (inner or left) join for every external key (and specify the expected fields)
  1563. //
  1564. // Returns an SQLQuery
  1565. //
  1566. $sTargetClass = $oFilter->GetFirstJoinedClass();
  1567. $sTargetAlias = $oFilter->GetFirstJoinedClassAlias();
  1568. $sTable = self::DBGetTable($sTableClass);
  1569. $sTableAlias = self::GenerateUniqueAlias($aTableAliases, $sTargetAlias.'_'.$sTable, $sTable);
  1570. $bIsOnQueriedClass = array_key_exists($sTargetAlias, $aSelectedClasses);
  1571. self::DbgTrace("Entering: tableclass=$sTableClass, filter=".$oFilter->ToOQL().", ".($bIsOnQueriedClass ? "MAIN" : "SECONDARY").", expectedatts=".count($aExpectedAtts).": ".implode(",", array_keys($aExpectedAtts)));
  1572. // 1 - SELECT and UPDATE
  1573. //
  1574. // Note: no need for any values nor fields for foreign Classes (ie not the queried Class)
  1575. //
  1576. $aSelect = array();
  1577. $aUpdateValues = array();
  1578. // 1/a - Get the key
  1579. //
  1580. if ($bIsOnQueriedClass)
  1581. {
  1582. $aSelect[$aExpectedAtts['id'][0]] = new FieldExpression(self::DBGetKey($sTableClass), $sTableAlias);
  1583. }
  1584. // We need one pkey to be the key, let's take the one corresponding to the root class
  1585. // (used to be based on the leaf, but it may happen that this one has no table defined)
  1586. $sRootClass = self::GetRootClass($sTargetClass);
  1587. if ($sTableClass == $sRootClass)
  1588. {
  1589. $aTranslation[$sTargetAlias]['id'] = array($sTableAlias, self::DBGetKey($sTableClass));
  1590. }
  1591. // 1/b - Get the other attributes
  1592. //
  1593. foreach(self::ListAttributeDefs($sTableClass) as $sAttCode=>$oAttDef)
  1594. {
  1595. // Skip this attribute if not defined in this table
  1596. if (self::$m_aAttribOrigins[$sTargetClass][$sAttCode] != $sTableClass) continue;
  1597. // Skip this attribute if not writable (means that it does not correspond
  1598. if (count($oAttDef->GetSQLExpressions()) == 0) continue;
  1599. // Update...
  1600. //
  1601. if ($bIsOnQueriedClass && array_key_exists($sAttCode, $aValues))
  1602. {
  1603. assert ($oAttDef->IsDirectField());
  1604. foreach ($oAttDef->GetSQLValues($aValues[$sAttCode]) as $sColumn => $sValue)
  1605. {
  1606. $aUpdateValues[$sColumn] = $sValue;
  1607. }
  1608. }
  1609. // Select...
  1610. //
  1611. // Skip, if a list of fields has been specified and it is not there
  1612. if (!array_key_exists($sAttCode, $aExpectedAtts)) continue;
  1613. if ($oAttDef->IsExternalField())
  1614. {
  1615. // skip, this will be handled in the joined tables
  1616. }
  1617. else
  1618. {
  1619. // standard field, or external key
  1620. // add it to the output
  1621. foreach ($oAttDef->GetSQLExpressions() as $sColId => $sSQLExpr)
  1622. {
  1623. foreach ($aExpectedAtts[$sAttCode] as $sAttAlias)
  1624. {
  1625. $aSelect[$sAttAlias.$sColId] = new FieldExpression($sSQLExpr, $sTableAlias);
  1626. }
  1627. }
  1628. }
  1629. }
  1630. // 2 - WHERE
  1631. //
  1632. foreach(self::$m_aFilterDefs[$sTargetClass] as $sFltCode => $oFltAtt)
  1633. {
  1634. // Skip this filter if not defined in this table
  1635. if (self::$m_aFilterOrigins[$sTargetClass][$sFltCode] != $sTableClass) continue;
  1636. // #@# todo - aller plus loin... a savoir que la table de translation doit contenir une "Expression"
  1637. foreach($oFltAtt->GetSQLExpressions() as $sColID => $sFltExpr)
  1638. {
  1639. // Note: I did not test it with filters relying on several expressions...
  1640. // as long as sColdID is empty, this is working, otherwise... ?
  1641. $aTranslation[$sTargetAlias][$sFltCode.$sColID] = array($sTableAlias, $sFltExpr);
  1642. }
  1643. }
  1644. // #@# todo - See what a full text search condition should be
  1645. // 2' - WHERE / Full text search condition
  1646. //
  1647. if ($bIsOnQueriedClass)
  1648. {
  1649. $aFullText = $oFilter->GetCriteria_FullText();
  1650. }
  1651. else
  1652. {
  1653. // Pourquoi ???
  1654. $aFullText = array();
  1655. }
  1656. // 3 - The whole stuff, for this table only
  1657. //
  1658. $oSelectBase = new SQLQuery($sTable, $sTableAlias, $aSelect, null, $aFullText, $bIsOnQueriedClass, $aUpdateValues);
  1659. // 4 - The external keys -> joins...
  1660. //
  1661. if (array_key_exists($sTableClass, $aExtKeys))
  1662. {
  1663. foreach ($aExtKeys[$sTableClass] as $sKeyAttCode => $aExtFields)
  1664. {
  1665. $oKeyAttDef = self::GetAttributeDef($sTargetClass, $sKeyAttCode);
  1666. $oExtFilter = $oFilter->GetCriteria_PointingTo($sKeyAttCode);
  1667. // In case the join was not explicitely defined in the filter,
  1668. // we need to do it now
  1669. if (empty($oExtFilter))
  1670. {
  1671. $sKeyClass = $oKeyAttDef->GetTargetClass();
  1672. $sKeyClassAlias = self::GenerateUniqueAlias($aClassAliases, $sKeyClass.'_'.$sKeyAttCode, $sKeyClass);
  1673. $oExtFilter = new DBObjectSearch($sKeyClass, $sKeyClassAlias);
  1674. }
  1675. else
  1676. {
  1677. // The aliases should not conflict because normalization occured while building the filter
  1678. $sKeyClass = $oExtFilter->GetFirstJoinedClass();
  1679. $sKeyClassAlias = $oExtFilter->GetFirstJoinedClassAlias();
  1680. // Note: there is no search condition in $oExtFilter, because normalization did merge the condition onto the top of the filter tree
  1681. }
  1682. // Specify expected attributes for the target class query
  1683. // ... and use the current alias !
  1684. $aExpAtts = array();
  1685. $aIntermediateTranslation = array();
  1686. foreach($aExtFields as $sAttCode => $oAtt)
  1687. {
  1688. $sExtAttCode = $oAtt->GetExtAttCode();
  1689. if (array_key_exists($sAttCode, $aExpectedAtts))
  1690. {
  1691. // Request this attribute... transmit the alias !
  1692. $aExpAtts[$sExtAttCode] = $aExpectedAtts[$sAttCode];
  1693. }
  1694. // Translate mainclass.extfield => remoteclassalias.remotefieldcode
  1695. $oRemoteAttDef = self::GetAttributeDef($sKeyClass, $sExtAttCode);
  1696. foreach ($oRemoteAttDef->GetSQLExpressions() as $sColID => $sRemoteAttExpr)
  1697. {
  1698. $aIntermediateTranslation[$sTargetAlias.$sColID][$sAttCode] = array($sKeyClassAlias, $sRemoteAttExpr);
  1699. }
  1700. //#@# debug - echo "<p>$sTargetAlias.$sAttCode to $sKeyClassAlias.$sRemoteAttExpr (class: $sKeyClass)</p>\n";
  1701. }
  1702. $oConditionTree = $oConditionTree->Translate($aIntermediateTranslation, false);
  1703. self::DbgTrace("External key $sKeyAttCode (class: $sKeyClass), call MakeQuery()");
  1704. $oSelectExtKey = self::MakeQuery($aSelectedClasses, $oConditionTree, $aClassAliases, $aTableAliases, $aTranslation, $oExtFilter, $aExpAtts);
  1705. $sLocalKeyField = current($oKeyAttDef->GetSQLExpressions()); // get the first column for an external key
  1706. $sExternalKeyField = self::DBGetKey($sKeyClass);
  1707. self::DbgTrace("External key $sKeyAttCode, Join on $sLocalKeyField = $sExternalKeyField");
  1708. if ($oKeyAttDef->IsNullAllowed())
  1709. {
  1710. $oSelectBase->AddLeftJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1711. }
  1712. else
  1713. {
  1714. $oSelectBase->AddInnerJoin($oSelectExtKey, $sLocalKeyField, $sExternalKeyField);
  1715. }
  1716. }
  1717. }
  1718. //MyHelpers::var_dump_html($oSelectBase->RenderSelect());
  1719. return $oSelectBase;
  1720. }
  1721. public static function GenerateUniqueAlias(&$aAliases, $sNewName, $sRealName)
  1722. {
  1723. if (!array_key_exists($sNewName, $aAliases))
  1724. {
  1725. $aAliases[$sNewName] = $sRealName;
  1726. return $sNewName;
  1727. }
  1728. for ($i = 1 ; $i < 100 ; $i++)
  1729. {
  1730. $sAnAlias = $sNewName.$i;
  1731. if (!array_key_exists($sAnAlias, $aAliases))
  1732. {
  1733. // Create that new alias
  1734. $aAliases[$sAnAlias] = $sRealName;
  1735. return $sAnAlias;
  1736. }
  1737. }
  1738. throw new CoreException('Failed to create an alias', array('aliases' => $aAliases, 'new'=>$sNewName));
  1739. }
  1740. public static function CheckDefinitions()
  1741. {
  1742. if (count(self::GetClasses()) == 0)
  1743. {
  1744. throw new CoreException("MetaModel::InitClasses() has not been called, or no class has been declared ?!?!");
  1745. }
  1746. $aErrors = array();
  1747. $aSugFix = array();
  1748. foreach (self::GetClasses() as $sClass)
  1749. {
  1750. $sNameAttCode = self::GetNameAttributeCode($sClass);
  1751. if (empty($sNameAttCode))
  1752. {
  1753. // let's try this !!!
  1754. // $aErrors[$sClass][] = "Missing value for name definition: the framework will (should...) replace it by the id";
  1755. // $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1756. }
  1757. else if(!self::IsValidAttCode($sClass, $sNameAttCode))
  1758. {
  1759. $aErrors[$sClass][] = "Unkown attribute code '".$sNameAttCode."' for the name definition";
  1760. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1761. }
  1762. foreach(self::GetReconcKeys($sClass) as $sReconcKeyAttCode)
  1763. {
  1764. if (!empty($sReconcKeyAttCode) && !self::IsValidAttCode($sClass, $sReconcKeyAttCode))
  1765. {
  1766. $aErrors[$sClass][] = "Unkown attribute code '".$sReconcKeyAttCode."' in the list of reconciliation keys";
  1767. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1768. }
  1769. }
  1770. $bHasWritableAttribute = false;
  1771. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  1772. {
  1773. // It makes no sense to check the attributes again and again in the subclasses
  1774. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  1775. if ($oAttDef->IsExternalKey())
  1776. {
  1777. if (!self::IsValidClass($oAttDef->GetTargetClass()))
  1778. {
  1779. $aErrors[$sClass][] = "Unkown class '".$oAttDef->GetTargetClass()."' for the external key '$sAttCode'";
  1780. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetClasses())."}";
  1781. }
  1782. }
  1783. elseif ($oAttDef->IsExternalField())
  1784. {
  1785. $sKeyAttCode = $oAttDef->GetKeyAttCode();
  1786. if (!self::IsValidAttCode($sClass, $sKeyAttCode) || !self::IsValidKeyAttCode($sClass, $sKeyAttCode))
  1787. {
  1788. $aErrors[$sClass][] = "Unkown key attribute code '".$sKeyAttCode."' for the external field $sAttCode";
  1789. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sClass))."}";
  1790. }
  1791. else
  1792. {
  1793. $oKeyAttDef = self::GetAttributeDef($sClass, $sKeyAttCode);
  1794. $sTargetClass = $oKeyAttDef->GetTargetClass();
  1795. $sExtAttCode = $oAttDef->GetExtAttCode();
  1796. if (!self::IsValidAttCode($sTargetClass, $sExtAttCode))
  1797. {
  1798. $aErrors[$sClass][] = "Unkown key attribute code '".$sExtAttCode."' for the external field $sAttCode";
  1799. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetKeysList($sTargetClass))."}";
  1800. }
  1801. }
  1802. }
  1803. else // standard attributes
  1804. {
  1805. // Check that the default values definition is a valid object!
  1806. $oValSetDef = $oAttDef->GetValuesDef();
  1807. if (!is_null($oValSetDef) && !$oValSetDef instanceof ValueSetDefinition)
  1808. {
  1809. $aErrors[$sClass][] = "Allowed values for attribute $sAttCode is not of the relevant type";
  1810. $aSugFix[$sClass][] = "Please set it as an instance of a ValueSetDefinition object.";
  1811. }
  1812. else
  1813. {
  1814. // Default value must be listed in the allowed values (if defined)
  1815. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  1816. if (!is_null($aAllowedValues))
  1817. {
  1818. $sDefaultValue = $oAttDef->GetDefaultValue();
  1819. if (!array_key_exists($sDefaultValue, $aAllowedValues))
  1820. {
  1821. $aErrors[$sClass][] = "Default value '".$sDefaultValue."' for attribute $sAttCode is not an allowed value";
  1822. $aSugFix[$sClass][] = "Please pickup the default value out of {'".implode(", ", array_keys($aAllowedValues))."'}";
  1823. }
  1824. }
  1825. }
  1826. }
  1827. // Check dependencies
  1828. if ($oAttDef->IsWritable())
  1829. {
  1830. $bHasWritableAttribute = true;
  1831. foreach ($oAttDef->GetPrerequisiteAttributes() as $sDependOnAttCode)
  1832. {
  1833. if (!self::IsValidAttCode($sClass, $sDependOnAttCode))
  1834. {
  1835. $aErrors[$sClass][] = "Unkown attribute code '".$sDependOnAttCode."' in the list of prerequisite attributes";
  1836. $aSugFix[$sClass][] = "Expecting a value in ".implode(", ", self::GetAttributesList($sClass));
  1837. }
  1838. }
  1839. }
  1840. }
  1841. foreach(self::GetClassFilterDefs($sClass) as $sFltCode=>$oFilterDef)
  1842. {
  1843. if (method_exists($oFilterDef, '__GetRefAttribute'))
  1844. {
  1845. $oAttDef = $oFilterDef->__GetRefAttribute();
  1846. if (!self::IsValidAttCode($sClass, $oAttDef->GetCode()))
  1847. {
  1848. $aErrors[$sClass][] = "Wrong attribute code '".$oAttDef->GetCode()."' (wrong class) for the \"basic\" filter $sFltCode";
  1849. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1850. }
  1851. }
  1852. }
  1853. // Lifecycle
  1854. //
  1855. $sStateAttCode = self::GetStateAttributeCode($sClass);
  1856. if (strlen($sStateAttCode) > 0)
  1857. {
  1858. // Lifecycle - check that the state attribute does exist as an attribute
  1859. if (!self::IsValidAttCode($sClass, $sStateAttCode))
  1860. {
  1861. $aErrors[$sClass][] = "Unkown attribute code '".$sStateAttCode."' for the state definition";
  1862. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1863. }
  1864. else
  1865. {
  1866. // Lifecycle - check that there is a value set constraint on the state attribute
  1867. $aAllowedValuesRaw = self::GetAllowedValues_att($sClass, $sStateAttCode);
  1868. $aStates = array_keys(self::EnumStates($sClass));
  1869. if (is_null($aAllowedValuesRaw))
  1870. {
  1871. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' will reflect the state of the object. It must be restricted to a set of values";
  1872. $aSugFix[$sClass][] = "Please define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')]";
  1873. }
  1874. else
  1875. {
  1876. $aAllowedValues = array_keys($aAllowedValuesRaw);
  1877. // Lifecycle - check the the state attribute allowed values are defined states
  1878. foreach($aAllowedValues as $sValue)
  1879. {
  1880. if (!in_array($sValue, $aStates))
  1881. {
  1882. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has an allowed value ($sValue) which is not a known state";
  1883. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1884. }
  1885. }
  1886. // Lifecycle - check that defined states are allowed values
  1887. foreach($aStates as $sStateValue)
  1888. {
  1889. if (!in_array($sStateValue, $aAllowedValues))
  1890. {
  1891. $aErrors[$sClass][] = "Attribute '".$sStateAttCode."' (object state) has a state ($sStateValue) which is not an allowed value";
  1892. $aSugFix[$sClass][] = "You may define its allowed_values property as [new ValueSetEnum('".implode(", ", $aStates)."')], or reconsider the list of states";
  1893. }
  1894. }
  1895. }
  1896. // Lifcycle - check that the action handlers are defined
  1897. foreach (self::EnumStates($sClass) as $sStateCode => $aStateDef)
  1898. {
  1899. foreach(self::EnumTransitions($sClass, $sStateCode) as $sStimulusCode => $aTransitionDef)
  1900. {
  1901. foreach ($aTransitionDef['actions'] as $sActionHandler)
  1902. {
  1903. if (!method_exists($sClass, $sActionHandler))
  1904. {
  1905. $aErrors[$sClass][] = "Unknown function '$sActionHandler' in transition [$sStateCode/$sStimulusCode] for state attribute '$sStateAttCode'";
  1906. $aSugFix[$sClass][] = "Specify a function which prototype is in the form [public function $sActionHandler(\$sStimulusCode){return true;}]";
  1907. }
  1908. }
  1909. }
  1910. }
  1911. }
  1912. }
  1913. if ($bHasWritableAttribute)
  1914. {
  1915. if (!self::HasTable($sClass))
  1916. {
  1917. $aErrors[$sClass][] = "No table has been defined for this class";
  1918. $aSugFix[$sClass][] = "Either define a table name or move the attributes elsewhere";
  1919. }
  1920. }
  1921. // ZList
  1922. //
  1923. foreach(self::EnumZLists() as $sListCode)
  1924. {
  1925. foreach (self::GetZListItems($sClass, $sListCode) as $sMyAttCode)
  1926. {
  1927. if (!self::IsValidAttCode($sClass, $sMyAttCode))
  1928. {
  1929. $aErrors[$sClass][] = "Unkown attribute code '".$sMyAttCode."' from ZList '$sListCode'";
  1930. $aSugFix[$sClass][] = "Expecting a value in {".implode(", ", self::GetAttributesList($sClass))."}";
  1931. }
  1932. }
  1933. }
  1934. }
  1935. if (count($aErrors) > 0)
  1936. {
  1937. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  1938. echo "<h3>Business model inconsistencies have been found</h3>\n";
  1939. // #@# later -> this is the responsibility of the caller to format the output
  1940. foreach ($aErrors as $sClass => $aMessages)
  1941. {
  1942. echo "<p>Wrong declaration for class <b>$sClass</b></p>\n";
  1943. echo "<ul class=\"treeview\">\n";
  1944. $i = 0;
  1945. foreach ($aMessages as $sMsg)
  1946. {
  1947. echo "<li>$sMsg ({$aSugFix[$sClass][$i]})</li>\n";
  1948. $i++;
  1949. }
  1950. echo "</ul>\n";
  1951. }
  1952. echo "<p>Aborting...</p>\n";
  1953. echo "</div>\n";
  1954. exit;
  1955. }
  1956. }
  1957. public static function DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes)
  1958. {
  1959. if (empty($sRepairUrl)) return;
  1960. // By design, some queries might be blank, we have to ignore them
  1961. $aCleanFixes = array();
  1962. foreach($aSQLFixes as $sSQLFix)
  1963. {
  1964. if (!empty($sSQLFix))
  1965. {
  1966. $aCleanFixes[] = $sSQLFix;
  1967. }
  1968. }
  1969. if (count($aCleanFixes) == 0) return;
  1970. echo "<form action=\"$sRepairUrl\" method=\"POST\">\n";
  1971. echo " <input type=\"hidden\" name=\"$sSQLStatementArgName\" value=\"".htmlentities(implode("##SEP##", $aCleanFixes))."\">\n";
  1972. echo " <input type=\"submit\" value=\" Apply changes (".count($aCleanFixes)." queries) \">\n";
  1973. echo "</form>\n";
  1974. }
  1975. public static function DBExists($bMustBeComplete = true)
  1976. {
  1977. // returns true if at least one table exists
  1978. //
  1979. if (!CMDBSource::IsDB(self::$m_sDBName))
  1980. {
  1981. return false;
  1982. }
  1983. CMDBSource::SelectDB(self::$m_sDBName);
  1984. $aFound = array();
  1985. $aMissing = array();
  1986. foreach (self::DBEnumTables() as $sTable => $aClasses)
  1987. {
  1988. if (CMDBSource::IsTable($sTable))
  1989. {
  1990. $aFound[] = $sTable;
  1991. }
  1992. else
  1993. {
  1994. $aMissing[] = $sTable;
  1995. }
  1996. }
  1997. if (count($aFound) == 0)
  1998. {
  1999. // no expected table has been found
  2000. return false;
  2001. }
  2002. else
  2003. {
  2004. if (count($aMissing) == 0)
  2005. {
  2006. // the database is complete (still, could be some fields missing!)
  2007. return true;
  2008. }
  2009. else
  2010. {
  2011. // not all the tables, could be an older version
  2012. if ($bMustBeComplete)
  2013. {
  2014. return false;
  2015. }
  2016. else
  2017. {
  2018. return true;
  2019. }
  2020. }
  2021. }
  2022. }
  2023. public static function DBDrop()
  2024. {
  2025. $bDropEntireDB = true;
  2026. if (!empty(self::$m_sTablePrefix))
  2027. {
  2028. // Do drop only tables corresponding to the sub-database (table prefix)
  2029. // then possibly drop the DB itself (if no table remain)
  2030. foreach (CMDBSource::EnumTables() as $sTable)
  2031. {
  2032. // perform a case insensitive test because on Windows the table names become lowercase :-(
  2033. if (strtolower(substr($sTable, 0, strlen(self::$m_sTablePrefix))) == strtolower(self::$m_sTablePrefix))
  2034. {
  2035. CMDBSource::DropTable($sTable);
  2036. }
  2037. else
  2038. {
  2039. // There is at least one table which is out of the scope of the current application
  2040. $bDropEntireDB = false;
  2041. }
  2042. }
  2043. }
  2044. if ($bDropEntireDB)
  2045. {
  2046. CMDBSource::DropDB(self::$m_sDBName);
  2047. }
  2048. }
  2049. public static function DBCreate()
  2050. {
  2051. // Note: we have to check if the DB does exist, because we may share the DB
  2052. // with other applications (in which case the DB does exist, not the tables with the given prefix)
  2053. if (!CMDBSource::IsDB(self::$m_sDBName))
  2054. {
  2055. CMDBSource::CreateDB(self::$m_sDBName);
  2056. }
  2057. self::DBCreateTables();
  2058. self::DBCreateViews();
  2059. }
  2060. protected static function DBCreateTables()
  2061. {
  2062. list($aErrors, $aSugFix) = self::DBCheckFormat();
  2063. $aSQL = array();
  2064. foreach ($aSugFix as $sClass => $aTarget)
  2065. {
  2066. foreach ($aTarget as $aQueries)
  2067. {
  2068. foreach ($aQueries as $sQuery)
  2069. {
  2070. if (!empty($sQuery))
  2071. {
  2072. //$aSQL[] = $sQuery;
  2073. // forces a refresh of cached information
  2074. CMDBSource::CreateTable($sQuery);
  2075. }
  2076. }
  2077. }
  2078. }
  2079. // does not work -how to have multiple statements in a single query?
  2080. // $sDoCreateAll = implode(" ; ", $aSQL);
  2081. }
  2082. protected static function DBCreateViews()
  2083. {
  2084. list($aErrors, $aSugFix) = self::DBCheckViews();
  2085. $aSQL = array();
  2086. foreach ($aSugFix as $sClass => $aTarget)
  2087. {
  2088. foreach ($aTarget as $aQueries)
  2089. {
  2090. foreach ($aQueries as $sQuery)
  2091. {
  2092. if (!empty($sQuery))
  2093. {
  2094. //$aSQL[] = $sQuery;
  2095. // forces a refresh of cached information
  2096. CMDBSource::CreateTable($sQuery);
  2097. }
  2098. }
  2099. }
  2100. }
  2101. }
  2102. public static function DBDump()
  2103. {
  2104. $aDataDump = array();
  2105. foreach (self::DBEnumTables() as $sTable => $aClasses)
  2106. {
  2107. $aRows = CMDBSource::DumpTable($sTable);
  2108. $aDataDump[$sTable] = $aRows;
  2109. }
  2110. return $aDataDump;
  2111. }
  2112. protected static function MakeDictEntry($sKey, $sValueFromOldSystem, $sDefaultValue, &$bNotInDico)
  2113. {
  2114. $sValue = Dict::S($sKey, 'x-no-nothing');
  2115. if ($sValue == 'x-no-nothing')
  2116. {
  2117. $bNotInDico = true;
  2118. $sValue = $sValueFromOldSystem;
  2119. if (strlen($sValue) == 0)
  2120. {
  2121. $sValue = $sDefaultValue;
  2122. }
  2123. }
  2124. return " '$sKey' => '".str_replace("'", "\\'", $sValue)."',\n";
  2125. }
  2126. public static function MakeDictionaryTemplate($sModules = '', $sOutputFilter = 'NotInDictionary')
  2127. {
  2128. $sRes = '';
  2129. $sRes .= "// Dictionnay conventions\n";
  2130. $sRes .= htmlentities("// Class:<class_name>\n");
  2131. $sRes .= htmlentities("// Class:<class_name>+\n");
  2132. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>\n");
  2133. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>+\n");
  2134. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>\n");
  2135. $sRes .= htmlentities("// Class:<class_name>/Attribute:<attribute_code>/Value:<value>+\n");
  2136. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>\n");
  2137. $sRes .= htmlentities("// Class:<class_name>/Stimulus:<stimulus_code>+\n");
  2138. $sRes .= "\n";
  2139. // Note: I did not use EnumCategories(), because a given class maybe found in several categories
  2140. // Need to invent the "module", to characterize the origins of a class
  2141. if (strlen($sModules) == 0)
  2142. {
  2143. $aModules = array('bizmodel', 'core/cmdb', 'gui' , 'application', 'addon/userrights');
  2144. }
  2145. else
  2146. {
  2147. $aModules = explode(', ', $sModules);
  2148. }
  2149. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2150. $sRes .= "// Note: The classes have been grouped by categories: ".implode(', ', $aModules)."\n";
  2151. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2152. foreach ($aModules as $sCategory)
  2153. {
  2154. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2155. $sRes .= "// Classes in '<em>$sCategory</em>'\n";
  2156. $sRes .= "//////////////////////////////////////////////////////////////////////\n";
  2157. $sRes .= "//\n";
  2158. $sRes .= "\n";
  2159. foreach (self::GetClasses($sCategory) as $sClass)
  2160. {
  2161. if (!self::HasTable($sClass)) continue;
  2162. $bNotInDico = false;
  2163. $sClassRes = "//\n";
  2164. $sClassRes .= "// Class: $sClass\n";
  2165. $sClassRes .= "//\n";
  2166. $sClassRes .= "\n";
  2167. $sClassRes .= "Dict::Add('EN US', 'English', 'English', array(\n";
  2168. $sClassRes .= self::MakeDictEntry("Class:$sClass", self::GetName_Obsolete($sClass), $sClass, $bNotInDico);
  2169. $sClassRes .= self::MakeDictEntry("Class:$sClass+", self::GetClassDescription_Obsolete($sClass), '', $bNotInDico);
  2170. foreach(self::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  2171. {
  2172. // Skip this attribute if not originaly defined in this class
  2173. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2174. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode", $oAttDef->GetLabel_Obsolete(), $sAttCode, $bNotInDico);
  2175. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode+", $oAttDef->GetDescription_Obsolete(), '', $bNotInDico);
  2176. if ($oAttDef instanceof AttributeEnum)
  2177. {
  2178. if (self::GetStateAttributeCode($sClass) == $sAttCode)
  2179. {
  2180. foreach (self::EnumStates($sClass) as $sStateCode => $aStateData)
  2181. {
  2182. if (array_key_exists('label', $aStateData))
  2183. {
  2184. $sValue = $aStateData['label'];
  2185. }
  2186. else
  2187. {
  2188. $sValue = MetaModel::GetStateLabel($sClass, $sStateCode);
  2189. }
  2190. if (array_key_exists('description', $aStateData))
  2191. {
  2192. $sValuePlus = $aStateData['description'];
  2193. }
  2194. else
  2195. {
  2196. $sValuePlus = MetaModel::GetStateDescription($sClass, $sStateCode);
  2197. }
  2198. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode", $sValue, '', $bNotInDico);
  2199. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sStateCode+", $sValuePlus, '', $bNotInDico);
  2200. }
  2201. }
  2202. else
  2203. {
  2204. foreach ($oAttDef->GetAllowedValues() as $sKey => $value)
  2205. {
  2206. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey", $value, '', $bNotInDico);
  2207. $sClassRes .= self::MakeDictEntry("Class:$sClass/Attribute:$sAttCode/Value:$sKey+", $value, '', $bNotInDico);
  2208. }
  2209. }
  2210. }
  2211. }
  2212. foreach(self::EnumStimuli($sClass) as $sStimulusCode => $oStimulus)
  2213. {
  2214. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode", $oStimulus->GetLabel_Obsolete(), '', $bNotInDico);
  2215. $sClassRes .= self::MakeDictEntry("Class:$sClass/Stimulus:$sStimulusCode+", $oStimulus->GetDescription_Obsolete(), '', $bNotInDico);
  2216. }
  2217. $sClassRes .= "));\n";
  2218. $sClassRes .= "\n";
  2219. if ($bNotInDico || ($sOutputFilter != 'NotInDictionary'))
  2220. {
  2221. $sRes .= $sClassRes;
  2222. }
  2223. }
  2224. }
  2225. return $sRes;
  2226. }
  2227. public static function DBCheckFormat()
  2228. {
  2229. $aErrors = array();
  2230. $aSugFix = array();
  2231. foreach (self::GetClasses() as $sClass)
  2232. {
  2233. if (!self::HasTable($sClass)) continue;
  2234. // Check that the table exists
  2235. //
  2236. $sTable = self::DBGetTable($sClass);
  2237. $sKeyField = self::DBGetKey($sClass);
  2238. $sAutoIncrement = (self::IsAutoIncrementKey($sClass) ? "AUTO_INCREMENT" : "");
  2239. if (!CMDBSource::IsTable($sTable))
  2240. {
  2241. $aErrors[$sClass]['*'][] = "table '$sTable' could not be found into the DB";
  2242. $aSugFix[$sClass]['*'][] = "CREATE TABLE `$sTable` (`$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY) ENGINE = innodb CHARACTER SET utf8 COLLATE utf8_unicode_ci";
  2243. }
  2244. // Check that the key field exists
  2245. //
  2246. elseif (!CMDBSource::IsField($sTable, $sKeyField))
  2247. {
  2248. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) could not be found";
  2249. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` ADD `$sKeyField` INT(11) NOT NULL $sAutoIncrement PRIMARY KEY";
  2250. }
  2251. else
  2252. {
  2253. // Check the key field properties
  2254. //
  2255. if (!CMDBSource::IsKey($sTable, $sKeyField))
  2256. {
  2257. $aErrors[$sClass]['id'][] = "key '$sKeyField' is not a key for table '$sTable'";
  2258. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable`, DROP PRIMARY KEY, ADD PRIMARY key(`$sKeyField`)";
  2259. }
  2260. if (self::IsAutoIncrementKey($sClass) && !CMDBSource::IsAutoIncrement($sTable, $sKeyField))
  2261. {
  2262. $aErrors[$sClass]['id'][] = "key '$sKeyField' (table $sTable) is not automatically incremented";
  2263. $aSugFix[$sClass]['id'][] = "ALTER TABLE `$sTable` CHANGE `$sKeyField` `$sKeyField` INT(11) NOT NULL AUTO_INCREMENT";
  2264. }
  2265. }
  2266. // Check that any defined field exists
  2267. //
  2268. $aTableInfo = CMDBSource::GetTableInfo($sTable);
  2269. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2270. {
  2271. // Skip this attribute if not originaly defined in this class
  2272. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2273. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  2274. {
  2275. $bIndexNeeded = $oAttDef->RequiresIndex();
  2276. $sFieldSpecs = $oAttDef->IsNullAllowed() ? "$sDBFieldType NULL" : "$sDBFieldType NOT NULL";
  2277. if (!CMDBSource::IsField($sTable, $sField))
  2278. {
  2279. $aErrors[$sClass][$sAttCode][] = "field '$sField' could not be found in table '$sTable'";
  2280. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD `$sField` $sFieldSpecs";
  2281. if ($bIndexNeeded)
  2282. {
  2283. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2284. }
  2285. }
  2286. else
  2287. {
  2288. // The field already exists, does it have the relevant properties?
  2289. //
  2290. $bToBeChanged = false;
  2291. if ($oAttDef->IsNullAllowed() != CMDBSource::IsNullAllowed($sTable, $sField))
  2292. {
  2293. $bToBeChanged = true;
  2294. if ($oAttDef->IsNullAllowed())
  2295. {
  2296. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could be NULL";
  2297. }
  2298. else
  2299. {
  2300. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' could NOT be NULL";
  2301. }
  2302. }
  2303. $sActualFieldType = CMDBSource::GetFieldType($sTable, $sField);
  2304. if (strcasecmp($sDBFieldType, $sActualFieldType) != 0)
  2305. {
  2306. $bToBeChanged = true;
  2307. $aErrors[$sClass][$sAttCode][] = "field '$sField' in table '$sTable' has a wrong type: found '$sActualFieldType' while expecting '$sDBFieldType'";
  2308. }
  2309. if ($bToBeChanged)
  2310. {
  2311. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` CHANGE `$sField` `$sField` $sFieldSpecs";
  2312. }
  2313. // Create indexes (external keys only... so far)
  2314. //
  2315. if ($bIndexNeeded && !CMDBSource::HasIndex($sTable, $sField))
  2316. {
  2317. $aErrors[$sClass][$sAttCode][] = "Foreign key '$sField' in table '$sTable' should have an index";
  2318. $aSugFix[$sClass][$sAttCode][] = "ALTER TABLE `$sTable` ADD INDEX (`$sField`)";
  2319. }
  2320. }
  2321. }
  2322. }
  2323. }
  2324. return array($aErrors, $aSugFix);
  2325. }
  2326. public static function DBCheckViews()
  2327. {
  2328. $aErrors = array();
  2329. $aSugFix = array();
  2330. // Reporting views (must be created after any other table)
  2331. //
  2332. foreach (self::GetClasses('bizmodel') as $sClass)
  2333. {
  2334. $sView = "view_$sClass";
  2335. if (CMDBSource::IsTable($sView))
  2336. {
  2337. // Check that the view is complete
  2338. //
  2339. $bIsComplete = true;
  2340. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2341. {
  2342. foreach($oAttDef->GetSQLExpressions() as $sSuffix => $sTrash)
  2343. {
  2344. $sCol = $sAttCode.$sSuffix;
  2345. if (!CMDBSource::IsField($sView, $sCol))
  2346. {
  2347. $bIsComplete = false;
  2348. $aErrors[$sClass][$sAttCode][] = "field '$sCol' could not be found in view '$sView'";
  2349. $aSugFix[$sClass][$sAttCode][] = "";
  2350. }
  2351. }
  2352. }
  2353. if (!$bIsComplete)
  2354. {
  2355. // Rework the view
  2356. //
  2357. $oFilter = new DBObjectSearch($sClass, '');
  2358. $sSQL = self::MakeSelectQuery($oFilter);
  2359. $aErrors[$sClass]['*'][] = "View '$sView' is currently not complete";
  2360. $aSugFix[$sClass]['*'][] = "ALTER VIEW `$sView` AS $sSQL";
  2361. }
  2362. }
  2363. else
  2364. {
  2365. // Create the view
  2366. //
  2367. $oFilter = new DBObjectSearch($sClass, '');
  2368. $sSQL = self::MakeSelectQuery($oFilter);
  2369. $aErrors[$sClass]['*'][] = "Missing view for class: $sClass";
  2370. $aSugFix[$sClass]['*'][] = "CREATE VIEW `$sView` AS $sSQL";
  2371. }
  2372. }
  2373. return array($aErrors, $aSugFix);
  2374. }
  2375. private static function DBCheckIntegrity_Check2Delete($sSelWrongRecs, $sErrorDesc, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel, $bProcessingFriends = false)
  2376. {
  2377. $sRootClass = self::GetRootClass($sClass);
  2378. $sTable = self::DBGetTable($sClass);
  2379. $sKeyField = self::DBGetKey($sClass);
  2380. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2381. {
  2382. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2383. }
  2384. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2385. if (count($aWrongRecords) == 0) return;
  2386. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2387. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2388. foreach ($aWrongRecords as $iRecordId)
  2389. {
  2390. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2391. {
  2392. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2393. {
  2394. case 'Delete':
  2395. // Already planned for a deletion
  2396. // Let's concatenate the errors description together
  2397. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2398. break;
  2399. case 'Update':
  2400. // Let's plan a deletion
  2401. break;
  2402. }
  2403. }
  2404. else
  2405. {
  2406. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2407. }
  2408. if (!$bProcessingFriends)
  2409. {
  2410. if (!array_key_exists($sTable, $aPlannedDel) || !in_array($iRecordId, $aPlannedDel[$sTable]))
  2411. {
  2412. // Something new to be deleted...
  2413. $iNewDelCount++;
  2414. }
  2415. }
  2416. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Delete';
  2417. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array();
  2418. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2419. $aPlannedDel[$sTable][] = $iRecordId;
  2420. }
  2421. // Now make sure that we would delete the records of the other tables for that class
  2422. //
  2423. if (!$bProcessingFriends)
  2424. {
  2425. $sDeleteKeys = "'".implode("', '", $aWrongRecords)."'";
  2426. foreach (self::EnumChildClasses($sRootClass, ENUM_CHILD_CLASSES_ALL) as $sFriendClass)
  2427. {
  2428. $sFriendTable = self::DBGetTable($sFriendClass);
  2429. $sFriendKey = self::DBGetKey($sFriendClass);
  2430. // skip the current table
  2431. if ($sFriendTable == $sTable) continue;
  2432. $sFindRelatedRec = "SELECT DISTINCT maintable.`$sFriendKey` AS id FROM `$sFriendTable` AS maintable WHERE maintable.`$sFriendKey` IN ($sDeleteKeys)";
  2433. self::DBCheckIntegrity_Check2Delete($sFindRelatedRec, "Cascading deletion of record in friend table `<em>$sTable</em>`", $sFriendClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel, true);
  2434. }
  2435. }
  2436. }
  2437. private static function DBCheckIntegrity_Check2Update($sSelWrongRecs, $sErrorDesc, $sColumn, $sNewValue, $sClass, &$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2438. {
  2439. $sRootClass = self::GetRootClass($sClass);
  2440. $sTable = self::DBGetTable($sClass);
  2441. $sKeyField = self::DBGetKey($sClass);
  2442. if (array_key_exists($sTable, $aPlannedDel) && count($aPlannedDel[$sTable]) > 0)
  2443. {
  2444. $sSelWrongRecs .= " AND maintable.`$sKeyField` NOT IN ('".implode("', '", $aPlannedDel[$sTable])."')";
  2445. }
  2446. $aWrongRecords = CMDBSource::QueryToCol($sSelWrongRecs, "id");
  2447. if (count($aWrongRecords) == 0) return;
  2448. if (!array_key_exists($sRootClass, $aErrorsAndFixes)) $aErrorsAndFixes[$sRootClass] = array();
  2449. if (!array_key_exists($sTable, $aErrorsAndFixes[$sRootClass])) $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2450. foreach ($aWrongRecords as $iRecordId)
  2451. {
  2452. if (array_key_exists($iRecordId, $aErrorsAndFixes[$sRootClass][$sTable]))
  2453. {
  2454. switch ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'])
  2455. {
  2456. case 'Delete':
  2457. // No need to update, the record will be deleted!
  2458. break;
  2459. case 'Update':
  2460. // Already planned for an update
  2461. // Add this new update spec to the list
  2462. $bFoundSameSpec = false;
  2463. foreach ($aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] as $aUpdateSpec)
  2464. {
  2465. if (($sColumn == $aUpdateSpec['column']) && ($sNewValue == $aUpdateSpec['newvalue']))
  2466. {
  2467. $bFoundSameSpec = true;
  2468. }
  2469. }
  2470. if (!$bFoundSameSpec)
  2471. {
  2472. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'][] = (array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2473. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] .= ', '.$sErrorDesc;
  2474. }
  2475. break;
  2476. }
  2477. }
  2478. else
  2479. {
  2480. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Reason'] = $sErrorDesc;
  2481. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action'] = 'Update';
  2482. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Action_Details'] = array(array('column' => $sColumn, 'newvalue'=>$sNewValue));
  2483. $aErrorsAndFixes[$sRootClass][$sTable][$iRecordId]['Pass'] = 123;
  2484. }
  2485. }
  2486. }
  2487. // returns the count of records found for deletion
  2488. public static function DBCheckIntegrity_SinglePass(&$aErrorsAndFixes, &$iNewDelCount, &$aPlannedDel)
  2489. {
  2490. foreach (self::GetClasses() as $sClass)
  2491. {
  2492. if (!self::HasTable($sClass)) continue;
  2493. $sRootClass = self::GetRootClass($sClass);
  2494. $sTable = self::DBGetTable($sClass);
  2495. $sKeyField = self::DBGetKey($sClass);
  2496. if (!self::IsStandaloneClass($sClass))
  2497. {
  2498. if (self::IsRootClass($sClass))
  2499. {
  2500. // Check that the final class field contains the name of a class which inherited from the current class
  2501. //
  2502. $sFinalClassField = self::DBGetClassField($sClass);
  2503. $aAllowedValues = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2504. $sAllowedValues = implode(",", CMDBSource::Quote($aAllowedValues, true));
  2505. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE `$sFinalClassField` NOT IN ($sAllowedValues)";
  2506. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "final class (field `<em>$sFinalClassField</em>`) is wrong (expected a value in {".$sAllowedValues."})", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2507. }
  2508. else
  2509. {
  2510. $sRootTable = self::DBGetTable($sRootClass);
  2511. $sRootKey = self::DBGetKey($sRootClass);
  2512. $sFinalClassField = self::DBGetClassField($sRootClass);
  2513. $aExpectedClasses = self::EnumChildClasses($sClass, ENUM_CHILD_CLASSES_ALL);
  2514. $sExpectedClasses = implode(",", CMDBSource::Quote($aExpectedClasses, true));
  2515. // Check that any record found here has its counterpart in the root table
  2516. // and which refers to a child class
  2517. //
  2518. $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";
  2519. 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);
  2520. // Check that any record found in the root table and referring to a child class
  2521. // has its counterpart here (detect orphan nodes -root or in the middle of the hierarchy)
  2522. //
  2523. $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)";
  2524. 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);
  2525. }
  2526. }
  2527. foreach(self::ListAttributeDefs($sClass) as $sAttCode=>$oAttDef)
  2528. {
  2529. // Skip this attribute if not defined in this table
  2530. if (self::$m_aAttribOrigins[$sClass][$sAttCode] != $sClass) continue;
  2531. if ($oAttDef->IsExternalKey())
  2532. {
  2533. // Check that any external field is pointing to an existing object
  2534. //
  2535. $sRemoteClass = $oAttDef->GetTargetClass();
  2536. $sRemoteTable = self::DBGetTable($sRemoteClass);
  2537. $sRemoteKey = self::DBGetKey($sRemoteClass);
  2538. $sExtKeyField = current($oAttDef->GetSQLExpressions()); // get the first column for an external key
  2539. // Note: a class/table may have an external key on itself
  2540. $sSelBase = "SELECT DISTINCT maintable.`$sKeyField` AS id, maintable.`$sExtKeyField` AS extkey FROM `$sTable` AS maintable LEFT JOIN `$sRemoteTable` ON maintable.`$sExtKeyField` = `$sRemoteTable`.`$sRemoteKey`";
  2541. $sSelWrongRecs = $sSelBase." WHERE `$sRemoteTable`.`$sRemoteKey` IS NULL";
  2542. if ($oAttDef->IsNullAllowed())
  2543. {
  2544. // Exclude the records pointing to 0/null from the errors
  2545. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2546. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2547. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2548. }
  2549. else
  2550. {
  2551. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') non existing objects", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2552. }
  2553. // Do almost the same, taking into account the records planned for deletion
  2554. if (array_key_exists($sRemoteTable, $aPlannedDel) && count($aPlannedDel[$sRemoteTable]) > 0)
  2555. {
  2556. // This could be done by the mean of a 'OR ... IN (aIgnoreRecords)
  2557. // but in that case you won't be able to track the root cause (cascading)
  2558. $sSelWrongRecs = $sSelBase." WHERE maintable.`$sExtKeyField` IN ('".implode("', '", $aPlannedDel[$sRemoteTable])."')";
  2559. if ($oAttDef->IsNullAllowed())
  2560. {
  2561. // Exclude the records pointing to 0/null from the errors
  2562. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` IS NOT NULL";
  2563. $sSelWrongRecs .= " AND maintable.`$sExtKeyField` != 0";
  2564. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sExtKeyField, 'null', $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2565. }
  2566. else
  2567. {
  2568. self::DBCheckIntegrity_Check2Delete($sSelWrongRecs, "Record pointing to (external key '<em>$sAttCode</em>') a record planned for deletion", $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2569. }
  2570. }
  2571. }
  2572. else if ($oAttDef->IsDirectField())
  2573. {
  2574. // Check that the values fit the allowed values
  2575. //
  2576. $aAllowedValues = self::GetAllowedValues_att($sClass, $sAttCode);
  2577. if (!is_null($aAllowedValues) && count($aAllowedValues) > 0)
  2578. {
  2579. $sExpectedValues = implode(",", CMDBSource::Quote(array_keys($aAllowedValues), true));
  2580. $sMyAttributeField = current($oAttDef->GetSQLExpressions()); // get the first column for the moment
  2581. $sDefaultValue = $oAttDef->GetDefaultValue();
  2582. $sSelWrongRecs = "SELECT DISTINCT maintable.`$sKeyField` AS id FROM `$sTable` AS maintable WHERE maintable.`$sMyAttributeField` NOT IN ($sExpectedValues)";
  2583. self::DBCheckIntegrity_Check2Update($sSelWrongRecs, "Record having a column ('<em>$sAttCode</em>') with an unexpected value", $sMyAttributeField, CMDBSource::Quote($sDefaultValue), $sClass, $aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2584. }
  2585. }
  2586. }
  2587. }
  2588. }
  2589. public static function DBCheckIntegrity($sRepairUrl = "", $sSQLStatementArgName = "")
  2590. {
  2591. // Records in error, and action to be taken: delete or update
  2592. // by RootClass/Table/Record
  2593. $aErrorsAndFixes = array();
  2594. // Records to be ignored in the current/next pass
  2595. // by Table = array of RecordId
  2596. $aPlannedDel = array();
  2597. // Count of errors in the next pass: no error means that we can leave...
  2598. $iErrorCount = 0;
  2599. // Limit in case of a bug in the algorythm
  2600. $iLoopCount = 0;
  2601. $iNewDelCount = 1; // startup...
  2602. while ($iNewDelCount > 0)
  2603. {
  2604. $iNewDelCount = 0;
  2605. self::DBCheckIntegrity_SinglePass($aErrorsAndFixes, $iNewDelCount, $aPlannedDel);
  2606. $iErrorCount += $iNewDelCount;
  2607. // Safety net #1 - limit the planned deletions
  2608. //
  2609. $iMaxDel = 1000;
  2610. $iPlannedDel = 0;
  2611. foreach ($aPlannedDel as $sTable => $aPlannedDelOnTable)
  2612. {
  2613. $iPlannedDel += count($aPlannedDelOnTable);
  2614. }
  2615. if ($iPlannedDel > $iMaxDel)
  2616. {
  2617. throw new CoreWarning("DB Integrity Check safety net - Exceeding the limit of $iMaxDel planned record deletion");
  2618. break;
  2619. }
  2620. // Safety net #2 - limit the iterations
  2621. //
  2622. $iLoopCount++;
  2623. $iMaxLoops = 10;
  2624. if ($iLoopCount > $iMaxLoops)
  2625. {
  2626. throw new CoreWarning("DB Integrity Check safety net - Reached the limit of $iMaxLoops loops");
  2627. break;
  2628. }
  2629. }
  2630. // Display the results
  2631. //
  2632. $iIssueCount = 0;
  2633. $aFixesDelete = array();
  2634. $aFixesUpdate = array();
  2635. foreach ($aErrorsAndFixes as $sRootClass => $aTables)
  2636. {
  2637. foreach ($aTables as $sTable => $aRecords)
  2638. {
  2639. foreach ($aRecords as $iRecord => $aError)
  2640. {
  2641. $sAction = $aError['Action'];
  2642. $sReason = $aError['Reason'];
  2643. $iPass = $aError['Pass'];
  2644. switch ($sAction)
  2645. {
  2646. case 'Delete':
  2647. $sActionDetails = "";
  2648. $aFixesDelete[$sTable][] = $iRecord;
  2649. break;
  2650. case 'Update':
  2651. $aUpdateDesc = array();
  2652. foreach($aError['Action_Details'] as $aUpdateSpec)
  2653. {
  2654. $aUpdateDesc[] = $aUpdateSpec['column']." -&gt; ".$aUpdateSpec['newvalue'];
  2655. $aFixesUpdate[$sTable][$aUpdateSpec['column']][$aUpdateSpec['newvalue']][] = $iRecord;
  2656. }
  2657. $sActionDetails = "Set ".implode(", ", $aUpdateDesc);
  2658. break;
  2659. default:
  2660. $sActionDetails = "bug: unknown action '$sAction'";
  2661. }
  2662. $aIssues[] = "$sRootClass / $sTable / $iRecord / $sReason / $sAction / $sActionDetails";
  2663. $iIssueCount++;
  2664. }
  2665. }
  2666. }
  2667. if ($iIssueCount > 0)
  2668. {
  2669. // Build the queries to fix in the database
  2670. //
  2671. // First step, be able to get class data out of the table name
  2672. // Could be optimized, because we've made the job earlier... but few benefits, so...
  2673. $aTable2ClassProp = array();
  2674. foreach (self::GetClasses() as $sClass)
  2675. {
  2676. if (!self::HasTable($sClass)) continue;
  2677. $sRootClass = self::GetRootClass($sClass);
  2678. $sTable = self::DBGetTable($sClass);
  2679. $sKeyField = self::DBGetKey($sClass);
  2680. $aErrorsAndFixes[$sRootClass][$sTable] = array();
  2681. $aTable2ClassProp[$sTable] = array('rootclass'=>$sRootClass, 'class'=>$sClass, 'keyfield'=>$sKeyField);
  2682. }
  2683. // Second step, build a flat list of SQL queries
  2684. $aSQLFixes = array();
  2685. $iPlannedUpdate = 0;
  2686. foreach ($aFixesUpdate as $sTable => $aColumns)
  2687. {
  2688. foreach ($aColumns as $sColumn => $aNewValues)
  2689. {
  2690. foreach ($aNewValues as $sNewValue => $aRecords)
  2691. {
  2692. $iPlannedUpdate += count($aRecords);
  2693. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2694. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2695. $aSQLFixes[] = "UPDATE `$sTable` SET `$sColumn` = $sNewValue WHERE `$sKeyField` IN ($sWrongRecords)";
  2696. }
  2697. }
  2698. }
  2699. $iPlannedDel = 0;
  2700. foreach ($aFixesDelete as $sTable => $aRecords)
  2701. {
  2702. $iPlannedDel += count($aRecords);
  2703. $sWrongRecords = "'".implode("', '", $aRecords)."'";
  2704. $sKeyField = $aTable2ClassProp[$sTable]['keyfield'];
  2705. $aSQLFixes[] = "DELETE FROM `$sTable` WHERE `$sKeyField` IN ($sWrongRecords)";
  2706. }
  2707. // Report the results
  2708. //
  2709. echo "<div style=\"width:100%;padding:10px;background:#FFAAAA;display:;\">";
  2710. echo "<h3>Database corruption error(s): $iErrorCount issues have been encountered. $iPlannedDel records will be deleted, $iPlannedUpdate records will be updated:</h3>\n";
  2711. // #@# later -> this is the responsibility of the caller to format the output
  2712. echo "<ul class=\"treeview\">\n";
  2713. foreach ($aIssues as $sIssueDesc)
  2714. {
  2715. echo "<li>$sIssueDesc</li>\n";
  2716. }
  2717. echo "</ul>\n";
  2718. self::DBShowApplyForm($sRepairUrl, $sSQLStatementArgName, $aSQLFixes);
  2719. echo "<p>Aborting...</p>\n";
  2720. echo "</div>\n";
  2721. exit;
  2722. }
  2723. }
  2724. public static function Startup($sConfigFile, $bAllowMissingDB = false)
  2725. {
  2726. self::LoadConfig($sConfigFile);
  2727. if (self::DBExists())
  2728. {
  2729. CMDBSource::SelectDB(self::$m_sDBName);
  2730. // Some of the init could not be done earlier (requiring classes to be declared and DB to be accessible)
  2731. self::InitPlugins();
  2732. }
  2733. else
  2734. {
  2735. if (!$bAllowMissingDB)
  2736. {
  2737. throw new CoreException('Database not found, check your configuration file', array('config_file'=>$sConfigFile, 'db_name'=>self::$m_sDBName));
  2738. }
  2739. }
  2740. }
  2741. public static function LoadConfig($sConfigFile)
  2742. {
  2743. $oConfig = new Config($sConfigFile);
  2744. // Set log ASAP
  2745. if ($oConfig->GetLogGlobal())
  2746. {
  2747. if ($oConfig->GetLogIssue())
  2748. {
  2749. self::$m_bLogIssue = true;
  2750. IssueLog::Enable('../error.log');
  2751. }
  2752. self::$m_bLogNotification = $oConfig->GetLogNotification();
  2753. self::$m_bLogWebService = $oConfig->GetLogWebService();
  2754. }
  2755. else
  2756. {
  2757. self::$m_bLogIssue = false;
  2758. self::$m_bLogNotification = false;
  2759. self::$m_bLogWebService = false;
  2760. }
  2761. // Note: load the dictionary as soon as possible, because it might be
  2762. // needed when some error occur
  2763. foreach ($oConfig->GetDictionaries() as $sModule => $sToInclude)
  2764. {
  2765. self::Plugin($sConfigFile, 'dictionaries', $sToInclude);
  2766. }
  2767. // Set the language... after the dictionaries have been loaded!
  2768. Dict::SetDefaultLanguage($oConfig->GetDefaultLanguage());
  2769. foreach ($oConfig->GetAppModules() as $sModule => $sToInclude)
  2770. {
  2771. self::Plugin($sConfigFile, 'application', $sToInclude);
  2772. }
  2773. foreach ($oConfig->GetDataModels() as $sModule => $sToInclude)
  2774. {
  2775. self::Plugin($sConfigFile, 'business', $sToInclude);
  2776. }
  2777. foreach ($oConfig->GetAddons() as $sModule => $sToInclude)
  2778. {
  2779. self::Plugin($sConfigFile, 'addons', $sToInclude);
  2780. }
  2781. $sServer = $oConfig->GetDBHost();
  2782. $sUser = $oConfig->GetDBUser();
  2783. $sPwd = $oConfig->GetDBPwd();
  2784. $sSource = $oConfig->GetDBName();
  2785. $sTablePrefix = $oConfig->GetDBSubname();
  2786. // The include have been included, let's browse the existing classes and
  2787. // develop some data based on the proposed model
  2788. self::InitClasses($sTablePrefix);
  2789. self::$m_sDBName = $sSource;
  2790. self::$m_sTablePrefix = $sTablePrefix;
  2791. CMDBSource::Init($sServer, $sUser, $sPwd); // do not select the DB (could not exist)
  2792. }
  2793. protected static $m_aPlugins = array();
  2794. public static function RegisterPlugin($sType, $sName, $aInitCallSpec = array())
  2795. {
  2796. self::$m_aPlugins[$sName] = array(
  2797. 'type' => $sType,
  2798. 'init' => $aInitCallSpec,
  2799. );
  2800. }
  2801. protected static function Plugin($sConfigFile, $sModuleType, $sToInclude)
  2802. {
  2803. if (!file_exists($sToInclude))
  2804. {
  2805. throw new CoreException('Wrong filename in configuration file', array('file' => $sConfigFile, 'module' => $sModuleType, 'filename' => $sToInclude));
  2806. }
  2807. require_once($sToInclude);
  2808. }
  2809. protected static function InitPlugins()
  2810. {
  2811. foreach(self::$m_aPlugins as $sName => $aData)
  2812. {
  2813. $aCallSpec = @$aData['init'];
  2814. if (count($aCallSpec) == 2)
  2815. {
  2816. if (!is_callable($aCallSpec))
  2817. {
  2818. throw new CoreException('Wrong declaration in plugin', array('plugin' => $aData['name'], 'type' => $aData['type'], 'class' => $aData['class'], 'init' => $aData['init']));
  2819. }
  2820. call_user_func($aCallSpec);
  2821. }
  2822. }
  2823. }
  2824. // Building an object
  2825. //
  2826. //
  2827. private static $aQueryCacheGetObject = array();
  2828. private static $aQueryCacheGetObjectHits = array();
  2829. public static function GetQueryCacheStatus()
  2830. {
  2831. $aRes = array();
  2832. $iTotalHits = 0;
  2833. foreach(self::$aQueryCacheGetObjectHits as $sClass => $iHits)
  2834. {
  2835. $aRes[] = "$sClass: $iHits";
  2836. $iTotalHits += $iHits;
  2837. }
  2838. return $iTotalHits.' ('.implode(', ', $aRes).')';
  2839. }
  2840. public static function MakeSingleRow($sClass, $iKey, $bMustBeFound = true)
  2841. {
  2842. if (!array_key_exists($sClass, self::$aQueryCacheGetObject))
  2843. {
  2844. // NOTE: Quick and VERY dirty caching mechanism which relies on
  2845. // the fact that the string '987654321' will never appear in the
  2846. // standard query
  2847. // This will be replaced for sure with a prepared statement
  2848. // or a view... next optimization to come!
  2849. $oFilter = new DBObjectSearch($sClass);
  2850. $oFilter->AddCondition('id', 987654321, '=');
  2851. $sSQL = self::MakeSelectQuery($oFilter);
  2852. self::$aQueryCacheGetObject[$sClass] = $sSQL;
  2853. self::$aQueryCacheGetObjectHits[$sClass] = 0;
  2854. }
  2855. else
  2856. {
  2857. $sSQL = self::$aQueryCacheGetObject[$sClass];
  2858. self::$aQueryCacheGetObjectHits[$sClass] += 1;
  2859. // echo " -load $sClass/$iKey- ".self::$aQueryCacheGetObjectHits[$sClass]."<br/>\n";
  2860. }
  2861. $sSQL = str_replace('987654321', CMDBSource::Quote($iKey), $sSQL);
  2862. $res = CMDBSource::Query($sSQL);
  2863. $aRow = CMDBSource::FetchArray($res);
  2864. CMDBSource::FreeResult($res);
  2865. if ($bMustBeFound && empty($aRow))
  2866. {
  2867. throw new CoreException("No result for the single row query: '$sSQL'");
  2868. }
  2869. return $aRow;
  2870. }
  2871. public static function GetObjectByRow($sClass, $aRow, $sClassAlias = '')
  2872. {
  2873. self::_check_subclass($sClass);
  2874. if (strlen($sClassAlias) == 0)
  2875. {
  2876. $sClassAlias = $sClass;
  2877. }
  2878. // Compound objects: if available, get the final object class
  2879. //
  2880. if (!array_key_exists($sClassAlias."finalclass", $aRow))
  2881. {
  2882. // Either this is a bug (forgot to specify a root class with a finalclass field
  2883. // Or this is the expected behavior, because the object is not made of several tables
  2884. }
  2885. elseif (empty($aRow[$sClassAlias."finalclass"]))
  2886. {
  2887. // The data is missing in the DB
  2888. // @#@ possible improvement: check that the class is valid !
  2889. $sRootClass = self::GetRootClass($sClass);
  2890. $sFinalClassField = self::DBGetClassField($sRootClass);
  2891. throw new CoreException("Empty class name for object $sClass::{$aRow["id"]} (root class '$sRootClass', field '{$sFinalClassField}' is empty)");
  2892. }
  2893. else
  2894. {
  2895. // do the job for the real target class
  2896. $sClass = $aRow[$sClassAlias."finalclass"];
  2897. }
  2898. return new $sClass($aRow, $sClassAlias);
  2899. }
  2900. public static function GetObject($sClass, $iKey, $bMustBeFound = true)
  2901. {
  2902. self::_check_subclass($sClass);
  2903. $aRow = self::MakeSingleRow($sClass, $iKey, $bMustBeFound);
  2904. if (empty($aRow))
  2905. {
  2906. return null;
  2907. }
  2908. return self::GetObjectByRow($sClass, $aRow);
  2909. }
  2910. public static function GetHyperLink($sTargetClass, $iKey)
  2911. {
  2912. if ($iKey < 0)
  2913. {
  2914. return "$sTargetClass: $iKey (invalid value)";
  2915. }
  2916. $oObj = self::GetObject($sTargetClass, $iKey, false);
  2917. if (is_null($oObj))
  2918. {
  2919. return "$sTargetClass: $iKey (not found)";
  2920. }
  2921. return $oObj->GetHyperLink();
  2922. }
  2923. public static function NewObject($sClass)
  2924. {
  2925. self::_check_subclass($sClass);
  2926. return new $sClass();
  2927. }
  2928. public static function GetNextKey($sClass)
  2929. {
  2930. $sRootClass = MetaModel::GetRootClass($sClass);
  2931. $sRootTable = MetaModel::DBGetTable($sRootClass);
  2932. $iNextKey = CMDBSource::GetNextInsertId($sRootTable);
  2933. return $iNextKey;
  2934. }
  2935. public static function BulkDelete(DBObjectSearch $oFilter)
  2936. {
  2937. $sSQL = self::MakeDeleteQuery($oFilter);
  2938. CMDBSource::Query($sSQL);
  2939. }
  2940. public static function BulkUpdate(DBObjectSearch $oFilter, array $aValues)
  2941. {
  2942. // $aValues is an array of $sAttCode => $value
  2943. $sSQL = self::MakeUpdateQuery($oFilter, $aValues);
  2944. CMDBSource::Query($sSQL);
  2945. }
  2946. // Links
  2947. //
  2948. //
  2949. public static function EnumReferencedClasses($sClass)
  2950. {
  2951. self::_check_subclass($sClass);
  2952. // 1-N links (referenced by my class), returns an array of sAttCode=>sClass
  2953. $aResult = array();
  2954. foreach(self::$m_aAttribDefs[$sClass] as $sAttCode=>$oAttDef)
  2955. {
  2956. if ($oAttDef->IsExternalKey())
  2957. {
  2958. $aResult[$sAttCode] = $oAttDef->GetTargetClass();
  2959. }
  2960. }
  2961. return $aResult;
  2962. }
  2963. public static function EnumReferencingClasses($sClass, $bSkipLinkingClasses = false, $bInnerJoinsOnly = false)
  2964. {
  2965. self::_check_subclass($sClass);
  2966. if ($bSkipLinkingClasses)
  2967. {
  2968. $aLinksClasses = self::EnumLinksClasses();
  2969. }
  2970. // 1-N links (referencing my class), array of sClass => array of sAttcode
  2971. $aResult = array();
  2972. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2973. {
  2974. if ($bSkipLinkingClasses && in_array($sSomeClass, $aLinksClasses)) continue;
  2975. $aExtKeys = array();
  2976. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  2977. {
  2978. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  2979. if ($oAttDef->IsExternalKey() && (self::IsParentClass($oAttDef->GetTargetClass(), $sClass)))
  2980. {
  2981. if ($bInnerJoinsOnly && $oAttDef->IsNullAllowed()) continue;
  2982. // Ok, I want this one
  2983. $aExtKeys[$sAttCode] = $oAttDef;
  2984. }
  2985. }
  2986. if (count($aExtKeys) != 0)
  2987. {
  2988. $aResult[$sSomeClass] = $aExtKeys;
  2989. }
  2990. }
  2991. return $aResult;
  2992. }
  2993. public static function EnumLinksClasses()
  2994. {
  2995. // Returns a flat array of classes having at least two external keys
  2996. $aResult = array();
  2997. foreach (self::$m_aAttribDefs as $sSomeClass=>$aClassAttributes)
  2998. {
  2999. $iExtKeyCount = 0;
  3000. foreach ($aClassAttributes as $sAttCode=>$oAttDef)
  3001. {
  3002. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3003. if ($oAttDef->IsExternalKey())
  3004. {
  3005. $iExtKeyCount++;
  3006. }
  3007. }
  3008. if ($iExtKeyCount >= 2)
  3009. {
  3010. $aResult[] = $sSomeClass;
  3011. }
  3012. }
  3013. return $aResult;
  3014. }
  3015. public static function EnumLinkingClasses($sClass = "")
  3016. {
  3017. // N-N links, array of sLinkClass => (array of sAttCode=>sClass)
  3018. $aResult = array();
  3019. foreach (self::EnumLinksClasses() as $sSomeClass)
  3020. {
  3021. $aTargets = array();
  3022. $bFoundClass = false;
  3023. foreach (self::ListAttributeDefs($sSomeClass) as $sAttCode=>$oAttDef)
  3024. {
  3025. if (self::$m_aAttribOrigins[$sSomeClass][$sAttCode] != $sSomeClass) continue;
  3026. if ($oAttDef->IsExternalKey())
  3027. {
  3028. $sRemoteClass = $oAttDef->GetTargetClass();
  3029. if (empty($sClass))
  3030. {
  3031. $aTargets[$sAttCode] = $sRemoteClass;
  3032. }
  3033. elseif ($sClass == $sRemoteClass)
  3034. {
  3035. $bFoundClass = true;
  3036. }
  3037. else
  3038. {
  3039. $aTargets[$sAttCode] = $sRemoteClass;
  3040. }
  3041. }
  3042. }
  3043. if (empty($sClass) || $bFoundClass)
  3044. {
  3045. $aResult[$sSomeClass] = $aTargets;
  3046. }
  3047. }
  3048. return $aResult;
  3049. }
  3050. public static function GetLinkLabel($sLinkClass, $sAttCode)
  3051. {
  3052. self::_check_subclass($sLinkClass);
  3053. // e.g. "supported by" (later: $this->GetLinkLabel(), computed on link data!)
  3054. return self::GetLabel($sLinkClass, $sAttCode);
  3055. }
  3056. /**
  3057. * Replaces all the parameters by the values passed in the hash array
  3058. */
  3059. static public function ApplyParams($aInput, $aParams)
  3060. {
  3061. $aSearches = array();
  3062. $aReplacements = array();
  3063. foreach($aParams as $sSearch => $sReplace)
  3064. {
  3065. $aSearches[] = '$'.$sSearch.'$';
  3066. $aReplacements[] = $sReplace;
  3067. }
  3068. return str_replace($aSearches, $aReplacements, $aInput);
  3069. }
  3070. } // class MetaModel
  3071. // Standard attribute lists
  3072. MetaModel::RegisterZList("noneditable", array("description"=>"non editable fields", "type"=>"attributes"));
  3073. MetaModel::RegisterZList("details", array("description"=>"All attributes to be displayed for the 'details' of an object", "type"=>"attributes"));
  3074. MetaModel::RegisterZList("list", array("description"=>"All attributes to be displayed for a list of objects", "type"=>"attributes"));
  3075. MetaModel::RegisterZList("preview", array("description"=>"All attributes visible in preview mode", "type"=>"attributes"));
  3076. MetaModel::RegisterZList("standard_search", array("description"=>"List of criteria for the standard search", "type"=>"filters"));
  3077. MetaModel::RegisterZList("advanced_search", array("description"=>"List of criteria for the advanced search", "type"=>"filters"));
  3078. ?>