示例#1
0
 /**
  * @param string $key
  * @return bool
  */
 public function hasKey($key)
 {
     if ($this->memoryCache->hasKey($key)) {
         return true;
     }
     return $this->fileCache->hasKey($key);
 }
示例#2
0
 /**
  * @test
  */
 public function testMemoizeResultIsCorrect()
 {
     $memoryCache = new MemoryCache();
     $func = $memoryCache->memoize($this->testFunction);
     $this->assertEquals(3, $func(1, 2));
     $this->assertEquals(3, $func(1, 2));
 }
 /**
  * Test load method correctly
  */
 public function testLoadObject()
 {
     $object = new TestClass('value');
     $object->publicParam = 'public';
     $this->memoryCache->save(self::KEY, $object);
     $this->assertEquals($object, $this->memoryCache->load(self::KEY));
     $object->setPrivateParam('new value');
     $this->assertNotEquals($object, $this->memoryCache->load(self::KEY));
 }
    /**
     * jUnit4 BeforeClass annotation.
     **/
    function setUp() {
        $stats = new StatisticsEcho();
        $cache = new MemoryCache();
        $metahandler = new MetaHandlerIMDB($stats);
        $cachedmetahandler = new MetaHandlerCache($metahandler, $cache);

        if (!TestIcefilmScraper::$is_setup) {
            date_default_timezone_set("EST");
            $cache->clear();
            TestIcefilmScraper::$is_setup = TRUE;
        }

        $this->url = 'http://www.icefilms.info/movies/popular/1';
        $this->scraper = new IcefilmScraper($cachedmetahandler, $cache, $stats);
    }
示例#5
0
 public function testExpire()
 {
     $key = uniqid();
     $c = new MemoryCache();
     $this->assertTrue($c->set($key, ['bar' => ['baz']], 1));
     $this->assertEquals(['bar' => ['baz']], $c->get($key));
     $this->assertTrue($c->expires($key) <= time() + 1);
     sleep(2);
     $this->assertNull($c->get($key));
     $this->assertEquals(0, $c->expires('foobar'));
 }
示例#6
0
 /**
  * @usage 获取被试的试卷信息,判断试卷是否全部完成,成功则返回试卷信息
  * @param int $project_id
  * @param int $examinee_id
  * @throws Exception
  * @return unknown
  */
 protected static function getPapers($project_id, $examinee_id)
 {
     $project_detail_json = MemoryCache::getProjectDetail($project_id);
     $project_detail = json_decode($project_detail_json->exam_json, true);
     $papers_tmp = QuestionAns::find(array("examinee_id = :examinee_id:", 'bind' => array('examinee_id' => $examinee_id)));
     if (count($papers_tmp) != count($project_detail)) {
         throw new Exception(self::$error_state . '-答卷数量不正确-' . count($papers_tmp) . '-' . count($project_detail));
     }
     $papers_id_tmp = array();
     foreach ($papers_tmp as $value) {
         $papers_id_tmp[] = $value->paper_id;
     }
     $project_papers_id = array();
     foreach ($project_detail as $key => $value) {
         $project_papers_id[] = MemoryCache::getPaperDetail($key)->id;
     }
     if (!array_diff($papers_id_tmp, $project_papers_id)) {
         return $papers_tmp;
     } else {
         throw new Exception(self::$error_state . '-答卷信息与题库信息不符-' . print_r($papers_id_tmp, true) . print_r($project_papers_id, true));
     }
 }
示例#7
0
 public function DoLogin()
 {
     global $g_ui_locale;
     $vs_redirect_url = $this->request->getParameter('redirect', pString) ?: caNavUrl($this->request, null, null, null);
     if (!$this->request->doAuthentication(array('dont_redirect_to_login' => true, 'redirect' => $vs_redirect_url, 'noPublicUsers' => true, 'user_name' => $this->request->getParameter('username', pString), 'password' => $this->request->getParameter('password', pString)))) {
         $this->notification->addNotification(_t("Login was invalid"), __NOTIFICATION_TYPE_ERROR__);
         $this->view->setVar('notifications', $this->notification->getNotifications());
         if (isset($_COOKIE['CA_' . __CA_APP_NAME__ . '_ui_locale'])) {
             if (!initializeLocale($_COOKIE['CA_' . __CA_APP_NAME__ . '_ui_locale'])) {
                 die("Error loading locale " . $g_ui_locale);
             }
         }
         $this->render('login_html.php');
     } else {
         //
         // Reset locale globals
         //
         global $g_ui_locale_id, $g_ui_locale, $g_ui_units_pref, $_, $_locale;
         $g_ui_locale_id = $this->request->user->getPreferredUILocaleID();
         // get current UI locale as locale_id	 			(available as global)
         $g_ui_locale = $this->request->user->getPreferredUILocale();
         // get current UI locale as locale string 			(available as global)
         $g_ui_units_pref = $this->request->user->getPreference('units');
         // user's selected display units for measurements 	(available as global)
         if (!initializeLocale($g_ui_locale)) {
             die("Error loading locale " . $g_ui_locale);
         }
         MemoryCache::flush('translation');
         AppNavigation::clearMenuBarCache($this->request);
         // want to clear menu bar on login
         // Notify the user of the good news
         $this->notification->addNotification(_t("You are now logged in"), __NOTIFICATION_TYPE_INFO__);
         // Jump to redirect if set
         if ($vs_redirect_url) {
             $this->redirect($vs_redirect_url);
         }
         $this->render('welcome_html.php');
     }
 }
 /**
  * 缓存路由表
  */
 private static function getCacheRoute()
 {
     $urlArr = parse_url($_SERVER['REQUEST_URI']);
     $urlArr['path'] = trim($urlArr['path'], '\\/');
     if (empty($urlArr['path'])) {
         $urlArr['path'] = 'index';
     }
     $memCacheObj = new MemoryCache();
     $urlRes = @$memCacheObj->get($urlArr['path']);
     return $urlRes;
 }
示例#9
0
 /**
  * Clears the caches.
  */
 function clear() {
     MemoryCache::$cache = array();
 }
示例#10
0
 /**
  * Removes all cached configuration
  */
 public static function clearCache()
 {
     ExternalCache::flush();
     MemoryCache::flush();
 }
示例#11
0
 /**
  * @usage 写入被试的答卷信息
  * @param int $examinee_id
  * @param string $paper_name
  * @param string $option_str
  * @param array $number_array
  * @throws Exception
  * @return boolean
  */
 public static function insertQuestionAns($examinee_id, $paper_name, $option_str, $number_array, $time)
 {
     $project_id = self::getProjectId($examinee_id);
     if (!$project_id) {
         return false;
     }
     $paper_name = strtoupper($paper_name);
     switch ($paper_name) {
         case 'EPQA':
             self::checkEPQA($option_str, $number_array, $project_id);
             break;
         case 'EPPS':
             self::checkEPPS($option_str, $number_array, $project_id);
             break;
         case 'CPI':
             self::checkCPI($option_str, $number_array, $project_id);
             break;
         case '16PF':
             self::checkKS($option_str, $number_array, $project_id);
             break;
         case 'SCL':
             self::checkSCL($option_str, $number_array, $project_id);
             break;
         case 'SPM':
             self::checkSPM($option_str, $number_array, $project_id);
             break;
         default:
             throw new Exception(self::$error_state . '-不存在试卷-' . $paper_name);
     }
     $paper_id = MemoryCache::getPaperDetail($paper_name)->id;
     try {
         // Create a transaction manager
         $manager = new TxManager();
         // Request a transaction
         $transaction = $manager->get();
         $question_ans = new QuestionAns();
         #将事务设置到每一次的new之后
         $question_ans->setTransaction($transaction);
         $question_ans->option = $option_str;
         $question_ans->paper_id = $paper_id;
         $question_ans->examinee_id = $examinee_id;
         $question_ans->question_number_list = implode("|", $number_array);
         $question_ans->time = $time;
         if ($question_ans->save() == false) {
             $transaction->rollback(self::$error_state . '-数据库插入失败-' . print_r($question_ans, true));
         }
         $transaction->commit();
         return true;
     } catch (TxFailed $e) {
         throw new Exception($e->getMessage());
     }
 }
示例#12
0
 /**
  * Establishes a connection to the database
  *
  * @param mixed $po_caller representation of the caller, usually a Db() object
  * @param array $pa_options array containing options like host, username, password
  * @return bool success state
  */
 public function connect($po_caller, $pa_options)
 {
     $vs_db_connection_key = $pa_options["host"] . '/' . $pa_options["database"];
     // reuse connection
     if (!($vb_unique_connection = caGetOption('uniqueConnection', $pa_options, false)) && MemoryCache::contains($vs_db_connection_key, 'PdoConnectionCache')) {
         $this->opr_db = MemoryCache::fetch($vs_db_connection_key, 'PdoConnectionCache');
         return true;
     }
     if (!class_exists("PDO")) {
         die(_t("Your PHP installation lacks PDO MySQL support. Please add it and retry..."));
     }
     try {
         $this->opr_db = new PDO('mysql:host=' . $pa_options["host"] . ';dbname=' . $pa_options["database"], $pa_options["username"], $pa_options["password"], array(PDO::ATTR_PERSISTENT => caGetOption("persistentConnections", $pa_options, true), PDO::ATTR_EMULATE_PREPARES => true, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
     } catch (Exception $e) {
         $po_caller->postError(200, $e->getMessage(), "Db->pdo_mysql->connect()");
         return false;
     }
     $this->opr_db->exec('SET NAMES \'utf8\'');
     $this->opr_db->exec('SET character_set_results = NULL');
     if (!$vb_unique_connection) {
         MemoryCache::save($vs_db_connection_key, $this->opr_db, 'PdoConnectionCache');
     }
     return true;
 }
示例#13
0
 public static function delete($id)
 {
     $res = MemoryCache::delete($id);
     $res &= DiskCache::delete($id);
     return $res;
 }
示例#14
0
 /**
  * Returns the locale name of the specified locale_id, or null if the id is invalid. Note that this does not
  * change the state of the model - it just returns the locale.
  *
  * @param int $pn_id The locale_id of the locale, or null if the code is invalid
  * @return string The name of the locale
  */
 public function localeIDToName($pn_id)
 {
     if (!MemoryCache::contains($pn_id, 'LocaleIdToName')) {
         ca_locales::getLocaleList();
     }
     return MemoryCache::fetch($pn_id, 'LocaleIdToName');
 }
示例#15
0
 /**
  * 
  */
 public static function getInstance($pm_element_code_or_id)
 {
     if (!$pm_element_code_or_id) {
         return null;
     }
     if (MemoryCache::contains($pm_element_code_or_id, 'ElementInstances')) {
         return MemoryCache::fetch($pm_element_code_or_id, 'ElementInstances');
     }
     $t_element = new ca_metadata_elements(is_numeric($pm_element_code_or_id) ? $pm_element_code_or_id : null);
     if (!($vn_element_id = $t_element->getPrimaryKey())) {
         if ($t_element->load(array('element_code' => $pm_element_code_or_id))) {
             MemoryCache::save($t_element->getPrimaryKey(), $t_element, 'ElementInstances');
             MemoryCache::save($t_element->get('element_code'), $t_element, 'ElementInstances');
             return $t_element;
         }
     } else {
         MemoryCache::save($vn_element_id, $t_element, 'ElementInstances');
         MemoryCache::save($t_element->get('element_code'), $t_element, 'ElementInstances');
         return $t_element;
     }
     return null;
 }
示例#16
0
 /**
  * @param string $ps_file_path
  * @param bool $pb_dont_cache
  * @param bool $pb_dont_cache_instance
  * @return Configuration
  */
 static function load($ps_file_path = __CA_APP_CONFIG__, $pb_dont_cache = false, $pb_dont_cache_instance = false)
 {
     if (!$ps_file_path) {
         $ps_file_path = __CA_APP_CONFIG__;
     }
     if (!MemoryCache::contains($ps_file_path, 'ConfigurationInstances') || $pb_dont_cache || $pb_dont_cache_instance) {
         MemoryCache::save($ps_file_path, new Configuration($ps_file_path, true, $pb_dont_cache), 'ConfigurationInstances');
     }
     return MemoryCache::fetch($ps_file_path, 'ConfigurationInstances');
 }
示例#17
0
 /**
  * Returns element_code of ca_metadata_element with specified element_id or NULL if the element doesn't exist
  */
 private function _getElementListCode($pn_element_id)
 {
     $vn_element_id = $this->_getElementID($pn_element_id);
     // ensures MemoryCache is populated
     return MemoryCache::fetch($vn_element_id, 'SearchIndexerElementIds');
 }
示例#18
0
/**
 * Extracts media metadata using MediaInfo
 *
 * @param string $ps_filepath file path
 * @param string $ps_mediainfo_path optional path to MediaInfo binary. If omitted the path configured in external_applications.conf is used.
 *
 * @return array Extracted metadata
 */
function caExtractMetadataWithMediaInfo($ps_filepath, $ps_mediainfo_path = null)
{
    if (!$ps_mediainfo_path) {
        $ps_mediainfo_path = caGetExternalApplicationPath('mediainfo');
    }
    if (!caIsValidFilePath($ps_mediainfo_path)) {
        return false;
    }
    if (MemoryCache::contains($ps_filepath, 'MediaInfoMetadata')) {
        return MemoryCache::fetch($ps_filepath, 'MediaInfoMetadata');
    }
    //
    // TODO: why don't we parse this from the XML output like civilized people?
    //
    exec($ps_mediainfo_path . " " . caEscapeShellArg($ps_filepath), $va_output, $vn_return);
    $vs_cat = "GENERIC";
    $va_return = array();
    foreach ($va_output as $vs_line) {
        $va_split = explode(":", $vs_line);
        $vs_left = trim(array_shift($va_split));
        $vs_right = trim(join(":", $va_split));
        if (strlen($vs_right) == 0) {
            // category line
            $vs_cat = strtoupper($vs_left);
            continue;
        }
        if (strlen($vs_left) && strlen($vs_right)) {
            if ($vs_left != "Complete name") {
                // we probably don't want to display temporary filenames
                $va_return[$vs_cat][$vs_left] = $vs_right;
            }
        }
    }
    MemoryCache::save($ps_filepath, $va_return, 'MediaInfoMetadata');
    return $va_return;
}
 /**
  * @expectedException MemoryCacheInvalidParameterException
  */
 public function testInvalidKey()
 {
     MemoryCache::save('', 'data1', 'barNamespace');
 }
示例#20
0
/**
 * Fetch item_id for item with specified value. Value must match exactly.
 *
 * @param string $ps_list_code List code
 * @param string $ps_value The item value to search for
 * @param array $pa_options Options include:
 *		transaction = transaction to execute queries within. [Default=null]
 * @return int item_id of list item or null if no matching item was found
 */
function caGetListItemIDForValue($ps_list_code, $ps_value, $pa_options = null)
{
    $vs_cache_key = md5($ps_list_code . $ps_value . serialize($pa_options));
    if (MemoryCache::contains($vs_cache_key, 'ListItemIDsForValues')) {
        return MemoryCache::fetch($vs_cache_key, 'ListItemIDsForValues');
    }
    $t_list = new ca_lists();
    if ($o_trans = caGetOption('transaction', $pa_options, null)) {
        $t_list->setTransaction($o_trans);
    }
    if ($va_item = $t_list->getItemFromListByItemValue($ps_list_code, $ps_value)) {
        $vs_ret = array_shift(array_keys($va_item));
        MemoryCache::save($vs_cache_key, $vs_ret, 'ListItemIDsForValues');
        return $vs_ret;
    }
    return null;
}
示例#21
0
 /**
  *
  */
 public function getRelationships($ps_left_table, $ps_right_table)
 {
     if (MemoryCache::contains("{$ps_left_table}/{$ps_right_table}", 'DatamodelRelationships')) {
         return MemoryCache::fetch("{$ps_left_table}/{$ps_right_table}", 'DatamodelRelationships');
     }
     $va_relationships = $this->opo_graph->getAttribute("relationships", $ps_left_table, $ps_right_table);
     MemoryCache::save("{$ps_left_table}/{$ps_right_table}", $va_relationships, 'DatamodelRelationships');
     return $va_relationships;
 }
示例#22
0
 /**
  * Flush whole cache, both in-memory and on-disk. Use with caution!
  */
 public static function flush()
 {
     MemoryCache::flush();
     ExternalCache::flush();
 }
示例#23
0
/**
 * The same as _t(), but rather than returning the translated string, it prints it
 **/
function _p($ps_key)
{
    if (!$ps_key) {
        return;
    }
    global $_;
    if (!sizeof(func_get_args()) && MemoryCache::contains($ps_key, 'translation')) {
        print MemoryCache::fetch($ps_key, 'translation');
        return;
    }
    if (is_array($_)) {
        $vs_str = $ps_key;
        foreach ($_ as $o_locale) {
            if ($o_locale->isTranslated($ps_key)) {
                $vs_str = $o_locale->_($ps_key);
                break;
            }
        }
    } else {
        if (!is_object($_)) {
            $vs_str = $ps_key;
        } else {
            $vs_str = $_->_($ps_key);
        }
    }
    if (sizeof($va_args = func_get_args()) > 1) {
        $vn_num_args = sizeof($va_args) - 1;
        for ($vn_i = $vn_num_args; $vn_i >= 1; $vn_i--) {
            $vs_str = str_replace("%{$vn_i}", $va_args[$vn_i], $vs_str);
        }
    }
    MemoryCache::save($ps_key, $vs_str, 'translation');
    print $vs_str;
    return;
}
示例#24
0
 function clearCache($arr = null)
 {
     $hash = 'sqlc' . hash('sha1', $this->queryString . serialize($arr));
     return MemoryCache::delete($hash);
 }
 public function Save()
 {
     $vs_view_name = 'preferences_html.php';
     $vs_action = $this->request->getParameter('action', pString);
     switch ($vs_action) {
         case 'EditCataloguingPrefs':
             $vs_group = 'cataloguing';
             $this->request->user->setPreference('cataloguing_locale', $this->request->getParameter('pref_cataloguing_locale', pString));
             $va_ui_prefs = array();
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 foreach ($_REQUEST as $vs_k => $vs_v) {
                     if (preg_match("!pref_{$vs_pref}_([\\d]+)!", $vs_k, $va_matches)) {
                         $va_ui_prefs[$vs_pref][$va_matches[1]] = $vs_v;
                     } elseif (preg_match("!pref_{$vs_pref}__NONE_!", $vs_k)) {
                         $va_ui_prefs[$vs_pref]['_NONE_'] = $vs_v;
                     }
                 }
                 foreach ($va_ui_prefs as $vs_pref => $va_values) {
                     $this->request->user->setPreference($vs_pref, $va_values);
                 }
             }
             $vs_view_name = 'preferences_cataloguing_html.php';
             break;
         case 'EditBatchPrefs':
             $vs_group = 'batch';
             $va_ui_prefs = array();
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 foreach ($_REQUEST as $vs_k => $vs_v) {
                     if (preg_match("!pref_{$vs_pref}!", $vs_k, $va_matches)) {
                         $this->request->user->setPreference($vs_pref, $vs_v);
                     }
                 }
             }
             $vs_view_name = 'preferences_batch_html.php';
             break;
         case 'EditQuickAddPrefs':
             $vs_group = 'quickadd';
             $va_ui_prefs = array();
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 foreach ($_REQUEST as $vs_k => $vs_v) {
                     if (preg_match("!pref_{$vs_pref}_([\\d]+)!", $vs_k, $va_matches)) {
                         $va_ui_prefs[$vs_pref][$va_matches[1]] = $vs_v;
                     }
                 }
                 foreach ($va_ui_prefs as $vs_pref => $va_values) {
                     $this->request->user->setPreference($vs_pref, $va_values);
                 }
             }
             $vs_view_name = 'preferences_quickadd_html.php';
             break;
         case 'EditMediaPrefs':
             $vs_group = 'media';
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 $this->request->user->setPreference($vs_pref, $this->request->getParameter('pref_' . $vs_pref, pString));
             }
             break;
         case 'EditUnitsPrefs':
             $vs_group = 'units';
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 $this->request->user->setPreference($vs_pref, $this->request->getParameter('pref_' . $vs_pref, pString));
             }
             break;
         case 'EditProfilePrefs':
             $vs_group = 'profile';
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 $this->request->user->setPreference($vs_pref, $this->request->getParameter('pref_' . $vs_pref, pString));
             }
             break;
         case 'EditDuplicationPrefs':
             $vs_group = 'duplication';
             foreach (array('ca_objects', 'ca_object_lots', 'ca_entities', 'ca_places', 'ca_occurrences', 'ca_collections', 'ca_storage_locations', 'ca_loans', 'ca_movements', 'ca_lists', 'ca_list_items', 'ca_tours', 'ca_tour_stops', 'ca_sets', 'ca_bundle_displays') as $vs_table) {
                 foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                     if ($vs_pref == 'duplicate_relationships') {
                         $vs_val = $this->request->getParameter("pref_{$vs_table}_{$vs_pref}", pArray);
                     } else {
                         $vs_val = $this->request->getParameter("pref_{$vs_table}_{$vs_pref}", pString);
                     }
                     $this->request->user->setPreference("{$vs_table}_{$vs_pref}", $vs_val);
                 }
             }
             $vs_view_name = 'preferences_duplication_html.php';
             break;
         case 'EditUIPrefs':
         default:
             $vs_group = 'ui';
             $vs_action = 'EditUIPrefs';
             foreach ($this->request->user->getValidPreferences($vs_group) as $vs_pref) {
                 $this->request->user->setPreference($vs_pref, $vs_locale = $this->request->getParameter('pref_' . $vs_pref, pString));
                 if ($vs_pref == 'ui_locale' && $vs_locale) {
                     global $_, $g_ui_locale_id, $g_ui_locale, $_locale;
                     // set UI locale for this request (causes UI language to change immediately - and in time - for this request)
                     // if we didn't do this, you'd have to reload the page to see the locale change
                     $this->request->user->setPreference('ui_locale', $vs_locale);
                     $g_ui_locale_id = $this->request->user->getPreferredUILocaleID();
                     // get current UI locale as locale_id	 			(available as global)
                     $g_ui_locale = $this->request->user->getPreferredUILocale();
                     // get current UI locale as locale string 			(available as global)
                     if (!initializeLocale($g_ui_locale)) {
                         die("Error loading locale " . $g_ui_locale);
                     }
                     MemoryCache::flush('translation');
                     // reload menu bar
                     AppNavigation::clearMenuBarCache($this->request);
                 }
                 if ($vs_pref == 'ui_theme') {
                     // set the view path to use the new theme; if we didn't set this here you'd have to reload the page to
                     // see the theme change.
                     $this->view->setViewPath($this->request->getViewsDirectoryPath() . '/' . $this->request->getModulePath());
                 }
             }
             break;
     }
     $this->request->setAction($vs_action);
     $this->view->setVar('group', $vs_group);
     $this->notification->addNotification(_t("Saved preference settings"), __NOTIFICATION_TYPE_INFO__);
     $this->view->setVar('t_user', $this->request->user);
     $this->render($vs_view_name);
 }
示例#26
0
 /**
  * Cache the given Nodes.
  *
  * @param string   $key
  * @param string[] $nodes
  * @param int      $ttl TTL in seconds
  *
  * @return bool
  */
 public function set($key, array $nodes, $ttl)
 {
     $this->read();
     parent::set($key, $nodes, $ttl);
     return $this->write();
 }
 public function testSetAndFetchFromExternalCache()
 {
     $vm_ret = ExternalCache::save('foo', array('foo' => 'bar'), 'barNamespace');
     $this->assertTrue($vm_ret, 'Setting item in cache should return true');
     $vm_ret = CompositeCache::contains('foo', 'barNamespace');
     $this->assertTrue($vm_ret, 'Checking for existence of a key we just set should return true');
     $vm_ret = CompositeCache::contains('foo');
     $this->assertFalse($vm_ret, 'The key should not exist in an unused namespace');
     $vm_ret = CompositeCache::fetch('foo', 'barNamespace');
     $this->assertArrayHasKey('foo', $vm_ret, 'Returned array should have key');
     $this->assertEquals(array('foo' => 'bar'), $vm_ret, 'Cache item should not change');
     // after we fetch it once using CompositeCache, it should be in memory
     $vm_ret = MemoryCache::fetch('foo', 'barNamespace');
     $this->assertArrayHasKey('foo', $vm_ret, 'Returned array should have key');
     $this->assertEquals(array('foo' => 'bar'), $vm_ret, 'Cache item should not change');
 }
示例#28
0
 /**
  * Flush cache
  * @param string|null $ps_namespace Optional namespace definition. If given, only this namespace is wiped.
  * @throws MemoryCacheInvalidParameterException
  */
 public static function flush($ps_namespace = null)
 {
     if (!$ps_namespace) {
         self::$opa_caches = array();
     } else {
         if (!is_string($ps_namespace)) {
             throw new MemoryCacheInvalidParameterException('Namespace has to be a string');
         }
         self::$opa_caches[$ps_namespace] = array();
     }
 }
示例#29
0
/**
 * Try to match given (partial) hierarchy path to a single subject in getty linked data AAT service
 * @param array $pa_hierarchy_path
 * @param int $pn_threshold
 * @param array $pa_options
 * 		removeParensFromLabels = Remove parens from labels for search and string comparison. This can improve results in specific cases.
 * @return bool|string
 */
function caMatchAAT($pa_hierarchy_path, $pn_threshold = 180, $pa_options = array())
{
    $vs_cache_key = md5(print_r($pa_hierarchy_path, true));
    if (MemoryCache::contains($vs_cache_key, 'AATMatches')) {
        return MemoryCache::fetch($vs_cache_key, 'AATMatches');
    }
    if (!is_array($pa_hierarchy_path)) {
        return false;
    }
    $pb_remove_parens_from_labels = caGetOption('removeParensFromLabels', $pa_options, false);
    // search the bottom-most component (the actual term)
    $vs_bot = trim(array_pop($pa_hierarchy_path));
    if ($pb_remove_parens_from_labels) {
        $vs_lookup = trim(preg_replace("/\\([\\p{L}\\-\\_\\s]+\\)/", '', $vs_bot));
    } else {
        $vs_lookup = $vs_bot;
    }
    $o_service = new WLPlugInformationServiceAAT();
    $va_hits = $o_service->lookup(array(), $vs_lookup, array('phrase' => true, 'raw' => true, 'limit' => 2000));
    if (!is_array($va_hits)) {
        return false;
    }
    $vn_best_distance = 0;
    $vn_pick = -1;
    foreach ($va_hits as $vn_i => $va_hit) {
        if (stripos($va_hit['TermPrefLabel']['value'], $vs_lookup) !== false) {
            // only consider terms that match what we searched
            // calculate similarity as a number by comparing both the term and the parent string
            $vs_label_with_parens = $va_hit['TermPrefLabel']['value'];
            $vs_label_without_parens = trim(preg_replace("/\\([\\p{L}\\s]+\\)/", '', $vs_label_with_parens));
            $va_label_percentages = array();
            // we try every combination with and without parens on both sides
            // unfortunately this code gets rather ugly because getting the similarity
            // as percentage is only possible by passing a reference parameter :-(
            similar_text($vs_label_with_parens, $vs_bot, $vn_label_percent);
            $va_label_percentages[] = $vn_label_percent;
            similar_text($vs_label_with_parens, $vs_lookup, $vn_label_percent);
            $va_label_percentages[] = $vn_label_percent;
            similar_text($vs_label_without_parens, $vs_bot, $vn_label_percent);
            $va_label_percentages[] = $vn_label_percent;
            similar_text($vs_label_without_parens, $vs_lookup, $vn_label_percent);
            $va_label_percentages[] = $vn_label_percent;
            // similarity to parent path
            similar_text($va_hit['ParentsFull']['value'], join(' ', array_reverse($pa_hierarchy_path)), $vn_parent_percent);
            // it's a weighted sum because the term label is more important than the exact path
            $vn_tmp = 2 * max($va_label_percentages) + $vn_parent_percent;
            //var_dump($va_hit); var_dump($vn_tmp);
            if ($vn_tmp > $vn_best_distance) {
                $vn_best_distance = $vn_tmp;
                $vn_pick = $vn_i;
            }
        }
    }
    if ($vn_pick >= 0 && $vn_best_distance > $pn_threshold) {
        $va_pick = $va_hits[$vn_pick];
        MemoryCache::save($vs_cache_key, $va_pick['ID']['value'], 'AATMatches');
        return $va_pick['ID']['value'];
    }
    return false;
}
 /**
  * Options:
  * 		rawDate - if true, returns date as an array of start and end historic timestames
  *		sortable - if true a language-independent sortable representation is returned.
  *		getDirectDate - get underlying historic timestamp (floatval)
  */
 public function getDisplayValue($pa_options = null)
 {
     if (!is_array($pa_options)) {
         $pa_options = array();
     }
     if (isset($pa_options['rawDate']) && $pa_options['rawDate']) {
         return array(0 => $this->opn_start_date, 1 => $this->opn_end_date, 'start' => $this->opn_start_date, 'end' => $this->opn_end_date);
     }
     if (caGetOption('GET_DIRECT_DATE', $pa_options, false) || caGetOption('getDirectDate', $pa_options, false)) {
         return $this->opn_start_date;
     }
     if (isset($pa_options['sortable']) && $pa_options['sortable']) {
         if (!$this->opn_start_date || !$this->opn_end_date) {
             return null;
         }
         return $this->opn_start_date . '/' . $this->opn_end_date;
     }
     $o_date_config = Configuration::load(__CA_CONF_DIR__ . '/datetime.conf');
     $vs_date_format = $o_date_config->get('dateFormat');
     $vs_cache_key = md5($vs_date_format . $this->opn_start_date . $this->opn_end_date);
     // pull from cache
     if (isset(DateRangeAttributeValue::$s_date_cache[$vs_cache_key])) {
         return DateRangeAttributeValue::$s_date_cache[$vs_cache_key];
     }
     // if neither start nor end date are set, the setHistoricTimestamps() call below will
     // fail and the TEP will return the text for whatever happened to be parsed previously
     // so we have to init() before trying
     DateRangeAttributeValue::$o_tep->init();
     if ($vs_date_format == 'original') {
         return DateRangeAttributeValue::$s_date_cache[$vs_cache_key] = $this->ops_text_value;
     } else {
         if (!is_array($va_settings = MemoryCache::fetch($this->getElementID(), 'ElementSettings'))) {
             $t_element = new ca_metadata_elements($this->getElementID());
             $va_settings = MemoryCache::fetch($this->getElementID(), 'ElementSettings');
         }
         DateRangeAttributeValue::$o_tep->setHistoricTimestamps($this->opn_start_date, $this->opn_end_date);
         return DateRangeAttributeValue::$s_date_cache[$vs_cache_key] = DateRangeAttributeValue::$o_tep->getText(array_merge(array('isLifespan' => $va_settings['isLifespan']), $pa_options));
         //$this->ops_text_value;
     }
 }