/**
  * This method is called immediately after the wrapper is initialized
  *
  * Connects to an SFTP server
  *
  * NOTE: This method is not get called by default for the following functions:
  * dir_opendir(), mkdir(), rename(), rmdir(), stream_metadata(), unlink() and url_stat()
  * So I implemented a call to stream_open() at the beginning of the functions and stream_close() at the end
  *
  * The wrapper will also reuse open connections
  *
  * @param String $path
  * @param String $mode
  * @param Integer $options
  * @param String &$opened_path
  * @return bool
  * @access public
  */
 public function stream_open($path, $mode, $options, &$opened_path)
 {
     $url = parse_url($path);
     $host = $url["host"];
     $port = $url["port"];
     $user = $url["user"];
     $pass = $url["pass"];
     $this->path = $url["path"];
     $connection_uuid = md5($host . $port . $user);
     // Generate a unique ID for the current connection
     if (isset(self::$instances[$connection_uuid])) {
         // Get previously established connection
         $this->sftp = self::$instances[$connection_uuid];
     } else {
         //$context = stream_context_get_options($this->context);
         if (!isset($user) || !isset($pass)) {
             return FALSE;
         }
         // Connection
         $sftp = new Net_SFTP($host, isset($port) ? $port : 22);
         if (!$sftp->login($user, $pass)) {
             return FALSE;
         }
         // Store connection instance
         self::$instances[$connection_uuid] = $sftp;
         // Get current connection
         $this->sftp = $sftp;
     }
     $filesize = $this->sftp->size($this->path);
     if (isset($mode)) {
         $this->mode = preg_replace('#[bt]$#', '', $mode);
     } else {
         $this->mode = 'r';
     }
     switch ($this->mode[0]) {
         case 'r':
             $this->position = 0;
             break;
         case 'w':
             $this->position = 0;
             if ($filesize === FALSE) {
                 $this->sftp->touch($this->path);
             } else {
                 $this->sftp->truncate($this->path, 0);
             }
             break;
         case 'a':
             if ($filesize === FALSE) {
                 $this->position = 0;
                 $this->sftp->touch($this->path);
             } else {
                 $this->position = $filesize;
             }
             break;
         case 'c':
             $this->position = 0;
             if ($filesize === FALSE) {
                 $this->sftp->touch($this->path);
             }
             break;
         default:
             return FALSE;
     }
     if ($options == STREAM_USE_PATH) {
         $opened_path = $this->sftp->pwd();
     }
     return TRUE;
 }