metamodel.class.php 167 KB

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