metamodel.class.php 173 KB

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