Esempio n. 1
0
 /**
  * The code that needs to be called when the cron is running
  * 
  * If $this->enableUserAndGroupSupport() returns TRUE then the run function 
  * will be called for each $user. (The $user parameter will be given)
  * 
  * If $this->enableUserAndGroupSupport() returns FALSE then the 
  * $user parameter is null and the run function will be called only once.
  * 
  * @param CronJob $cronJob
  * @param \GO\Base\Model\User $user [OPTIONAL]
  */
 public function run(CronJob $cronJob, \GO\Base\Model\User $user = null)
 {
     \GO::session()->runAsRoot();
     $usersStmt = \GO\Base\Model\User::model()->findByAttribute('mail_reminders', 1);
     while ($userModel = $usersStmt->fetch()) {
         \GO::debug("Sending mail reminders to " . $userModel->username);
         $remindersStmt = \GO\Base\Model\Reminder::model()->find(\GO\Base\Db\FindParams::newInstance()->joinModel(array('model' => 'GO\\Base\\Model\\ReminderUser', 'localTableAlias' => 't', 'localField' => 'id', 'foreignField' => 'reminder_id', 'tableAlias' => 'ru'))->criteria(\GO\Base\Db\FindCriteria::newInstance()->addCondition('user_id', $userModel->id, '=', 'ru')->addCondition('time', time(), '<', 'ru')->addCondition('mail_sent', '0', '=', 'ru')));
         while ($reminderModel = $remindersStmt->fetch()) {
             //					$relatedModel = $reminderModel->getRelatedModel();
             //					var_dump($relatedModel->name);
             //					$modelName = $relatedModel ? $relatedModel->localizedName : \GO::t('unknown');
             $subject = \GO::t('reminder') . ': ' . $reminderModel->name;
             $time = !empty($reminderModel->vtime) ? $reminderModel->vtime : $reminderModel->time;
             date_default_timezone_set($userModel->timezone);
             $body = \GO::t('time') . ': ' . date($userModel->completeDateFormat . ' ' . $userModel->time_format, $time) . "\n";
             $body .= \GO::t('name') . ': ' . str_replace('<br />', ',', $reminderModel->name) . "\n";
             //					date_default_timezone_set(\GO::user()->timezone);
             $message = \GO\Base\Mail\Message::newInstance($subject, $body);
             $message->addFrom(\GO::config()->noreply_email, \GO::config()->title);
             $message->addTo($userModel->email, $userModel->name);
             \GO\Base\Mail\Mailer::newGoInstance()->send($message, $failedRecipients);
             if (!empty($failedRecipients)) {
                 trigger_error("Reminder mail failed for recipient: " . implode(',', $failedRecipients), E_USER_NOTICE);
             }
             $reminderUserModelSend = \GO\Base\Model\ReminderUser::model()->findSingleByAttributes(array('user_id' => $userModel->id, 'reminder_id' => $reminderModel->id));
             $reminderUserModelSend->mail_sent = 1;
             $reminderUserModelSend->save();
         }
         date_default_timezone_set(\GO::user()->timezone);
     }
 }
Esempio n. 2
0
 private function _sendMessage($dbxUser, $e, $body)
 {
     Model\Sync::log("Sending failure e-mail to " . $dbxUser->user->email);
     $message = Message::newInstance();
     $message->setSubject(GO::t('syncFailed', 'dropbox'));
     $body .= "\n\nError: " . $e->getMessage();
     $message->setBody($body, 'text/plain');
     $message->setFrom(GO::config()->webmaster_email, GO::config()->title);
     $message->addTo($dbxUser->user->email, $dbxUser->user->name);
     Mailer::newGoInstance()->send($message);
 }
Esempio n. 3
0
 /**
  * send an email to webmaster_email in config
  * @return boolean true when successfull
  */
 public function send()
 {
     if (!$this->validate()) {
         return false;
     }
     $message = \GO\Base\Mail\Message::newInstance();
     $message->setSubject("Groupoffice contact form");
     $message->setBody($this->message);
     $message->addFrom($this->email, $this->name);
     $message->addTo($this->receipt);
     return \GO\Base\Mail\Mailer::newGoInstance()->send($message);
 }
Esempio n. 4
0
 protected function actionSaveToFile($params)
 {
     $message = new \GO\Base\Mail\Message();
     $alias = \GO\Email\Model\Alias::model()->findByPk($params['alias_id']);
     $message->handleEmailFormInput($params);
     $message->setFrom($alias->email, $alias->name);
     $file = new \GO\Base\Fs\File(GO::config()->file_storage_path . $params['save_to_path']);
     $fbs = new \Swift_ByteStream_FileByteStream($file->path(), true);
     $message->toByteStream($fbs);
     $response['success'] = $file->exists();
     return $response;
 }
Esempio n. 5
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";
 }
Esempio n. 6
0
 /**
  * Sends a meeting request to all participants. If the participant is not a Group-Office user
  * or the organizer has no permissions to schedule an event it will include an
  * icalendar attachment so the calendar software can schedule it.
  * 
  * @return boolean
  * @throws Exception
  */
 public function sendMeetingRequest($newParticipantsOnly = false, $update = false)
 {
     if (!$this->is_organizer) {
         throw new \Exception("Meeting request can only be send from the organizer's event");
     }
     $stmt = $this->participants;
     //handle missing user
     if (!$this->user) {
         $this->user_id = 1;
         $this->save(true);
     }
     while ($participant = $stmt->fetch()) {
         if (!$newParticipantsOnly || isset(\GO::session()->values['new_participant_ids']) && in_array($participant->user_id, \GO::session()->values['new_participant_ids'])) {
             //don't invite organizer
             if ($participant->is_organizer) {
                 continue;
             }
             // Set the language of the email to the language of the participant.
             $language = false;
             if (!empty($participant->user_id)) {
                 $user = \GO\Base\Model\User::model()->findByPk($participant->user_id);
                 if ($user) {
                     \GO::language()->setLanguage($user->language);
                 }
             }
             //if participant status is pending then send a new inviation subject. Otherwise send it as update
             if (!$update) {
                 $subject = \GO::t('invitation', 'calendar') . ': ' . $this->name;
                 $bodyLine = \GO::t('invited', 'calendar');
             } else {
                 $subject = \GO::t('invitation_update', 'calendar') . ': ' . $this->name;
                 $bodyLine = \GO::t('eventUpdated', 'calendar');
             }
             //create e-mail message
             $message = \GO\Base\Mail\Message::newInstance($subject)->setFrom($this->user->email, $this->user->name)->addTo($participant->email, $participant->name);
             //check if we have a Group-Office event. If so, we can handle accepting
             //and declining in Group-Office. Otherwise we'll use ICS calendar objects by mail
             $participantEvent = $participant->getParticipantEvent();
             $body = '<p>' . $bodyLine . ': </p>' . $this->toHtml();
             //				if(!$participantEvent){
             //build message for external program
             $acceptUrl = \GO::url("calendar/event/invitation", array("id" => $this->id, 'accept' => 1, 'email' => $participant->email, 'participantToken' => $participant->getSecurityToken()), false);
             $declineUrl = \GO::url("calendar/event/invitation", array("id" => $this->id, 'accept' => 0, 'email' => $participant->email, 'participantToken' => $participant->getSecurityToken()), false);
             //				if($participantEvent){
             //hide confusing buttons if user has a GO event.
             $body .= '<div class="go-hidden">';
             //				}
             $body .= '<p><br /><b>' . \GO::t('linkIfCalendarNotSupported', 'calendar') . '</b></p>' . '<p>' . \GO::t('acccept_question', 'calendar') . '</p>' . '<a href="' . $acceptUrl . '">' . \GO::t('accept', 'calendar') . '</a>' . '&nbsp;|&nbsp;' . '<a href="' . $declineUrl . '">' . \GO::t('decline', 'calendar') . '</a>';
             //				if($participantEvent){
             $body .= '</div>';
             //				}
             $ics = $this->toICS("REQUEST");
             $a = \Swift_Attachment::newInstance($ics, \GO\Base\Fs\File::stripInvalidChars($this->name) . '.ics', 'text/calendar; METHOD="REQUEST"');
             $a->setEncoder(new Swift_Mime_ContentEncoder_PlainContentEncoder("8bit"));
             $a->setDisposition("inline");
             $message->attach($a);
             //for outlook 2003 compatibility
             $a2 = \Swift_Attachment::newInstance($ics, 'invite.ics', 'application/ics');
             $a2->setEncoder(new Swift_Mime_ContentEncoder_PlainContentEncoder("8bit"));
             $message->attach($a2);
             if ($participantEvent) {
                 $url = \GO::createExternalUrl('calendar', 'openCalendar', array('unixtime' => $this->start_time));
                 $body .= '<br /><a href="' . $url . '">' . \GO::t('openCalendar', 'calendar') . '</a>';
             }
             $message->setHtmlAlternateBody($body);
             // Set back the original language
             if ($language !== false) {
                 \GO::language()->setLanguage($language);
             }
             \GO\Base\Mail\Mailer::newGoInstance()->send($message);
         }
     }
     unset(\GO::session()->values['new_participant_ids']);
     return true;
 }
Esempio n. 7
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();
    }
Esempio n. 8
0
 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);
         }
     }
 }
Esempio n. 9
0
 /**
  * Send an email to the newly registrated user when he just created an account.
  * The mail should contain a welcome message and a username and password
  * @param string $view path to a template for the email. If the view is not set or
  * not found the default email body will be loaded from groupoffice
  * @param string $title title of email
  * @param array $_data this array will be explode to the view. if the view template
  * is not found it will be ignored
  * @return boolean true when email was send
  */
 public function sendRegistrationMail($view = null, $title = null, $_data = array(), $message = false)
 {
     $this->password = $this->_unencryptedPassword;
     //to non-crypted email password
     if (!empty($view) && is_readable($view . '.php')) {
         $model = $this;
         if (!empty($_data)) {
             extract($_data, EXTR_PREFIX_SAME, 'data');
         }
         ob_start();
         ob_implicit_flush(false);
         require $view . '.php';
         $emailBody = ob_get_clean();
         $type = 'text/html';
     } else {
         //fallback to register_email_body when no view
         $emailBody = GO::config()->get_setting('register_email_body') ?: GO::t('register_email_body', 'users');
         foreach ($this->getAttributes() as $key => $value) {
             if (is_string($value)) {
                 $emailBody = str_replace('{' . $key . '}', $value, $emailBody);
             }
         }
         $emailBody = str_replace('{url}', GO::config()->full_url, $emailBody);
         $emailBody = str_replace('{title}', GO::config()->title, $emailBody);
         $type = null;
     }
     if (!$title) {
         $title = GO::config()->get_setting('register_email_subject') ?: GO::t('register_email_subject', 'users');
     }
     if (empty($title) || empty($emailBody)) {
         return false;
     }
     if (!$message) {
         $message = new Message();
         $message->addFrom(GO::config()->webmaster_email, GO::config()->title);
     }
     $message->setSubject($title)->setBody($emailBody, $type)->addTo($this->email, $this->getName());
     return Mailer::newGoInstance()->send($message);
 }
Esempio n. 10
0
 /**
  * Send the email to the users
  * 
  * @param \GO\Base\Model\User $user
  * @param eventAndTaskPdf $pdf
  * @return Boolean
  */
 private function _sendEmail(\GO\Base\Model\User $user, $pdf)
 {
     $filename = \GO\Base\Fs\File::stripInvalidChars($user->name) . '.pdf';
     //Set the PDF filename
     $filename = str_replace(',', '', $filename);
     $mailSubject = \GO::t('cronEventAndTaskReportMailerSubject', 'calendar');
     $body = \GO::t('cronEventAndTaskReportMailerContent', 'calendar');
     $message = \GO\Base\Mail\Message::newInstance($mailSubject)->setFrom(\GO::config()->webmaster_email, \GO::config()->title)->addTo($user->email);
     $message->setHtmlAlternateBody(nl2br($body));
     $message->attach(\Swift_Attachment::newInstance($pdf, $filename, 'application/pdf'));
     \GO::debug('CRON SEND MAIL TO: ' . $user->email);
     return \GO\Base\Mail\Mailer::newGoInstance()->send($message);
 }