metamodel.class.php 170 KB

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