From c2d81e32a54df3cdf83a53947099cc4b152daea1 Mon Sep 17 00:00:00 2001
From: Joseph Naegele <jnaegele@grierforensics.com>
Date: Wed, 1 Feb 2017 11:28:03 -0500
Subject: [PATCH] Add option for automatic S/MIME encryption

---
 imp/config/prefs.php |  7 +++++++
 imp/lib/Compose.php  | 26 ++++++++++++++++++++++++++
 2 files changed, 33 insertions(+)

diff --git a/imp/config/prefs.php b/imp/config/prefs.php
index 8debcd0..32ba8dc 100644
--- a/imp/config/prefs.php
+++ b/imp/config/prefs.php
@@ -438,6 +438,13 @@ $_prefs['smime_verify'] = array(
     'requires' => array('use_smime')
 );
 
+$_prefs['smime_automatic'] = array(
+    'value' => 0,
+    'type' => 'checkbox',
+    'desc' => _("Should S/MIME encryption be performed opportunistically?"),
+    'requires' => array('use_smime')
+);
+
 // S/MIME public keys management widget
 $_prefs['smimepublickey'] = array(
     'type' => 'special',
diff --git a/imp/lib/Compose.php b/imp/lib/Compose.php
index 7c4540d..e3286ee 100644
--- a/imp/lib/Compose.php
+++ b/imp/lib/Compose.php
@@ -1013,6 +1013,32 @@ class IMP_Compose implements ArrayAccess, Countable, IteratorAggregate
             break;
         }
 
+        /* Attempt to enable S/MIME encryption if configured automatically */
+        if (IMP_Smime::enabled() && $prefs->getValue('smime_automatic') &&
+            !in_array($encrypt, array(IMP_Smime::ENCRYPT, IMP_Smime::SIGNENC))) {
+
+            $imp_smime = $injector->getInstance('IMP_Smime');
+            $possible = true;
+            try {
+                foreach ($recip['list'] as $addr) {
+                    $key = $imp_smime->getPublicKey($addr->bare_address);
+                    if (is_null($key)) {
+                        $possible = false;
+                    }
+                }
+            } catch (Horde_Exception $e) {
+                $possible = false;
+            }
+
+            if ($possible) {
+                if ($encrypt == IMP_Smime::SIGN) {
+                    $encrypt = IMP_Crypt_Smime::SIGNENC;
+                } else {
+                    $encrypt = IMP_Crypt_Smime::ENCRYPT;
+                }
+            }
+        }
+
         switch ($encrypt) {
         case IMP_Pgp::ENCRYPT:
         case IMP_Pgp::SIGN:
-- 
2.10.1 (Apple Git-78)