metamodel.class.php 110 KB

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