metamodel.class.php 175 KB

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