metamodel.class.php 174 KB

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