metamodel.class.php 116 KB

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