/** * Final submission * * @return void */ public function submitTask() { // Incoming $id = Request::getInt('id', 0); // Ensure we have an ID to work with if (!$id) { throw new Exception(Lang::txt('COM_CONTRIBUTE_NO_ID'), 500); } // Load resource info $resource = new Resource($this->database); $resource->load($id); // Set a flag for if the resource was already published or not $published = 0; if ($resource->published != 2) { $published = 1; } // Check if a newly submitted resource was authorized to be published $authorized = Request::getInt('authorization', 0); if (!$authorized && !$published) { $this->setError(Lang::txt('COM_CONTRIBUTE_CONTRIBUTION_NOT_AUTHORIZED')); $this->_checkProgress($id); $this->step_review(); return; } // Is this a newly submitted resource? if (!$published) { // 0 = unpublished, 1 = published, 2 = composing, 3 = pending (submitted), 4 = deleted // Are submissions auto-approved? if ($this->config->get('autoapprove') == 1) { //checks if autoapproved content has children (configurable in options on backend) if ($this->config->get('autoapprove_content_check') == 1) { require_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'resource.php'; $item = new \Components\Resources\Models\Resource($id); if (count($item->children()) < 1) { $this->setError(Lang::txt('COM_CONTRIBUTE_NO_CONTENT')); $this->step_review(); return; } } // Set status to published $resource->published = 1; $resource->publish_up = Date::toSql(); } else { $apu = $this->config->get('autoapproved_users'); $apu = explode(',', $apu); $apu = array_map('trim', $apu); if (in_array(User::get('username'), $apu)) { // Set status to published $resource->published = 1; $resource->publish_up = Date::toSql(); } else { // Set status to pending review (submitted) $resource->published = 3; } } // Get the resource's contributors $helper = new Helper($id, $this->database); $helper->getCons(); $contributors = $helper->_contributors; if (!$contributors || count($contributors) <= 0) { $this->setError(Lang::txt('COM_CONTRIBUTE_CONTRIBUTION_HAS_NO_AUTHORS')); $this->_checkProgress($id); $this->step_review(); return; } // Get any set emails that should be notified of ticket submission $defs = explode(',', $this->config->get('email_when_submitted', '{config.mailfrom}')); if (!empty($defs)) { $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_RESOURCES_EMAIL_SUBJECT_NEW_SUBMISSION', $resource->id)); $message->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_option))); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'submitted_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->resource = $resource; $eview->delimiter = ''; $plain = $eview->loadTemplate(); $plain = str_replace("\n", "\r\n", $plain); $message->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('submitted_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $message->addPart($html, 'text/html'); // Loop through the addresses foreach ($defs as $def) { $def = trim($def); // Check if the address should come from config if ($def == '{config.mailfrom}') { $def = Config::get('mailfrom'); } // Check for a valid address if (\Hubzero\Utility\Validate::email($def)) { // Send e-mail $message->setTo(array($def)); $message->send(); } } } } // Is this resource licensed under Creative Commons? if ($this->config->get('cc_license')) { $license = Request::getVar('license', ''); if ($license == 'custom') { $license .= $resource->id; $licenseText = Request::getVar('license-text', ''); if ($licenseText == '[ENTER LICENSE HERE]') { $this->setError(Lang::txt('Please enter a license.')); $this->_checkProgress($id); $this->step_review(); return; } include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'license.php'; $rl = new License($this->database); $rl->load($license); $rl->name = $license; $rl->text = $licenseText; $rl->info = $resource->id; $rl->check(); $rl->store(); } // set license $params = new \Hubzero\Config\Registry($resource->params); $params->set('license', $license); $resource->params = $params->toString(); } // Save and checkin the resource $resource->store(); $resource->checkin(); // If a previously published resource, redirect to the resource page if ($published == 1) { if ($resource->alias) { $url = Route::url('index.php?option=com_resources&alias=' . $resource->alias); } else { $url = Route::url('index.php?option=com_resources&id=' . $resource->id); } App::redirect($url); return; } // Output HTML $this->setView($this->_controller, 'thanks'); $this->view->title = $this->_title; $this->view->config = $this->config; $this->view->resource = $resource; foreach ($this->getErrors() as $error) { $this->view->setError($error); } $this->view->display(); }
/** * Email * * @param string $email * @param string $subject * @param string $body * @param array $from * @return void */ public static function email($email, $subject, $body, $from) { if ($from) { $body_plain = is_array($body) && isset($body['plaintext']) ? $body['plaintext'] : $body; $body_html = is_array($body) && isset($body['multipart']) ? $body['multipart'] : NULL; $message = new \Hubzero\Mail\Message(); $message->setSubject($subject)->addTo($email, $email)->addFrom($from['email'], $from['name'])->setPriority('normal'); $message->addPart($body_plain, 'text/plain'); if ($body_html) { $message->addPart($body_html, 'text/html'); } if ($message->send()) { return true; } } return false; }
/** * Email instructor course digest * * @param object $job \Components\Cron\Models\Job * @return boolean */ public function emailInstructorDigest(\Components\Cron\Models\Job $job) { $database = \App::get('db'); $cconfig = Component::params('com_courses'); Lang::load('com_courses') || Lang::load('com_courses', PATH_CORE . DS . 'components' . DS . 'com_courses' . DS . 'site'); $from = array('name' => Config::get('sitename') . ' ' . Lang::txt('COM_COURSES'), 'email' => Config::get('mailfrom')); $subject = Lang::txt('COM_COURSES') . ': ' . Lang::txt('COM_COURSES_SUBJECT_EMAIL_DIGEST'); require_once PATH_CORE . DS . 'components' . DS . 'com_courses' . DS . 'models' . DS . 'courses.php'; $course_id = 0; $params = $job->get('params'); if (isset($params) && is_object($params)) { $course_id = $params->get('course'); } $coursesObj = new \Components\Courses\Models\Courses(); if ($course_id) { $courses = array($coursesObj->course($course_id)); } else { $courses = $coursesObj->courses(); } if (isset($courses) && count($courses) > 0) { foreach ($courses as $course) { if (!$course->isAvailable()) { continue; } $mailed = array(); $managers = $course->managers(); $enrollments = $course->students(array('count' => true)); $offerings = $course->offerings(); if (isset($offerings) && count($offerings) > 0) { foreach ($offerings as $offering) { if (!$offering->isAvailable()) { continue; } $offering->gradebook()->refresh(); $passing = $offering->gradebook()->countPassing(false); $failing = $offering->gradebook()->countFailing(false); if (isset($managers) && count($managers) > 0) { foreach ($managers as $manager) { // Get the user's account $user = User::getInstance($manager->get('user_id')); if (!$user->get('id')) { continue; } // Try to ensure no duplicates if (in_array($user->get('username'), $mailed)) { continue; } // Only mail instructors (i.e. not managers) if ($manager->get('role_alias') != 'instructor') { continue; } // Get discussion stats and posts require_once PATH_CORE . DS . 'components' . DS . 'com_forum' . DS . 'tables' . DS . 'post.php'; $postsTbl = new \Components\Forum\Tables\Post($database); $filters = array('scope' => 'course', 'scope_id' => $offering->get('id'), 'state' => 1, 'sort' => 'created', 'sort_Dir' => 'DESC', 'limit' => 100); $posts = $postsTbl->find($filters); $posts_cnt = count($posts); $latest = array(); $latest_cnt = 0; if (isset($posts) && $posts_cnt > 0) { foreach ($posts as $post) { if (strtotime($post->created) > strtotime('-1 day')) { $latest[] = $post; } else { break; } } $latest_cnt = count($latest); } $eview = new \Hubzero\Component\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_courses' . DS . 'site', 'name' => 'emails', 'layout' => 'digest_plain')); $eview->option = 'com_courses'; $eview->controller = 'courses'; $eview->delimiter = '~!~!~!~!~!~!~!~!~!~!'; $eview->course = $course; $eview->enrollments = $enrollments; $eview->passing = $passing; $eview->failing = $failing; $eview->offering = $offering; $eview->posts_cnt = $posts_cnt; $eview->latest = $latest; $eview->latest_cnt = $latest_cnt; $plain = $eview->loadTemplate(); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('digest_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // Build message $message = new \Hubzero\Mail\Message(); $message->setSubject($subject)->addFrom($from['email'], $from['name'])->addTo($user->get('email'), $user->get('name'))->addHeader('X-Component', 'com_courses')->addHeader('X-Component-Object', 'courses_instructor_digest'); $message->addPart($plain, 'text/plain'); $message->addPart($html, 'text/html'); // Send mail if (!$message->send()) { $this->setError('Failed to mail %s', $user->get('email')); } $mailed[] = $user->get('username'); } } } } } } return true; }
public function emailOrderComplete($transactionInfo) { $params = Component::params(Request::getVar('option')); $items = unserialize($transactionInfo->tiItems); //print_r($items); die; // Build emails // Build order summary $summary = 'Order number: ' . $transactionInfo->tId . "\n\n"; $summary .= "\n====================\n\n"; $summary .= 'Subtotal: ' . '$' . number_format($transactionInfo->tiSubtotal, 2) . "\n"; if (!$transactionInfo->tiShipping) { $transactionInfo->tiShipping = 0; } if ($transactionInfo->tiShipping > 0) { $summary .= 'Shipping and handling: ' . '$' . number_format($transactionInfo->tiShipping, 2) . "\n"; } if (!$transactionInfo->tiTax) { $transactionInfo->tiTax = 0; } if ($transactionInfo->tiDiscounts > 0 || $transactionInfo->tiShippingDiscount > 0) { $summary .= 'Discounts: ' . '$' . number_format($transactionInfo->tiDiscounts + $transactionInfo->tiShippingDiscount, 2) . "\n"; } if ($transactionInfo->tiTax > 0) { $summary .= 'Tax: ' . '$' . number_format($transactionInfo->tiTax, 2) . "\n"; } $summary .= 'Total: ' . '$' . number_format($transactionInfo->tiTotal, 2) . "\n"; if (!empty($transactionInfo->tiShippingToFirst)) { $summary .= "\n\nShipping address:"; $summary .= "\n--------------------\n"; $summary .= $transactionInfo->tiShippingToFirst . ' ' . $transactionInfo->tiShippingToLast . "\n"; $summary .= $transactionInfo->tiShippingAddress . "\n"; $summary .= $transactionInfo->tiShippingCity . ', ' . $transactionInfo->tiShippingState . ' ' . $transactionInfo->tiShippingZip . "\n"; } $summary .= "\n\nItems ordered:"; $summary .= "\n--------------------\n"; require_once PATH_CORE . DS . 'components' . DS . 'com_storefront' . DS . 'models' . DS . 'Warehouse.php'; $warehouse = new \Components\Storefront\Models\Warehouse(); foreach ($items as $k => $item) { $itemInfo = $item['info']; $cartInfo = $item['cartInfo']; $itemMeta = $item['meta']; //print_r($item); die; $productType = $warehouse->getProductTypeInfo($itemInfo->ptId)['ptName']; // If course, generate a link to the course $action = false; if ($productType == 'Course') { $action = ' Go to the course page at: ' . ($action .= Route::url('index.php?option=com_courses', true, -1) . $itemMeta['courseId'] . '/' . $itemMeta['offeringId']); } elseif ($productType == 'Software Download') { $action = ' Download at: ' . ($action .= Route::url('index.php?option=com_cart', true, -1) . 'download/' . $transactionInfo->tId . '/' . $itemInfo->sId); if (isset($itemMeta['serial']) && !empty($itemMeta['serial'])) { $action .= "\n\t"; $action .= " Serial number: " . $itemMeta['serial']; } } $summary .= "{$cartInfo->qty} x "; $summary .= "{$itemInfo->pName}"; if (!empty($item['options'])) { $summary .= '('; $optionCount = 0; foreach ($item['options'] as $option) { if ($optionCount) { $summary .= ', '; } $summary .= $option; $optionCount++; } $summary .= ')'; } $summary .= ' @ ' . '$' . number_format($itemInfo->sPrice, 2); if ($action) { $summary .= "\n\t"; $summary .= $action; } $summary .= "\n"; } //print_r($summary); die; // Get message plugin JPluginHelper::importPlugin('xmessage'); // "from" info $from = array(); $from['name'] = Config::get('sitename'); $from['email'] = Config::get('mailfrom'); // Email to admin $adminEmail = "There is a new online store order: \n\n"; $adminEmail .= $summary; // Admin email $to = array($params->get('storeAdminId')); Event::trigger('onSendMessage', array('store_notifications', 'New order at ' . $from['name'], $adminEmail, $from, $to, '', null, '', 0, true)); // Email to client $clientEmail = 'Thank you for your order at ' . Config::get('sitename') . "!\n\n"; $clientEmail .= $summary; require_once dirname(dirname(__DIR__)) . DS . 'models' . DS . 'Cart.php'; $to = array(\Components\Cart\Models\Cart::getCartUser($transactionInfo->crtId)); Event::trigger('onSendMessage', array('store_notifications', 'Your order at ' . $from['name'], $clientEmail, $from, $to, '', null, '', 0, true)); // Email notification extra $notifyTo = $params->get('sendNotificationTo'); if (!empty($notifyTo)) { $notifyTo = explode(',', str_replace(' ', '', $notifyTo)); $notifyEmail = 'There is a new online store order at ' . Config::get('sitename') . "\n\n"; $notifyEmail .= $summary; // Plain text email $eview = new \Hubzero\Component\View(array('name' => 'emails', 'layout' => 'order_notify')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->message = $notifyEmail; $plain = $eview->loadTemplate(); $plain = str_replace("\n", "\r\n", $plain); $message = new \Hubzero\Mail\Message(); $message->setSubject('ORDER NOTIFICATION: New order at ' . $from['name']); $message->addFrom(Config::get('mailfrom'), Config::get('sitename')); $message->addPart($plain, 'text/plain'); foreach ($notifyTo as $email) { if (\Hubzero\Utility\Validate::email($email)) { $message->addTo($email); } } $message->setBody($plain); $message->send(); } }
/** * Send an email * * @param string $to * @param array $from * @param string $subject * @param string $body * @return boolean */ private function _sendEmail($to, $from, $subject, $body) { // create message object $message = new \Hubzero\Mail\Message(); // set message details and send $message->setSubject($subject)->addFrom($from['email'], $from['name'])->setTo($to)->addPart($body, 'text/plain')->addHeader('X-Component', 'com_groups')->addHeader('X-Component-Object', 'Group Calendar Event Registration')->send(); // add good return true; }
/** * Close tickets in a specified state * * @return boolean */ public function onAfterRepositoryUpdate() { $database = App::get('db'); $sconfig = Component::params('com_support'); $open = 0; $status = $this->params->get('support_ticket_closed', 0); $status = $status == '-1' ? 0 : $status; if ($status) { include_once PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'tables' . DS . 'status.php'; $st = new \Components\Support\Tables\Status($database); $st->load($status); $open = $st->open; } $slc = "SELECT id, login, email, name FROM `#__support_tickets` AS t"; $upd = "UPDATE `#__support_tickets` AS t SET t.`open`=" . $database->quote($open) . ", t.`status`=" . $database->quote($status) . ", t.`closed`=" . $database->quote(Date::toSql()); $where = array(); $where[] = "t.`type`=0"; $where[] = "t.`open`=1"; // Gather a list of statuses $statuses = array(); if (is_numeric($this->params->get('support_ticket_state1'))) { $statuses[] = $this->params->get('support_ticket_state1'); } if (is_numeric($this->params->get('support_ticket_state2'))) { $statuses[] = $this->params->get('support_ticket_state2'); } if (is_numeric($this->params->get('support_ticket_state3'))) { $statuses[] = $this->params->get('support_ticket_state3'); } if (count($statuses)) { $where[] = "t.`status` IN (" . implode(',', $statuses) . ")"; } // Only tickets for a specified group? if ($group = $this->params->get('support_ticket_group')) { $where[] = "t.`group`=" . $database->quote($group); } // Only tickets for specified owners? if ($owners = $this->params->get('support_ticket_owners')) { $usernames = explode(',', $owners); $usernames = array_map('trim', $usernames); foreach ($usernames as $k => $username) { $user = User::getInstance($username); $usernames[$k] = $database->quote($user->get('id')); } $where[] = "t.`owner` IN (" . implode(", ", $usernames) . ")"; } // Tickets with a specified severity? if ($severity = $this->params->get('support_ticket_severity')) { if ($severity != 'all') { $severities = explode(',', $severity); $severities = array_map('trim', $severities); foreach ($severities as $k => $severity) { $severities[$k] = $database->quote($severity); } $where[] = "t.`severity` IN (" . implode(", ", $severities) . ")"; } } // Only tickets by specified submitters if ($submitters = $this->params->get('support_ticket_submitters')) { $usernames = explode(',', $submitters); $usernames = array_map('trim', $usernames); foreach ($usernames as $k => $username) { $usernames[$k] = $database->quote($username); } $where[] = "t.`login` IN (" . implode(", ", $usernames) . ")"; } // Tickets WITHOUT specified tags if ($tags = $this->params->get('support_ticket_excludeTags', '')) { $tags = explode(',', $tags); $tags = array_map('trim', $tags); foreach ($tags as $k => $tag) { $tags[$k] = $database->quote($tag); } $where[] = "t.`id` NOT IN (\n\t\t\t\t\t\tSELECT jto.`objectid` FROM `#__tags_object` AS jto\n\t\t\t\t\t\tJOIN `#__tags` AS jt ON jto.`tagid`=jt.`id`\n\t\t\t\t\t\tWHERE jto.`tbl`='support'\n\t\t\t\t\t\tAND (\n\t\t\t\t\t\t\tjt.`tag` IN (" . implode(", ", $tags) . ") OR jt.`raw_tag` IN (" . implode(", ", $tags) . ")\n\t\t\t\t\t\t)\n\t\t\t\t\t)"; } // Tickets WITH specified tags if ($tags = $this->params->get('support_ticket_includeTags', '')) { $tags = explode(',', $tags); $tags = array_map('trim', $tags); foreach ($tags as $k => $tag) { $tags[$k] = $database->quote($tag); } $where[] = "t.`id` IN (\n\t\t\t\t\t\tSELECT jto.`objectid` FROM `#__tags_object` AS jto\n\t\t\t\t\t\tJOIN `#__tags` AS jt ON jto.`tagid`=jt.`id`\n\t\t\t\t\t\tWHERE jto.`tbl`='support'\n\t\t\t\t\t\tAND (\n\t\t\t\t\t\t\tjt.`tag` IN (" . implode(", ", $tags) . ") OR jt.`raw_tag` IN (" . implode(", ", $tags) . ")\n\t\t\t\t\t\t)\n\t\t\t\t\t)"; } // Last activity within specified time range if ($created = $this->params->get('support_ticket_activity')) { $op = ''; switch ($created) { // Created before (older than) case '-day': $op = '<='; $timestamp = Date::modify('-1 day'); break; case '-week': $op = '<='; $timestamp = Date::modify('-1 week'); break; case '-2week': $op = '<='; $timestamp = Date::modify('-2 week'); break; case '-3week': $op = '<='; $timestamp = Date::modify('-3 week'); break; case '-month': $op = '<='; $timestamp = Date::modify('-1 month'); break; case '-6month': $op = '<='; $timestamp = Date::modify('-6 month'); break; case '-year': $op = '<='; $timestamp = Date::modify('-1 year'); break; case '--': $op = ''; break; } if ($op) { $where[] = "(SELECT MAX(c.`created`) FROM `#__support_comments` AS c WHERE c.`ticket`=t.`id`) " . $op . $database->quote($timestamp->toSql()); } } if (count($where) > 0) { $slc .= " WHERE " . implode(" AND ", $where); $upd .= " WHERE " . implode(" AND ", $where); } $message_id = $this->params->get('support_ticket_message'); // Get a list of tickets before we update them $tickets = array(); if ($message_id) { $database->setQuery($slc); $tickets = $database->loadObjectList(); } // Update the tickets $database->setQuery($upd); if (!$database->query()) { Log::error('Ticket query failed: ' . $database->getErrorMsg()); return false; } // If we're sending a message... if ($message_id && !empty($tickets)) { Lang::load('com_support') || Lang::load('com_support', PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'site'); include_once PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'tables' . DS . 'message.php'; include_once PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'models' . DS . 'ticket.php'; $message = new \Components\Support\Tables\Message($database); $message->load($message_id); // Make sure we have a message to send if ($message->message) { $from = array('name' => Config::get('sitename') . ' ' . Lang::txt('COM_SUPPORT'), 'email' => Config::get('mailfrom'), 'multipart' => md5(date('U'))); // Set mail additional args (mail return path - used for bounces) if ($host = Request::getVar('HTTP_HOST', '', 'server')) { $args = '-f hubmail-bounces@' . $host; } $subject = Lang::txt('COM_SUPPORT') . ': ' . Lang::txt('COM_SUPPORT_TICKETS'); $mailed = array(); $message->message = str_replace('{sitename}', Config::get('sitename'), $message->message); $message->message = str_replace('{siteemail}', Config::get('mailfrom'), $message->message); $comment = new \Components\Support\Models\Comment(); $comment->set('created', Date::toSql()); $comment->set('created_by', 0); $comment->set('access', 0); $comment->set('comment', $message->message); foreach ($tickets as $submitter) { $name = null; $email = null; if ($submitter->login) { // Get the user's account $user = User::getInstance($submitter->login); if (is_object($user) && $user->get('id')) { $name = $user->get('name'); $email = $user->get('email'); } } $email = $email ?: $submitter->email; $name = $name ?: $submitter->name; $name = $name ?: $email; if (!$email) { continue; } // Try to ensure no duplicates if (in_array($email, $mailed)) { continue; } $old = new \Components\Support\Models\Ticket($submitter->id); $old->set('open', 1); $row = clone $old; $row->set('open', 0); $comment->set('comment', str_replace('#XXX', '#' . $row->get('id'), $comment->get('comment'))); $comment->set('comment', str_replace('{ticket#}', $row->get('id'), $comment->get('comment'))); // Compare fields to find out what has changed for this ticket and build a changelog $comment->changelog()->diff($old, $row); $comment->set('ticket', $row->get('id')); $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'site', 'name' => 'emails', 'layout' => 'comment_plain')); $eview->option = 'com_support'; $eview->controller = 'tickets'; $eview->delimiter = '~!~!~!~!~!~!~!~!~!~!'; $eview->boundary = $from['multipart']; $eview->comment = $comment; $eview->config = $sconfig; $eview->ticket = $row; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('comment_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // Build message $message = new \Hubzero\Mail\Message(); $message->setSubject($subject)->addFrom($from['email'], $from['name'])->addTo($email, $name)->addHeader('X-Component', 'com_support')->addHeader('X-Component-Object', 'support_ticket_comment'); $message->addPart($plain, 'text/plain'); $message->addPart($html, 'text/html'); // Send mail if (!$message->send()) { Log::error('Ticket email failed: ' . Lang::txt('Failed to mail %s', $email)); } $mailed[] = $email; } } } return true; }
/** * Save profile * * @return void */ private function _saveEntryData() { $isNew = !$this->_profile->get('uidNumber'); if (!isset($this->raw->password)) { $this->raw->password = null; } if ($isNew) { if (!$this->_profile->get('username')) { $valid = false; // Try to create from name $username = preg_replace('/[^a-z9-0_]/i', '', strtolower($this->_profile->get('name'))); if (\Hubzero\Utility\Validate::username($username)) { if (!$this->_usernameExists($username)) { $valid = true; } } // Try to create from portion preceeding @ in email address if (!$valid) { $username = strstr($this->_profile->get('email'), '@', true); if (\Hubzero\Utility\Validate::username($username)) { if ($this->_usernameExists($username)) { $valid = true; } } } // Try to create from whole email address if (!$valid) { for ($i = 0; $i <= 99; $i++) { $username = preg_replace('/[^a-z9-0_]/i', '', strtolower($this->_profile->get('name'))) . $i; if (\Hubzero\Utility\Validate::username($username)) { if ($this->_usernameExists($username)) { $valid = true; break; } } } } if ($valid) { $this->_profile->set('username', $username); } } if (!$this->raw->password) { //\Hubzero\User\Helper::random_password(); $this->raw->password = $this->_profile->get('username'); } $usersConfig = Component::params('com_users'); $newUsertype = $usersConfig->get('new_usertype'); if (!$newUsertype) { $db = \App::get('db'); $query = $db->getQuery(true)->select('id')->from('#__usergroups')->where('title = "Registered"'); $db->setQuery($query); $newUsertype = $db->loadResult(); } $user = User::getRoot(); $user->set('username', $this->_profile->get('username')); $user->set('name', $this->_profile->get('name')); $user->set('email', $this->_profile->get('email')); $user->set('id', 0); $user->set('groups', array($newUsertype)); $user->set('registerDate', Date::of('now')->toSql()); $user->set('password', $this->raw->password); $user->set('password_clear', $this->raw->password); $user->save(); $user->set('password_clear', ''); // Attempt to get the new user $profile = \Hubzero\User\Profile::getInstance($user->get('id')); $result = is_object($profile); // Did we successfully create an account? if ($result) { if (!$this->record->entry->get('emailConfirmed', null)) { $this->_profile->set('emailConfirmed', -rand(1, pow(2, 31) - 1)); } $this->_profile->set('uidNumber', $user->get('id')); $this->_profile->set('gidNumber', $profile->get('gidNumber')); if (!$this->_profile->get('homeDirectory')) { $this->_profile->set('homeDirectory', $profile->get('homeDirectory')); } if (!$this->_profile->get('loginShell')) { $this->_profile->set('loginShell', $profile->get('loginShell')); } if (!$this->_profile->get('ftpShell')) { $this->_profile->set('ftpShell', $profile->get('ftpShell')); } if (!$this->_profile->get('jobsAllowed')) { $this->_profile->set('jobsAllowed', $profile->get('jobsAllowed')); } } } if (!$this->_profile->store()) { throw new Exception(Lang::txt('Unable to save the entry data.')); } if ($password = $this->raw->password) { /*if ($isNew) { // We need to bypass any hashing $this->raw->password = '******'; \Hubzero\User\Password::changePasshash($this->_profile->get('uidNumber'), $password); } else {*/ \Hubzero\User\Password::changePassword($this->_profile->get('uidNumber'), $password); //} } \Hubzero\User\Password::expirePassword($this->_profile->get('uidNumber')); if ($isNew && $this->_options['emailnew'] == 1) { $eview = new \Hubzero\Component\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'site', 'name' => 'emails', 'layout' => 'confirm')); $eview->option = 'com_members'; $eview->controller = 'register'; $eview->sitename = Config::get('sitename'); $eview->login = $this->_profile->get('username'); $eview->name = $this->_profile->get('name'); $eview->registerDate = $this->_profile->get('registerDate'); $eview->confirm = $this->_profile->get('emailConfirmed'); $eview->baseURL = Request::base(); $msg = new \Hubzero\Mail\Message(); $msg->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'))->addTo($this->_profile->get('email'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', 'com_members'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('confirm_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { array_push($this->record->errors, Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION')); } } }
/** * Handles the actual sending of emails * * @param object $subscriber * @param string $message * @param string $subject * @param string $url * @return bool */ private function _sendEmail($subscriber, $message, $subject, $url) { $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_publications' . DS . 'site', 'name' => 'emails', 'layout' => 'watch_plain')); $eview->delimiter = '~!~!~!~!~!~!~!~!~!~!'; $eview->message = $message; $eview->subject = $subject; $eview->publication = $this->publication; $eview->url = $url; $name = Config::get('sitename') . ' ' . Lang::txt('PLG_PUBLICATIONS_WATCH_SUBSCRIBER'); $email = $subscriber->email; $eview->unsubscribeLink = Route::url($this->publication->link() . '&active=watch&action=unsubscribe&confirm=1&email=' . $email); // Get profile information if ($subscriber->created_by) { $user = User::getInstance($subscriber->created_by); $name = $user ? $user->get('name') : $name; $email = $user ? $user->get('email') : $email; } $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('watch_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); if (empty($email)) { return false; } // Build message $message = new \Hubzero\Mail\Message(); $message->setSubject($subject)->addFrom(Config::get('mailfrom'), Config::get('sitename'))->addTo($email, $name)->addHeader('X-Component', 'com_publications')->addHeader('X-Component-Object', 'publications_watch_email'); $message->addPart($plain, 'text/plain'); $message->addPart($html, 'text/html'); // Send mail if (!$message->send()) { $this->setError('Failed to mail %s', $email); return false; } return true; }
/** * Processes any queued newsletter mailings. * * @param object $job \Components\Cron\Models\Job * @return boolean */ public function processMailings(\Components\Cron\Models\Job $job) { // load needed libraries require_once PATH_CORE . DS . 'components' . DS . 'com_newsletter' . DS . 'tables' . DS . 'mailing.recipient.php'; require_once PATH_CORE . DS . 'components' . DS . 'com_newsletter' . DS . 'helpers' . DS . 'helper.php'; // needed vars $limit = 25; $processed = array(); // do we have a param defined limit $params = $job->get('params'); if (is_object($params) && $params->get('newsletter_queue_limit')) { $paramDefinedLimit = $params->get('newsletter_queue_limit'); if (is_numeric($paramDefinedLimit) && $paramDefinedLimit > 0 && $paramDefinedLimit < 100) { $limit = $paramDefinedLimit; } } // create needed objects $database = App::get('db'); // get all queued mailing recipients $sql = "SELECT nmr.id AS mailing_recipientid, nm.id AS mailingid, nm.nid AS newsletterid, nm.lid AS mailinglistid, nmr.email, nm.subject, nm.html_body, nm.plain_body, nm.headers, nm.args, nm.tracking\n\t\t\t\tFROM `#__newsletter_mailings` AS nm, `#__newsletter_mailing_recipients` AS nmr\n\t\t\t\tWHERE nm.id=nmr.mid\n\t\t\t\tAND nmr.status='queued'\n\t\t\t\tAND nm.deleted=0\n\t\t\t\tAND UTC_TIMESTAMP() >= nm.date\n\t\t\t\tORDER BY nmr.date_added\n\t\t\t\tLIMIT {$limit}"; $database->setQuery($sql); $queuedEmails = $database->loadObjectList(); // loop through each newsletter recipient, prepare and mail foreach ($queuedEmails as $queuedEmail) { if (in_array($queuedEmail->email, $processed)) { continue; } // get tracking & unsubscribe token $emailToken = \Components\Newsletter\Helpers\Helper::generateMailingToken($queuedEmail); // if tracking is on add it to email if ($queuedEmail->tracking) { $queuedEmail->html_body = \Components\Newsletter\Helpers\Helper::addTrackingToEmailMessage($queuedEmail->html_body, $emailToken); } // create unsubscribe link $unsubscribeMailtoLink = ''; $unsubscribeLink = 'https://' . $_SERVER['SERVER_NAME'] . '/newsletter/unsubscribe?e=' . urlencode($queuedEmail->email) . '&t=' . $emailToken; // add unsubscribe link - placeholder & in header (must do after adding tracking!!) $queuedEmail->html_body = str_replace("{{UNSUBSCRIBE_LINK}}", $unsubscribeLink, $queuedEmail->html_body); $queuedEmail->headers = str_replace("{{UNSUBSCRIBE_LINK}}", $unsubscribeLink, $queuedEmail->headers); $queuedEmail->headers = str_replace("{{UNSUBSCRIBE_MAILTO_LINK}}", $unsubscribeMailtoLink, $queuedEmail->headers); // add mailing id to header $queuedEmail->headers = str_replace("{{CAMPAIGN_MAILING_ID}}", $queuedEmail->mailingid, $queuedEmail->headers); // create new message $message = new \Hubzero\Mail\Message(); // add headers foreach (explode("\r\n", $queuedEmail->headers) as $header) { $parts = array_map("trim", explode(':', $header)); switch ($parts[0]) { case 'From': if (preg_match("/\\\"([^\"]*)\\\"\\s<([^>]*)>/ux", $parts[1], $matches)) { $message->setFrom(array($matches[2] => $matches[1])); } break; case 'Reply-To': if (preg_match("/\\\"([^\"]*)\\\"\\s<([^>]*)>/ux", $parts[1], $matches)) { $message->setReplyTo(array($matches[2] => $matches[1])); } break; case 'Importance': case 'X-Priority': case 'X-MSMail-Priority': $priority = isset($parts[1]) && in_array($parts[1], array(1, 2, 3, 4, 5)) ? $parts[1] : 3; $message->setPriority($priority); break; default: if (isset($parts[1])) { $message->addHeader($parts[0], $parts[1]); } } } // build message object and send $message->setSubject($queuedEmail->subject)->setTo($queuedEmail->email)->setBody($queuedEmail->plain_body, 'text/plain')->addPart($queuedEmail->html_body, 'text/html'); // mail message if ($message->send()) { // add to process email array $processed[] = $queuedEmail->email; // load recipient object $newsletterMailingRecipient = new \Components\Newsletter\Tables\MailingRecipient($database); $newsletterMailingRecipient->load($queuedEmail->mailing_recipientid); // mark as sent and save $newsletterMailingRecipient->status = 'sent'; $newsletterMailingRecipient->date_sent = Date::toSql(); $newsletterMailingRecipient->save($newsletterMailingRecipient); } } return true; }
/** * Saves a trouble report as a ticket * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); $live_site = rtrim(Request::base(), '/'); // Trigger any events that need to be called before session stop Event::trigger('support.onPreTicketSubmission', array()); // Incoming $no_html = Request::getInt('no_html', 0); $verified = Request::getInt('verified', 0); if (!isset($_POST['reporter']) || !isset($_POST['problem'])) { // This really, REALLY shouldn't happen. throw new Exception(Lang::txt('COM_SUPPORT_ERROR_MISSING_DATA'), 400); } $reporter = Request::getVar('reporter', array(), 'post', 'none', 2); $problem = Request::getVar('problem', array(), 'post', 'none', 2); //$reporter = array_map('trim', $_POST['reporter']); //$problem = array_map('trim', $_POST['problem']); // Normally calling Request::getVar calls _cleanVar, but b/c of the way this page processes the posts // (with array square brackets in the html names) against the $_POST collection, we explicitly // call the clean_var function on these arrays after fetching them //$reporter = array_map(array('Request', '_cleanVar'), $reporter); //$problem = array_map(array('Request', '_cleanVar'), $problem); // [!] zooley - Who added this? Why? // Reporter login can only be for authenticated users -- ignore any form submitted login names //$reporterLogin = $this->_getUser(); //$reporter['login'] = $reporterLogin['login']; // Probably redundant after the change to call Request::_cleanVar change above, It is a bit hard to // tell if the Joomla _cleanvar function does enough to allow us to remove the purifyText call $reporter = array_map(array('\\Hubzero\\Utility\\Sanitize', 'stripAll'), $reporter); //$problem = array_map(array('\\Hubzero\\Utility\\Sanitize', 'stripAll'), $problem); $reporter['name'] = trim($reporter['name']); $reporter['email'] = trim($reporter['email']); $problem['long'] = trim($problem['long']); // Make sure email address is valid $validemail = Validate::email($reporter['email']); // Set page title $this->_buildTitle(); $this->view->title = $this->_title; // Set the pathway $this->_buildPathway(); // Trigger any events that need to be called $customValidation = true; $result = Event::trigger('support.onValidateTicketSubmission', array($reporter, $problem)); $customValidation = is_array($result) && !empty($result) ? $result[0] : $customValidation; // Check for some required fields if (!$reporter['name'] || !$reporter['email'] || !$validemail || !$problem['long'] || !$customValidation) { Request::setVar('task', 'new'); // Output form with error messages if (!$reporter['name'] || !$reporter['email'] || !$problem['long']) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_MISSING_DATA')); } if (!$validemail) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_INVALID_EMAIL')); } if (!$customValidation) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_INVALID_DATA')); } foreach ($this->getErrors() as $error) { $this->view->setError($error); } return $this->newTask(); } // Get the user's IP $ip = Request::ip(); $hostname = gethostbyaddr(Request::getVar('REMOTE_ADDR', '', 'server')); if (!$verified) { // Check CAPTCHA $validcaptchas = Event::trigger('support.onValidateCaptcha'); if (count($validcaptchas) > 0) { foreach ($validcaptchas as $validcaptcha) { if (!$validcaptcha) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_INVALID_CAPTCHA')); } } } } // Are they verified? if (!$verified) { // Quick spam filter $spam = $this->_detectSpam($problem['long'], $ip); if ($spam) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_FLAGGED_AS_SPAM')); return; } // Quick bot check $botcheck = Request::getVar('botcheck', ''); if ($botcheck) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_INVALID_BOTCHECK')); return; } } // Check for errors // If any found, push back into the submission form view if ($this->getError()) { if ($no_html) { // Output error messages (AJAX) $this->view->setLayout('error'); if ($this->getError()) { $this->view->setError($this->getError()); } $this->view->display(); return; } else { Request::setVar('task', 'new'); $this->view->setError($this->getError()); return $this->newTask(); } } // Cut suggestion at 70 characters if (!$problem['short'] && $problem['long']) { $problem['short'] = substr($problem['long'], 0, 70); if (strlen($problem['short']) >= 70) { $problem['short'] .= '...'; } } $group = isset($problem['group']) ? $problem['group'] : ''; // Initiate class and bind data to database fields $row = new Ticket(); $row->set('open', 1); $row->set('status', 0); $row->set('created', Date::toSql()); $row->set('login', $reporter['login']); $row->set('severity', isset($problem['severity']) ? $problem['severity'] : 'normal'); $row->set('owner', isset($problem['owner']) ? $problem['owner'] : null); $row->set('category', isset($problem['category']) ? $problem['category'] : ''); $row->set('summary', $problem['short']); $row->set('report', $problem['long']); $row->set('resolved', isset($problem['resolved']) ? $problem['resolved'] : null); $row->set('email', $reporter['email']); $row->set('name', $reporter['name']); $row->set('os', $problem['os'] . ' ' . $problem['osver']); $row->set('browser', $problem['browser'] . ' ' . $problem['browserver']); $row->set('ip', $ip); $row->set('hostname', $hostname); $row->set('uas', Request::getVar('HTTP_USER_AGENT', '', 'server')); $row->set('referrer', base64_decode($problem['referer'])); $row->set('cookies', Request::getVar('sessioncookie', '', 'cookie') ? 1 : 0); $row->set('instances', 1); $row->set('section', 1); $row->set('group', $group); if (isset($incoming['target_date'])) { if (!$incoming['target_date']) { $row->set('target_date', '0000-00-00 00:00:00'); } else { $row->set('target_date', Date::of($incoming['target_date'], Config::get('offset'))->toSql()); } } // check if previous ticket submitted is the same as this one. $ticket = new Tables\Ticket($this->database); $filters = array('status' => 'new', 'sort' => 'id', 'sortdir' => 'DESC', 'limit' => '1', 'start' => 0); $prevSubmission = $ticket->getTickets($filters, false); // for the first ticket ever if (isset($prevSubmission[0]) && $prevSubmission[0]->report == $row->get('report') && time() - strtotime($prevSubmission[0]->created) <= 15) { $this->setError(Lang::txt('COM_SUPPORT_TICKET_DUPLICATE_DETECTION')); return $this->newTask($row); } // Save the data if (!$row->store()) { $this->setError($row->getError()); } $attachment = $this->uploadTask($row->get('id')); // Save tags $row->set('tags', Request::getVar('tags', '', 'post')); $row->tag($row->get('tags'), User::get('id'), 1); // Get any set emails that should be notified of ticket submission $defs = explode(',', $this->config->get('emails', '{config.mailfrom}')); if ($defs) { $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_SUPPORT_EMAIL_SUBJECT_NEW_TICKET', $row->get('id'))); $message->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_option))); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'ticket_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->ticket = $row; $eview->config = $this->config; $eview->delimiter = ''; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $message->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('ticket_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); if (!$this->config->get('email_terse')) { foreach ($row->attachments() as $attachment) { if ($attachment->size() < 2097152) { if ($attachment->isImage()) { $file = basename($attachment->link('filepath')); $html = preg_replace('/<a class="img" data\\-filename="' . str_replace('.', '\\.', $file) . '" href="(.*?)"\\>(.*?)<\\/a>/i', '<img src="' . $message->getEmbed($attachment->link('filepath')) . '" alt="" />', $html); } else { $message->addAttachment($attachment->link('filepath')); } } } } $message->addPart($html, 'text/html'); // Loop through the addresses foreach ($defs as $def) { $def = trim($def); // Check if the address should come from Joomla config if ($def == '{config.mailfrom}') { $def = Config::get('mailfrom'); } // Check for a valid address if (Validate::email($def)) { // Send e-mail $message->setTo(array($def)); $message->send(); } } } // Log activity $creator = User::getInstance($row->get('login')); if ($creator && $creator->get('id')) { Event::trigger('system.logActivity', ['activity' => ['action' => 'created', 'scope' => 'support.ticket', 'scope_id' => $row->get('id'), 'description' => Lang::txt('COM_SUPPORT_ACTIVITY_TICKET_CREATED', '<a href="' . Route::url($row->link()) . '">#' . $row->get('id') . ' - ' . $row->get('summary') . '</a>'), 'details' => array('id' => $row->get('id'), 'summary' => $row->get('summary'), 'url' => Route::url($row->link()))], 'recipients' => [['support.tickets', 1], ['user', $creator->get('id')]]]); } if (!User::isGuest() && $this->acl->check('update', 'tickets') > 0) { // Only do the following if a comment was posted // otherwise, we're only recording a changelog $old = new Ticket(); $old->set('open', 1); $old->set('owner', 0); $old->set('status', 0); $old->set('tags', ''); $old->set('severity', 'normal'); $rowc = new Comment(); $rowc->set('ticket', $row->get('id')); $rowc->set('created', Date::toSql()); $rowc->set('created_by', User::get('id')); $rowc->set('access', 1); $rowc->set('comment', Lang::txt('COM_SUPPORT_TICKET_SUBMITTED')); // Compare fields to find out what has changed for this ticket and build a changelog $rowc->changelog()->diff($old, $row); $rowc->changelog()->cced(Request::getVar('cc', '')); // Were there any changes, CCs, or comments to record? if (count($rowc->changelog()->get('changes')) > 0 || count($rowc->changelog()->get('cc')) > 0) { // Save the data if (!$rowc->store()) { throw new Exception($rowc->getError(), 500); } if ($row->get('owner')) { $rowc->addTo(array('role' => Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_OWNER'), 'name' => $row->owner('name'), 'email' => $row->owner('email'), 'id' => $row->owner('id'))); } elseif ($row->get('group')) { $group = \Hubzero\User\Group::getInstance($row->get('group')); if ($group) { foreach ($group->get('managers') as $manager) { $manager = User::getInstance($manager); if (!$manager || !$manager->get('id')) { continue; } $rowc->addTo(array('role' => Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_GROUPMANAGER'), 'name' => $manager->get('name'), 'email' => $manager->get('email'), 'id' => $manager->get('id'))); } } } // Add any CCs to the e-mail list foreach ($rowc->changelog()->get('cc') as $cc) { $rowc->addTo($cc, Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_CC')); } $recipients = array(['support.tickets', 1]); // Check if the notify list has eny entries if (count($rowc->to())) { $allowEmailResponses = $this->config->get('email_processing'); if ($this->config->get('email_terse')) { $allowEmailResponses = false; } if ($allowEmailResponses) { try { $encryptor = new \Hubzero\Mail\Token(); } catch (Exception $e) { $allowEmailResponses = false; } } $subject = Lang::txt('COM_SUPPORT_EMAIL_SUBJECT_TICKET_COMMENT', $row->get('id')); $from = array('name' => Lang::txt('COM_SUPPORT_EMAIL_FROM', Config::get('sitename')), 'email' => Config::get('mailfrom'), 'multipart' => md5(date('U'))); $message = array(); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'comment_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->comment = $rowc; $eview->ticket = $row; $eview->config = $this->config; $eview->delimiter = $allowEmailResponses ? '~!~!~!~!~!~!~!~!~!~!' : ''; $message['plaintext'] = $eview->loadTemplate(false); $message['plaintext'] = str_replace("\n", "\r\n", $message['plaintext']); // HTML email $eview->setLayout('comment_html'); $message['multipart'] = $eview->loadTemplate(); $message['multipart'] = str_replace("\n", "\r\n", $message['multipart']); // Send e-mail to admin? foreach ($rowc->to('ids') as $to) { $recipients[] = ['user', $to['id']]; if ($allowEmailResponses) { // The reply-to address contains the token $token = $encryptor->buildEmailToken(1, 1, $to['id'], $row->get('id')); $from['replytoemail'] = 'htc-' . $token . strstr(Config::get('mailfrom'), '@'); } // Get the user's email address if (!Event::trigger('xmessage.onSendMessage', array('support_reply_submitted', $subject, $message, $from, array($to['id']), $this->_option))) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_FAILED_TO_MESSAGE', $to['name'] . '(' . $to['role'] . ')')); } $rowc->changelog()->notified($to['role'], $to['name'], $to['email']); } foreach ($rowc->to('emails') as $to) { if ($allowEmailResponses) { $token = $encryptor->buildEmailToken(1, 1, -9999, $row->get('id')); $email = array($to['email'], 'htc-' . $token . strstr(Config::get('mailfrom'), '@')); // In this case each item in email in an array, 1- To, 2:reply to address Utilities::sendEmail($email[0], $subject, $message, $from, $email[1]); } else { // email is just a plain 'ol string Utilities::sendEmail($to['email'], $subject, $message, $from); } $rowc->changelog()->notified($to['role'], $to['name'], $to['email']); } } // Were there any changes? if (count($rowc->changelog()->get('notifications')) > 0 || count($rowc->changelog()->get('cc')) > 0 || count($rowc->changelog()->get('changes')) > 0) { // Save the data if (!$rowc->store()) { $this->setError($rowc->getError()); } } // Record the activity if (!$rowc->isPrivate() && $creator->get('id')) { $recipients[] = ['user', $creator->get('id')]; } $desc = Lang::txt('COM_SUPPORT_ACTIVITY_TICKET_UPDATED', '<a href="' . Route::url($row->link()) . '">#' . $row->get('id') . ' - ' . $row->get('summary') . '</a>'); if ($rowc->get('comment')) { $desc = Lang::txt('COM_SUPPORT_ACTIVITY_COMMENT_CREATED', $rowc->get('id'), '<a href="' . Route::url($row->link()) . '">#' . $row->get('id') . ' - ' . $row->get('summary') . '</a>'); } Event::trigger('system.logActivity', ['activity' => ['action' => 'created', 'scope' => 'support.ticket.comment', 'scope_id' => $rowc->get('id'), 'description' => $desc, 'details' => array('id' => $row->get('id'), 'summary' => $row->get('summary'), 'url' => Route::url($row->link()), 'comment' => $rowc->get('id'))], 'recipients' => $recipients]); } } // Trigger any events that need to be called Event::trigger('support.onTicketSubmission', array($row)); // Output Thank You message $this->view->ticket = $row->get('id'); $this->view->no_html = $no_html; foreach ($this->getErrors() as $error) { $this->view->setError($error); } $this->view->display(); }
/** * Send an email to an invited user * * @param string $email Email address to message * @return boolean True if message sent */ private function notifyEmailInvitedUser($email) { // Get the group information $group = $this->group; // Build the SEF referenced in the message $sef = Route::url('index.php?option=' . $this->_option . '&cn=' . $group->get('cn')); $sef = ltrim($sef, '/'); //get the reason $reason = Request::getVar('reason', '', 'post'); // Build the "from" info for e-mails $from = array('name' => Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->name)), 'email' => Config::get('mailfrom')); //create the subject $subject = Lang::txt('PLG_GROUPS_MESSAGES_SUBJECT_INVITATION_CANCELLED'); //create the message body $plain = "Your invitation for membership in the " . $group->get('description') . " group has been cancelled.\r\n\r\n"; if ($reason) { $plain .= stripslashes($reason) . "\r\n\r\n"; } $plain .= "If you feel this is in error, you may try to join the group by going to:\r\n"; $plain .= Request::base() . $sef . "\r\n"; //send the message if ($email) { // create message object $message = new \Hubzero\Mail\Message(); // set message details and send $message->setSubject($subject)->addFrom($from['email'], $from['name'])->setTo($email)->addPart($plain, 'text/plain')->send(); } // all good return true; }
/** * Final submission * * @return void */ public function submitTask() { // Incoming $id = Request::getInt('id', 0); // Ensure we have an ID to work with if (!$id) { App::abort(404, Lang::txt('COM_CONTRIBUTE_NO_ID')); } // Load resource info $resource = Resource::oneOrFail($id); // Set a flag for if the resource was already published or not $published = 0; if ($resource->get('published') != 2) { $published = 1; } // Check if a newly submitted resource was authorized to be published $authorized = Request::getInt('authorization', 0); if (!$authorized && !$published) { $this->setError(Lang::txt('COM_CONTRIBUTE_CONTRIBUTION_NOT_AUTHORIZED')); $this->_checkProgress($id); return $this->step_review(); } // Allow for any other validation $results = Event::trigger('resources.onResourceBeforeSubmit', array($resource)); foreach ($results as $result) { if ($result) { $this->setError($result); $this->_checkProgress($id); return $this->step_review(); } } // Is this a newly submitted resource? if (!$published) { $activity = 'submitted'; // 0 = unpublished, 1 = published, 2 = composing, 3 = pending (submitted), 4 = deleted // Are submissions auto-approved? if ($this->config->get('autoapprove') == 1) { //checks if autoapproved content has children (configurable in options on backend) if ($this->config->get('autoapprove_content_check') == 1) { if ($resource->children()->total() < 1) { $this->setError(Lang::txt('COM_CONTRIBUTE_NO_CONTENT')); return $this->step_review(); } } // Set status to published $resource->set('published', 1); $resource->set('publish_up', Date::toSql()); $activity = 'published'; } else { $apu = $this->config->get('autoapproved_users'); $apu = explode(',', $apu); $apu = array_map('trim', $apu); if (in_array(User::get('username'), $apu)) { // Set status to published $resource->set('published', 1); $resource->set('publish_up', Date::toSql()); } else { // Set status to pending review (submitted) $resource->set('published', 3); } } // Get the resource's contributors $authors = $resource->authors()->rows(); if ($authors->count() <= 0) { $this->setError(Lang::txt('COM_CONTRIBUTE_CONTRIBUTION_HAS_NO_AUTHORS')); $this->_checkProgress($id); return $this->step_review(); } // Get any set emails that should be notified of ticket submission $defs = explode(',', $this->config->get('email_when_submitted', '{config.mailfrom}')); if (!empty($defs)) { $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_RESOURCES_EMAIL_SUBJECT_NEW_SUBMISSION', $resource->id)); $message->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_option))); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'submitted_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->resource = $resource; $eview->delimiter = ''; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $message->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('submitted_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $message->addPart($html, 'text/html'); // Loop through the addresses foreach ($defs as $def) { $def = trim($def); // Check if the address should come from config if ($def == '{config.mailfrom}') { $def = Config::get('mailfrom'); } // Check for a valid address if (\Hubzero\Utility\Validate::email($def)) { // Send e-mail $message->setTo(array($def)); $message->send(); } } } // Log activity $recipients = array(['resource', $resource->get('id')], ['user', $resource->get('created_by')]); foreach ($authors as $author) { if ($author->get('authorid') > 0) { $recipients[] = ['user', $author->get('authorid')]; } } Event::trigger('system.logActivity', ['activity' => ['action' => $activity, 'scope' => 'resource', 'scope_id' => $resource->get('title'), 'description' => Lang::txt('COM_RESOURCES_ACTIVITY_ENTRY_' . strtoupper($activity), '<a href="' . Route::url($resource->link()) . '">' . $resource->get('title') . '</a>'), 'details' => array('title' => $resource->get('title'), 'url' => Route::url($resource->link()))], 'recipients' => $recipients]); } // Is this resource licensed under Creative Commons? if ($this->config->get('cc_license')) { $license = Request::getVar('license', ''); if ($license == 'custom') { $license .= $resource->get('id'); $licenseText = Request::getVar('license-text', ''); if ($licenseText == '[ENTER LICENSE HERE]') { $this->setError(Lang::txt('Please enter a license.')); $this->_checkProgress($id); return $this->step_review(); } $rl = License::oneOrNew($license); $rl->set('name', $license); $rl->set('text', $licenseText); $rl->set('info', $resource->get('id')); $rl->save(); } // set license $params = new \Hubzero\Config\Registry($resource->get('params')); $params->set('license', $license); $resource->set('params', $params->toString()); } // Save the resource $resource->save(); Event::trigger('resources.onResourceAfterSubmit', array($resource)); // If a previously published resource, redirect to the resource page if ($published == 1) { App::redirect(Route::url($resource->link())); return; } // Output HTML $this->setView($this->_controller, 'thanks'); $this->view->set('title', $this->_title)->set('config', $this->config)->set('resource', $resource)->setErrors($this->getErrors())->display(); }
/** * Save an abuse report and displays a "Thank you" message * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); // Incoming $this->view->cat = Request::getVar('category', ''); $this->view->refid = Request::getInt('referenceid', 0); $this->view->returnlink = Request::getVar('link', ''); $no_html = Request::getInt('no_html', 0); // Trim and addslashes all posted items $incoming = array_map('trim', $_POST); // Initiate class and bind posted items to database fields $row = new ReportAbuse($this->database); if (!$row->bind($incoming)) { if ($no_html) { echo json_encode(array('success' => false, 'message' => $row->getError(), 'id' => $this->view->refid, 'category' => $this->view->cat)); return; } Request::setVar('id', $this->view->refid); $this->setError($row->getError()); $this->displayTask(); return; } $row->report = Sanitize::clean($row->report); $row->report = nl2br($row->report); $row->created_by = User::get('id'); $row->created = Date::toSql(); $row->state = 0; // Check content if (!$row->check()) { if ($no_html) { echo json_encode(array('success' => false, 'message' => $row->getError(), 'id' => $this->view->refid, 'category' => $this->view->cat)); return; } Request::setVar('id', $this->view->refid); $this->setError($row->getError()); $this->displayTask(); return; } // Store new content if (!$row->store()) { if ($no_html) { echo json_encode(array('success' => false, 'message' => $row->getError(), 'id' => $this->view->refid, 'category' => $this->view->cat)); return; } Request::setVar('id', $this->view->refid); $this->setError($row->getError()); $this->displayTask(); return; } // Get the search result totals $results = Event::trigger('support.onReportItem', array($this->view->refid, $this->view->cat)); // Send notification email if ($this->config->get('abuse_notify', 1)) { $reported = new \stdClass(); $reported->author = 0; // Get the search result totals $results = Event::trigger('support.getReportedItem', array($this->view->refid, $this->view->cat, 0)); // Check the results returned for a reported item if ($results) { foreach ($results as $result) { if ($result) { $reported = $result[0]; break; } } } // Get any set emails that should be notified of ticket submission $defs = str_replace("\r", '', $this->config->get('abuse_emails', '{config.mailfrom}')); $defs = str_replace('\\n', "\n", $defs); $defs = explode("\n", $defs); $defs = array_map('trim', $defs); $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_SUPPORT_ABUSE_REPORT'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_option)))->addHeader('X-Component', 'com_support')->addHeader('X-Component-Object', 'abuse_item_report'); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'abuse_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->report = $row; $eview->reported = $reported; $eview->author = null; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $message->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('abuse_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $message->addPart($html, 'text/html'); // Loop through the addresses foreach ($defs as $def) { // Check if the address should come from Joomla config if ($def == '{config.mailfrom}') { $def = Config::get('mailfrom'); } // Check for a valid address if (Validate::email($def)) { $message->addTo($def); } } // Send e-mail if (!$message->send()) { $this->setError(Lang::txt('Uh-oh')); } } if ($no_html) { echo json_encode(array('success' => true, 'report_id' => $row->id, 'message' => Lang::txt('COM_SUPPORT_REPORT_NUMBER_REFERENCE', $row->id), 'id' => $this->view->refid, 'category' => $this->view->cat)); return; } // Set the page title $this->_buildTitle(); $this->view->title = $this->_title; $this->view->report = $row; // Set the pathway $this->_buildPathway(); // Output HTML foreach ($this->getErrors() as $error) { $this->view->setError($error); } $this->view->display(); }
/** * Finalize the purchase process * * @return void */ public function finalizeTask() { // Check for request forgeries Request::checkToken(); // Set page title $this->_buildTitle(); // Set the pathway $this->_buildPathway(); // Check authorization if (User::isGuest()) { $this->loginTask(); return; } $now = \Date::toSql(); // Get cart object $item = new Cart($this->database); // Calculate total $cost = $item->getCartItems(User::get('id'), 'cost'); // Check available user funds $BTL = new Teller(User::get('id')); $balance = $BTL->summary(); $credit = $BTL->credit_summary(); $funds = $balance - $credit; $funds = $funds > 0 ? $funds : '0'; // Get cart items $items = $item->getCartItems(User::get('id')); if (!$items or $cost > $funds) { $this->cartTask(); return; } // Get shipping info $shipping = array_map('trim', $_POST); // make sure email address is valid $email = \Hubzero\Utility\Validate::email($shipping['email']) ? $shipping['email'] : User::get('email'); // Format posted info $details = Lang::txt('COM_STORE_SHIP_TO') . ':' . "\r\n"; $details .= $shipping['name'] . "\r\n"; $details .= Sanitize::stripAll($shipping['address']) . "\r\n"; $details .= Lang::txt('COM_STORE_COUNTRY') . ': ' . $shipping['country'] . "\r\n"; $details .= '----------------------------------------------------------' . "\r\n"; $details .= Lang::txt('COM_STORE_CONTACT') . ': ' . "\r\n"; if ($shipping['phone']) { $details .= $shipping['phone'] . "\r\n"; } $details .= $email . "\r\n"; $details .= '----------------------------------------------------------' . "\r\n"; $details .= Lang::txt('COM_STORE_DETAILS') . ': '; $details .= $shipping['comments'] ? "\r\n" . Sanitize::stripAll($shipping['comments']) : 'N/A'; // Register a new order $order = new Order($this->database); $order->uid = User::get('id'); $order->total = $cost; $order->status = '0'; // order placed $order->ordered = $now; $order->email = $email; $order->details = $details; // Store new content if (!$order->store()) { throw new Exception($order->getError(), 500); } // Get order ID $objO = new Order($this->database); $orderid = $objO->getOrderID(User::get('id'), $now); if ($orderid) { // Transfer cart items to order foreach ($items as $itm) { $orderitem = new OrderItem($this->database); $orderitem->uid = User::get('id'); $orderitem->oid = $orderid; $orderitem->itemid = $itm->itemid; $orderitem->price = $itm->price; $orderitem->quantity = $itm->quantity; $orderitem->selections = $itm->selections; // Save order item if (!$orderitem->store()) { throw new Exception($orderitem->getError(), 500); } } // Put the purchase amount on hold $BTL = new Teller(User::get('id')); $BTL->hold($order->total, Lang::txt('COM_STORE_BANKING_HOLD'), 'store', $orderid); $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_STORE_EMAIL_SUBJECT_NEW_ORDER', $orderid)); $message->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_option))); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'confirmation_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->orderid = $orderid; $eview->cost = $cost; $eview->shipping = $shipping; $eview->details = $details; $eview->items = $items; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $message->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('confirmation_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $message->addPart($html, 'text/html'); // Send e-mail $message->setTo(array(User::get('email'))); $message->send(); } // Empty cart $item->deleteCartItem('', User::get('id'), 'all'); if ($this->getError()) { \Notify::message($this->getError(), 'error'); } else { \Notify::message(Lang::txt('COM_STORE_SUCCESS_MESSAGE', $orderid), 'success'); } App::redirect(Route::url('index.php?option=' . $this->_option)); return; }
/** * Email Announcement * * @param object $announcement * @param object $group * @return boolean */ public static function send($announcement, $group) { // get all group members $groupMembers = array(); foreach ($group->get('members') as $member) { if ($profile = User::getInstance($member)) { // Skip invalid emails if (preg_match('/^-[0-9]+@invalid$/', $profile->get('email'))) { continue; } $groupMembers[$profile->get('email')] = $profile->get('name'); } } if (!count($groupMembers)) { return true; } // create view object $eview = new \Hubzero\Mail\View(array('base_path' => __DIR__, 'name' => 'email', 'layout' => 'announcement_plain')); // plain text $eview->set('announcement', $announcement); $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('announcement_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // set from address $from = array('name' => Config::get('sitename') . ' Groups', 'email' => Config::get('mailfrom')); // define subject $subject = $group->get('description') . ' Group Announcement'; foreach ($groupMembers as $email => $name) { // create message object $message = new \Hubzero\Mail\Message(); // set message details and send $message->setSubject($subject)->addReplyTo($from['email'], $from['name'])->addFrom($from['email'], $from['name'])->setTo($email, $name)->addPart($plain, 'text/plain')->addPart($html, 'text/html')->send(); } // all good return true; }
/** * Send confirmation Email to user * * @param $email Confirmation Email Address * @param $mailinglist Mailing list we just subscribed to * @param $addedByAdmin Did we sign up or we were added by admin? * @return void */ public static function sendMailinglistConfirmationEmail($emailAddress, $mailinglistObject, $addedByAdmin = true) { // create from details $from = array('name' => \Config::get('sitename') . ' Mailing Lists', 'email' => 'hubmail-mailinglists@' . $_SERVER['HTTP_HOST']); // create replyto details $replyto = array('name' => 'DO NOT REPLY', 'email' => 'do-not-reply@' . $_SERVER['HTTP_HOST']); //build subject $subject = "Confirm Email Subscription to '" . $mailinglistObject->name . "' on " . \Config::get('sitename'); //get token $token = self::generateConfirmationToken($emailAddress, $mailinglistObject); //build body if ($addedByAdmin) { $body = "You are receiving this email because you have been added to the following mailing list by a site administrator. "; } else { $body = "You are receiving this email because you have signed up for the following mailing list. "; } $body .= "Please confirm or remove your email subscription by clicking on one of the links below" . PHP_EOL . PHP_EOL; $body .= $mailinglistObject->name . PHP_EOL; $body .= $mailinglistObject->description . PHP_EOL . PHP_EOL . PHP_EOL; $body .= "========================================================================" . PHP_EOL . PHP_EOL; $body .= "Click this link to CONFIRM your subscription:" . PHP_EOL; $body .= 'https://' . $_SERVER['HTTP_HOST'] . '/newsletter/confirm?e=' . urlencode($emailAddress) . '&t=' . $token . PHP_EOL . PHP_EOL; $body .= "------------------------------------------------------------------------" . PHP_EOL . PHP_EOL; $body .= "Click this link to REMOVE this email from the mailing list:" . PHP_EOL; $body .= 'https://' . $_SERVER['HTTP_HOST'] . '/newsletter/remove?e=' . urlencode($emailAddress) . '&t=' . $token . PHP_EOL . PHP_EOL; $body .= "========================================================================"; // create new message $message = new \Hubzero\Mail\Message(); // build message object and send $message->setSubject($subject)->addFrom($from['email'], $from['name'])->setReplyTo($replyto['email'], $replyto['name'])->setTo($emailAddress)->addHeader('X-Mailer', 'PHP/' . phpversion())->addHeader('X-Component', 'com_newsletter')->addHeader('X-Component-Object', 'Mailinglist')->addHeader('X-Component-ObjectId', $mailinglistObject->id)->addPart($body, 'text/plain')->send(); return true; }
/** * Change registered email * * @return void */ public function changeTask() { // Set the pathway $this->_buildPathway(); // Set the page title $this->_buildTitle(); // Check if the user is logged in if (User::isGuest()) { $return = base64_encode(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&task=' . $this->_task, false, true)); App::redirect(Route::url('index.php?option=com_users&view=login&return=' . $return, false), Lang::txt('COM_MEMBERS_REGISTER_ERROR_LOGIN_TO_UPDATE'), 'warning'); return; } $xprofile = \Hubzero\User\Profile::getInstance(User::get('id')); $login = $xprofile->get('username'); $email = $xprofile->get('email'); $email_confirmed = $xprofile->get('emailConfirmed'); // Instantiate a new view $this->view->title = Lang::txt('COM_MEMBERS_REGISTER_CHANGE'); $this->view->login = $login; $this->view->email = $email; $this->view->email_confirmed = $email_confirmed; $this->view->success = false; // Incoming $return = urldecode(Request::getVar('return', '/')); $this->view->return = $return; // Check if a new email was submitted $pemail = Request::getVar('email', '', 'post'); $update = Request::getVar('update', '', 'post'); if ($update) { if (!$pemail) { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_INVALID_EMAIL')); } if ($pemail && \Components\Members\Helpers\Utility::validemail($pemail)) { // Check if the email address was actually changed if ($pemail == $email) { // Addresses are the same! Redirect App::redirect($return, '', 'message', true); } else { // New email submitted - attempt to save it $xprofile = \Hubzero\User\Profile::getInstance($login); if ($xprofile) { $dtmodify = Date::toSql(); $xprofile->set('email', $pemail); $xprofile->set('modifiedDate', $dtmodify); if ($xprofile->update()) { $user = User::getInstance($login); $user->set('email', $pemail); $user->save(); } else { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_UPDATING_ACCOUNT')); } } else { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_UPDATING_ACCOUNT')); } // Any errors returned? if (!$this->getError()) { // No errors // Attempt to send a new confirmation code $confirm = \Components\Members\Helpers\Utility::genemailconfirm(); $xprofile = new \Hubzero\User\Profile(); $xprofile->load($login); $xprofile->set('emailConfirmed', $confirm); $xprofile->update(); $subject = Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'); $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'confirm')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->sitename = Config::get('sitename'); $eview->login = $login; $eview->name = $xprofile->get('name'); $eview->registerDate = $xprofile->get('registerDate'); $eview->baseURL = $this->baseURL; $eview->confirm = $confirm; $msg = new \Hubzero\Mail\Message(); $msg->setSubject($subject)->addTo($pemail)->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', $this->_option); $message = $eview->loadTemplate(false); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('confirm_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION', $pemail)); } // Show the success form $this->view->success = true; } } } else { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_INVALID_EMAIL')); } } // Output the view if ($this->getError()) { $this->view->email = $pemail; $this->view->setError($this->getError()); } $this->view->display(); }
/** * Saves changes to an order * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); $statusmsg = ''; $data = array_map('trim', $_POST); $action = isset($data['action']) ? $data['action'] : ''; $id = $data['id'] ? $data['id'] : 0; $cost = intval($data['total']); if ($id) { // initiate extended database class $row = new Order($this->database); $row->load($id); $row->notes = \Hubzero\Utility\Sanitize::clean($data['notes']); $hold = $row->total; $row->total = $cost; // get user bank account $xprofile = User::getInstance($row->uid); $BTL_Q = new Teller($this->database, $xprofile->get('id')); switch ($action) { case 'complete_order': // adjust credit $credit = $BTL_Q->credit_summary(); $adjusted = $credit - $hold; $BTL_Q->credit_adjustment($adjusted); // remove hold $sql = "DELETE FROM `#__users_transactions` WHERE category='store' AND type='hold' AND referenceid='" . $id . "' AND uid=" . intval($row->uid); $this->database->setQuery($sql); if (!$this->database->query()) { throw new Exception($this->database->getErrorMsg(), 500); } // debit account if ($cost > 0) { $BTL_Q->withdraw($cost, Lang::txt('COM_STORE_BANKING_PURCHASE') . ' #' . $id, 'store', $id); } // update order information $row->status_changed = Date::toSql(); $row->status = 1; $statusmsg = Lang::txt('COM_STORE_ORDER') . ' #' . $id . ' ' . Lang::txt('COM_STORE_HAS_BEEN') . ' ' . strtolower(Lang::txt('COM_STORE_COMPLETED')) . '.'; break; case 'cancel_order': // adjust credit $credit = $BTL_Q->credit_summary(); $adjusted = $credit - $hold; $BTL_Q->credit_adjustment($adjusted); // remove hold $sql = "DELETE FROM `#__users_transactions` WHERE category='store' AND type='hold' AND referenceid='" . $id . "' AND uid=" . intval($row->uid); $this->database->setQuery($sql); if (!$this->database->query()) { throw new Exception($this->database->getErrorMsg(), 500); } // update order information $row->status_changed = Date::toSql(); $row->status = 2; $statusmsg = Lang::txt('COM_STORE_ORDER') . ' #' . $id . ' ' . Lang::txt('COM_STORE_HAS_BEEN') . ' ' . strtolower(Lang::txt('COM_STORE_CANCELLED')) . '.'; break; case 'message': $statusmsg = Lang::txt('COM_STORE_MSG_SENT') . '.'; break; default: $statusmsg = Lang::txt('COM_STORE_ORDER_DETAILS_UPDATED') . '.'; break; } // check content if (!$row->check()) { throw new Exception($row->getError(), 500); return; } // store new content if (!$row->store()) { throw new Exception($row->getError(), 500); } // send email if ($action || $data['message']) { if (\Hubzero\Utility\Validate::email($row->email)) { $message = new \Hubzero\Mail\Message(); $message->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_STORE_EMAIL_UPDATE_SHORT', $id)); $message->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt('COM_STORE_STORE')); // Plain text email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => '_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->orderid = $id; $eview->cost = $cost; $eview->row = $row; $eview->action = $action; $eview->message = \Hubzero\Utility\Sanitize::stripAll($data['message']); $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $message->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); $message->addPart($html, 'text/html'); // Send e-mail $message->setTo(array($row->email)); $message->send(); } } } App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), $statusmsg); }
/** * Permanently delete group * * @return void */ public function doDeleteTask() { // Check if they're logged in if (User::isGuest()) { $this->loginTask(Lang::txt('COM_GROUPS_DELETE_MUST_BE_LOGGED_IN')); return; } //check to make sure we have cname if (!$this->cn) { $this->_errorHandler(400, Lang::txt('COM_GROUPS_ERROR_NO_ID')); } // Load the group page $this->view->group = Group::getInstance($this->cn); // Ensure we found the group info if (!$this->view->group || !$this->view->group->get('gidNumber')) { $this->_errorHandler(404, Lang::txt('COM_GROUPS_ERROR_NOT_FOUND')); } // Check authorization if ($this->_authorize() != 'manager') { $this->_errorHandler(403, Lang::txt('COM_GROUPS_ERROR_NOT_AUTH')); } //get request vars $confirm_delete = Request::getInt('confirmdel', ''); $message = trim(Request::getVar('msg', '', 'post')); //check to make sure we have confirmed if (!$confirm_delete) { $this->setNotification(Lang::txt('COM_GROUPS_DELETE_MISSING_CONFIRM_MESSAGE'), 'error'); $this->deleteTask(); return; } // Start log $log = Lang::txt('COM_GROUPS_DELETE_MESSAGE_SUBJECT', $this->view->group->get('cn')) . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_ID') . ': ' . $this->view->group->get('gidNumber') . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_CNAME') . ': ' . $this->view->group->get('cn') . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_TITLE') . ': ' . $this->view->group->get('description') . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_DISCOVERABILITY') . ': ' . $this->view->group->get('discoverability') . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_PUBLIC_TEXT') . ': ' . stripslashes($this->view->group->get('public_desc')) . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_PRIVATE_TEXT') . ': ' . stripslashes($this->view->group->get('private_desc')) . "\n"; $log .= Lang::txt('COM_GROUPS_GROUP_RESTRICTED_MESSAGE') . ': ' . stripslashes($this->view->group->get('restrict_msg')) . "\n"; // Get number of group members $members = $this->view->group->get('members'); $managers = $this->view->group->get('managers'); // Log ids of group members if ($members) { $log .= Lang::txt('COM_GROUP_MEMBERS') . ': '; foreach ($members as $gu) { $log .= $gu . ' '; } $log .= '' . "\n"; } $log .= Lang::txt('COM_GROUP_MANAGERS') . ': '; foreach ($managers as $gm) { $log .= $gm . ' '; } $log .= '' . "\n"; // Trigger the functions that delete associated content // Should return logs of what was deleted $logs = Event::trigger('groups.onGroupDelete', array($this->view->group)); if (count($logs) > 0) { $log .= implode('', $logs); } // Build the file path $path = PATH_APP . DS . trim($this->config->get('uploadpath', '/site/groups'), DS) . DS . $this->view->group->get('gidNumber'); if (is_dir($path)) { // Attempt to delete the file if (!Filesystem::deleteDirectory($path)) { $this->setNotification(Lang::txt('UNABLE_TO_DELETE_DIRECTORY'), 'error'); } } //clone the deleted group $deletedgroup = clone $this->view->group; // Delete group if (!$this->view->group->delete()) { $this->setNotification($this->view->group->error, 'error'); $this->deleteTask(); return; } // Build the "from" info for e-mails $from = array(); $from['name'] = Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_name)); $from['email'] = Config::get('mailfrom'); // E-mail subject $subject = Lang::txt('COM_GROUPS_DELETE_MESSAGE_SUBJECT', $deletedgroup->get('cn')); // Build the e-mail message $eview = new \Hubzero\Component\View(array('name' => 'emails', 'layout' => 'deleted')); $eview->option = $this->_option; $eview->sitename = Config::get('sitename'); $eview->user = User::getRoot(); $eview->gcn = $deletedgroup->get('cn'); $eview->msg = $message; $eview->group = $deletedgroup; $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // build array of email recipients $groupMembers = array(); foreach ($members as $member) { $profile = \Hubzero\User\Profile::getInstance($member); if ($profile) { $groupMembers[$profile->get('email')] = $profile->get('name'); } } // create new message $message = new \Hubzero\Mail\Message(); // build message object and send $message->setSubject($subject)->addFrom($from['email'], $from['name'])->setTo($groupMembers)->addHeader('X-Mailer', 'PHP/' . phpversion())->addHeader('X-Component', 'com_groups')->addHeader('X-Component-Object', 'group_deleted')->addHeader('X-Component-ObjectId', $deletedgroup->get('gidNumber'))->addPart($html, 'text/plain')->send(); // log deleted group Log::log(array('gidNumber' => $deletedgroup->get('gidNumber'), 'action' => 'group_deleted', 'comments' => $log)); // Redirect back to the groups page $this->setNotification(Lang::txt('COM_GROUPS_DELETE_SUCCESS', $deletedgroup->get('description')), 'passed'); App::redirect(Route::url('index.php?option=' . $this->_option)); return; }
/** * Archive publications beyond grace period * * @param object $job \Components\Cron\Models\Job * @return boolean */ public function runMkAip(\Components\Cron\Models\Job $job) { $database = \App::get('db'); $config = Component::params('com_publications'); require_once PATH_CORE . DS . 'components' . DS . 'com_publications' . DS . 'helpers' . DS . 'utilities.php'; require_once PATH_CORE . DS . 'components' . DS . 'com_publications' . DS . 'tables' . DS . 'version.php'; require_once PATH_CORE . DS . 'components' . DS . 'com_projects' . DS . 'helpers' . DS . 'html.php'; // Check that mkAIP script exists if (!\Components\Publications\Helpers\Utilities::archiveOn()) { return; } // Check for grace period $gracePeriod = $config->get('graceperiod', 0); if (!$gracePeriod) { // If no grace period, this cron is unnecessary (archived as approval) return; } $aipBasePath = trim($config->get('aip_path', NULL), DS); $aipBasePath = $aipBasePath && is_dir(DS . $aipBasePath) ? DS . $aipBasePath : NULL; // Check for base path if (!$aipBasePath) { $this->setError('Missing archival base directory'); return; } // Get all unarchived publication versions $query = "SELECT V.*, C.id as id, V.id as version_id "; $query .= " FROM #__publication_versions as V, #__publications as C "; $query .= " WHERE C.id=V.publication_id AND V.state=1 "; $query .= " AND V.doi IS NOT NULL "; $query .= " AND V.accepted IS NOT NULL AND V.accepted !='0000-00-00 00:00:00' "; $query .= " AND (V.archived IS NULL OR V.archived ='0000-00-00 00:00:00') "; $database->setQuery($query); if (!($rows = $database->loadObjectList())) { return true; } // Start email message $subject = Lang::txt('Update on recently archived publications'); $body = Lang::txt('The following publications passed the grace period and were archived:') . "\n"; $aipGroup = $config->get('aip_group'); $counter = 0; foreach ($rows as $row) { // Grace period unexpired? $monthFrom = Date::of($row->accepted . '+1 month')->toSql(); if (strtotime($monthFrom) > strtotime(Date::of('now'))) { continue; } // Load version $pv = new \Components\Publications\Tables\Version($database); if (!$pv->load($row->version_id)) { continue; } // Create aip path $doiParts = explode('/', $row->doi); $aipName = count($doiParts) > 1 ? $doiParts[0] . '__' . $doiParts[1] : ''; // Archival package exists? if ($aipBasePath && $aipName && is_dir($aipBasePath . DS . $aipName)) { // Save approved date and archive date $pv->archived = $pv->accepted; $pv->store(); // Do not overwrite existing archives !! continue; } // Run mkAIP and save archived date if (\Components\Publications\Helpers\Utilities::mkAip($row)) { $pv->archived = Date::toSql(); $pv->store(); $counter++; $body .= $row->title . ' v.' . $row->version_label . ' (id #' . $row->id . ')' . "\n"; } } // Email update to admins if ($counter > 0 && $aipGroup) { // Set email config $from = array('name' => Config::get('fromname') . ' ' . Lang::txt('Publications'), 'email' => Config::get('mailfrom'), 'multipart' => md5(date('U'))); $admins = \Components\Projects\Helpers\Html::getGroupMembers($aipGroup); // Build message if (!empty($admins)) { foreach ($admins as $admin) { // Get the user's account $user = User::getInstance($admin); if (!$user->get('id')) { continue; } $message = new \Hubzero\Mail\Message(); $message->setSubject($subject)->addFrom($from['email'], $from['name'])->addTo($user->get('email'), $user->get('name'))->addHeader('X-Component', 'com_publications')->addHeader('X-Component-Object', 'publications'); $message->addPart($body, 'text/plain'); $message->send(); } } } // All done return true; }
/** * Send mail that page has been approved * * @param $type type of object just approved * @param $object object approved * @return void */ public static function sendApprovedNotification($type, $object) { // build title $title = Lang::txt('Page "%s" Approved', $object->get('title')); if ($type == 'module') { $title = Lang::txt('Module "%s" Approved', $object->get('title')); } // get \Hubzero\User\Group object $group = \Hubzero\User\Group::getInstance(Request::getCmd('cn', Request::getCmd('gid'))); // array to hold manager emails $managers = array(); // get all manager email addresses foreach ($group->get('managers') as $m) { $profile = \Hubzero\User\Profile::getInstance($m); if ($profile) { $managers[$profile->get('email')] = $profile->get('name'); } } // subject details $subject = Config::get('sitename') . ' ' . Lang::txt('Groups') . ', ' . $title; // from details $from = array('name' => Config::get('sitename') . ' ' . Lang::txt('Groups'), 'email' => Config::get('mailfrom')); // build html email $eview = new \Hubzero\Component\View(array('base_path' => dirname(__DIR__) . DS . 'site', 'name' => 'emails', 'layout' => $type)); $eview->option = Request::getCmd('option', 'com_groups'); $eview->controller = Request::getCmd('controller', 'groups'); $eview->group = $group; $eview->object = $object; $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // create new message $message = new \Hubzero\Mail\Message(); // build message object and send $message->setSubject($subject)->addFrom($from['email'], $from['name'])->setTo($managers)->addHeader('X-Mailer', 'PHP/' . phpversion())->addHeader('X-Component', 'com_groups')->addHeader('X-Component-Object', $type . '_approved')->addPart($html, 'text/html')->send(); }
/** * Send Newsletter * * @param $newsletter * @param $newsletterHtmlContent * @param $newsletterPlainContent * @param $newsletterContacts * @param $newsletterMailinglist * @param $sendingTest * @return object */ private function _send($newsletter, $newsletterHtmlContent, $newsletterPlainContent, $newsletterContacts, $newsletterMailinglist, $sendingTest = false) { //set default mail from and reply-to names and addresses $defaultMailFromName = Config::get("sitename") . ' Newsletter'; $defaultMailFromAddress = 'contact@' . $_SERVER['HTTP_HOST']; $defaultMailReplytoName = Config::get("sitename") . ' Newsletter - Do Not Reply'; $defaultMailReplytoAddress = 'do-not-reply@' . $_SERVER['HTTP_HOST']; //get the config mail from and reply-to names and addresses $mailFromName = $this->config->get('newsletter_from_name', $defaultMailFromName); $mailFromAddress = $this->config->get('newsletter_from_address', $defaultMailFromAddress); $mailReplytoName = $this->config->get('newsletter_replyto_name', $defaultMailReplytoName); $mailReplytoAddress = $this->config->get('newsletter_replyto_address', $defaultMailReplytoAddress); //parse newsletter specific emails $params = new Registry($newsletter->params); $mailFromName = $params->get('from_name', $mailFromName); $mailFromAddress = $params->get('from_address', $mailFromAddress); $mailReplytoName = $params->get('replyto_name', $mailReplytoName); $mailReplytoAddress = $params->get('replyto_address', $mailReplytoAddress); //set final mail from and reply-to $mailFrom = '"' . $mailFromName . '" <' . $mailFromAddress . '>'; $mailReplyTo = '"' . $mailReplytoName . '" <' . $mailReplytoAddress . '>'; //set subject and body $mailSubject = $newsletter->name ? $newsletter->name : 'Your ' . Config::get("sitename") . '.org Newsletter'; $mailHtmlBody = $newsletterHtmlContent; $mailPlainBody = $newsletterPlainContent; //set mail headers //$mailHeaders = "MIME-Version: 1.0" . "\r\n"; //$mailHeaders .= "Content-type: text/html; charset=\"UTF-8\"" . "\r\n"; $mailHeaders = "From: {$mailFrom}" . "\r\n"; $mailHeaders .= "Reply-To: {$mailReplyTo}" . "\r\n"; //set mail priority $mailHeaders .= "X-Priority: 3" . "\r\n"; //$mailHeaders .= "X-MSMail-Priority: Normal" . "\r\n"; //$mailHeaders .= "Importance: Normal\n"; //set extra headers $mailHeaders .= "X-Mailer: PHP/" . phpversion() . "\r\n"; $mailHeaders .= "X-Component: " . $this->_option . "\r\n"; $mailHeaders .= "X-Component-Object: Campaign Mailing" . "\r\n"; $mailHeaders .= "X-Component-ObjectId: {{CAMPAIGN_MAILING_ID}}" . "\r\n"; //$mailHeaders .= "List-Unsubscribe: <mailto:{{UNSUBSCRIBE_MAILTO_LINK}}>, <{{UNSUBSCRIBE_LINK}}>"; //set mail args $mailArgs = ''; //$mailArgs = '-f hubmail-bounces@' . $_SERVER['HTTP_HOST']; //are we sending test mailing if ($sendingTest) { foreach ($newsletterContacts as $contact) { // get tracking & unsubscribe token $recipient = new stdClass(); $recipient->email = $contact; $recipient->mailingid = $newsletterMailinglist ? $newsletterMailinglist : -1; $emailToken = \Components\Newsletter\Helpers\Helper::generateMailingToken($recipient); // create unsubscribe link $unsubscribeMailtoLink = ''; $unsubscribeLink = 'https://' . $_SERVER['SERVER_NAME'] . '/newsletter/unsubscribe?e=' . urlencode($contact) . '&t=' . $emailToken; // add unsubscribe link - placeholder & in header (must do after adding tracking!!) $mailHtmlBody = str_replace("{{UNSUBSCRIBE_LINK}}", $unsubscribeLink, $mailHtmlBody); $mailPlainBody = str_replace("{{UNSUBSCRIBE_LINK}}", $unsubscribeLink, $mailPlainBody); // create new message $message = new \Hubzero\Mail\Message(); foreach (explode("\r\n", $mailHeaders) as $header) { $parts = array_map("trim", explode(':', $header)); switch ($parts[0]) { case 'From': if (preg_match("/\\\"([^\"]*)\\\"\\s<([^>]*)>/ux", $parts[1], $matches)) { $message->setFrom(array($matches[2] => $matches[1])); } break; case 'Reply-To': if (preg_match("/\\\"([^\"]*)\\\"\\s<([^>]*)>/ux", $parts[1], $matches)) { $message->setReplyTo(array($matches[2] => $matches[1])); } break; case 'Importance': case 'X-Priority': case 'X-MSMail-Priority': $priority = isset($parts[1]) && in_array($parts[1], array(1, 2, 3, 4, 5)) ? $parts[1] : 3; $message->setPriority($priority); break; default: if (isset($parts[1])) { $message->addHeader($parts[0], $parts[1]); } } } // build message object and send $message->setSubject('[SENDING TEST] - ' . $mailSubject)->setTo($contact)->addPart($mailHtmlBody, 'text/html')->addPart($mailPlainBody, 'text/plain')->send(); } return true; } //get the scheduling $scheduler = Request::getInt('scheduler', 1); if ($scheduler == '1') { $scheduledDate = Date::toSql(); } else { $schedulerDate = Request::getVar('scheduler_date', ''); $schedulerHour = Request::getVar('scheduler_date_hour', '00'); $schedulerMinute = Request::getVar('scheduler_date_minute', '00'); $schedulerMeridian = Request::getVar('scheduler_date_meridian', 'AM'); //make sure we have at least the date or we use now if (!$schedulerDate) { $scheduledDate = Date::toSql(); } //break apart parts of date $schedulerDateParts = explode('/', $schedulerDate); //make sure its in 24 time if ($schedulerMeridian == 'pm') { $schedulerHour += 12; } //build scheduled time $scheduledTime = $schedulerDateParts[2] . '-' . $schedulerDateParts[0] . '-' . $schedulerDateParts[1]; $scheduledTime .= ' ' . $schedulerHour . ':' . $schedulerMinute . ':00'; $scheduledDate = Date::of(strtotime($scheduledTime))->toSql(); } //create mailing object $mailing = new stdClass(); $mailing->nid = $newsletter->id; $mailing->lid = $newsletterMailinglist; $mailing->subject = $mailSubject; $mailing->html_body = $mailHtmlBody; $mailing->plain_body = $mailPlainBody; $mailing->headers = $mailHeaders; $mailing->args = $mailArgs; $mailing->tracking = $newsletter->tracking; $mailing->date = $scheduledDate; //save mailing object $newsletterMailing = new Mailing($this->database); if (!$newsletterMailing->save($mailing)) { $this->setError(Lang::txt('COM_NEWSLETTER_NEWSLETTER_SEND_FAIL')); $this->sendNewsletterTask(); return; } // create recipients $this->_sendTo($newsletterMailing, $newsletterContacts); return $newsletterMailing; }
/** * Send emails reminding people of their open tickets * * @param object $job \Components\Cron\Models\Job * @return boolean */ public function sendTicketList(\Components\Cron\Models\Job $job) { $params = $job->get('params'); $database = App::get('db'); $sconfig = Component::params('com_support'); Lang::load('com_support') || Lang::load('com_support', PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'site'); $sql = "SELECT t.*, o.`name` AS owner_name FROM `#__support_tickets` AS t LEFT JOIN `#__users` AS o ON o.`id`=t.`owner`"; $where = array(); $where[] = "t.`type`=0"; if (is_object($params)) { if ($val = $params->get('support_ticketlist_open', 1)) { $where[] = "t.`open`=" . $val; } $statuses = array(); if (is_numeric($params->get('support_ticketlist_status1'))) { $statuses[] = $params->get('support_ticketlist_status1'); } if (is_numeric($params->get('support_ticketlist_status2'))) { $statuses[] = $params->get('support_ticketlist_status2'); } if (is_numeric($params->get('support_ticketlist_status3'))) { $statuses[] = $params->get('support_ticketlist_status3'); } if (count($statuses)) { $where[] = "t.`status` IN (" . implode(',', $statuses) . ")"; } if ($group = $params->get('support_ticketlist_group')) { $where[] = "t.`group`=" . $database->quote($group); } if ($owners = $params->get('support_ticketlist_owners')) { $usernames = explode(',', $owners); $usernames = array_map('trim', $usernames); foreach ($usernames as $k => $username) { $user = User::getInstance($username); $usernames[$k] = $database->quote($user->get('id')); } $where[] = "t.`owner` IN (" . implode(", ", $usernames) . ")"; } if ($severity = $params->get('support_ticketlist_severity')) { if ($severity != 'all') { $severities = explode(',', $severity); $severities = array_map('trim', $severities); foreach ($severities as $k => $severity) { $severities[$k] = $database->quote($severity); } $where[] = "t.`severity` IN (" . implode(", ", $severities) . ")"; } } if ($owned = intval($params->get('support_ticketlist_owned', 0))) { if ($owned == 1) { $where[] = "(t.`owner` IS NULL OR t.`owner`='0')"; } else { if ($owned == 2) { $where[] = "(t.`owner` IS NOT NULL AND t.`owner` !='0')"; } } } if ($submitters = $params->get('support_ticketlist_submitters')) { $usernames = explode(',', $submitters); $usernames = array_map('trim', $usernames); foreach ($usernames as $k => $username) { $usernames[$k] = $database->quote($username); } $where[] = "t.`login` IN (" . implode(", ", $usernames) . ")"; } if ($tags = $params->get('support_ticketlist_excludeTags')) { $tags = explode(',', $tags); $tags = array_map('trim', $tags); foreach ($tags as $k => $tag) { $tags[$k] = $database->quote($tag); } $where[] = "t.`id` NOT IN (\n\t\t\t\t\t\t\tSELECT jto.`objectid` FROM `#__tags_object` AS jto\n\t\t\t\t\t\t\tJOIN `#__tags` AS jt ON jto.`tagid`=jt.`id`\n\t\t\t\t\t\t\tWHERE jto.`tbl`='support'\n\t\t\t\t\t\t\tAND (\n\t\t\t\t\t\t\t\tjt.`tag` IN (" . implode(", ", $tags) . ") OR jt.`raw_tag` IN (" . implode(", ", $tags) . ")\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)"; } if ($tags = $params->get('support_ticketlist_includeTags')) { $tags = explode(',', $tags); $tags = array_map('trim', $tags); foreach ($tags as $k => $tag) { $tags[$k] = $database->quote($tag); } $where[] = "t.`id` IN (\n\t\t\t\t\t\t\tSELECT jto.`objectid` FROM `#__tags_object` AS jto\n\t\t\t\t\t\t\tJOIN `#__tags` AS jt ON jto.`tagid`=jt.`id`\n\t\t\t\t\t\t\tWHERE jto.`tbl`='support'\n\t\t\t\t\t\t\tAND (\n\t\t\t\t\t\t\t\tjt.`tag` IN (" . implode(", ", $tags) . ") OR jt.`raw_tag` IN (" . implode(", ", $tags) . ")\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)"; } if ($created = $params->get('support_ticketlist_created', '+week')) { $op = ''; switch ($created) { // Created before (older than) case '-day': $op = '<='; $timestamp = Date::modify('-1 day'); break; case '-week': $op = '<='; $timestamp = Date::modify('-1 week'); break; case '-2week': $op = '<='; $timestamp = Date::modify('-2 week'); break; case '-3week': $op = '<='; $timestamp = Date::modify('-3 week'); break; case '-month': $op = '<='; $timestamp = Date::modify('-1 month'); break; case '-6month': $op = '<='; $timestamp = Date::modify('-6 month'); break; case '-year': $op = '<='; $timestamp = Date::modify('-1 year'); break; // Created since (newer than) // Created since (newer than) case '+day': $op = '>='; $timestamp = Date::modify('-1 day'); break; case '+week': $op = '>='; $timestamp = Date::modify('-1 week'); break; case '+2week': $op = '>='; $timestamp = Date::modify('-2 week'); break; case '+3week': $op = '>='; $timestamp = Date::modify('-3 week'); break; case '+month': $op = '>='; $timestamp = Date::modify('-1 month'); break; case '+6month': $op = '>='; $timestamp = Date::modify('-6 month'); break; case '+year': $op = '>='; $timestamp = Date::modify('-1 year'); break; } if ($op) { $where[] = "t.`created`" . $op . $database->quote($timestamp->toSql()); } } if ($created = $params->get('support_ticketlist_activity', '--')) { $op = ''; switch ($created) { // Created before (older than) case '-day': $op = '<='; $timestamp = Date::modify('-1 day'); break; case '-week': $op = '<='; $timestamp = Date::modify('-1 week'); break; case '-2week': $op = '<='; $timestamp = Date::modify('-2 week'); break; case '-3week': $op = '<='; $timestamp = Date::modify('-3 week'); break; case '-month': $op = '<='; $timestamp = Date::modify('-1 month'); break; case '-6month': $op = '<='; $timestamp = Date::modify('-6 month'); break; case '-year': $op = '<='; $timestamp = Date::modify('-1 year'); break; case 'all': case '--': $op = ''; break; } if ($op) { $where[] = "(SELECT MAX(c.`created`) FROM `#__support_comments` AS c WHERE c.`ticket`=t.`id`) " . $op . $database->quote($timestamp->toSql()); } } } else { $where[] = "t.`open`=1"; } if (count($where) > 0) { $sql .= " WHERE " . implode(" AND ", $where); } $sql .= " ORDER BY t.`created` ASC LIMIT 0, 500"; $database->setQuery($sql); if (!($results = $database->loadObjectList())) { return true; } include_once PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'models' . DS . 'ticket.php'; if ($params->get('support_ticketlist_severity', 'all') != 'all') { $severities = explode(',', $params->get('support_ticketlist_severity', 'all')); } else { include_once PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'helpers' . DS . 'utilities.php'; $severities = \Components\Support\Helpers\Utilities::getSeverities($sconfig->get('severities')); } $from = array(); $from['name'] = Config::get('sitename') . ' ' . Lang::txt('COM_SUPPORT'); $from['email'] = Config::get('mailfrom'); $from['multipart'] = md5(date('U')); // Set mail additional args (mail return path - used for bounces) if ($host = Request::getVar('HTTP_HOST', '', 'server')) { $args = '-f hubmail-bounces@' . $host; } $subject = Lang::txt('COM_SUPPORT') . ': ' . Lang::txt('COM_SUPPORT_TICKETS'); $usernames = array(); if ($users = $params->get('support_ticketlist_notify')) { $usernames = explode(',', $users); $usernames = array_map('trim', $usernames); } $mailed = array(); foreach ($usernames as $owner) { if ($owner == '{config.mailfrom}') { $name = Config::get('mailfrom'); $email = Config::get('mailfrom'); } else { if (strstr($owner, '@')) { $name = $owner; $email = $owner; } else { // Get the user's account $user = User::getInstance($owner); if (!is_object($user) || !$user->get('id')) { continue; } $name = $user->get('name'); $email = $user->get('email'); } } // Try to ensure no duplicates if (in_array($email, $mailed)) { continue; } $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_support' . DS . 'site', 'name' => 'emails', 'layout' => 'ticketlist_plain')); $eview->option = 'com_support'; $eview->controller = 'tickets'; $eview->delimiter = '~!~!~!~!~!~!~!~!~!~!'; $eview->boundary = $from['multipart']; $eview->tickets = $results; $eview->config = $sconfig; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); // HTML $eview->setLayout('ticketlist_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // Build message $message = new \Hubzero\Mail\Message(); $message->setSubject($subject)->addFrom($from['email'], $from['name'])->addTo($email, $name)->addHeader('X-Component', 'com_support')->addHeader('X-Component-Object', 'support_ticket_list'); $message->addPart($plain, 'text/plain'); $message->addPart($html, 'text/html'); // Send mail if (!$message->send()) { //$this->setError(Lang::txt('Failed to mail %s', $fullEmailAddress)); Log::error('CRON email failed: ' . Lang::txt('Failed to mail %s', $email)); } $mailed[] = $email; } return true; }
/** * Saves changes to a ticket, adds a new comment/changelog, * notifies any relevant parties * * @return void */ public function saveTask($redirect = 1) { // Check for request forgeries Request::checkToken(); // Incoming $isNew = true; $id = Request::getInt('id', 0); if ($id) { $isNew = false; } // Load the old ticket so we can compare for the changelog $old = new Ticket($id); $old->set('tags', $old->tags('string')); // Initiate class and bind posted items to database fields $row = new Ticket($id); if (!$row->bind($_POST)) { throw new Exception($row->getError(), 500); } if ($row->get('target_date') && $row->get('target_date') != '0000-00-00 00:00:00') { $row->set('target_date', Date::of($row->get('target_date'), Config::get('offset'))->toSql()); } else { $row->set('target_date', '0000-00-00 00:00:00'); } $comment = Request::getVar('comment', '', 'post', 'none', 2); $rowc = new Comment(); $rowc->set('ticket', $id); // Check if changes were made inbetween the time the comment was started and posted if ($id) { $started = Request::getVar('started', Date::toSql(), 'post'); $lastcomment = $row->comments('list', array('sort' => 'created', 'sort_Dir' => 'DESC', 'limit' => 1, 'start' => 0, 'ticket' => $id))->first(); if (isset($lastcomment) && $lastcomment->created() >= $started) { $rowc->set('comment', $comment); \Notify::error(Lang::txt('Changes were made to this ticket in the time since you began commenting/making changes. Please review your changes before submitting.')); return $this->editTask($rowc); } } if ($id && isset($_POST['status']) && $_POST['status'] == 0) { $row->set('open', 0); $row->set('resolved', Lang::txt('COM_SUPPORT_TICKET_COMMENT_OPT_CLOSED')); } $row->set('open', $row->status('open')); // If an existing ticket AND closed AND previously open if ($id && !$row->get('open') && $row->get('open') != $old->get('open')) { // Record the closing time $row->set('closed', Date::toSql()); } // Check content if (!$row->check()) { throw new Exception($row->getError(), 500); } // Store new content if (!$row->store()) { throw new Exception($row->getError(), 500); } // Save the tags $row->tag(Request::getVar('tags', '', 'post'), User::get('id'), 1); $row->set('tags', $row->tags('string')); $base = Request::base(); if (substr($base, -14) == 'administrator/') { $base = substr($base, 0, strlen($base) - 14); } $webpath = trim($this->config->get('webpath'), '/'); $allowEmailResponses = $this->config->get('email_processing'); $this->config->set('email_terse', Request::getInt('email_terse', 0)); if ($this->config->get('email_terse')) { $allowEmailResponses = false; } if ($allowEmailResponses) { try { $encryptor = new \Hubzero\Mail\Token(); } catch (Exception $e) { $allowEmailResponses = false; } } // If a new ticket... if ($isNew) { // Get any set emails that should be notified of ticket submission $defs = explode(',', $this->config->get('emails', '{config.mailfrom}')); if ($defs) { // Get some email settings $msg = new \Hubzero\Mail\Message(); $msg->setSubject(Config::get('sitename') . ' ' . Lang::txt('COM_SUPPORT') . ', ' . Lang::txt('COM_SUPPORT_TICKET_NUMBER', $row->get('id'))); $msg->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_option))); // Plain text email $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . $this->_option . DS . 'site', 'name' => 'emails', 'layout' => 'ticket_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->ticket = $row; $eview->config = $this->config; $eview->delimiter = ''; $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $msg->addPart($plain, 'text/plain'); // HTML email $eview->setLayout('ticket_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); if (!$this->config->get('email_terse')) { foreach ($row->attachments() as $attachment) { if ($attachment->size() < 2097152) { if ($attachment->isImage()) { $file = basename($attachment->link('filepath')); $html = preg_replace('/<a class="img" data\\-filename="' . str_replace('.', '\\.', $file) . '" href="(.*?)"\\>(.*?)<\\/a>/i', '<img src="' . $message->getEmbed($attachment->link('filepath')) . '" alt="" />', $html); } else { $message->addAttachment($attachment->link('filepath')); } } } } $msg->addPart($html, 'text/html'); // Loop through the addresses foreach ($defs as $def) { $def = trim($def); // Check if the address should come from Joomla config if ($def == '{config.mailfrom}') { $def = Config::get('mailfrom'); } // Check for a valid address if (Validate::email($def)) { // Send e-mail $msg->setTo(array($def)); $msg->send(); } } } } // Incoming comment if ($comment) { // If a comment was posted by the ticket submitter to a "waiting user response" ticket, change status. if ($row->isWaiting() && User::get('username') == $row->get('login')) { $row->open(); } } // Create a new support comment object and populate it $access = Request::getInt('access', 0); //$rowc = new Comment(); $rowc->set('ticket', $row->get('id')); $rowc->set('comment', nl2br($comment)); $rowc->set('created', Date::toSql()); $rowc->set('created_by', User::get('id')); $rowc->set('access', $access); // Compare fields to find out what has changed for this ticket and build a changelog $rowc->changelog()->diff($old, $row); $rowc->changelog()->cced(Request::getVar('cc', '')); // Save the data if (!$rowc->store()) { throw new Exception($rowc->getError(), 500); } Event::trigger('support.onTicketUpdate', array($row, $rowc)); if ($tmp = Request::getInt('tmp_dir')) { $attach = new Tables\Attachment($this->database); $attach->updateCommentId($tmp, $rowc->get('id')); } if (!$isNew) { $attachment = $this->uploadTask($row->get('id'), $rowc->get('id')); } // Only do the following if a comment was posted or ticket was reassigned // otherwise, we're only recording a changelog if ($rowc->get('comment') || $row->get('owner') != $old->get('owner') || $row->get('group') != $old->get('group') || $rowc->attachments()->total() > 0) { // Send e-mail to ticket submitter? if (Request::getInt('email_submitter', 0) == 1) { // Is the comment private? If so, we do NOT send e-mail to the // submitter regardless of the above setting if (!$rowc->isPrivate()) { $rowc->addTo(array('role' => Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_SUBMITTER'), 'name' => $row->submitter('name'), 'email' => $row->submitter('email'), 'id' => $row->submitter('id'))); } } // Send e-mail to ticket owner? if (Request::getInt('email_owner', 0) == 1) { if ($old->get('owner') && $row->get('owner') != $old->get('owner')) { $rowc->addTo(array('role' => Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_PRIOR_OWNER'), 'name' => $old->owner('name'), 'email' => $old->owner('email'), 'id' => $old->owner('id'))); } if ($row->get('owner')) { $rowc->addTo(array('role' => Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_OWNER'), 'name' => $row->owner('name'), 'email' => $row->owner('email'), 'id' => $row->owner('id'))); } elseif ($row->get('group')) { $group = \Hubzero\User\Group::getInstance($row->get('group')); if ($group) { foreach ($group->get('managers') as $manager) { $manager = User::getInstance($manager); if (!$manager || !$manager->get('id')) { continue; } $rowc->addTo(array('role' => Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_GROUPMANAGER'), 'name' => $manager->get('name'), 'email' => $manager->get('email'), 'id' => $manager->get('id'))); } } } } // Add any CCs to the e-mail list foreach ($rowc->changelog()->get('cc') as $cc) { $rowc->addTo($cc, Lang::txt('COM_SUPPORT_COMMENT_SEND_EMAIL_CC')); } // Message people watching this ticket, // but ONLY if the comment was NOT marked private $this->acl = ACL::getACL(); foreach ($row->watchers() as $watcher) { $this->acl->setUser($watcher->user_id); if (!$rowc->isPrivate() || $rowc->isPrivate() && $this->acl->check('read', 'private_comments')) { $rowc->addTo($watcher->user_id, 'watcher'); } } $this->acl->setUser(User::get('id')); if (count($rowc->to())) { // Build e-mail components $subject = Lang::txt('COM_SUPPORT_EMAIL_SUBJECT_TICKET_COMMENT', $row->get('id')); $from = array('name' => Lang::txt('COM_SUPPORT_EMAIL_FROM', Config::get('sitename')), 'email' => Config::get('mailfrom'), 'multipart' => md5(date('U'))); // Plain text email $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . $this->_option . DS . 'site', 'name' => 'emails', 'layout' => 'comment_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->comment = $rowc; $eview->ticket = $row; $eview->config = $this->config; $eview->delimiter = $allowEmailResponses ? '~!~!~!~!~!~!~!~!~!~!' : ''; $message['plaintext'] = $eview->loadTemplate(false); $message['plaintext'] = str_replace("\n", "\r\n", $message['plaintext']); // HTML email $eview->setLayout('comment_html'); $message['multipart'] = $eview->loadTemplate(); $message['multipart'] = str_replace("\n", "\r\n", $message['multipart']); $message['attachments'] = array(); if (!$this->config->get('email_terse')) { foreach ($rowc->attachments() as $attachment) { if ($attachment->size() < 2097152) { $message['attachments'][] = $attachment->link('filepath'); } } } // Send e-mail to admin? foreach ($rowc->to('ids') as $to) { if ($allowEmailResponses) { // The reply-to address contains the token $token = $encryptor->buildEmailToken(1, 1, $to['id'], $id); $from['replytoemail'] = 'htc-' . $token . strstr(Config::get('mailfrom'), '@'); } // Get the user's email address if (!Event::trigger('xmessage.onSendMessage', array('support_reply_submitted', $subject, $message, $from, array($to['id']), $this->_option))) { $this->setError(Lang::txt('COM_SUPPORT_ERROR_FAILED_TO_MESSAGE', $to['name'] . '(' . $to['role'] . ')')); } // Watching should be anonymous if ($to['role'] == 'watcher') { continue; } $rowc->changelog()->notified($to['role'], $to['name'], $to['email']); } foreach ($rowc->to('emails') as $to) { if ($allowEmailResponses) { $token = $encryptor->buildEmailToken(1, 1, -9999, $id); $email = array($to['email'], 'htc-' . $token . strstr(Config::get('mailfrom'), '@')); // In this case each item in email in an array, 1- To, 2:reply to address Utilities::sendEmail($email[0], $subject, $message, $from, $email[1]); } else { // Email is just a plain 'ol string Utilities::sendEmail($to['email'], $subject, $message, $from); } // Watching should be anonymous if ($to['role'] == 'watcher') { continue; } $rowc->changelog()->notified($to['role'], $to['name'], $to['email']); } } else { // Force entry to private if no comment or attachment was made if (!$rowc->get('comment') && $rowc->attachments()->total() <= 0) { $rowc->set('access', 1); } } // Were there any changes? if (count($rowc->changelog()->get('notifications')) > 0 || $access != $rowc->get('access')) { // Save the data if (!$rowc->store()) { throw new Exception($rowc->getError(), 500); } } } // output messsage and redirect if ($redirect) { $filters = Request::getVar('filters', ''); $filters = str_replace('&', '&', $filters); // Redirect App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller . ($filters ? '&' . $filters : ''), false), Lang::txt('COM_SUPPORT_TICKET_SUCCESSFULLY_SAVED', $row->get('id'))); return; } $this->view->setLayout('edit'); $this->editTask(); }
/** * Send email * * @param object $publication Models\Publication * @param array $addressees * @param string $subject * @param string $message * @return void */ public static function notify($publication, $addressees = array(), $subject = NULL, $message = NULL, $hubMessage = false) { if (!$subject || !$message || empty($addressees)) { return false; } // Is messaging turned on? if ($publication->config('email') != 1) { return false; } // Component params $params = Component::params('com_publications'); $address = $params->get('curatorreplyto'); // Set up email config $from = array(); $from['name'] = Config::get('sitename') . ' ' . Lang::txt('COM_PUBLICATIONS'); if (!isset($address) || $address == '') { $from['email'] = Config::get('mailfrom'); } else { $from['email'] = $address; } // Html email $from['multipart'] = md5(date('U')); // Get message body $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_publications' . DS . 'site', 'name' => 'emails', 'layout' => '_plain')); $eview->publication = $publication; $eview->message = $message; $eview->subject = $subject; $body = array(); $body['plaintext'] = $eview->loadTemplate(false); $body['plaintext'] = str_replace("\n", "\r\n", $body['plaintext']); // HTML email $eview->setLayout('_html'); $body['multipart'] = $eview->loadTemplate(); $body['multipart'] = str_replace("\n", "\r\n", $body['multipart']); $body_plain = is_array($body) && isset($body['plaintext']) ? $body['plaintext'] : $body; $body_html = is_array($body) && isset($body['multipart']) ? $body['multipart'] : NULL; // Send HUB message if ($hubMessage) { Event::trigger('xmessage.onSendMessage', array('publication_status_changed', $subject, $body, $from, $addressees, 'com_publications')); } else { // Send email foreach ($addressees as $userid) { $user = User::getInstance(trim($userid)); if (!$user->get('id')) { continue; } $mail = new \Hubzero\Mail\Message(); $mail->setSubject($subject)->addTo($user->get('email'), $user->get('name'))->addFrom($from['email'], $from['name'])->setPriority('normal'); $mail->addPart($body_plain, 'text/plain'); if ($body_html) { $mail->addPart($body_html, 'text/html'); } $mail->send(); } } }
/** * Send token email * * @return bool - true if email send successfully */ private function sendEmail($token) { // Create the email with the new token $url = rtrim(Request::base(), '/'); $return = $url . Route::url($this->member->getLink() . '&acitve=account&task=confirmtoken'); $subject = 'Set local password, confirmation token for ' . $url; $message = 'You have requested to set your local password at ' . $url . "\n\n"; $message .= 'Your reset token is: ' . $token; $msg = new \Hubzero\Mail\Message(); $msg->setSubject($subject)->addTo($this->user->get('email'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->setBody($message); // Send the email if (!$msg->send()) { App::abort(500, Lang::txt('PLG_MEMBERS_ACCOUNT_CONFIRMATION_EMAIL_NOT_SENT')); return; } return true; }
/** * Add membership request for user * * @return array */ public function dorequestTask() { // Check if they're logged in if (User::isGuest()) { $this->loginTask(Lang::txt('COM_GROUPS_INVITE_MUST_BE_LOGGED_IN_TO_REQUEST')); return; } Request::checkToken(); //check to make sure we have cname if (!$this->cn) { $this->_errorHandler(400, Lang::txt('COM_GROUPS_ERROR_NO_ID')); } // Load the group page $this->view->group = Group::getInstance($this->cn); // Ensure we found the group info if (!$this->view->group || !$this->view->group->get('gidNumber')) { $this->_errorHandler(404, Lang::txt('COM_GROUPS_ERROR_NOT_FOUND')); } // Get the group params $gparams = new Registry($this->view->group->get('params')); // If membership is managed in seperate place disallow action if ($gparams->get('membership_control', 1) == 0) { $this->setNotification(Lang::txt('COM_GROUPS_MEMBERSHIP_MANAGED_ELSEWHERE'), 'error'); App::redirect(Route::url('index.php?option=com_groups&cn=' . $this->view->group->get('cn'))); return; } //make sure group has restricted policy if ($this->view->group->get('join_policy') != 1) { return; } //add user to applicants $this->view->group->add('applicants', array(User::get('id'))); $this->view->group->update(); // Instantiate the reason object and bind the incoming data $row = new Reason($this->database); $row->uidNumber = User::get('id'); $row->gidNumber = $this->view->group->get('gidNumber'); $row->reason = Request::getVar('reason', Lang::txt('GROUPS_NO_REASON_GIVEN'), 'post'); $row->reason = \Hubzero\Utility\Sanitize::stripAll($row->reason); $row->date = Date::toSql(); // Check and store the reason if (!$row->check()) { return App::abort(500, $row->getError()); } if (!$row->store()) { return App::abort(500, $row->getError()); } // Log the membership request Log::log(array('gidNumber' => $this->view->group->get('gidNumber'), 'action' => 'membership_requested', 'comments' => array(User::get('id')))); // Log activity $url = Route::url('index.php?option=' . $this->_option . '&cn=' . $this->view->group->get('cn')); $recipients = array(['group', $this->view->group->get('gidNumber')], ['user', User::get('id')]); foreach ($this->view->group->get('managers') as $recipient) { $recipients[] = ['user', $recipient]; } Event::trigger('system.logActivity', ['activity' => ['action' => 'requested', 'scope' => 'group', 'scope_id' => $this->view->group->get('gidNumber'), 'description' => Lang::txt('COM_GROUPS_ACTIVITY_GROUP_USER_REQUESTED', '<a href="' . $url . '">' . $this->view->group->get('description') . '</a>'), 'details' => array('title' => $this->view->group->get('description'), 'url' => $url, 'cn' => $this->view->group->get('cn'), 'gidNumber' => $this->view->group->get('gidNumber'))], 'recipients' => $recipients]); // E-mail subject $subject = Lang::txt('COM_GROUPS_JOIN_REQUEST_EMAIL_SUBJECT', $this->view->group->get('cn')); // Build the e-mail message $eview = new \Hubzero\Component\View(array('name' => 'emails', 'layout' => 'request')); $eview->option = $this->_option; $eview->sitename = Config::get('sitename'); $eview->user = User::getInstance(); $eview->group = $this->view->group; $eview->row = $row; $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // Get the system administrator e-mail $emailadmin = Config::get('mailfrom'); // Build the "from" portion of the e-mail $from = array(); $from['name'] = Config::get('sitename') . ' ' . Lang::txt(strtoupper($this->_name)); $from['email'] = Config::get('mailfrom'); // build array of managers $managers = array(); foreach ($this->view->group->get('managers') as $m) { $profile = User::getInstance($m); if ($profile) { $managers[$profile->get('email')] = $profile->get('name'); } } // create new message $message = new \Hubzero\Mail\Message(); // build message object and send $message->setSubject($subject)->addFrom($from['email'], $from['name'])->setTo($managers)->addHeader('X-Mailer', 'PHP/' . phpversion())->addHeader('X-Component', 'com_groups')->addHeader('X-Component-Object', 'group_membership_requested')->addPart($html, 'text/plain')->send(); //tell the user they just did good $this->setNotification(Lang::txt('COM_GROUPS_INVITE_REQUEST_FORWARDED'), 'passed'); // Push through to the groups listing App::redirect($url); }
/** * sendConfirmEmail * * @static * @access public * @return void */ public static function sendConfirmEmail($user, $xregistration) { $baseURL = rtrim(Request::base(), '/'); $subject = Config::get('sitename') . ' ' . Lang::txt('COM_MEMBERS_REGISTER_EMAIL_CONFIRMATION'); $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'create')); $eview->option = 'com_members'; //$this->_option; //com_members $eview->controller = 'register'; //$this->_controller; //register $eview->sitename = Config::get('sitename'); $eview->xprofile = $user; $eview->baseURL = $baseURL; $eview->xregistration = $xregistration; $msg = new \Hubzero\Mail\Message(); $msg->setSubject($subject)->addTo($user->get('email'), $user->get('name'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', 'com_members'); $message = $eview->loadTemplate(false); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/plain'); $eview->setLayout('create_html'); $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); $msg->addPart($message, 'text/html'); if (!$msg->send()) { $this->setError(Lang::txt('COM_MEMBERS_REGISTER_ERROR_EMAILING_CONFIRMATION')); // @FIXME: LOG ERROR SOMEWHERE return false; } else { return true; } }
/** * Processes intial reset password request * * @return void */ public function resettingTask() { // Check the request token Session::checkToken('post') or exit(Lang::txt('JINVALID_TOKEN')); // Grab the incoming username if (!($username = trim(Request::getVar('username', false)))) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_MISSING_USERNAME'), 'warning'); return; } // Make sure it looks like a valid username require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'utility.php'; // Determine if attempting to log in via username or email address if (strpos($username, '@')) { $validator = 'validemail'; $field = 'email'; } else { $validator = 'validlogin'; $field = 'username'; } if (!\Components\Members\Helpers\Utility::$validator($username)) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_INVALID_USERNAME'), 'warning'); return; } // Find the user for the given username $user = \Hubzero\User\User::whereEquals($field, $username)->rows(); // Make sure we have at least one and not more than one if ($user->count() < 1) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_USER_NOT_FOUND'), 'warning'); return; } else { if ($user->count() > 1) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_MULTIPLE_RESULTS'), 'warning'); return; } } // Get the user object $user = $user->first(); // Make sure the user isn't blocked if ($user->get('block')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_USER_NOT_FOUND'), 'warning'); return; } // Make sure the user isn't a super admin if ($user->authorise('core.admin')) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_USER_IS_SUPER'), 'warning'); return; } // Make sure the user has not exceeded the reset limit if ($this->hasExceededResetLimit($user)) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=reset', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_EXCEEDED_LIMIT'), 'warning'); return; } // Set the confirmation token $token = App::hash(\JUserHelper::genRandomPassword()); $salt = \JUserHelper::getSalt('crypt-md5'); $hashedToken = md5($token . $salt) . ':' . $salt; // Save the token $user->tokens()->save(['token' => $hashedToken]); // Send an email $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'reset_plain')); $eview->config = Config::getRoot(); $eview->baseUrl = rtrim(Request::base(), '/'); $eview->user = $user; $eview->token = $token; $eview->return = Route::url('index.php?option=' . $this->_option . '&task=verify'); $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $eview->setLayout('reset_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // Build message $message = new \Hubzero\Mail\Message(); $message->setSubject(Lang::txt('COM_MEMBERS_CREDENTIALS_EMAIL_RESET_SUBJECT', Config::get('sitename')))->addFrom(Config::get('mailfrom'), Config::get('fromname'))->addTo($user->get('email'), $user->get('name'))->addHeader('X-Component', $this->_option)->addHeader('X-Component-Object', 'password_reset')->addPart($plain, 'text/plain')->addPart($html, 'text/html'); // Send mail if (!$message->send()) { Log::error('Members password reset email failed: ' . Lang::txt('Failed to mail %s', $user->get('email'))); App::redirect(Route::url('index.php?option=' . $this->_option . '&task=remind', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_FIAILED_TO_SEND_MAIL'), 'warning'); return; } // Push the user data into the session User::setState('com_users.reset.user', $user->get('id')); // Everything went well...go to the token verification page App::redirect(Route::url('index.php?option=' . $this->_option . '&task=verify', false), Lang::txt('COM_MEMBERS_CREDENTIALS_EMAIL_SENT'), 'passed'); }
/** * Send an email to a user * stating their account has been approved * * @param object $user * @return bool */ protected function emailApprovedUser($user) { // Compute the mail subject. $emailSubject = Lang::txt('COM_MEMBERS_APPROVED_USER_EMAIL_SUBJECT', $user->get('name'), Config::get('sitename')); // Compute the mail body. $eview = new \Hubzero\Mail\View(array('base_path' => dirname(dirname(__DIR__)) . DS . 'site', 'name' => 'emails', 'layout' => 'approved_plain')); $eview->option = $this->_option; $eview->controller = $this->_controller; $eview->config = $this->config; $eview->baseURL = Request::root(); $eview->user = $user; $eview->sitename = Config::get('sitename'); $plain = $eview->loadTemplate(false); $plain = str_replace("\n", "\r\n", $plain); $eview->setLayout('approved_html'); $html = $eview->loadTemplate(); $html = str_replace("\n", "\r\n", $html); // Build the message and send it $mail = new \Hubzero\Mail\Message(); $mail->addFrom(Config::get('mailfrom'), Config::get('fromname'))->addTo($user->get('email'))->setSubject($emailSubject); $mail->addPart($plain, 'text/plain'); $mail->addPart($html, 'text/html'); if (!$mail->send()) { return false; } return true; }