/**
  * Up
  **/
 public function up()
 {
     if (!$this->db->tableExists('#__tool_session_classes')) {
         $query = "CREATE TABLE `#__tool_session_classes` (\n\t\t\t\t  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\t\t  `alias` varchar(255) NOT NULL DEFAULT '',\n\t\t\t\t  `jobs` int(11) NOT NULL DEFAULT '0',\n\t\t\t\t  PRIMARY KEY (`id`),\n\t\t\t\t  UNIQUE KEY `uidx_alias` (`alias`)\n\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $this->db->setQuery($query);
         $this->db->query();
         $this->db->setQuery("INSERT INTO `#__tool_session_classes` (`alias`, `jobs`) VALUES ('default', 3)");
         $this->db->query();
     }
     if (!$this->db->tableExists('#__tool_session_class_groups')) {
         $query = "CREATE TABLE `#__tool_session_class_groups` (\n\t\t\t\t  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n\t\t\t\t  `class_id` int(11) unsigned NOT NULL DEFAULT '0',\n\t\t\t\t  `group_id` int(11) unsigned NOT NULL DEFAULT '0',\n\t\t\t\t  PRIMARY KEY (`id`),\n\t\t\t\t  KEY `idx_class_id` (`class_id`),\n\t\t\t\t  KEY `idx_group_id` (`group_id`)\n\t\t\t\t) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
         $this->db->setQuery($query);
         $this->db->query();
     }
     if ($this->db->tableExists('#__users_tool_preferences')) {
         if (!$this->db->tableHasField('#__users_tool_preferences', 'class_id')) {
             $query = "ALTER TABLE `#__users_tool_preferences` ADD COLUMN `class_id` int(11) NOT NULL DEFAULT 0";
             $this->db->setQuery($query);
             $this->db->query();
             $query = "ALTER TABLE `#__users_tool_preferences` ADD INDEX `idx_class_id` (`class_id`)";
             $this->db->setQuery($query);
             $this->db->query();
         }
         if (!$this->db->tableHasField('#__users_tool_preferences', 'jobs')) {
             $query = "ALTER TABLE `#__users_tool_preferences` ADD COLUMN `jobs` int(11) NOT NULL DEFAULT 0";
             $this->db->setQuery($query);
             $this->db->query();
         }
         // Create a preferences entry for anyone who has a non-default value for jobs allowed
         $query = "SELECT `uidNumber`, `jobsAllowed` FROM `#__xprofiles` WHERE `jobsAllowed`!=3 AND `uidNumber` > 0";
         $this->db->setQuery($query);
         if ($rows = $this->db->loadObjectList()) {
             include_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'preferences.php';
             foreach ($rows as $row) {
                 $preferences = new \Components\Tools\Tables\Preferences($this->db);
                 $preferences->loadByUser($row->uidNumber);
                 $preferences->user_id = $row->uidNumber;
                 $preferences->class_id = 0;
                 $preferences->jobs = $row->jobsAllowed ? $row->jobsAllowed : 10;
                 $preferences->store();
             }
         }
         if ($this->db->tableHasField('#__xprofiles', 'jobsAllowed')) {
             $query = "ALTER TABLE `#__xprofiles` DROP COLUMN `jobsAllowed`;";
             $this->db->setQuery($query);
             $this->db->query();
         }
     }
 }
Esempio n. 2
0
 /**
  * Invoke a tool session
  *
  * @return     void
  */
 public function invokeTask()
 {
     // Check that the user is logged in
     if (User::isGuest()) {
         $this->loginTask();
         return;
     }
     $params = Request::getString('params', '', 'default', JREQUEST_ALLOWRAW);
     if (!empty($params)) {
         $params_whitelist = explode(',', $this->config->get('params_whitelist', ''));
         $separator = "\r\n";
         $line = trim(strtok($params, $separator));
         $verified_params = array();
         while ($line !== false) {
             $re = "/\\s*(directory|file|int)\\s*(?:\\:|\\(\\s*(.*?)\\s*\\)\\s*:)\\s*(.*?)\\s*\$/";
             if (preg_match($re, $line, $matches) != false) {
                 $type = $matches[1];
                 $key = $matches[2];
                 $value = $matches[3];
                 if ($type == 'directory' || $type == 'file') {
                     // Replace ~/ prefix with user's home directory
                     if (strncmp($value, "~/", 2) === 0) {
                         $homeDirectory = rtrim(User::get('homeDirectory'), '/');
                         if (!isset($homeDirectory[0]) || $homeDirectory[0] !== '/') {
                             break;
                         }
                         $value = substr_replace($value, $homeDirectory, 0, 1);
                     }
                     // Fail if $value doesn't start with '/'
                     if ($value[0] != '/') {
                         break;
                     }
                     // Fail if unable to normalize $value
                     $value = $this->normalize_path($value, $type == 'file');
                     if ($value === false) {
                         break;
                     }
                     // Fail if $value contains a control charcater (0x00-0x1F) or an invalid utf-8 string
                     if (preg_match('/^[^\\x00-\\x1f]*$/u', $value) == 0) {
                         break;
                     }
                     // Fail if whitelist is empty
                     if (empty($params_whitelist)) {
                         break;
                     }
                     // Fail if $value isn't prefixed with a whitelisted directory
                     foreach ($params_whitelist as $wl) {
                         if (empty($wl)) {
                             continue;
                         }
                         $wl = rtrim(trim($wl), '/') . '/';
                         // make sure we compare against a full path element
                         if (strncmp($wl, $value, strlen($wl)) === 0) {
                             $match = $wl;
                             break;
                         }
                     }
                     if (!isset($match)) {
                         break;
                     }
                     // Add verified parameter to array
                     if ($key) {
                         $verified_params[] = $type . '(' . $key . '):' . $value;
                     } else {
                         $verified_params[] = $type . ':' . $value;
                     }
                 } else {
                     if ($type == 'int') {
                         // Fail if $value contains a control charcater (0x00-0x1F) or an invalid utf-8 string
                         if (preg_match('/^[^\\x00-\\x1f]*$/u', $value) == 0) {
                             break;
                         }
                         // Fail if $value not an integer
                         if (preg_match('/^[-+]?[0-9]+$/', $value) == 0) {
                             break;
                         }
                         // Add verified parameter to array
                         if ($key) {
                             $verified_params[] = $type . '(' . $key . '):' . $value;
                         } else {
                             $verified_params[] = $type . ':' . $value;
                         }
                     }
                 }
             } else {
                 if (!empty($line)) {
                     break;
                 }
             }
             $line = strtok($separator);
             // Get next line
         }
         if ($line !== false) {
             $this->badparamsTask($params);
             return;
         }
     }
     // Incoming
     $app = new stdClass();
     $app->name = trim(str_replace(':', '-', Request::getVar('app', '')));
     //$app->number  = 0;
     $app->version = Request::getVar('version', 'default');
     // Get the user's IP address
     $app->ip = Request::ip();
     // Make sure we have an app to invoke
     if (!$app->name) {
         App::redirect(Route::url($this->config->get('stopRedirect', 'index.php?option=com_members&task=myaccount')));
         return;
     }
     // Get the parent toolname (appname without any revision number "_r423")
     include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'version.php';
     $tv = new \Components\Tools\Tables\Version($this->database);
     switch ($app->version) {
         case 1:
         case 'current':
         case 'default':
             $app->name = $tv->getCurrentVersionProperty($app->name, 'instance');
             break;
         case 'test':
         case 'dev':
             $app->name .= '_dev';
             break;
         default:
             $app->name .= '_r' . $app->version;
             break;
     }
     $app->toolname = $app->name;
     if ($parent = $tv->getToolname($app->name)) {
         $app->toolname = $parent;
     }
     // Check of the toolname has a revision indicator
     $r = substr(strrchr($app->name, '_'), 1);
     if (substr($r, 0, 1) != 'r' && substr($r, 0, 3) != 'dev') {
         $r = '';
     }
     // No version passed and no revision
     if ((!$app->version || $app->version == 'default' || $app->version == 'current') && !$r) {
         // Get the latest version
         $app->version = $tv->getCurrentVersionProperty($app->toolname, 'revision');
         $app->name = $app->toolname . '_r' . $app->version;
     }
     // Get the caption/session title
     $tv->loadFromInstance($app->name);
     $app->caption = stripslashes($tv->title);
     $app->title = stripslashes($tv->title);
     // Check if they have access to run this tool
     $hasaccess = $this->_getToolAccess($app->name);
     //$status2 = ($hasaccess) ? "PASSED" : "FAILED";
     //Log::debug("mw::invoke " . $app->name . " by " . User::get('username') . " from " . $app->ip . " _getToolAccess " . $status2);
     if ($this->getError()) {
         echo '<!-- ' . $this->getError() . ' -->';
     }
     if (!$hasaccess) {
         //$this->_redirect = Route::url('index.php?option=' . $this->_option . '&task=accessdenied');
         $this->app = $app;
         $this->accessdeniedTask();
         return;
     }
     $country = \Hubzero\Geocode\Geocode::ipcountry($app->ip);
     //die($app->ip . $country);
     // Log the launch attempt
     $this->_recordUsage($app->toolname, User::get('id'));
     // Get the middleware database
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // Find out how many sessions the user is running.
     $ms = new \Components\Tools\Tables\Session($mwdb);
     $jobs = $ms->getCount(User::get('username'));
     // Find out how many sessions the user is ALLOWED to run.
     include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'preferences.php';
     $preferences = new \Components\Tools\Tables\Preferences($this->database);
     $preferences->loadByUser(User::get('id'));
     if (!$preferences || !$preferences->id) {
         include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'sessionclass.php';
         $scls = new \Components\Tools\Tables\SessionClass($this->database);
         $default = $scls->find('one', array('alias' => 'default'));
         $preferences->user_id = User::get('id');
         $preferences->class_id = $default->id;
         $preferences->jobs = $default->jobs ? $default->jobs : 3;
         $preferences->store();
     }
     $remain = $preferences->jobs - $jobs;
     // Have they reached their session quota?
     if ($remain <= 0) {
         $this->quotaexceededTask();
         return;
     }
     if ($this->config->get('warn_multiples', 0) && !Request::getInt('newinstance', 0)) {
         $sessions = $ms->getRecords(User::get('username'), $app->name, false);
         if ($sessions && count($sessions) > 0) {
             $this->view->setLayout('list');
             $this->view->app = $app;
             $this->view->config = $this->config;
             $this->view->sessions = $sessions;
             foreach ($this->getErrors() as $error) {
                 $view->setError($error);
             }
             $this->view->display();
             return;
         }
     }
     // Get their disk space usage
     $this->_getDiskUsage();
     $this->_redirect = '';
     $app->percent = 0;
     if ($this->config->get('show_storage', 1)) {
         $app->percent = $this->percent;
     }
     if ($this->percent >= 100) {
         App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=storage'));
         return;
     }
     // Get plugins
     Plugin::import('mw', $app->toolname);
     // Trigger any events that need to be called before session invoke
     Event::trigger('mw.onBeforeSessionInvoke', array($app->toolname, $app->version));
     $toolparams = '';
     if (!empty($params)) {
         $toolparams = " params=" . rawurlencode($params) . " ";
     }
     // Determine zone
     $app->zone_id = 0;
     if ($this->config->get('zones')) {
         $middleware = new \Components\Tools\Models\Middleware();
         $this->database->setQuery("SELECT zone_id FROM `#__tool_version_zone` WHERE tool_version_id=" . $this->database->quote($tv->id));
         $middleware->set('allowed', $this->database->loadColumn());
         if ($zone = $middleware->zoning($app->ip, $middleware->get('allowed'))) {
             if ($zone->exists()) {
                 $toolparams .= ' zone=' . $zone->get('zone');
                 $app->zone_id = $zone->get('id');
             }
         }
     }
     // We've passed all checks so let's actually start the session
     $status = $this->middleware("start user="******" ip=" . $app->ip . " app=" . $app->name . " version=" . $app->version . $toolparams, $output);
     if ($this->getError()) {
         //App::abort(500, $this->getError());
         //return;
         App::redirect(Route::url($this->config->get('stopRedirect', 'index.php?option=com_members&task=myaccount')), Lang::txt('COM_TOOLS_ERROR_SESSION_INVOKE_FAILED'), 'error');
         return;
     }
     $app->sess = !empty($output->session) ? $output->session : '';
     // Trigger any events that need to be called after session invoke
     Event::trigger('mw.onAfterSessionInvoke', array($app->toolname, $app->version));
     // Get a count of the number of sessions of this specific tool
     $appcount = $ms->getCount(User::get('username'), $app->name);
     // Do we have more than one session of this tool?
     if ($appcount > 1) {
         // We do, so let's append a timestamp
         $app->caption .= ' (' . Date::toLocal('g:i a') . ')';
     }
     // Save the changed caption
     $ms->load($app->sess);
     $ms->sessname = $app->caption;
     $ms->params = $params;
     if (!$ms->store()) {
         App::abort(500, $ms->getError());
     }
     $rtrn = Request::getVar('return', '');
     $url = 'index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&app=' . $app->toolname . '&task=session&sess=' . $app->sess . '&return=' . $rtrn . (Request::getWord('viewer') ? '&viewer=' . Request::getWord('viewer') : '');
     // Log activity
     Event::trigger('system.logActivity', ['activity' => ['action' => 'created', 'scope' => 'tool.session', 'scope_id' => $app->sess, 'description' => Lang::txt('COM_TOOLS_ACTIVITY_SESSION_CREATED', $app->sess, '<a href="' . Route::url($url) . '">' . $app->caption . '</a>'), 'details' => array('tool' => $app->name, 'url' => $url)], 'recipients' => array(['user', User::get('id')])]);
     App::redirect(Route::url($url, false));
 }
Esempio n. 3
0
 */
// No direct access.
defined('_HZEXEC_') or die;
Html::behavior('core');
//is this a share session thats read-only
$readOnly = false;
foreach ($this->shares as $share) {
    if (User::get('username') == $share->viewuser) {
        if (strtolower($share->readonly) == 'yes') {
            $readOnly = true;
        }
    }
}
include_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'preferences.php';
$database = App::get('db');
$preferences = new \Components\Tools\Tables\Preferences($database);
$preferences->loadByUser(User::get('id'));
$declared = Request::getWord('viewer');
if ($declared) {
    if (Request::getInt('preferred', 0)) {
        $preferences->set('user_id', User::get('id'));
        $preferences->param()->set('viewer', $declared);
        $preferences->store();
    }
} else {
    if ($declared = $preferences->param('viewer')) {
        Request::setVar('viewer', $declared);
    }
}
// We actually need to do this first so we know what viewer is the active one.
$output = Event::trigger('tools.onToolSessionView', array($this->app, $this->output, $readOnly));
Esempio n. 4
0
 /**
  * Utility method to act on a user after it has been saved.
  *
  * @param   array    $user     Holds the new user data.
  * @param   boolean  $isnew    True if a new user is stored.
  * @param   boolean  $success  True if user was succesfully stored in the database.
  * @param   string   $msg      Message.
  * @return  void
  */
 public function onUserAfterSave($user, $isnew, $success, $msg)
 {
     $userId = \Hubzero\Utility\Arr::getValue($user, 'id', 0, 'int');
     if ($userId && $success) {
         try {
             $gids = JUserHelper::getUserGroups($userId);
             $db = App::get('db');
             //
             // Quota class
             //
             require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'quotas_classes.php';
             require_once PATH_CORE . DS . 'components' . DS . 'com_members' . DS . 'tables' . DS . 'users_quotas.php';
             $row = new \Components\Members\Tables\UsersQuotas($db);
             // Check for an existing quota record
             $db->setQuery("SELECT * FROM `#__users_quotas` WHERE `user_id`=" . $userId);
             if ($quota = $db->loadObject()) {
                 $row->bind($quota);
             } else {
                 $row->user_id = $userId;
             }
             // If (no quota record OR a record and a quota class [e.g., not custom]) ...
             if (!$row->id || $row->id && $row->class_id) {
                 $val = array('hard_files' => 0, 'soft_files' => 0, 'hard_blocks' => 0, 'soft_blocks' => 0);
                 $db->setQuery("SELECT c.* FROM `#__users_quotas_classes` AS c LEFT JOIN `#__users_quotas_classes_groups` AS g ON g.`class_id`=c.`id` WHERE g.`group_id` IN (" . implode(',', $gids) . ")");
                 $cids = $db->loadObjectList();
                 if (count($cids) <= 0) {
                     $db->setQuery("SELECT c.* FROM `#__users_quotas_classes` AS c WHERE c.`alias`=" . $db->quote('default'));
                     $cids = $db->loadObjectList();
                 }
                 // Loop through each usergroup and find the highest quota values
                 foreach ($cids as $cls) {
                     $cls->hard_blocks = intval($cls->hard_blocks);
                     $cls->soft_blocks = intval($cls->soft_blocks);
                     if ($cls->hard_blocks > $val['hard_blocks'] && $cls->soft_blocks > $val['soft_blocks']) {
                         $row->class_id = $cls->id;
                     }
                     //$val['hard_files']  = ($val['hard_files']  > $cls->hard_files  ?: $cls->hard_files);
                     //$val['soft_files']  = ($val['soft_files']  > $cls->soft_files  ?: $cls->soft_files);
                     $val['hard_blocks'] = $val['hard_blocks'] > $cls->hard_blocks ? $val['hard_blocks'] : $cls->hard_blocks;
                     $val['soft_blocks'] = $val['soft_blocks'] > $cls->soft_blocks ? $val['soft_blocks'] : $cls->soft_blocks;
                 }
                 $row->hard_files = $val['hard_files'];
                 $row->soft_files = $val['soft_files'];
                 $row->hard_blocks = $val['hard_blocks'];
                 $row->soft_blocks = $val['soft_blocks'];
                 if (!$row->check()) {
                     throw new Exception($row->getError());
                 }
                 if (!$row->store()) {
                     throw new Exception($row->getError());
                 }
             }
             //
             // Session limits
             //
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'sessionclass.php';
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'preferences.php';
             $row = new \Components\Tools\Tables\Preferences($db);
             // Check for an existing quota record
             $db->setQuery("SELECT * FROM `#__users_tool_preferences` WHERE `user_id`=" . $userId);
             if ($quota = $db->loadObject()) {
                 $row->bind($quota);
             } else {
                 $row->user_id = $userId;
             }
             // If (no quota record OR a record and a quota class [e.g., not custom]) ...
             if (!$row->id || $row->id && $row->class_id) {
                 $val = array('jobs' => 0);
                 $db->setQuery("SELECT c.* FROM `#__tool_session_classes` AS c LEFT JOIN `#__tool_session_class_groups` AS g ON g.`class_id`=c.`id` WHERE g.`group_id` IN (" . implode(',', $gids) . ")");
                 $cids = $db->loadObjectList();
                 if (count($cids) <= 0) {
                     $db->setQuery("SELECT c.* FROM `#__tool_session_classes` AS c WHERE c.`alias`=" . $db->quote('default'));
                     $cids = $db->loadObjectList();
                 }
                 // Loop through each usergroup and find the highest 'jobs allowed' value
                 foreach ($cids as $cls) {
                 }
                 $cls->jobs = intval($cls->jobs);
                 if ($cls->jobs > $val['jobs']) {
                     $row->class_id = $cls->id;
                 }
                 $val['jobs'] = $val['jobs'] > $cls->jobs ? $val['jobs'] : $cls->jobs;
                 $row->jobs = $val['jobs'];
                 if (!$row->check()) {
                     throw new Exception($row->getError());
                 }
                 if (!$row->store()) {
                     throw new Exception($row->getError());
                 }
             }
         } catch (Exception $e) {
             $this->_subject->setError($e->getMessage());
             return false;
         }
     }
     return true;
 }
Esempio n. 5
0
 /**
  * Runs a rappture job.
  *
  * This is more than just invoking a tool. We're expecting a driver file to pass to the
  * tool to be picked up and automatically run by rappture.
  *
  * @apiMethod POST
  * @apiUri    /tools/run
  * @apiParameter {
  * 		"name":          "app",
  * 		"description":   "Name of app installed as a tool in the hub",
  * 		"type":          "string",
  * 		"required":      true,
  * }
  * @apiParameter {
  * 		"name":          "revision",
  * 		"description":   "The specific requested revision of the app",
  * 		"type":          "string",
  * 		"required":      false,
  * 		"default":       "default",
  * }
  * @apiParameter {
  * 		"name":          "xml",
  * 		"description":   "Content of the driver file that rappture will use to invoke the given app",
  * 		"type":          "string",
  * 		"required":      true,
  * }
  * @return     void
  */
 public function runTask()
 {
     $this->requiresAuthentication();
     // Get the user_id and attempt to load user profile
     $userid = App::get('authn')['user_id'];
     $profile = User::getInstance($userid);
     // Make sure we have a user
     if (!$profile->get('id')) {
         throw new Exception(Lang::txt('Unable to find user.'), 404);
     }
     // Grab tool name and version
     $tool_name = Request::getVar('app', '');
     $tool_version = Request::getVar('revision', 'default');
     // Build application object
     $app = new stdClass();
     $app->name = trim(str_replace(':', '-', $tool_name));
     $app->version = $tool_version;
     $app->ip = $_SERVER["REMOTE_ADDR"];
     // Check to make sure we have an app to invoke
     if (!$app->name) {
         throw new Exception(Lang::txt('A valid app name must be provided'), 404);
     }
     // Include needed tool libraries
     require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'version.php';
     require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'session.php';
     require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'viewperm.php';
     // Create database object
     $database = \App::get('db');
     // Load the tool version
     $tv = new \Components\Tools\Tables\Version($database);
     switch ($app->version) {
         case 1:
         case 'default':
             $app->name = $tv->getCurrentVersionProperty($app->name, 'instance');
             break;
         case 'test':
         case 'dev':
             $app->name .= '_dev';
             break;
         default:
             $app->name .= '_r' . $app->version;
             break;
     }
     $app->toolname = $app->name;
     if ($parent = $tv->getToolname($app->name)) {
         $app->toolname = $parent;
     }
     // Check of the toolname has a revision indicator
     $r = substr(strrchr($app->name, '_'), 1);
     if (substr($r, 0, 1) != 'r' && substr($r, 0, 3) != 'dev') {
         $r = '';
     }
     // No version passed and no revision
     if ((!$app->version || $app->version == 'default') && !$r) {
         // Get the latest version
         $app->version = $tv->getCurrentVersionProperty($app->toolname, 'revision');
         $app->name = $app->toolname . '_r' . $app->version;
     }
     // Get the caption/session title
     $tv->loadFromInstance($app->name);
     $app->caption = stripslashes($tv->title);
     $app->title = stripslashes($tv->title);
     // Make sure we have a valid tool
     if ($app->title == '' || $app->toolname == '') {
         throw new Exception(Lang::txt('The tool "%s" does not exist on the HUB.', $tool_name), 404);
     }
     // Get tool access
     $toolAccess = \Components\Tools\Helpers\Utils::getToolAccess($app->name, $profile->get('username'));
     // Do we have access
     if ($toolAccess->valid != 1) {
         throw new Exception($toolAccess->error->message, 500);
     }
     // Log the launch attempt
     \Components\Tools\Helpers\Utils::recordToolUsage($app->toolname, $profile->get('id'));
     // Get the middleware database
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // Find out how many sessions the user is running
     $ms = new \Components\Tools\Tables\Session($mwdb);
     $jobs = $ms->getCount($profile->get('username'));
     // Find out how many sessions the user is ALLOWED to run.
     include_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'preferences.php';
     $preferences = new \Components\Tools\Tables\Preferences($database);
     $preferences->loadByUser($profile->get('id'));
     if (!$preferences || !$preferences->id) {
         $default = $preferences->find('one', array('alias' => 'default'));
         $preferences->user_id = $profile->get('id');
         $preferences->class_id = $default->id;
         $preferences->jobs = $default->jobs;
         $preferences->store();
     }
     $remain = $preferences->jobs - $jobs;
     //can we open another session
     if ($remain <= 0) {
         throw new Exception(Lang::txt('You are using all (%s) your available job slots.', $jobs), 401);
     }
     // Check for an incoming driver file
     if ($driver = Request::getVar('xml', false, 'post', 'none', 2)) {
         // Build a path to where the driver file will go through webdav
         $base = DS . 'webdav' . DS . 'home';
         $user = DS . $profile->get('username');
         $data = DS . 'data';
         $drvr = DS . '.queued_drivers';
         $inst = DS . md5(time()) . '.xml';
         // Real home directory
         $homeDir = $profile->get('homeDirectory');
         // First, make sure webdav is there and that the necessary folders are there
         if (!\Filesystem::exists($base)) {
             throw new Exception(Lang::txt('Home directories are unavailable'), 500);
         }
         // Now see if the user has a home directory yet
         if (!\Filesystem::exists($homeDir)) {
             // Try to create their home directory
             require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'utils.php';
             if (!\Components\Tools\Helpers\Utils::createHomeDirectory($profile->get('username'))) {
                 throw new Exception(Lang::txt('Failed to create user home directory'), 500);
             }
         }
         // Check for, and create if needed a session data directory
         if (!\Filesystem::exists($base . $user . $data) && !\Filesystem::makeDirectory($base . $user . $data, 0700)) {
             throw new Exception(Lang::txt('Failed to create data directory'), 500);
         }
         // Check for, and create if needed a queued drivers directory
         if (!\Filesystem::exists($base . $user . $data . $drvr) && !\Filesystem::makeDirectory($base . $user . $data . $drvr, 0700)) {
             throw new Exception(Lang::txt('Failed to create drivers directory'), 500);
         }
         // Write the driver file out
         if (!\Filesystem::write($base . $user . $data . $drvr . $inst, $driver)) {
             throw new Exception(Lang::txt('Failed to create driver file'), 500);
         }
     } else {
         throw new Exception(Lang::txt('No driver file provided'), 404);
     }
     // Now build params path that will be included with tool execution
     // We know from the checks above that this directory already exists
     $params = 'file(execute):' . $homeDir . DS . 'data' . DS . '.queued_drivers' . $inst;
     $encoded = ' params=' . rawurlencode($params) . ' ';
     $command = 'start user='******'username') . " ip={$app->ip} app={$app->name} version={$app->version}" . $encoded;
     $status = \Components\Tools\Helpers\Utils::middleware($command, $output);
     if (!$status) {
         throw new Exception(Lang::txt('Tool invocation failed'), 500);
     }
     $this->send(array('success' => true, 'session' => $output->session));
 }
Esempio n. 6
0
 /**
  * Show a form for raising a user's allowed sessions, storage, etc.
  *
  * @return  void
  */
 public function raiselimitTask()
 {
     // Check if they're logged in
     if (User::isGuest()) {
         $rtrn = Request::getVar('REQUEST_URI', Route::url('index.php?option=' . $this->_controller . '&task=raiselimit', false, true), 'server');
         App::redirect(Route::url('index.php?option=com_users&view=login&return=' . base64_encode($rtrn), false));
     }
     // Incoming
     $id = Request::getInt('id', 0);
     // Initiate profile class
     $profile = Member::oneOrFail($id);
     // Ensure we have a member
     if (!$profile->get('id')) {
         App::abort(404, Lang::txt('MEMBERS_NOT_FOUND'));
     }
     // Check authorization
     if (!User::authorise('core.manage', $this->_option) && User::get('id') != $id) {
         App::abort(403, Lang::txt('COM_MEMBERS_NOT_AUTH'));
     }
     // Set the page title
     $title = Lang::txt(strtoupper($this->_option));
     $title .= $this->_task ? ': ' . Lang::txt(strtoupper($this->_task)) : '';
     Document::setTitle($title);
     // Set the pathway
     if (Pathway::count() <= 0) {
         Pathway::append(Lang::txt(strtoupper($this->_option)), 'index.php?option=' . $this->_option);
     }
     Pathway::append(stripslashes($profile->get('name')), 'index.php?option=' . $this->_option . '&id=' . $profile->get('id'));
     Pathway::append(Lang::txt(strtoupper($this->_task)), 'index.php?option=' . $this->_option . '&id=' . $profile->get('id') . '&task=' . $this->_task);
     // Incoming
     $request = Request::getVar('request', null, 'post');
     $raiselimit = Request::getVar('raiselimit', null, 'post');
     if ($raiselimit) {
         $k = '';
         if (is_array($raiselimit)) {
             $k = key($raiselimit);
         }
         switch ($k) {
             case 'sessions':
                 include_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'tables' . DS . 'preferences.php';
                 $preferences = new \Components\Tools\Tables\Preferences($this->database);
                 $preferences->loadByUser($profile->get('id'));
                 if (!$preferences || !$preferences->id) {
                     $default = $preferences->find('one', array('alias' => 'default'));
                     $preferences->user_id = $profile->get('id');
                     $preferences->class_id = $default->id;
                     $preferences->jobs = $default->jobs;
                     $preferences->store();
                 }
                 $oldlimit = $preferences->jobs;
                 $newlimit = $oldlimit + 3;
                 $resourcemessage = 'session limit from ' . $oldlimit . ' to ' . $newlimit . ' sessions ';
                 if ($this->view->authorized == 'admin') {
                     $preferences->class_id = 0;
                     $preferences->jobs = $newlimit;
                     $preferences->store();
                     $resourcemessage = 'The session limit for [' . $profile->get('username') . '] has been raised from ' . $oldlimit . ' to ' . $newlimit . ' sessions.';
                 } else {
                     if ($request === null) {
                         $this->view->set('title', $title)->set('resource', $k)->setLayout('select')->display();
                         return;
                     }
                 }
                 break;
             case 'storage':
                 $oldlimit = 'unknown';
                 // $profile->get('quota');
                 $newlimit = 'unknown';
                 // $profile->get('quota') + 100;
                 $resourcemessage = ' storage limit has been raised from ' . $oldlimit . ' to ' . $newlimit . '.';
                 if (User::authorise('core.manage', $this->_option)) {
                     $resourcemessage = 'The storage limit for [' . $profile->get('username') . '] has been raised from ' . $oldlimit . ' to ' . $newlimit . '.';
                 } else {
                     $this->view->set('title', $title)->set('resource', $k)->setLayout('select')->display();
                     return;
                 }
                 break;
             case 'meetings':
                 $oldlimit = 'unknown';
                 // $profile->get('max_meetings');
                 $newlimit = 'unknown';
                 // $profile->get('max_meetings') + 3;
                 $resourcemessage = ' meeting limit has been raised from ' . $oldlimit . ' to ' . $newlimit . '.';
                 if (User::authorise('core.manage', $this->_option)) {
                     // $profile->set('max_meetings', $newlimit);
                     // $profile->update();
                     $resourcemessage = 'The meeting limit for [' . $profile->get('username') . '] has been raised from ' . $oldlimit . ' to ' . $newlimit . '.';
                 } else {
                     $this->view->set('title', $title)->set('resource', $k)->setLayout('select')->display();
                     return;
                 }
                 break;
             default:
                 // Show limit selection form
                 $this->view->set('title', $title)->display();
                 return;
                 break;
         }
     }
     // Do we need to email admin?
     if ($request !== null && !empty($resourcemessage)) {
         $sitename = Config::get('sitename');
         $live_site = rtrim(Request::base(), '/');
         // Email subject
         $subject = $hubName . " Account Resource Request";
         // Email message
         $message = 'Name: ' . $profile->get('name');
         if ($profile->get('organization')) {
             $message .= " / " . $profile->get('organization');
         }
         $message .= "\r\n";
         $message .= "Email: " . $profile->get('email') . "\r\n";
         $message .= "Username: "******"\r\n\r\n";
         $message .= 'Has requested an increases in their ' . $hubName;
         $message .= $resourcemessage . "\r\n\r\n";
         $message .= "Reason: ";
         if (empty($request)) {
             $message .= "NONE GIVEN\r\n\r\n";
         } else {
             $message .= $request . "\r\n\r\n";
         }
         $message .= "Click the following link to grant this request:\r\n";
         $sef = Route::url('index.php?option=' . $this->_option . '&id=' . $profile->get('id') . '&task=' . $this->_task);
         $url = Request::base() . ltrim($sef, DS);
         $message .= $url . "\r\n\r\n";
         $message .= "Click the following link to review this user's account:\r\n";
         $sef = Route::url('index.php?option=' . $this->_option . '&id=' . $profile->get('id'));
         $url = Request::base() . ltrim($sef, DS);
         $message .= $url . "\r\n";
         $msg = new \Hubzero\Mail\Message();
         $msg->setSubject($subject)->addTo(Config::get('mailfrom'))->addFrom(Config::get('mailfrom'), Config::get('sitename') . ' Administrator')->addHeader('X-Component', $this->_option)->setBody($message);
         // Send an e-mail to admin
         if (!$msg->send()) {
             return App::abort(500, 'xHUB Internal Error: Error mailing resource request to site administrator(s).');
         }
         // Output the view
         $this->view->set('resourcemessage', $resourcemessage)->setLayout('success')->display();
         return;
     } else {
         if (User::authorise('core.manage', $this->_option) && !empty($resourcemessage)) {
             // Output the view
             $this->view->set('resourcemessage', $resourcemessage)->setLayout('success')->display();
             return;
         }
     }
     // Output the view
     $this->view->set('resource', null)->set('title', $title)->display();
 }