Exemplo n.º 1
0
 /**
  * Get execution zones list
  *
  * @return     array
  */
 public function getExecutionZones()
 {
     $query = "SELECT zone FROM `zones`";
     $mwdb = Utils::getMWDBO();
     $mwdb->setQuery($query);
     return $mwdb->loadList();
 }
Exemplo n.º 2
0
 /**
  * Constructor
  *
  * @param      mixed $oid Integer (ID), string (alias), object or array
  * @return     void
  */
 public function __construct($db = null)
 {
     if (!$db instanceof \JDatabase && !$db instanceof \Hubzero\Database\Driver) {
         $db = Utils::getMWDBO();
     }
     $this->_db = $db;
 }
Exemplo n.º 3
0
 /**
  * Constructor
  *
  * @param      mixed  $oid        Integer (ID), string (alias), object or array
  * @param      string $authorized Authorization level
  * @return     void
  */
 public function __construct($oid = null, $authorized = null)
 {
     $this->_db = Utils::getMWDBO();
     if ($this->_tbl_name) {
         $cls = $this->_tbl_name;
         $this->_tbl = new $cls($this->_db);
         if (!$this->_tbl instanceof \JTable) {
             $this->_logError(__CLASS__ . '::' . __FUNCTION__ . '(); ' . Lang::txt('Table class must be an instance of JTable.'));
             throw new \LogicException(Lang::txt('Table class must be an instance of JTable.'));
         }
         if (is_numeric($oid) || is_string($oid)) {
             // Make sure $oid isn't empty
             // This saves a database call
             if ($oid) {
                 $obj = $this->_tbl->loadSession($oid, $authorized);
                 if ($obj) {
                     $this->bind($obj);
                 }
             }
         } else {
             if (is_object($oid) || is_array($oid)) {
                 $this->bind($oid);
             }
         }
     }
 }
Exemplo n.º 4
0
 /**
  * Saves the name of a session (AJAX)
  *
  * @return     void
  */
 public function renameTask()
 {
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     $id = Request::getInt('id', 0);
     $name = trim(Request::getVar('name', ''));
     if ($id && $name) {
         $ms = new \Components\Tools\Tables\Session($mwdb);
         $ms->load($id);
         $ms->sessname = $name;
         $ms->store();
     }
     echo $name;
 }
Exemplo n.º 5
0
			</tr>
		</thead>
		<tfoot>
			<tr>
				<td colspan="7">
					<?php 
// Initiate paging
echo $this->pagination($this->total, $this->filters['start'], $this->filters['limit']);
?>
				</td>
			</tr>
		</tfoot>
		<tbody>
<?php 
if ($this->rows) {
    $db = \Components\Tools\Helpers\Utils::getMWDBO();
    $i = 0;
    foreach ($this->rows as $row) {
        $list = array();
        for ($k = 0; $k < count($this->hosttypes); $k++) {
            $r = $this->hosttypes[$k];
            $list[$r->name] = (int) $r->value & (int) $row->provisions;
        }
        ?>
			<tr>
				<td>
					<input type="checkbox" name="id[]" id="cb<?php 
        echo $i;
        ?>
" value="<?php 
        echo $row->hostname;
Exemplo n.º 6
0
 /**
  * Authenticate requests
  *
  * @return  mixed
  */
 public function authenticate()
 {
     if (!$this->_route) {
         return;
     }
     JLoader::import('Hubzero.User.Profile');
     JLoader::import('Hubzero.User.Helper');
     JLoader::import('Hubzero.Oauth.Provider');
     JLoader::import('Hubzero.User');
     JLoader::import('Hubzero.Xml');
     /*
      * If CLI then we have to gather all query, post and header values
      * into params for Oauth_Provider's constructor.
      */
     $params = array();
     if (php_sapi_name() == 'cli') {
         $queryvars = $this->request->get('queryvars');
         $postvars = $this->request->get('postdata');
         if (!empty($queryvars)) {
             foreach ($queryvars as $key => $value) {
                 if (isset($queryvars[$key])) {
                     $params[$key] = $queryvars[$key];
                 } else {
                     if (isset($postvars[$key])) {
                         $params[$key] = $postvars[$key];
                     }
                 }
             }
         }
         if (!empty($postvars)) {
             foreach ($postvars as $key => $value) {
                 if (isset($queryvars[$key])) {
                     $params[$key] = $queryvars[$key];
                 } else {
                     if (isset($postvars[$key])) {
                         $params[$key] = $postvars[$key];
                     }
                 }
             }
         }
         if (empty($params)) {
             return false;
         }
     }
     /*
         If request has a Basic Auth header Oauth will throw an exception if the header doesn't
         conform to the OAuth protocol. We catch that (or any other)  exception and proceed as 
         if there was no oauth data.
     
         @TODO A better approach might be to inspect the Basic Auth header and see if it even
         looks like OAuth was being attempted and throw an Oauth compliant error if it was.
     */
     try {
         $oauthp = new \Hubzero\Oauth\Provider($params);
         $oauthp->setRequestTokenPath('/api/oauth/request_token');
         $oauthp->setAccessTokenPath('/api/oauth/access_token');
         $oauthp->setAuthorizePath('/api/oauth/authorize');
         $result = $oauthp->validateRequest($this->request->get('request'), $this->request->get('method'));
         if (is_array($result)) {
             $this->response->setResponseProvides('application/x-www-form-urlencoded');
             $this->response->setMessage($result['message'], $result['status'], $result['reason']);
             return false;
         }
         $this->_provider = $oauthp;
         $this->_authn['oauth_token'] = $oauthp->getToken();
         $this->_authn['consumer_key'] = $oauthp->getConsumerKey();
     } catch (Exception $e) {
         $result = false;
     }
     $this->_authn['user_id'] = null;
     if (isset($this->_authn['oauth_token']) && $this->_authn['oauth_token']) {
         $data = $oauthp->getTokenData();
         if (!empty($data->user_id)) {
             $this->_authn['user_id'] = $data->user_id;
         }
         $this->_authn['session_id'] = null;
         JFactory::getSession()->set('user', new JUser($data->user_id));
     } else {
         // well lets try to authenticate it with a session instead
         $session_name = md5(self::getHash('site'));
         $session_id = null;
         if (!empty($_COOKIE[$session_name])) {
             $session_id = $_COOKIE[$session_name];
         }
         $this->_authn['session_id'] = $session_id;
         $this->_authn['user_id'] = null;
         if (!empty($session_id)) {
             $db = JFactory::getDBO();
             $timeout = JFactory::getConfig()->getValue('config.timeout');
             $query = "SELECT userid FROM `#__session` WHERE session_id=" . $db->Quote($session_id) . "AND " . " time + " . (int) $timeout . " <= NOW() AND client_id = 0;";
             $db->setQuery($query);
             $user_id = $db->loadResult();
             if (!empty($user_id)) {
                 $this->_authn['user_id'] = $user_id;
             }
         }
         // tool session authentication
         $toolSessionId = JRequest::getInt('sessionnum', null, 'POST');
         $toolSessionToken = JRequest::getCmd('sessiontoken', null, 'POST');
         // use request headers as backup method to post vars
         if (!$toolSessionId && !$toolSessionToken) {
             $headers = apache_request_headers();
             $toolSessionId = isset($headers['sessionnum']) ? $headers['sessionnum'] : null;
             $toolSessionToken = isset($headers['sessiontoken']) ? $headers['sessiontoken'] : null;
         }
         // if we have a session id & token lets use those to authenticate
         if ($toolSessionId && $toolSessionToken) {
             // include neede libs
             require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php';
             // instantiate middleware database
             $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
             // attempt to load session from db
             $query = "SELECT * FROM `session` WHERE `sessnum`= " . $mwdb->quote($toolSessionId) . " AND `sesstoken`=" . $mwdb->quote($toolSessionToken);
             $mwdb->setQuery($query);
             // only continue if a valid session was found
             if ($session = $mwdb->loadObject()) {
                 // check users IP against the session execution host IP
                 if (JRequest::ip() == gethostbyname($session->exechost)) {
                     $profile = \Hubzero\User\User::oneByUsername($session->username);
                     $this->_authn['user_id'] = $profile->get('id');
                 }
             }
         }
     }
     $this->request->validApiKey = !empty($this->_authn['consumer_key']);
 }
Exemplo n.º 7
0
 /**
  * Delete one or more hostname records
  *
  * @return     void
  */
 public function removeTask()
 {
     // Check for request forgeries
     Request::checkToken(['get', 'post']);
     // Incoming
     $ids = Request::getVar('id', array());
     $mwdb = Utils::getMWDBO();
     if (count($ids) > 0) {
         $row = new Tables\Session($mwdb);
         // Loop through each ID
         foreach ($ids as $id) {
             $id = intval($id);
             if (!$row->load($id)) {
                 Notify::error(Lang::txt('COM_TOOLS_ERROR_FAILED_TO_LOAD_SESSION', $id));
                 continue;
             }
             // Trigger any events that need to be called before session stop
             Event::trigger('mw.onBeforeSessionStop', array($row->appname));
             // Stop the session
             $status = $this->middleware("stop {$id}", $output);
             if ($status) {
                 $msg = 'Stopping ' . $id . '<br />';
                 foreach ($output as $line) {
                     $msg .= $line . "\n";
                 }
                 Notify::error($msg);
             }
             // Trigger any events that need to be called after session stop
             Event::trigger('mw.onAfterSessionStop', array($row->appname));
         }
     }
     App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_TOOLS_SESSIONS_TERMINATED'), 'message');
 }
Exemplo n.º 8
0
 /**
  * Delete one or more hostname records
  *
  * @return  void
  */
 public function removeTask()
 {
     // Check for request forgeries
     Request::checkToken();
     // Incoming
     $ids = Request::getVar('id', array());
     $mwdb = Utils::getMWDBO();
     if (count($ids) > 0) {
         $row = new Tables\Host($mwdb);
         // Loop through each ID
         foreach ($ids as $id) {
             $id = preg_replace("/[^A-Za-z0-9-.]/", '', $id);
             if (!$row->delete($id)) {
                 throw new \Exception($row->getError(), 500);
             }
         }
     }
     App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false), Lang::txt('COM_TOOLS_ITEM_DELETED'), 'message');
 }
Exemplo n.º 9
0
 /**
  * Edit a record
  *
  * @return  void
  */
 public function editTask($row = null)
 {
     Request::setVar('hidemainmenu', 1);
     // Get the middleware database
     $mwdb = Utils::getMWDBO();
     $mw = new Middleware($mwdb);
     if (!is_object($row)) {
         // Incoming
         $id = Request::getInt('id', 0);
         $row = new Middleware\Location($id);
     }
     $this->view->row = $row;
     $this->view->zone = Request::getInt('zone', 0);
     if (!$this->view->row->exists()) {
         $this->view->row->set('zone_id', $this->view->zone);
     }
     $this->view->tmpl = Request::getVar('tmpl', '');
     // Set any errors
     foreach ($this->getErrors() as $error) {
         $this->view->setError($error);
     }
     // Display results
     $this->view->setLayout('edit')->display();
 }
Exemplo n.º 10
0
 /**
  * Get a member's tool sessions
  *
  * @apiMethod GET
  * @apiUri    /members/{id}/tools/sessions
  * @apiParameter {
  * 		"name":        "id",
  * 		"description": "Member identifier",
  * 		"type":        "integer",
  * 		"required":    true,
  * 		"default":     null
  * }
  * @return  void
  */
 public function sessionsTask()
 {
     $this->requiresAuthentication();
     $userid = Request::getInt('id', 0);
     $result = User::getInstance($userid);
     if ($result === false) {
         throw new Exception(Lang::txt('COM_MEMBERS_ERROR_USER_NOT_FOUND'), 404);
     }
     // Include middleware utilities
     include_once Component::path('com_tools') . DS . 'helpers' . DS . 'utils.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'session.php';
     // Get db connection
     $db = \App::get('db');
     // Get Middleware DB connection
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // Get com_tools params
     $mconfig = Component::params('com_tools');
     // Check to make sure we have a connection to the middleware and its on
     if (!$mwdb || !$mconfig->get('mw_on') || $mconfig->get('mw_on') > 1) {
         throw new Exception(Lang::txt('Middleware Service Unavailable'), 503);
     }
     // Get request vars
     $format = Request::getVar('format', 'json');
     $order = Request::getVar('order', 'id_asc');
     // Get my sessions
     $ms = new \Components\Tools\Tables\Session($mwdb);
     $sessions = $ms->getRecords($result->get("username"), '', false);
     // Run middleware command to create screenshots
     $cmd = "/bin/sh " . Component::path('com_tools') . "/scripts/mw screenshot " . $result->get('username') . " 2>&1 </dev/null";
     exec($cmd, $results, $status);
     $results = array();
     foreach ($sessions as $session) {
         $r = array('id' => $session->sessnum, 'app' => $session->appname, 'name' => $session->sessname, 'started' => $session->start, 'accessed' => $session->accesstime, 'owner' => $result->get('username') == $session->username ? 1 : 0, 'ready-only' => $session->readonly == 'No' ? 0 : 1);
         $results[] = $r;
     }
     // Make sure we have an acceptable ordering
     $accepted_ordering = array('id_asc', 'id_desc', 'started_asc', 'started_desc', 'accessed_asc', 'accessed_desc');
     if (in_array($order, $accepted_ordering)) {
         switch ($order) {
             case 'id_asc':
                 break;
             case 'id_desc':
                 usort($results, array($this, "id_sort_desc"));
                 break;
             case 'started_asc':
                 break;
             case 'started_desc':
                 usort($results, array($this, "started_date_sort_desc"));
                 break;
             case 'accessed_asc':
                 usort($results, array($this, "accessed_date_sort_asc"));
                 break;
             case 'accessed_desc':
                 usort($results, array($this, "accessed_date_sort_desc"));
                 break;
         }
     }
     // Encode sessions for return
     $object = new stdClass();
     $object->sessions = $results;
     // Set format and content
     $this->send($object);
 }
Exemplo n.º 11
0
 /**
  * Display module content
  *
  * @return  void
  */
 public function display()
 {
     // Include mw libraries
     include_once Component::path('com_tools') . DS . 'helpers' . DS . 'utils.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'job.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'view.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'viewperm.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'session.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'host.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'hosttype.php';
     include_once Component::path('com_tools') . DS . 'tables' . DS . 'recent.php';
     require_once Component::path('com_members') . DS . 'models' . DS . 'member.php';
     // Get database object
     $this->database = \App::get('db');
     // Get a connection to the middleware database
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // Get tool paras
     $this->toolsConfig = Component::params('com_tools');
     // Set ACL for com_tools
     $authorized = User::authorise('core.manage', 'com_tools');
     // Ensure we have a connection to the middleware
     $this->error = false;
     if (!$mwdb || !$mwdb->connected() || !$this->toolsConfig->get('mw_on') || $this->toolsConfig->get('mw_on') > 1 && !$authorized) {
         $this->error = true;
         return false;
     }
     // Run middleware command to create screenshots
     // only take snapshots if screenshots are on
     if ($this->params->get('show_screenshots', 1)) {
         $cmd = "/bin/sh " . Component::path('com_tools') . "/scripts/mw screenshot " . User::get('username') . " 2>&1 </dev/null";
         exec($cmd, $results, $status);
     }
     // Get sessions
     $session = new \Components\Tools\Tables\Session($mwdb);
     $this->sessions = $session->getRecords(User::get('username'), '', false);
     // Output module
     require $this->getLayoutPath();
 }
Exemplo n.º 12
0
 /**
  * Method to setup Windows filesharing connection
  *
  * @apiMethod GET
  * @apiUri    /tools/{sessionid}/fileshare
  * @apiParameter {
  * 		"name":          "sessionid",
  * 		"description":   "Tool session identifier",
  * 		"type":          "integer",
  * 		"required":      true,
  * 		"default":       0
  * }
  * @apiParameter {
  * 		"name":          "username",
  * 		"description":   "Username",
  * 		"type":          "string",
  * 		"required":      false,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "private_ip",
  * 		"description":   "Private IP Address",
  * 		"type":          "string",
  * 		"required":      false,
  * 		"default":       null
  * }
  * @apiParameter {
  * 		"name":          "public_ip",
  * 		"description":   "Public IP Address",
  * 		"type":          "string",
  * 		"required":      false,
  * 		"default":       null
  * }
  * @return     void
  *
  *
  *
  * @TODO: This is just a rough draft. needs a little polishing.
  *
  */
 public function fileshareTask()
 {
     //$this->requiresAuthentication();
     require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'session.php';
     require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'viewperm.php';
     // instantiate middleware database object
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // get any request vars
     $username = Request::getVar('username');
     $sessionid = Request::getVar('id');
     $private_ip = Request::getVar('private_ip');
     $public_ip = Request::getVar('public_ip', Request::ip());
     // check to make sure we have a valid sessionid
     if ($sessionid == '' || !is_numeric($sessionid)) {
         throw new Exception(Lang::txt('No session ID Specified.'), 401);
     }
     // load session
     $ms = new \Components\Tools\Tables\Session($mwdb);
     $sess = $ms->loadSession($sessionid);
     $command = "/usr/bin/sudo /usr/bin/hzappstream --remote 128.46.19.124 fileshare add {$username} {$sessionid} {$public_ip} {$private_ip} --ipsec-use-default-psk";
     $command = escapeshellcmd($command);
     $descriptorspec = array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"));
     $process = proc_open($command, $descriptorspec, $pipes, "/", NULL);
     if (is_resource($process)) {
         // $pipes now looks like this:
         // 0 => writeable handle connected to child stdin
         // 1 => readable handle connected to child stdout
         // Any error output will be appended to /tmp/error-output.txt
         fclose($pipes[0]);
         $output = stream_get_contents($pipes[1]);
         fclose($pipes[1]);
         $error = stream_get_contents($pipes[2]);
         fclose($pipes[2]);
         // It is important that you close any pipes before calling
         // proc_close in order to avoid a deadlock
         $return_value = proc_close($process);
         $output = strstr($output, '{');
         $joutput = json_decode($output);
         $object = array('fileserver' => '128.46.19.124', 'username' => $username, 'session' => $sessionid, 'ipsec_ip1' => $public_ip, 'ipsec_ip2' => $private_ip, 'smb_username' => 'smb-' . $sessionid);
         $object['smb_password'] = $joutput->smb_password;
     } else {
         $object = array('fileserver' => '128.46.19.124', 'username' => $username, 'session' => $sessionid, 'ipsec_ip1' => $public_ip, 'ipsec_ip2' => $private_ip, 'ipsec_password' => NULL, 'smb_username' => 'smb-' . $sessionid, 'smb_password' => NULL);
     }
     $this->send($object);
 }
Exemplo n.º 13
0
 /**
  * Method to set the default property for a zone
  *
  * @return     void
  */
 public function defaultTask()
 {
     // Get item to default from request
     $id = Request::getVar('id', [], '', 'array');
     if (empty($id)) {
         App::abort(404, Lang::txt('COM_TOOLS_ERROR_MISSING_ID'));
     }
     // Get the middleware database
     $mwdb = Utils::getMWDBO();
     $row = new \Components\Tools\Tables\Zones($mwdb);
     if ($row->load($id[0])) {
         // Get rid of the current default
         $default = new \Components\Tools\Tables\Zones($mwdb);
         $default->load(['is_default' => 1]);
         $default->is_default = 0;
         if (!$default->store()) {
             App::abort(500, Lang::txt('COM_TOOLS_ERROR_DEFAULT_UPDATE_FAILED'));
         }
         // Set a new default
         $row->is_default = 1;
         if (!$row->store()) {
             App::abort(500, Lang::txt('COM_TOOLS_ERROR_DEFAULT_UPDATE_FAILED'));
         }
     }
     App::redirect(Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller, false));
 }
Exemplo n.º 14
0
 /**
  * Method to disconnect from shared tool session
  *
  * @apiMethod GET
  * @apiUri    /tools/{session}/unshare
  * @return    void
  */
 public function unshareTask()
 {
     $this->requiresAuthentication();
     //get the userid and attempt to load user profile
     $userid = App::get('authn')['user_id'];
     $result = \Hubzero\User\Profile::getInstance($userid);
     //make sure we have a user
     if ($result === false) {
         return $this->not_found();
     }
     //include needed libraries
     require_once dirname(dirname(__DIR__)) . DS . 'tables' . DS . 'mw.viewperm.php';
     //instantiate middleware database object
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     //get request vars
     $sessionid = Request::getVar('sessionid', '');
     //check to make sure we have session id
     if (!$sessionid) {
         throw new Exception(Lang::txt('Missing session ID.'), 404);
     }
     // Delete the viewperm
     $mv = new \Components\Tools\Models\Middleware\Viewperm($mwdb);
     $mv->deleteViewperm($sessionid, $result->get('username'));
     //make sure we didnt have error disconnecting
     if (!$mv->getError()) {
         $object = new stdClass();
         $object->session = array('session' => $sessionid, 'status' => 'disconnected', 'disconnected' => with(new Date())->toSql());
         $this->send($object);
     }
 }
Exemplo n.º 15
0
 /**
  * Validate tool session data
  * 
  * @param   string  $toolSessionId     Tool session id
  * @param   string  $toolSessionToken  Tool session token
  * @return  bool    Result of test
  */
 public function validateToolSessionData($toolSessionId, $toolSessionToken)
 {
     // include neede libs
     require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php';
     // instantiate middleware database
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // attempt to load session from db
     $query = "SELECT * \n\t\t\t\t  FROM `session`\n\t\t\t\t  WHERE `sessnum`= " . $mwdb->quote($toolSessionId) . " \n\t\t\t\t  AND `sesstoken`=" . $mwdb->quote($toolSessionToken);
     $mwdb->setQuery($query);
     // only continue if a valid session was found
     if (!($session = $mwdb->loadObject())) {
         return false;
     }
     $ip = new \Hubzero\Utility\Ip(\App::get('request')->ip());
     // ip should be coming from a private address
     if (!$ip->isPrivate()) {
         return false;
     }
     // return user id
     $profile = \Hubzero\User\User::oneByUsername($session->username);
     return $profile->get('id');
 }
Exemplo n.º 16
0
 /**
  * Generate a Windows tool invoke URL to redirect to
  *
  * @param   string  $option  Name of the component
  * @param   string  $appid
  * @param   object  $user
  * @param   string  $ip
  * @return  string
  */
 public function generateInvokeUrl($option, $appid = null, $user = null, $ip = null)
 {
     $appid = $appid ?: Request::getVar('appid');
     if (!$appid) {
         return '';
     }
     $user = $user ?: User::getInstance();
     $ip = $ip ?: Request::ip();
     // Get summary usage data
     $startdate = new \DateTime('midnight first day of this month');
     $enddate = new \DateTime('midnight first day of next month');
     $db = App::get('db');
     $sql = 'SELECT truncate(sum(walltime)/60/60,3) as totalhours FROM `sessionlog` ';
     $sql .= 'WHERE start >' . $db->quote($startdate->format('Y-m-d H:i:s')) . ' ';
     $sql .= 'AND start <' . $db->quote($enddate->format('Y-m-d H:i:s'));
     $db->setQuery($sql);
     $totalUsageFigure = $db->loadObjectList();
     $params = Component::params('com_tools');
     $maxhours = $params->get('windows_monthly_max_hours', '100');
     if (floatval($totalUsageFigure[0]->totalhours) > floatval($maxhours)) {
         return '';
     }
     // Get the middleware database
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // Get the session table
     $ms = new \Components\Tools\Tables\Session($mwdb);
     $ms->bind(array('username' => $user->get('username'), 'remoteip' => $ip));
     // Save the entry
     $ms->store();
     // Get back the ID
     $sessionID = $ms->sessnum;
     // Opaque data
     $od = "username="******",email=" . $user->get('email');
     $od = $od . ",userip=" . $ip;
     $od = $od . ",sessionid=" . $sessionID;
     $od = $od . ",ts=" . (new \DateTime())->format('Y.m.d.H.i.s');
     $eurl = exec("/usr/bin/hz-aws-appstream getentitlementurl --appid '" . $appid . "' --opaquedata '" . $od . "'");
     return $eurl;
 }
Exemplo n.º 17
0
 /**
  * Validate tool session data
  * 
  * @param   string  $toolSessionId     Tool session id
  * @param   string  $toolSessionToken  Tool session token
  * @return  bool    Result of test
  */
 public function validateToolSessionData($toolSessionId, $toolSessionToken)
 {
     // include neede libs
     require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php';
     // instantiate middleware database
     $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
     // attempt to load session from db
     $query = "SELECT * \n\t\t\t\t  FROM `session`\n\t\t\t\t  WHERE `sessnum`= " . $mwdb->quote($toolSessionId) . " \n\t\t\t\t  AND `sesstoken`=" . $mwdb->quote($toolSessionToken);
     $mwdb->setQuery($query);
     // only continue if a valid session was found
     if (!($session = $mwdb->loadObject())) {
         return false;
     }
     // check users IP against the session execution host IP
     if (\App::get('request')->ip() != gethostbyname($session->exechost)) {
         return false;
     }
     // return user id
     $profile = \Hubzero\User\Profile::getInstance($session->username);
     return $profile->get('uidNumber');
 }
Exemplo n.º 18
0
 /**
  * Checks for a ticket and increases instance count if found
  * Creates new ticket if not
  *
  * NOTE: This method is called by Rappture
  * TODO: Create a proper API
  *
  *   option  = 'com_support';
  *   task    = 'create';
  *   no_html = 1;
  *   type    = 1;
  *   sesstoken (optional)
  *
  *   login    (optional) default: automated
  *   severity (optional) default: normal
  *   category (optional) default: Tools
  *   summary  (optional) default: first 75 characters of report
  *   report
  *   email    (optional) default: supportemail
  *   name     (optional) default: Automated Error Report
  *   os       (optional)
  *   browser  (optional)
  *   ip       (optional)
  *   hostname (optional)
  *   uas      (optional)
  *   referrer (optional)
  *   cookies  (optional) default: 1 (since it's coming from rappture we assume they're already logged in and thus have cookies enabled)
  *   section  (optional)
  *   upload   (optional)
  *
  * @return  string
  */
 public function createTask()
 {
     // trim and addslashes all posted items
     $incoming = array_map('trim', $_POST);
     $incoming = array_map('addslashes', $incoming);
     // initiate class and bind posted items to database fields
     $row = new Ticket();
     if (!$row->bind($incoming)) {
         echo $row->getError();
         return;
     }
     $row->set('summary', $row->content('clean', 200));
     // Check for a session token
     $sessnum = '';
     if ($sess = Request::getVar('sesstoken', '')) {
         include_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php';
         $mwdb = \Components\Tools\Helpers\Utils::getMWDBO();
         // retrieve the username and IP from session with this session token
         $query = "SELECT * FROM session WHERE session.sesstoken=" . $this->database->quote($sess) . " LIMIT 1";
         $mwdb->setQuery($query);
         $viewperms = $mwdb->loadObjectList();
         if ($viewperms) {
             foreach ($viewperms as $sinfo) {
                 $row->set('login', $sinfo->username);
                 $row->set('ip', $sinfo->remoteip);
                 $sessnum = $sinfo->sessnum;
             }
             // get user's infor from login
             $user = User::getInstance($row->get('login'));
             $row->set('name', $user->get('name'));
             $row->set('email', $user->get('email'));
         }
     }
     $row->set('login', $row->get('login') ? $row->get('login') : 'automated');
     // check for an existing ticket with this report
     $summary = $row->get('summary');
     if (strstr($summary, '"') || strstr($summary, "'")) {
         $summary = str_replace("\\'", "\\\\\\\\\\'", $summary);
         $summary = str_replace('\\"', '\\\\\\\\\\"', $summary);
         $query = "SELECT id FROM `#__support_tickets` WHERE LOWER(summary) LIKE " . $this->database->quote('%' . strtolower($summary) . '%') . " AND type=1 LIMIT 1";
     }
     $query = "SELECT id FROM `#__support_tickets` WHERE LOWER(summary) LIKE " . $this->database->quote('%' . strtolower($summary) . '%') . " AND type=1 LIMIT 1";
     $this->database->setQuery($query);
     if ($ticket = $this->database->loadResult()) {
         $changelog = '';
         // open existing ticket if closed
         $oldticket = new Ticket($ticket);
         $oldticket->set('instances', $oldticket->get('instances') + 1);
         if (!$oldticket->isOpen()) {
             $before = new Ticket($ticket);
             $oldticket->set('open', 1);
             $oldticket->set('status', 1);
             $oldticket->set('resolved', '');
             $rowc = new Comment();
             $rowc->set('ticket', $ticket);
             $rowc->set('comment', '');
             $rowc->set('created', Date::toSql());
             $rowc->set('created_by', User::get('id'));
             $rowc->set('access', 1);
             // Compare fields to find out what has changed for this ticket and build a changelog
             $rowc->changelog()->diff($before, $oldticket);
             if (!$rowc->store(true)) {
                 echo $rowc->getError();
                 return;
             }
         }
         // store new content
         if (!$oldticket->store(true)) {
             echo $oldticket->getError();
             return;
         }
         $status = $oldticket->status('text');
         $count = $oldticket->get('instances');
     } else {
         // set some defaults
         $row->set('status', 0);
         $row->set('open', 1);
         $row->set('created', Date::toSql());
         $row->set('severity', $row->get('severity') ? $row->get('severity') : 'normal');
         $row->set('category', $row->get('category') ? $row->get('category') : Lang::txt('COM_SUPPORT_CATEGORY_TOOLS'));
         $row->set('resolved', '');
         $row->set('email', $row->get('email') ? $row->get('email') : $this->_data['supportemail']);
         $row->set('name', $row->get('name') ? $row->get('name') : Lang::txt('COM_SUPPORT_AUTOMATED_REPORT'));
         $row->set('cookies', $row->get('cookies') ? $row->get('cookies') : 1);
         $row->set('instances', 1);
         $row->set('section', $row->get('section') ? $row->get('section') : 1);
         $row->set('type', 1);
         // store new content
         if (!$row->store(true)) {
             echo $row->getError();
             return;
         }
         $row->tag($incoming['tags'], User::get('id'), 1);
         if ($attachment = $this->uploadTask($row->get('id'))) {
             $row->set('report', $row->get('report') . "\n\n" . $attachment);
             if (!$row->store()) {
                 $this->setError($row->getError());
             }
         }
         $ticket = $row->get('id');
         $status = 'new';
         $count = 1;
     }
     echo 'Ticket #' . $ticket . ' (' . $status . ') ' . $count . ' times';
 }