metamodel.class.php 115 KB

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