metamodel.class.php 127 KB

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