Example #1
0
 public function formatStoreRecord($record, $model, $store)
 {
     $r = new \GO\Base\Mail\EmailRecipients();
     $r->addRecipient($model->email, $model->name);
     $record['from'] = (string) $r;
     $record['html_signature'] = \GO\Base\Util\String::text_to_html($model->signature);
     $record['plain_signature'] = $model->signature;
     $record['signature_below_reply'] = $model->account->signature_below_reply;
     $record['template_id'] = 0;
     if (\GO::modules()->addressbook) {
         $defaultAccountTemplateModel = \GO\Addressbook\Model\DefaultTemplateForAccount::model()->findByPk($model->account_id);
         if ($defaultAccountTemplateModel) {
             $record['template_id'] = $defaultAccountTemplateModel->template_id;
         } else {
             $defaultUserTemplateModel = \GO\Addressbook\Model\DefaultTemplate::model()->findByPk(\GO::user()->id);
             if (!$defaultUserTemplateModel) {
                 $defaultUserTemplateModel = new \GO\Addressbook\Model\DefaultTemplateForAccount();
                 $defaultUserTemplateModel->account_id = $model->account_id;
                 $defaultUserTemplateModel->save();
             }
             $record['template_id'] = $defaultUserTemplateModel->template_id;
         }
     }
     unset($record['signature']);
     return parent::formatStoreRecord($record, $model, $store);
 }
Example #2
0
 protected function actionInfo($params)
 {
     if (empty(GO::session()->values['debug'])) {
         throw new \GO\Base\Exception\AccessDenied("Debugging can only be enabled by an admin");
     }
     $response = array('success' => true, 'info' => '');
     $info['username'] = GO::user()->username;
     $info['config'] = GO::config()->get_config_file();
     $info['database'] = GO::config()->db_name;
     $modules = GO::modules()->getAllModules();
     foreach ($modules as $module) {
         if (!isset($info['modules'])) {
             $info['modules'] = $module->id;
         } else {
             $info['modules'] .= ', ' . $module->id;
         }
     }
     $info = array_merge($info, $_SERVER);
     $response['info'] = '<table>';
     foreach ($info as $key => $value) {
         $response['info'] .= '<tr><td>' . $key . ':</td><td>' . $value . '</td></tr>';
     }
     $response['info'] .= '</table>';
     ob_start();
     phpinfo();
     $phpinfo = ob_get_contents();
     ob_get_clean();
     $response['info'] .= \GO\Base\Util\String::sanitizeHtml($phpinfo);
     return $response;
 }
Example #3
0
 public static function toUtf8($string, $charset)
 {
     if (!\GO\Base\Util\String::is8bit($string, $charset)) {
         return $string;
     }
     //		$searches = array();
     //		$replaces = array();
     //		foreach (self::$map as $key => $values) {
     ////			if($key!='C1')
     ////				continue;
     //
     //			$replace = '';
     //			foreach ($values as $val)
     //				$replace.=self::unicodeToUtf8($val);
     //
     //			 $searches[] = chr(hexdec($key));
     //			//echo hexdec($key).' ';
     //			$replaces[] = $replace;
     //		}
     //		return str_replace($searches, $replaces, $string);
     $out = '';
     $len = strlen($string);
     for ($i = 0; $i < $len; $i++) {
         $hex = strtoupper(dechex(ord($string[$i])));
         if (isset(self::$map[$hex])) {
             foreach (self::$map[$hex] as $unicodeHex) {
                 $out .= self::unicodeToUtf8($unicodeHex);
             }
         } else {
             $out .= $string[$i];
         }
     }
     return $out;
 }
Example #4
0
 public static function inlinescripts()
 {
     $t = \GO::config()->get_setting('login_screen_text_enabled');
     if (!empty($t)) {
         $login_screen_text = \GO::config()->get_setting('login_screen_text');
         $login_screen_text_title = \GO::config()->get_setting('login_screen_text_title');
         echo 'GO.mainLayout.on("login", function(mainLayout){mainLayout.msg("' . \GO\Base\Util\String::escape_javascript($login_screen_text_title) . '", "' . \GO\Base\Util\String::escape_javascript($login_screen_text) . '", 3600, 400);});';
     }
 }
Example #5
0
 /**
  * Create a new reminder
  *
  * @param string $name The text that will appear in the reminder
  * @param int $time Unix timestamp
  * @param string $model_name Optional model name and model id so that the reminder links to the dialog.
  * @param int $model_id
  * @param int $vtime The time that will be displayed in the reminder
  * 
  * @return Reminder 
  */
 public static function newInstance($name, $time, $model_name = '', $model_id = 0, $vtime = null)
 {
     $r = new Reminder();
     $r->name = \GO\Base\Util\String::cut_string($name, 100);
     $r->time = $time;
     $r->vtime = $vtime;
     $r->model_type_id = \GO::getModel($model_name)->modelTypeId();
     $r->model_id = $model_id;
     $r->save();
     return $r;
 }
Example #6
0
 private function _convertUTF8($attr)
 {
     if (is_array($attr)) {
         $new = array();
         foreach ($attr as $key => $val) {
             $new[$key] = $this->_convertUTF8($val);
         }
     } else {
         $new = GO\Base\Util\String::clean_utf8($attr);
     }
     return $new;
 }
Example #7
0
 public static function mimeHeaderDecode($string, $defaultCharset = 'UTF-8')
 {
     /*
      * (=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)     (ab)
      *  White space between adjacent 'encoded-word's is not displayed.
      *
      *  http://www.faqs.org/rfcs/rfc2047.html
      */
     $string = preg_replace("/\\?=[\\s]*=\\?/", "?==?", $string);
     if (preg_match_all("/(=\\?[^\\?]+\\?(q|b)\\?[^\\?]+\\?=)/i", $string, $matches)) {
         foreach ($matches[1] as $v) {
             $fld = substr($v, 2, -2);
             $charset = strtolower(substr($fld, 0, strpos($fld, '?')));
             $fld = substr($fld, strlen($charset) + 1);
             $encoding = $fld[0];
             $fld = substr($fld, strpos($fld, '?') + 1);
             $fld = str_replace('_', '=20', $fld);
             if (strtoupper($encoding) == 'B') {
                 $fld = base64_decode($fld);
             } elseif (strtoupper($encoding) == 'Q') {
                 $fld = quoted_printable_decode($fld);
             }
             $fld = \GO\Base\Util\String::clean_utf8($fld, $charset);
             $string = str_replace($v, $fld, $string);
         }
     } elseif (($pos = strpos($string, "''")) && $pos < 64) {
         //check pos for not being to great
         //eg. iso-8859-1''%66%6F%73%73%2D%69%74%2D%73%6D%61%6C%6C%2E%67%69%66
         $charset = substr($string, 0, $pos);
         //			throw new \Exception($charset.' : '.substr($string, $pos+2));
         $string = rawurldecode(substr($string, $pos + 2));
         $string = \GO\Base\Util\String::clean_utf8($string, $charset);
     } else {
         $string = \GO\Base\Util\String::clean_utf8($string, $defaultCharset);
     }
     //		$string=\GO\Base\Util\String::clean_utf8($string);
     //\GO::debug($string);
     return str_replace(array('\\\\', '\\(', '\\)'), array('\\', '(', ')'), $string);
 }
Example #8
0
 private function _convertZipEncoding(\GO\Base\Fs\Folder $folder, $charset = 'CP850')
 {
     $items = $folder->ls();
     foreach ($items as $item) {
         if (!\GO\Base\Util\String::isUtf8($item->name())) {
             $item->rename(\GO\Base\Util\String::clean_utf8($item->name(), $charset));
         }
         if ($item->isFolder()) {
             $this->_convertZipEncoding($item, $charset);
         }
     }
 }
Example #9
0
 /**
  * A function that checks the consistency with the database.
  * Generally this is called by r=maintenance/checkDabase
  */
 public function checkDatabase()
 {
     //$this->save();
     echo "Checking " . (is_array($this->pk) ? implode(',', $this->pk) : $this->pk) . " " . $this->className() . "\n";
     flush();
     if ($this->aclField() && !$this->isJoinedAclField) {
         $acl = $this->acl;
         if (!$acl) {
             $this->setNewAcl();
         } else {
             $user_id = empty($this->user_id) ? 1 : $this->user_id;
             $acl->user_id = $user_id;
             $acl->description = $this->tableName() . '.' . $this->aclField();
             $acl->save();
         }
     }
     if ($this->hasFiles() && GO::modules()->isInstalled('files')) {
         //ACL must be generated here.
         $fc = new \GO\Files\Controller\FolderController();
         $this->files_folder_id = $fc->checkModelFolder($this);
     }
     //normalize crlf
     foreach ($this->columns as $field => $attr) {
         if (($attr['gotype'] == 'textfield' || $attr['gotype'] == 'textarea') && !empty($this->_attributes[$field])) {
             $this->{$field} = \GO\Base\Util\String::normalizeCrlf($this->_attributes[$field], "\n");
         }
     }
     //fill in empty required attributes that have defaults
     $defaults = $this->getDefaultAttributes();
     foreach ($this->columns as $field => $attr) {
         if ($attr['required'] && empty($this->{$field}) && isset($defaults[$field])) {
             $this->{$field} = $defaults[$field];
             echo "Setting default value " . $this->className() . ":" . $this->id . " {$field}=" . $defaults[$field] . "\n";
         }
     }
     if ($this->isModified()) {
         $this->save();
     }
 }
Example #10
0
 public function getPlainBody($asHtml = false, $noMaxBodySize = false)
 {
     $inlineImages = array();
     if (!isset($this->_plainBody)) {
         $imap = $this->getImapConnection();
         $this->_loadBodyParts();
         $this->_plainBody = '';
         if ($this->_plainParts['text_found']) {
             //check if we found a plain body
             foreach ($this->_plainParts['parts'] as $plainPart) {
                 if ($plainPart['type'] == 'text') {
                     if (!empty($this->_plainBody)) {
                         $this->_plainBody .= "\n";
                     }
                     $maxBodySize = $noMaxBodySize ? false : $this->maxBodySize;
                     $this->_plainBody .= $imap->get_message_part_decoded($this->uid, $plainPart['number'], $plainPart['encoding'], $plainPart['charset'], $this->peek, $maxBodySize);
                     $this->_bodyTruncated = $imap->max_read;
                 } else {
                     if ($asHtml) {
                         //we have to put in this tag and replace it after we convert the text to html. Otherwise this html get's convert into htmlspecialchars.
                         $this->_plainBody .= '{inline_' . count($inlineImages) . '}';
                         $attachment = $this->getAttachment($plainPart['number']);
                         if ($attachment) {
                             $attachment->content_id = 'go-autogen-' . $plainPart['number'];
                             $inlineImages[] = '<img alt="' . $plainPart['name'] . '" src="cid:' . $attachment->content_id . '" style="display:block;margin:10px 0;" />';
                         }
                     }
                 }
             }
         }
     } else {
         foreach ($this->_plainParts['parts'] as $plainPart) {
             if ($plainPart['type'] != 'text') {
                 if ($asHtml) {
                     $attachment = $this->getAttachment($plainPart['number']);
                     if ($attachment) {
                         $attachment->content_id = 'go-autogen-' . $plainPart['number'];
                         $inlineImages[] = '<img alt="' . $plainPart['name'] . '" src="cid:' . $attachment->content_id . '" style="display:block;margin:10px 0;" />';
                     }
                 }
             }
         }
     }
     $this->_plainBody = \GO\Base\Util\String::normalizeCrlf($this->_plainBody);
     $this->extractUuencodedAttachments($this->_plainBody);
     if ($asHtml) {
         $body = $this->_plainBody;
         $body = \GO\Base\Util\String::text_to_html($body);
         for ($i = 0, $max = count($inlineImages); $i < $max; $i++) {
             $body = str_replace('{inline_' . $i . '}', $inlineImages[$i], $body);
         }
         return $body;
     } else {
         if (empty($this->_plainBody)) {
             return $this->getHtmlBody(true, $noMaxBodySize);
         } else {
             return $this->_plainBody;
         }
     }
 }
Example #11
0
 public function formatDisplay($key, &$attributes, \GO\Customfields\Model\AbstractCustomFieldsRecord $model)
 {
     $prefix = !empty($this->field->prefix) ? $this->field->prefix . ' ' : '';
     $suffix = !empty($this->field->suffix) ? ' ' . $this->field->suffix : '';
     return $prefix . \GO\Base\Util\String::text_to_html($attributes[$key]) . $suffix;
 }
Example #12
0
<?php

$GO_SCRIPTS_JS .= 'GO.addressbook.lang.defaultSalutationExpression="' . \GO\Base\Util\String::escape_javascript(\GO::t('defaultSalutation', 'addressbook')) . '";';
$export_acl_id = \GO::config()->get_setting('go_addressbook_export', 0);
if (!$export_acl_id) {
    $acl = new \GO\Base\Model\Acl();
    $acl->description = 'addressbook_export';
    $acl->save();
    $export_acl_id = $acl->id;
    \GO::config()->save_setting('go_addressbook_export', $acl->id, 0);
}
$GO_SCRIPTS_JS .= 'GO.addressbook.export_acl_id="' . $export_acl_id . '";';
$acl_level = \GO\Base\Model\Acl::getUserPermissionLevel($export_acl_id, \GO::user()->id);
$GO_SCRIPTS_JS .= 'GO.addressbook.exportPermission="' . ($acl_level ? 1 : 0) . '";';
if (\GO::modules()->customfields) {
    $GO_SCRIPTS_JS .= '

	GO.customfields.settingsPanels={
		name: "' . \GO\Addressbook\Model\Contact::model()->localizedName . '",
		panels: []
	};' . "\n";
    $stmt = \GO\Users\Model\CfSettingTab::model()->getSettingTabs();
    while ($category = $stmt->fetch()) {
        $fields = array();
        $fstmt = $category->fields();
        while ($field = $fstmt->fetch()) {
            $fields[] = $field->toJsonArray();
        }
        // Makes global, client-side, editable form panels for every customfield category
        $GO_SCRIPTS_JS .= "\n\n" . 'GO.customfields.settingsPanels.panels.push({xtype : "customformpanel", itemId:"cf-panel-' . $category->id . '", category_id: ' . $category->id . ', title : "' . htmlspecialchars($category->name, ENT_QUOTES, 'UTF-8') . '", customfields : ' . json_encode($fields) . '});' . "\n";
    }
Example #13
0
 /**
  * Returns MIME fields contained in this class's instance as an associative
  * array.
  *
  * @param boolean $html Whether or not to return the HTML body. The alternative is
  * plain text. Defaults to true.
  *
  * @return Array
  */
 public function toOutputArray($html = true, $recipientsAsString = false, $noMaxBodySize = false, $useHtmlSpecialChars = true)
 {
     $from = $this->from->getAddresses();
     $response['notification'] = $this->disposition_notification_to;
     //seen is expensive because it can't be recovered from cache.
     // We'll use the grid to check if a message was seen or not.
     //$response['seen']=$this->seen;
     $from = $this->from->getAddress();
     $response['seen'] = $this->seen;
     $response['forwarded'] = $this->forwarded;
     $response['flagged'] = $this->flagged;
     $response['answered'] = $this->answered;
     $response['from'] = $from['personal'];
     $response['sender'] = $from['email'];
     $response['to'] = $recipientsAsString ? (string) $this->to : $this->_convertRecipientArray($this->to->getAddresses());
     $response['cc'] = $recipientsAsString ? (string) $this->cc : $this->_convertRecipientArray($this->cc->getAddresses());
     $response['bcc'] = $recipientsAsString ? (string) $this->bcc : $this->_convertRecipientArray($this->bcc->getAddresses());
     $response['reply_to'] = (string) $this->reply_to;
     $response['message_id'] = $this->message_id;
     $response['date'] = $this->date;
     $response['to_string'] = (string) $this->to;
     if (!$recipientsAsString && empty($response['to'])) {
         $response['to'][] = array('email' => '', 'personal' => \GO::t('no_recipients', 'email'));
     }
     $response['full_from'] = (string) $this->from;
     $response['priority'] = intval($this->x_priority);
     $response['udate'] = $this->udate;
     $response['date'] = \GO\Base\Util\Date::get_timestamp($this->udate);
     $response['size'] = $this->size;
     $labels = array();
     if (property_exists($this, 'account')) {
         $labels = \GO\Email\Model\Label::model()->getAccountLabels($this->account->id);
     }
     $response['labels'] = array();
     if (!empty($this->labels)) {
         foreach ($this->labels as $label) {
             if (isset($labels[$label])) {
                 $response['labels'][] = array('name' => $labels[$label]->name, 'color' => $labels[$label]->color);
             }
         }
     }
     $response['attachments'] = array();
     $response['zip_of_attachments_url'] = $this->getZipOfAttachmentsUrl();
     $response['inlineAttachments'] = array();
     if ($html) {
         $response['htmlbody'] = $this->getHtmlBody(false, $noMaxBodySize);
     } else {
         $response['plainbody'] = $this->getPlainBody(false, $noMaxBodySize);
     }
     if ($useHtmlSpecialChars) {
         $response['subject'] = htmlspecialchars($this->subject, ENT_COMPAT, 'UTF-8');
     } else {
         $response['subject'] = $this->subject;
     }
     $response['body_truncated'] = $this->bodyIsTruncated();
     $response['smime_signed'] = isset($this->content_type_attributes['smime-type']) && $this->content_type_attributes['smime-type'] == 'signed-data';
     $attachments = $this->getAttachments();
     foreach ($attachments as $att) {
         if ($html && $att->disposition != 'attachment') {
             if ($att->mime == 'text/html') {
                 $htmlPartStr = $att->getData();
                 $htmlPartStr = \GO\Base\Util\String::convertLinks($htmlPartStr);
                 $htmlPartStr = \GO\Base\Util\String::sanitizeHtml($htmlPartStr);
                 $response['htmlbody'] .= '<hr />' . $htmlPartStr;
                 continue;
             } else {
                 if ($att->mime == 'text/plain') {
                     $htmlPartStr = $att->getData();
                     $htmlPartStr = \GO\Base\Util\String::text_to_html($htmlPartStr);
                     $response['htmlbody'] .= '<hr />' . $htmlPartStr;
                     continue;
                 }
             }
         }
         $replaceCount = 0;
         $a = $att->getAttributes();
         //add unique token for detecting precense of inline attachment when we submit the message in handleFormInput
         $a['token'] = md5($a['tmp_file']);
         $a['url'] .= '&amp;token=' . $a['token'];
         if ($html && !empty($a['content_id'])) {
             $response['htmlbody'] = str_replace('cid:' . $a['content_id'], $a['url'], $response['htmlbody'], $replaceCount);
         }
         if ($a['name'] == 'smime.p7s') {
             $response['smime_signed'] = true;
             continue;
         }
         if (!$replaceCount) {
             $response['attachments'][] = $a;
         } else {
             $response['inlineAttachments'][] = $a;
         }
     }
     $response['contact_name'] = "";
     $response['contact_thumb_url'] = GO::config()->host . 'modules/addressbook/themes/Default/images/unknown-person.png';
     $response['blocked_images'] = 0;
     $response['xssDetected'] = false;
     $this->fireEvent('tooutputarray', array(&$response, $this));
     return $response;
 }
Example #14
0
 public function getExcerpt($maxLength = 100)
 {
     return $this->getEncrypted() ? GO::t('encryptedContent', 'notes') : GO\Base\Util\String::cut_string($this->content, $maxLength);
 }
Example #15
0
                                auto_list_rooms: true,
                                //auto_subscribe: true,
                                debug: false,
                                hide_muc_server: true,
                                i18n: locales["' . GO::language()->getLanguage() . '"], // Refer to ./locale/locales.js to see which locales are supported
                                show_controlbox_by_default: true,
                                xhr_user_search: false,
								jid: "' . GO::user()->username . '@puan.ddns.net",
								password: "******",
                                //fullname: "' . GO::user()->name . '"
								
								allow_registration: false
                });


		var name = converseJs.select("input.new-chatroom-name");
		name.value="conference.' . \GO\Chat\ChatModule::getXmppHost() . '";
			
		var nick = converseJs.select("input.new-chatroom-nick");
		nick.value="' . \GO\Base\Util\String::escape_javascript(GO::user()->name) . '";

});








';
Example #16
0
 private function _getParts($structure, $part_number_prefix = '')
 {
     if (isset($structure->parts)) {
         $structure->ctype_primary = strtolower($structure->ctype_primary);
         $structure->ctype_secondary = strtolower($structure->ctype_secondary);
         //$part_number=0;
         foreach ($structure->parts as $part_number => $part) {
             $part->ctype_primary = strtolower($part->ctype_primary);
             $part->ctype_secondary = strtolower($part->ctype_secondary);
             //text part and no attachment so it must be the body
             if ($structure->ctype_primary == 'multipart' && $structure->ctype_secondary == 'alternative' && $part->ctype_primary == 'text' && $part->ctype_secondary == 'plain') {
                 //check if html part is there
                 if ($this->_hasHtmlPart($structure)) {
                     continue;
                 }
             }
             if ($part->ctype_primary == 'text' && ($part->ctype_secondary == 'plain' || $part->ctype_secondary == 'html') && (!isset($part->disposition) || $part->disposition != 'attachment') && empty($part->d_parameters['filename'])) {
                 $charset = isset($part->ctype_parameters['charset']) ? $part->ctype_parameters['charset'] : 'UTF-8';
                 $body = \GO\Base\Util\String::clean_utf8($part->body, $charset);
                 if (stripos($part->ctype_secondary, 'plain') !== false) {
                     $body = nl2br($body);
                 } else {
                     $body = \GO\Base\Util\String::convertLinks($body);
                     $body = \GO\Base\Util\String::sanitizeHtml($body);
                     $body = $body;
                 }
                 $this->_loadedBody .= $body;
             } elseif ($part->ctype_primary == 'multipart') {
             } else {
                 //attachment
                 if (!empty($part->ctype_parameters['name'])) {
                     $filename = $part->ctype_parameters['name'];
                 } elseif (!empty($part->d_parameters['filename'])) {
                     $filename = $part->d_parameters['filename'];
                 } elseif (!empty($part->d_parameters['filename*'])) {
                     $filename = $part->d_parameters['filename*'];
                 } else {
                     $filename = uniqid(time());
                 }
                 $mime_type = $part->ctype_primary . '/' . $part->ctype_secondary;
                 if (isset($part->headers['content-id'])) {
                     $content_id = trim($part->headers['content-id']);
                     if (strpos($content_id, '>')) {
                         $content_id = substr($part->headers['content-id'], 1, strlen($part->headers['content-id']) - 2);
                     }
                 } else {
                     $content_id = '';
                 }
                 $f = new \GO\Base\Fs\File($filename);
                 $a = new MessageAttachment();
                 $a->name = $filename;
                 $a->number = $part_number_prefix . $part_number;
                 $a->content_id = $content_id;
                 $a->mime = $mime_type;
                 $tmp_file = new \GO\Base\Fs\File($this->_getTempDir() . $filename);
                 if (!empty($part->body)) {
                     $tmp_file = new \GO\Base\Fs\File($this->_getTempDir() . $filename);
                     if (!$tmp_file->exists()) {
                         $tmp_file->putContents($part->body);
                     }
                     $a->setTempFile($tmp_file);
                 }
                 $a->index = count($this->attachments);
                 $a->size = isset($part->body) ? strlen($part->body) : 0;
                 $a->encoding = isset($part->headers['content-transfer-encoding']) ? $part->headers['content-transfer-encoding'] : '';
                 $a->disposition = isset($part->disposition) ? $part->disposition : '';
                 $this->addAttachment($a);
             }
             //$part_number++;
             if (isset($part->parts)) {
                 $this->_getParts($part, $part_number_prefix . $part_number . '.');
             }
         }
     } elseif (isset($structure->body)) {
         $charset = isset($structure->ctype_parameters['charset']) ? $structure->ctype_parameters['charset'] : 'UTF-8';
         $text_part = \GO\Base\Util\String::clean_utf8($structure->body, $charset);
         //convert text to html
         if (stripos($structure->ctype_secondary, 'plain') !== false) {
             $this->extractUuencodedAttachments($text_part);
             $text_part = nl2br($text_part);
         } else {
             $text_part = \GO\Base\Util\String::convertLinks($text_part);
             $text_part = \GO\Base\Util\String::sanitizeHtml($text_part);
         }
         $this->_loadedBody .= $text_part;
     }
 }
Example #17
0
 /**
  * Before importing a contact in the database first check if the company name of this contact
  * Is a company that excists in the database. If not create a company. After this set the id
  * of the create company to the contact we insert.
  * 
  * If the email addres set to a contact does not validate. Remove it so import wont fail
  */
 protected function beforeImport($params, &$model, &$attributes, $record)
 {
     $impBasParams = json_decode($params['importBaseParams'], true);
     $addressbookId = $impBasParams['addressbook_id'];
     if (!empty($attributes['Company'])) {
         $companyName = $attributes['Company'];
     } else {
         if (!empty($attributes['company'])) {
             $companyName = $attributes['company'];
         } else {
             if (!empty($attributes['company_name'])) {
                 $companyName = $attributes['company_name'];
             } else {
                 if (!empty($attributes['companyName'])) {
                     $companyName = $attributes['companyName'];
                 } else {
                     if (!empty($attributes['name'])) {
                         $companyName = $attributes['name'];
                     }
                 }
             }
         }
     }
     if (!empty($companyName)) {
         $companyModel = \GO\Addressbook\Model\Company::model()->find(\GO\Base\Db\FindParams::newInstance()->single()->criteria(\GO\Base\Db\FindCriteria::newInstance()->addCondition('name', $companyName)->addCondition('addressbook_id', $addressbookId)));
         if (empty($companyModel)) {
             $companyModel = new \GO\Addressbook\Model\Company();
             $companyModel->setAttributes(array('name' => $companyName, 'addressbook_id' => $addressbookId));
             $companyModel->save();
         }
         $model->company_id = $companyModel->id;
     }
     if (isset($attributes['email']) && !\GO\Base\Util\String::validate_email($attributes['email'])) {
         unset($attributes['email']);
     }
     if (isset($attributes['email2']) && !\GO\Base\Util\String::validate_email($attributes['email2'])) {
         unset($attributes['email2']);
     }
     if (isset($attributes['email3']) && !\GO\Base\Util\String::validate_email($attributes['email3'])) {
         unset($attributes['email3']);
     }
     return parent::beforeImport($params, $model, $attributes, $record);
 }
Example #18
0
 /**
  * Add contacts to an addresslist.
  * @param type $params MUST contain addresslistId AND (EITHER senderNames and
  * senderEmails OR contactIds)
  * @return $response If there are email addresses that are not found in any
  * addressbook, the corresponding senders are registered in 
  * $response['unknownSenders'], and  $response['success'] becomes false, so
  * that the user can decide what to do with the unknown senders.
  */
 public function actionAddContactsToAddresslist($params)
 {
     $addresslistModel = \GO\Addressbook\Model\Addresslist::model()->findByPk($params['addresslistId']);
     $response = array('success' => true);
     $nAddedContacts = 0;
     if (!empty($params['contactIds'])) {
         // Only contact ids are sent from the client
         $contactIds = json_decode($params['contactIds']);
         foreach ($contactIds as $contactId) {
             $addresslistModel->addManyMany('contacts', $contactId);
         }
     } else {
         // email addresses and names are sent from the client
         $senderEmails = json_decode($params['senderEmails']);
         $senderNames = json_decode($params['senderNames']);
         $senders = array();
         // format: $senders[$senderEmail] = array('first_name'=>'Jack','middle_name'=>'','last_name'=>'Johnson');
         $unknownSenders = array();
         // format: $unknownSenders[$senderEmail] = array('first_name'=>'Jack','middle_name'=>'','last_name'=>'Johnson');
         // Create array of senders
         foreach ($senderEmails as $key => $senderEmail) {
             if (empty($senders[$senderEmail])) {
                 $senders[$senderEmail] = $senderNames[$key];
             }
         }
         foreach ($senders as $senderEmail => $senderNameArr) {
             $contactNameArr = \GO\Base\Util\String::split_name($senderNameArr);
             $contactStmt = \GO\Addressbook\Model\Contact::model()->find(\GO\Base\Db\FindParams::newInstance()->criteria(\GO\Base\Db\FindCriteria::newInstance()->addCondition('email', $senderEmail, '=', 't', false)->addCondition('email2', $senderEmail, '=', 't', false)->addCondition('email3', $senderEmail, '=', 't', false)));
             //->findSingleByAttribute('email', $senderEmail);
             if (empty($contactStmt) && empty($unknownSenders[$senderEmail])) {
                 // Keep track of contacts not found in database.
                 $unknownSenders[] = array('email' => $senderEmail, 'name' => $senderNameArr, 'first_name' => $contactNameArr['first_name'], 'middle_name' => $contactNameArr['middle_name'], 'last_name' => $contactNameArr['last_name']);
             } else {
                 // add contact to addresslist, but ensure only one email per addresslist
                 $emailAlreadyInAddresslist = false;
                 $linkableContactModel = false;
                 while ($contactModel = $contactStmt->fetch()) {
                     if ($addresslistModel->hasManyMany('contacts', $contactModel->id)) {
                         $emailAlreadyInAddresslist = true;
                     } else {
                         $linkableContactModel = $contactModel;
                     }
                 }
                 if (!empty($linkableContactModel) && !$emailAlreadyInAddresslist) {
                     $linkableContactModel->first_name = $contactNameArr['first_name'];
                     $linkableContactModel->middle_name = $contactNameArr['middle_name'];
                     $linkableContactModel->last_name = $contactNameArr['last_name'];
                     $linkableContactModel->save();
                     $addresslistModel->addManyMany('contacts', $linkableContactModel->id);
                     $nAddedContacts++;
                 }
             }
         }
         $response['addedSenders'] = $nAddedContacts;
         if (count($unknownSenders)) {
             $response['success'] = false;
             $response['unknownSenders'] = json_encode($unknownSenders);
             $response['addresslistId'] = $addresslistModel->id;
         }
     }
     return $response;
 }
Example #19
0
 /**
  * The link that can be send in an e-mail as download link.
  *
  * @return string
  */
 public function getEmailDownloadURL($html = true, $newExpireTime = false, $deleteWhenExpired = false)
 {
     if ($newExpireTime) {
         $this->random_code = \GO\Base\Util\String::randomPassword(11, 'a-z,A-Z,0-9');
         $this->expire_time = $newExpireTime;
         $this->delete_when_expired = $deleteWhenExpired;
         $this->save();
     }
     if (!empty($this->expire_time) && !empty($this->random_code)) {
         return \GO::url('files/file/download', array('id' => $this->id, 'random_code' => $this->random_code, 'inline' => 'false'), false, $html);
     }
 }
Example #20
0
 /**
  * Get's a message part and returned in binary form or UTF-8 charset.
  *
  * @param int $uid
  * @param string $part_no
  * @param stirng $encoding
  * @param string $charset
  * @param boolean $peek
  * @return string
  */
 public function get_message_part_decoded($uid, $part_no, $encoding, $charset = false, $peek = false, $cutofflength = false, $fp = false)
 {
     \GO::debug("get_message_part_decoded({$uid}, {$part_no}, {$encoding}, {$charset})");
     if ($encoding == 'uuencode') {
         return $this->_uudecode($uid, $part_no, $peek, $fp);
     }
     $str = '';
     $this->get_message_part_start($uid, $part_no, $peek);
     $leftOver = '';
     while ($line = $this->get_message_part_line()) {
         switch (strtolower($encoding)) {
             case 'base64':
                 $line = trim($leftOver . $line);
                 $leftOver = "";
                 if (strlen($line) % 4 == 0) {
                     if (!$fp) {
                         $str .= base64_decode($line);
                     } else {
                         fputs($fp, base64_decode($line));
                     }
                 } else {
                     $buffer = "";
                     while (strlen($line) > 4) {
                         $buffer .= substr($line, 0, 4);
                         $line = substr($line, 4);
                     }
                     if (!$fp) {
                         $str .= base64_decode($buffer);
                     } else {
                         fputs($fp, base64_decode($buffer));
                     }
                     if (strlen($line)) {
                         $leftOver = $line;
                     }
                 }
                 break;
             case 'quoted-printable':
                 if (!$fp) {
                     $str .= quoted_printable_decode($line);
                 } else {
                     fputs($fp, quoted_printable_decode($line));
                 }
                 break;
             default:
                 if (!$fp) {
                     $str .= $line;
                 } else {
                     fputs($fp, $line);
                 }
                 break;
         }
         if ($cutofflength && strlen($line) > $cutofflength) {
             break;
         }
     }
     if (!empty($leftOver)) {
         \GO::debug($leftOver);
         if (!$fp) {
             $str .= base64_decode($leftOver);
         } else {
             fputs($fp, base64_decode($leftOver));
         }
     }
     if ($charset) {
         //some clients don't send the charset.
         if ($charset == 'us-ascii') {
             $charset = 'windows-1252';
         }
         $str = \GO\Base\Util\String::clean_utf8($str, $charset);
         if ($charset != 'utf-8') {
             $str = str_replace($charset, 'utf-8', $str);
         }
     }
     return $fp ? true : $str;
     //		return $this->decode_message_part(
     //						$this->get_message_part($uid, $part_no, $peek, $cutofflength),
     //						$encoding,
     //						$charset
     //		);
 }
Example #21
0
 /**
  * Adds the current buffers to the addresses array
  *
  * @access private
  * @return void
  */
 private function _addBuffer()
 {
     $this->_buffer = trim($this->_buffer);
     if (!empty($this->_personal) && empty($this->_buffer)) {
         $this->_buffer = 'noaddress';
     }
     if (!empty($this->_buffer)) {
         if ($this->strict && !\GO\Base\Util\String::validate_email($this->_buffer)) {
             throw new \Exception("Address " . $this->_buffer . " is not valid");
         } else {
             $this->addRecipient($this->_buffer, $this->_personal);
         }
     }
     $this->_buffer = '';
     $this->_personal = false;
     $this->_emailFound = false;
     $this->_quote = false;
 }
 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);
         }
     }
 }
Example #23
0
				GO.customfields.types["' . String::escape_javascript($model->extendsModel()) . '"]={
					name: "' . \GO::getModel($model->extendsModel())->localizedName . '",
					panels: []
				};' . "\n";
                $stmt = \GO\Customfields\Model\Category::model()->findByModel($model->extendsModel());
                while ($category = $stmt->fetch()) {
                    $fields = array();
                    $fstmt = $category->fields();
                    while ($field = $fstmt->fetch()) {
                        $fields[] = $field->toJsonArray();
                    }
                    // Makes global, client-side, editable form panels for every customfield category
                    if ($category->checkPermissionLevel(\GO\Base\Model\Acl::WRITE_PERMISSION)) {
                        $GO_SCRIPTS_JS .= "\n\n" . 'GO.customfields.types["' . String::escape_javascript($model->extendsModel()) . '"].panels.push({xtype : "customformpanel", itemId:"cf-panel-' . $category->id . '", category_id: ' . $category->id . ', title : "' . htmlspecialchars($category->name, ENT_QUOTES, 'UTF-8') . '", customfields : ' . json_encode($fields) . '});' . "\n";
                    }
                    /**
                     * Registers customfield column information in a global, client-side object, ordered by model.
                     * Also, this loop ensures that every customfield data being used has such information
                     * described in a global, client-side object, ordered by customfield id.
                     */
                    foreach ($fields as $field) {
                        $align = $field['datatype'] == 'GO\\Customfields\\Customfieldtype\\Number' || $field['datatype'] == 'GO\\Customfields\\Customfieldtype\\Date' || $field['datatype'] == 'GO\\Customfields\\Customfieldtype\\Datetime' ? 'right' : 'left';
                        $exclude_from_grid = $field['exclude_from_grid'] || $field['datatype'] == 'GO\\Customfields\\Customfieldtype\\Heading' ? 'true' : 'false';
                        $GO_SCRIPTS_JS .= 'GO.customfields.columns["' . String::escape_javascript($model->extendsModel()) . '"].push({' . 'header: "' . \GO\Base\Util\String::escape_javascript($field['name']) . '",' . 'dataIndex: "' . $field['dataname'] . '" ,' . 'datatype:"' . \GO\Base\Util\String::escape_javascript($field['datatype']) . '", ' . 'align:"' . $align . '", ' . 'sortable:true,' . 'id: "' . $field['dataname'] . '",' . 'customfield_id: "' . $field['id'] . '",' . 'nesting_level: "' . $field['nesting_level'] . '",' . 'exclude_from_grid: "' . $exclude_from_grid . '",' . 'hidden:true});' . "\n" . 'GO.customfields.columnMap["' . $field['dataname'] . '"]=GO.customfields.columns["' . String::escape_javascript($model->extendsModel()) . '"][GO.customfields.columns["' . String::escape_javascript($model->extendsModel()) . '"].length-1];' . "\n";
                    }
                }
            }
        }
    }
}
Example #24
0
    /**
     * handleEmailFormInput
     * 
     * This method can be used in Models and Controllers. It puts the email body
     * and inline (image) attachments from the client in the message, which can
     * then be used for storage in the database or sending emails.
     * 
     * @param Array $params Must contain elements: body (string) and
     * 
     * inlineAttachments (string).
     */
    public function handleEmailFormInput($params)
    {
        if (!empty($params['subject'])) {
            $this->setSubject($params['subject']);
        }
        if (!empty($params['to'])) {
            $to = new EmailRecipients($params['to']);
            foreach ($to->getAddresses() as $email => $personal) {
                $this->addTo($email, $personal);
            }
        }
        if (!empty($params['cc'])) {
            $cc = new EmailRecipients($params['cc']);
            foreach ($cc->getAddresses() as $email => $personal) {
                $this->addCc($email, $personal);
            }
        }
        if (!empty($params['bcc'])) {
            $bcc = new EmailRecipients($params['bcc']);
            foreach ($bcc->getAddresses() as $email => $personal) {
                $this->addBcc($email, $personal);
            }
        }
        if (isset($params['alias_id'])) {
            $alias = \GO\Email\Model\Alias::model()->findByPk($params['alias_id']);
            $this->setFrom($alias->email, $alias->name);
            if (!empty($params['notification'])) {
                $this->setReadReceiptTo(array($alias->email => $alias->name));
            }
        }
        if (isset($params['priority'])) {
            $this->setPriority($params['priority']);
        }
        if (isset($params['in_reply_to'])) {
            $headers = $this->getHeaders();
            $headers->addTextHeader('In-Reply-To', $params['in_reply_to']);
            $headers->addTextHeader('References', $params['in_reply_to']);
        }
        if ($params['content_type'] == 'html') {
            $params['htmlbody'] = $this->_embedPastedImages($params['htmlbody']);
            //inlineAttachments is an array(array('url'=>'',tmp_file=>'relative/path/');
            if (!empty($params['inlineAttachments'])) {
                $inlineAttachments = json_decode($params['inlineAttachments']);
                /* inline attachments must of course exist as a file, and also be used in
                 * the message body
                 */
                if (count($inlineAttachments)) {
                    foreach ($inlineAttachments as $ia) {
                        //$tmpFile = new \GO\Base\Fs\File(\GO::config()->tmpdir.$ia['tmp_file']);
                        if (empty($ia->tmp_file)) {
                            continue;
                            // Continue to the next inline attachment for processing.
                            //throw new Exception("No temp file for inline attachment ".$ia->name);
                        }
                        $path = empty($ia->from_file_storage) ? \GO::config()->tmpdir . $ia->tmp_file : \GO::config()->file_storage_path . $ia->tmp_file;
                        $tmpFile = new \GO\Base\Fs\File($path);
                        if ($tmpFile->exists()) {
                            //Different browsers reformat URL's to absolute or relative. So a pattern match on the filename.
                            //$filename = rawurlencode($tmpFile->name());
                            $result = preg_match('/="([^"]*' . preg_quote($ia->token) . '[^"]*)"/', $params['htmlbody'], $matches);
                            if ($result) {
                                $img = \Swift_EmbeddedFile::fromPath($tmpFile->path());
                                $img->setContentType($tmpFile->mimeType());
                                $contentId = $this->embed($img);
                                //$tmpFile->delete();
                                $params['htmlbody'] = \GO\Base\Util\String::replaceOnce($matches[1], $contentId, $params['htmlbody']);
                            } else {
                                //this may happen when an inline image was attached but deleted in the editor afterwards.
                                //
                                //throw new \Exception("Error: inline attachment could not be found in text: ".$ia->token);
                            }
                        } else {
                            throw new \Exception("Error: inline attachment missing on server: " . $tmpFile->stripTempPath() . ".<br /><br />The temporary files folder is cleared on each login. Did you relogin?");
                        }
                    }
                }
            }
            $params['htmlbody'] = $this->_fixRelativeUrls($params['htmlbody']);
            $htmlTop = '<html>
<head>
<style type="text/css">
body,p,td,div,span{
	' . \GO::config()->html_editor_font . '
};
body p{
	margin:0px;
}
</style>
</head>
<body>';
            $htmlBottom = '</body></html>';
            $this->setHtmlAlternateBody($htmlTop . $params['htmlbody'] . $htmlBottom);
        } else {
            $this->setBody($params['plainbody'], 'text/plain');
        }
        if (!empty($params['attachments'])) {
            $attachments = json_decode($params['attachments']);
            foreach ($attachments as $att) {
                $path = empty($att->from_file_storage) ? \GO::config()->tmpdir . $att->tmp_file : \GO::config()->file_storage_path . $att->tmp_file;
                $tmpFile = new \GO\Base\Fs\File($path);
                if ($tmpFile->exists()) {
                    $file = \Swift_Attachment::fromPath($tmpFile->path());
                    $file->setContentType($tmpFile->mimeType());
                    $file->setFilename($att->fileName);
                    $this->attach($file);
                    //$tmpFile->delete();
                } else {
                    throw new \Exception("Error: attachment missing on server: " . $tmpFile->stripTempPath() . ".<br /><br />The temporary files folder is cleared on each login. Did you relogin?");
                }
            }
        }
    }
Example #25
0
 private function _checkXSS($params, $response)
 {
     if (!empty($params['filterXSS'])) {
         $response['htmlbody'] = \GO\Base\Util\String::filterXSS($response['htmlbody']);
     } elseif (\GO\Base\Util\String::detectXSS($response['htmlbody'])) {
         $response['htmlbody'] = GO::t('xssMessageHidden', 'email');
         $response['xssDetected'] = true;
     } else {
         $response['xssDetected'] = false;
     }
     return $response;
 }
Example #26
0
 public static function read($data, $options = 0)
 {
     //parsing of rrule is done by GO. SabreDAV fails on vcalendar 1.0 rrules
     //
     if (strpos($data, "VERSION:1.0")) {
         Sabre\VObject\Component\VCalendar::$propertyMap['RRULE'] = 'Sabre\\VObject\\Property\\Text';
         //Workaround funambol bug
         $data = str_replace("RRULE;ENCODING=QUOTED-PRINTABLE", "RRULE;", $data);
     }
     //remove quoted printable line breaks
     $data = \GO\Base\Util\String::normalizeCrlf($data, "\n");
     if (strpos($data, 'QUOTED-PRINTABLE')) {
         $data = str_replace("=\n", "", $data);
     }
     //workaround for funambol bug
     $data = str_replace('EXDATE: ', 'EXDATE:', $data);
     $options = \Sabre\VObject\Reader::OPTION_FORGIVING + \Sabre\VObject\Reader::OPTION_IGNORE_INVALID_LINES;
     return parent::read($data, $options);
 }
Example #27
0
 /**
  * Remove the invalid emails from records to be imported
  */
 protected function beforeImport($params, &$model, &$attributes, $record)
 {
     if (isset($attributes['email']) && !\GO\Base\Util\String::validate_email($attributes['email'])) {
         unset($attributes['email']);
     }
     return parent::beforeImport($params, $model, $attributes, $record);
 }
Example #28
0
 protected function init()
 {
     $this->columns['addressbook_id']['required'] = true;
     $this->columns['email']['regex'] = \GO\Base\Util\String::get_email_validation_regex();
     $this->columns['invoice_email']['regex'] = \GO\Base\Util\String::get_email_validation_regex();
     //
     //		$this->columns['phone']['gotype']='phone';
     //		$this->columns['fax']['gotype']='phone';
     return parent::init();
 }
Example #29
0
 /**
  * Convert and clean the file to ensure it has valid UTF-8 data.
  * 
  * @return boolean 
  */
 public function convertToUtf8()
 {
     if (!$this->isWritable()) {
         return false;
     }
     $str = $this->getContents();
     if (!$str) {
         return false;
     }
     $enc = $this->detectEncoding($str);
     if (!$enc) {
         $enc = 'UTF-8';
     }
     $bom = pack("CCC", 0xef, 0xbb, 0xbf);
     if (0 == strncmp($str, $bom, 3)) {
         //echo "BOM detected - file is UTF-8\n";
         $str = substr($str, 3);
     }
     return $this->putContents(\GO\Base\Util\String::clean_utf8($str, $enc));
 }
Example #30
0
 /**
  * Get the event in HTML markup
  * 
  * @todo Add recurrence info
  * @return string 
  */
 public function toHtml()
 {
     $html = '<table id="event-' . $this->uuid . '">' . '<tr><td>' . \GO::t('subject', 'calendar') . ':</td>' . '<td>' . $this->name . '</td></tr>';
     if ($this->calendar) {
         $html .= '<tr><td>' . \GO::t('calendar', 'calendar') . ':</td>' . '<td>' . $this->calendar->name . '</td></tr>';
     }
     $html .= '<tr><td>' . \GO::t('startsAt', 'calendar') . ':</td>' . '<td>' . \GO\Base\Util\Date::get_timestamp($this->start_time, empty($this->all_day_event)) . '</td></tr>' . '<tr><td>' . \GO::t('endsAt', 'calendar') . ':</td>' . '<td>' . \GO\Base\Util\Date::get_timestamp($this->end_time, empty($this->all_day_event)) . '</td></tr>';
     $html .= '<tr><td>' . \GO::t('status', 'calendar') . ':</td>' . '<td>' . $this->getLocalizedStatus() . '</td></tr>';
     if (!empty($this->location)) {
         $html .= '<tr><td style="vertical-align:top">' . \GO::t('location', 'calendar') . ':</td>' . '<td>' . \GO\Base\Util\String::text_to_html($this->location) . '</td></tr>';
     }
     if (!empty($this->description)) {
         $html .= '<tr><td style="vertical-align:top">' . \GO::t('strDescription') . ':</td>' . '<td>' . \GO\Base\Util\String::text_to_html($this->description) . '</td></tr>';
     }
     if ($this->isRecurring()) {
         $html .= '<tr><td colspan="2">' . $this->getRecurrencePattern()->getAsText() . '</td></tr>';
     }
     //don't calculate timezone offset for all day events
     //		$timezone_offset_string = \GO\Base\Util\Date::get_timezone_offset($this->start_time);
     //
     //		if ($timezone_offset_string > 0) {
     //			$gmt_string = '(\G\M\T +' . $timezone_offset_string . ')';
     //		} elseif ($timezone_offset_string < 0) {
     //			$gmt_string = '(\G\M\T -' . $timezone_offset_string . ')';
     //		} else {
     //			$gmt_string = '(\G\M\T)';
     //		}
     //$html .= '<tr><td colspan="2">&nbsp;</td></tr>';
     $cfRecord = $this->getCustomfieldsRecord();
     if (!empty($cfRecord)) {
         $columns = $cfRecord->getColumns();
         foreach ($columns as $column) {
             if (isset($column['customfield'])) {
                 $colId = $column['customfield']->id;
                 $colId = 'col_' . $colId;
                 $recordAttributes = $cfRecord->getAttributes();
                 if (!empty($recordAttributes[$colId])) {
                     $colValue = $cfRecord->getAttribute($column['customfield']->name);
                     $html .= '<tr><td style="vertical-align:top">' . $column['customfield']->name . '</td>' . '<td>' . $recordAttributes[$colId] . '</td></tr>';
                 }
             }
         }
     }
     $html .= '</table>';
     $stmt = $this->participants();
     if ($stmt->rowCount()) {
         $html .= '<table>';
         $html .= '<tr><td colspan="3"><br /></td></tr>';
         $html .= '<tr><td><b>' . \GO::t('participant', 'calendar') . '</b></td><td><b>' . \GO::t('status', 'calendar') . '</b></td><td><b>' . \GO::t('organizer', 'calendar') . '</b></td></tr>';
         while ($participant = $stmt->fetch()) {
             $html .= '<tr><td>' . $participant->name . '&nbsp;</td><td>' . $participant->statusName . '&nbsp;</td><td>' . ($participant->is_organizer ? \GO::t('yes') : '') . '</td></tr>';
         }
         $html .= '</table>';
     }
     return $html;
 }