Example #1
0
 public function actionAccountTemplatesStore($params)
 {
     $findParams = \GO\Base\Db\FindParams::newInstance()->order('name');
     $findParams->getCriteria()->addCondition('type', \GO\Addressbook\Model\Template::TYPE_EMAIL);
     $stmt = \GO\Addressbook\Model\Template::model()->find($findParams);
     $store = \GO\Base\Data\Store::newInstance(\GO\Addressbook\Model\Template::model());
     //		$store->getColumnModel()->setFormatRecordFunction(array($this, 'formatEmailSelectionRecord'));
     $store->setStatement($stmt);
     $response = $store->getData();
     $response['total']++;
     $response['results'][] = array('id' => -1, 'name' => '-- ' . \GO::t('userDefaultTemplate', 'addressbook') . ' --', 'group' => '', 'text' => '', 'template_id' => '', 'checked' => false);
     return $response;
 }
Example #2
0
 /**
  * This action will generate multiple Email Download link and return a JSON
  * response with the generated links in the email subject
  * @param array $params
  * - string ids: json encode file ids to mail
  * - timestamp expire_time: chosen email link expire time 
  * - int template_id: id of used template
  * - int alias_id: id of alias to mail from
  * - string content_type : html | plain  
  * @return string Json response
  */
 protected function actionEmailDownloadLink($params)
 {
     $files = \GO\Files\Model\File::model()->findByAttribute('id', json_decode($params['ids']));
     $html = $params['content_type'] == 'html';
     $bodyindex = $html ? 'htmlbody' : 'plainbody';
     $lb = $html ? '<br />' : "\n";
     $text = $html ? \GO::t('clickHereToDownload', "files") : \GO::t('copyPasteToDownload', "files");
     $linktext = $html ? "<ul>" : $lb;
     foreach ($files as $file) {
         $url = $file->getEmailDownloadURL($html, \GO\Base\Util\Date::date_add($params['expire_time'], 1), $params['delete_when_expired']);
         $linktext .= $html ? '<li><a href="' . $url . '">' . $file->name . '</a></li>' . $lb : $url . $lb;
     }
     $linktext .= $html ? "</ul>" : "\n";
     $text .= ' (' . \GO::t('possibleUntil', 'files') . ' ' . \GO\Base\Util\Date::get_timestamp(\GO\Base\Util\Date::date_add($file->expire_time, -1), false) . ')' . $lb;
     $text .= $linktext;
     if ($params['template_id'] && ($template = \GO\Addressbook\Model\Template::model()->findByPk($params['template_id']))) {
         $message = \GO\Email\Model\SavedMessage::model()->createFromMimeData($template->content);
         $response['data'] = $message->toOutputArray($html, true);
         if (strpos($response['data'][$bodyindex], '{body}')) {
             $response['data'][$bodyindex] = \GO\Addressbook\Model\Template::model()->replaceUserTags($response['data'][$bodyindex], true);
             \GO\Addressbook\Model\Template::model()->htmlSpecialChars = false;
             $response['data'][$bodyindex] = \GO\Addressbook\Model\Template::model()->replaceCustomTags($response['data'][$bodyindex], array('body' => $text));
         } else {
             $response['data'][$bodyindex] = \GO\Addressbook\Model\Template::model()->replaceUserTags($response['data'][$bodyindex], false);
             $response['data'][$bodyindex] = $text . $response['data'][$bodyindex];
         }
     } else {
         $response['data'][$bodyindex] = $text;
     }
     $response['data']['subject'] = \GO::t('downloadLink', 'files');
     //.' '.$file->name;
     $response['success'] = true;
     return $response;
 }
Example #3
0
 public function loadTemplate($params)
 {
     if (GO::modules()->addressbook && !empty($params['template_id'])) {
         try {
             $template = \GO\Addressbook\Model\Template::model()->findByPk($params['template_id']);
             $templateContent = $template ? $template->content : '';
         } catch (\GO\Base\Exception\AccessDenied $e) {
             $templateContent = "";
         }
         $message = \GO\Email\Model\SavedMessage::model()->createFromMimeData($templateContent);
         $response['data'] = $message->toOutputArray(true, true);
         $presetbody = isset($params['body']) ? $params['body'] : '';
         if (!empty($presetbody) && strpos($response['data']['htmlbody'], '{body}') == false) {
             $response['data']['htmlbody'] = $params['body'] . '<br />' . $response['data']['htmlbody'];
         } else {
             $response['data']['htmlbody'] = str_replace('{body}', $presetbody, $response['data']['htmlbody']);
         }
         unset($response['data']['to'], $response['data']['cc'], $response['data']['bcc']);
         //			unset($response['data']['cc'], $response['data']['bcc'], $response['data']['subject']);
         $defaultTags = array('contact:salutation' => GO::t('default_salutation_unknown'));
         // Parse the link tag
         $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceLinkTag($response['data']['htmlbody'], $message);
         //keep template tags for mailings to addresslists
         if (empty($params['addresslist_id'])) {
             //if contact_id is not set but email is check if there's contact info available
             if (!empty($params['to']) || !empty($params['contact_id']) || !empty($params['company_id'])) {
                 if (!empty($params['contact_id'])) {
                     $contact = \GO\Addressbook\Model\Contact::model()->findByPk($params['contact_id']);
                 } else {
                     $email = \GO\Base\Util\String::get_email_from_string($params['to']);
                     $contact = \GO\Addressbook\Model\Contact::model()->findSingleByEmail($email);
                 }
                 $company = false;
                 if (!empty($params['company_id'])) {
                     $company = \GO\Addressbook\Model\Company::model()->findByPk($params['company_id']);
                 }
                 if ($company) {
                     $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceModelTags($response['data']['htmlbody'], $company, 'company:', true);
                 }
                 if ($contact) {
                     $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceContactTags($response['data']['htmlbody'], $contact);
                 } else {
                     $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceCustomTags($response['data']['htmlbody'], $defaultTags, true);
                     $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceUserTags($response['data']['htmlbody']);
                 }
             } else {
                 $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceCustomTags($response['data']['htmlbody'], $defaultTags, true);
                 $response['data']['htmlbody'] = \GO\Addressbook\Model\Template::model()->replaceUserTags($response['data']['htmlbody']);
             }
         }
         if ($params['content_type'] == 'plain') {
             $response['data']['plainbody'] = \GO\Base\Util\String::html_to_text($response['data']['htmlbody'], false);
             unset($response['data']['htmlbody']);
         }
     } else {
         $response['data'] = array();
         if ($params['content_type'] == 'plain') {
             $response['data']['plainbody'] = '';
         } else {
             $response['data']['htmlbody'] = '';
         }
     }
     $response['success'] = true;
     return $response;
 }
Example #4
0
 protected function actionBatchSend($params)
 {
     $this->requireCli();
     $this->_sentEmails = array();
     \GO::$disableModelCache = true;
     $mailing = \GO\Addressbook\Model\SentMailing::model()->findByPk($params['mailing_id']);
     if (!$mailing) {
         throw new \Exception("Mailing not found!\n");
     }
     \GO::session()->runAs($mailing->user_id);
     echo 'Status: ' . $mailing->status . "\n";
     if (empty($mailing->status)) {
         echo "Starting mailing at " . \GO\Base\Util\Date::get_timestamp(time()) . "\n";
         $mailing->reset();
     } elseif (!empty($params['restart'])) {
         echo "Restarting mailing at " . \GO\Base\Util\Date::get_timestamp(time()) . "\n";
         $mailing->reset();
     } elseif ($mailing->status == \GO\Addressbook\Model\SentMailing::STATUS_PAUSED) {
         echo "Resuming mailing at " . \GO\Base\Util\Date::get_timestamp(time()) . "\n";
         $mailing->status = \GO\Addressbook\Model\SentMailing::STATUS_RUNNING;
         $mailing->save();
     }
     $htmlToText = new \GO\Base\Util\Html2Text();
     //$addresslist = \GO\Addressbook\Model\Addresslist::model()->findByPk($mailing->addresslist_id);
     $mimeData = file_get_contents(\GO::config()->file_storage_path . $mailing->message_path);
     $message = \GO\Base\Mail\Message::newInstance()->loadMimeMessage($mimeData);
     $joinCriteria = \GO\Base\Db\FindCriteria::newInstance()->addRawCondition('t.id', 'a.account_id');
     $findParams = \GO\Base\Db\FindParams::newInstance()->single()->join(\GO\Email\Model\Alias::model()->tableName(), $joinCriteria, 'a')->criteria(\GO\Base\Db\FindCriteria::newInstance()->addCondition('id', $mailing->alias_id, '=', 'a'));
     if ($mailing->campaign_id > 0 && \GO::modules()->isAvailable('campaigns')) {
         $account = new \GO\Email\Model\Account();
         $account->username = \GO::config()->campaigns_imap_user;
         $account->password = \GO::config()->campaigns_imap_pass;
         $account->host = \GO::config()->campaigns_imap_server;
         $account->port = \GO::config()->campaigns_imap_port;
         $account->smtp_username = \GO::config()->campaigns_smtp_user;
         $account->smtp_password = \GO::config()->campaigns_smtp_pass;
         $account->smtp_host = \GO::config()->campaigns_smtp_server;
         $account->smtp_port = \GO::config()->campaigns_smtp_port;
         $message->setFrom(\GO::config()->campaigns_from);
     } else {
         $account = \GO\Email\Model\Account::model()->find($findParams);
         if (!$account->store_password && !empty($mailing->temp_pass)) {
             $account->smtp_password = $mailing->temp_pass;
         }
     }
     $mailer = \GO\Base\Mail\Mailer::newGoInstance(\GO\Email\Transport::newGoInstance($account));
     echo "Will send emails from " . $account->username . ".\n";
     if (empty(\GO::config()->mailing_messages_per_minute)) {
         \GO::config()->mailing_messages_per_minute = 30;
     }
     //Rate limit to 100 emails per-minute
     $mailer->registerPlugin(new \Swift_Plugins_ThrottlerPlugin(\GO::config()->mailing_messages_per_minute, \Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE));
     // Use AntiFlood to re-connect after 50 emails
     $mailer->registerPlugin(new \Swift_Plugins_AntiFloodPlugin(\GO::config()->mailing_messages_per_minute));
     echo 'Sending a maximum of ' . \GO::config()->mailing_messages_per_minute . ' messages per minute' . "\n";
     $failedRecipients = array();
     $bodyWithTags = $message->getBody();
     foreach ($mailing->contacts as $contact) {
         $sentMailingContactModel = \GO\Addressbook\Model\SentMailingContact::model()->findSingleByAttributes(array('sent_mailing_id' => $mailing->id, 'contact_id' => $contact->id));
         if (!$sentMailingContactModel->sent) {
             $errors = 1;
             $unsubscribeHref = \GO::url('addressbook/sentMailing/unsubscribe', array('addresslist_id' => $mailing->addresslist_id, 'contact_id' => $contact->id, 'token' => md5($contact->ctime . $contact->addressbook_id . $contact->firstEmail)), false, true);
             $body = str_replace('%unsubscribe_href%', $unsubscribeHref, $bodyWithTags);
             //curly brackets don't work inside links in browser wysiwyg editors.
             $templateModel = \GO\Addressbook\Model\Template::model();
             $templateModel->htmlSpecialChars = false;
             $body = $templateModel->replaceCustomTags($body, array('unsubscribe_link' => '<a href="' . $unsubscribeHref . '" target="_blank">' . \GO::t("unsubscription", "addressbook") . '</a>'), true);
             $templateModel->htmlSpecialChars = true;
             try {
                 if (!$contact->email_allowed) {
                     echo "Skipping contact " . $contact->firstEmail . " because newsletter sending is disabled in the addresslists tab.\n\n";
                 } elseif (empty($contact->firstEmail)) {
                     echo "Skipping contact " . $contact->name . " no e-mail address was set.\n\n";
                 } else {
                     $body = \GO\Addressbook\Model\Template::model()->replaceContactTags($body, $contact);
                     $message->setTo($contact->firstEmail, $contact->name);
                     $message->setBody($body);
                     $plainTextPart = $message->findPlainTextBody();
                     if ($plainTextPart) {
                         $htmlToText->set_html($body);
                         $plainTextPart->setBody($htmlToText->get_text());
                     }
                     // Check mail limit
                     $nSentMails = \GO::config()->get_setting('campaigns_number_sent_mails', 0);
                     if ($mailing->campaign_id > 0 && $nSentMails >= \GO::config()->campaigns_max_mails_per_period) {
                         $this->_pauseMailing($mailing->id);
                         echo "Error for " . $contact->firstEmail . ": \n";
                         echo str_replace('%maxMails', \GO::config()->campaigns_max_mails_per_period, \GO::t('sentMailLimitReached', 'campaigns'));
                         exit;
                     }
                     $this->_sendmail($message, $contact, $mailer, $mailing);
                     \GO::config()->save_setting('campaigns_number_sent_mails', $nSentMails + 1, 0);
                     $errors = 0;
                 }
             } catch (\Exception $e) {
                 echo "Error for " . $contact->firstEmail . ": " . $e->getMessage() . "\n";
             }
             if ($errors) {
                 $mailing->errors++;
                 $mailing->save();
             }
         }
     }
     foreach ($mailing->companies as $company) {
         $sentMailingCompanyModel = \GO\Addressbook\Model\SentMailingCompany::model()->findSingleByAttributes(array('sent_mailing_id' => $mailing->id, 'company_id' => $company->id));
         if (!$sentMailingCompanyModel->sent) {
             $errors = 1;
             $unsubscribeHref = \GO::url('addressbook/sentMailing/unsubscribe', array('addresslist_id' => $mailing->addresslist_id, 'company_id' => $company->id, 'token' => md5($company->ctime . $company->addressbook_id . $company->email)), true, true);
             $body = str_replace('%unsubscribe_href%', $unsubscribeHref, $bodyWithTags);
             //curly brackets don't work inside links in browser wysiwyg editors.
             $body = \GO\Addressbook\Model\Template::model()->replaceCustomTags($body, array('unsubscribe_link' => '<a href="' . $unsubscribeHref . '">' . \GO::t("unsubscription", "addressbook") . '</a>'), true);
             try {
                 if (!$company->email_allowed) {
                     echo "Skipping company " . $company->email . " because newsletter sending is disabled in the addresslists tab.\n\n";
                 } elseif (empty($company->email)) {
                     echo "Skipping company " . $company->name . " no e-mail address was set.\n\n";
                 } else {
                     $body = \GO\Addressbook\Model\Template::model()->replaceModelTags($body, $company);
                     $message->setTo($company->email, $company->name);
                     $message->setBody($body);
                     $plainTextPart = $message->findPlainTextBody();
                     if ($plainTextPart) {
                         $htmlToText->set_html($body);
                         $plainTextPart->setBody($htmlToText->get_text());
                     }
                     // Check mail limit
                     $nSentMails = \GO::config()->get_setting('campaigns_number_sent_mails', 0);
                     if ($mailing->campaign_id > 0 && $nSentMails >= \GO::config()->campaigns_max_mails_per_period) {
                         $this->_pauseMailing($mailing->id);
                         echo "Error for " . $contact->firstEmail . ": \n";
                         echo str_replace('%maxMails', \GO::config()->campaigns_max_mails_per_period, \GO::t('sentMailLimitReached', 'campaigns'));
                         exit;
                     }
                     $this->_sendmail($message, $company, $mailer, $mailing);
                     \GO::config()->save_setting('campaigns_number_sent_mails', $nSentMails + 1, 0);
                     $errors = 0;
                 }
             } catch (\Exception $e) {
                 echo "Error for " . $company->email . ": " . $e->getMessage() . "\n";
             }
             if ($errors) {
                 $mailing->errors++;
                 $mailing->save();
             }
         }
     }
     $mailing->status = \GO\Addressbook\Model\SentMailing::STATUS_FINISHED;
     // Unset the temp_pass
     if (!empty($mailing->temp_pass)) {
         $mailing->temp_pass = "";
     }
     $mailing->save();
     echo "Mailing finished at " . \GO\Base\Util\Date::get_timestamp(time()) . "\n";
 }
Example #5
0
    public function install()
    {
        parent::install();
        $default_language = \GO::config()->default_country;
        if (empty($default_language)) {
            $default_language = 'US';
        }
        $addressbook = new Model\Addressbook();
        $addressbook->setAttributes(array('user_id' => 1, 'name' => \GO::t('prospects', 'addressbook')));
        $addressbook->save();
        $addressbook->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
        $addressbook = new Model\Addressbook();
        $addressbook->setAttributes(array('user_id' => 1, 'name' => \GO::t('suppliers', 'addressbook')));
        $addressbook->save();
        $addressbook->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
        if (!is_dir(\GO::config()->file_storage_path . 'contacts/contact_photos')) {
            mkdir(\GO::config()->file_storage_path . 'contacts/contact_photos', 0755, true);
        }
        $addressbook = new Model\Addressbook();
        $addressbook->setAttributes(array('user_id' => 1, 'name' => \GO::t('customers', 'addressbook')));
        $addressbook->save();
        $addressbook->acl->addGroup(\GO::config()->group_internal, \GO\Base\Model\Acl::WRITE_PERMISSION);
        //Each user should have a contact
        $stmt = \GO\Base\Model\User::model()->find(\GO\Base\Db\FindParams::newInstance()->ignoreAcl());
        while ($user = $stmt->fetch()) {
            $user->createContact();
        }
        $message = new \GO\Base\Mail\Message();
        $message->setHtmlAlternateBody('{salutation},<br />
<br />
{body}<br />
<br />
' . \GO::t('greet', 'addressbook') . '<br />
<br />
<br />
{user:name}<br />
{usercompany:name}<br />');
        $template = new Model\Template();
        $template->setAttributes(array('content' => $message->toString(), 'name' => \GO::t('default'), 'type' => Model\Template::TYPE_EMAIL, 'user_id' => 1));
        $template->save();
        $template->acl->addGroup(\GO::config()->group_internal);
        $dt = Model\Template::model()->findSingleByAttribute('name', 'Letter');
        if (!$dt) {
            $dt = new Model\Template();
            $dt->type = Model\Template::TYPE_DOCUMENT;
            $dt->content = file_get_contents(\GO::modules()->addressbook->path . 'install/letter_template.docx');
            $dt->extension = 'docx';
            $dt->name = 'Letter';
            $dt->save();
            $dt->acl->addGroup(\GO::config()->group_internal);
        }
        $this->setFolderPermissions();
    }
 function process_form()
 {
     \GO::$ignoreAclPermissions = true;
     $this->check_required();
     if (!isset($_POST['salutation'])) {
         $_POST['salutation'] = isset($_POST['sex']) ? \GO::t('default_salutation_' . $_POST['sex']) : \GO::t('default_salutation_unknown');
     }
     //user registation
     //		if(!empty($_POST['username'])){
     //			$credentials = array ('username','first_name','middle_name','last_name','title','initials','sex','email',
     //			'home_phone','fax','cellular','address','address_no',
     //			'zip','city','state','country','company','department','function','work_phone',
     //			'work_fax');
     //
     //			if($_POST['password1'] != $_POST['password2'])
     //			{
     //				throw new Exception(\GO::t('error_match_pass','users'));
     //			}
     //
     //			foreach($credentials as $key)
     //			{
     //				if(!empty($_REQUEST[$key]))
     //				{
     //					$userCredentials[$key] = $_REQUEST[$key];
     //				}
     //			}
     //			$userCredentials['password']=$_POST['password1'];
     //
     //			$userModel = new \GO\Base\Model\User();
     //			$userModel->setAttributes($userCredentials);
     //			$userModel->save();
     //			foreach($this->user_groups as $groupId) {
     //				$currentGroupModel = \GO\Base\Model\Group::model()->findByPk($groupId);
     //				if($groupId>0 && $groupId!=\GO::config()->group_everyone && !$currentGroupModel->hasUser($userModel->id)) {
     //					$currentGroupModel->addUser($userModel->id);
     //				}
     //			}
     //			foreach($this->visible_user_groups as $groupId) {
     //				$userAclModel = \GO\Base\Model\Acl::model()->findByPk($userModel->acl_id);
     //				if($groupId>0 && !empty($userAclModel) && $userAclModel->hasGroup($groupId)) {
     //					$userAclModel->addGroup($groupId);
     //				}
     //			}
     //
     //			\GO::session()->login($userCredentials['username'], $userCredentials['password']);
     //		}
     if (!empty($_POST['email']) && !\GO\Base\Util\String::validate_email($_POST['email'])) {
         throw new Exception(\GO::t('invalidEmailError'));
     }
     if (!empty($_REQUEST['addressbook'])) {
         //			require($GO_LANGUAGE->get_language_file('addressbook'));
         //			require_once($GO_MODULES->modules['addressbook']['class_path'].'addressbook.class.inc.php');
         //			$ab = new addressbook();
         //
         //			$addressbook = $ab->get_addressbook_by_name($_REQUEST['addressbook']);
         $addressbookModel = \GO\Addressbook\Model\Addressbook::model()->findSingleByAttribute('name', $_REQUEST['addressbook']);
         if (!$addressbookModel) {
             throw new Exception('Addressbook not found!');
         }
         $credentials = array('first_name', 'middle_name', 'last_name', 'title', 'initials', 'sex', 'email', 'email2', 'email3', 'home_phone', 'fax', 'cellular', 'comment', 'address', 'address_no', 'zip', 'city', 'state', 'country', 'company', 'department', 'function', 'work_phone', 'work_fax', 'salutation', 'url_linkedin', 'url_facebook', 'url_twitter', 'skype_name');
         foreach ($credentials as $key) {
             if (!empty($_REQUEST[$key])) {
                 $contactCredentials[$key] = $_REQUEST[$key];
             }
         }
         if (isset($contactCredentials['comment']) && is_array($contactCredentials['comment'])) {
             $comments = '';
             foreach ($contactCredentials['comment'] as $key => $value) {
                 if ($value == 'date') {
                     $value = date($_SESSION['GO_SESSION']['date_format'] . ' ' . $_SESSION['GO_SESSION']['time_format']);
                 }
                 if (!empty($value)) {
                     $comments .= trim($key) . ":\n" . trim($value) . "\n\n";
                 }
             }
             $contactCredentials['comment'] = $comments;
         }
         if ($this->no_urls && isset($contactCredentials['comment']) && stripos($contactCredentials['comment'], 'http')) {
             throw new Exception('Sorry, but to prevent spamming we don\'t allow URL\'s in the message');
         }
         $contactCredentials['addressbook_id'] = $addressbookModel->id;
         $contactCredentials['email_allowed'] = isset($_POST['email_allowed']) ? '1' : '0';
         if (!empty($contactCredentials['company']) && empty($contactCredentials['company_id'])) {
             $companyModel = \GO\Addressbook\Model\Company::model()->findSingleByAttributes(array('name' => $contactCredentials['company'], 'addressbook_id' => $contactCredentials['addressbook_id']));
             if (empty($companyModel)) {
                 $companyModel = new \GO\Addressbook\Model\Company();
                 $companyModel->addressbook_id = $contactCredentials['addressbook_id'];
                 $companyModel->name = $contactCredentials['company'];
                 // bedrijfsnaam
                 $companyModel->user_id = \GO::user()->id;
                 $companyModel->save();
                 $contactCredentials['company_id'] = $companyModel->id;
             }
         }
         if (isset($_POST['birthday'])) {
             try {
                 $contactCredentials['birthday'] = \GO\Base\Util\Date::to_db_date($_POST['birthday'], false);
             } catch (Exception $e) {
                 throw new Exception(\GO::t('birthdayFormatMustBe') . ': ' . $_SESSION['GO_SESSION']['date_format'] . '.');
             }
             if (!empty($_POST['birthday']) && $contactCredentials['birthday'] == '0000-00-00') {
                 throw new Exception(\GO::t('invalidDateError'));
             }
         }
         unset($contactCredentials['company']);
         $existingContactModel = false;
         if (!empty($_POST['contact_id'])) {
             $existingContactModel = \GO\Addressbook\Model\Contact::model()->findByPk($_POST['contact_id']);
         } elseif (!empty($contactCredentials['email'])) {
             $existingContactModel = \GO\Addressbook\Model\Contact::model()->findSingleByAttributes(array('email' => $contactCredentials['email'], 'addressbook_id' => $contactCredentials['addressbook_id']));
         }
         if ($existingContactModel) {
             $this->contact_id = $contactId = $existingContactModel->id;
             $filesFolderId = $existingContactModel->files_folder_id = $existingContactModel->getFilesFolder()->id;
             /*
              * Only update empty fields
              */
             if (empty($_POST['contact_id'])) {
                 foreach ($contactCredentials as $key => $value) {
                     if ($key != 'comment') {
                         if (!empty($existingContactModel->{$key})) {
                             unset($contactCredentials[$key]);
                         }
                     }
                 }
             }
             $contactCredentials['id'] = $contactId;
             if (!empty($existingContactModel->comment) && !empty($contactCredentials['comment'])) {
                 $contactCredentials['comment'] = $existingContactModel->comment . "\n\n----\n\n" . $contactCredentials['comment'];
             }
             if (empty($contactCredentials['comment'])) {
                 unset($contactCredentials['comment']);
             }
             $existingContactModel->setAttributes($contactCredentials);
             $existingContactModel->save();
         } else {
             $newContactModel = new \GO\Addressbook\Model\Contact();
             $newContactModel->setAttributes($contactCredentials);
             $newContactModel->save();
             $this->contact_id = $contactId = $newContactModel->id;
             $filesFolderId = $newContactModel->files_folder_id = $newContactModel->getFilesFolder()->id;
             $newContactModel->save();
             if (isset($_POST['contact_id']) && empty($userId) && \GO::user()->id > 0) {
                 $userId = $this->user_id = \GO::user()->id;
             }
             if (!empty($userId)) {
                 $userModel = \GO\Base\Model\User::model()->findByPk($userId);
                 $userModel->contact_id = $contactId;
                 $userModel->save();
             }
         }
         if (!$contactId) {
             throw new Exception(\GO::t('saveError'));
         }
         if (\GO::modules()->isInstalled('files')) {
             $folderModel = \GO\Files\Model\Folder::model()->findByPk($filesFolderId);
             $path = $folderModel->path;
             $response['files_folder_id'] = $filesFolderId;
             $full_path = \GO::config()->file_storage_path . $path;
             foreach ($_FILES as $key => $file) {
                 if ($key != 'photo') {
                     //photo is handled later
                     if (is_uploaded_file($file['tmp_name'])) {
                         $fsFile = new \GO\Base\Fs\File($file['tmp_name']);
                         $fsFile->move(new \GO\Base\Fs\Folder($full_path), $file['name'], false, true);
                         $fsFile->setDefaultPermissions();
                         \GO\Files\Model\File::importFromFilesystem($fsFile);
                     }
                 }
             }
         }
         if (\GO::modules()->isInstalled('customfields')) {
             $cfFields = array();
             foreach ($_POST as $k => $v) {
                 if (strpos($k, 'col_') === 0) {
                     $cfFields[$k] = $v;
                 }
             }
             $contactCfModel = \GO\Addressbook\Customfields\Model\Contact::model()->findByPk($contactId);
             if (!$contactCfModel) {
                 $contactCfModel = new \GO\Addressbook\Customfields\Model\Contact();
                 $contactCfModel->model_id = $contactId;
             }
             $contactCfModel->setAttributes($cfFields);
             $contactCfModel->save();
         }
         if (isset($_POST['mailings'])) {
             foreach ($_POST['mailings'] as $mailingName) {
                 if (!empty($mailingName)) {
                     $addresslistModel = \GO\Addressbook\Model\Addresslist::model()->findSingleByAttribute('name', $mailingName);
                     if (empty($addresslistModel)) {
                         throw new Exception('Addresslist not found!');
                     }
                     $addresslistModel->addManyMany('contacts', $contactId);
                 }
             }
         }
         if ($this->contact_id > 0) {
             if (isset($_FILES['photo']['tmp_name']) && is_uploaded_file($_FILES['photo']['tmp_name'])) {
                 $fsFile = new \GO\Base\Fs\File($_FILES['photo']['tmp_name']);
                 $fsFile->move(new \GO\Base\Fs\Folder(\GO::config()->tmpdir), $_FILES['photo']['name'], false, false);
                 $contactModel = \GO\Addressbook\Model\Contact::model()->findByPk($contactId);
                 $contactModel->setPhoto(\GO::config()->tmpdir . $_FILES['photo']['name']);
             }
         }
         if (!isset($_POST['contact_id'])) {
             /**
              * Send notification of new contact to (1) users specified by 'notify_users'
              * in the form itself and to (2) the addressbook owner if so specified. 
              */
             // Send the email to the admin users in the language of the addressbook owner.
             $oldLanguage = \GO::language()->getLanguage();
             \GO::language()->setLanguage($addressbookModel->user->language);
             $usersToNotify = isset($_POST['notify_users']) ? explode(',', $_POST['notify_users']) : array();
             if (!empty($_POST['notify_addressbook_owner'])) {
                 $usersToNotify[] = $addressbookModel->user_id;
             }
             $mailTo = array();
             foreach ($usersToNotify as $userToNotifyId) {
                 $userModel = \GO\Base\Model\User::model()->findByPk($userToNotifyId);
                 $mailTo[] = $userModel->email;
             }
             if (count($mailTo)) {
                 $viewContactUrl = \GO::createExternalUrl('addressbook', 'showContact', array($contactId));
                 $contactModel = \GO\Addressbook\Model\Contact::model()->findByPk($contactId);
                 $companyModel = \GO\Addressbook\Model\Company::model()->findByPk($contactModel->company_id);
                 if (!empty($companyModel)) {
                     $companyName = $companyModel->name;
                 } else {
                     $companyName = '';
                 }
                 $values = array('address_no', 'address', 'zip', 'city', 'state', 'country');
                 $formatted_address = nl2br(\GO\Base\Util\Common::formatAddress('{country}', '{address}', '{address_no}', '{zip}', '{city}', '{state}'));
                 foreach ($values as $val) {
                     $formatted_address = str_replace('{' . $val . '}', $contactModel->{$val}, $formatted_address);
                 }
                 $body = \GO::t('newContactFromSite', 'addressbook') . ':<br />';
                 $body .= \GO::t('name', 'addressbook') . ': ' . $contactModel->addressbook->name . '<br />';
                 $body .= "<br />" . $contactModel->name;
                 $body .= "<br />" . $formatted_address;
                 if (!empty($contactModel->home_phone)) {
                     $body .= "<br />" . \GO::t('phone') . ': ' . $contactModel->home_phone;
                 }
                 if (!empty($contactModel->cellular)) {
                     $body .= "<br />" . \GO::t('cellular') . ': ' . $contactModel->cellular;
                 }
                 if (!empty($companyName)) {
                     $body .= "<br /><br />" . $companyName;
                 }
                 if (!empty($contactModel->work_phone)) {
                     $body .= "<br />" . \GO::t('workphone') . ': ' . $contactModel->work_phone;
                 }
                 $body .= '<br /><a href="' . $viewContactUrl . '">' . \GO::t('clickHereToView', 'addressbook') . '</a>' . "<br />";
                 $mailFrom = !empty($_POST['mail_from']) ? $_POST['mail_from'] : \GO::config()->webmaster_email;
                 $mailMessage = \GO\Base\Mail\Message::newInstance(\GO::t('newContactAdded', 'addressbook'), $body, 'text/html')->setFrom($mailFrom, \GO::config()->title);
                 foreach ($mailTo as $v) {
                     $mailMessage->addTo($v);
                 }
                 \GO\Base\Mail\Mailer::newGoInstance()->send($mailMessage);
             }
             // Restore the language
             \GO::language()->setLanguage($oldLanguage);
         }
         //
         //
         //	Maybe make this workable with GO 4.0 later....
         //
         //
         //			if(isset($_POST['confirmation_template']))
         //			{
         //				if(empty($_POST['email']))
         //				{
         //					throw new Exception('Fatal error: No email given for confirmation e-mail!');
         //				}
         //
         //				$url = create_direct_url('addressbook', 'showContact', array($contactId));
         //				$body = $lang['addressbook']['newContactFromSite'].'<br /><a href="'.$url.'">'.$lang['addressbook']['clickHereToView'].'</a>';
         //
         //				global $smarty;
         //				$email = $smarty->fetch($_POST['confirmation_template']);
         //
         //				$pos = strpos($email,"\n");
         //
         //				$subject = trim(substr($email, 0, $pos));
         //				$body = trim(substr($email,$pos));
         //
         //				require_once(\GO::config()->class_path.'mail/GoSwift.class.inc.php');
         //				$swift = new GoSwift($_POST['email'], $subject);
         //				$swift->set_body($body);
         //				$swift->set_from(\GO::config()->webmaster_email, \GO::config()->title);
         //				$swift->sendmail();
         //			}
         if (isset($_POST['confirmation_email']) && !empty($_POST['email'])) {
             if (strpos($_POST['confirmation_email'], '../') !== false || strpos($_POST['confirmation_email'], '..\\') !== false) {
                 throw new Exception('Invalid path');
             }
             $path = \GO::config()->file_storage_path . $_POST['confirmation_email'];
             if (!file_exists($path)) {
                 $path = dirname(\GO::config()->get_config_file()) . '/' . $_POST['confirmation_email'];
             }
             //$email = file_get_contents($path);
             //$messageModel = \GO\Email\Model\SavedMessage::model()->createFromMimeFile($path);
             //				$htmlBodyString = \GO\Addressbook\Model\Template::model()->replaceUserTags($messageModel->getHtmlBody());
             //				$htmlBodyString = \GO\Addressbook\Model\Template::model()
             //								->replaceContactTags(
             //												$htmlBodyString,
             //												\GO\Addressbook\Model\Contact::model()->findByPk($contactId),
             //												false);
             //				$messageModel->body =
             $mailMessage = \GO\Base\Mail\Message::newInstance()->loadMimeMessage(file_get_contents($path));
             $htmlBodyString = $mailMessage->getBody();
             foreach ($this->confirmation_replacements as $tag => $replacement) {
                 $htmlBodyString = str_replace('{' . $tag . '}', $replacement, $htmlBodyString);
             }
             $htmlBodyString = \GO\Addressbook\Model\Template::model()->replaceUserTags($htmlBodyString, true);
             $htmlBodyString = \GO\Addressbook\Model\Template::model()->replaceContactTags($htmlBodyString, \GO\Addressbook\Model\Contact::model()->findByPk($contactId), false);
             $mailMessage->setBody($htmlBodyString);
             $mailMessage->setFrom($mailMessage->getFrom(), $mailMessage->getSender());
             $mailMessage->addTo($_POST['email']);
             \GO\Base\Mail\Mailer::newGoInstance()->send($mailMessage);
         }
     }
 }