metamodel.class.php 158 KB

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