From dab120040a6b24d73e16ae5018e90f559669f47c Mon Sep 17 00:00:00 2001
From: Makara Wang <makara15@gmail.com>
Date: Wed, 21 Sep 2011 15:24:13 +0800
Subject: [PATCH] #910726 - Use MongoBinData for non-UTF8 strings.

---
 mongodb_cache/mongodb_cache.inc |   20 ++++++++++++++++----
 1 files changed, 16 insertions(+), 4 deletions(-)

diff --git a/mongodb_cache/mongodb_cache.inc b/mongodb_cache/mongodb_cache.inc
index a2b9d46..bf2512a 100644
--- a/mongodb_cache/mongodb_cache.inc
+++ b/mongodb_cache/mongodb_cache.inc
@@ -86,6 +86,7 @@ class DrupalMongoDBCache implements DrupalCacheInterface {
     $cache = (object)$cache;
     // If the data is permanent or we are not enforcing a minimum cache lifetime
     // always return the cached data.
+    // ?
     if ($cache->expire == CACHE_PERMANENT || !variable_get('cache_lifetime', 0)) {
     }
     // If enforcing a minimum cache lifetime, validate that the data is
@@ -98,6 +99,9 @@ class DrupalMongoDBCache implements DrupalCacheInterface {
       // This cache data is too old and thus not valid for us, ignore it.
       return FALSE;
     }
+    if ($cache->data instanceof MongoBinData) {
+      $cache->data = $cache->data->bin;
+    }
     if ($cache->serialized) {
       $cache->data = unserialize($cache->data);
     }
@@ -105,21 +109,29 @@ class DrupalMongoDBCache implements DrupalCacheInterface {
     return $cache;
   }
 
-  function set($cid, $data, $expire = CACHE_PERMANENT, array $headers = NULL) {
+  function set($cid, $data, $expire = CACHE_PERMANENT) {
     $scalar = is_scalar($data);
     $entry = array(
       '_id' => (string)$cid,
       'cid' => (string)$cid,
       'created' => REQUEST_TIME,
       'expire' => $expire,
-      'headers' => $headers,
       'serialized' => !$scalar,
       'data' => $scalar ? $data : serialize($data),
     );
 
-    $collection = mongodb_collection($this->bin);
+    // Use MongoBinData for non-UTF8 strings.
+    if (is_string($entry['data']) && !drupal_validate_utf8($entry['data'])) {
+      $entry['data'] = new MongoBinData($entry['data']);
+    }
 
-    $collection->save($entry);
+    try {
+      $collection = mongodb_collection($this->bin);
+      $collection->save($entry);
+    }
+    catch (Exception $e) {
+      // The database may not be available, so we'll ignore cache_set requests.
+    }
   }
 
   function clear($cid = NULL, $wildcard = FALSE) {
-- 
1.7.6.1

