/** * Clean some text * * @param string $text Text to clean * @return string * @throws \InvalidArgumentException If no text passed */ public function __invoke($text = null) { if (null === $text) { throw new \InvalidArgumentException(__METHOD__ . '(); No text passed.'); } return Sanitize::clean($text); }
/** * Finder before save content method * Article is passed by reference, but after the save, so no changes will be saved. * Method is called right after the content is saved * * @param string The context of the content passed to the plugin */ public function onContentBeforeSave($context, &$article, $isNew) { if (!$article instanceof \Hubzero\Base\Object || $context == 'com_content.article') { return; } $key = $this->_key($context); $content = ltrim($article->get($key)); if (!$content) { return; } // Is there a format already applied? if (preg_match('/^<!-- \\{FORMAT:(.*)\\} -->/i', $content, $matches)) { $format = strtolower(trim($matches[1])); if ($format != 'html') { return; } } elseif (strstr($content, '</')) { // Force apply a format? if (!$this->params->get('applyFormat')) { return; } } if ($this->params->get('sanitizeBefore', 1)) { $content = \Hubzero\Utility\Sanitize::clean($content); $content = \Hubzero\Utility\Sanitize::html($content); } if ($this->params->get('applyFormat')) { $content = preg_replace('/^(<!-- \\{FORMAT:HTML\\} -->)/i', '', $content); $content = '<!-- {FORMAT:HTML} -->' . $content; } $article->set($key, $content); }
/** * Validate data * * @return boolean True if data is valid */ public function check() { $this->title = trim($this->title); if ($this->title == '') { $this->setError(Lang::txt('Missing title for the wish list')); return false; } $this->description = rtrim(stripslashes($this->description)); $this->description = Sanitize::clean($this->description); $this->description = nl2br($this->description); return true; }
/** * 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(); }
/** * Save an event * * @return void */ public function saveTask() { // Check if they are logged in if (User::isGuest()) { $this->loginTask(); return; } // good ol' form validation Request::checkToken(); Request::checkHoneypot() or die('Invalid Field Data Detected. Please try again.'); $offset = $this->offset; // Incoming $start_time = Request::getVar('start_time', '08:00', 'post'); $start_time = $start_time ? $start_time : '08:00'; $start_pm = Request::getInt('start_pm', 0, 'post'); $end_time = Request::getVar('end_time', '17:00', 'post'); $end_time = $end_time ? $end_time : '17:00'; $end_pm = Request::getInt('end_pm', 0, 'post'); $time_zone = Request::getVar('time_zone', -5, 'post'); $tags = Request::getVar('tags', '', 'post'); // Bind the posted data to an event object $row = new Event($this->database); if (!$row->bind($_POST)) { throw new Exception($row->getError(), 500); } // New entry or existing? if ($row->id) { $state = 'edit'; // Existing - update modified info $row->modified = strftime("%Y-%m-%d %H:%M:%S", time() + $offset * 60 * 60); if (User::get('id')) { $row->modified_by = User::get('id'); } } else { $state = 'add'; // New - set created info $row->created = strftime("%Y-%m-%d %H:%M:%S", time() + $offset * 60 * 60); if (User::get('id')) { $row->created_by = User::get('id'); } } // Set some fields and do some cleanup work if ($row->catid) { $row->catid = intval($row->catid); } //$row->title = htmlentities($row->title); $row->content = $_POST['econtent']; $row->content = \Hubzero\Utility\Sanitize::clean($row->content); // Get the custom fields defined in the events configuration if (isset($_POST['fields'])) { $fields = $_POST['fields']; $fields = array_map('trim', $fields); // Wrap up the content of the field and attach it to the event content $fs = $this->config->fields; foreach ($fields as $param => $value) { if (trim($value) != '') { $row->content .= '<ef:' . $param . '>' . $this->_clean($value) . '</ef:' . $param . '>'; } else { foreach ($fs as $f) { if ($f[0] == $param && end($f) == 1) { throw new Exception(Lang::txt('EVENTS_REQUIRED_FIELD_CHECK', $f[1]), 500); } } } } } // Clean adresse $row->adresse_info = $this->_clean($row->adresse_info); // Clean contact $row->contact_info = $this->_clean($row->contact_info); // Clean extra $row->extra_info = $this->_clean($row->extra_info); // Prepend http:// to URLs without it if ($row->extra_info != NULL) { if (substr($row->extra_info, 0, 7) != 'http://' && substr($row->extra_info, 0, 8) != 'https://') { $row->extra_info = 'http://' . $row->extra_info; } } // Reformat the time into 24hr format if necessary if ($this->config->getCfg('calUseStdTime') == 'YES') { list($hrs, $mins) = explode(':', $start_time); $hrs = intval($hrs); $mins = intval($mins); if ($hrs != 12 && $start_pm) { $hrs += 12; } else { if ($hrs == 12 && !$start_pm) { $hrs = 0; } } if ($hrs < 10) { $hrs = '0' . $hrs; } if ($mins < 10) { $mins = '0' . $mins; } $start_time = $hrs . ':' . $mins; list($hrs, $mins) = explode(':', $end_time); $hrs = intval($hrs); $mins = intval($mins); if ($hrs != 12 && $end_pm) { $hrs += 12; } else { if ($hrs == 12 && !$end_pm) { $hrs = 0; } } if ($hrs < 10) { $hrs = '0' . $hrs; } if ($mins < 10) { $mins = '0' . $mins; } $end_time = $hrs . ':' . $mins; } // hack to fix where timezones cant be found by offset int // really need to figure datetimes out switch ($row->time_zone) { case -12: $tz = 'Pacific/Kwajalein'; break; case -9.5: $tz = 'Pacific/Marquesa'; break; case -3.5: $tz = 'Canada/Newfoundland'; break; case -2: $tz = 'America/Noronha'; break; case 3.5: $tz = 'Asia/Tehran'; break; case 4.5: $tz = 'Asia/Kabul'; break; case 6: $tz = 'Asia/Dhaka'; break; case 6.5: $tz = 'Asia/Rangoon'; break; case 8.75: $tz = 'Asia/Shanghai'; break; case 9.5: $tz = 'Australia/Adelaide'; break; case 11: $tz = 'Asia/Vladivostok'; break; case 11.5: $tz = 'Asia/Vladivostok'; break; case 13: $tz = 'Pacific/Tongatapu'; break; case 14: $tz = 'Pacific/Kiritimati'; break; default: $tz = timezone_name_from_abbr('', $row->time_zone * 3600, NULL); } // create publish up date time string $rpup = $row->publish_up; $publishtime = date('Y-m-d 00:00:00'); if ($row->publish_up) { $publishtime = $row->publish_up . ' ' . $start_time . ':00'; $row->publish_up = \Date::of($publishtime)->toSql(); } // create publish down date/time string $publishtime = date('Y-m-d 00:00:00'); if ($row->publish_down) { $publishtime = $row->publish_down . ' ' . $end_time . ':00'; $row->publish_down = \Date::of($publishtime)->toSql(); } // Always unpublish if no Publisher otherwise publish automatically if ($this->config->getCfg('adminlevel')) { $row->state = 0; } else { $row->state = 1; } $row->state = 1; // Verify that the event doesn't start after it ends or ends before it starts. $pubdow = strtotime($row->publish_down); $pubup = strtotime($row->publish_up); if ($pubdow <= $pubup) { // Set the error message $this->setError(Lang::txt('EVENTS_EVENT_MUST_END_AFTER_START')); // Fall through to the edit view $this->editTask($row); return; } //set the scope to be regular events $row->scope = 'event'; if (!$row->check()) { // Set the error message $this->setError($row->getError()); $this->tags = $tags; // Fall through to the edit view $this->editTask($row); return; } if (!$row->store()) { // Set the error message $this->setError($row->getError()); $this->tags = $tags; // Fall through to the edit view $this->editTask($row); return; } $row->checkin(); // Save the tags $rt = new Tags($row->id); $rt->setTags($tags, User::get('id')); // Build the message to be e-mailed if ($state == 'add') { $subject = '[' . Config::get('sitename') . ' ' . Lang::txt('EVENTS_CAL_LANG_CAL_TITLE') . '] - ' . Lang::txt('EVENTS_CAL_LANG_MAIL_ADDED'); $eview = new View(array('name' => 'emails', 'layout' => 'created')); } else { $subject = '[' . Config::get('sitename') . ' ' . Lang::txt('EVENTS_CAL_LANG_CAL_TITLE') . '] - ' . Lang::txt('EVENTS_CAL_LANG_MAIL_ADDED'); $eview = new View(array('name' => 'emails', 'layout' => 'edited')); } $eview->option = $this->_option; $eview->sitename = Config::get('sitename'); $eview->user = User::getInstance(); $eview->row = $row; $message = $eview->loadTemplate(); $message = str_replace("\n", "\r\n", $message); // Send the e-mail $this->_sendMail(Config::get('sitename'), Config::get('mailfrom'), $subject, $message); // Redirect to the details page for the event we just created App::redirect(Route::url('index.php?option=' . $this->_option . '&task=details&id=' . $row->id)); }
/** * Display a feed of comments * * @return void */ protected function _feed() { if (!$this->params->get('comments_feeds')) { $this->action = 'view'; $this->_view(); return; } // Set the mime encoding for the document Document::setType('feed'); // Load the comments $comment = new \Plugins\Hubzero\Comments\Models\Comment(); $filters = array('parent' => 0, 'item_type' => $this->obj_type, 'item_id' => $this->obj_id); if ($this->obj instanceof \Hubzero\Base\Model) { $title = $this->obj->get('title'); } else { $title = $this->obj->title; } // Start a new feed object $doc = Document::instance(); $doc->link = Route::url($this->url); $doc->title = Config::get('sitename') . ' - ' . Lang::txt(strtoupper($this->_option)); $doc->title .= $title ? ': ' . stripslashes($title) : ''; $doc->title .= ': ' . Lang::txt('PLG_HUBZERO_COMMENTS'); $doc->description = Lang::txt('PLG_HUBZERO_COMMENTS_RSS_DESCRIPTION', Config::get('sitename'), stripslashes($title)); $doc->copyright = Lang::txt('PLG_HUBZERO_COMMENTS_RSS_COPYRIGHT', date("Y"), Config::get('sitename')); // Start outputing results if any found if ($comment->replies('list', $filters)->total() > 0) { foreach ($comment->replies() as $row) { // URL link to article $link = Route::url('index.php?option=' . $this->_option . '§ion=' . $section->alias . '&category=' . $category->alias . '&alias=' . $entry->alias . '#c' . $row->id); $author = Lang::txt('PLG_HUBZERO_COMMENTS_ANONYMOUS'); if (!$row->get('anonymous')) { $author = $row->creator('name'); } // Prepare the title $title = Lang::txt('PLG_HUBZERO_COMMENTS_COMMENT_BY', $author) . ' @ ' . $row->created('time') . ' on ' . $row->created('date'); // Strip html from feed item description text if ($row->isReported()) { $description = Lang::txt('PLG_HUBZERO_COMMENTS_REPORTED_AS_ABUSIVE'); } else { $description = $row->content('clean'); } @($date = $row->created() ? date('r', strtotime($row->created())) : ''); // Load individual item creator class $item = new \Hubzero\Document\Type\Feed\Item(); $item->title = $title; $item->link = $link; $item->description = $description; $item->date = $date; $item->category = ''; $item->author = $author; // Loads item info into rss array $doc->addItem($item); // Check for any replies if ($row->replies()->total()) { foreach ($row->replies() as $reply) { // URL link to article $link = Route::url('index.php?option=' . $this->_option . '§ion=' . $section->alias . '&category=' . $category->alias . '&alias=' . $entry->alias . '#c' . $reply->id); $author = Lang::txt('PLG_HUBZERO_COMMENTS_ANONYMOUS'); if (!$reply->anonymous) { $cuser = User::getInstance($reply->created_by); $author = $cuser->get('name'); } // Prepare the title $title = Lang::txt('PLG_HUBZERO_COMMENTS_REPLY_TO_COMMENT', $row->id, $author) . ' @ ' . Date::of($reply->created)->toLocal(Lang::txt('TIME_FORMAT_HZ1')) . ' ' . Lang::txt('PLG_HUBZERO_COMMENTS_ON') . ' ' . Date::of($reply->created)->toLocal(Lang::txt('DATE_FORMAT_HZ1')); // Strip html from feed item description text if ($reply->reports) { $description = Lang::txt('PLG_HUBZERO_COMMENTS_REPORTED_AS_ABUSIVE'); } else { $description = is_object($p) ? $p->parse(stripslashes($reply->content)) : nl2br(stripslashes($reply->content)); } $description = html_entity_decode(\Hubzero\Utility\Sanitize::clean($description)); @($date = $reply->created ? gmdate('r', strtotime($reply->created)) : ''); // Load individual item creator class $item = new \Hubzero\Document\Type\Feed\Item(); $item->title = $title; $item->link = $link; $item->description = $description; $item->date = $date; $item->category = ''; $item->author = $author; // Loads item info into rss array $doc->addItem($item); if ($reply->replies) { foreach ($reply->replies as $response) { // URL link to article $link = Route::url('index.php?option=' . $this->_option . '§ion=' . $section->alias . '&category=' . $category->alias . '&alias=' . $entry->alias . '#c' . $response->id); $author = Lang::txt('PLG_HUBZERO_COMMENTS_ANONYMOUS'); if (!$response->anonymous) { $cuser = User::getInstance($response->created_by); $author = $cuser->get('name'); } // Prepare the title $title = Lang::txt('PLG_HUBZERO_COMMENTS_REPLY_TO_COMMENT', $reply->id, $author) . ' @ ' . Date::of($response->created)->toLocal(Lang::txt('TIME_FORMAT_HZ1')) . ' ' . Lang::txt('PLG_HUBZERO_COMMENTS_ON') . ' ' . Date::of($response->created)->toLocal(Lang::txt('DATE_FORMAT_HZ1')); // Strip html from feed item description text if ($response->reports) { $description = Lang::txt('PLG_HUBZERO_COMMENTS_REPORTED_AS_ABUSIVE'); } else { $description = is_object($p) ? $p->parse(stripslashes($response->content)) : nl2br(stripslashes($response->content)); } $description = html_entity_decode(\Hubzero\Utility\Sanitize::clean($description)); @($date = $response->created ? gmdate('r', strtotime($response->created)) : ''); // Load individual item creator class $item = new \Hubzero\Document\Type\Feed\Item(); $item->title = $title; $item->link = $link; $item->description = $description; $item->date = $date; $item->category = ''; $item->author = $author; // Loads item info into rss array $doc->addItem($item); } } } } } } // Output the feed echo $doc->render(); }
/** * Saves a project * Redirects to main listing * * @param boolean $redirect * @return void */ public function saveTask($redirect = false) { // Check for request forgeries Request::checkToken(); // Config $setup_complete = $this->config->get('confirm_step', 0) ? 3 : 2; // Incoming $formdata = $_POST; $id = Request::getVar('id', 0); $action = Request::getVar('admin_action', ''); $message = rtrim(\Hubzero\Utility\Sanitize::clean(Request::getVar('message', ''))); // Load model $model = new Models\Project($id); if (!$model->exists()) { App::redirect('index.php?option=' . $this->_option, Lang::txt('COM_PROJECTS_NOTICE_ID_NOT_FOUND'), 'error'); } $title = $formdata['title'] ? rtrim($formdata['title']) : $model->get('title'); $type = isset($formdata['type']) ? $formdata['type'] : 1; $model->set('title', $title); $model->set('about', rtrim(\Hubzero\Utility\Sanitize::clean($formdata['about']))); $model->set('type', $type); $model->set('modified', Date::toSql()); $model->set('modified_by', User::get('id')); $model->set('private', Request::getInt('private', 0)); $this->_message = Lang::txt('COM_PROJECTS_SUCCESS_SAVED'); // Was project suspended? $suspended = false; if ($model->isInactive()) { $suspended = $model->table('Activity')->checkActivity($id, Lang::txt('COM_PROJECTS_ACTIVITY_PROJECT_SUSPENDED')); } $subject = Lang::txt('COM_PROJECTS_PROJECT') . ' "' . $model->get('alias') . '" '; $sendmail = 0; // Get project managers $managers = $model->table('Owner')->getIds($id, 1, 1); // Admin actions if ($action) { switch ($action) { case 'delete': $model->set('state', 2); $what = Lang::txt('COM_PROJECTS_ACTIVITY_PROJECT_DELETED'); $subject .= Lang::txt('COM_PROJECTS_MSG_ADMIN_DELETED'); $this->_message = Lang::txt('COM_PROJECTS_SUCCESS_DELETED'); break; case 'suspend': $model->set('state', 0); $what = Lang::txt('COM_PROJECTS_ACTIVITY_PROJECT_SUSPENDED'); $subject .= Lang::txt('COM_PROJECTS_MSG_ADMIN_SUSPENDED'); $this->_message = Lang::txt('COM_PROJECTS_SUCCESS_SUSPENDED'); break; case 'reinstate': $model->set('state', 1); $what = $suspended ? Lang::txt('COM_PROJECTS_ACTIVITY_PROJECT_REINSTATED') : Lang::txt('COM_PROJECTS_ACTIVITY_PROJECT_ACTIVATED'); $subject .= $suspended ? Lang::txt('COM_PROJECTS_MSG_ADMIN_REINSTATED') : Lang::txt('COM_PROJECTS_MSG_ADMIN_ACTIVATED'); $this->_message = $suspended ? Lang::txt('COM_PROJECTS_SUCCESS_REINSTATED') : Lang::txt('COM_PROJECTS_SUCCESS_ACTIVATED'); break; } // Add activity $model->recordActivity($what, 0, '', '', 'project', 0, $admin = 1); $sendmail = 1; } elseif ($message) { $subject .= ' - ' . Lang::txt('COM_PROJECTS_MSG_ADMIN_NEW_MESSAGE'); $sendmail = 1; $this->_message = Lang::txt('COM_PROJECTS_SUCCESS_MESSAGE_SENT'); } // Save changes if (!$model->store()) { $this->setError($model->getError()); return false; } // Incoming tags $tags = Request::getVar('tags', '', 'post'); // Save the tags $cloud = new Models\Tags($model->get('id')); $cloud->setTags($tags, User::get('id'), 1); // Save params $incoming = Request::getVar('params', array()); if (!empty($incoming)) { foreach ($incoming as $key => $value) { if ($key == 'quota' || $key == 'pubQuota') { // convert GB to bytes $value = Helpers\Html::convertSize(floatval($value), 'GB', 'b'); } $model->saveParam($key, $value); } } // Add members if specified $this->model = $model; $this->_saveMember(); // Change ownership $this->_changeOwnership(); // Send message if ($this->config->get('messaging', 0) && $sendmail && count($managers) > 0) { // Email config $from = array(); $from['name'] = Config::get('sitename') . ' ' . Lang::txt('COM_PROJECTS'); $from['email'] = Config::get('mailfrom'); // Html email $from['multipart'] = md5(date('U')); // Message body $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'admin_plain')); $eview->option = $this->_option; $eview->subject = $subject; $eview->action = $action; $eview->project = $model; $eview->message = $message; $body = array(); $body['plaintext'] = $eview->loadTemplate(false); $body['plaintext'] = str_replace("\n", "\r\n", $body['plaintext']); // HTML email $eview->setLayout('admin_html'); $body['multipart'] = $eview->loadTemplate(); $body['multipart'] = str_replace("\n", "\r\n", $body['multipart']); // Send HUB message Event::trigger('xmessage.onSendMessage', array('projects_admin_notice', $subject, $body, $from, $managers, $this->_option)); } Notify::message($this->_message, 'success'); // Redirect to edit view? if ($redirect) { App::redirect(Route::url('index.php?option=' . $this->_option . '&task=edit&id=' . $id, false)); } else { App::redirect(Route::url('index.php?option=' . $this->_option, false)); } }
/** * Save a review * * @return void */ public function savereview() { // Check for request forgeries Request::checkToken(); // Incoming $resource_id = Request::getInt('resource_id', 0); // Do we have a resource ID? if (!$resource_id) { // No ID - fail! Can't do anything else without an ID $this->setError(Lang::txt('PLG_RESOURCES_REVIEWS_NO_RESOURCE_ID')); return; } $database = App::get('db'); // Bind the form data to our object $row = new \Components\Resources\Tables\Review($database); if (!$row->bind($_POST)) { $this->setError($row->getError()); return; } // Perform some text cleaning, etc. $row->id = Request::getInt('reviewid', 0); if (!$row->id) { $row->state = 1; } $row->comment = \Hubzero\Utility\Sanitize::stripImages(\Hubzero\Utility\Sanitize::clean($row->comment)); $row->anonymous = $row->anonymous == 1 || $row->anonymous == '1' ? $row->anonymous : 0; $row->created = $row->created && $row->created != '0000-00-00 00:00:00' ? $row->created : Date::toSql(); // Check for missing (required) fields if (!$row->check()) { $this->setError($row->getError()); return; } // Save the data if (!$row->store()) { $this->setError($row->getError()); return; } // Calculate the new average rating for the parent resource $resource =& $this->resource; $resource->calculateRating(); $resource->updateRating(); // Process tags $tags = trim(Request::getVar('review_tags', '')); if ($tags) { $rt = new \Components\Resources\Helpers\Tags($resource_id); $rt->setTags($tags, $row->user_id); } // Instantiate a helper object and get all the contributor IDs $helper = new \Components\Resources\Helpers\Helper($resource->id, $database); $helper->getContributorIDs(); $users = $helper->contributorIDs; // Build the subject $subject = Config::get('sitename') . ' ' . Lang::txt('PLG_RESOURCES_REVIEWS_CONTRIBUTIONS'); // Message $eview = new \Hubzero\Plugin\View(array('folder' => 'resources', 'element' => 'reviews', 'name' => 'emails')); $eview->option = $this->_option; $eview->user = User::getRoot(); $eview->resource = $resource; $eview->review = $row; $message = $eview->loadTemplate(); // Build the "from" data for the e-mail $from = array('name' => Config::get('sitename') . ' ' . Lang::txt('PLG_RESOURCES_REVIEWS_CONTRIBUTIONS'), 'email' => Config::get('mailfrom')); // Send message if (!Event::trigger('xmessage.onSendMessage', array('resources_new_comment', $subject, $message, $from, $users, $this->_option))) { $this->setError(Lang::txt('PLG_RESOURCES_REVIEWS_FAILED_TO_MESSAGE')); } }
/** * Display module content * * @return void */ public function display() { // Field labels $this->name_label = $this->params->get('name_label', Lang::txt('MOD_RAPID_CONTACT_FIELD_NAME')); $this->email_label = $this->params->get('email_label', Lang::txt('MOD_RAPID_CONTACT_FIELD_EMAIL')); $this->subject_label = $this->params->get('subject_label', Lang::txt('MOD_RAPID_CONTACT_FIELD_SUBJECT')); $this->message_label = $this->params->get('message_label', Lang::txt('MOD_RAPID_CONTACT_FIELD_MESSAGE')); // Button text $this->button_text = $this->params->get('button_text', Lang::txt('MOD_RAPID_CONTACT_SEND')); // Pre text $this->pre_text = $this->params->get('pre_text', ''); // Thank you message $this->page_text = $this->params->get('page_text', Lang::txt('MOD_RAPID_CONTACT_THANK_YOU')); // Error messages $this->error_text = $this->params->get('error_text', Lang::txt('MOD_RAPID_CONTACT_ERROR_SENDING')); $this->no_email = $this->params->get('no_email', Lang::txt('MOD_RAPID_CONTACT_ERROR_NO_EMAIL')); $this->invalid_email = $this->params->get('invalid_email', Lang::txt('MOD_RAPID_CONTACT_ERROR_INVALID_EMAIL')); // From $this->from_name = $this->params->get('from_name', Lang::txt('MOD_RAPID_CONTACT')); $this->from_email = $this->params->get('from_email', '*****@*****.**'); // To $this->recipient = $this->params->get('email_recipient', Config::get('mailfrom')); if (!trim($this->recipient)) { $this->recipient = Config::get('mailfrom'); } // Enable Anti-spam? $this->enable_anti_spam = $this->params->get('enable_anti_spam', true); $this->anti_spam_q = $this->params->get('anti_spam_q', Lang::txt('MOD_RAPID_CONTACT_ANTIPSAM')); $this->anti_spam_a = $this->params->get('anti_spam_a', '2'); $this->mod_class_suffix = $this->params->get('moduleclass_sfx', ''); $disable_https = $this->params->get('disable_https', false); $exact_url = $this->params->get('exact_url', true); if (!$exact_url) { //$this->url = $this->_cleanXss(filter_var(Request::current(), FILTER_SANITIZE_URL)); $this->url = Request::current(); } else { if (!$disable_https) { $this->url = !empty($_SERVER['HTTPS']) ? 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] : 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; } else { $this->url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; } } //$qs = str_replace(array('"', '?'), '', urldecode($_SERVER['QUERY_STRING'])); //$aqs = explode('?', $this->url); //$this->url = $aqs[0] . '?' . urlencode($qs); $fixed_url = $this->params->get('fixed_url', true); if ($fixed_url) { $this->url = $this->params->get('fixed_url_address', ''); } $this->error = ''; $this->replacement = ''; $this->posted = array('name' => '', 'email' => '', 'subject' => '', 'message' => ''); if (isset($_POST['rp'])) { $this->posted = Request::getVar('rp', array(), 'post'); if ($this->enable_anti_spam) { if (!isset($this->posted['anti_spam_answer']) || $this->posted['anti_spam_answer'] != $this->anti_spam_a) { $this->error = Lang::txt('MOD_RAPID_CONTACT_INVALID_ANTIPSAM_ANSWER'); } } if ($this->posted['email'] === '') { $this->error = $this->no_email; } if (!preg_match("#^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})\$#i", $this->posted['email'])) { $this->error = $this->invalid_email; } if ($this->error == '') { $mySubject = Sanitize::clean($this->posted['subject']); $myMessage = Lang::txt('MOD_RAPID_CONTACT_MESSAGE_FROM', $this->posted['name'], $this->posted['email'], Request::getVar('HTTP_REFERER', '', 'SERVER'), Config::get('sitename')); $myMessage .= "\n\n" . Sanitize::clean($this->posted['message']); $this->from_email = $this->posted['email']; $this->from_name = isset($this->posted['name']) && Sanitize::clean($this->posted['name']) ? Sanitize::clean($this->posted['name']) : $this->posted['email']; $mailSender = new Message(); $mailSender->setSubject($mySubject)->addFrom($this->from_email, $this->from_name)->addTo($this->recipient)->addReplyTo($this->posted['email'], $this->posted['name'])->setBody($myMessage); if (!$mailSender->send()) { $this->error = $this->error_text; } else { $this->replacement = $this->page_text; } } } require $this->getLayoutPath($this->params->get('layout', 'default')); }
/** * Store changes to this offering * * @param boolean $check Perform data validation check? * @return boolean False if error, True on success */ public function store($check = true) { if (!$this->get('anonymous')) { $this->set('anonymous', 0); } $this->set('about', \Hubzero\Utility\Sanitize::clean($this->get('about'))); if (!parent::store($check)) { return false; } return true; }
/** * 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'); }
/** * Display an RSS feed * * @return void */ public function feedTask() { Document::setType('feed'); // Start a new feed object $doc = Document::instance(); // Incoming $id = Request::getInt('id', 0); $alias = Request::getVar('alias', ''); // Ensure we have an ID or alias to work with if (!$id && !$alias) { App::redirect(Route::url('index.php?option=' . $this->_option)); return; } // Load the resource $resource = new Resource($this->database); if ($alias) { $resource->load($alias); $id = $resource->id; } else { $resource->load($id); $alias = $resource->alias; } // Make sure we got a result from the database if (!$resource) { App::abort(404, Lang::txt('COM_RESOURCES_RESOURCE_NOT_FOUND')); return; } // Make sure the resource is published and standalone if ($resource->published == 0 || $resource->standalone != 1) { App::abort(403, Lang::txt('COM_RESOURCES_ALERTNOTAUTH')); return; } // Make sure they have access to view this resource if ($this->checkGroupAccess($resource)) { App::abort(403, Lang::txt('COM_RESOURCES_ALERTNOTAUTH')); return; } // Incoming $filters = array(); if ($resource->type == 2) { $filters['sortby'] = Request::getVar('sortby', 'ordering'); } else { $filters['sortby'] = Request::getVar('sortby', 'ranking'); } $filters['limit'] = Request::getInt('limit', 100); $filters['start'] = Request::getInt('limitstart', 0); $filters['year'] = Request::getInt('year', 0); $filters['id'] = $resource->id; $feedtype = Request::getVar('content', 'audio'); // Initiate a resource helper class $helper = new Helper($resource->id, $this->database); $rows = $helper->getStandaloneChildren($filters); $base = rtrim(Request::base(), '/'); $title = $resource->title; $feedtypes_abr = array(" ", "slides", "audio", "video", "sd_video", "hd_video"); $feedtypes_full = array(" & ", "Slides", "Audio", "Video", "SD full", "HD"); $type = str_replace($feedtypes_abr, $feedtypes_full, $feedtype); $title = '[' . $type . '] ' . $title; // Build some basic RSS document information $dtitle = \Hubzero\Utility\Sanitize::clean(stripslashes($title)); $doc->title = trim(\Hubzero\Utility\String::truncate(html_entity_decode($dtitle), 250)); $doc->description = htmlspecialchars(html_entity_decode(\Hubzero\Utility\Sanitize::clean(stripslashes($resource->introtext))), ENT_COMPAT, 'UTF-8'); $doc->copyright = \Lang::txt('COM_RESOURCES_RSS_COPYRIGHT', date("Y"), Config::get('sitename')); $doc->category = Lang::txt('COM_RESOURCES_RSS_CATEGORY'); $doc->link = Route::url('index.php?option=' . $this->_option . '&id=' . $resource->id); $rt = new Tags($resource->id); $rtags = $rt->tags(); $tagarray = array(); $categories = array(); $subcategories = array(); if ($rtags) { foreach ($rtags as $tag) { if (substr($tag->get('tag'), 0, 6) == 'itunes') { $tbits = explode(':', $tag->get('raw_tag')); if (count($tbits) > 2) { $subcategories[] = end($tbits); } else { $categories[] = str_replace('itunes:', '', $tag->get('raw_tag')); } } elseif ($tag->get('admin') == 0) { $tagarray[] = $tag->get('raw_tag'); } } } $tags = implode(', ', $tagarray); $tags = trim(\Hubzero\Utility\String::truncate($tags, 250)); $tags = rtrim($tags, ','); $helper->getUnlinkedContributors(); $cons = $helper->ul_contributors; $cons = explode(';', $cons); $author = ''; foreach ($cons as $con) { if ($con) { $author = trim($con); break; } } $doc->itunes_summary = html_entity_decode(\Hubzero\Utility\Sanitize::clean(stripslashes($resource->introtext))); if (count($categories) > 0) { $doc->itunes_category = $categories[0]; if (count($subcategories) > 0) { $doc->itunes_subcategories = $subcategories; } } $doc->itunes_explicit = 'no'; $doc->itunes_keywords = $tags; $doc->itunes_author = $author; $itunes_image_name = 'itunes_' . str_replace(' ', '_', strtolower($feedtype)); $dimg = $this->_checkForImage($itunes_image_name, $this->config->get('uploadpath'), $resource->created, $resource->id); if ($dimg) { $dimage = new \Hubzero\Document\Type\Feed\Image(); $dimage->url = $dimg; $dimage->title = trim(\Hubzero\Utility\String::truncate(html_entity_decode($dtitle . ' ' . Lang::txt('COM_RESOURCES_RSS_ARTWORK')), 250)); $dimage->link = $base . $doc->link; $doc->itunes_image = $dimage; } $owner = new \Hubzero\Document\Type\Feed\ItunesOwner(); $owner->email = Config::get('mailfrom'); $owner->name = Config::get('sitename'); $doc->itunes_owner = $owner; // Start outputing results if any found if (count($rows) > 0) { foreach ($rows as $row) { // Prepare the title $title = strip_tags($row->title); $title = html_entity_decode($title); // URL link to resource $link = DS . ltrim(Route::url('index.php?option=' . $this->_option . '&id=' . $row->id), DS); // Strip html from feed item description text $description = html_entity_decode(\Hubzero\Utility\Sanitize::stripAll(stripslashes($row->introtext))); $author = ''; @($date = $row->publish_up ? date('r', strtotime($row->publish_up)) : ''); // Instantiate a resource helper $rhelper = new Helper($row->id, $this->database); // Get any podcast/vodcast files $podcast = ''; $type_model = new Type($this->database); $all_logical_types = $type_model->getTypes(28); // 28 means 'logical' types. $queried_logical_types = @explode(' ', $feedtype); if (is_null($queried_logical_types) || !is_array($queried_logical_types)) { App::abort(404, Lang::txt('COM_RESOURCES_RESOURCE_FEED_BAD_REQUEST')); return; } $relevant_logical_types_by_id = array(); foreach ($queried_logical_types as $queried) { $as_mnemonic = preg_replace('/[_-]/', ' ', $queried); foreach ($all_logical_types as $logical_type) { if (preg_match_all('/Podcast \\(([^()]+)\\)/', $logical_type->type, $matches) == 1 && strcasecmp($matches[1][0], $as_mnemonic) == 0) { $relevant_logical_types_by_id[$logical_type->id] = $logical_type; break; } elseif ($as_mnemonic == 'slides' && $logical_type->type == 'Presentation Slides') { $relevant_logical_types_by_id[$logical_type->id] = $logical_type; break; } elseif ($as_mnemonic == 'notes' && $logical_type->type == 'Lecture Notes') { $relevant_logical_types_by_id[$logical_type->id] = $logical_type; break; } } } $rhelper->getChildren(); $podcasts = array(); $children = array(); if ($rhelper->children && count($rhelper->children) > 0) { $grandchildren = $rhelper->children; foreach ($grandchildren as $grandchild) { if (isset($relevant_logical_types_by_id[(int) $grandchild->logicaltype])) { if (stripslashes($grandchild->introtext) != '') { $gdescription = html_entity_decode(\Hubzero\Utility\Sanitize::clean(stripslashes($grandchild->introtext))); } array_push($podcasts, $grandchild->path); array_push($children, $grandchild); } } } // Get the contributors of this resource $rhelper->getContributors(); $author = strip_tags($rhelper->contributors); $rtt = new Tags($row->id); $rtags = $rtt->render('string'); if (trim($rtags)) { $rtags = trim(\Hubzero\Utility\String::truncate($rtags, 250)); $rtags = rtrim($rtags, ','); } // Get attributes //$attribs = new \Hubzero\Config\Registry($row->attribs); if ($children) { $attribs = new \Hubzero\Config\Registry($children[0]->attribs); } foreach ($podcasts as $podcast) { // Load individual item creator class $item = new \Hubzero\Document\Type\Feed\Item(); $item->title = $title; $item->link = $link; $item->description = $description; $item->date = $date; $item->category = $row->typetitle ? $row->typetitle : ''; $item->author = $author; $img = $this->_checkForImage('ituness_artwork', $this->config->get('uploadpath'), $row->created, $row->id); if ($img) { $image = new \Hubzero\Document\Type\Feed\Image(); $image->url = $img; $image->title = $title . ' ' . Lang::txt('COM_RESOURCES_RSS_ARTWORK'); $image->link = $base . $link; $item->itunes_image = $image; } $item->itunes_summary = $description; $item->itunes_explicit = 'no'; $item->itunes_keywords = $rtags; $item->itunes_author = $author; if ($attribs->get('duration')) { $item->itunes_duration = $attribs->get('duration'); } if ($podcast) { $podcastp = $podcast; $podcast = DS . ltrim($this->_fullPath($podcast), DS); if (substr($podcastp, 0, strlen($this->config->get('uploadpath'))) == $this->config->get('uploadpath')) { // Do nothing } else { $podcastp = trim($this->config->get('uploadpath'), DS) . DS . ltrim($podcastp, DS); } $podcastp = PATH_APP . DS . ltrim($podcastp, DS); if (file_exists($podcastp)) { $fs = filesize($podcastp); $enclosure = new \Hubzero\Document\Type\Feed\Enclosure(); $enclosure->url = $podcast; switch (Html::getFileExtension($podcast)) { case 'm4v': $enclosure->type = 'video/x-m4v'; break; case 'mp4': $enclosure->type = 'video/mp4'; break; case 'wmv': $enclosure->type = 'video/wmv'; break; case 'mov': $enclosure->type = 'video/quicktime'; break; case 'qt': $enclosure->type = 'video/quicktime'; break; case 'mpg': $enclosure->type = 'video/mpeg'; break; case 'mpeg': $enclosure->type = 'video/mpeg'; break; case 'mpe': $enclosure->type = 'video/mpeg'; break; case 'mp2': $enclosure->type = 'video/mpeg'; break; case 'mpv2': $enclosure->type = 'video/mpeg'; break; case 'mp3': $enclosure->type = 'audio/mpeg'; break; case 'm4a': $enclosure->type = 'audio/x-m4a'; break; case 'aiff': $enclosure->type = 'audio/x-aiff'; break; case 'aif': $enclosure->type = 'audio/x-aiff'; break; case 'wav': $enclosure->type = 'audio/x-wav'; break; case 'ra': $enclosure->type = 'audio/x-pn-realaudio'; break; case 'ram': $enclosure->type = 'audio/x-pn-realaudio'; break; case 'ppt': $enclosure->type = 'application/vnd.ms-powerpoint'; break; case 'pps': $enclosure->type = 'application/vnd.ms-powerpoint'; break; case 'pdf': $enclosure->type = 'application/pdf'; break; case 'doc': $enclosure->type = 'application/msword'; break; case 'txt': $enclosure->type = 'text/plain'; break; case 'html': $enclosure->type = 'text/html'; break; case 'htm': $enclosure->type = 'text/html'; break; } $enclosure->length = $fs; $item->guid = $podcast; $item->enclosure = $enclosure; } // Loads item info into rss array $doc->addItem($item); } } } } }
/** * 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); }
/** * Save a review * * @return void */ public function savereview() { // Is the user logged in? if (User::isGuest()) { $this->setError(Lang::txt('PLG_RESOURCES_REVIEWS_LOGIN_NOTICE')); return; } // Check for request forgeries Request::checkToken(); // Incoming $data = Request::getVar('review', array(), 'post', 'none', 2); // Bind the form data to our object $row = \Components\Resources\Reviews\Models\Review::oneOrNew($data['id'])->set($data); // Perform some text cleaning, etc. if ($row->isNew()) { $row->set('state', \Components\Resources\Reviews\Models\Review::STATE_PUBLISHED); } $row->set('comment', \Hubzero\Utility\Sanitize::stripImages(\Hubzero\Utility\Sanitize::clean($row->get('comment')))); $row->set('anonymous', $row->get('anonymous') ? 1 : 0); // Save the data if (!$row->save()) { $this->setError($row->getError()); return; } // Calculate the new average rating for the parent resource $resource =& $this->resource; $resource->calculateRating(); $resource->updateRating(); // Instantiate a helper object and get all the contributor IDs $database = App::get('db'); $helper = new \Components\Resources\Helpers\Helper($resource->id, $database); $helper->getContributorIDs(); $users = $helper->contributorIDs; // Build the subject $subject = Config::get('sitename') . ' ' . Lang::txt('PLG_RESOURCES_REVIEWS_CONTRIBUTIONS'); // Message $eview = new \Hubzero\Plugin\View(array('folder' => 'resources', 'element' => 'reviews', 'name' => 'emails')); $eview->option = $this->_option; $eview->user = User::getInstance(); $eview->resource = $resource; $eview->review = $row; $message = $eview->loadTemplate(); // Build the "from" data for the e-mail $from = array('name' => Config::get('sitename') . ' ' . Lang::txt('PLG_RESOURCES_REVIEWS_CONTRIBUTIONS'), 'email' => Config::get('mailfrom')); // Send message if (!Event::trigger('xmessage.onSendMessage', array('resources_new_comment', $subject, $message, $from, $users, $this->_option))) { $this->setError(Lang::txt('PLG_RESOURCES_REVIEWS_FAILED_TO_MESSAGE')); } }
/** * Applies filters to Citations model and returns applied filters * @param array $filters array of POST values * @return array sanitized and validated filter values */ private function _filterHandler($filters = array(), $scope_id = 0) { $citations = \Components\Citations\Models\Citation::all(); // require citations if (!$citations) { return false; } $filterCount = count($filters); // see if we have members too $config = json_decode($this->group->get('params')); $members = $this->group->members; // get the ones for this group if (isset($config->display) && $config->display == 'member') { // if all filter is applied if (array_key_exists('filter', $filters) && ($filters['filter'] == '' || $filters['filter'] == 'all')) { // get the ID's of the citations of members of the group $memberCitations = \Components\Citations\Models\Citation::all()->where('scope', '=', 'member')->whereIn('scope_id', $members)->where('published', '=', $citations::STATE_PUBLISHED); // don't include deleted citations // push them to an array $memberCites = array(); foreach ($memberCitations as $mC) { array_push($memberCites, $mC->id); } // Get the group's citations plus member citations. $citations->where('scope', '=', self::PLUGIN_SCOPE)->where('scope_id', '=', $scope_id)->orWhereIn('id', $memberCites)->where('published', '!=', $citations::STATE_DELETED); // don't include deleted citations } elseif (array_key_exists('filter', $filters) && $filters['filter'] == 'member') { $citations->where('scope', '=', 'member')->whereIn('scope_id', $members)->where('published', '=', $citations::STATE_PUBLISHED); // don't include deleted citations } else { // get the ID's of the citations of members of the group $memberCitations = \Components\Citations\Models\Citation::all()->where('scope', '=', 'member')->whereIn('scope_id', $members)->where('published', '=', $citations::STATE_PUBLISHED); // don't include deleted citations // push them to an array $memberCites = array(); foreach ($memberCitations as $mC) { array_push($memberCites, $mC->id); } // Get the group's citations plus member citations. $citations->where('scope', '=', self::PLUGIN_SCOPE)->where('scope_id', '=', $scope_id)->orWhereIn('id', $memberCites)->where('published', '!=', $citations::STATE_DELETED); // don't include deleted citations } } else { // display only group citations $citations->where('scope', '=', self::PLUGIN_SCOPE); $citations->where('scope_id', '=', $scope_id); $citations->where('published', '!=', $citations::STATE_DELETED); // don't include deleted citations } // apply filters on the set of citations if ($filterCount > 0) { foreach ($filters as $filter => $value) { // sanitization $value = \Hubzero\Utility\Sanitize::clean($value); // we handle things differently in search and sorting if ($filter != 'search' && $filter != 'sort' && $filter != 'tag' && $value != "" && $filter != 'filter') { switch ($filter) { case 'author': $citations->where('author', 'LIKE', "%{$value}%", 'and', 1); break; case 'publishedin': $citations->where('date_publish', 'LIKE', "%{$value}-%"); break; case 'year_start': $citations->where('year', '>=', $value); break; case 'year_end': $citations->where('year', '<=', $value); break; default: $citations->where($filter, '=', $value); break; } } // end if not search & not sort & non-empty value // for searching if ($filter == "search" && $value != "") { $terms = preg_split('/\\s+/', $value); $value = \Hubzero\Utility\Sanitize::clean($value); $term = $value; $collection = array(); $columns = array('author', 'title', 'isbn', 'doi', 'publisher', 'abstract'); foreach ($columns as $column) { foreach ($terms as $term) { // copy the original item $cite = clone $citations; // do some searching $cite->where($column, 'LIKE', "%{$term}%"); foreach ($cite as $c) { // put for collection later array_push($collection, $c->id); } // end foreach $cite } // end foreach terms } // end foreach columns // remove duplicates $collection = array_unique($collection); // pull the appropriate ones. $citations->whereIn('id', $collection); } // end searching // for tags if ($filter == "tag" && $value != "") { $collection = array(); $cite = clone $citations; foreach ($cite as $c) { foreach ($c->tags as $tag) { if ($tag->tag == $value) { array_push($collection, $c->id); } } } // remove duplicates $collection = array_unique($collection); // get the tagged ones $citations->whereIn('id', $collection); } // end if tags if ($filter == "sort" && $value != "") { $clause = explode(" ", $value); $citations->order($clause[0], $clause[1]); } } // end foreach filters as filter return array('citations' => $citations, 'filters' => $filters); } else { return array('citations' => $citations, 'filters' => array()); } }
/** * Saves a publication * Redirects to main listing * * @param boolean $redirect * @return void */ public function saveTask($redirect = false) { // Check for request forgeries Request::checkToken(); // Incoming $id = Request::getInt('id', 0); $action = Request::getVar('admin_action', ''); $published_up = Request::getVar('published_up', ''); $version = Request::getVar('version', 'default'); // Is this a new publication? Cannot create via back-end $isnew = $id ? 0 : 1; if (!$id) { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_PUBLICATIONS_ERROR_LOAD_PUBLICATION'), 'error'); return; } // Load publication model $this->model = new Models\Publication($id, $version); if (!$this->model->exists()) { throw new Exception(Lang::txt('COM_PUBLICATIONS_NOT_FOUND'), 404); } // Checkin resource $this->model->publication->checkin(); // Set redirect URL $url = Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&task=edit' . '&id[]=' . $id . '&version=' . $version, false); $authors = $this->model->authors(); $project = $this->model->project(); $this->model->setCuration(); $requireDoi = isset($this->model->_curationModel->_manifest->params->require_doi) ? $this->model->_curationModel->_manifest->params->require_doi : 0; // Incoming updates $title = trim(Request::getVar('title', '', 'post')); $title = htmlspecialchars($title); $abstract = trim(Request::getVar('abstract', '', 'post')); $abstract = htmlspecialchars(\Hubzero\Utility\Sanitize::clean($abstract)); $description = trim(Request::getVar('description', '', 'post', 'none', 2)); $release_notes = stripslashes(trim(Request::getVar('release_notes', '', 'post', 'none', 2))); $group_owner = Request::getInt('group_owner', 0, 'post'); $published_up = trim(Request::getVar('published_up', '', 'post')); $published_down = trim(Request::getVar('published_down', '', 'post')); $state = Request::getInt('state', 0); $metadata = ''; $activity = ''; // Save publication record $this->model->publication->alias = trim(Request::getVar('alias', '', 'post')); $this->model->publication->category = trim(Request::getInt('category', 0, 'post')); $this->model->publication->access = Request::getInt('access', 0, 'post'); if (!$project->get('owned_by_group')) { $this->model->publication->group_owner = $group_owner; } $this->model->publication->store(); // Get metadata if (isset($_POST['nbtag'])) { $category = $this->model->category(); $fields = array(); if (trim($category->customFields) != '') { $fs = explode("\n", trim($category->customFields)); foreach ($fs as $f) { $fields[] = explode('=', $f); } } $nbtag = Request::getVar('nbtag', array(), 'request', 'array'); foreach ($nbtag as $tagname => $tagcontent) { $tagcontent = trim(stripslashes($tagcontent)); if ($tagcontent != '') { $metadata .= "\n" . '<nb:' . $tagname . '>' . $tagcontent . '</nb:' . $tagname . '>' . "\n"; } else { foreach ($fields as $f) { if ($f[0] == $tagname && end($f) == 1) { echo Helpers\Html::alert(Lang::txt('COM_PUBLICATIONS_REQUIRED_FIELD_CHECK', $f[1])); exit; } } } } } // Save incoming $this->model->version->title = $title; $this->model->version->abstract = \Hubzero\Utility\String::truncate($abstract, 250); $this->model->version->description = $description; $this->model->version->metadata = $metadata; $this->model->version->release_notes = $release_notes; $this->model->version->license_text = trim(Request::getVar('license_text', '', 'post')); $this->model->version->license_type = Request::getInt('license_type', 0, 'post'); $this->model->version->access = Request::getInt('access', 0, 'post'); // Get DOI service $doiService = new Models\Doi($this->model); // DOI manually entered? $doi = trim(Request::getVar('doi', '', 'post')); if ($doi && (!$this->model->version->doi || !preg_match("/" . $doiService->_configs->shoulder . "/", $this->model->version->doi))) { $this->model->version->doi = $doi; } $this->model->version->published_up = $published_up ? Date::of($published_up, Config::get('offset'))->toSql() : '0000-00-00 00:00:00'; $this->model->version->published_down = $published_down && trim($published_down) != 'Never' ? Date::of($published_down, Config::get('offset'))->toSql() : '0000-00-00 00:00:00'; // Determine action (if status is flipped) if ($this->model->version->state != $state) { switch ($state) { case 1: $action = $this->model->version->state == 0 ? 'republish' : 'publish'; break; case 0: $action = 'unpublish'; break; case 3: case 4: $action = 'revert'; break; case 7: $action = 'wip'; break; } $this->model->version->state = $state; } // Update DOI with latest information if ($this->model->version->doi && !$action) { // Update DOI if locally issued if (preg_match("/" . $doiService->_configs->shoulder . "/", $this->model->version->doi)) { $doiService->update($this->model->version->doi, true); } } // Incoming tags $tags = Request::getVar('tags', '', 'post'); // Save the tags $rt = new Helpers\Tags($this->database); $rt->tag_object(User::get('id'), $id, $tags, 1, true); // Email config $pubtitle = \Hubzero\Utility\String::truncate($this->model->version->title, 100); $subject = Lang::txt('Version') . ' ' . $this->model->version->version_label . ' ' . Lang::txt('COM_PUBLICATIONS_OF') . ' ' . strtolower(Lang::txt('COM_PUBLICATIONS_PUBLICATION')) . ' "' . $pubtitle . '" '; $sendmail = 0; $message = rtrim(\Hubzero\Utility\Sanitize::clean(Request::getVar('message', ''))); $output = Lang::txt('COM_PUBLICATIONS_SUCCESS_SAVED_ITEM'); // Admin actions if ($action) { $output = ''; switch ($action) { case 'publish': case 'republish': // Unset the published_down timestamp if publishing $this->model->version->published_down = '0000-00-00 00:00:00'; $activity = $action == 'publish' ? Lang::txt('COM_PUBLICATIONS_ACTIVITY_ADMIN_PUBLISHED') : Lang::txt('COM_PUBLICATIONS_ACTIVITY_ADMIN_REPUBLISHED'); $subject .= $action == 'publish' ? Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_PUBLISHED') : Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_REPUBLISHED'); $this->model->version->state = 1; // Is service enabled? - Issue/update a DOI if ($doiService->on()) { if ($this->model->version->doi && preg_match("/" . $doiService->_configs->shoulder . "/", $this->model->version->doi)) { // Update $doiService->update($this->model->version->doi, true); if ($doiService->getError()) { $this->setError($doiService->getError()); } } elseif ($requireDoi) { // Register $doi = $doiService->register(true); if (!$doi) { App::redirect($url, Lang::txt('COM_PUBLICATIONS_ERROR_DOI') . ' ' . $doiService->getError(), 'error'); return; } else { $this->model->version->doi = $doi; } } } // Save date accepted if ($action == 'publish') { $this->model->version->accepted = Date::toSql(); $this->model->version->published_up = $published_up ? Date::of($published_up, Config::get('offset'))->toSql() : Date::toSql(); // Get and save manifest and its version $versionNumber = $this->model->_curationModel->checkCurationVersion(); $this->model->version->set('curation', json_encode($this->model->_curationModel->_manifest)); $this->model->version->set('curation_version_id', $versionNumber); // Check if publication is within grace period (published status) $gracePeriod = $this->config->get('graceperiod', 0); $allowArchive = $gracePeriod ? false : true; if ($allowArchive && $this->model->version->accepted && $this->model->version->accepted != '0000-00-00 00:00:00') { $monthFrom = Date::of($this->model->version->accepted . '+1 month')->toSql(); if (strtotime($monthFrom) < Date::toUnix()) { $allowArchive = true; } } // Run mkAIP if no grace period set or passed if (!$this->getError() && $this->model->version->doi && $allowArchive == true && (!$this->model->version->archived || $this->model->version->archived == '0000-00-00 00:00:00') && Helpers\Utilities::mkAip($this->model->version)) { $this->model->version->archived = Date::toSql(); } } if (!$this->getError()) { $output .= ' ' . Lang::txt('COM_PUBLICATIONS_ITEM') . ' '; $output .= $action == 'publish' ? Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_PUBLISHED') : Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_REPUBLISHED'); } break; case 'revert': // What is this? This sets it to the state it's alreayd in. //$this->model->version->state = $state ? $state : 4; $this->model->version->state = 3; $activity = Lang::txt('COM_PUBLICATIONS_ACTIVITY_ADMIN_REVERTED'); $subject .= Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_REVERTED'); $output .= ' ' . Lang::txt('COM_PUBLICATIONS_ITEM') . ' '; $output .= Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_REVERTED'); break; case 'unpublish': $this->model->version->state = 0; $this->model->version->published_down = Date::toSql(); $activity = Lang::txt('COM_PUBLICATIONS_ACTIVITY_ADMIN_UNPUBLISHED'); $subject .= Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_UNPUBLISHED'); $output .= ' ' . Lang::txt('COM_PUBLICATIONS_ITEM') . ' '; $output .= Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_UNPUBLISHED'); break; case 'wip': $activity = Lang::txt('COM_PUBLICATIONS_ACTIVITY_ADMIN_REQUESTED_CHANGES'); $subject .= Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_REQUESTED_CHANGES'); $output .= ' ' . Lang::txt('COM_PUBLICATIONS_ITEM') . ' '; $output .= Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_REQUESTED_CHANGES'); break; } } // Updating entry if anything changed if (!$this->getError()) { $this->model->version->modified = Date::toSql(); $this->model->version->modified_by = User::get('id'); // Store content if (!$this->model->version->store()) { App::redirect($url, $this->model->version->getError(), 'error'); return; } elseif ($action) { // Add activity $activity .= ' ' . strtolower(Lang::txt('version')) . ' ' . $this->model->version->version_label . ' ' . Lang::txt('COM_PUBLICATIONS_OF') . ' ' . strtolower(Lang::txt('publication')) . ' "' . $pubtitle . '" '; // Build return url $link = '/projects/' . $project->get('alias') . '/publications/' . $id . '/?version=' . $this->model->version->version_number; if ($action != 'message' && !$this->getError()) { $aid = $project->recordActivity($activity, $id, $pubtitle, $link, 'publication', 0, $admin = 1); $sendmail = $this->config->get('email') ? 1 : 0; // Append comment to activity if ($message && $aid) { require_once PATH_CORE . DS . 'components' . DS . 'com_projects' . DS . 'tables' . DS . 'comment.php'; $objC = new \Components\Projects\Tables\Comment($this->database); $comment = \Hubzero\Utility\String::truncate($message, 250); $comment = \Hubzero\Utility\Sanitize::stripAll($comment); $objC->itemid = $aid; $objC->tbl = 'activity'; $objC->parent_activity = $aid; $objC->comment = $comment; $objC->admin = 1; $objC->created = Date::toSql(); $objC->created_by = User::get('id'); $objC->store(); // Get new entry ID if (!$objC->id) { $objC->checkin(); } if ($objC->id) { $what = Lang::txt('COM_PROJECTS_AN_ACTIVITY'); $curl = Route::url($project->link('feed')) . '#tr_' . $aid; // same-page link $caid = $project->recordActivity(Lang::txt('COM_PROJECTS_COMMENTED') . ' ' . Lang::txt('COM_PROJECTS_ON') . ' ' . $what, $objC->id, $what, $curl, 'quote', 0, 1); // Store activity ID if ($caid) { $objC->activityid = $aid; $objC->store(); } } } } } } // Save parameters $params = Request::getVar('params', '', 'post'); if (is_array($params)) { foreach ($params as $k => $v) { $this->model->version->saveParam($this->model->version->id, $k, $v); } } // Do we have a message to send? if ($message) { $subject .= ' - ' . Lang::txt('COM_PUBLICATIONS_MSG_ADMIN_NEW_MESSAGE'); $sendmail = 1; $output .= ' ' . Lang::txt('COM_PUBLICATIONS_MESSAGE_SENT'); } // Send email if ($sendmail && !$this->getError()) { // Get ids of publication authors with accounts $notify = $this->model->table('Author')->getAuthors($this->model->version->id, 1, 1, 1, true); $notify[] = $this->model->version->created_by; $notify = array_unique($notify); $this->_emailContributors($subject, $message, $notify, $action); } // Append any errors if ($this->getError()) { $output .= ' ' . $this->getError(); } // Redirect to edit view? if ($redirect) { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&task=edit' . '&id[]=' . $id . '&version=' . $this->model->get('version_number'), false), $output); } else { App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), $output); } return; }
/** * Applies filters to Citations model and returns applied filters * @param array $filters array of POST values * @return array sanitized and validated filter values */ private function _filterHandler($filters = array(), $scope_id = 0) { $citations = \Components\Citations\Models\Citation::all(); // require citations if (!$citations) { return false; } // get the ones for this group $citations->where('scope', '=', 'member'); $citations->where('scope_id', '=', $scope_id); $citations->where('published', '!=', $citations::STATE_DELETED); // don't include deleted citations if (count($filters) > 0) { foreach ($filters as $filter => $value) { // sanitization $value = \Hubzero\Utility\Sanitize::clean($value); // we handle things differently in search and sorting if ($filter != 'search' && $filter != 'sort' && $filter != 'tag' && $value != "") { switch ($filter) { case 'author': $citations->where('author', 'LIKE', "%{$value}%", 'and', 1); break; case 'publishedin': $citations->where('date_publish', 'LIKE', "%{$value}-%"); break; case 'year_start': $citations->where('year', '>=', $value); break; case 'year_end': $citations->where('year', '<=', $value); break; case 'filter': if ($value == 'aff') { $value = 1; } else { $value = 0; } $citations->where('affiliated', '=', $value); break; default: $citations->where($filter, '=', $value); break; } } // end if not search & not sort & non-empty value // for searching if ($filter == "search" && $value != "") { $terms = preg_split('/\\s+/', $value); $value = \Hubzero\Utility\Sanitize::clean($value); $term = $value; $collection = array(); $columns = array('author', 'title', 'isbn', 'doi', 'publisher', 'abstract'); foreach ($columns as $column) { foreach ($terms as $term) { // copy the original item $cite = clone $citations; // do some searching $cite->where($column, 'LIKE', "%{$term}%"); foreach ($cite as $c) { // put for collection later array_push($collection, $c->id); } // end foreach $cite } // end foreach terms } // end foreach columns // remove duplicates $collection = array_unique($collection); // pull the appropriate ones. $citations->whereIn('id', $collection); } // end searching // for tags if ($filter == "tag" && $value != "") { $collection = array(); $cite = clone $citations; foreach ($cite as $c) { foreach ($c->tags as $tag) { if ($tag->tag == $value) { array_push($collection, $c->id); } } } // remove duplicates $collection = array_unique($collection); // get the tagged ones $citations->whereIn('id', $collection); } // end if tags if ($filter == "sort" && $value != "") { $clause = explode(" ", $value); $citations->order($clause[0], $clause[1]); } } // end foreach filters as filter return array('citations' => $citations, 'filters' => $filters); } else { return array('citations' => $citations, 'filters' => array()); } }
/** * Save a type * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); //get format $format = Request::getVar('citationFormat', array()); // create or update custom format $model = CitationFormat::oneOrNew($format['id']); if ($model->style == 'Hub Custom' || $model->isNew() === true) { $model->set(array('style' => 'Hub Custom', 'format' => \Hubzero\Utility\Sanitize::clean($format['format']))); } else { $model->set(array('format' => \Hubzero\Utility\Sanitize::clean($format['format']))); } if (!$model->save()) { // redirect with error message App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('CITATION_FORMAT_NOT_SAVED'), 'error'); } // successfully set the default value, redirect App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('CITATION_FORMAT_SAVED') . ' ' . $model->style); }
/** * Save block content * * @return string HTML */ public function save($manifest = NULL, $blockId = 0, $pub = NULL, $actor = 0, $elementId = 0) { // Set block manifest if ($this->_manifest === NULL) { $this->_manifest = $manifest ? $manifest : self::getManifest(); } // Make sure changes are allowed if ($this->_parent->checkFreeze($this->_manifest->params, $pub)) { return false; } // Load publication version $row = new \Components\Publications\Tables\Version($this->_parent->_db); if (!$row->load($pub->version_id)) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_VERSION_NOT_FOUND')); return false; } $originalType = $row->license_type; $originalText = $row->license_text; // Load license class $objL = new \Components\Publications\Tables\License($this->_parent->_db); // Incoming - license screen agreements $license = Request::getInt('license', 0, 'post'); $text = \Hubzero\Utility\Sanitize::clean(Request::getVar('license_text', '', 'post')); $agree = Request::getInt('agree', 0, 'post'); $custom = Request::getVar('substitute', array(), 'request', 'array'); if ($license) { if (!$objL->load($license)) { $this->setError(Lang::txt('There was a problem saving license selection')); return false; } if ($objL->agreement == 1 && !$agree) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_LICENSE_NEED_AGREEMENT')); return false; } elseif ($objL->customizable == 1 && !$text) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_LICENSE_NEED_TEXT')); return false; } $row->license_type = $license; $text = preg_replace("/\r/", '', $text); $row->license_text = $text; // Pre-defined license text if ($objL->text && $objL->customizable == 0) { $row->license_text = $objL->text; // Do we have template items to replace? preg_match_all('/\\[([^\\]]*)\\]/', $objL->text, $substitutes); if (count($substitutes) > 1) { foreach ($substitutes[1] as $sub) { if (!isset($custom[$sub]) || !$custom[$sub]) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_LICENSE_NEED_CUSTOM')); return false; } else { $row->license_text = preg_replace('/\\[' . $sub . '\\]/', trim($custom[$sub]), $row->license_text); } } } } $row->store(); // Save agreement $row->saveParam($pub->version_id, 'licenseagreement', 1); // Save custom fields in version params foreach ($custom as $label => $value) { $row->saveParam($pub->version_id, 'licensecustom' . strtolower($label), trim($value)); } if ($license != $originalType || $text != $originalText) { $this->_parent->set('_update', 1); } // Check agreements return true; } // Incoming - selector screen $selections = Request::getVar('selecteditems', ''); $toAttach = explode(',', $selections); $i = 0; foreach ($toAttach as $license) { if (!trim($license)) { continue; } // Make sure license exists if ($objL->load($license)) { $row->license_type = $license; $i++; $row->store(); // Clear agreement if license is changed if ($originalType != $license) { // Save agreement $row->saveParam($pub->version_id, 'licenseagreement', 0); $this->_parent->set('_update', 1); } // Only one choice break; } } if ($i) { $this->set('_message', Lang::txt('License selection saved')); return true; } else { $this->setError(Lang::txt('There was a problem saving license selection')); return false; } }
/** * Static method for formatting results * * @param object $row Database row * @return string HTML */ public static function out($row) { $row->href = Route::url('index.php?option=com_answers&task=question&id=' . $row->id); $html = "\t" . '<li class="answer">' . "\n"; $html .= "\t\t" . '<p class="title"><a href="' . $row->href . '">' . strip_tags(stripslashes($row->title)) . '</a></p>' . "\n"; $html .= "\t\t" . '<p class="details">'; if ($row->state == 1) { $html .= Lang::txt('PLG_TAGS_ANSWERS_OPEN'); } else { $html .= Lang::txt('PLG_TAGS_ANSWERS_CLOSED'); } $html .= ' <span>|</span> ' . Lang::txt('PLG_TAGS_ANSWERS_RESPONSES') . ' ' . $row->rcount . '</p>' . "\n"; if ($row->ftext) { $html .= "\t\t" . \Hubzero\Utility\String::truncate(\Hubzero\Utility\Sanitize::clean(stripslashes($row->ftext)), 200) . "\n"; } $html .= "\t\t" . '<p class="href">' . Request::base() . ltrim($row->href, '/') . '</p>' . "\n"; $html .= "\t" . '</li>' . "\n"; return $html; }
/** * Save param * * @param string $param * @param string $value * * @return void */ public function saveParam($param = '', $value = '') { // Clean up incoming $param = \Hubzero\Utility\Sanitize::paranoid($param, array('-', '_')); $value = \Hubzero\Utility\Sanitize::clean($value); if (!$this->exists()) { return false; } if (!$param || !$value) { return false; } $this->version->saveParam($this->get('version_id'), trim($param), htmlentities($value)); return $value; }
/** * Generates RSS feed when called by URL * * @return void */ public function generateFeedTask() { // Get the approved posts $model = new Models\Posts(); $posts = $model->getPostsByStatus(1000, 0, 2); // Set the mime encoding for the document Document::setType('feed'); // Start a new feed object $doc = Document::instance(); $doc->title = Config::get('sitename') . ' ' . Lang::txt('COM_FEEDAGGREGATOR_AGGREGATED_FEED'); $doc->description = Lang::txt(Config::get('sitename') . ' ' . Lang::txt('COM_FEEDAGGREGATOR_AGGREGATED_FEED_SELECTED_READING')); $doc->copyright = Lang::txt(date("Y"), Config::get('sitename')); $doc->category = Lang::txt('COM_FEEDAGGREGATOR_EXTERNAL_CONTENT'); // Start outputing results if any found if (count($posts) > 0) { foreach ($posts as $post) { // Load individual item creator class $item = new \Hubzero\Document\Type\Feed\Item(); // sanitize ouput $item->title = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $post->title); $item->title = preg_replace("/&#?[a-z1-9]{2,8};/i", "", $post->title); $item->title = (string) strip_tags($item->title); $item->title = html_entity_decode($item->title); $item->title = Sanitize::clean($item->title); // encapsulate link in unparseable $item->link = '<![CDATA[' . $post->link . ']]>'; $item->date = date($post->created); // sanitize ouput $item->description = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $post->description); $item->description = preg_replace('/[^A-Za-z0-9 ]/', '', $item->description); $item->description = preg_replace("/&#?[a-z1-9]{2,8};/i", "", $post->description); $item->description = html_entity_decode($post->description); $item->description = Sanitize::html($post->description); $doc->addItem($item); } } // Output the feed echo $doc->render(); }
} $base = rtrim(Request::base(), '/'); $html = '<h3>' . $this->escape(stripslashes($name)) . ' <span>(' . Lang::txt('COM_TAGS_RESULTS_THROUGH_OF', $this->filters['start'] + 1, $ttl, $total) . ')</span></h3>' . "\n"; if ($this->results) { $html .= '<ol class="results">' . "\n"; foreach ($this->results as $row) { $obj = 'plgTags' . ucfirst($row->section); if (method_exists($obj, 'out')) { $html .= call_user_func(array($obj, 'out'), $row); } else { // @todo accomodate scope (aka) group citations if (strstr($row->href, 'index.php')) { $row->href = Route::url($row->href); } $html .= "\t" . '<li>' . "\n"; $html .= "\t\t" . '<p class="title"><a href="' . $row->href . '">' . \Hubzero\Utility\Sanitize::clean($row->title) . '</a></p>' . "\n"; if ($row->ftext) { $html .= "\t\t" . '<p>' . \Hubzero\Utility\String::truncate(strip_tags($row->ftext), 200) . "</p>\n"; } $html .= "\t\t" . '<p class="href">' . $base . $row->href . '</p>' . "\n"; $html .= "\t" . '</li>' . "\n"; } } $html .= '</ol>' . "\n"; } else { $html = '<p class="warning">' . Lang::txt('COM_TAGS_NO_RESULTS') . '</p>'; } echo $html; ?> </div><!-- / .container-block --> <?php
/** * Save an answer (reply to question) * * @return void */ public function saveaTask() { // Check for request forgeries Request::checkToken(); // Login required if (User::isGuest()) { $this->setError(Lang::txt('COM_ANSWERS_PLEASE_LOGIN')); return $this->loginTask(); } // Incoming $response = Request::getVar('response', array(), 'post', 'none', 2); // clean input array_walk($response, function (&$field, $key) { $field = \Hubzero\Utility\Sanitize::clean($field); }); // Initiate class and bind posted items to database fields $row = Response::oneOrNew($response['id'])->set($response); // Store new content if (!$row->save()) { App::abort(500, $row->getError()); } // Load the question $question = Question::oneOrFail($row->get('question_id')); // Build the "from" info $from = array('email' => Config::get('mailfrom'), 'name' => Config::get('sitename') . ' ' . Lang::txt('COM_ANSWERS_ANSWERS'), 'multipart' => md5(date('U'))); // Build the message subject $subject = Config::get('sitename') . ' ' . Lang::txt('COM_ANSWERS_ANSWERS') . ', ' . Lang::txt('COM_ANSWERS_QUESTION') . ' #' . $question->get('id') . ' ' . Lang::txt('COM_ANSWERS_RESPONSE'); $message = array(); // Plain text message $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'response_plaintext')); $eview->option = $this->_option; $eview->sitename = Config::get('sitename'); $eview->question = $question; $eview->row = $row; $eview->id = $response['question_id']; $eview->boundary = $from['multipart']; $message['plaintext'] = $eview->loadTemplate(false); $message['plaintext'] = str_replace("\n", "\r\n", $message['plaintext']); // HTML message $eview->setLayout('response_html'); $message['multipart'] = $eview->loadTemplate(); $message['multipart'] = str_replace("\n", "\r\n", $message['multipart']); // --- $authorid = $question->get('created_by'); $receivers = $this->recipients(); // Send the message if (!in_array($authorid, $receivers) && $question->get('email')) { // Flag to mask identity of anonymous question asker // MCRN Ticket #134 if ($question->get('anonymous') == '1') { $messageType = 'answers_reply_submitted_anonymous'; } else { $messageType = 'answers_reply_submitted'; } if (!Event::trigger('xmessage.onSendMessage', array($messageType, $subject, $message, $from, array($authorid), $this->_option))) { $this->setError(Lang::txt('COM_ANSWERS_MESSAGE_FAILED')); } } // Send the answers admins message if (!empty($receivers)) { if (!Event::trigger('xmessage.onSendMessage', array('new_answer_admin', $subject, $message, $from, $receivers, $this->_option))) { $this->setError(Lang::txt('COM_ANSWERS_MESSAGE_FAILED')); } } // Log activity $recipients = array($row->get('created_by')); if ($row->get('created_by') != $question->get('created_by')) { $recipients[] = $question->get('created_by'); } $recipients = $this->recipients($recipients); Event::trigger('system.logActivity', ['activity' => ['action' => $response['id'] ? 'updated' : 'created', 'scope' => 'question.answer', 'scope_id' => $row->get('id'), 'description' => Lang::txt('COM_ANSWERS_ACTIVITY_ANSWER_SUBMITTED', '<a href="' . Route::url($question->link() . '#a' . $row->get('id')) . '">' . $question->get('subject') . '</a>'), 'details' => array('title' => $question->get('title'), 'question_id' => $question->get('id'), 'url' => $question->link())], 'recipients' => $recipients]); // Redirect to the question App::redirect(Route::url($question->link()), Lang::txt('COM_ANSWERS_NOTICE_POSTED_THANKS'), 'success'); }
/** * Store changes to this offering * * @param boolean $check Perform data validation check? * @return boolean False if error, True on success */ public function store($check = true) { if (!$this->get('anonymous')) { $this->set('anonymous', 0); } $string = str_replace(array('&', '<', '>'), array('&', '<', '>'), $this->get('about')); $this->set('about', \Hubzero\Utility\Sanitize::clean($string)); if (!parent::store($check)) { return false; } return true; }
/** * Save history log * * @param integer $actor Actor user ID * @param integer $oldStatus Previous version state * @param integer $newStatus New version state * @param integer $curator Author or curator * @return boolean */ public function saveHistory($actor = 0, $oldStatus = 0, $newStatus = 0, $curator = 0) { if (empty($this->_pub)) { return false; } // Incoming $comment = Request::getVar('comment', '', 'post'); // Collect details $changelog = $this->getChangeLog($oldStatus, $newStatus, $curator); if (!$changelog) { return false; } $obj = new Tables\CurationHistory($this->_db); // Create new record $obj->publication_version_id = $this->_pub->version_id; $obj->created = Date::toSql(); $obj->created_by = $actor; $obj->changelog = $changelog; $obj->curator = $curator; $obj->newstatus = $newStatus; $obj->oldstatus = $oldStatus; $obj->comment = \Hubzero\Utility\Sanitize::clean(htmlspecialchars($comment)); if ($obj->store()) { return true; } return false; }
/** * Save an entry * * @return void */ public function saveTask() { // Check if they're logged in if (User::isGuest()) { $this->loginTask(); return; } Request::checkToken(); // get the posted vars $id = Request::getInt('id', 0, 'post'); $c = Request::getVar('fields', array(), 'post'); $c['id'] = $id; // clean vars foreach ($c as $key => $val) { if (!is_array($val)) { $val = html_entity_decode(urldecode($val)); $val = Sanitize::stripAll($val); $c[$key] = Sanitize::clean($val); } } // Bind incoming data to object $row = new Citation($this->database); if (!$row->bind($c)) { $this->setError($row->getError()); $this->editTask(); return; } // New entry so set the created date if (!$row->id) { $row->created = Date::toSql(); } if (!filter_var($row->url, FILTER_VALIDATE_URL)) { $row->url = null; } // Check content for missing required data if (!$row->check()) { $this->setError($row->getError()); $this->editTask(); return; } // Store new content if (!$row->store()) { $this->setError($row->getError()); $this->editTask(); return; } // Incoming associations $arr = Request::getVar('assocs', array(), 'post'); $ignored = array(); foreach ($arr as $a) { $a = array_map('trim', $a); // Initiate extended database class $assoc = new Association($this->database); //check to see if we should delete if (isset($a['id']) && $a['tbl'] == '' && $a['oid'] == '') { // Delete the row if (!$assoc->delete($a['id'])) { $this->setError($assoc->getError()); $this->editTask(); return; } } else { if ($a['tbl'] != '' || $a['oid'] != '') { $a['cid'] = $row->id; // bind the data if (!$assoc->bind($a)) { $this->setError($assoc->getError()); $this->editTask(); return; } // Check content if (!$assoc->check()) { $this->setError($assoc->getError()); $this->editTask(); return; } // Store new content if (!$assoc->store()) { $this->setError($assoc->getError()); $this->editTask(); return; } } } } //check if we are allowing tags if ($this->config->get('citation_allow_tags', 'no') == 'yes') { $tags = trim(Request::getVar('tags', '', 'post')); $ct1 = new Tags($row->id); $ct1->setTags($tags, User::get('id'), 0, 1, ''); } //check if we are allowing badges if ($this->config->get('citation_allow_badges', 'no') == 'yes') { $badges = trim(Request::getVar('badges', '', 'post')); $ct2 = new Tags($row->id); $ct2->setTags($badges, User::get('id'), 0, 1, 'badge'); } // Redirect $task = '&task=browse'; if ($this->config->get('citation_single_view', 1)) { $task = '&task=view&id=' . $row->id; } App::redirect(Route::url('index.php?option=' . $this->_option . $task), Lang::txt('COM_CITATIONS_CITATION_SAVED')); }
/** * Saves changes to a store item * * @return void */ public function saveTask() { // Check for request forgeries Request::checkToken(); // Incoming $id = Request::getInt('id', 0); $_POST = array_map('trim', $_POST); // initiate extended database class $row = new Store($this->database); if (!$row->bind($_POST)) { throw new Exception($row->getError(), 500); } // code cleaner $row->description = Sanitize::clean($row->description); if (!$id) { $row->created = $row->created ? $row->created : Date::toSql(); } $sizes = $_POST['sizes'] ? $_POST['sizes'] : ''; $sizes = str_replace(' ', '', $sizes); $sizes = preg_split('#,#', $sizes); $sizes_cl = ''; foreach ($sizes as $s) { if (trim($s) != '') { $sizes_cl .= $s; $sizes_cl .= $s == end($sizes) ? '' : ', '; } } $row->title = htmlspecialchars(stripslashes($row->title)); $row->params = $sizes_cl ? 'size=' . $sizes_cl : ''; $row->published = isset($_POST['published']) ? 1 : 0; $row->available = isset($_POST['available']) ? 1 : 0; $row->featured = isset($_POST['featured']) ? 1 : 0; $row->type = $_POST['category'] == 'service' ? 2 : 1; // check content if (!$row->check()) { throw new Exception($row->getError(), 500); } // store new content if (!$row->store()) { throw new Exception($row->getError(), 500); } App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_STORE_MSG_SAVED')); }
/** * Save a reply * * @return void */ private function savereply() { // Check for request forgeries Request::checkToken(); // Is the user logged in? if (User::isGuest()) { $this->setError(Lang::txt('PLG_PUBLICATIONS_REVIEWS_LOGIN_NOTICE')); return; } $publication =& $this->publication; // Trim and addslashes all posted items $comment = Request::getVar('comment', array(), 'post', 'none', 2); if (!$publication->exists()) { // Cannot proceed $this->setError(Lang::txt('PLG_PUBLICATIONS_REVIEWS_COMMENT_ERROR_NO_REFERENCE_ID')); return; } $database = App::get('db'); $row = \Hubzero\Item\Comment::blank()->set($comment); $message = $row->id ? Lang::txt('PLG_PUBLICATIONS_REVIEWS_EDITS_SAVED') : Lang::txt('PLG_PUBLICATIONS_REVIEWS_COMMENT_POSTED'); // Perform some text cleaning, etc. $row->set('content', \Hubzero\Utility\Sanitize::clean($row->get('content'))); $row->set('anonymous', $row->get('anonymous') ? $row->get('anonymous') : 0); $row->set('state', $row->get('id') ? $row->get('state') : 0); // Save the data if (!$row->save()) { $this->setError($row->getError()); return; } // Redirect App::redirect(Route::url($publication->link('reviews')), $message); }
/** * Save block * * @return string HTML */ public function save($manifest = NULL, $blockId = 0, $pub = NULL, $actor = 0, $elementId = 0) { // Set block manifest if ($this->_manifest === NULL) { $this->_manifest = $manifest ? $manifest : self::getManifest(); } // Make sure changes are allowed if ($this->_parent->checkFreeze($this->_manifest->params, $pub)) { return false; } // Load publication version $row = new \Components\Publications\Tables\Version($this->_parent->_db); if (!$row->load($pub->version_id)) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_PUBLICATION_VERSION_NOT_FOUND')); return false; } // Track changes $changed = 0; $missed = 0; $collapse = $this->_manifest->params->collapse_elements == 0 ? 0 : 1; // Incoming $nbtags = Request::getVar('nbtag', array(), 'request', 'array'); // Parse metadata $data = array(); preg_match_all("#<nb:(.*?)>(.*?)</nb:(.*?)>#s", $pub->metadata, $matches, PREG_SET_ORDER); if (count($matches) > 0) { foreach ($matches as $match) { $data[$match[1]] = \Components\Publications\Helpers\Html::_txtUnpee($match[2]); } } // Save each element foreach ($this->_manifest->elements as $id => $element) { // Are we saving just one element? if ($elementId && $id != $elementId && $collapse) { continue; } $field = $element->params->field; $aliasmap = $element->params->aliasmap; $input = $element->params->input; $required = $element->params->required; if ($field == 'metadata') { $value = isset($nbtags[$aliasmap]) ? trim(stripslashes($nbtags[$aliasmap])) : NULL; if (!$value && $required) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_ERROR_MISSING_REQUIRED')); } else { if ($value && !isset($data[$aliasmap]) || isset($data[$aliasmap]) && $data[$aliasmap] != $value) { $changed++; } // Replace data $data[$aliasmap] = $value; // Save all in one field $tagCollect = ''; foreach ($data as $tagname => $tagcontent) { $tagCollect .= "\n" . '<nb:' . $tagname . '>' . $tagcontent . '</nb:' . $tagname . '>' . "\n"; } $row->metadata = $tagCollect; } } else { $value = trim(Request::getVar($field, '', 'post', 'none', 2)); $value = $input == 'editor' ? stripslashes($value) : \Hubzero\Utility\Sanitize::clean($value); if (!$value && $required) { $missed++; } if ($row->{$field} != $value) { $lastRecord = $pub->_curationModel->getLastUpdate($id, $this->_name, $blockId); $changed++; // Record update time $data = new stdClass(); $data->updated = Date::toSql(); $data->updated_by = $actor; // Unmark as skipped if ($lastRecord && $lastRecord->review_status == 3) { $data->review_status = 0; $data->update = ''; } if ($value) { $data->update = ''; // remove dispute message if requirement satisfied } $pub->_curationModel->saveUpdate($data, $id, $this->_name, $pub, $blockId); } $row->{$field} = $value; } } // Update modified info if ($changed) { $row->modified = Date::toSql(); $row->modified_by = $actor; $this->_parent->set('_update', 1); } // Report error if ($missed && $collapse == 0) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_ERROR_MISSING_REQUIRED')); } // Save if (!$row->store()) { $this->setError(Lang::txt('PLG_PROJECTS_PUBLICATIONS_ERROR_SAVE_PUBLICATION')); return false; } // Set success message $this->_parent->set('_message', $this->get('_message')); return true; }