metamodel.class.php 179 KB

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