Example #1
0
 /**
  * Short description for 'getToolVersions'
  *
  * Long description (if any) ...
  *
  * @param      string $toolid Parameter description (if any) ...
  * @param      array &$versions Parameter description (if any) ...
  * @param      string $toolname Parameter description (if any) ...
  * @param      integer $exclude_dev Parameter description (if any) ...
  * @return     array Return description (if any) ...
  */
 public function getToolVersions($toolid, &$versions, $toolname = '', $exclude_dev = 0)
 {
     $objA = new \Components\Tools\Tables\Author($this->_db);
     $query = "SELECT v.*, d.* ";
     $query .= "FROM #__tool_version as v LEFT JOIN #__doi_mapping as d ON d.alias = v.toolname AND d.local_revision=v.revision ";
     if ($toolid) {
         $query .= "WHERE v.toolid = " . $this->_db->quote($toolid) . " ";
     } else {
         if ($toolname) {
             $query .= "WHERE v.toolname = " . $this->_db->quote($toolname) . " ";
         }
     }
     if (($toolname or $toolid) && $exclude_dev) {
         $query .= "AND v.state != '3'";
     }
     $query .= " ORDER BY v.state DESC, v.revision DESC";
     $this->_db->setQuery($query);
     $versions = $this->_db->loadObjectList();
     if ($versions) {
         require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'models' . DS . 'tool.php';
         foreach ($versions as $version) {
             // get list of authors
             if ($version->state != 3) {
                 $version->authors = $objA->getToolAuthors($version->id);
             } else {
                 $rid = \Components\Tools\Models\Tool::getResourceId($version->toolid);
                 $version->authors = $objA->getToolAuthors('dev', $rid);
             }
         }
     }
     return $versions;
 }
Example #2
0
 /**
  * Retrieves a user's questions
  *
  * @param   string  $kind       The kind of results to retrieve
  * @param   array   $interests  Array of tags
  * @return  array   Database results
  */
 private function _getQuestions($kind = 'open', $interests = array())
 {
     // Get some classes we need
     require_once Component::path('com_answers') . DS . 'models' . DS . 'question.php';
     require_once Component::path('com_answers') . DS . 'helpers' . DS . 'economy.php';
     $limit = intval($this->params->get('limit', 10));
     $tags = null;
     $records = \Components\Answers\Models\Question::all()->including(['responses', function ($response) {
         $response->select('id')->select('question_id');
     }])->whereEquals('state', 0);
     if ($kind == 'mine') {
         $records->whereEquals('created_by', User::get('id'));
     }
     if ($kind == 'interest') {
         $tags = count($interests) <= 0 ? $this->_getInterests() : $interests;
     }
     if ($kind == 'assigned') {
         require_once Component::path('com_tools') . DS . 'tables' . DS . 'author.php';
         $database = \App::get('db');
         $TA = new \Components\Tools\Tables\Author($database);
         $tools = $TA->getToolContributions(User::get('id'));
         if ($tools) {
             foreach ($tools as $tool) {
                 $tags .= 'tool' . $tool->toolname . ',';
             }
             $tags = rtrim($tags, ',');
         }
     }
     if ($tags) {
         $cloud = new \Components\Answers\Models\Tags();
         $tags = $cloud->parse($tags);
         $records->select('#__answers_questions.*')->join('#__tags_object', '#__tags_object.objectid', '#__answers_questions.id')->join('#__tags', '#__tags.id', '#__tags_object.tagid')->whereEquals('#__tags_object.tbl', 'answers')->whereIn('#__tags.tag', $tags);
     }
     $data = $records->limit($limit)->ordered()->rows();
     $results = array();
     foreach ($data as $datum) {
         $datum->set('rcount', $datum->responses->count());
         $results[] = $datum;
     }
     if ($this->banking && $results) {
         $database = \App::get('db');
         $AE = new \Components\Answers\Helpers\Economy($database);
         $awards = array();
         foreach ($results as $result) {
             // Calculate max award
             $result->set('marketvalue', round($AE->calculate_marketvalue($result->get('id'), 'maxaward')));
             $result->set('maxaward', round(2 * ($result->get('marketvalue', 0) / 3)));
             if ($kind != 'mine') {
                 $result->set('maxaward', $result->get('maxaward') + $result->get('reward'));
             }
             $awards[] = $result->get('maxaward', 0);
         }
         // re-sort by max reponses
         array_multisort($awards, SORT_DESC, $results);
     }
     return $results;
 }
Example #3
0
 /**
  * Display forms for editing/creating a reosurce
  *
  * @return     void
  */
 public function displayTask()
 {
     // Incoming
     $alias = Request::getVar('app', '');
     $version = Request::getVar('editversion', 'dev');
     $step = Request::getInt('step', 1);
     // Load the tool
     $obj = new \Components\Tools\Tables\Tool($this->database);
     $this->_toolid = $obj->getToolId($alias);
     if (!$this->_toolid) {
         App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=pipeline'));
         return;
     }
     // make sure user is authorized to go further
     if (!$this->_checkAccess($this->_toolid)) {
         App::abort(403, Lang::txt('COM_TOOLS_ALERTNOTAUTH'));
         return;
     }
     $nextstep = $step + 1;
     // get tool version (dev or current) information
     $obj->getToolStatus($this->_toolid, $this->_option, $status, $version);
     // get resource information
     $row = new \Components\Resources\Tables\Resource($this->database);
     $row->loadAlias($alias);
     $row->alias = $row->alias ? $row->alias : $alias;
     if (!$status['fulltxt']) {
         $status['fulltxt'] = $row->fulltxt;
     }
     // process first step
     if ($nextstep == 3 && (isset($_POST['nbtag']) || isset($_POST['fulltxt']))) {
         if (!isset($_POST['fulltxt']) || !trim($_POST['fulltxt'])) {
             $this->setError(Lang::txt('COM_TOOLS_REQUIRED_FIELD_CHECK', 'Abstract'));
             $step = 1;
             $nextstep--;
         }
         $hztv = \Components\Tools\Helpers\Version::getToolRevision($this->_toolid, $version);
         $objV = new \Components\Tools\Tables\Version($this->database);
         if (!$objV->bind($_POST)) {
             $this->setError($objV->getError());
             return;
         }
         $body = $this->txtClean($_POST['fulltxt']);
         if (preg_match("/([\\<])([^\\>]{1,})*([\\>])/i", $body)) {
             // Do nothing
             $status['fulltxt'] = trim(stripslashes($body));
         } else {
             // Wiki format will be used
             $status['fulltxt'] = Request::getVar('fulltxt', $status['fulltxt'], 'post');
         }
         // Get custom areas, add wrapper tags, and compile into fulltxt
         $type = new \Components\Resources\Tables\Type($this->database);
         $type->load($row->type);
         include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'models' . DS . 'elements.php';
         $elements = new \Components\Resources\Models\Elements(array(), $type->customFields);
         $schema = $elements->getSchema();
         $fields = array();
         foreach ($schema->fields as $field) {
             $fields[$field->name] = $field;
         }
         $nbtag = Request::getVar('nbtag', array());
         $found = array();
         foreach ($nbtag as $tagname => $tagcontent) {
             $f = '';
             $status['fulltxt'] .= "\n" . '<nb:' . $tagname . '>';
             if (is_array($tagcontent)) {
                 $c = count($tagcontent);
                 $num = 0;
                 foreach ($tagcontent as $key => $val) {
                     if (trim($val)) {
                         $num++;
                     }
                     $status['fulltxt'] .= '<' . $key . '>' . trim($val) . '</' . $key . '>';
                 }
                 if ($c == $num) {
                     $f = 'found';
                 }
             } else {
                 $f = trim($tagcontent);
                 if ($f) {
                     $status['fulltxt'] .= trim($tagcontent);
                 }
             }
             $status['fulltxt'] .= '</nb:' . $tagname . '>' . "\n";
             if (!$f && isset($fields[$tagname]) && $fields[$tagname]->required) {
                 $this->setError(Lang::txt('COM_TOOLS_REQUIRED_FIELD_CHECK', $fields[$tagname]->label));
             }
             $found[] = $tagname;
         }
         foreach ($fields as $field) {
             if (!in_array($field->name, $found) && $field->required) {
                 $found[] = $field->name;
                 $this->setError(Lang::txt('COM_TOOLS_REQUIRED_FIELD_CHECK', $field->label));
             }
         }
         $hztv->fulltxt = $objV->fulltxt = $status['fulltxt'];
         $hztv->description = $objV->description = \Hubzero\Utility\String::truncate(Request::getVar('description', $status['description'], 'post'), 500);
         $hztv->title = $objV->title = \Hubzero\Utility\String::truncate(preg_replace('/\\s+/', ' ', Request::getVar('title', $status['title'], 'post')), 500);
         if (!$hztv->update()) {
             throw new Exception(Lang::txt('COM_TOOLS_ERROR_UPDATING_TOOL'), 500);
         } else {
             // get updated tool status
             $obj->getToolStatus($this->_toolid, $this->_option, $status, $version);
         }
         if ($version == 'dev') {
             // update resource page
             $this->updatePage($row->id, $status);
         }
     }
     // Group access
     //$accesses = array('Public', 'Registered', 'Special', 'Protected', 'Private');
     //$lists = array();
     //$lists['access'] = \Components\Tools\Helpers\Html::selectAccess($accesses, $row->access);
     //$groups = \Hubzero\User\Helper::getGroups(User::get('id'), 'members');
     // get authors
     $objA = new \Components\Tools\Tables\Author($this->database);
     $authors = $version == 'current' ? $objA->getToolAuthors($version, $row->id, $status['toolname']) : array();
     // Tags
     $tags = Request::getVar('tags', '', 'post');
     $tagfa = Request::getVar('tagfa', '', 'post');
     // Get any HUB focus areas
     // These are used where any resource is required to have one of these tags
     $tconfig = Component::params('com_tags');
     $fa1 = $tconfig->get('focus_area_01');
     $fa2 = $tconfig->get('focus_area_02');
     $fa3 = $tconfig->get('focus_area_03');
     $fa4 = $tconfig->get('focus_area_04');
     $fa5 = $tconfig->get('focus_area_05');
     $fa6 = $tconfig->get('focus_area_06');
     $fa7 = $tconfig->get('focus_area_07');
     $fa8 = $tconfig->get('focus_area_08');
     $fa9 = $tconfig->get('focus_area_09');
     $fa10 = $tconfig->get('focus_area_10');
     // Instantiate our tag object
     $tagcloud = new \Components\Resources\Helpers\Tags($row->id);
     // Normalize the focus areas
     $tagfa1 = $tagcloud->normalize($fa1);
     $tagfa2 = $tagcloud->normalize($fa2);
     $tagfa3 = $tagcloud->normalize($fa3);
     $tagfa4 = $tagcloud->normalize($fa4);
     $tagfa5 = $tagcloud->normalize($fa5);
     $tagfa6 = $tagcloud->normalize($fa6);
     $tagfa7 = $tagcloud->normalize($fa7);
     $tagfa8 = $tagcloud->normalize($fa8);
     $tagfa9 = $tagcloud->normalize($fa9);
     $tagfa10 = $tagcloud->normalize($fa10);
     // process new tags
     if ($tags or $tagfa) {
         $newtags = '';
         if ($tagfa) {
             $newtags = $tagfa . ', ';
         }
         if ($tags) {
             $newtags .= $tags;
         }
         $tagcloud->setTags($newtags, User::get('id'));
     }
     // Get all the tags on this resource
     $tags_men = $tagcloud->tags();
     $mytagarray = array();
     $fas = array($tagfa1, $tagfa2, $tagfa3, $tagfa4, $tagfa5, $tagfa6, $tagfa7, $tagfa8, $tagfa9, $tagfa10);
     $fats = array();
     if ($fa1) {
         $fats[$fa1] = $tagfa1;
     }
     if ($fa2) {
         $fats[$fa2] = $tagfa2;
     }
     if ($fa3) {
         $fats[$fa3] = $tagfa3;
     }
     if ($fa4) {
         $fats[$fa4] = $tagfa4;
     }
     if ($fa5) {
         $fats[$fa5] = $tagfa5;
     }
     if ($fa6) {
         $fats[$fa6] = $tagfa6;
     }
     if ($fa7) {
         $fats[$fa7] = $tagfa7;
     }
     if ($fa8) {
         $fats[$fa8] = $tagfa8;
     }
     if ($fa9) {
         $fats[$fa9] = $tagfa9;
     }
     if ($fa10) {
         $fats[$fa10] = $tagfa10;
     }
     // Loop through all the tags and pull out the focus areas - those will be displayed differently
     foreach ($tags_men as $tag_men) {
         if (in_array($tag_men->get('tag'), $fas)) {
             $tagfa = $tag_men->get('tag');
         } else {
             $mytagarray[] = $tag_men->get('raw_tag');
         }
     }
     $tags = implode(', ', $mytagarray);
     // Set the document title
     $this->view->title = Lang::txt(strtoupper($this->_option)) . ': ' . Lang::txt('COM_TOOLS_EDIT_TOOL_PAGE') . ' (' . $status['toolname'] . ')';
     Document::setTitle($this->view->title);
     // Set the document pathway (breadcrumbs)
     if (Pathway::count() <= 0) {
         Pathway::append(Lang::txt(strtoupper($this->_name)), 'index.php?option=' . $this->_option);
     }
     if (Pathway::count() <= 1) {
         Pathway::append(Lang::txt('COM_TOOLS_STATUS_FOR', $status['toolname']), 'index.php?option=' . $this->_option . '&controller=pipeline&task=status&app=' . $alias);
         Pathway::append(Lang::txt('COM_TOOLS_EDIT_TOOL_PAGE'), 'index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&app=' . $alias . '&task=start&step=1');
     }
     $this->view->row = $row;
     $this->view->step = $step;
     $this->view->version = $version;
     $this->view->status = $status;
     $this->view->tags = $tags;
     $this->view->tagfa = $tagfa;
     $this->view->fats = $fats;
     $this->view->authors = $authors;
     // Pass error messages to the view
     foreach ($this->getErrors() as $error) {
         $this->view->setError($error);
     }
     // Output HTML
     $this->view->display();
 }
Example #4
0
 /**
  * Save a question and redirect to the main listing when done
  *
  * @return     void
  */
 private function _save()
 {
     // Login required
     if (User::isGuest()) {
         return $this->_browse();
     }
     // Check for request forgeries
     Request::checkToken();
     Lang::load('com_answers');
     // Incoming
     $tags = Request::getVar('tags', '');
     $funds = Request::getInt('funds', 0);
     $reward = Request::getInt('reward', 0);
     // If offering a reward, do some checks
     if ($reward) {
         // Is it an actual number?
         if (!is_numeric($reward)) {
             App::abort(500, Lang::txt('COM_ANSWERS_REWARD_MUST_BE_NUMERIC'));
             return;
         }
         // Are they offering more than they can afford?
         if ($reward > $funds) {
             App::abort(500, Lang::txt('COM_ANSWERS_INSUFFICIENT_FUNDS'));
             return;
         }
     }
     // Initiate class and bind posted items to database fields
     $fields = Request::getVar('question', array(), 'post', 'none', 2);
     $row = new \Components\Answers\Models\Question($fields['id']);
     if (!$row->bind($fields)) {
         $this->setError($row->getError());
         return $this->_new($row);
     }
     if ($reward && $this->banking) {
         $row->set('reward', 1);
     }
     // Ensure the user added a tag
     /*
     if (!$tags)
     {
     	$this->setError(Lang::txt('COM_ANSWERS_QUESTION_MUST_HAVE_TAG'));
     	return $this->_new($row);
     }
     */
     // Store new content
     if (!$row->store(true)) {
         $row->set('tags', $tags);
         $this->setError($row->getError());
         return $this->_new($row);
     }
     // Hold the reward for this question if we're banking
     if ($reward && $this->banking) {
         $BTL = new \Hubzero\Bank\Teller($this->database, User::get('id'));
         $BTL->hold($reward, Lang::txt('COM_ANSWERS_HOLD_REWARD_FOR_BEST_ANSWER'), 'answers', $row->get('id'));
     }
     // Add the tags
     $row->tag($tags);
     // Add the tag to link to the resource
     $tag = $this->model->isTool() ? 'tool:' . $this->model->resource->alias : 'resource:' . $this->model->resource->id;
     $row->addTag($tag, User::get('id'), $this->model->isTool() ? 0 : 1);
     // Get users who need to be notified on every question
     $config = Component::params('com_answers');
     $apu = $config->get('notify_users', '');
     $apu = explode(',', $apu);
     $apu = array_map('trim', $apu);
     $receivers = array();
     // Get tool contributors if question is about a tool
     if ($tags) {
         $tags = explode(',', $tags);
         if (count($tags) > 0) {
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'author.php';
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'version.php';
             $TA = new \Components\Tools\Tables\Author($this->database);
             $objV = new \Components\Tools\Tables\Version($this->database);
             if ($this->model->isTool()) {
                 $toolname = $this->model->resource->alias;
                 $rev = $objV->getCurrentVersionProperty($toolname, 'revision');
                 $authors = $TA->getToolAuthors('', 0, $toolname, $rev);
                 if (count($authors) > 0) {
                     foreach ($authors as $author) {
                         $receivers[] = $author->uidNumber;
                     }
                 }
             }
         }
     }
     if (!empty($apu)) {
         foreach ($apu as $u) {
             $user = User::getInstance($u);
             if ($user) {
                 $receivers[] = $user->get('id');
             }
         }
     }
     $receivers = array_unique($receivers);
     // Send the message
     if (!empty($receivers)) {
         // Send a message about the new question to authorized users (specified admins or related content authors)
         $from = array('email' => Config::get('mailfrom'), 'name' => Config::get('sitename') . ' ' . Lang::txt('COM_ANSWERS_ANSWERS'), 'multipart' => md5(date('U')));
         // Build the message subject
         $subject = Lang::txt('COM_ANSWERS_ANSWERS') . ', ' . Lang::txt('new question about content you author or manage');
         // Build the message
         $eview = new \Hubzero\Mail\View(array('base_path' => PATH_CORE . DS . 'components' . DS . 'com_answers' . DS . 'site', 'name' => 'emails', 'layout' => 'question_plaintext'));
         $eview->option = 'com_answers';
         $eview->sitename = Config::get('sitename');
         $eview->question = $row;
         $eview->id = $row->get('id', 0);
         $eview->boundary = $from['multipart'];
         $message['plaintext'] = $eview->loadTemplate(false);
         $message['plaintext'] = str_replace("\n", "\r\n", $message['plaintext']);
         // HTML message
         $eview->setLayout('question_html');
         $message['multipart'] = $eview->loadTemplate();
         $message['multipart'] = str_replace("\n", "\r\n", $message['multipart']);
         if (!Event::trigger('xmessage.onSendMessage', array('new_question_admin', $subject, $message, $from, $receivers, 'com_answers'))) {
             $this->setError(Lang::txt('COM_ANSWERS_MESSAGE_FAILED'));
         }
     }
     // Redirect to the question
     App::redirect(Route::url('index.php?option=' . $this->option . '&id=' . $this->model->resource->id . '&active=' . $this->_name));
 }
Example #5
0
 /**
  * Search entries
  *
  * @return  void
  */
 public function searchTask()
 {
     // Incoming
     $filters = array('limit' => Request::getInt('limit', Config::get('list_limit')), 'start' => Request::getInt('limitstart', 0), 'tag' => Request::getVar('tags', ''), 'search' => Request::getVar('q', ''), 'filterby' => Request::getWord('filterby', ''), 'sortby' => Request::getWord('sortby', 'date'), 'sort_Dir' => strtolower(Request::getWord('sortdir', 'desc')), 'area' => Request::getVar('area', ''));
     // Validate inputs
     $filters['tag'] = $filters['tag'] ? $filters['tag'] : Request::getVar('tag', '');
     if ($filters['filterby'] && !in_array($filters['filterby'], array('open', 'closed'))) {
         $filters['filterby'] = '';
     }
     if (!in_array($filters['sortby'], array('date', 'votes', 'rewards'))) {
         $filters['sortby'] = 'date';
     }
     if (!in_array($filters['sort_Dir'], array('desc', 'asc'))) {
         $filters['sort_Dir'] = 'desc';
     }
     if ($filters['area'] && !in_array($filters['area'], array('mine', 'assigned', 'interest'))) {
         $filters['area'] = '';
     }
     // Get questions of interest
     // @TODO: Remove reference to members. Add getTags() to user?
     if ($filters['area'] == 'interest') {
         require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'models' . DS . 'tags.php';
         // Get tags of interest
         $mt = new \Components\Members\Models\Tags(User::get('id'));
         $filters['tag'] = $mt->render('string');
     }
     // Get assigned questions
     // @TODO: Remove reference to tools. Turn into an event call?
     if ($filters['area'] == 'assigned') {
         require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'author.php';
         // What tools did this user contribute?
         $db = App::get('db');
         $TA = new \Components\Tools\Tables\Author($db);
         $tools = $TA->getToolContributions(User::get('id'));
         $mytooltags = array();
         if ($tools) {
             foreach ($tools as $tool) {
                 $mytooltags[] = 'tool' . $tool->toolname;
             }
         }
         $filters['tag'] = implode(',', $mytooltags);
     }
     $records = Question::all()->including(['responses', function ($response) {
         $response->select('id')->select('question_id')->where('state', '!=', Question::STATE_DELETED);
     }]);
     if ($filters['tag'] || $filters['area'] == 'interest' || $filters['area'] == 'assigned') {
         $cloud = new Tags();
         $tags = $cloud->parse($filters['tag']);
         $records->select('#__answers_questions.*')->join('#__tags_object', '#__tags_object.objectid', '#__answers_questions.id')->join('#__tags', '#__tags.id', '#__tags_object.tagid')->whereEquals('#__tags_object.tbl', 'answers')->whereIn('#__tags.tag', $tags);
     }
     if ($filters['search']) {
         $filters['search'] = strtolower((string) $filters['search']);
         $records->whereLike('subject', $filters['search'], 1)->orWhereLike('question', $filters['search'], 1)->resetDepth();
     }
     if ($filters['filterby'] == 'open') {
         $records->whereEquals('state', 0);
     }
     if ($filters['filterby'] == 'closed') {
         $records->whereEquals('state', 1);
     }
     if (!$filters['filterby'] || $filters['filterby'] == 'both') {
         $records->where('state', '<', Question::STATE_DELETED);
     }
     if ($filters['area'] == 'mine') {
         $records->whereEquals('created_by', User::get('id'));
     }
     switch ($filters['sortby']) {
         case 'rewards':
             $order = 'reward';
             break;
         case 'votes':
             $order = 'helpful';
             break;
         case 'date':
         default:
             $order = 'created';
             break;
     }
     $results = $records->order($order, $filters['sort_Dir'])->paginated()->rows();
     // Output HTML
     $this->view->setError($this->getErrors())->set('results', $results)->set('filters', $filters)->set('config', $this->config)->setLayout('search')->display();
 }
Example #6
0
 /**
  * Retrieves a user's questions
  *
  * @param   string  $kind       The kind of results to retrieve
  * @param   array   $interests  Array of tags
  * @return  array   Database results
  */
 private function _getQuestions($kind = 'open', $interests = array())
 {
     $database = \App::get('db');
     // Get some classes we need
     require_once Component::path('com_answers') . DS . 'models' . DS . 'question.php';
     require_once Component::path('com_answers') . DS . 'tables' . DS . 'response.php';
     require_once Component::path('com_answers') . DS . 'tables' . DS . 'log.php';
     require_once Component::path('com_answers') . DS . 'tables' . DS . 'questionslog.php';
     require_once Component::path('com_answers') . DS . 'helpers' . DS . 'economy.php';
     $aq = new \Components\Answers\Tables\Question($database);
     if ($this->banking) {
         $AE = new \Components\Answers\Helpers\Economy($database);
         $BT = new \Hubzero\Bank\Transaction($database);
     }
     $params =& $this->params;
     $moduleclass = $params->get('moduleclass');
     $limit = intval($params->get('limit', 10));
     $limit = $limit ? $limit : 10;
     $filters = array('limit' => $limit, 'start' => 0, 'tag' => '', 'filterby' => 'open', 'sortby' => 'date');
     switch ($kind) {
         case 'mine':
             $filters['mine'] = 1;
             $filters['sortby'] = 'responses';
             break;
         case 'assigned':
             $filters['mine'] = 0;
             require_once Component::path('com_tools') . DS . 'tables' . DS . 'author.php';
             $TA = new \Components\Tools\Tables\Author($database);
             $tools = $TA->getToolContributions(User::get('id'));
             if ($tools) {
                 foreach ($tools as $tool) {
                     $filters['tag'] .= 'tool' . $tool->toolname . ',';
                 }
             }
             if (!$filters['tag']) {
                 $filters['filterby'] = 'none';
             }
             break;
         case 'interest':
             $filters['mine'] = 0;
             $interests = count($interests) <= 0 ? $this->_getInterests() : $interests;
             $filters['filterby'] = !$interests ? 'none' : 'open';
             $filters['tag'] = $interests;
             break;
     }
     $results = $aq->getResults($filters);
     if ($this->banking && $results) {
         $awards = array();
         foreach ($results as $result) {
             // Calculate max award
             $result->marketvalue = round($AE->calculate_marketvalue($result->id, 'maxaward'));
             $result->maxaward = round(2 * ($result->marketvalue / 3));
             if ($kind != 'mine') {
                 $result->maxaward = $result->maxaward + $result->reward;
             }
             $awards[] = $result->maxaward ? $result->maxaward : 0;
         }
         // re-sort by max reponses
         array_multisort($awards, SORT_DESC, $results);
     }
     foreach ($results as $k => $result) {
         $results[$k] = new \Components\Answers\Models\Question($result);
     }
     return $results;
 }
Example #7
0
 /**
  * Temp function to issue new service DOIs for tool versions published previously
  *
  * @return  void
  */
 public function batchdoiTask()
 {
     $yearFormat = 'Y';
     //  Limit one-time batch size
     $limit = Request::getInt('limit', 2);
     // Store output
     $created = array();
     $failed = array();
     // Initiate extended database classes
     $resource = new \Components\Resources\Tables\Resource($this->database);
     $objDOI = new \Components\Resources\Tables\Doi($this->database);
     $objV = new \Components\Tools\Tables\Version($this->database);
     $objA = new \Components\Tools\Tables\Author($this->database);
     $live_site = rtrim(Request::base(), '/');
     $sitename = Config::get('sitename');
     // Get config
     $config = \Component::params($this->_option);
     // Get all tool publications without new DOI
     $this->database->setQuery("SELECT * FROM `#__doi_mapping` WHERE doi='' OR doi IS NULL ");
     $rows = $this->database->loadObjectList();
     if ($rows) {
         $i = 0;
         foreach ($rows as $row) {
             if ($limit && $i == $limit) {
                 // Output status message
                 if ($created) {
                     foreach ($created as $cr) {
                         echo '<p>' . $cr . '</p>';
                     }
                 }
                 echo '<p>' . Lang::txt('COM_TOOLS_REGISTERED_DOIS', count($created), count($failed)) . '</p>';
                 return;
             }
             // Skip entries with no resource information loaded / non-tool resources
             if (!$resource->load($row->rid) || !$row->alias) {
                 continue;
             }
             // Get version info
             $this->database->setQuery("SELECT * FROM `#__tool_version` WHERE toolname='" . $row->alias . "' AND revision='" . $row->local_revision . "' AND state!=3 LIMIT 1");
             $results = $this->database->loadObjectList();
             if ($results) {
                 $title = $results[0]->title ? $results[0]->title : $resource->title;
                 $pubyear = $results[0]->released ? trim(Date::of($results[0]->released)->toLocal($yearFormat)) : date('Y');
             } else {
                 // Skip if version not found
                 continue;
             }
             // Collect metadata
             $metadata = array();
             $metadata['targetURL'] = $live_site . '/resources/' . $row->rid . '/?rev=' . $row->local_revision;
             $metadata['title'] = htmlspecialchars($title);
             $metadata['pubYear'] = $pubyear;
             // Get authors
             $objA = new \Components\Tools\Tables\Author($this->database);
             $authors = $objA->getAuthorsDOI($row->rid);
             // Register DOI
             $doiSuccess = $objDOI->registerDOI($authors, $config, $metadata, $doierr);
             if ($doiSuccess) {
                 $this->database->setQuery("UPDATE `#__doi_mapping` SET doi='{$doiSuccess}' WHERE rid={$row->rid} AND local_revision={$row->local_revision}");
                 if (!$this->database->query()) {
                     $failed[] = $doiSuccess;
                 } else {
                     $created[] = $doiSuccess;
                 }
             } else {
                 print_r($doierr);
                 echo '<br />';
                 print_r($metadata);
                 echo '<br />';
             }
             $i++;
         }
     }
     // Output status message
     if ($created) {
         foreach ($created as $cr) {
             echo '<p>' . $cr . '</p>';
         }
     }
     echo '<p>' . Lang::txt('COM_TOOLS_REGISTERED_DOIS', count($created), count($failed)) . '</p>';
     return;
 }
Example #8
0
 /**
  * Publish a tool
  *
  * @return     void
  */
 public function publishTask()
 {
     // Set the layout (note: all the views for this controller use the same layout)
     $this->view->setLayout('display');
     // Create a Tool object
     $obj = new \Components\Tools\Tables\Tool($this->database);
     // Do we have an alias?
     if ($alias = Request::getVar('app', '')) {
         $this->_toolid = $obj->getToolId($alias);
     }
     // Do we have a tool ID
     if (!$this->_toolid) {
         App::abort(403, Lang::txt('COM_TOOLS_ERROR_TOOL_NOT_FOUND'));
         return;
     }
     // Get the tool status
     $obj->getToolStatus($this->_toolid, $this->_option, $status, 'dev');
     // Check for a status
     if (count($status) <= 0) {
         App::abort(500, Lang::txt('COM_TOOLS_ERR_CANNOT_RETRIEVE'));
         return;
     }
     $result = true;
     Log::debug("publish(): checkpoint 1:{$result}");
     // get config
     // Create a Tool Version object
     $objV = new \Components\Tools\Tables\Version($this->database);
     $objV->getToolVersions($this->_toolid, $tools, '', 1);
     // make checks
     if (!is_numeric($status['revision'])) {
         // bad format
         $result = false;
         $this->setError(Lang::txt('COM_TOOLS_ERR_MISSING_REVISION_OR_BAD_FORMAT'));
     } else {
         if (count($tools) > 0 && $status['revision']) {
             // check for duplicate revision
             foreach ($tools as $t) {
                 if ($t->revision == $status['revision']) {
                     $result = false;
                     $this->setError(Lang::txt('COM_TOOLS_ERR_REVISION_EXISTS') . ' ' . $status['revision']);
                 }
             }
             // check that revision number is greater than in previous version
             $currentrev = $objV->getCurrentVersionProperty($status['toolname'], 'revision');
             if ($currentrev && intval($currentrev) > intval($status['revision'])) {
                 $result = false;
                 $this->setError(Lang::txt('COM_TOOLS_ERR_REVISION_GREATER'));
             }
         }
     }
     // Log checkpoint
     Log::debug("publish(): checkpoint 2:{$result}, check revision");
     // check if version is valid
     if (!\Components\Tools\Models\Tool::validateVersion($status['version'], $error_v, $this->_toolid)) {
         $result = false;
         $this->setError($error_v);
     }
     // Log checkpoint
     Log::debug("publish(): checkpoint 3:{$result}, running finalize tool");
     // Run finalizetool
     if (!$this->getError()) {
         if ($this->_finalizeTool($out)) {
             $this->setMessage(Lang::txt('COM_TOOLS_Version finalized.'));
         } else {
             $this->setError($out);
             $result = false;
         }
     }
     Log::debug("publish(): checkpoint 4:{$result}, running doi stuff");
     // Register DOI handle
     if ($result && $this->config->get('new_doi', 0)) {
         include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'tables' . DS . 'doi.php';
         // Collect metadata
         $url = Request::base() . ltrim(Route::url('index.php?option=com_resources&id=' . $status['resourceid'] . '&rev=' . $status['revision']), DS);
         // Check if DOI exists for this revision
         $objDOI = new \Components\Resources\Tables\Doi($this->database);
         $bingo = $objDOI->getDoi($status['resourceid'], $status['revision'], '', 1);
         // DOI already exists for this revision
         if ($bingo) {
             $this->setError(Lang::txt('COM_TOOLS_ERR_DOI_ALREADY_EXISTS') . ': ' . $bingo);
         } else {
             // Get latest DOI label
             $latestdoi = $objDOI->getLatestDoi($status['resourceid']);
             $newlabel = $latestdoi ? intval($latestdoi) + 1 : 1;
             // Collect metadata
             $metadata = array('targetURL' => $url, 'title' => htmlspecialchars(stripslashes($status['title'])), 'version' => $status['version'], 'abstract' => htmlspecialchars(stripslashes($status['description'])));
             // Get authors
             $objA = new \Components\Tools\Tables\Author($this->database);
             $authors = $objA->getAuthorsDOI($status['resourceid']);
             // Register DOI
             $doiSuccess = $objDOI->registerDOI($authors, $this->config, $metadata, $doierr);
             // Save [new] DOI record
             if ($doiSuccess) {
                 if (!$objDOI->loadDOI($status['resourceid'], $status['revision'])) {
                     if ($objDOI->saveDOI($status['revision'], $newlabel, $status['resourceid'], $status['toolname'], 0, $doiSuccess)) {
                         $this->setMessage(Lang::txt('COM_TOOLS_SUCCESS_DOI_CREATED') . ' ' . $doiSuccess);
                     } else {
                         $this->setError(Lang::txt('COM_TOOLS_ERR_DOI_STORE_FAILED'));
                         $result = false;
                     }
                 } else {
                     $this->setError(Lang::txt('COM_TOOLS_DOI already exists: ') . $objDOI->doi);
                 }
             } else {
                 $this->setError(Lang::txt('COM_TOOLS_ERR_DOI_STORE_FAILED'));
                 $this->setError($doierr);
                 $result = false;
             }
         }
     }
     if ($result) {
         $invokedir = rtrim($this->config->get('invokescript_dir', DS . 'apps'), "\\/");
         $hzt = \Components\Tools\Models\Tool::getInstance($this->_toolid);
         $hztv_cur = $hzt->getCurrentVersion();
         $hztv_dev = $hzt->getDevelopmentVersion();
         Log::debug("publish(): checkpoint 6:{$result}, running database stuff");
         // create tool instance in the database
         $newtool = $status['toolname'] . '_r' . $status['revision'];
         // get version id
         $currentid = is_object($hztv_cur) ? $hztv_cur->id : null;
         $new = $currentid ? 0 : 1;
         $devid = $hztv_dev->id;
         $exportmap = array('@OPEN' => null, '@GROUP' => null, '@US' => 'us', '@PU' => 'pu', '@D1' => 'd1');
         $new_hztv = \Components\Tools\Models\Version::createInstance($status['toolname'], $newtool);
         $new_hztv->toolname = $status['toolname'];
         $new_hztv->instance = $newtool;
         $new_hztv->toolid = $this->_toolid;
         $new_hztv->state = 1;
         $new_hztv->title = $status['title'];
         $new_hztv->version = $status['version'];
         $new_hztv->revision = $status['revision'];
         $new_hztv->description = $status['description'];
         $new_hztv->toolaccess = $status['exec'];
         $new_hztv->codeaccess = $status['code'];
         $new_hztv->wikiaccess = $status['wiki'];
         $new_hztv->vnc_geometry = $status['vncGeometry'];
         $new_hztv->vnc_command = $invokedir . DS . $status['toolname'] . DS . 'r' . $status['revision'] . DS . 'middleware' . DS . 'invoke -T r' . $status['revision'];
         $new_hztv->mw = $status['mw'];
         $new_hztv->released = Date::toSql();
         $new_hztv->released_by = User::get('username');
         $new_hztv->license = $status['license'];
         $new_hztv->fulltxt = $status['fulltxt'];
         $new_hztv->exportControl = $exportmap[strtoupper($status['exec'])];
         $new_hztv->owner = $hztv_dev->owner;
         $new_hztv->member = $hztv_dev->member;
         $new_hztv->vnc_timeout = $hztv_dev->vnc_timeout;
         $new_hztv->hostreq = $hztv_dev->hostreq;
         $new_hztv->params = $status['params'];
         if (!$new_hztv->update()) {
             $this->setError(Lang::txt('COM_TOOLS_ERROR_UPDATING_INSTANCE'));
             $result = false;
         } else {
             $this->_setTracAccess($new_hztv->toolname, $new_hztv->codeaccess, $new_hztv->wikiaccess);
             // update tool entry
             $hzt = \Components\Tools\Models\Tool::getInstance($this->_toolid);
             $hzt->add('version', $new_hztv->instance);
             $hzt->update();
             if ($hzt->published != 1) {
                 $hzt->published = 1;
                 // save tool info
                 if (!$hzt->update()) {
                     $this->setError(Lang::txt('COM_TOOLS_ERROR_UPDATING_INSTANCE'));
                 } else {
                     $this->setMessage(Lang::txt('COM_TOOLS_NOTICE_TOOL_MARKED_PUBLISHED'));
                 }
             }
             // unpublish previous version
             if (!$new) {
                 if ($hzt->unpublishVersion($hztv_cur->instance)) {
                     $this->setMessage(Lang::txt('COM_TOOLS_NOTICE_UNPUBLISHED_PREV_VERSION_DB'));
                 } else {
                     $this->setError(Lang::txt('COM_TOOLS_ERR_FAILED_TO_UNPUBLISH_PREV_VERSION_DB'));
                 }
             }
             // get version id
             $currentid = $new_hztv->id;
             // save authors for this version
             $objA = new \Components\Tools\Tables\Author($this->database);
             if ($objA->saveAuthors($status['developers'], $currentid, $status['resourceid'], $status['revision'], $status['toolname'])) {
                 $this->setMessage(Lang::txt('COM_TOOLS_AUTHORS_SAVED'));
             } else {
                 $this->setError(Lang::txt('COM_TOOLS_ERROR_SAVING_AUTHORS', $currentid));
             }
             // transfer screenshots
             if ($devid && $currentid) {
                 include_once __DIR__ . DS . 'screenshots.php';
                 $screenshots = new Screenshots();
                 if ($screenshots->transfer($devid, $currentid, $status['resourceid'])) {
                     $this->setMessage(Lang::txt('COM_TOOLS_SCREENSHOTS_TRANSFERRED'));
                 } else {
                     $this->setError(Lang::txt('COM_TOOLS_ERROR_TRANSFERRING_SCREENSHOTS'));
                 }
             }
             include_once __DIR__ . DS . 'resource.php';
             $resource = new Resource();
             // update and publish resource page
             $resource->updatePage($status['resourceid'], $status, '1', $new);
         }
     }
     Log::debug("publish(): checkpoint 7:{$result}, gather output");
     // Set errors to view
     foreach ($this->getErrors() as $error) {
         $this->view->setError($error);
     }
     // Set messages to view
     $this->view->messages = $this->getMessages();
     // Output HTML
     if (!($no_html = Request::getInt('no_html', 0))) {
         App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=pipeline&task=status&app=' . $alias));
         return;
     }
     $this->view->display();
 }
Example #9
0
 /**
  * Save a question
  *
  * @return     void
  */
 public function saveqTask()
 {
     // Check for request forgeries
     Request::checkToken();
     // Login required
     if (User::isGuest()) {
         $this->setError(Lang::txt('COM_ANSWERS_PLEASE_LOGIN'));
         $this->loginTask();
         return;
     }
     if (!User::authorise('core.edit', $this->_option) && !User::authorise('core.create', $this->_option) && !User::authorise('core.manage', $this->_option)) {
         throw new Exception(Lang::txt('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
     }
     // Incoming
     $fields = Request::getVar('fields', array(), 'post', 'none', 2);
     $tags = Request::getVar('tags', '');
     if (!isset($fields['reward'])) {
         $fields['reward'] = 0;
     }
     // If offering a reward, do some checks
     if ($fields['reward']) {
         // Is it an actual number?
         if (!is_numeric($fields['reward'])) {
             throw new Exception(Lang::txt('COM_ANSWERS_REWARD_MUST_BE_NUMERIC'), 500);
         }
         // Are they offering more than they can afford?
         if ($fields['reward'] > $fields['funds']) {
             throw new Exception(Lang::txt('COM_ANSWERS_INSUFFICIENT_FUNDS'), 500);
         }
     }
     // clean input
     array_walk($fields, function (&$field, $key) {
         $field = \Hubzero\Utility\Sanitize::clean($field);
     });
     // Initiate class and bind posted items to database fields
     $row = new Question($fields['id']);
     if (!$row->bind($fields)) {
         throw new Exception($row->getError(), 500);
     }
     if ($fields['reward'] && $this->config->get('banking')) {
         $row->set('reward', 1);
     }
     // Store new content
     if (!Request::checkHoneypot()) {
         $this->setError(Lang::txt('JLIB_APPLICATION_ERROR_INVALID_CONTENT'));
         $this->newTask($row);
         return;
     }
     // Ensure the user added a tag
     if (!$tags) {
         $this->setError(Lang::txt('COM_ANSWERS_QUESTION_MUST_HAVE_TAG'));
         $this->newTask($row);
         return;
     }
     // We need to temporarily set this so the store() method
     // has access to the tags string to be able to run it
     // through spam checkers and validation.
     $row->set('tags', $tags);
     // Store new content
     if (!$row->store(true)) {
         Request::setVar('tag', $tags);
         $this->setError($row->getError());
         $this->newTask($row);
         return;
     }
     // Hold the reward for this question if we're banking
     if ($fields['reward'] && $this->config->get('banking')) {
         $BTL = new Teller($this->database, User::get('id'));
         $BTL->hold($fields['reward'], Lang::txt('COM_ANSWERS_HOLD_REWARD_FOR_BEST_ANSWER'), 'answers', $row->get('id'));
     }
     // Add the tags
     $row->tag($tags);
     // Get users who need to be notified on every question
     $apu = $this->config->get('notify_users', '');
     $apu = explode(',', $apu);
     $apu = array_map('trim', $apu);
     $receivers = array();
     // Get tool contributors if question is about a tool
     if ($tags) {
         $tags = preg_split("/[,;]/", $tags);
         if (count($tags) > 0) {
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'author.php';
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'version.php';
             $TA = new \Components\Tools\Tables\Author($this->database);
             $objV = new \Components\Tools\Tables\Version($this->database);
             foreach ($tags as $tag) {
                 if ($tag == '') {
                     continue;
                 }
                 if (preg_match('/tool:/', $tag)) {
                     $toolname = preg_replace('/tool:/', '', $tag);
                     if (trim($toolname)) {
                         $rev = $objV->getCurrentVersionProperty($toolname, 'revision');
                         $authors = $TA->getToolAuthors('', 0, $toolname, $rev);
                         if (count($authors) > 0) {
                             foreach ($authors as $author) {
                                 $receivers[] = $author->uidNumber;
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!empty($apu)) {
         foreach ($apu as $u) {
             $user = User::getInstance($u);
             if ($user) {
                 $receivers[] = $user->get('id');
             }
         }
     }
     $receivers = array_unique($receivers);
     // Send the message
     if (!empty($receivers)) {
         // Send a message about the new question to authorized users (specified admins or related content authors)
         $from = array('email' => Config::get('mailfrom'), 'name' => Config::get('sitename') . ' ' . Lang::txt('COM_ANSWERS_ANSWERS'), 'multipart' => md5(date('U')));
         // Build the message subject
         $subject = Lang::txt('COM_ANSWERS_ANSWERS') . ', ' . Lang::txt('new question about content you author or manage');
         $message = array();
         // Plain text message
         $eview = new \Hubzero\Mail\View(array('name' => 'emails', 'layout' => 'question_plaintext'));
         $eview->option = $this->_option;
         $eview->sitename = Config::get('sitename');
         $eview->question = $row;
         $eview->id = $row->get('id', 0);
         $eview->boundary = $from['multipart'];
         $message['plaintext'] = $eview->loadTemplate(false);
         $message['plaintext'] = str_replace("\n", "\r\n", $message['plaintext']);
         // HTML message
         $eview->setLayout('question_html');
         $message['multipart'] = $eview->loadTemplate();
         $message['multipart'] = str_replace("\n", "\r\n", $message['multipart']);
         if (!Event::trigger('xmessage.onSendMessage', array('new_question_admin', $subject, $message, $from, $receivers, $this->_option))) {
             $this->setError(Lang::txt('COM_ANSWERS_MESSAGE_FAILED'));
         }
     }
     // Redirect to the question
     App::redirect(Route::url('index.php?option=' . $this->_option . '&task=question&id=' . $row->get('id')), Lang::txt('COM_ANSWERS_NOTICE_QUESTION_POSTED_THANKS'));
 }