metamodel.class.php 141 KB

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