function tearDown() { SimpleORMap::expireTableScheme(); Config::set(null); StudipCacheFactory::setConfig(null); $GLOBALS['CACHING_ENABLE'] = false; }
/** * Wrapper around the actual #_performRequest memoizing its * results to prevent calling Google on each invocation. */ private function performRequest($url, $shorten) { $cache = \StudipCacheFactory::getCache(); $cache_key = 'cliqr/google/' . md5($url) . '/' . (int) $shorten; $result = unserialize($cache->read($cache_key)); if ($result === false) { $result = $this->_performRequest($url, $shorten); $cache->write($cache_key, serialize($result)); } return $result; }
private static function parseAndCacheFile($path) { $cache = \StudipCacheFactory::getCache(); $parsed = unserialize($cache->read('squeeze/' . $path)); if (!$parsed) { $parsed = self::parseFile($path); # write to cache and expire in 10 seconds $cache->write('squeeze/' . $path, serialize($parsed), 10); } return $parsed; }
/** * Searches on remote hosts for the text. * @param $text * @param bool|false $tag */ protected static function fetchRemoteSearch($text, $tag = false) { $cache_name = "Lernmarktplatz_remote_searched_for_" . md5($text) . "_" . ($tag ? 1 : 0); $already_searched = (bool) StudipCacheFactory::getCache()->read($cache_name); if (!$already_searched) { $host = LernmarktplatzHost::findOneBySQL("index_server = '1' AND allowed_as_index_server = '1' ORDER BY RAND()"); if ($host && !$host->isMe()) { $host->fetchRemoteSearch($text, $tag); } StudipCacheFactory::getCache()->read($cache_name, "1", 60); } }
private static function get_kings() { if (self::$kings === null) { $cache = StudipCacheFactory::getCache(); # read cache (unserializing a cache miss - FALSE - does not matter) $kings = unserialize($cache->read(self::CACHE_KEY)); # cache miss, retrieve from database if ($kings === FALSE) { $kings = self::get_kings_uncached(); # write to cache with an expiry time of 24 hours $cache->write(self::CACHE_KEY, serialize($kings), 86400); } self::$kings = $kings; } return self::$kings; }
/** * Retrieves the score for the current user * * @return integer the score * */ static function GetMyScore($user_or_id = null) { $user = $user_or_id ? User::toObject($user_or_id) : User::findCurrent(); $cache = StudipCacheFactory::getCache(); if ($cache->read("user_score_of_".$user->id)) { return $cache->read("user_score_of_".$user->id); } //Behold! The all new mighty score algorithm! //Step 1: Select all activities as mkdate-timestamps. //Step 2: Group these activities to timeslots of halfhours // with COUNT(*) as a weigh of the timeslot. //Step 3: Calculate the measurement of the timeslot from the weigh of it. // This makes the first activity count fully, the second // almost half and so on. We use log_n to make huge amounts of // activities to not count so much. //Step 4: Calculate a single score for each timeslot depending on the // measurement and the mkdate-timestamp. Use arctan as the function // here so that older activities tend to zero. //Step 5: Sum all scores from all timeslots together. $sql = " SELECT round(SUM((-atan(measurement / " . round(31556926 / self::MEASURING_STEP) . ") / PI() + 0.5) * 200)) as score FROM ( SELECT ((unix_timestamp() / " . self::MEASURING_STEP . ") - timeslot) / (LN(weigh) + 1) AS measurement FROM ( SELECT (round(mkdate / " . self::MEASURING_STEP . ")) as timeslot, COUNT(*) AS weigh FROM ( " . self::createTimestampQuery() . " ) as mkdates GROUP BY timeslot ) as measurements ) as dates "; $stmt = DBManager::get()->prepare($sql); $stmt->execute(array(':user' => $user->id)); $score = $stmt->fetchColumn(); if ($user->score && $user->score != $score) { $user->score = $score; $user->store(); } $cache->write("user_score_of_".$user->id, $score, 60 * 5); return $score; }
/** * Returns all valid values for a certain criterion type. * * @param string $type Name of the criterion type * @return array Associative array containing the values as keys and * descriptive names as values */ public static function getValuesForType($type) { if (!array_key_exists($type, self::$types)) { throw new Exception('[UserLookup] Unknown type "' . $type . '"'); } if (self::USE_CACHE) { $cache = StudipCacheFactory::getCache(); $cache_key = 'UserLookup/' . $type . '/values'; $cached_values = $cache->read($cache_key); if ($cached_values) { return unserialize($cached_values); } } $values = call_user_func(self::$types[$type]['values']); if (self::USE_CACHE) { $cache->write($cache_key, serialize($values), self::CACHE_DURATION); } return $values; }
protected function getToplistEntries($sem_status) { $sql_where_query_seminare = " WHERE 1 "; $parameters = array(); if (!$GLOBALS['perm']->have_perm(get_config('SEM_VISIBILITY_PERM'))) { $sql_where_query_seminare .= " AND seminare.visible = 1 "; } if ($_SESSION['sem_portal']['bereich'] != 'all' && count($sem_status)) { $sql_where_query_seminare .= " AND seminare.status IN (?) "; $parameters[] = $sem_status; } switch ($_SESSION['sem_portal']["toplist"]) { case 4: default: $query = "SELECT seminar_id, name, mkdate AS count\n FROM seminare\n {$sql_where_query_seminare}\n ORDER BY mkdate DESC\n LIMIT 5"; $statement = DBManager::get()->prepare($query); $statement->execute($parameters); $top_list = $statement->fetchAll(PDO::FETCH_ASSOC); //$toplist = $this->getToplist(_('neueste Veranstaltungen'), $query, 'date', $parameters); break; case 1: $query = "SELECT seminare.seminar_id, seminare.name, COUNT(seminare.seminar_id) AS count\n FROM seminare\n LEFT JOIN seminar_user USING (seminar_id)\n {$sql_where_query_seminare}\n GROUP BY seminare.seminar_id\n ORDER BY count DESC\n LIMIT 5"; $statement = DBManager::get()->prepare($query); $statement->execute($parameters); $top_list = $statement->fetchAll(PDO::FETCH_ASSOC); //$toplist = $this->getToplist(_('Teilnehmeranzahl'), $query, 'count', $parameters); break; case 2: $query = "SELECT dokumente.seminar_id, seminare.name, COUNT(dokumente.seminar_id) AS count\n FROM seminare\n INNER JOIN dokumente USING (seminar_id)\n {$sql_where_query_seminare}\n GROUP BY dokumente.seminar_id\n ORDER BY count DESC\n LIMIT 5"; $statement = DBManager::get()->prepare($query); $statement->execute($parameters); $top_list = $statement->fetchAll(PDO::FETCH_ASSOC); //$toplist = $this->getToplist(_('die meisten Materialien'), $query, 'count', $parameters); break; case 3: $cache = StudipCacheFactory::getCache(); $hash = '/sem_portal/most_active'; $top_list = unserialize($cache->read($hash)); if (!$top_list) { // get TopTen of seminars from all ForumModules and add up the // count for seminars with more than one active ForumModule // to get a combined toplist $seminars = array(); foreach (PluginEngine::getPlugins('ForumModule') as $plugin) { $new_seminars = $plugin->getTopTenSeminars(); foreach ($new_seminars as $sem) { if (!isset($seminars[$sem['seminar_id']])) { $seminars[$sem['seminar_id']] = $sem; $seminars[$sem['seminar_id']]['name'] = $seminars[$sem['seminar_id']]['display']; } else { $seminars[$sem['seminar_id']]['count'] += $sem['count']; } } } // sort the seminars by the number of combined postings usort($seminars, function ($a, $b) { if ($a['count'] == $b['count']) { return 0; } return $a['count'] > $b['count'] ? -1 : 1; }); $top_list = $seminars; // use only the first five seminars $top_list = array_slice($top_list, 0, 5); $cache->write($hash, serialize($top_list), 5 * 60); } break; } return $top_list; }
/** * get the number of currently online users * * @param int $active_time filter: the time in minutes until last life-sign * * @return int */ function get_users_online_count($active_time = 5) { $cache = StudipCacheFactory::getCache(); $online_count = $cache->read('online_count'); if ($online_count === false) { $query = "SELECT COUNT(*) FROM user_online\n WHERE last_lifesign > ?"; $statement = DBManager::get()->prepare($query); try { $statement->execute(array(time() - $active_time * 60)); } catch (PDOException $e) { require_once 'lib/migrations/db_schema_version.php'; $version = new DBSchemaVersion('studip'); if ($version->get() < 98) { Log::ALERT('get_users_online_count() failed. Check migration no. 98!'); } else { throw $e; } } $online_count = $statement->fetchColumn(); $cache->write('online_count', $online_count, 180); } if ($GLOBALS['user']->id && $GLOBALS['user']->id != 'nobody') { --$online_count; } return $online_count > 0 ? $online_count : 0; }
function store() { $cache = StudipCacheFactory::getCache(); $cache->expire('course/undecorated_data/' . $this->range_id); $this->chdate = time(); if ($this->ex_termin) { $this->killAssign(); $this->killIssue(); } // date_typ = 0 defaults to TERMIN_TYP[1] because there never exists one with zero if (!$this->date_typ) { $this->date_typ = 1; } if ($this->orig_ex != $this->ex_termin) { SingleDateDB::deleteSingleDate($this->termin_id, $this->orig_ex); } return SingleDateDB::storeSingleDate($this); }
function indicator($key) { $cache = StudipCacheFactory::getCache(); if ($found_in_cache = $cache->read(__METHOD__ . $key)) { return $found_in_cache; } $template = $this->template_factory->open('indicator'); $indicator['seminar_all'] = array("count" => array('count_table_rows', 'seminare'), "title" => _("Aktive Veranstaltungen"), "detail" => _("alle Veranstaltungen, die nicht archiviert wurden")); $indicator['seminar_archived'] = array("count" => array('count_table_rows', 'archiv'), "title" => _("Archivierte Veranstaltungen"), "detail" => _("alle Veranstaltungen, die archiviert wurden")); $indicator['institute_secondlevel_all'] = array("query" => "SELECT COUNT(*) FROM Institute WHERE Institut_id != fakultaets_id", "title" => _("beteiligte Einrichtungen"), "detail" => _("alle Einrichtungen außer den Fakultäten")); $indicator['institute_firstlevel_all'] = array("query" => "SELECT COUNT(*) FROM Institute WHERE Institut_id = fakultaets_id", "title" => _("beteiligte Fakultäten"), "detail" => _("alle Fakultäten")); $indicator['user_admin'] = array("query" => "SELECT COUNT(*) FROM auth_user_md5 WHERE perms='admin'", "title" => _("registrierte Administratoren"), "detail" => ""); $indicator['user_dozent'] = array("query" => "SELECT COUNT(*) FROM auth_user_md5 WHERE perms='dozent'", "title" => _("registrierte Dozenten"), "detail" => ""); $indicator['user_tutor'] = array("query" => "SELECT COUNT(*) FROM auth_user_md5 WHERE perms='tutor'", "title" => _("registrierte Tutoren"), "detail" => ""); $indicator['user_autor'] = array("query" => "SELECT COUNT(*) FROM auth_user_md5 WHERE perms='autor'", "title" => _("registrierte Autoren"), "detail" => ""); $indicator['document'] = array("query" => "SELECT COUNT(*) FROM dokumente WHERE url = ''", "title" => _("Dokumente"), "detail" => ""); $indicator['link'] = array("query" => "SELECT COUNT(*) FROM dokumente WHERE url != ''", "title" => _("verlinkte Dateien"), "detail" => ""); $indicator['litlist'] = array("count" => array('count_table_rows', 'lit_list'), "title" => _("Literaturlisten"), "detail" => "", "constraint" => get_config('LITERATURE_ENABLE')); $indicator['termin'] = array("count" => array('count_table_rows', 'termine'), "title" => _("Termine"), "detail" => ""); $indicator['news'] = array("count" => array('count_table_rows', 'news'), "title" => _("Ankündigungen"), "detail" => ""); $indicator['vote'] = array("count" => array('count_table_rows', 'questionnaires'), "title" => _("Fragebögen"), "detail" => "", "constraint" => get_config('VOTE_ENABLE')); $indicator['evaluation'] = array("count" => array('count_table_rows', 'eval'), "title" => _("Evaluationen"), "detail" => "", "constraint" => get_config('VOTE_ENABLE')); $indicator['wiki_pages'] = array("query" => "SELECT COUNT(DISTINCT keyword) AS count FROM wiki", "title" => _("Wiki-Seiten"), "detail" => "", "constraint" => get_config('WIKI_ENABLE')); $indicator['resource'] = array("count" => array('count_table_rows', 'resources_objects'), "title" => _("Ressourcen-Objekte"), "detail" => _("von Stud.IP verwaltete Ressourcen wie Räume oder Geräte"), "constraint" => Config::get()->RESOURCES_ENABLE); if ($key == 'posting') { $count = 0; // sum up number of postings for all availabe ForumModules foreach (PluginEngine::getPlugins('ForumModule') as $plugin) { $count += $plugin->getNumberOfPostings(); } $template->title = _('Forenbeiträge'); $template->detail = _('Anzahl Beiträge aller verwendeten Foren'); $template->count = $count; } else { // iterate over the other indicators if (in_array($key, array_keys($indicator))) { if (!isset($indicator[$key]['constraint']) || $indicator[$key]['constraint']) { if ($indicator[$key]['query']) { $result = $this->db->query($indicator[$key]['query']); $rows = $result->fetch(PDO::FETCH_NUM); $template->count = $rows[0]; } else { $template->count = call_user_func($indicator[$key]['count'][0], $indicator[$key]['count'][1]); } $template->title = $indicator[$key]['title']; if ($indicator[$key]['detail']) { $template->detail = $indicator[$key]['detail']; } } else { return ""; } } else { return ""; } } $ret = $template->render(); $cache->write(__METHOD__ . $key, $ret); return $ret; }
/** * force reload of cached table metadata */ public static function expireTableScheme() { StudipCacheFactory::getCache()->expire('DB_TABLE_SCHEMES'); self::$schemes = null; }
function ac_start() { $this->cache = StudipCacheFactory::getCache(); }
/** * Returns a cache instance. * * @param bool $apply_proxied_operations Whether or not to apply any * proxied (disable this in tests!) * @return StudipCache the cache instance */ public static function getCache($apply_proxied_operations = true) { if (is_null(self::$cache)) { $proxied = false; if (!$GLOBALS['CACHING_ENABLE']) { self::$cache = new StudipNullCache(); // Proxy cache operations if CACHING_ENABLE is different from the globally set // caching value. This should only be the case in cli mode. if (isset($GLOBALS['GLOBAL_CACHING_ENABLE']) && $GLOBALS['GLOBAL_CACHING_ENABLE']) { $proxied = true; } } else { try { $class = self::loadCacheClass(); $args = self::retrieveConstructorArguments(); self::$cache = self::instantiateCache($class, $args); } catch (Exception $e) { error_log(__METHOD__ . ': ' . $e->getMessage()); PageLayout::addBodyElements(MessageBox::error(__METHOD__ . ': ' . $e->getMessage())); $class = self::DEFAULT_CACHE_CLASS; self::$cache = new $class(); } } // If proxy should be used, inject it. Otherwise apply pending // operations, if any. if ($proxied) { self::$cache = new StudipCacheProxy(self::$cache); } elseif ($GLOBALS['CACHING_ENABLE'] && $apply_proxied_operations) { // Even if the above condition will try to eliminate most // failures, the following operation still needs to be wrapped // in a try/catch block. Otherwise there are no means to // execute migration 166 which creates the neccessary tables // for said operation. try { StudipCacheOperation::apply(self::$cache); } catch (Exception $e) { } } } return self::$cache; }
/** * Enter description here... * * @param int $pluginid * @return array */ public static function getAssignedPluginRoles($pluginid=-1) { $cache = StudipCacheFactory::getCache(); // read plugin roles from cache (unserialize does not matter on cache $key = self::ROLES_PLUGINS_CACHE_KEY . (int) $pluginid; $result = unserialize($cache->read($key)); // cache miss, retrieve roles from database if (!$result) { $result = array(); $roles = self::getAllRoles(); $stmt = DBManager::get()->prepare("SELECT * FROM roles_plugins WHERE pluginid=?"); $stmt->execute(array($pluginid)); while ($row = $stmt->fetch()) { if (isset($roles[$row["roleid"]])) { $result[] = $roles[$row["roleid"]]; } } // write to cache $cache->write($key, serialize($result)); } return $result; }
public function addSingleDate(&$singledate) { // logging >>>>>> StudipLog::log("SEM_ADD_SINGLEDATE", $this->getId(), $singledate->toString(), 'SingleDateID: '.$singledate->getTerminID()); // logging <<<<<< $cache = StudipCacheFactory::getCache(); $cache->expire('course/undecorated_data/'. $this->getId()); $this->readSingleDates(); $this->irregularSingleDates[$singledate->getSingleDateID()] =& $singledate; NotificationCenter::postNotification("CourseDidChangeSchedule", $this); return TRUE; }
/** * Removes the cached entries for a specific user. * * @param String $user_id Id of the user */ protected static function expireCache($user_id) { $cache = StudipCacheFactory::getCache(); $hash = self::getCacheHash($user_id); $cache->expire($hash); }