metamodel.class.php 127 KB

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