metamodel.class.php 167 KB

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