/**
  * 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;
 }
Exemple #2
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);
             }
         }
     }
 }
Exemple #3
0
 /**
  * Get execution zones list
  *
  * @return     array
  */
 public function getExecutionZones()
 {
     $query = "SELECT zone FROM `zones`";
     $mwdb = Utils::getMWDBO();
     $mwdb->setQuery($query);
     return $mwdb->loadList();
 }
Exemple #4
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));
 }
Exemple #5
0
 /**
  * Display how much disk usage is being used
  *
  * @return     void
  */
 public function diskusageTask()
 {
     // Check that the user is logged in
     if (User::isGuest()) {
         $this->_login();
         return;
     }
     $msgs = Request::getInt('msgs', 0);
     $du = \Components\Tools\Helpers\Utils::getDiskUsage(User::get('username'));
     if (count($du) <= 1) {
         // error
         $percent = 0;
     } else {
         bcscale(6);
         $val = isset($du['softspace']) && $du['softspace'] != 0 ? bcdiv($du['space'], $du['softspace']) : 0;
         $percent = round($val * 100);
     }
     $amt = $percent > 100 ? '100' : $percent;
     $total = isset($du['softspace']) ? $du['softspace'] / 1024000000 : 0;
     $this->view->amt = $amt;
     $this->view->total = $total;
     $this->view->du = $du;
     $this->view->percent = $percent;
     $this->view->msgs = $msgs;
     $this->view->ajax = 1;
     $this->view->writelink = 1;
     foreach ($this->getErrors() as $error) {
         $this->view->setError($error);
     }
     $this->view->display();
 }
Exemple #6
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;
Exemple #7
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';
 }
 /**
  * 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();
 }
 /**
  * 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');
 }
Exemple #10
0
<?php 
if ($this->params->get('show_storage', 1)) {
    ?>
	<div class="session-storage">
		<span><?php 
    echo Lang::txt('MOD_MYSESSIONS_STORAGE');
    ?>
 (<a href="<?php 
    echo Route::url('index.php?option=com_tools&task=storage');
    ?>
"><?php 
    echo Lang::txt('MOD_MYSESSIONS_MANAGE');
    ?>
</a>)</span>
		<?php 
    $diskUsage = \Components\Tools\Helpers\Utils::getDiskUsage(User::get('username'));
    if (!is_array($diskUsage) || !isset($diskUsage['space'])) {
        echo '<p class="error">' . Lang::txt('MOD_MYSESSIONS_ERROR_RETRIEVING_STORAGE') . '</p></div>';
        return;
    } else {
        if (isset($diskUsage['softspace']) && $diskUsage['softspace'] == 0) {
            echo '<p class="info">' . Lang::txt('MOD_MYSESSIONS_NO_QUOTA') . '</p></div>';
            return;
        } else {
            // Calculate the percentage of spaced used
            bcscale(6);
            $total = $diskUsage['softspace'] / 1024000000;
            $val = $diskUsage['softspace'] > 0 ? bcdiv($diskUsage['space'], $diskUsage['softspace']) : 0;
            $percent = round($val * 100);
            $percent = $percent > 100 ? 100 : $percent;
            // Amount can only have a max of 100 due to some display restrictions
 /**
  * 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);
 }
Exemple #12
0
 /**
  * Save a list of authors
  *
  * @param      array   $authors  List of authors to add
  * @param      string  $version  Tool version
  * @param      integer $rid      Resource ID
  * @param      integer $revision Revision number
  * @param      string  $toolname Tool name
  * @return     boolean False if errors, True if not
  */
 public function saveAuthors($authors, $version = 'dev', $rid = 0, $revision = 0, $toolname = '')
 {
     if (!$rid) {
         return false;
     }
     if ($authors) {
         $authors = Utils::transform($authors, 'uidNumber');
     }
     $dev_authors = $this->getToolAuthors('dev', $rid);
     $dev_authors = Utils::transform($dev_authors, 'uidNumber');
     if ($dev_authors && $version == 'dev') {
         // update
         $to_delete = array_diff($current_authors, $authors);
         if ($to_delete) {
             foreach ($to_delete as $del) {
                 $query = "DELETE FROM #__author_assoc  WHERE authorid=" . $this->_db->quote($del) . " AND subid=" . $this->_db->quote($rid) . " AND subtable='resources'";
                 $this->_db->setQuery($query);
                 $this->_db->query();
             }
         }
     }
     // add new authors
     if ($version == 'dev') {
         // development version is updated
         $to_delete = array_diff($dev_authors, $authors);
         $rc = new \Components\Resources\Tables\Contributor($this->_db);
         $rc->subtable = 'resources';
         $rc->subid = $rid;
         if ($to_delete) {
             foreach ($to_delete as $del) {
                 $query = "DELETE FROM #__author_assoc  WHERE authorid=" . $this->_db->quote($del) . " AND subid=" . $this->_db->quote($rid) . " AND subtable='resources'";
                 $this->_db->setQuery($query);
                 $this->_db->query();
             }
         }
         // Get the last child in the ordering
         $order = $rc->getLastOrder($rid, 'resources');
         $order = $order + 1;
         // new items are always last
         foreach ($authors as $authid) {
             // Check if they're already linked to this resource
             $rc->loadAssociation($authid, $rid, 'resources');
             if (!$rc->authorid) {
                 $xprofile = User::getInstance($authid);
                 // New record
                 $rc->authorid = $authid;
                 $rc->ordering = $order;
                 $rc->name = addslashes($xprofile->get('name'));
                 $rc->organization = addslashes($xprofile->get('organization'));
                 $rc->createAssociation();
                 $order++;
             }
         }
     } else {
         if ($dev_authors) {
             // new version is being published, transfer data from author_assoc
             $i = 0;
             foreach ($dev_authors as $authid) {
                 $name = '';
                 $organization = '';
                 // Check the author_assoc table first, as that's what gets updated when you edit the tool info
                 $query = "SELECT name, organization FROM `#__author_assoc` ";
                 $query .= "WHERE subid= " . $this->_db->quote($rid);
                 $query .= " AND authorid=" . $this->_db->quote($authid);
                 $query .= " AND subtable='resources'";
                 $this->_db->setQuery($query);
                 $author = $this->_db->loadObject();
                 if ($author) {
                     $name = $author->name;
                     $organization = $author->organization;
                 }
                 if (!$name || !$organization) {
                     // Do we have name/org info in previous version?
                     $query = "SELECT name, organization FROM #__tool_authors ";
                     $query .= "WHERE toolname=" . $this->_db->quote($toolname) . " AND uid=" . $this->_db->quote($authid) . " AND revision < " . $this->_db->quote($revision);
                     $query .= " AND name IS NOT NULL AND organization IS NOT NULL ";
                     $query .= " ORDER BY revision DESC LIMIT 1";
                     $this->_db->setQuery($query);
                     $info = $this->_db->loadObjectList();
                     if ($info) {
                         $name = $name ?: $info[0]->name;
                         $organization = $organization ?: $info[0]->organization;
                     }
                     // If we still don't have it, try to grab it from the profile
                     if (!$name || !$organization) {
                         $xprofile = User::getInstance($authid);
                         $name = $name ?: $xprofile->get('name');
                         $organization = $organization ?: $xprofile->get('organization');
                     }
                 }
                 $query = "INSERT INTO {$this->_tbl} (toolname, revision, uid, ordering, version_id, name, organization) VALUES ('" . $toolname . "','" . $revision . "','" . $authid . "','" . $i . "', '" . $version . "', '" . addslashes($name) . "', '" . addslashes($organization) . "')";
                 $this->_db->setQuery($query);
                 if (!$this->_db->query()) {
                     return false;
                 }
                 $i++;
             }
         }
     }
     return true;
 }
 /**
  * Method to return users storage results
  *
  * @apiMethod GET
  * @apiUri    /tools/{user_id}
  * @return    void
  */
 public function storageTask()
 {
     $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();
     }
     //get request vars
     $type = Request::getVar('type', 'soft');
     //get storage quota
     require_once dirname(dirname(__DIR__)) . DS . 'helpers' . DS . 'utils.php';
     $disk_usage = \Components\Tools\Helpers\Utils::getDiskUsage($result->get('username'));
     //get the tools storage path
     $com_tools_params = Component::params('com_tools');
     $path = DS . $com_tools_params->get('storagepath', 'webdav' . DS . 'home') . DS . $result->get('username');
     //get a list of files
     $files = array();
     //$files = Filesystem::files($path, '.', true, true, array('.svn', 'CVS'));
     //return result
     $object = new stdClass();
     $object->storage = array('quota' => $disk_usage, 'files' => $files);
     $this->send($object);
 }
Exemple #14
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');
 }
 /**
  * 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;
 }
Exemple #16
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');
 }
Exemple #17
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();
 }
Exemple #18
0
 /**
  * Send an email to one or more users
  *
  * @param      string $toolid   Tool ID
  * @param      string $summary  Message subject
  * @param      string $comment  Message
  * @param      unknown $access  Parameter description (if any) ...
  * @param      string $action   Parameter description (if any) ...
  * @param      array  $toolinfo Array of tool information
  * @return     void
  */
 protected function _email($toolid, $summary, $comment, $access, $action, $toolinfo = array())
 {
     $headline = '';
     // Get tool information
     $obj = new \Components\Tools\Tables\Tool($this->database);
     $obj->getToolStatus($toolid, $this->_option, $status, 'dev');
     if (empty($status) && !empty($toolinfo)) {
         $status = $toolinfo;
     }
     // Get team
     $team = \Components\Tools\Helpers\Utils::transform($status['developers'], 'uidNumber');
     // Get admins
     $admins = array();
     if ($this->config->get('access-admin-component')) {
         $admins[] = User::get('username');
     }
     $admingroup = $this->config->get('admingroup', '');
     $group = \Hubzero\User\Group::getInstance($admingroup);
     if (is_object($group)) {
         $members = $group->get('members');
         $managers = $group->get('managers');
         $members = array_merge($members, $managers);
         if ($members) {
             foreach ($members as $member) {
                 $muser = User::getInstance($member);
                 if (is_object($muser)) {
                     $admins[] = $member;
                 }
             }
         }
     }
     $inteam = in_array(User::get('id'), $team) ? 1 : 0;
     // collector for those who need to get notified
     $users = array();
     switch ($action) {
         case 1:
             $action = 'contribtool_info_changed';
             $headline = Lang::txt('COM_TOOLS_INFORMATION_CHANGED');
             //$users = $team;
             break;
         case 2:
             $action = 'contribtool_status_changed';
             $headline = $summary;
             //$users = $this->config->get('access-admin-component') ? $team : $admins;
             //if (!$inteam)
             //{
             //$users[] = User::get('id'); // cc person who made the change if not in team
             //}
             break;
         case 3:
             $action = 'contribtool_new_message';
             $headline = Lang::txt('COM_TOOLS_new message');
             //$users = $this->config->get('access-admin-component') && $access != 1 ? $team : $admins;
             break;
         case 4:
             $action = 'contribtool_status_changed';
             $headline = Lang::txt('COM_TOOLS_NEW_REGISTRATION');
             //$users = array_merge($team, $admins);
             break;
         case 5:
             $action = 'contribtool_status_changed';
             $headline = Lang::txt('COM_TOOLS_REGISTRATION_CANCELLED');
             //$users = array_merge($team, $admins);
             break;
     }
     // send messages to everyone
     $users = array_merge($team, $admins);
     // make sure we are not mailing twice
     $users = array_unique($users);
     // Build e-mail components
     $subject = Lang::txt(strtoupper($this->_option)) . ', ' . Lang::txt('COM_TOOLS_TOOL') . ' ' . $status['toolname'] . '(#' . $toolid . '): ' . $headline;
     $from = Config::get('sitename') . ' ' . Lang::txt('COM_TOOLS_CONTRIBTOOL');
     $hub = array('email' => Config::get('mailfrom'), 'name' => $from);
     $live_site = rtrim(Request::base(), '/');
     // Compose Message
     $message = strtoupper(Lang::txt('COM_TOOLS_TOOL')) . ': ' . $status['title'] . ' (' . $status['toolname'] . ')' . "\r\n";
     $message .= strtoupper(Lang::txt('COM_TOOLS_SUMMARY')) . ': ' . $summary . "\r\n";
     $message .= strtoupper(Lang::txt('COM_TOOLS_WHEN')) . ' ' . Date::of(Date::toSql())->toLocal(Lang::txt('DATE_FORMAT_HZ1')) . "\r\n";
     $message .= strtoupper(Lang::txt('COM_TOOLS_BY')) . ': ' . User::get('username') . "\r\n";
     $message .= '----------------------------' . "\r\n\r\n";
     if ($comment) {
         $message .= strtoupper(Lang::txt('COM_TOOLS_MESSAGE')) . ': ' . "\r\n";
         $message .= $comment . "\r\n";
         $message .= '----------------------------' . "\r\n\r\n";
     }
     $message .= Lang::txt('COM_TOOLS_TIP_URL_TO_STATUS') . "\r\n";
     $message .= $live_site . Route::url('index.php?option=' . $this->_option . '&controller=' . $this->_controller . '&task=status&app=' . $status['toolname']) . "\r\n";
     // fire off message
     if ($summary or $comment) {
         if (!Event::trigger('xmessage.onSendMessage', array($action, $subject, $message, $hub, $users, $this->_option))) {
             Notify::error(Lang::txt('COM_TOOLS_FAILED_TO_MESSAGE'));
         }
     }
 }
Exemple #19
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');
 }
Exemple #20
0
 /**
  * Upload a screenshot
  *
  * @return     void
  */
 public function uploadTask()
 {
     // Incoming
     $pid = Request::getInt('pid', 0);
     if (!$pid) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_NO_ID'));
         $this->displayTask($pid, $version);
         return;
     }
     $version = Request::getVar('version', 'dev');
     $title = preg_replace('/\\s+/', ' ', Request::getVar('title', ''));
     $allowed = array('.gif', '.jpg', '.png', '.bmp');
     $changing_version = Request::getInt('changing_version', 0);
     if ($changing_version) {
         // reload screen
         $this->displayTask($pid, $version);
         return;
     }
     // Get resource information
     $resource = new \Components\Resources\Tables\Resource($this->database);
     $resource->load($pid);
     // Incoming file
     $file = Request::getVar('upload', '', 'files', 'array');
     if (!$file['name']) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_NO_FILE'));
         $this->displayTask($pid, $version);
         return;
     }
     // Make the filename safe
     $file['name'] = Filesystem::clean($file['name']);
     $file['name'] = str_replace(' ', '_', $file['name']);
     $file['name'] = str_replace('-tn', '', $file['name']);
     $file_basename = substr($file['name'], 0, strripos($file['name'], '.'));
     // strip extention
     $file_ext = substr($file['name'], strripos($file['name'], '.'));
     // Make sure we have an allowed format
     if (!in_array(strtolower($file_ext), $allowed)) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_WRONG_FILE_FORMAT'));
         $this->displayTask($pid, $version);
         return;
     }
     // Get version id
     $objV = new \Components\Tools\Tables\Version($this->database);
     $vid = $objV->getVersionIdFromResource($pid, $version);
     if ($vid == NULL) {
         $this->setError(Lang::txt('COM_TOOLS_CONTRIBUTE_VERSION_ID_NOT_FOUND'));
         $this->displayTask($pid, $version);
         return;
     }
     // Instantiate a new screenshot object
     $row = new \Components\Resources\Tables\Screenshot($this->database);
     // Check if file with the same name already exists
     $files = $row->getFiles($pid, $vid);
     if (count($files) > 0) {
         $files = \Components\Tools\Helpers\Utils::transform($files, 'filename');
         foreach ($files as $f) {
             if ($f == $file['name']) {
                 // append extra characters in the end
                 $file['name'] = $file_basename . '_' . time() . $file_ext;
                 $file_basename = $file_basename . '_' . time();
             }
         }
     }
     $row->title = preg_replace('/"((.)*?)"/i', "&#147;\\1&#148;", $title);
     $row->versionid = $vid;
     $ordering = $row->getLastOrdering($pid, $vid);
     $row->ordering = $ordering ? $ordering + 1 : count($files) + 1;
     // put in the end
     $row->filename = $file['name'];
     $row->resourceid = $pid;
     // Check content
     if (!$row->check()) {
         $this->setError($row->getError());
         $this->displayTask($pid, $version);
         return;
     }
     // Build the path
     include_once PATH_CORE . DS . 'components' . DS . 'com_resources' . DS . 'helpers' . DS . 'html.php';
     $listdir = \Components\Resources\Helpers\Html::build_path($resource->created, $pid, '');
     $listdir .= DS . $vid;
     $path = $this->_buildUploadPath($listdir, '');
     // Make sure the upload path exist
     if (!is_dir($path)) {
         if (!Filesystem::makeDirectory($path)) {
             $this->setError(Lang::txt('COM_TOOLS_UNABLE_TO_CREATE_UPLOAD_PATH') . $path);
             $this->displayTask($pid, $version);
             return;
         }
     }
     // Perform the upload
     if (!\Filesystem::upload($file['tmp_name'], $path . DS . $file['name'])) {
         $this->setError(Lang::txt('COM_TOOLS_ERROR_UPLOADING'));
     } else {
         // Store new content
         if (!$row->store()) {
             $this->setError($row->getError());
             $this->displayTask($pid, $version);
             return;
         }
         if (!$row->id) {
             $row->id = $row->insertid();
         }
         // Create thumbnail
         $ss_height = intval($this->config->get('screenshot_maxheight', 58)) > 30 ? intval($this->config->get('screenshot_maxheight', 58)) : 58;
         $ss_width = intval($this->config->get('screenshot_maxwidth', 91)) > 80 ? intval($this->config->get('screenshot_maxwidth', 91)) : 91;
         $tn = \Components\Resources\Helpers\Html::thumbnail($file['name']);
         if ($file_ext != '.swf') {
             $this->_createThumb($path . DS . $file['name'], $ss_width, $ss_height, $path, $tn);
         } else {
             //$this->_createAnimThumb($path . DS . $file['name'], $ss_width, $ss_height, $path, $tn);
         }
     }
     // Store new content
     if (!$row->store()) {
         $this->setError($row->getError());
         $this->displayTask($pid, $version);
         return;
     }
     $this->_rid = $pid;
     // Push through to the screenshot view
     $this->displayTask($pid, $version);
 }
Exemple #21
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']);
 }
Exemple #22
0
 /**
  * Get a resource based on tool name
  *
  * @apiMethod GET
  * @apiUri    /members/{id}/tools/diskusage
  * @apiParameter {
  * 		"name":        "id",
  * 		"description": "Member identifier",
  * 		"type":        "integer",
  * 		"required":    true,
  * 		"default":     null
  * }
  * @return  void
  */
 public function diskusageTask()
 {
     $this->requiresAuthentication();
     $userid = App::get('authn')['user_id'];
     $result = User::getInstance($userid);
     if ($result === false) {
         throw new Exception(Lang::txt('COM_MEMBERS_ERROR_USER_NOT_FOUND'), 404);
     }
     require_once Component::path('com_tools') . DS . 'helpers' . DS . 'utils.php';
     $du = \Components\Tools\Helpers\Utils::getDiskUsage($result->get('username'));
     if (count($du) <= 1) {
         // Error
         $percent = 0;
     } else {
         bcscale(6);
         $val = isset($du['softspace']) && $du['softspace'] != 0 ? bcdiv($du['space'], $du['softspace']) : 0;
         $percent = round($val * 100);
     }
     $amt = $percent > 100 ? '100' : $percent;
     $total = isset($du['softspace']) ? $du['softspace'] / 1024000000 : 0;
     // Encode sessions for return
     $object = new stdClass();
     $object->amount = $amt;
     $object->total = $total;
     $this->send($object);
 }
Exemple #23
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;
 }
Exemple #24
0
 /**
  * Return tool access
  *
  * @param	$tool	Tool name we are getting access rights to
  * @param	$login	User Login name
  *
  * @return     BOOL
  */
 public static function getToolAccess($tool, $login = '')
 {
     //include tool models
     include_once dirname(__DIR__) . DS . 'tables' . DS . 'tool.php';
     include_once dirname(__DIR__) . DS . 'tables' . DS . 'group.php';
     include_once dirname(__DIR__) . DS . 'tables' . DS . 'version.php';
     //instantiate objects
     $access = new stdClass();
     $access->error = new stdClass();
     $database = \App::get('db');
     // Ensure we have a tool
     if (!$tool) {
         $access->valid = 0;
         $access->error->message = 'No tool provided.';
         \Log::debug("mw::_getToolAccess({$tool},{$login}) FAILED null tool check");
         return $access;
     }
     // Ensure we have a login
     if ($login == '') {
         $login = User::get('username');
         if ($login == '') {
             $access->valid = 0;
             $access->error->message = 'Unable to grant tool access to user, no user was found.';
             \Log::debug("mw::_getToolAccess({$tool},{$login}) FAILED null user check");
             return $access;
         }
     }
     //load tool version
     $toolVersion = new \Components\Tools\Tables\Version($database);
     $toolVersion->loadFromInstance($tool);
     if (empty($toolVersion)) {
         $access->valid = 0;
         $access->error->message = 'Unable to load the tool';
         $xlog->debug("mw::_getToolAccess({$tool},{$login}) FAILED null tool version check");
         return $access;
     }
     //load the tool groups
     $toolGroup = new \Components\Tools\Tables\Group($database);
     $query = "SELECT * FROM " . $toolGroup->getTableName() . " WHERE toolid=" . $toolVersion->toolid;
     $database->setQuery($query);
     $toolgroups = $database->loadObjectList();
     //get users groups
     $xgroups = \Hubzero\User\Helper::getGroups(User::get('id'), 'members');
     // Check if the user is in any groups for this app
     $ingroup = false;
     $groups = array();
     $indevgroup = false;
     if ($xgroups) {
         foreach ($xgroups as $xgroup) {
             $groups[] = $xgroup->cn;
         }
         if ($toolgroups) {
             foreach ($toolgroups as $toolgroup) {
                 if (in_array($toolgroup->cn, $groups)) {
                     $ingroup = true;
                     if ($toolgroup->role == 1) {
                         $indevgroup = true;
                     }
                 }
             }
         }
     }
     //check to see if we are an admin
     $admin = false;
     $ctconfig = Component::params('com_tools');
     if ($ctconfig->get('admingroup') != '' && in_array($ctconfig->get('admingroup'), $groups)) {
         $admin = true;
     }
     //get access settings
     $exportAllowed = \Components\Tools\Helpers\Utils::getToolExportAccess($toolVersion->exportControl);
     $isToolPublished = $toolVersion->state == 1;
     $isToolDev = $toolVersion->state == 3;
     $isGroupControlled = $toolVersion->toolaccess == '@GROUP';
     //check for dev tools
     if ($isToolDev) {
         //if were not in the dev group or an admin we must deny
         if (!$indevgroup && !$admin) {
             $access->valid = 0;
             $access->error->message = 'The development version of this tool may only be accessed by members of it\'s development group.';
             \Log::debug("mw::_getToolAccess({$tool},{$login}): DEV TOOL ACCESS DENIED (USER NOT IN DEVELOPMENT OR ADMIN GROUPS)");
         } else {
             $access->valid = 1;
         }
     } else {
         if ($isToolPublished) {
             //are we checking for a group controlled tool
             if ($isGroupControlled) {
                 //if were not in the group that controls it and not admin we must deny
                 if (!$ingroup && !$admin) {
                     $access->valid = 0;
                     $access->error->message = 'This tool may only be accessed by members of it\'s access control groups.';
                     \Log::debug("mw::_getToolAccess({$tool},{$login}): PUBLISHED TOOL ACCESS DENIED (USER NOT IN ACCESS OR ADMIN GROUPS)");
                 } else {
                     $access->valid = 1;
                 }
             } else {
                 if (!$exportAllowed->valid) {
                     $access->valid = 0;
                     $access->error->message = 'Export Access Denied';
                     \Log::debug("mw::_getToolAccess({$tool},{$login}): PUBLISHED TOOL ACCESS DENIED (EXPORT DENIED)");
                 } else {
                     $access->valid = 1;
                 }
             }
         } else {
             $access->valid = 0;
             $access->error->message = 'This tool version is not published.';
             \Log::debug("mw::_getToolAccess({$tool},{$login}): UNPUBLISHED TOOL ACCESS DENIED (TOOL NOT PUBLISHED)");
         }
     }
     //return access
     return $access;
 }
Exemple #25
0
 /**
  * Read SSH key
  *
  * @return string - .ssh/authorized_keys file content
  */
 private function readKey()
 {
     // Webdav path
     $base = DS . 'webdav' . DS . 'home';
     $user = DS . $this->member->get('username');
     $ssh = DS . '.ssh';
     $auth = DS . 'authorized_keys';
     // Real home directory
     $homeDir = $this->member->get('homeDirectory');
     $key = '';
     // First, make sure webdav is there and that the necessary folders are there
     if (!Filesystem::exists($base)) {
         // Not sure what to do here
         return $key = false;
     }
     if (!Filesystem::exists($homeDir)) {
         // Try to create their home directory
         require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'helpers' . DS . 'utils.php';
         if (!\Components\Tools\Helpers\Utils::createHomeDirectory($this->member->get('username'))) {
             return $key = false;
         }
     }
     if (!Filesystem::exists($base . $user . $ssh)) {
         // User doesn't have an ssh directory, so try to create one (with appropriate permissions)
         if (!Filesystem::makeDirectory($base . $user . $ssh, 0700)) {
             return $key = false;
         }
     }
     if (!Filesystem::exists($base . $user . $ssh . $auth)) {
         // Try to create their authorized keys file
         $content = '';
         // J25 passes param by reference so couldn't use constant below
         Filesystem::write($base . $user . $ssh . $auth, $content);
         if (!Filesystem::exists($base . $user . $ssh . $auth)) {
             return $key = false;
         } else {
             // Set correct permissions on authorized_keys file
             JPath::setPermissions($base . $user . $ssh . $auth, '0600');
             return $key;
         }
     }
     // Read the file contents
     $key = Filesystem::read($base . $user . $ssh . $auth);
     return $key;
 }
Exemple #26
0
 /**
  * Short description for 'saveMemberGroups'
  *
  * Long description (if any) ...
  *
  * @param      string $toolid Parameter description (if any) ...
  * @param      array $newgroups Parameter description (if any) ...
  * @param      string $editversion Parameter description (if any) ...
  * @param      array $membergroups Parameter description (if any) ...
  * @return     boolean Return description (if any) ...
  */
 public function saveMemberGroups($toolid = NULL, $newgroups, $editversion = 'dev', $membergroups = array())
 {
     if (!$toolid) {
         return false;
     }
     require_once PATH_CORE . DS . 'components' . DS . 'com_tools' . DS . 'models' . DS . 'tool.php';
     $membergroups = \Components\Tools\Models\Tool::getToolGroups($toolid);
     $membergroups = \Components\Tools\Helpers\Utils::transform($membergroups, 'cn');
     $newgroups = \Components\Tools\Helpers\Utils::transform($newgroups, 'cn');
     $to_delete = array_diff($membergroups, $newgroups);
     if (count($to_delete) > 0 && $editversion != 'current') {
         foreach ($to_delete as $del) {
             $query = "DELETE FROM {$this->_tbl} WHERE cn=" . $this->_db->quote($del) . " AND toolid=" . $this->_db->quote($toolid) . " AND role=0";
             $this->_db->setQuery($query);
             $this->_db->query();
         }
     }
     if (count($newgroups) > 0) {
         foreach ($newgroups as $newgroup) {
             if (\Hubzero\User\Group::exists($newgroup) && !in_array($newgroup, $membergroups)) {
                 // create an entry in tool_groups table
                 $this->save($newgroup, $toolid, '0');
             }
         }
     }
     return true;
 }