metamodel.class.php 120 KB

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