metamodel.class.php 131 KB

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