From ffc9c13a8e8e9a5414d62fbb21e6dbfbffa5edef Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Thu, 10 Apr 2014 16:11:22 -0500
Subject: [PATCH] orgs: Auto import based on email domain

---
 include/class.organization.php | 13 +++++++++++--
 include/class.user.php         | 10 ++++++++++
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/include/class.organization.php b/include/class.organization.php
index a12300391..ad9deec88 100644
--- a/include/class.organization.php
+++ b/include/class.organization.php
@@ -129,6 +129,15 @@ class Organization extends OrganizationModel {
         return $base;
     }
 
+    function isMappedToDomain($domain) {
+        foreach (explode(',', $this->domain) as $d) {
+            if (strcasecmp($domain, trim($d)) === 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     function to_json() {
 
         $info = array(
@@ -164,8 +173,8 @@ class Organization extends OrganizationModel {
 
         if ($vars['domain']) {
             foreach (explode(',', $vars['domain']) as $d) {
-                if (!Validator::is_email('test' . trim($d))) {
-                    $errors['domain'] = 'Enter a valid email domain, like @domain.com';
+                if (!Validator::is_email('t@' . trim($d))) {
+                    $errors['domain'] = 'Enter a valid email domain, like domain.com';
                 }
             }
         }
diff --git a/include/class.user.php b/include/class.user.php
index 9eb4fd3a6..0f105be3f 100644
--- a/include/class.user.php
+++ b/include/class.user.php
@@ -154,6 +154,16 @@ class User extends UserModel {
                 // of the detached emails is fixed.
                 'default_email' => UserEmail::ensure($vars['email'])
             ));
+            // Is there an organization registered for this domain
+            list($mailbox, $domain) = explode('@', $vars['email'], 2);
+            foreach (Organization::objects()
+                    ->filter(array('domain__contains'=>$domain)) as $org) {
+                if ($org->isMappedToDomain($domain)) {
+                    $user->setOrganization($org);
+                    break;
+                }
+            }
+
             $user->save(true);
             $user->emails->add($user->default_email);
             // Attach initial custom fields
-- 
GitLab