示例#1
0
 /**
  * Runs extra setup code when creating a new model
  *
  * @return  void
  */
 public function setup()
 {
     $this->addRule('ip', function ($data) {
         if (isset($data['ip']) && !Validate::ip($data['ip'])) {
             return Lang::txt('Invalid IP address');
         }
         return false;
     });
 }
示例#2
0
 /**
  * Check method, used when saving
  * 
  * @return  bool
  */
 public function check()
 {
     // verify name
     $this->name = trim($this->name);
     if ($this->name == '') {
         $this->setError(Lang::txt('COM_DEVELOPER_API_APPLICATION_MISSING_NAME'));
         return false;
     }
     // verify description
     $this->description = trim($this->description);
     if ($this->description == '') {
         $this->setError(Lang::txt('COM_DEVELOPER_API_APPLICATION_MISSING_DESCRIPTION'));
         return false;
     }
     // verify redirect URIs
     $uris = array_map('trim', explode(PHP_EOL, $this->redirect_uri));
     // must have one
     if (empty($uris)) {
         $this->setError(Lang::txt('COM_DEVELOPER_API_APPLICATION_MISSING_REDIRECT_URI'));
         return false;
     }
     // validate each one
     $invalid = array();
     foreach ($uris as $uri) {
         if (!Validate::url($uri)) {
             $invalid[] = $uri;
         }
     }
     // if we have any invalid URIs lets inform the user
     if (!empty($invalid)) {
         $this->setError(Lang::txt('COM_DEVELOPER_API_APPLICATION_INVALID_REDIRECT_URI', implode('<br />', $invalid)));
         return false;
     }
     // turn back into string for saving
     $this->redirect_uri = implode(' ', $uris);
     // if we dont have a created by add one
     if (!$this->created_by) {
         $this->created_by = User::get('id');
     }
     // if this is a new record
     if (!$this->id) {
         $this->created = with(new Date('now'))->toSql();
         if (!$this->hub_account) {
             // Allow the 3 main grantypes
             //
             // authorization code = 3 legged oauth
             // password           = users username/password
             // refresh_token      = allow refreshing of access_tokens to require less logins
             $this->grant_types = 'authorization_code password refresh_token';
         }
         // generate unique client id & secret
         list($this->client_id, $this->client_secret) = $this->generateUniqueClientIdAndSecret();
     }
     return true;
 }
示例#3
0
 /**
  * Processes the username recovery request
  *
  * @return  void
  */
 public function remindingTask()
 {
     // Check the request token
     Session::checkToken('post') or exit(Lang::txt('JINVALID_TOKEN'));
     // Get the email address
     if (!($email = trim(Request::getVar('email', false)))) {
         App::redirect(Route::url('index.php?option=' . $this->_option . '&task=remind', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_MISSING_EMAIL'), 'warning');
         return;
     }
     // Make sure it looks like a valid email address
     if (!\Hubzero\Utility\Validate::email($email)) {
         App::redirect(Route::url('index.php?option=' . $this->_option . '&task=remind', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_INVALID_EMAIL'), 'warning');
         return;
     }
     // Find the user(s) for the given email address
     $users = \Hubzero\User\User::whereEquals('email', $email)->whereEquals('block', 0)->rows();
     // Make sure we have at least one
     if ($users->count() < 1) {
         App::redirect(Route::url('index.php?option=' . $this->_option . '&task=remind', false), Lang::txt('COM_MEMBERS_CREDENTIALS_ERROR_USER_NOT_FOUND'), 'warning');
         return;
     }
     $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'remind_plain'));
     $eview->config = Config::getRoot();
     $eview->baseUrl = rtrim(Request::base(), DS);
     $eview->users = $users;
     $plain = $eview->loadTemplate(false);
     $plain = str_replace("\n", "\r\n", $plain);
     // HTML
     $eview->setLayout('remind_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_REMIND_SUBJECT', Config::get('sitename')))->addFrom(Config::get('mailfrom'), Config::get('fromname'))->addTo($email, $users->first()->name)->addHeader('X-Component', $this->_option)->addHeader('X-Component-Object', 'username_reminder')->addPart($plain, 'text/plain')->addPart($html, 'text/html');
     // Send mail
     if (!$message->send()) {
         Log::error('Members username reminder email failed: ' . Lang::txt('Failed to mail %s', $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;
     }
     // Everything went well...go to the login page
     App::redirect(Route::url('index.php?option=com_users&view=login', false), Lang::txt('COM_MEMBERS_CREDENTIALS_EMAIL_SENT'), 'passed');
 }
示例#4
0
 /**
  * Validate data
  *
  * @return  boolean  True if data is valid
  */
 public function check()
 {
     $this->response_id = intval($this->response_id);
     if (!$this->response_id) {
         $this->setError(Lang::txt('Missing response ID'));
     }
     $this->helpful = strtolower(trim($this->helpful));
     if (!$this->helpful) {
         $this->setError(Lang::txt('Missing vote'));
     }
     if (!in_array($this->helpful, array(1, 'yes', 'like', 'up', -1, 'no', 'dislike', 'down'))) {
         $this->setError(Lang::txt('Invalid vote'));
     }
     if (!Validate::ip($this->ip)) {
         $this->setError(Lang::txt('Invalid IP address'));
     }
     if ($this->getError()) {
         return false;
     }
     return true;
 }
示例#5
0
 /**
  * Validate data
  *
  * @return  boolean  True if data is valid
  */
 public function check()
 {
     $this->question_id = intval($this->question_id);
     if (!$this->question_id) {
         $this->setError(Lang::txt('Missing question ID'));
     }
     $this->voter = intval($this->voter);
     if (!$this->voter) {
         $this->voter = User::get('id');
     }
     if (!$this->expires) {
         $this->expires = Date::of(time() + 7 * 24 * 60 * 60)->toSql();
         // in a week
     }
     if (!Validate::ip($this->ip)) {
         $this->setError(Lang::txt('Invalid IP address'));
     }
     if ($this->getError()) {
         return false;
     }
     return true;
 }
示例#6
0
 /**
  * Validate data
  *
  * @return  boolean  True if data is valid
  */
 public function check()
 {
     $this->referenceid = intval($this->referenceid);
     if (!$this->referenceid) {
         $this->setError(Lang::txt('Missing reference ID'));
     }
     $this->category = trim($this->category);
     if (!$this->category) {
         $this->setError(Lang::txt('Missing category'));
     }
     if (!$this->id) {
         $this->voted = $this->voted ? $this->voted : Date::toSql();
         $this->voter = $this->voter ? $this->voter : User::get('id');
     }
     if (!Validate::ip($this->ip)) {
         $this->setError(Lang::txt('Invalid IP address'));
     }
     if ($this->getError()) {
         return false;
     }
     return true;
 }
示例#7
0
 /**
  * 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('&amp;', '&', $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();
 }
示例#8
0
 /**
  * Checks that var is email
  *
  * @param   string       $key  The field name
  * @param   mixed        $var  The field content
  * @return  bool|string
  * @since   2.0.0
  **/
 private static function email($key, $var)
 {
     return \Hubzero\Utility\Validate::email($var) ? false : "{$key} does not appear to be a valid email address";
 }
示例#9
0
 /**
  * Sets up additional custom rules
  *
  * @return  void
  */
 public function setup()
 {
     // Check that username conforms to rules
     $this->addRule('username', function ($data) {
         $username = $data['username'];
         // We do this here because we need to allow one possible
         // "invalid" username to pass through, used when creating
         // temp accounts during the 3rd party auth registration
         if (is_numeric($username) && $username < 0) {
             return false;
         }
         if (preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $username) || strlen(utf8_decode($username)) < 2 || trim($username) != $username) {
             return \Lang::txt('JLIB_DATABASE_ERROR_VALID_AZ09', 2);
         }
         return false;
     });
     // Check for existing username
     $this->addRule('username', function ($data) {
         $user = self::oneByUsername($data['username']);
         if ($user->get('id') && $user->get('id') != $data['id']) {
             return \Lang::txt('JLIB_DATABASE_ERROR_USERNAME_INUSE');
         }
         return false;
     });
     // Check for valid email address
     // We do this here because we need to allow one possible
     // "invalid" address to pass through, used when creating
     // temp accounts during the 3rd party auth registration
     $this->addRule('email', function ($data) {
         $email = $data['email'];
         if (preg_match('/^-[0-9]+@invalid$/', $email)) {
             return false;
         }
         return \Hubzero\Utility\Validate::email($email) ? false : 'Email does not appear to be valid';
     });
 }
示例#10
0
 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();
     }
 }
示例#11
0
 /**
  * Check if a group exists.
  * Given the group id, returns true if group exists.
  *
  * @param   integer  $group         The group id number (GID) of the group being verified.
  * @param   boolean  $check_system  Boolean for checking against POSIX user.
  * @return  boolean  Returns false if group does not exist; true if group exists.
  */
 public static function exists($group, $check_system = false)
 {
     $db = \App::get('db');
     if (empty($group)) {
         return false;
     }
     if ($check_system) {
         if (is_numeric($group) && posix_getgrgid($group)) {
             return true;
         }
         if (!is_numeric($group) && posix_getgrnam($group)) {
             return true;
         }
     }
     // check reserved
     if (Validate::reserved('group', $group)) {
         return true;
     }
     if (is_numeric($group)) {
         $query = 'SELECT gidNumber FROM `#__xgroups` WHERE gidNumber=' . $db->quote($group);
     } else {
         $query = 'SELECT gidNumber FROM `#__xgroups` WHERE cn=' . $db->quote($group);
     }
     $db->setQuery($query);
     if (!$db->query()) {
         return false;
     }
     if ($db->loadResult() > 0) {
         return true;
     }
     return false;
 }
示例#12
0
 /**
  * Sets up additional custom rules
  *
  * @return  void
  **/
 public function setup()
 {
     $this->addRule('redirect_uri', function ($data) {
         if (!isset($data['redirect_uri']) || !$data['redirect_uri']) {
             return Lang::txt('COM_DEVELOPER_API_APPLICATION_MISSING_REDIRECT_URI');
         }
         $uris = array_map('trim', explode(PHP_EOL, $data['redirect_uri']));
         // must have one
         if (empty($uris)) {
             return Lang::txt('COM_DEVELOPER_API_APPLICATION_MISSING_REDIRECT_URI');
         }
         // validate each one
         $invalid = array();
         foreach ($uris as $uri) {
             if (!Validate::url($uri)) {
                 $invalid[] = $uri;
             }
         }
         // if we have any invalid URIs lets inform the user
         if (!empty($invalid)) {
             return Lang::txt('COM_DEVELOPER_API_APPLICATION_INVALID_REDIRECT_URI', implode('<br />', $invalid));
         }
         return false;
     });
 }
示例#13
0
 /**
  * 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();
 }
示例#14
0
 /**
  * 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;
 }
示例#15
0
 /**
  * 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();
 }
示例#16
0
 /**
  * Create a user profile
  *
  * @apiMethod POST
  * @apiUri    /members
  * @return    void
  */
 public function createTask()
 {
     $this->requiresAuthentication();
     // Initialize new usertype setting
     $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();
     }
     // Incoming
     $user = User::getInstance();
     $user->set('id', 0);
     $user->set('groups', array($newUsertype));
     $user->set('registerDate', Date::toSql());
     $user->set('name', Request::getVar('name', '', 'post'));
     if (!$user->get('name')) {
         App::abort(500, Lang::txt('No name provided.'));
     }
     $user->set('username', Request::getVar('username', '', 'post'));
     if (!$user->get('username')) {
         App::abort(500, Lang::txt('No username provided.'));
     }
     if (!\Hubzero\Utility\Validate::username($user->get('username'))) {
         App::abort(500, Lang::txt('Username not valid.'));
     }
     $user->set('email', Request::getVar('email', '', 'post'));
     if (!$user->get('email')) {
         App::abort(500, Lang::txt('No email provided.'));
     }
     if (!\Hubzero\Utility\Validate::email($user->get('email'))) {
         App::abort(500, Lang::txt('Email not valid.'));
     }
     $name = explode(' ', $user->get('name'));
     $surname = $user->get('name');
     $givenName = '';
     $middleName = '';
     if (count($name) > 1) {
         $surname = array_pop($name);
         $givenName = array_shift($name);
         $middleName = implode(' ', $name);
     }
     // Set the new info
     $user->set('givenName', $givenName);
     $user->set('middleName', $middleName);
     $user->set('surname', $surname);
     $user->set('activation', -rand(1, pow(2, 31) - 1));
     $user->set('access', 1);
     $user->set('password', $password);
     //$user->set('password_clear', $password);
     $result = $user->save();
     $user->set('password_clear', '');
     $user->set('password', '');
     if ($result) {
         $result = \Hubzero\User\Password::changePassword($user->get('id'), $password);
         // Set password back here in case anything else down the line is looking for it
         $user->set('password', $password);
         $user->save();
     }
     // Did we successfully create/update an account?
     if (!$result) {
         App::abort(500, Lang::txt('Account creation failed.'));
     }
     if ($groups = Request::getVar('groups', array(), 'post')) {
         foreach ($groups as $id) {
             $group = \Hubzero\User\Group::getInstance($id);
             if ($group) {
                 if (!in_array($user->get('id'), $group->get('members'))) {
                     $group->add('members', array($user->get('id')));
                     $group->update();
                 }
             }
         }
     }
     // Create a response object
     $response = new stdClass();
     $response->id = $user->get('id');
     $response->name = $user->get('name');
     $response->email = $user->get('email');
     $response->username = $user->get('username');
     $this->send($response);
 }
示例#17
0
 /**
  * Save an entry and return to main listing
  *
  * @return  void
  */
 public function saveTask()
 {
     // Check for request forgeries
     Request::checkToken();
     if (!User::authorise('core.manage', $this->_option) && !User::authorise('core.admin', $this->_option) && !User::authorise('core.create', $this->_option) && !User::authorise('core.edit', $this->_option)) {
         App::abort(403, Lang::txt('JERROR_ALERTNOAUTHOR'));
     }
     // Incoming profile edits
     $fields = Request::getVar('fields', array(), 'post', 'none', 2);
     // Load the profile
     $user = Member::oneOrNew($fields['id']);
     // Get the user before changes so we can
     // compare how data changed later on
     $prev = clone $user;
     // Set the incoming data
     $user->set($fields);
     if ($user->isNew()) {
         $newUsertype = $this->config->get('new_usertype');
         if (!$newUsertype) {
             $newUsertype = Accessgroup::oneByTitle('Registered')->get('id');
         }
         $user->set('accessgroups', array($newUsertype));
         // Check that username is filled
         if (!Validate::username($user->get('username'))) {
             Notify::error(Lang::txt('COM_MEMBERS_MEMBER_USERNAME_INVALID'));
             return $this->editTask($user);
         }
         // Check email is valid
         if (!Validate::email($user->get('email'))) {
             Notify::error(Lang::txt('COM_MEMBERS_MEMBER_EMAIL_INVALID'));
             return $this->editTask($user);
         }
         // Set home directory
         $hubHomeDir = rtrim($this->config->get('homedir'), '/');
         if (!$hubHomeDir) {
             // try to deduce a viable home directory based on sitename or live_site
             $sitename = strtolower(Config::get('sitename'));
             $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1);
             $sitename = trim($sitename, '/ ');
             $sitename_e = explode('.', $sitename, 2);
             if (isset($sitename_e[1])) {
                 $sitename = $sitename_e[0];
             }
             if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) {
                 $sitename = '';
             }
             if (empty($sitename)) {
                 $sitename = strtolower(Request::base());
                 $sitename = preg_replace('/^http[s]{0,1}:\\/\\//', '', $sitename, 1);
                 $sitename = trim($sitename, '/ ');
                 $sitename_e = explode('.', $sitename, 2);
                 if (isset($sitename_e[1])) {
                     $sitename = $sitename_e[0];
                 }
                 if (!preg_match("/^[a-zA-Z]+[\\-_0-9a-zA-Z\\.]+\$/i", $sitename)) {
                     $sitename = '';
                 }
             }
             $hubHomeDir = DS . 'home';
             if (!empty($sitename)) {
                 $hubHomeDir .= DS . $sitename;
             }
         }
         $user->set('homeDirectory', $hubHomeDir . DS . $user->get('username'));
         $user->set('loginShell', '/bin/bash');
         $user->set('ftpShell', '/usr/lib/sftp-server');
         $user->set('registerDate', Date::toSql());
     }
     // Set the new info
     $user->set('givenName', preg_replace('/\\s+/', ' ', trim($fields['givenName'])));
     $user->set('middleName', preg_replace('/\\s+/', ' ', trim($fields['middleName'])));
     $user->set('surname', preg_replace('/\\s+/', ' ', trim($fields['surname'])));
     $name = array($user->get('givenName'), $user->get('middleName'), $user->get('surname'));
     $name = implode(' ', $name);
     $name = preg_replace('/\\s+/', ' ', $name);
     $user->set('name', $name);
     $user->set('modifiedDate', Date::toSql());
     if ($ec = Request::getInt('activation', 0, 'post')) {
         $user->set('activation', $ec);
     } else {
         $user->set('activation', Helpers\Utility::genemailconfirm());
     }
     // Can't block yourself
     if ($user->get('block') && $user->get('id') == User::get('id') && !User::get('block')) {
         Notify::error(Lang::txt('COM_USERS_USERS_ERROR_CANNOT_BLOCK_SELF'));
         return $this->editTask($user);
     }
     // Make sure that we are not removing ourself from Super Admin group
     $iAmSuperAdmin = User::authorise('core.admin');
     if ($iAmSuperAdmin && User::get('id') == $user->get('id')) {
         // Check that at least one of our new groups is Super Admin
         $stillSuperAdmin = false;
         foreach ($fields['accessgroups'] as $group) {
             $stillSuperAdmin = $stillSuperAdmin ? $stillSuperAdmin : \JAccess::checkGroup($group, 'core.admin');
         }
         if (!$stillSuperAdmin) {
             Notify::error(Lang::txt('COM_USERS_USERS_ERROR_CANNOT_DEMOTE_SELF'));
             return $this->editTask($user);
         }
     }
     // Save the changes
     if (!$user->save()) {
         Notify::error($user->getError());
         return $this->editTask($user);
     }
     // Save profile data
     $profile = Request::getVar('profile', array(), 'post', 'none', 2);
     $access = Request::getVar('profileaccess', array(), 'post', 'none', 2);
     foreach ($profile as $key => $data) {
         if (isset($profile[$key]) && is_array($profile[$key])) {
             $profile[$key] = array_filter($profile[$key]);
         }
         if (isset($profile[$key . '_other']) && trim($profile[$key . '_other'])) {
             if (is_array($profile[$key])) {
                 $profile[$key][] = $profile[$key . '_other'];
             } else {
                 $profile[$key] = $profile[$key . '_other'];
             }
             unset($profile[$key . '_other']);
         }
     }
     if (!$user->saveProfile($profile, $access)) {
         Notify::error($user->getError());
         return $this->editTask($user);
     }
     // Do we have a new pass?
     $newpass = trim(Request::getVar('newpass', '', 'post'));
     if ($newpass) {
         // Get password rules and validate
         $password_rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows();
         $validated = \Hubzero\Password\Rule::verify($newpass, $password_rules, $user->get('id'));
         if (!empty($validated)) {
             // Set error
             Notify::error(Lang::txt('COM_MEMBERS_PASSWORD_DOES_NOT_MEET_REQUIREMENTS'));
             $this->validated = $validated;
             $this->_task = 'apply';
         } else {
             // Save password
             \Hubzero\User\Password::changePassword($user->get('username'), $newpass);
         }
     }
     $passinfo = \Hubzero\User\Password::getInstance($user->get('id'));
     if (is_object($passinfo)) {
         // Do we have shadow info to change?
         $shadowMax = Request::getInt('shadowMax', false, 'post');
         $shadowWarning = Request::getInt('shadowWarning', false, 'post');
         $shadowExpire = Request::getVar('shadowExpire', '', 'post');
         if ($shadowMax || $shadowWarning || !is_null($passinfo->get('shadowExpire')) && empty($shadowExpire)) {
             if ($shadowMax) {
                 $passinfo->set('shadowMax', $shadowMax);
             }
             if ($shadowExpire || !is_null($passinfo->get('shadowExpire')) && empty($shadowExpire)) {
                 if (preg_match("/[0-9]{4}-[0-9]{2}-[0-9]{2}/", $shadowExpire)) {
                     $shadowExpire = strtotime($shadowExpire) / 86400;
                     $passinfo->set('shadowExpire', $shadowExpire);
                 } elseif (preg_match("/[0-9]+/", $shadowExpire)) {
                     $passinfo->set('shadowExpire', $shadowExpire);
                 } elseif (empty($shadowExpire)) {
                     $passinfo->set('shadowExpire', NULL);
                 }
             }
             if ($shadowWarning) {
                 $passinfo->set('shadowWarning', $shadowWarning);
             }
             $passinfo->update();
         }
     }
     // Check for spam count
     $reputation = Request::getVar('spam_count', null, 'post');
     if (!is_null($reputation)) {
         $user->reputation->set('spam_count', $reputation);
         $user->reputation->save();
     }
     // Email the user that their account has been approved
     if (!$prev->get('approved') && $this->config->get('useractivation_email')) {
         if (!$this->emailApprovedUser($user)) {
             Notify::error(Lang::txt('COM_MEMBERS_ERROR_EMAIL_FAILED'));
         }
     }
     // Set success message
     Notify::success(Lang::txt('COM_MEMBERS_MEMBER_SAVED'));
     // Drop through to edit form?
     if ($this->getTask() == 'apply') {
         return $this->editTask($user);
     }
     // Redirect
     $this->cancelTask();
 }
示例#18
0
 /**
  * Change publication status
  *
  * @return     string
  */
 public function publishDraft()
 {
     // Incoming
     $pid = $this->_pid ? $this->_pid : Request::getInt('pid', 0);
     $confirm = Request::getInt('confirm', 0);
     $version = Request::getVar('version', 'dev');
     $agree = Request::getInt('agree', 0);
     $pubdate = Request::getVar('publish_date', '', 'post');
     $submitter = Request::getInt('submitter', $this->_uid, 'post');
     $notify = 1;
     $block = Request::getVar('section', '');
     $blockId = Request::getInt('step', 0);
     $element = Request::getInt('element', 0);
     // Check permission
     if (!$this->model->access('content')) {
         throw new Exception(Lang::txt('ALERTNOTAUTH'), 403);
         return;
     }
     // Load review step
     if (!$confirm && $this->_task != 'revert') {
         $this->_task = 'review';
         return $this->editDraft();
     }
     // Load publication model
     $pub = new \Components\Publications\Models\Publication($pid, $version);
     // Error loading publication record
     if (!$pub->exists()) {
         \Notify::message(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_NOT_FOUND'), 'error', 'projects');
         App::redirect(Route::url($pub->link('editbase')));
         return;
     }
     // Agreement to terms is required
     if ($confirm && !$agree) {
         \Notify::message(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_REVIEW_AGREE_TERMS_REQUIRED'), 'error', 'projects');
         App::redirect(Route::url($pub->link('editversion') . '&action=' . $this->_task));
         return;
     }
     // Check against quota
     if ($this->_overQuota()) {
         \Notify::message(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_NO_DISK_SPACE'), 'error', 'projects');
         App::redirect(Route::url($pub->link('editversion') . '&action=' . $this->_task));
         return;
     }
     // Set curation
     $pub->setCuration();
     // Require DOI?
     $requireDoi = isset($pub->_curationModel->_manifest->params->require_doi) ? $pub->_curationModel->_manifest->params->require_doi : 0;
     // Make sure the publication belongs to the project
     if (!$pub->belongsToProject($this->model->get('id'))) {
         Notify::message(Lang::txt('PLG_PROJECTS_PUBLICATIONS_ERROR_PROJECT_ASSOC'), 'error', 'projects');
         App::redirect(Route::url($this->model->link('publications')));
         return;
     }
     // Check that version label was not published before
     $used_labels = $pub->version->getUsedLabels($pid, $version);
     if (!$pub->version->version_label || in_array($pub->version->version_label, $used_labels)) {
         $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_VERSION_LABEL_USED'));
     }
     // Is draft complete?
     if (!$pub->curation('complete') && $this->_task != 'revert') {
         $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_NOT_ALLOWED'));
     }
     // Is revert allowed?
     $revertAllowed = $this->_pubconfig->get('graceperiod', 0);
     if ($revertAllowed && $pub->version->state == 1 && $pub->version->accepted && $pub->version->accepted != '0000-00-00 00:00:00') {
         $monthFrom = Date::of($pub->version->accepted . '+1 month')->toSql();
         if (strtotime($monthFrom) < strtotime(Date::of())) {
             $revertAllowed = 0;
         }
     }
     // Embargo?
     if ($pubdate) {
         $pubdate = $this->_parseDate($pubdate);
         $tenYearsFromNow = Date::of(strtotime("+10 years"))->toSql();
         // Stop if more than 10 years from now
         if ($pubdate > $tenYearsFromNow) {
             $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_ERROR_EMBARGO'));
         }
     }
     // Contact info is required for repositories
     if ($pub->config()->get('repository')) {
         $contact = Request::getVar('contact', array(), 'post');
         if (!$contact || empty($contact)) {
             $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_ERROR_CONTACT_INFO_MISSING'));
         }
         foreach (array('name', 'email', 'phone') as $key) {
             if (!isset($contact[$key]) || !$contact[$key]) {
                 $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_ERROR_CONTACT_INFO_MISSING'));
             }
         }
         if (!\Hubzero\Utility\Validate::email($contact['email'])) {
             $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_ERROR_CONTACT_INVALID_EMAIL'));
         }
         if (!\Hubzero\Utility\Validate::phone($contact['phone'])) {
             $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_ERROR_CONTACT_INVALID_PHONE'));
         }
         $data = array();
         preg_match_all("#<nb:(.*?)>(.*?)</nb:(.*?)>#s", $pub->version->metadata, $matches, PREG_SET_ORDER);
         if (count($matches) > 0) {
             foreach ($matches as $match) {
                 $data[$match[1]] = $match[2];
             }
         }
         foreach ($contact as $key => $val) {
             $data['repository_' . $key] = $val;
         }
         $metadata = '';
         foreach ($data as $k => $v) {
             $metadata .= "\n" . '<nb:' . $k . '>' . $v . '</nb:' . $k . '>' . "\n";
         }
         $pub->version->metadata = $metadata;
     }
     // Main version?
     $main = $this->_task == 'republish' ? $pub->version->main : 1;
     $main_vid = $pub->version->getMainVersionId($pid);
     // current default version
     // Save version before changes
     $originalStatus = $pub->version->state;
     // Checks
     if ($this->_task == 'republish' && $pub->version->state != 0) {
         // Can only re-publish unpublished version
         $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_CANNOT_REPUBLISH'));
     } elseif ($this->_task == 'revert' && $pub->version->state != 5 && !$revertAllowed) {
         // Can only revert a pending resource
         $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_CANNOT_REVERT'));
     }
     // On error
     if ($this->getError()) {
         \Notify::message($this->getError(), 'error', 'projects');
         App::redirect(Route::url($pub->link('editversion') . '&action=' . $this->_task));
         return;
     }
     // Determine state
     $state = 5;
     // Default - pending approval
     if ($this->_task == 'share' || $this->_task == 'revert') {
         $state = 4;
         // No approval needed
     } elseif ($this->_task == 'republish') {
         $state = 1;
         // No approval needed
     } else {
         $pub->version->set('submitted', Date::toSql());
         // Save submitter
         $pa = new \Components\Publications\Tables\Author($this->_database);
         $pa->saveSubmitter($pub->version->id, $submitter, $this->model->get('id'));
         if ($this->_pubconfig->get('autoapprove') == 1) {
             $state = 1;
         } else {
             $apu = $this->_pubconfig->get('autoapproved_users');
             $apu = explode(',', $apu);
             $apu = array_map('trim', $apu);
             if (in_array(User::get('username'), $apu)) {
                 // Set status to published
                 $state = 1;
             } else {
                 // Set status to pending review (submitted)
                 $state = 5;
             }
         }
     }
     // Save state
     $pub->version->set('state', $state);
     $pub->version->set('main', $main);
     if ($this->_task != 'revert') {
         $publishedUp = $this->_task == 'republish' ? $pub->version->published_up : Date::toSql();
         $publishedUp = $pubdate ? $pubdate : $publishedUp;
         $pub->version->set('rating', '0.0');
         $pub->version->set('published_up', $publishedUp);
         $pub->version->set('published_down', '');
     }
     $pub->version->set('modified', Date::toSql());
     $pub->version->set('modified_by', $this->_uid);
     // Issue DOI
     /*if ($requireDoi > 0 && $this->_task == 'publish' && !$pub->version->doi)
     		{
     			// Get DOI service
     			$doiService = new \Components\Publications\Models\Doi($pub);
     			$extended = $state == 5 ? false : true;
     			$doi = $doiService->register($extended);
     
     			// Store DOI
     			if ($doi)
     			{
     				$pub->version->set('doi', $doi);
     			}
     
     			// Can't proceed without a valid DOI
     			if (!$doi || $doiService->getError())
     			{
     				$this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_ERROR_DOI')
     					. ' ' . $doiService->getError());
     			}
     		}*/
     // Proceed if no error
     if (!$this->getError()) {
         if ($state == 1) {
             // Get and save manifest and its version
             $versionNumber = $pub->_curationModel->checkCurationVersion();
             $pub->version->set('curation', json_encode($pub->_curationModel->_manifest));
             $pub->version->set('curation_version_id', $versionNumber);
         }
         // Save data
         if (!$pub->version->store()) {
             throw new Exception(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_FAILED'), 403);
             return;
         }
         // Remove main flag from previous default version
         if ($main && $main_vid && $main_vid != $pub->version->get('id')) {
             $pub->version->removeMainFlag($main_vid);
         }
     }
     // OnAfterPublish
     $this->onAfterChangeState($pub, $originalStatus);
     // Redirect
     App::redirect(Route::url($pub->link('editversion')));
     return;
 }
示例#19
0
 /**
  * Create a group
  *
  * @apiMethod POST
  * @apiUri    /groups
  * @apiParameter {
  * 		"name":          "cn",
  * 		"description":   "Group alias that appears in the url for group. Only lowercase alphanumeric chars allowed.",
  * 		"type":          "string",
  * 		"required":      true,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "title",
  * 		"description":   "Group title",
  * 		"type":          "string",
  * 		"required":      true,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "tags",
  * 		"description":   "Group tags",
  * 		"type":          "string (comma separated)",
  * 		"required":      false,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "public_description",
  * 		"description":   "Group public description",
  * 		"type":          "string",
  * 		"required":      false,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "private_description",
  * 		"description":   "Group private description",
  * 		"type":          "string",
  * 		"required":      false,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "join_policy",
  * 		"description":   "Membership join policy",
  * 		"type":          "string",
  * 		"required":      true,
  * 		"default":       "open",
  * 		"allowedValues": "open, restricted, invite_only, closed"
  * }
  * @apiParameter {
  * 		"name":          "discoverability",
  * 		"description":   "Is the group shown in hub searches/listings.",
  * 		"type":          "string",
  * 		"required":      true,
  * 		"default":       "visible",
  * 		"allowedValues": "visible, hidden"
  * }
  * @return  void
  */
 public function createTask()
 {
     $this->requiresAuthentication();
     $cn = Request::getWord('cn', '');
     $title = Request::getVar('title', '');
     $tags = Request::getVar('tags', '');
     $publicDesc = Request::getVar('public_description', '');
     $privateDesc = Request::getVar('private_description', '');
     $joinPolicy = strtolower(Request::getWord('join_policy', 'open'));
     $discoverability = Request::getWord('discoverability', 'visible');
     // var to hold errors
     $errors = array();
     // check for required fields (cn & title)
     if ($cn == '') {
         $errors[] = array('field' => 'cn', 'message' => Lang::txt('Group cn cannot be empty.'));
     }
     if ($title == '') {
         $errors[] = array('field' => 'title', 'message' => Lang::txt('Group title cannot be empty.'));
     }
     // check to make sure cn is valid & isnt taken
     if (!\Hubzero\Utility\Validate::group($cn, false)) {
         $errors[] = array('field' => 'cn', 'message' => Lang::txt('COM_GROUPS_SAVE_ERROR_INVALID_ID'));
     }
     if (\Hubzero\User\Group::exists($cn, false)) {
         $errors[] = array('field' => 'cn', 'message' => Lang::txt('COM_GROUPS_SAVE_ERROR_ID_TAKEN'));
     }
     // valid join policy
     $policies = array(0 => 'open', 1 => 'restricted', 2 => 'invite_only', 3 => 'closed');
     // make sure we have a valid policy
     if (!in_array($joinPolicy, $policies)) {
         $errors[] = array('field' => 'join_policy', 'message' => Lang::txt('Group "join_policy" value must be one of the following: %s', implode(', ', $policies)));
     }
     // valid discoverabilities
     $discoverabilities = array(0 => 'visible', 1 => 'hidden');
     // make sure we have a valid discoverability
     if (!in_array($discoverability, $discoverabilities)) {
         $errors[] = array('field' => 'discoverability', 'message' => Lang::txt('Group "discoverability" value must be one of the following: %s', implode(', ', $discoverabilities)));
     }
     // check for errors at this point
     if (!empty($errors)) {
         throw new Exception(Lang::txt('Validation Failed') . ': ' . implode("\n", $errors), 422);
     }
     // make sure we have a public desc of none was entered
     if ($publicDesc == '') {
         $publicDesc = $title;
     }
     // map the join policy & discoverability values to their int value
     $joinPolicy = array_search($joinPolicy, $policies);
     $discoverability = array_search($discoverability, $discoverabilities);
     // bind all our fields to the group object
     $group = new \Hubzero\User\Group();
     $group->set('cn', $cn);
     $group->set('type', 1);
     $group->set('published', 1);
     $group->set('approved', \App::get('component')->params('com_groups')->get('auto_approve', 1));
     $group->set('description', $title);
     $group->set('public_desc', $publicDesc);
     $group->set('private_desc', $privateDesc);
     $group->set('join_policy', $joinPolicy);
     $group->set('discoverability', $discoverability);
     $group->set('created', with(new Date('now'))->toSql());
     $group->set('created_by', User::get('id'));
     $group->add('managers', array(User::get('id')));
     $group->add('members', array(User::get('id')));
     if (!$group->create() || !$group->update()) {
         throw new Exception(Lang::txt('Failed to create group.'), 500);
     }
     $this->send($group);
 }
示例#20
0
 /**
  * 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();
 }
示例#21
0
 /**
  * Short description for 'check'
  *
  * Long description (if any) ...
  *
  * @param      string $task Parameter description (if any) ...
  * @param      integer $id Parameter description (if any) ...
  * @return     boolean Return description (if any) ...
  */
 public function check($task = 'create', $id = 0, $field_to_check = array())
 {
     $sitename = Config::get('sitename');
     if ($id == 0) {
         $id = User::get('id');
     }
     $registration = $this->_registration;
     if ($task == 'proxy') {
         $task = 'proxycreate';
     }
     $this->_missing = array();
     $_invalid = array();
     $registrationUsername = $this->registrationField('registrationUsername', 'RROO', $task);
     $registrationPassword = $this->registrationField('registrationPassword', 'RRHH', $task);
     $registrationConfirmPassword = $this->registrationField('registrationConfirmPassword', 'RRHH', $task);
     $registrationFullname = $this->registrationField('registrationFullname', 'RRRR', $task);
     $registrationEmail = $this->registrationField('registrationEmail', 'RRRR', $task);
     $registrationConfirmEmail = $this->registrationField('registrationConfirmEmail', 'RRRR', $task);
     $registrationURL = $this->registrationField('registrationURL', 'HHHH', $task);
     $registrationPhone = $this->registrationField('registrationPhone', 'HHHH', $task);
     $registrationEmployment = $this->registrationField('registrationEmployment', 'HHHH', $task);
     $registrationOrganization = $this->registrationField('registrationOrganization', 'HHHH', $task);
     $registrationCitizenship = $this->registrationField('registrationCitizenship', 'HHHH', $task);
     $registrationResidency = $this->registrationField('registrationResidency', 'HHHH', $task);
     $registrationSex = $this->registrationField('registrationSex', 'HHHH', $task);
     $registrationDisability = $this->registrationField('registrationDisability', 'HHHH', $task);
     $registrationHispanic = $this->registrationField('registrationHispanic', 'HHHH', $task);
     $registrationRace = $this->registrationField('registrationRace', 'HHHH', $task);
     $registrationInterests = $this->registrationField('registrationInterests', 'HHHH', $task);
     $registrationReason = $this->registrationField('registrationReason', 'HHHH', $task);
     $registrationOptIn = $this->registrationField('registrationOptIn', 'HHHH', $task);
     $registrationCAPTCHA = $this->registrationField('registrationCAPTCHA', 'HHHH', $task);
     $registrationTOU = $this->registrationField('registrationTOU', 'HHHH', $task);
     $registrationAddress = $this->registrationField('registrationAddress', 'OOOO', $task);
     $registrationORCID = $this->registrationField('registrationORCID', 'HHHO', $task);
     if ($task == 'update') {
         if (empty($registration['login'])) {
             $registrationUsername = REG_REQUIRED;
         } else {
             $registrationUsername = REG_READONLY;
         }
         $registrationPassword = REG_HIDE;
         $registrationConfirmPassword = REG_HIDE;
         if (empty($registration['email'])) {
             $registrationEmail = REG_REQUIRED;
         }
     }
     if ($task == 'edit') {
         $registrationUsername = REG_READONLY;
         $registrationPassword = REG_HIDE;
         $registrationConfirmPassword = REG_HIDE;
     }
     if (User::get('auth_link_id') && $task == 'create') {
         $registrationPassword = REG_HIDE;
         $registrationConfirmPassword = REG_HIDE;
     }
     $login = $registration['login'];
     $email = $registration['email'];
     $confirmEmail = $registration['confirmEmail'];
     if ($registrationUsername == REG_REQUIRED) {
         if (empty($login)) {
             $this->_missing['login'] = '******';
             $this->_invalid['login'] = '******';
         }
     }
     if ($registrationUsername != REG_HIDE) {
         $allowNumericFirstCharacter = $task == 'update' ? true : false;
         if (!empty($login) && !Helpers\Utility::validlogin($login, $allowNumericFirstCharacter)) {
             $this->_invalid['login'] = '******';
         }
     }
     if (!empty($login) && ($task == 'create' || $task == 'proxycreate' || $task == 'update')) {
         jimport('joomla.user.helper');
         $uid = \JUserHelper::getUserId($login);
         if ($uid && $uid != $id) {
             $this->_invalid['login'] = '******' . htmlentities($login) . '" already exists. Please try another.';
         }
         if (\Hubzero\Utility\Validate::reserved('username', $login)) {
             $this->_invalid['login'] = '******' . htmlentities($login) . '" already exists. Please try another.';
         }
         // system username check
         $puser = posix_getpwnam($login);
         if (!empty($puser) && $uid && $uid != $puser['uid']) {
             // log error and display error to user
             \Log::error('System username/userid does not match DB username/password for user: '******'login'] = '******';
         }
     }
     if ($registrationPassword == REG_REQUIRED) {
         if (empty($registration['password'])) {
             $this->_missing['password'] = '******';
             $this->_invalid['password'] = '******';
         }
     }
     /*
     if ($registrationPassword != REG_HIDE)
     {
     	if (!empty($registration['password']))
     	{
     		$result = Helpers\Utility::valid_password($registration['password']);
     
     		if ($result)
     			$this->_invalid['password'] = $result;
     	}
     }
     */
     if ($registrationConfirmPassword == REG_REQUIRED) {
         if (empty($registration['confirmPassword'])) {
             $this->_missing['confirmPassword'] = '******';
             $this->_invalid['confirmPassword'] = '******';
         }
     }
     if ($registrationPassword != REG_HIDE && $registrationConfirmPassword != REG_HIDE) {
         if ($registration['password'] != $registration['confirmPassword']) {
             $this->_invalid['confirmPassword'] = '******';
         }
     }
     if ($registrationPassword == REG_REQUIRED) {
         $score = $this->scorePassword($registration['password'], $registration['login']);
         if ($score < PASS_SCORE_MEDIOCRE) {
             $this->_invalid['password'] = '******';
         } else {
             if ($score >= PASS_SCORE_MEDIOCRE && $score < PASS_SCORE_GOOD) {
                 // Mediocre pass
             } else {
                 if ($score >= PASS_SCORE_GOOD && $score < PASS_SCORE_STRONG) {
                     // Good pass
                 } else {
                     if ($score >= PASS_SCORE_STRONG) {
                         // Strong pass
                     }
                 }
             }
         }
         $rules = \Hubzero\Password\Rule::getRules();
         $msg = \Hubzero\Password\Rule::validate($registration['password'], $rules, $login, $registration['name']);
         if (!empty($msg)) {
             $this->_invalid['password'] = $msg;
         }
     }
     if ($registrationFullname == REG_REQUIRED) {
         if (empty($registration['name'])) {
             $this->_missing['name'] = 'Full Name';
             $this->_invalid['name'] = 'Please provide a name.';
         } else {
             $bits = explode(' ', $registration['name']);
             $surname = null;
             $middleName = null;
             $givenName = null;
             if (count($bits) == 1) {
                 $givenName = array_shift($bits);
             } else {
                 $surname = array_pop($bits);
                 if (count($bits) >= 1) {
                     $givenName = array_shift($bits);
                 }
                 if (count($bits) >= 1) {
                     $middleName = implode(' ', $bits);
                 }
             }
             if (!$givenName) {
                 $this->_missing['name'] = 'Full Name';
                 $this->_invalid['name'] = 'Please provide a name.';
             }
         }
     }
     if ($registrationFullname != REG_HIDE) {
         if (!empty($registration['name']) && !Helpers\Utility::validname($registration['name'])) {
             $this->_invalid['name'] = 'Invalid name. You may be using characters that are not allowed.';
         }
     }
     if ($registrationEmail == REG_REQUIRED) {
         if (empty($email)) {
             $this->_missing['email'] = 'Valid Email';
             $this->_invalid['email'] = 'Please provide a valid e-mail address.';
         }
     }
     if ($registrationEmail != REG_HIDE) {
         if (empty($email)) {
             $this->_missing['email'] = 'Valid Email';
         } elseif (!Helpers\Utility::validemail($email)) {
             $this->_invalid['email'] = 'Invalid email address. Please correct and try again.';
         } else {
             $usersConfig = \Component::params('com_users');
             $allow_duplicate_emails = $usersConfig->get('allow_duplicate_emails');
             // Check if the email is already in use
             $db = \App::get('db');
             $query = "SELECT `id` FROM `#__users` WHERE `email` = " . $db->quote($email) . " AND `id` != " . (int) $id;
             $db->setQuery($query);
             $xid = intval($db->loadResult());
             // 0 = not allowed
             // 1 = allowed (i.e. no check needed)
             // 2 = only existing accounts (grandfathered)
             if ($xid && ($allow_duplicate_emails == 0 || $allow_duplicate_emails == 2)) {
                 if ($allow_duplicate_emails == 0) {
                     $this->_invalid['email'] = 'An existing account is already using this e-mail address.';
                 } else {
                     if ($allow_duplicate_emails == 2) {
                         // If duplicates are only allowed in grandfathered accounts,
                         // then new accounts shouldn't be created with the same email.
                         if ($task == 'create' || $task == 'proxycreate') {
                             $this->_invalid['email'] = 'An existing account is already using this e-mail address.';
                         } else {
                             // We also need to catch existing users who might try to change their
                             // email to an existing email address on the hub. For that, we need to
                             // check and see if their email address is changing with this save.
                             $db = \App::get('db');
                             $query = "SELECT `email` FROM `#__users` WHERE `id` = " . (int) $id;
                             $db->setQuery($query);
                             $currentEmail = $db->loadResult();
                             if ($currentEmail != $email) {
                                 $this->_invalid['email'] = 'An existing account is already using this e-mail address.';
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($registrationConfirmEmail == REG_REQUIRED) {
         if (empty($confirmEmail) && empty($this->_invalid['email'])) {
             $this->_missing['confirmEmail'] = 'Valid Email Confirmation';
             $this->_invalid['confirmEmail'] = 'Please provide a valid e-mail address again.';
         }
     }
     if ($registrationConfirmEmail != REG_HIDE) {
         if ($email != $confirmEmail) {
             if (empty($this->_invalid['email'])) {
                 $this->_invalid['confirmEmail'] = 'Email addresses do not match. Please correct and try again.';
                 $this->_invalid['email'] = 'Email addresses do not match. Please correct and try again.';
             }
         }
     }
     if ($registrationURL == REG_REQUIRED) {
         if (empty($registration['web'])) {
             $this->_missing['web'] = 'Personal Web Page';
             $this->_invalid['web'] = 'Please provide a valid website URL';
         }
     }
     if ($registrationURL != REG_HIDE) {
         $registration['web'] = trim($registration['web']);
         if (!empty($registration['web']) && (strstr($registration['web'], ' ') || !Helpers\Utility::validurl($registration['web']))) {
             $this->_invalid['web'] = 'Invalid web site URL. You may be using characters that are not allowed.';
         }
     }
     if ($registrationORCID == REG_REQUIRED) {
         if (empty($registration['orcid'])) {
             $this->_missing['orcid'] = 'ORCID';
             $this->_invalid['orcid'] = 'Please provide a valid ORCID';
         }
     }
     if ($registrationORCID != REG_HIDE) {
         if (!empty($registration['orcid']) && !Helpers\Utility::validorcid($registration['orcid'])) {
             $this->_invalid['orcid'] = 'Invalid ORCID. It should be in the form of XXXX-XXXX-XXXX-XXXX.';
         }
     }
     if ($registrationPhone == REG_REQUIRED) {
         if (empty($registration['phone'])) {
             $this->_missing['phone'] = 'Phone Number';
             $this->_invalid['phone'] = 'Please provide a valid phone number';
         }
     }
     if ($registrationPhone != REG_HIDE) {
         if (!empty($registration['phone']) && !Helpers\Utility::validphone($registration['phone'])) {
             $this->_invalid['phone'] = 'Invalid phone number. You may be using characters that are not allowed.';
         }
     }
     if ($registrationEmployment == REG_REQUIRED) {
         if (empty($registration['orgtype'])) {
             $this->_missing['orgtype'] = 'Employment Type';
             $this->_invalid['orgtype'] = 'Please make an employment type selection';
         }
     }
     /*
     if ($registrationEmployment != REG_HIDE)
     	if (empty($registration['orgtype']))
     	{
     		//if (!Helpers\Utility::validateOrgType($registration['orgtype']) )
     			$this->_invalid['orgtype'] = 'Invalid employment status. Please make a new selection.';
     	}
     */
     if ($registrationOrganization == REG_REQUIRED) {
         if (empty($registration['org']) && empty($registration['orgtext'])) {
             $this->_missing['org'] = 'Organization';
             $this->_invalid['org'] = 'Invalid affiliation';
         }
     }
     if ($registrationOrganization != REG_HIDE) {
         if (!empty($registration['org']) && !Helpers\Utility::validtext($registration['org'])) {
             $this->_invalid['org'] = 'Invalid affiliation. You may be using characters that are not allowed.';
         } elseif (!empty($registration['orgtext']) && !Helpers\Utility::validtext($registration['orgtext'])) {
             $this->_invalid['org'] = 'Invalid affiliation. You may be using characters that are not allowed.';
         }
     }
     if ($registrationCitizenship == REG_REQUIRED) {
         if (empty($registration['countryorigin'])) {
             $this->_missing['countryorigin'] = 'Country of Citizenship / Permanent Residence';
             $this->_invalid['countryorigin'] = 'Invalid country of origin.';
         }
     }
     if ($registrationCitizenship != REG_HIDE) {
         if (!empty($registration['countryorigin']) && !Helpers\Utility::validtext($registration['countryorigin'])) {
             $this->_invalid['countryorigin'] = 'Invalid country of origin. You may be using characters that are not allowed.';
         }
     }
     if ($registrationResidency == REG_REQUIRED) {
         if (empty($registration['countryresident'])) {
             $this->_missing['countryresident'] = 'Country of Current Residence';
             $this->_invalid['countryresident'] = 'Invalid country of residency';
         }
     }
     if ($registrationResidency != REG_HIDE) {
         if (!empty($registration['countryresident']) && !Helpers\Utility::validtext($registration['countryresident'])) {
             $this->_invalid['countryresident'] = 'Invalid country of residency. You may be using characters that are not allowed.';
         }
     }
     if ($registrationSex == REG_REQUIRED) {
         if (empty($registration['sex'])) {
             $this->_missing['sex'] = 'Gender';
             $this->_invalid['sex'] = 'Please select gender.';
         }
     }
     if ($registrationSex != REG_HIDE) {
         if (!empty($registration['sex']) && !Helpers\Utility::validtext($registration['sex'])) {
             $this->_invalid['sex'] = 'Invalid gender selection.';
         }
     }
     if ($registrationDisability == REG_REQUIRED) {
         if (empty($registration['disability'])) {
             $this->_missing['disability'] = 'Disability Information';
             $this->_invalid['disability'] = 'Please indicate any disabilities you may have.';
         }
     }
     if ($registrationDisability != REG_HIDE) {
         if (!empty($registration['disability']) && in_array('yes', $registration['disability'])) {
             $this->_invalid['disability'] = 'Invalid disability selection.';
         }
     }
     if ($registrationHispanic == REG_REQUIRED) {
         if (empty($registration['hispanic'])) {
             $this->_missing['hispanic'] = 'Hispanic Ethnic Heritage';
             $this->_invalid['hispanic'] = 'Please make a selection or choose not to reveal.';
         }
     }
     /*
     if ($registrationHispanic != REG_HIDE)
     {
     	if (empty($registration['hispanic']))
     	{
     		$this->_invalid['hispanic'] = 'Invalid hispanic heritage selection.';
     	}
     }
     */
     if ($registrationRace == REG_REQUIRED) {
         if ($task == 'edit') {
             $corigin_incoming = in_array('countryorigin', $field_to_check) ? true : false;
             $profile = \Hubzero\User\Profile::getInstance(User::get('id'));
         } else {
             $corigin_incoming = true;
         }
         if (empty($registration['race']) && ($corigin_incoming && strtolower($registration['countryorigin']) == 'us' || !$corigin_incoming && isset($profile) && strtolower($profile->get('countryorigin')) == 'us')) {
             $this->_missing['race'] = 'Racial Background';
             $this->_invalid['race'] = 'Please make a selection or choose not to reveal.';
         }
     }
     /*
     if ($registrationRace != REG_HIDE)
     {
     	if (!empty($registration['race']) || !Helpers\Utility::validtext($registration['race']))
     	{
     		$this->_invalid['race'] = 'Invalid racial selection.';
     	}
     }
     */
     if ($registrationInterests == REG_REQUIRED) {
         if (empty($registration['interests']) || $registration['interests'] == '') {
             $this->_missing['interests'] = 'Interests';
             $this->_invalid['interests'] = 'Please select materials your are interested in';
         }
     }
     /*
     if ($registrationInterests != REG_HIDE)
     {
     	if (!empty($registration['edulevel']) && !Helpers\Utility::validtext($registration['edulevel']))
     		$this->_invalid['interests'] = 'Invalid interest selection.';
     	if (!empty($registration['role']) && !Helpers\Utility::validtext($registration['role']))
     		$this->_invalid['interests'] = 'Invalid interest selection.';
     }
     */
     if ($registrationReason == REG_REQUIRED) {
         if (empty($registration['reason']) && empty($registration['reasontxt'])) {
             $this->_missing['reason'] = 'Reason for registering';
             $this->_invalid['reason'] = 'Reason for registering';
         }
     }
     if ($registrationReason != REG_HIDE) {
         if (!empty($registration['reason']) && !Helpers\Utility::validtext($registration['reason'])) {
             $this->_invalid['reason'] = 'Invalid reason text. You may be using characters that are not allowed.';
         }
         if (!empty($registration['reasontxt']) && !Helpers\Utility::validtext($registration['reasontxt'])) {
             $this->_invalid['reason'] = 'Invalid reason text. You may be using characters that are not allowed.';
         }
     }
     if ($registrationOptIn == REG_REQUIRED) {
         if (is_null($registration['mailPreferenceOption']) || intval($registration['mailPreferenceOption']) < 0) {
             $this->_missing['mailPreferenceOption'] = 'Receive Email Updates';
             $this->_invalid['mailPreferenceOption'] = 'Receive Email Updates has not been selected';
         }
     }
     if ($registrationCAPTCHA == REG_REQUIRED) {
         $botcheck = Request::getVar('botcheck', '');
         if ($botcheck) {
             $this->_invalid['captcha'] = 'Error: Invalid CAPTCHA response.';
         }
         $validcaptchas = Event::trigger('hubzero.onValidateCaptcha');
         if (count($validcaptchas) > 0) {
             foreach ($validcaptchas as $validcaptcha) {
                 if (!$validcaptcha) {
                     $this->_invalid['captcha'] = 'Error: Invalid CAPTCHA response.';
                 }
             }
         }
     }
     if ($registrationTOU == REG_REQUIRED) {
         if (empty($registration['usageAgreement'])) {
             $this->_missing['usageAgreement'] = 'Usage Agreement';
             $this->_invalid['usageAgreement'] = 'Registration requires acceptance of the usage agreement';
         }
     }
     /*
     if ($registrationTOU != REG_HIDE)
     	if (!empty($registration['usageAgreement']))
     		$this->_invalid['usageAgreement'] = 'Usage Agreement has not been Read and Accepted';
     */
     if ($registrationAddress == REG_REQUIRED) {
         if (count($registration['address']) == 0) {
             $this->_missing['address'] = 'Member Address';
             $this->_invalid['address'] = 'Member Address';
         }
     }
     if (!empty($field_to_check)) {
         if ($this->_missing) {
             foreach ($this->_missing as $k => $v) {
                 if (!in_array($k, $field_to_check)) {
                     unset($this->_missing[$k]);
                 }
             }
         }
         if ($this->_invalid) {
             foreach ($this->_invalid as $k => $v) {
                 if (!in_array($k, $field_to_check)) {
                     unset($this->_invalid[$k]);
                 }
             }
         }
     }
     if (empty($this->_missing) && empty($this->_invalid)) {
         return true;
     }
     return false;
 }
示例#22
0
 /**
  * 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();
 }
示例#23
0
 /**
  * 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'));
         }
     }
 }
示例#24
0
 /**
  * Add CC info to the log
  *
  * @param   string  $val  Value to log
  * @return  object
  */
 public function cced($val)
 {
     $val = trim($val);
     if (!$val) {
         return $this;
     }
     $val = preg_split("/[,;]/", $val);
     $val = array_map('trim', $val);
     foreach ($val as $acc) {
         // Is this a username or email address?
         if (!strstr($acc, '@')) {
             // Username or user ID - load the user
             $acc = is_string($acc) ? strtolower($acc) : $acc;
             $user = User::getInstance($acc);
             // Did we find an account?
             if (is_object($user)) {
                 $this->_log['cc'][] = $user->get('username');
             } else {
                 // Move on - nothing else we can do here
                 continue;
             }
         } else {
             if (Validate::email($acc)) {
                 $this->_log['cc'][] = $acc;
             }
         }
     }
     return $this;
 }
示例#25
0
 /**
  * Save an entry
  *
  * @return    string
  */
 private function save()
 {
     Request::checkToken();
     //get request vars
     $event = Request::getVar('event', array(), 'post');
     $event['time_zone'] = Request::getVar('time_zone', -5);
     $event['params'] = Request::getVar('params', array());
     $event['content'] = Request::getVar('content', '', 'post', 'STRING', JREQUEST_ALLOWRAW);
     $registration = Request::getVar('include-registration', 0);
     //set vars for saving
     $event['catid'] = '-1';
     $event['state'] = 1;
     $event['scope'] = 'group';
     $event['scope_id'] = $this->group->get('gidNumber');
     $event['modified'] = Date::toSql();
     $event['modified_by'] = $this->user->get('id');
     // repeating rule
     $event['repeating_rule'] = $this->_buildRepeatingRule();
     //if we are updating set modified time and actor
     if (!isset($event['id']) || $event['id'] == 0) {
         $event['created'] = Date::toSql();
         $event['created_by'] = $this->user->get('id');
     }
     // timezone
     $timezone = new DateTimezone(Config::get('offset'));
     //parse publish up date/time
     if (isset($event['publish_up']) && $event['publish_up'] != '') {
         // combine date & time
         if (isset($event['publish_up_time'])) {
             $event['publish_up'] = $event['publish_up'] . ' ' . $event['publish_up_time'];
         }
         $event['publish_up'] = Date::of($event['publish_up'], $timezone)->format("Y-m-d H:i:s");
         unset($event['publish_up_time']);
     }
     //parse publish down date/time
     if (isset($event['publish_down']) && $event['publish_down'] != '') {
         // combine date & time
         if (isset($event['publish_down_time'])) {
             $event['publish_down'] = $event['publish_down'] . ' ' . $event['publish_down_time'];
         }
         $event['publish_down'] = Date::of($event['publish_down'], $timezone)->format("Y-m-d H:i:s");
         unset($event['publish_down_time']);
     }
     //parse register by date/time
     if (isset($event['registerby']) && $event['registerby'] != '') {
         //remove @ symbol
         $event['registerby'] = str_replace("@", "", $event['registerby']);
         $event['registerby'] = Date::of($event['registerby'], $timezone)->format("Y-m-d H:i:s");
     }
     //stringify params
     if (isset($event['params']) && count($event['params']) > 0) {
         $params = new \Hubzero\Config\Registry($event['params']);
         $event['params'] = $params->toString();
     }
     //did we want to turn off registration?
     if (!$registration) {
         $event['registerby'] = '0000-00-00 00:00:00';
     }
     //instantiate new event object
     $eventsModelEvent = new \Components\Events\Models\Event();
     // attempt to bind
     if (!$eventsModelEvent->bind($event)) {
         $this->setError($eventsModelEvent->getError());
         $this->event = $eventsModelEvent;
         return $this->edit();
     }
     if (isset($event['content']) && $event['content']) {
         $event['content'] = \Hubzero\Utility\Sanitize::clean($event['content']);
     }
     if (isset($event['extra_info']) && $event['extra_info'] && !\Hubzero\Utility\Validate::url($event['extra_info'])) {
         $this->setError('Website entered does not appear to be a valid URL.');
         $this->event = $eventsModelEvent;
         return $this->edit();
     }
     //make sure we have both start and end time
     if ($event['publish_up'] == '') {
         $this->setError('You must enter an event start, an end date is optional.');
         $this->event = $eventsModelEvent;
         return $this->edit();
     }
     //check to make sure end time is greater than start time
     if (isset($event['publish_down']) && $event['publish_down'] != '0000-00-00 00:00:00' && $event['publish_down'] != '') {
         $up = strtotime($event['publish_up']);
         $down = strtotime($event['publish_down']);
         $allday = isset($event['allday']) && $event['allday'] == 1 ? true : false;
         // make sure up greater than down when not all day
         // when all day event up can equal down
         if ($up >= $down && !$allday || $allday && $up > $down) {
             $this->setError('You must an event end date greater than the start date.');
             $this->event = $eventsModelEvent;
             return $this->edit();
         }
     }
     //make sure registration email is valid
     if ($registration && isset($event['email']) && $event['email'] != '' && !filter_var($event['email'], FILTER_VALIDATE_EMAIL)) {
         $this->setError('You must enter a valid email address for the events registration admin email.');
         $this->event = $eventsModelEvent;
         return $this->edit();
     }
     //make sure registration email is valid
     if ($registration && (!isset($event['registerby']) || $event['registerby'] == '')) {
         $this->setError('You must enter a valid event registration deadline to require registration.');
         Request::setVar('includeRegistration', 1);
         $this->event = $eventsModelEvent;
         return $this->edit();
     }
     //check to make sure we have valid info
     if (!$eventsModelEvent->store(true)) {
         $this->setError('An error occurred when trying to edit the event. Please try again.');
         $this->event = $eventsModelEvent;
         return $this->edit();
     }
     //get the year and month for this event
     //so we can jump to that spot
     $year = Date::of(strtotime($event['publish_up']))->format("Y");
     $month = Date::of(strtotime($event['publish_up']))->format("m");
     //build message
     $message = Lang::txt('You have successfully created a new group event.');
     if (isset($event['id']) && $event['id'] != 0) {
         $message = Lang::txt('You have successfully edited the group event.');
     }
     //inform user and redirect
     App::redirect(Route::url('index.php?option=' . $this->option . '&cn=' . $this->group->get('cn') . '&active=calendar&action=details&event_id=' . $eventsModelEvent->get('id')), $message, 'passed');
 }
示例#26
0
 /**
  * Check data
  *
  * @param   string   $task
  * @param   integer  $id
  * @return  boolean
  */
 public function check($task = 'create', $id = 0, $field_to_check = array())
 {
     $sitename = Config::get('sitename');
     if ($id == 0) {
         $id = User::get('id');
     }
     $registration = $this->_registration;
     if ($task == 'proxy') {
         $task = 'proxycreate';
     }
     $this->_missing = array();
     $this->_invalid = array();
     $registrationUsername = $this->registrationField('registrationUsername', 'RROO', $task);
     $registrationPassword = $this->registrationField('registrationPassword', 'RRHH', $task);
     $registrationConfirmPassword = $this->registrationField('registrationConfirmPassword', 'RRHH', $task);
     $registrationFullname = $this->registrationField('registrationFullname', 'RRRR', $task);
     $registrationEmail = $this->registrationField('registrationEmail', 'RRRR', $task);
     $registrationConfirmEmail = $this->registrationField('registrationConfirmEmail', 'RRRR', $task);
     $registrationOptIn = $this->registrationField('registrationOptIn', 'HHHH', $task);
     $registrationCAPTCHA = $this->registrationField('registrationCAPTCHA', 'HHHH', $task);
     $registrationTOU = $this->registrationField('registrationTOU', 'HHHH', $task);
     if ($task == 'update') {
         if (empty($registration['login'])) {
             $registrationUsername = REG_REQUIRED;
         } else {
             $registrationUsername = REG_READONLY;
         }
         $registrationPassword = REG_HIDE;
         $registrationConfirmPassword = REG_HIDE;
         if (empty($registration['email'])) {
             $registrationEmail = REG_REQUIRED;
         }
     }
     if ($task == 'edit') {
         $registrationUsername = REG_READONLY;
         $registrationPassword = REG_HIDE;
         $registrationConfirmPassword = REG_HIDE;
     }
     if (User::get('auth_link_id') && $task == 'create') {
         $registrationPassword = REG_HIDE;
         $registrationConfirmPassword = REG_HIDE;
     }
     $login = $registration['login'];
     $email = $registration['email'];
     $confirmEmail = $registration['confirmEmail'];
     if ($registrationUsername == REG_REQUIRED) {
         if (empty($login)) {
             $this->_missing['login'] = '******';
             $this->_invalid['login'] = '******';
         }
     }
     if ($registrationUsername != REG_HIDE) {
         $allowNumericFirstCharacter = $task == 'update' ? true : false;
         if (!empty($login) && !Helpers\Utility::validlogin($login, $allowNumericFirstCharacter)) {
             $this->_invalid['login'] = '******';
         }
     }
     if (!empty($login) && ($task == 'create' || $task == 'proxycreate' || $task == 'update')) {
         $uid = User::getInstance($login)->get('id');
         if ($uid && $uid != $id) {
             $this->_invalid['login'] = '******' . htmlentities($login) . '" already exists. Please try another.';
         }
         if (\Hubzero\Utility\Validate::reserved('username', $login)) {
             $this->_invalid['login'] = '******' . htmlentities($login) . '" already exists. Please try another.';
         }
         // system username check
         $puser = posix_getpwnam($login);
         if (!empty($puser) && $uid && $uid != $puser['uid']) {
             // log error and display error to user
             \Log::error('System username/userid does not match DB username/password for user: '******'login'] = '******';
         }
     }
     if ($registrationPassword == REG_REQUIRED) {
         if (empty($registration['password'])) {
             $this->_missing['password'] = '******';
             $this->_invalid['password'] = '******';
         }
     }
     /*
     if ($registrationPassword != REG_HIDE)
     {
     	if (!empty($registration['password']))
     	{
     		$result = Helpers\Utility::valid_password($registration['password']);
     
     		if ($result)
     			$this->_invalid['password'] = $result;
     	}
     }
     */
     if ($registrationConfirmPassword == REG_REQUIRED) {
         if (empty($registration['confirmPassword'])) {
             $this->_missing['confirmPassword'] = '******';
             $this->_invalid['confirmPassword'] = '******';
         }
     }
     if ($registrationPassword != REG_HIDE && $registrationConfirmPassword != REG_HIDE) {
         if ($registration['password'] != $registration['confirmPassword']) {
             $this->_invalid['confirmPassword'] = '******';
         }
     }
     if ($registrationPassword == REG_REQUIRED) {
         $score = $this->scorePassword($registration['password'], $registration['login']);
         if ($score < PASS_SCORE_MEDIOCRE) {
             $this->_invalid['password'] = '******';
         } else {
             if ($score >= PASS_SCORE_MEDIOCRE && $score < PASS_SCORE_GOOD) {
                 // Mediocre pass
             } else {
                 if ($score >= PASS_SCORE_GOOD && $score < PASS_SCORE_STRONG) {
                     // Good pass
                 } else {
                     if ($score >= PASS_SCORE_STRONG) {
                         // Strong pass
                     }
                 }
             }
         }
         $rules = \Hubzero\Password\Rule::all()->whereEquals('enabled', 1)->rows();
         $msg = \Hubzero\Password\Rule::verify($registration['password'], $rules, $login, $registration['name']);
         if (!empty($msg)) {
             $this->_invalid['password'] = $msg;
         }
     }
     if ($registrationFullname == REG_REQUIRED) {
         if (empty($registration['name'])) {
             $this->_missing['name'] = 'Full Name';
             $this->_invalid['name'] = 'Please provide a name.';
         } else {
             $bits = explode(' ', $registration['name']);
             $surname = null;
             $middleName = null;
             $givenName = null;
             if (count($bits) == 1) {
                 $givenName = array_shift($bits);
             } else {
                 $surname = array_pop($bits);
                 if (count($bits) >= 1) {
                     $givenName = array_shift($bits);
                 }
                 if (count($bits) >= 1) {
                     $middleName = implode(' ', $bits);
                 }
             }
             if (!$givenName || !$surname) {
                 $this->_missing['name'] = 'Full Name';
                 $this->_invalid['name'] = 'Please provide a name.';
             }
         }
     }
     if ($registrationFullname != REG_HIDE) {
         if (!empty($registration['name']) && !Helpers\Utility::validname($registration['name'])) {
             $this->_invalid['name'] = 'Invalid name. You may be using characters that are not allowed.';
         }
     }
     if ($registrationEmail == REG_REQUIRED) {
         if (empty($email)) {
             $this->_missing['email'] = 'Valid Email';
             $this->_invalid['email'] = 'Please provide a valid e-mail address.';
         }
     }
     if ($registrationEmail != REG_HIDE) {
         if (empty($email)) {
             $this->_missing['email'] = 'Valid Email';
         } elseif (!Helpers\Utility::validemail($email)) {
             $this->_invalid['email'] = 'Invalid email address. Please correct and try again.';
         } else {
             $usersConfig = \Component::params('com_users');
             $allow_duplicate_emails = $usersConfig->get('allow_duplicate_emails');
             // Check if the email is already in use
             $row = \Hubzero\User\User::all()->whereEquals('email', $email)->where('id', '!=', (int) $id)->row();
             $xid = intval($row->get('id'));
             // 0 = not allowed
             // 1 = allowed (i.e. no check needed)
             // 2 = only existing accounts (grandfathered)
             if ($xid && ($allow_duplicate_emails == 0 || $allow_duplicate_emails == 2)) {
                 if ($allow_duplicate_emails == 0) {
                     $this->_invalid['email'] = 'An existing account is already using this e-mail address.';
                 } else {
                     if ($allow_duplicate_emails == 2) {
                         // If duplicates are only allowed in grandfathered accounts,
                         // then new accounts shouldn't be created with the same email.
                         if ($task == 'create' || $task == 'proxycreate') {
                             $this->_invalid['email'] = 'An existing account is already using this e-mail address.';
                         } else {
                             // We also need to catch existing users who might try to change their
                             // email to an existing email address on the hub. For that, we need to
                             // check and see if their email address is changing with this save.
                             $row = \Hubzero\User\User::oneOrNew((int) $id);
                             $currentEmail = $row->get('email');
                             if ($currentEmail != $email) {
                                 $this->_invalid['email'] = 'An existing account is already using this e-mail address.';
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($registrationConfirmEmail == REG_REQUIRED) {
         if (empty($confirmEmail) && empty($this->_invalid['email'])) {
             $this->_missing['confirmEmail'] = 'Valid Email Confirmation';
             $this->_invalid['confirmEmail'] = 'Please provide a valid e-mail address again.';
         }
     }
     if ($registrationConfirmEmail != REG_HIDE) {
         if ($email != $confirmEmail) {
             if (empty($this->_invalid['email'])) {
                 $this->_invalid['confirmEmail'] = 'Email addresses do not match. Please correct and try again.';
                 $this->_invalid['email'] = 'Email addresses do not match. Please correct and try again.';
             }
         }
     }
     if ($registrationOptIn == REG_REQUIRED) {
         if (is_null($registration['sendEmail']) || intval($registration['sendEmail']) < 0) {
             $this->_missing['sendEmail'] = 'Receive Email Updates';
             $this->_invalid['sendEmail'] = 'Receive Email Updates has not been selected';
         }
     }
     if ($registrationCAPTCHA == REG_REQUIRED) {
         $botcheck = Request::getVar('botcheck', '');
         if ($botcheck) {
             $this->_invalid['captcha'] = 'Error: Invalid CAPTCHA response.';
         }
         $validcaptchas = Event::trigger('captcha.onCheckAnswer');
         if (count($validcaptchas) > 0) {
             foreach ($validcaptchas as $validcaptcha) {
                 if (!$validcaptcha) {
                     $this->_invalid['captcha'] = 'Error: Invalid CAPTCHA response.';
                 }
             }
         }
     }
     if ($registrationTOU == REG_REQUIRED) {
         if (empty($registration['usageAgreement'])) {
             $this->_missing['usageAgreement'] = 'Usage Agreement';
             $this->_invalid['usageAgreement'] = 'Registration requires acceptance of the usage agreement';
         }
     }
     /* Everything below is currently done elsewhere
     		   @TODO  Move code to here or refactor?
     
     		if ($registrationAddress == REG_REQUIRED)
     		{
     			if (count($registration['address']) == 0)
     			{
     				$this->_missing['address'] = 'Member Address';
     				$this->_invalid['address'] = 'Member Address';
     			}
     		}
     
     		// Load all fields not hidden
     		$fields = Field::all()
     			->including(['options', function ($option){
     				$option
     					->select('*')
     					->ordered();
     			}])
     			->where('action_' . $task, '!=', Field::STATE_HIDDEN)
     			->ordered()
     			->rows();
     
     		if (!isset($registration['_profile']))
     		{
     			$registration['_profile'] = array();
     		}
     
     		// Find missing required fields
     		foreach ($fields as $field)
     		{
     			if ($field->get('type') != 'hidden')
     			{
     				if (!isset($registration['_profile'][$field->get('name')]))
     				{
     					continue;
     				}
     
     				$value = $registration['_profile'][$field->get('name')];
     
     				if (empty($value) && $field->get('action_' . $task) == Field::STATE_REQUIRED)
     				{
     					$this->_missing[$field->get('name')] = $field->get('label');
     				}
     			}
     		}
     
     		// Validate input
     		$form = new \Hubzero\Form\Form('profile', array('control' => 'profile'));
     		$form->load(Field::toXml($fields, $action));
     		$form->bind(new \Hubzero\Config\Registry($registration['_profile']));
     
     		if (!$form->validate($registration['_profile']))
     		{
     			foreach ($form->getErrors() as $error)
     			{
     				$this->_invalid[] = $error;
     			}
     		}*/
     // Filter out fields
     if (!empty($field_to_check)) {
         if ($this->_missing) {
             foreach ($this->_missing as $k => $v) {
                 if (!in_array($k, $field_to_check)) {
                     unset($this->_missing[$k]);
                 }
             }
         }
         if ($this->_invalid) {
             foreach ($this->_invalid as $k => $v) {
                 if (!in_array($k, $field_to_check)) {
                     unset($this->_invalid[$k]);
                 }
             }
         }
     }
     if (empty($this->_missing) && empty($this->_invalid)) {
         return true;
     }
     return false;
 }
示例#27
0
 /**
  * Registers a new authy user
  *
  * @return void
  **/
 private function register()
 {
     $authy = new AuthyApi($this->params->get('key'));
     // Gather and validate inputs
     $email = Request::getVar('email', null);
     $phone = Request::getVar('phone', null);
     $cc = Request::getInt('country_code', 1);
     if (!Validate::email($email) || !Validate::phone($phone)) {
         Notify::error("Invalid email or phone provided. Please try again");
         App::redirect(Request::current());
     }
     // Register the user
     $user = $authy->registerUser($email, $phone, $cc);
     // If everything checks out, we store the user id in the database
     if ($user->ok()) {
         // Store factor domain id in the database
         Factor::oneOrNew(0)->set(['user_id' => User::get('id'), 'domain' => 'authy', 'factor_id' => $user->id(), 'data' => json_encode(['email' => $email, 'phone' => $phone, 'country_code' => $cc])])->save();
     } else {
         // Return errors
         foreach ($user->errors() as $field => $message) {
             Notify::error("{$field}: {$message}");
         }
     }
     // Redirect for verification process to occur
     App::redirect(Request::current());
 }
示例#28
0
 /**
  * Upload a file to the wiki via AJAX
  *
  * @return     string
  */
 public function ajaxCreateTask()
 {
     // Check if they're logged in
     if (User::isGuest()) {
         echo json_encode(array('error' => Lang::txt('Must be logged in.')));
         return;
     }
     // Ensure we have an ID to work with
     $pid = strtolower(Request::getInt('pid', 0));
     if (!$pid) {
         echo json_encode(array('error' => Lang::txt('COM_RESOURCES_NO_ID')));
         return;
     }
     // Create database entry
     $asset = new Resource($this->database);
     $asset->title = 'A link';
     $asset->introtext = $asset->title;
     $asset->created = Date::toSql();
     $asset->created_by = User::get('id');
     $asset->published = 1;
     $asset->publish_up = Date::toSql();
     $asset->publish_down = '0000-00-00 00:00:00';
     $asset->standalone = 0;
     $asset->access = 0;
     $asset->path = Request::getVar('url', 'http://');
     $asset->type = 11;
     $asset->path = str_replace(array('|', '\\', '{', '}', '^'), array('%7C', '%5C', '%7B', '%7D', '%5E'), $asset->path);
     if (!Validate::url($asset->path)) {
         echo json_encode(array('success' => false, 'errors' => array(Lang::txt('Link provided is not a valid URL.')), 'file' => $asset->path, 'directory' => '', 'parent' => $pid, 'id' => 0));
         return;
     }
     if (!$asset->check()) {
         echo json_encode(array('success' => false, 'errors' => $asset->getErrors(), 'file' => $asset->path, 'directory' => '', 'parent' => $pid, 'id' => 0));
         return;
     }
     if (!$asset->store()) {
         echo json_encode(array('success' => false, 'errors' => $asset->getErrors(), 'file' => 'http://', 'directory' => '', 'parent' => $pid, 'id' => 0));
         return;
     }
     // Instantiate a Resources Assoc object
     $assoc = new Assoc($this->database);
     // Get the last child in the ordering
     $assoc->ordering = $assoc->getLastOrder($pid);
     $assoc->ordering = $assoc->ordering ? $assoc->ordering : 0;
     // Increase the ordering - new items are always last
     $assoc->ordering++;
     // Create new parent/child association
     $assoc->parent_id = $pid;
     $assoc->child_id = $asset->id;
     $assoc->grouping = 0;
     if (!$assoc->check()) {
         echo json_encode(array('success' => false, 'errors' => $assoc->getErrors(), 'file' => $asset->path, 'directory' => '', 'parent' => $pid, 'id' => $asset->id));
         return;
     }
     if (!$assoc->store(true)) {
         echo json_encode(array('success' => false, 'errors' => $assoc->getErrors(), 'file' => $asset->path, 'directory' => '', 'parent' => $pid, 'id' => $asset->id));
         return;
     }
     //echo result
     echo json_encode(array('success' => true, 'errors' => array(), 'file' => $asset->path, 'directory' => '', 'parent' => $pid, 'id' => $asset->id));
 }
示例#29
0
 /**
  * Check if a group alias is valid
  *
  * @param 		integer 	$cname 			Group alias
  * @param 		boolean		$allowDashes 	Allow dashes in cn
  * @return 		boolean		True if valid, false if not
  */
 private function _validCn($cn, $allowDashes = false)
 {
     $regex = '/^[0-9a-zA-Z]+[_0-9a-zA-Z]*$/i';
     if ($allowDashes) {
         $regex = '/^[0-9a-zA-Z]+[-_0-9a-zA-Z]*$/i';
     }
     if (\Hubzero\Utility\Validate::reserved('group', $cn)) {
         return false;
     }
     if (preg_match($regex, $cn)) {
         if (is_numeric($cn) && intval($cn) == $cn && $cn >= 0) {
             return false;
         } else {
             return true;
         }
     }
     return false;
 }
示例#30
0
 /**
  * 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);
 }