--- lib.php	2009-10-16 18:10:01.000000000 +0200
+++ lib.php.my	2009-10-16 16:14:59.000000000 +0200
@@ -23,8 +23,9 @@
 define('MOD_CLASS_ACTIVITY', 0);
 define('MOD_CLASS_RESOURCE', 1);
 
-if (!defined('MAX_MODINFO_CACHE_SIZE')) { 
-    define('MAX_MODINFO_CACHE_SIZE', 10);
+if (!defined('MAX_MODINFO_CACHE_SIZE')) {
+     // define('MAX_MODINFO_CACHE_SIZE', 10); // moodle default
+     define('MAX_MODINFO_CACHE_SIZE', 250); // should be at least 20
 }
 
 function make_log_url($module, $url) {
@@ -1059,9 +1060,14 @@
     global $CFG, $USER;
 
     static $cache = array();
+    // use static variable instead of count(), which is less expensive
+    static $cachecount = 0;
+    static $cache_hit = array();
 
     if ($course === 'reset') {
         $cache = array();
+        $cache_hit = array();
+        $cachecount = 0;
         $nothing = null;
         return $nothing; // we must return some reference
     }
@@ -1070,10 +1076,34 @@
         $userid = $USER->id;
     }
 
-    if (array_key_exists($course->id, $cache) and $cache[$course->id]->userid == $userid) {
+    if ( isset($cache[$course->id]) and $cache[$course->id]->userid == $userid) {
         return $cache[$course->id];
     }
 
+    // Ensure cache does not use too much RAM
+    // Cache
+    if ($cachecount >= MAX_MODINFO_CACHE_SIZE) {
+      // select some more, just in case we found one with a cache hit
+      $rand_keys = array_rand($cache, (MAX_MODINFO_CACHE_SIZE*0.4)); 
+       reset($rand_keys);
+       while ((list(,$rand) = each($rand_keys)) && ($cachecount > (MAX_MODINFO_CACHE_SIZE*0.8)) ){ // 80 %
+          if (!isset($cache_hit[$rand])){
+              unset($cache[$rand]);
+              $cachecount--;
+           }
+        }
+
+        // if we still need more space, remove those wich already had a cache hit
+        while ( $cachecount > (MAX_MODINFO_CACHE_SIZE*0.8)){ // 80 %
+            end($cache_hit);
+            $key = key($cache_hit);
+            unset($cache[$key]);
+            unset($cache_hit[$key]);
+            $cachecount--;
+        }
+    }
+    // End Cache
+
     if (empty($course->modinfo)) {
         // no modinfo yet - load it
         rebuild_course_cache($course->id);
@@ -1178,15 +1208,13 @@
         unset($cm);
     }
 
-    unset($cache[$course->id]); // prevent potential reference problems when switching users
+    if ( isset($cache[$course->id]) ){ 
+        unset($cache[$course->id]); // prevent potential reference problems when switching users
+        $cachecount--;
+    }
     $cache[$course->id] = $modinfo;
+    $cachecount++;
 
-    // Ensure cache does not use too much RAM
-    if (count($cache) > MAX_MODINFO_CACHE_SIZE) {
-        reset($cache);
-        $key = key($cache);
-        unset($cache[$key]);
-    }
 
     return $cache[$course->id];
 }
