Exemplo n.º 1
0
function escribe_archivo_via_sftp($cadena, $nombre_archivo_remoto = "", $factura_id, $fe_folio)
{
    $sql_update = "update vta_p_facturas set \n\tFE_SERIE='A', FE_FOLIO={$fe_folio}\n\twhere (FE_SERIE = '' OR FE_SERIE IS NULL or FE_SERIE=0) AND (FE_FOLIO = '' OR FE_FOLIO IS NULL or FE_FOLIO =0) \n\tAND FACTURA_ID=" . $factura_id;
    $result_update = mysql_db_query(DB_NAME, $sql_update);
    // echo $sql_update;
    define("TEPath", "../TableEditor/");
    include '../TableEditor/Net/SFTP.php';
    //  $ftp_sitio="demo-partners.xsa.com.mx";
    //  $ftp_usuario="testftpfacciisa";
    //  $ftp_pass="******";
    $ftp_sitio = "173.205.255.84";
    $ftp_usuario = "ftpciisa";
    $ftp_pass = "******";
    $sftp = new Net_SFTP($ftp_sitio);
    if (!$sftp->login($ftp_usuario, $ftp_pass)) {
        exit('Acceso incorrecto..');
    }
    $sftp->put($nombre_archivo_remoto, utf8_encode($cadena));
    $sftp->chdir("1");
    $sftp->put($nombre_archivo_remoto, utf8_encode($cadena));
    $folio_fiscal = consulta("select FOLIO_FISCAL from vta_p_facturas WHERE FACTURA_ID=" . $factura_id);
    $folio_fiscal = $folio_fiscal["FOLIO_FISCAL"];
    //echo $fe_serie["FE_FOLIO"]."+";
    echo "Envio exitoso... Factura " . $folio_fiscal;
}
Exemplo n.º 2
0
 public function getCommand(\Net_SFTP $ssh)
 {
     $gitCommand = str_replace("\n", '', $ssh->exec('which git'));
     if ($gitCommand == '') {
         throw new \Exception('the git command wasn\'t found on this server');
     }
     return $gitCommand;
 }
Exemplo n.º 3
0
 /**
  * copy a file from the remote server to the local install
  * @param $source string
  * @param $destination string
  * @return bool
  */
 public function scpRemoteLocal($source, $destination)
 {
     $sftp = new \Net_SFTP(Setting::getSetting('remote:host'));
     $key = new Crypt_RSA();
     $key->loadKey(file_get_contents(Setting::getSetting('ssh:priv_key')));
     if (!$sftp->login(Setting::getSetting('remote:user'), $key)) {
         $cli = new CLImate();
         $cli->error("Could not connect to server");
         return false;
     }
     $sftp->get($source, $destination);
 }
Exemplo n.º 4
0
function sftp_printer($xml_file)
{
    if (strrpos(get_include_path(), "phpseclib0.3.0") === false) {
        set_include_path(get_include_path() . PATH_SEPARATOR . './phpseclib0.3.0');
        // Staging requires the ../ to be ./
    }
    include 'Net/SFTP.php';
    $rtn = false;
    $sftp = new Net_SFTP('ftp.tginc.com', 2222);
    if (isset($_GET['tID'])) {
        echo $sftp->login('flatterbox', 'T&!Fl@!!er');
    }
    //if ( isset($_GET['tID']) ) : print_r( $sftp->getSupportedVersions() ); endif;
    if (!$sftp->login('flatterbox', 'T&!Fl@!!er') || true) {
        $rtn = 'Login Failed';
    }
    $local_directory = './orderlist/';
    // Set in previous function -- orderlist/';
    $remote_directory = '/incoming/';
    //echo $local_directory.'<br/>';
    //echo $remote_directory.'<br/>';
    $files_to_upload = array();
    if ($xml_file != "." && $xml_file != "..") {
        $files_to_upload[] = $xml_file;
    }
    if (!empty($files_to_upload) && $rtn == false) {
        foreach ($files_to_upload as $file) {
            /*
            echo dirname(__FILE__).'<br/>';
            echo $file.'<br/>';
            echo $local_directory . $file.'<br/>';
            */
            //$rtn = $sftp->put($remote_directory . $file, $local_directory . $file, NET_SFTP_LOCAL_FILE);
            $data = file_get_contents($local_directory . $file);
            if (isset($_GET['tID'])) {
                echo $data;
            }
            $rtn = $sftp->put($remote_directory . $file, $data);
        }
    }
    return $rtn;
    /*
    	$conn = ssh2_connect('ftp.tginc.com', 2222);
    	ssh2_auth_password($conn, 'flatterbox', 'T&!Fl@!!er');
    
    	// send a file
    	return ssh2_scp_send($conn, $local_directory.$xml_file, $remote_directory.$xml_file, 0644);
    */
}
Exemplo n.º 5
0
 public function connect()
 {
     // we have to mangle the include path a little to find our plugins
     $oldIncludePath = get_include_path();
     set_include_path($oldIncludePath . ':' . TL_ROOT . '/plugins/phpseclib/:' . TL_ROOT . '/plugins/phpseclib/Net:' . TL_ROOT . '/plugins/phpseclib/Crypt');
     include 'SFTP.php';
     if ($GLOBALS['TL_CONFIG']['sftpKeyFile']) {
         include 'RSA.php';
     }
     set_include_path($oldIncludePath);
     $this->ftpHost = $GLOBALS['TL_CONFIG']['ftpHost'];
     $this->ftpPort = $GLOBALS['TL_CONFIG']['ftpPort'];
     $this->ftpUser = $GLOBALS['TL_CONFIG']['ftpUser'];
     if ($GLOBALS['TL_CONFIG']['sftpKeyFile']) {
         $key = new Crypt_RSA();
         if ($GLOBALS['TL_CONFIG']['sftpKeyPass']) {
             $key->setPassword($GLOBALS['TL_CONFIG']['sftpKeyPass']);
         }
         $key->loadKey(file_get_contents($GLOBALS['TL_CONFIG']['sftpKeyFile']));
         $this->ftpPass = $key;
     } else {
         $this->ftpPass = $GLOBALS['TL_CONFIG']['ftpPass'];
     }
     $this->ftpPath = $GLOBALS['TL_CONFIG']['ftpPath'];
     // Connect to FTP server
     if (!is_numeric($this->ftpPort) || $this->ftpPort == 0) {
         $this->ftpPort = 22;
     }
     if ($GLOBALS['TL_CONFIG']['debugSmhExtended']) {
         define('NET_SSH2_LOGGING', true);
         define('NET_SFTP_LOGGING', true);
     }
     if (($resConnection = new Net_SFTP($this->ftpHost, $this->ftpPort, 5)) != false) {
         // Login
         if (!$resConnection->login($this->ftpUser, $this->ftpPass)) {
             throw new Exception('Could not login to sftp: ' . $resConnection->getLastError() . (defined('NET_SSH2_LOGGING') ? implode("\n", $resConnection->message_number_log) : ''));
         }
         // security, clean user id and password as we won't need them anymore.
         $this->ftpUser = NULL;
         $this->ftpPass = NULL;
         // change to root directory to ensure we can really work.
         $resConnection->chdir($this->ftpPath);
         $this->resConnection = $resConnection;
         return $resConnection;
     } else {
         throw new Exception('Could not connect to sftp: ' . $resConnection->getLastError());
     }
 }
Exemplo n.º 6
0
 /**
  * get a file
  *
  * @param String $source_file      the target file to download
  * @param bool   $destination_file the save path
  *
  * @return String
  * @throws CMbException
  */
 private function _getFile($source_file, $destination_file = false)
 {
     if (!$this->connexion) {
         throw new CMbException("CSourceSFTP-connexion-failed", $this->hostname);
     }
     // Download the file
     if (!($data = $this->connexion->get($source_file, $destination_file))) {
         throw new CMbException("CSourceSFTP-download-file-failed", $source_file, $destination_file);
     }
     return $data;
 }
Exemplo n.º 7
0
 public function stat($path)
 {
     try {
         $stat = $this->client->stat($this->absPath($path));
         $mtime = $stat ? $stat['mtime'] : -1;
         $size = $stat ? $stat['size'] : 0;
         return array('mtime' => $mtime, 'size' => $size, 'ctime' => -1);
     } catch (\Exception $e) {
         return false;
     }
 }
Exemplo n.º 8
0
 /**
  * Login to the SFTP service.
  *
  * @throws ServiceException
  *   Whe we can't login to the SFTP server.
  */
 protected function login()
 {
     if ($this->loggedIn) {
         return true;
     }
     $result = $this->sftp->login($this->getUsername(), $this->getPassword());
     if (!$result) {
         throw new ServiceException(sprintf('Can\'t login with user "%s".', $this->getUsername()));
     }
     $this->loggedIn = true;
 }
Exemplo n.º 9
0
 /**
  * @param array $config
  *
  * @throws Mageplace_Backup_Exception|Mage_Core_Exception
  * @return Net_SFTP
  */
 public function getSftp(array $config = array())
 {
     if ($this->_getData('sftp') === null) {
         $host = $this->getConfigValue(self::HOST);
         $port = (int) $this->getConfigValue(self::PORT);
         if ($port <= 0) {
             $port = self::DEFAULT_PORT;
         }
         $sftp = new Net_SFTP($host, $port, $this->getTimeOut());
         if (!$sftp->login($this->getConfigValue(self::USERNAME), $this->getConfigValue(self::PASSWORD))) {
             $this->_throwExeption($this->_helper->__("SFTP connection error: unable to open connection as %s@%s:%d", $this->getConfigValue(self::USERNAME), $host, $port));
         }
         if ($path = rtrim($this->getConfigValue(self::PATH), '/')) {
             if (!$sftp->chdir($path)) {
                 $this->_throwExeption($this->_helper->__('SFTP connection error: invalid path'));
             }
         }
         $this->setData('sftp', $sftp);
     }
     return $this->_getData('sftp');
 }
Exemplo n.º 10
0
 /**
  * @param \Cogeco\Build\Entity\Host $host
  * @return \Net_SFTP
  * @throws \Cogeco\Build\Exception
  */
 public static function connect(Host $host)
 {
     // Throw an exception if no host is provided
     if (empty($host)) {
         throw new Exception(__METHOD__ . "() No host specified");
     }
     // If the connection doesn't already exist, create it
     if (empty(self::$handles[$host->hostname])) {
         self::log("- Starting an SSH session on {$host->hostname} for user {$host->account->username}\n\n");
         self::$handles[$host->hostname] = $handle = new \Net_SFTP($host->hostname);
         if (!$handle->login($host->account->username, $host->account->password)) {
             throw new Exception(__METHOD__ . '() SSH connection failed');
         }
         // Set the home folder, if it isn't explicitly set already
         $homeDirPath = $handle->pwd();
         if (empty($host->homeDirPath) && !empty($homeDirPath)) {
             $host->homeDirPath = $homeDirPath;
         }
     }
     return self::$handles[$host->hostname];
 }
Exemplo n.º 11
0
 /**
  * Returns the connection.
  *
  * @return \Net_SFTP connected client instance
  * @throws \Exception when the connection failed
  */
 public function getConnection()
 {
     if (!is_null($this->client)) {
         return $this->client;
     }
     $hostKeys = $this->readHostKeys();
     $this->client = new \Net_SFTP($this->host);
     // The SSH Host Key MUST be verified before login().
     $currentHostKey = $this->client->getServerPublicHostKey();
     if (array_key_exists($this->host, $hostKeys)) {
         if ($hostKeys[$this->host] != $currentHostKey) {
             throw new \Exception('Host public key does not match known key');
         }
     } else {
         $hostKeys[$this->host] = $currentHostKey;
         $this->writeHostKeys($hostKeys);
     }
     if (!$this->client->login($this->user, $this->password)) {
         throw new \Exception('Login failed');
     }
     return $this->client;
 }
Exemplo n.º 12
0
 /**
  * @param $command
  *
  * @return string
  */
 public function exec($command)
 {
     $sftpDir = $this->pwd();
     switch ($this->_connType) {
         case SftpHelper::TYPE_SFTP:
         default:
             $execOutput = $this->_connection->exec('cd ' . $sftpDir . ' && ' . $command);
             $this->_lastExecExitStatus = $this->_connection->getExitStatus();
             break;
         case SftpHelper::TYPE_FTP:
             // TODO: test ftp_exec on a server which supports it
             $execOutput = '';
             $res = @ftp_exec($this->_connection, 'cd ' . $sftpDir . ' && ' . $command);
             $this->_lastExecExitStatus = $res ? 0 : 1;
             break;
     }
     return $execOutput;
 }
Exemplo n.º 13
0
 /**
  * Notify about config changes.
  */
 public function notifyConfigChange()
 {
     $host = $this->config->get(FilesystemConfig::HOST);
     $port = $this->config->get(FilesystemConfig::PORT);
     $username = $this->config->get(FilesystemConfig::USERNAME);
     $password = $this->config->get(FilesystemConfig::PASSWORD);
     $key = $this->config->get(self::CONFIG_KEY);
     $keyFile = $this->config->get(self::CONFIG_KEY_FILE);
     $basepath = $this->config->get('/' . FilesystemConfig::BASEPATH);
     if ($basepath) {
         $basepath = Util::normalizePath($basepath);
     }
     $connectUrl = $username;
     if ($keyFile) {
         $connectUrl .= ':' . crypt($keyFile . $password);
     } else {
         if ($key) {
             $connectUrl .= ':' . crypt($key . $password);
         } else {
             if ($password) {
                 $connectUrl .= ':' . crypt($password);
             }
         }
     }
     $connectUrl .= '@' . $host;
     if ($port) {
         $connectUrl .= ':' . $port;
     }
     $connectUrl .= $basepath;
     if ($this->connectionURL != $connectUrl) {
         if ($this->connection) {
             $this->connection->disconnect();
             $this->connection = null;
         }
         $this->connectionURL = $connectUrl;
     }
 }
Exemplo n.º 14
0
 public function rawls()
 {
     $list = $this->_connection->rawlist();
     return $list;
 }
Exemplo n.º 15
0
        pb_backupbuddy::alert(__('No backups were deleted.', 'it-l10n-backupbuddy'));
    }
    echo '<br>';
}
// Connect to server.
$server = $destination['address'];
$port = '22';
// Default sFTP port.
if (strstr($server, ':')) {
    // Handle custom sFTP port.
    $server_params = explode(':', $server);
    $server = $server_params[0];
    $port = $server_params[1];
}
pb_backupbuddy::status('details', 'Connecting to sFTP server...');
$sftp = new Net_SFTP($server, $port);
if (!$sftp->login($destination['username'], $destination['password'])) {
    pb_backupbuddy::status('error', 'Connection to sFTP server FAILED.');
    return false;
} else {
    pb_backupbuddy::status('details', 'Success connecting to sFTP server.');
}
pb_backupbuddy::status('details', 'Attempting to create path (if it does not exist)...');
if (true === $sftp->mkdir($destination['path'])) {
    // Try to make directory.
    pb_backupbuddy::status('details', 'Directory created.');
} else {
    pb_backupbuddy::status('details', 'Directory not created.');
}
// List files.
$files = $sftp->rawlist($destination['path']);
Exemplo n.º 16
0
/**
 * Poll all eligible labs for new results and store them in the database.
 *
 * @param  array   &$info  Conveys information to and from the caller:
 * FROM THE CALLER:
 * $info["$ppid/$filename"]['delete'] = a non-empty value if file deletion is requested.
 * $info['select'] = array of patient matching responses where key is serialized patient
 *   attributes and value is selected pid for this patient, or 0 to create the patient.
 * TO THE CALLER:
 * $info["$ppid/$filename"]['mssgs'] = array of messages from this function.
 * $info['match'] = array of patient matching requests where key is serialized patient
 *   attributes (ss, fname, lname, DOB) and value is TRUE (irrelevant).
 *
 * @return string  Error text, or empty if no errors.
 */
function poll_hl7_results(&$info)
{
    global $srcdir;
    // echo "<!-- post: "; print_r($_POST); echo " -->\n"; // debugging
    // echo "<!-- in:   "; print_r($info); echo " -->\n"; // debugging
    $filecount = 0;
    $badcount = 0;
    if (!isset($info['match'])) {
        $info['match'] = array();
    }
    // match requests
    if (!isset($info['select'])) {
        $info['select'] = array();
    }
    // match request responses
    $ppres = sqlStatement("SELECT * FROM procedure_providers ORDER BY name");
    while ($pprow = sqlFetchArray($ppres)) {
        $ppid = $pprow['ppid'];
        $protocol = $pprow['protocol'];
        $remote_host = $pprow['remote_host'];
        $hl7 = '';
        if ($protocol == 'SFTP') {
            $remote_port = 22;
            // Hostname may have ":port" appended to specify a nonstandard port number.
            if ($i = strrpos($remote_host, ':')) {
                $remote_port = 0 + substr($remote_host, $i + 1);
                $remote_host = substr($remote_host, 0, $i);
            }
            ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "{$srcdir}/phpseclib");
            require_once "{$srcdir}/phpseclib/Net/SFTP.php";
            // Compute the target path name.
            $pathname = '.';
            if ($pprow['results_path']) {
                $pathname = $pprow['results_path'] . '/' . $pathname;
            }
            // Connect to the server and enumerate files to process.
            $sftp = new Net_SFTP($remote_host, $remote_port);
            if (!$sftp->login($pprow['login'], $pprow['password'])) {
                return xl('Login to remote host') . " '{$remote_host}' " . xl('failed');
            }
            $files = $sftp->nlist($pathname);
            foreach ($files as $file) {
                if (substr($file, 0, 1) == '.') {
                    continue;
                }
                ++$filecount;
                if (!isset($info["{$ppid}/{$file}"])) {
                    $info["{$ppid}/{$file}"] = array();
                }
                // Ensure that archive directory exists.
                $prpath = $GLOBALS['OE_SITE_DIR'] . "/procedure_results";
                if (!file_exists($prpath)) {
                    mkdir($prpath);
                }
                $prpath .= '/' . $pprow['ppid'];
                if (!file_exists($prpath)) {
                    mkdir($prpath);
                }
                // Get file contents.
                $hl7 = $sftp->get("{$pathname}/{$file}");
                // If user requested reject and delete, do that.
                if (!empty($info["{$ppid}/{$file}"]['delete'])) {
                    $fh = fopen("{$prpath}/{$file}.rejected", 'w');
                    if ($fh) {
                        fwrite($fh, $hl7);
                        fclose($fh);
                    } else {
                        return xl('Cannot create file') . ' "' . "{$prpath}/{$file}.rejected" . '"';
                    }
                    if (!$sftp->delete("{$pathname}/{$file}")) {
                        return xl('Cannot delete (from SFTP server) file') . ' "' . "{$pathname}/{$file}" . '"';
                    }
                    continue;
                }
                // Do a dry run of its contents and check for errors and match requests.
                $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']);
                $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs'];
                // $info["$ppid/$file"]['match'] = $tmp['match'];
                if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) {
                    // There are errors or matching requests so skip this file.
                    continue;
                }
                // Now the money shot - not a dry run.
                $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']);
                $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs'];
                // $info["$ppid/$file"]['match'] = $tmp['match'];
                if (empty($tmp['fatal']) && empty($tmp['needmatch'])) {
                    // It worked, archive and delete the file.
                    $fh = fopen("{$prpath}/{$file}", 'w');
                    if ($fh) {
                        fwrite($fh, $hl7);
                        fclose($fh);
                    } else {
                        return xl('Cannot create file') . ' "' . "{$prpath}/{$file}" . '"';
                    }
                    if (!$sftp->delete("{$pathname}/{$file}")) {
                        return xl('Cannot delete (from SFTP server) file') . ' "' . "{$pathname}/{$file}" . '"';
                    }
                }
            }
            // end of this file
        } else {
            if ($protocol == 'FS') {
                // Filesystem directory containing results files.
                $pathname = $pprow['results_path'];
                if (!($dh = opendir($pathname))) {
                    return xl('Unable to access directory') . " '{$pathname}'";
                }
                // Sort by filename just because.
                $files = array();
                while (false !== ($file = readdir($dh))) {
                    if (substr($file, 0, 1) == '.') {
                        continue;
                    }
                    $files[$file] = $file;
                }
                closedir($dh);
                ksort($files);
                // For each file...
                foreach ($files as $file) {
                    ++$filecount;
                    if (!isset($info["{$ppid}/{$file}"])) {
                        $info["{$ppid}/{$file}"] = array();
                    }
                    // Ensure that archive directory exists.
                    $prpath = $GLOBALS['OE_SITE_DIR'] . "/procedure_results";
                    if (!file_exists($prpath)) {
                        mkdir($prpath);
                    }
                    $prpath .= '/' . $pprow['ppid'];
                    if (!file_exists($prpath)) {
                        mkdir($prpath);
                    }
                    // Get file contents.
                    $hl7 = file_get_contents("{$pathname}/{$file}");
                    // If user requested reject and delete, do that.
                    if (!empty($info["{$ppid}/{$file}"]['delete'])) {
                        $fh = fopen("{$prpath}/{$file}.rejected", 'w');
                        if ($fh) {
                            fwrite($fh, $hl7);
                            fclose($fh);
                        } else {
                            return xl('Cannot create file') . ' "' . "{$prpath}/{$file}.rejected" . '"';
                        }
                        if (!unlink("{$pathname}/{$file}")) {
                            return xl('Cannot delete file') . ' "' . "{$pathname}/{$file}" . '"';
                        }
                        continue;
                    }
                    // Do a dry run of its contents and check for errors and match requests.
                    $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], true, $info['select']);
                    $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs'];
                    // $info["$ppid/$file"]['match'] = $tmp['match'];
                    if (!empty($tmp['fatal']) || !empty($tmp['needmatch'])) {
                        // There are errors or matching requests so skip this file.
                        continue;
                    }
                    // Now the money shot - not a dry run.
                    $tmp = receive_hl7_results($hl7, $info['match'], $ppid, $pprow['direction'], false, $info['select']);
                    $info["{$ppid}/{$file}"]['mssgs'] = $tmp['mssgs'];
                    // $info["$ppid/$file"]['match'] = $tmp['match'];
                    if (empty($tmp['fatal']) && empty($tmp['needmatch'])) {
                        // It worked, archive and delete the file.
                        $fh = fopen("{$prpath}/{$file}", 'w');
                        if ($fh) {
                            fwrite($fh, $hl7);
                            fclose($fh);
                        } else {
                            return xl('Cannot create file') . ' "' . "{$prpath}/{$file}" . '"';
                        }
                        if (!unlink("{$pathname}/{$file}")) {
                            return xl('Cannot delete file') . ' "' . "{$pathname}/{$file}" . '"';
                        }
                    }
                }
                // end of this file
            }
        }
        // end FS protocol
        // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols.
    }
    // end procedure provider
    // echo "<!-- out: "; print_r($info); echo " -->\n"; // debugging
    return '';
}
	//$to = "*****@*****.**";
	$subject =  "[Important] Encryption Failed for ".$recipient." Weekly Appointment Summary";
	mail($to,$subject,$msg);

	exit(0);
}*/
//if(file_exists($encryptedFileName))
if (file_exists($localfilename)) {
    include "Net/SFTP.php";
    $ftp_server = 'PDCFTP.cvty.com';
    $ftp_user = '******';
    $ftp_password = '******';
    $ftp_port = '21000';
    $ftp_directory = '/Incoming/';
    //'/Test/Incoming/'
    $sftp = new Net_SFTP($ftp_server, $ftp_port);
    // FTP Login
    if ($sftp->login($ftp_user, $ftp_password)) {
        // Change directory
        if ($sftp->chdir($ftp_directory)) {
            if ($sftp->put($remoteFileName, $localfilename, NET_SFTP_LOCAL_FILE)) {
                $destFileName = str_replace('C:\\Inetpub\\wwwroot\\plexis\\php\\', 'D:\\Documents\\Misc\\' . $clientName . "_", $savePathAndFileName);
                //echo "destFileName:  ".$destFileName."\n";
                //echo "localfilename:  ".$localfilename."\n";
                //echo "remoteFileName:  ".$remoteFileName."\n";
                if (file_exists($destFileName)) {
                    unlink($destFileName);
                }
                rename($localfilename, $destFileName);
            } else {
                $msg = "Unable to put " . $localfilename . " file to [" . $ftp_server . "] /" . $ftp_directory . "/" . $remoteFileName . "<br/>";
Exemplo n.º 18
0
 public function createSFTPSession()
 {
     $sftp_url = $this->config['batch_url'];
     $sftp_username = $this->config['sftp_username'];
     $sftp_password = $this->config['sftp_password'];
     $session = new \Net_SFTP($sftp_url);
     if (!$session->login($sftp_username, $sftp_password)) {
         throw new \RuntimeException("Failed to SFTP with the username {$sftp_username} and the password {$sftp_password} to the host {$sftp_url}. Check your credentials!");
     }
     return $session;
 }
Exemplo n.º 19
0
 $mail->Body = "U prilogu je izvestaj o storno stavkama u txt formatu";
 //HTML Body
 $mail->AltBody = "AltBody - U prilogu je izvestaj o storno stavkama u txt formatu";
 // optional, comment out and test
 $mail->WordWrap = 50;
 // set word wrap
 //$mail->MsgHTML($body);
 // send email
 //$mail = mail($to,$subject,$message,$header);
 if (!$mail->Send()) {
     echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
     echo "Message sent!";
 }
 //unlink('/tmp/kontakti.txt');
 $sftp = new Net_SFTP('podrska.bbtrade.rs');
 if (!$sftp->login('root', 'bbsb100$')) {
     echo "Login Failed";
     exit('Login Failed');
 }
 // outputs the contents of filename.remote to the screen
 //echo $sftp->get('/tmp/kontakti.txt');
 // copies filename.remote to filename.local from the SFTP server
 //$sftp->get('/tmp/kontakti.txt', '\\C$\Users\%username%\Desktop\kontakti.txt');
 $sftp->get('/tmp/izvestaj.csv', '/cygdrive/c/storno/izvestaj.txt');
 //ssh2.sftp://{$resSFTP}/cygdrive/c/to/path
 if ($sftp->delete('/tmp/izvestaj.csv')) {
     // doesn't delete directories
     echo "File /tmp/izvestaj.csv je obrisan!";
 } else {
     echo "File /tmp/izvestaj.csv nije obrisan!";
Exemplo n.º 20
0
 public function downloadFromFulfillment()
 {
     $arrayCsvFiles = array();
     $arrayCsvFilesClear = array();
     $sql = "SELECT *\n                FROM `fulfillment_files`\n                WHERE `fulfillment_id`=?i";
     $result = self::$_msql->getInd('filename', $sql, $this->fulfillment_id);
     if ($this->ssl) {
         $sftp = new Net_SFTP($this->server);
         if (!$sftp->login($this->username, $this->password)) {
             exit('Login Failed');
         }
         //$contents = $sftp->nlist("{$this->download_path}");
         $dPath = trim($this->download_path, '/');
         $contents = $sftp->nlist("{$dPath}");
         if (!$contents) {
             return;
         }
         foreach ($contents as $file) {
             if (substr($file, -4, 4) == '.csv') {
                 $arrayCsvFiles[] = $arrayCsvFilesClear[] = $file;
             }
         }
         foreach ($arrayCsvFiles as $file) {
             $tF = explode('/', $file);
             $fName = array_pop($tF);
             if (isset($result["{$fName}"])) {
                 continue;
             }
             $downloadFilePath = AF::path(time() . rand(1, 1000), array('files', 'csv', 'temp'), 'csv');
             if ($sftp->get($dPath . '/' . $file, $downloadFilePath)) {
                 self::parserCsvFiles($downloadFilePath);
                 $sql = "INSERT INTO `fulfillment_files` (`fulfillment_id`, `filename`, `time`) VALUES (?i, ?s, NOW())";
                 self::$_msql->query($sql, $this->fulfillment_id, $fName);
             }
         }
         $sftp->_disconnect(0);
     } else {
         $ftp = ftp_connect($this->server, $this->port, 300);
         if (!$ftp) {
             return;
         }
         if ($this->username && $this->password) {
             ftp_login($ftp, $this->username, $this->password);
         }
         ftp_pasv($ftp, true);
         // Passive mode
         $contents = ftp_nlist($ftp, "{$this->download_path}");
         if (!$contents) {
             return;
         }
         foreach ($contents as $file) {
             if (substr($file, -4, 4) == '.csv') {
                 $file = str_replace('\\', '/', $file);
                 $arrayCsvFiles[] = $file;
                 $tF = explode('/', $file);
                 $arrayCsvFilesClear[] = (string) trim(array_pop($tF));
             }
         }
         foreach ($arrayCsvFiles as $file) {
             $tF = explode('/', $file);
             $fName = (string) trim(array_pop($tF));
             if (isset($result["{$fName}"])) {
                 continue;
             }
             $downloadFilePath = AF::path(time() . rand(1, 1000), array('files', 'csv', 'temp'), 'csv');
             if (ftp_get($ftp, $downloadFilePath, $file, FTP_ASCII)) {
                 self::parserCsvFiles($downloadFilePath);
                 $sql = "INSERT INTO `fulfillment_files` (`fulfillment_id`, `filename`, `time`) VALUES (?i, ?s, NOW())";
                 self::$_msql->query($sql, $this->fulfillment_id, $fName);
             }
         }
         ftp_close($ftp);
     }
     $sql = "DELETE FROM `fulfillment_files`\n                WHERE `fulfillment_id` = ?i\n                AND `filename` NOT IN (?a)";
     self::$_msql->query($sql, $this->fulfillment_id, $arrayCsvFilesClear);
 }
Exemplo n.º 21
0
 public function dataPush($date = '2014-12-14 00:00:00')
 {
     $res = array();
     $dstFile = "iff_data_production/test_data.json";
     $fileContents = "test content";
     // set up basic connection
     $domain = "sftp.tiger.jba-processing.com";
     try {
         $sftp = new Net_SFTP($domain);
         if ($sftp->login('tiger_mccann', 'fsJcBsuepHMVrYrY')) {
             $sftp->put($dstFile, $fileContents);
             var_dump($sftp->size($dstFile));
             var_dump($sftp->size('nonexistant.json'));
         }
     } catch (Exception $e) {
         var_dump($e);
     }
     echo $sftp->getSFTPLog();
     return;
 }
Exemplo n.º 22
0
 function get_ftp_backup($args, $current_file_num = 0)
 {
     extract($args);
     if (isset($use_sftp) && $use_sftp == 1) {
         $port = $ftp_port ? $ftp_port : 22;
         //default port is 22
         /*
          * SFTP section start here phpseclib library is used for this functionality
          */
         $iwp_mmb_plugin_dir = WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__));
         $path = $iwp_mmb_plugin_dir . '/lib/phpseclib';
         set_include_path(get_include_path() . PATH_SEPARATOR . $path);
         include_once 'Net/SFTP.php';
         $sftp = new Net_SFTP($ftp_hostname, $port);
         if (!$sftp) {
             return array('error' => 'Failed to connect to ' . $ftp_hostname, 'partial' => 1);
         }
         if (!$sftp->login($ftp_username, $ftp_password)) {
             return array('error' => 'FTP login failed for ' . $ftp_username . ', ' . $ftp_password, 'partial' => 1);
         } else {
             if ($ftp_site_folder) {
                 $ftp_remote_folder .= '/' . $this->site_name;
             }
             $remote_loation = basename($backup_file);
             $local_location = $backup_file;
             $sftp->chdir($ftp_remote_folder);
             //$sftp->delete(basename($backup_file));
             $temp = wp_tempnam('iwp_temp_backup.zip');
             $get = $sftp->get(basename($backup_file), $temp);
             if ($get === false) {
                 return false;
             } else {
                 return $temp;
             }
             //SFTP library has automatic connection closed. So no need to call seperate connection close function
         }
     } else {
         //Args: $ftp_username, $ftp_password, $ftp_hostname, $backup_file, $ftp_remote_folder
         $port = $ftp_port ? $ftp_port : 21;
         //default port is 21
         if ($ftp_ssl && function_exists('ftp_ssl_connect')) {
             $conn_id = ftp_ssl_connect($ftp_hostname, $port);
         } else {
             if (function_exists('ftp_connect')) {
                 $conn_id = ftp_connect($ftp_hostname, $port);
                 if ($conn_id === false) {
                     return false;
                 }
             }
         }
         $login = @ftp_login($conn_id, $ftp_username, $ftp_password);
         if ($login === false) {
             return false;
         }
         if ($ftp_site_folder) {
             $ftp_remote_folder .= '/' . $this->site_name;
         }
         if ($ftp_passive) {
             @ftp_pasv($conn_id, true);
         }
         //$temp = ABSPATH . 'iwp_temp_backup.zip';
         $temp = wp_tempnam('iwp_temp_backup.zip');
         $get = ftp_get($conn_id, $temp, $ftp_remote_folder . '/' . $backup_file, FTP_BINARY);
         if ($get === false) {
             return false;
         } else {
         }
         ftp_close($conn_id);
         return $temp;
     }
 }
Exemplo n.º 23
0
/**
 * Poll all eligible labs for new results and store them in the database.
 *
 * @param  array   &$messages  Receives messages of interest.
 * @return string  Error text, or empty if no errors.
 */
function poll_hl7_results(&$messages)
{
    global $srcdir;
    $messages = array();
    $filecount = 0;
    $badcount = 0;
    $ppres = sqlStatement("SELECT * FROM procedure_providers ORDER BY name");
    while ($pprow = sqlFetchArray($ppres)) {
        $protocol = $pprow['protocol'];
        $remote_host = $pprow['remote_host'];
        $hl7 = '';
        if ($protocol == 'SFTP') {
            ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "{$srcdir}/phpseclib");
            require_once "{$srcdir}/phpseclib/Net/SFTP.php";
            // Compute the target path name.
            $pathname = '.';
            if ($pprow['results_path']) {
                $pathname = $pprow['results_path'] . '/' . $pathname;
            }
            // Connect to the server and enumerate files to process.
            $sftp = new Net_SFTP($remote_host);
            if (!$sftp->login($pprow['login'], $pprow['password'])) {
                return xl('Login to remote host') . " '{$remote_host}' " . xl('failed');
            }
            $files = $sftp->nlist($pathname);
            foreach ($files as $file) {
                if (substr($file, 0, 1) == '.') {
                    continue;
                }
                ++$filecount;
                $hl7 = $sftp->get("{$pathname}/{$file}");
                // Archive the results file.
                $prpath = $GLOBALS['OE_SITE_DIR'] . "/procedure_results";
                if (!file_exists($prpath)) {
                    mkdir($prpath);
                }
                $prpath .= '/' . $pprow['ppid'];
                if (!file_exists($prpath)) {
                    mkdir($prpath);
                }
                $fh = fopen("{$prpath}/{$file}", 'w');
                if ($fh) {
                    fwrite($fh, $hl7);
                    fclose($fh);
                } else {
                    $messages[] = xl('File') . " '{$file}' " . xl('cannot be archived, ignored');
                    ++$badcount;
                    continue;
                }
                // Now delete it from its ftp directory.
                if (!$sftp->delete("{$pathname}/{$file}")) {
                    $messages[] = xl('File') . " '{$file}' " . xl('cannot be deleted, ignored');
                    ++$badcount;
                    continue;
                }
                // Parse and process its contents.
                $msg = receive_hl7_results($hl7);
                if ($msg) {
                    $messages[] = xl('Error processing file') . " '{$file}':" . $msg;
                    ++$badcount;
                    continue;
                }
                $messages[] = xl('New file') . " '{$file}' " . xl('processed successfully');
            }
        }
        // TBD: Insert "else if ($protocol == '???') {...}" to support other protocols.
    }
    if ($badcount) {
        return "{$badcount} " . xl('error(s) encountered from new results');
    }
    return '';
}
Exemplo n.º 24
0
$remoteOutputFile = "/code/spopt-stable/tests/" . $session . "/input.txt.out";
$remoteSolutionsFile = "/code/spopt-stable/tests/" . $session . "/input.txt.solutions";
$remoteDiscardedFile = "/code/spopt-stable/tests/" . $session . "/input.txt.discarded";
//ssh2 and sftp used to remotely connect
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
include 'Net/SSH2.php';
include 'Net/SFTP.php';
//ssh connect to cr2g server
$ssh = new Net_SSH2('cr2g01.cs.utep.edu', 22);
if (!$ssh->login('rlgruver', 'utep$2015')) {
    exit('ssh Login Failed');
}
//attempted to set an ssh timeout, not allowed on UTEP server
$ssh->setTimeout(7200);
//sftp connect to cr2g server
$sftp = new Net_SFTP('cr2g01.cs.utep.edu', 22);
if (!$sftp->login('rlgruver', 'utep$2015')) {
    exit('sftp Login Failed');
}
//send input file to cr2g server
$sftp->mkdir('/code/spopt-stable/tests/' . $session);
$sftp->put($remoteInputFile, $localInputFile, NET_SFTP_LOCAL_FILE);
$sftp->chmod(0777, $remoteInputFile);
//execute python script in this order to run the Solver:
//1. change to directory where solver script is located
$ssh->write("cd /code/spopt-stable\n");
//2. 'read' command to ensure script is called from the proper directory
$ssh->read('rlgruver@cr2g01:/code/spopt-stable$');
//3. run the solver script with the test from the current session
$ssh->write("python SpOpt.py tests/" . $session . "/input.txt\n");
//start timerin case anything gets stuck, will break within 120 minutes (7200 sec)
Exemplo n.º 25
0
 public static function test($settings)
 {
     self::_init();
     // Connect to server.
     $server = $settings['address'];
     $port = '22';
     // Default sFTP port.
     if (strstr($server, ':')) {
         // Handle custom sFTP port.
         $server_params = explode(':', $server);
         $server = $server_params[0];
         $port = $server_params[1];
     }
     pb_backupbuddy::status('details', 'Connecting to sFTP server...');
     $sftp = new Net_SFTP($server, $port);
     if (!$sftp->login($settings['username'], $settings['password'])) {
         pb_backupbuddy::status('error', 'Connection to sFTP server FAILED.');
         pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.');
         return __('Unable to connect to server using host, username, and password combination provided.', 'it-l10n-backupbuddy');
     } else {
         pb_backupbuddy::status('details', 'Success connecting to sFTP server.');
     }
     pb_backupbuddy::status('details', 'Attempting to create path (if it does not exist)...');
     if (true === $sftp->mkdir($settings['path'])) {
         // Try to make directory.
         pb_backupbuddy::status('details', 'Directory created.');
     } else {
         pb_backupbuddy::status('details', 'Directory not created.');
     }
     $destination_file = $settings['path'] . '/backupbuddy_test.txt';
     pb_backupbuddy::status('details', 'About to put to sFTP test file `backupbuddy_test.txt` to remote location `' . $destination_file . '`.');
     $send_time = -microtime(true);
     if (true !== $sftp->put($destination_file, 'Upload test for BackupBuddy destination. Delete me.')) {
         pb_backupbuddy::status('details', 'sFTP test: Failure uploading test file.');
         $sftp->delete($destination_file);
         // Just in case it partionally made file. This has happened oddly.
         pb_backupbuddy::status('details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.');
         return __('Failure uploading. Check path & permissions.', 'it-l10n-backupbuddy');
     } else {
         // File uploaded.
         pb_backupbuddy::status('details', 'File uploaded.');
         if ($settings['url'] != '') {
             $response = wp_remote_get(rtrim($settings['url'], '/\\') . '/backupbuddy_test.txt', array('method' => 'GET', 'timeout' => 20, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array()));
             if (is_wp_error($response)) {
                 return __('Failure. Unable to connect to the provided optional URL.', 'it-l10n-backupbuddy');
             }
             if (stristr($response['body'], 'backupbuddy') === false) {
                 return __('Failure. The path appears valid but the URL does not correspond to it. Leave the URL blank if not using this destination for migrations.', 'it-l10n-backupbuddy');
             }
         }
         pb_backupbuddy::status('details', 'sFTP test: Deleting temp test file.');
         $sftp->delete($destination_file);
     }
     return true;
     // Success if we got this far.
 }
Exemplo n.º 26
0
<?php

session_start();
include 'header.php';
include 'Net/SFTP.php';
$file = $_GET['file'];
$sftp = new Net_SFTP(SSH_HOST);
if ($sftp->login($_SESSION['id'], $_SESSION['passwd'])) {
    $sftp->delete('/scratch/' . $_SESSION['id'] . '/meshslicer/' . $file);
    $reply = json_encode(array('Error' => '0', 'Message' => ""));
    unset($_SESSION['fileList'][array_search($file, $_SESSION['fileList'])]);
} else {
    $reply = json_encode(array('Error' => '1', 'Message' => 'Astral problem. Please try again.'));
}
echo $reply;
Exemplo n.º 27
0
/**
 * Transmit HL7 for the specified lab.
 *
 * @param  integer $ppid  Procedure provider ID.
 * @param  string  $out   The HL7 text to be sent.
 * @return string         Error text, or empty if no errors.
 */
function send_hl7_order($ppid, $out)
{
    global $srcdir;
    $d0 = "\r";
    $pprow = sqlQuery("SELECT * FROM procedure_providers " . "WHERE ppid = ?", array($ppid));
    if (empty($pprow)) {
        return xl('Procedure provider') . " {$ppid} " . xl('not found');
    }
    $protocol = $pprow['protocol'];
    $remote_host = $pprow['remote_host'];
    // Extract MSH-10 which is the message control ID.
    $segmsh = explode(substr($out, 3, 1), substr($out, 0, strpos($out, $d0)));
    $msgid = $segmsh[9];
    if (empty($msgid)) {
        return xl('Internal error: Cannot find MSH-10');
    }
    if ($protocol == 'DL' || $pprow['orders_path'] === '') {
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=order_{$msgid}.hl7");
        header("Content-Description: File Transfer");
        echo $out;
        exit;
    } else {
        if ($protocol == 'SFTP') {
            ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . "{$srcdir}/phpseclib");
            require_once "{$srcdir}/phpseclib/Net/SFTP.php";
            // Compute the target path/file name.
            $filename = $msgid . '.txt';
            if ($pprow['orders_path']) {
                $filename = $pprow['orders_path'] . '/' . $filename;
            }
            // Connect to the server and write the file.
            $sftp = new Net_SFTP($remote_host);
            if (!$sftp->login($pprow['login'], $pprow['password'])) {
                return xl('Login to this remote host failed') . ": '{$remote_host}'";
            }
            if (!$sftp->put($filename, $out)) {
                return xl('Creating this file on remote host failed') . ": '{$filename}'";
            }
        } else {
            if ($protocol == 'FS') {
                // Compute the target path/file name.
                $filename = $msgid . '.txt';
                if ($pprow['orders_path']) {
                    $filename = $pprow['orders_path'] . '/' . $filename;
                }
                $fh = fopen("{$filename}", 'w');
                if ($fh) {
                    fwrite($fh, $out);
                    fclose($fh);
                } else {
                    return xl('Cannot create file') . ' "' . "{$filename}" . '"';
                }
            } else {
                return xl('This protocol is not implemented') . ": '{$protocol}'";
            }
        }
    }
    // Falling through to here indicates success.
    newEvent("proc_order_xmit", $_SESSION['authUser'], $_SESSION['authProvider'], 1, "ID: {$msgid} Protocol: {$protocol} Host: {$remote_host}");
    return '';
}
Exemplo n.º 28
0
 ###
 // Rights
 $checkGroup = checkClientGroup($server['groupid'], $_SESSION['clientid']);
 if ($checkGroup == FALSE) {
     $_SESSION['msg1'] = T_('Error!');
     $_SESSION['msg2'] = T_('This is not your server!');
     $_SESSION['msg-type'] = 'error';
     header('Location: index.php');
     die;
 }
 ###
 $aes = new Crypt_AES();
 $aes->setKeyLength(256);
 $aes->setKey(CRYPT_KEY);
 // Get SFTP
 $sftp = new Net_SFTP($box['ip'], $box['sshport']);
 if (!$sftp->login($box['login'], $aes->decrypt($box['password']))) {
     $_SESSION['msg1'] = T_('Connection Error!');
     $_SESSION['msg2'] = '';
     $_SESSION['msg-type'] = 'error';
     header("Location: server.php?id=" . urlencode($serverid));
     die;
 }
 $log = $sftp->get(dirname($server['path']) . '/screenlog.0');
 $sftp->disconnect();
 //Adding event to the database
 $message = mysql_real_escape_string($server['name']) . ' : screenlog downloaded';
 query_basic("INSERT INTO `" . DBPREFIX . "log` SET `serverid` = '" . $serverid . "', `message` = '" . $message . "', `name` = '" . $_SESSION['clientfirstname'] . " " . $_SESSION['clientlastname'] . "', `ip` = '" . $_SERVER['REMOTE_ADDR'] . "'");
 ###
 header('Content-type: text/plain');
 header('Content-Disposition: attachment; filename="' . $server['screen'] . '_' . date('Y-m-d') . '.screenlog"');
Exemplo n.º 29
0
 public function getError()
 {
     $err = $this->ftp->getLastError();
     if (!$err) {
         $err = $this->ftp->getLastSFTPError();
     }
     if ($err) {
         return $err['msg'];
     }
 }
Exemplo n.º 30
0
function tsdns($action, $sship, $sshport, $sshuser, $keyuse, $sshkey, $sshpw, $notified, $path, $bitversion, $tsip, $tsport, $tsdns, $reseller_id, $maxnotified = 2)
{
    global $sql;
    $sshSftpObject = new Net_SFTP($sship, $sshport);
    if ($keyuse != 'N') {
        $privateKey = EASYWIDIR . '/keys/' . removePub($sshkey);
        $sshpw = new Crypt_RSA();
        if ($keyuse == 'B') {
            $sshpw->setPassword($sshpw);
        }
        $keyContent = @file_get_contents($privateKey);
        if ($keyContent) {
            $sshpw->loadKey($keyContent);
        }
    }
    if ($sshSftpObject->login($sshuser, $sshpw)) {
        $split_config = preg_split('/\\//', $path, -1, PREG_SPLIT_NO_EMPTY);
        $folderfilecount = count($split_config) - 1;
        $i = 0;
        $folders = substr($path, 0, 1) == '/' ? '/' : '';
        $lastFolder = '';
        while ($i <= $folderfilecount) {
            $folders .= $split_config[$i] . '/';
            $lastFolder = $split_config[$i];
            $i++;
        }
        if ($lastFolder != 'tsdns' or substr($path, 0, 1) != '/') {
            $folders .= 'tsdns/';
        }
        if ($action == 'md' or $action == 'dl') {
            $newip = $tsip[0];
            $oldip = isset($tsip[1]) ? $tsip[1] : '';
            $newport = $tsport[0];
            $oldport = isset($tsport[1]) ? $tsport[1] : '';
            $newdns = $tsdns[0];
            $olddns = isset($tsdns[1]) ? $tsdns[1] : '';
        } else {
            $dnsarray = array();
        }
        $file = substr($path, 0, 1) == '/' ? $folders . 'tsdns_settings.ini' : '/home/' . $sshuser . '/' . $folders . 'tsdns_settings.ini';
        if ($action != 'rs') {
            $data = $sshSftpObject->get($file);
            $data = str_replace(array("", "\\b", "\r", "\\Z"), '', $data);
        }
        if ($action != 'rs' and $action != 'mw') {
            $edited = false;
            $ca = array();
            foreach (preg_split('/\\n/', $data, -1, PREG_SPLIT_NO_EMPTY) as $configLine) {
                if ($action != 'li' and $configLine != $olddns . '=' . $oldip . ':' . $oldport and $configLine != $newdns . '=' . $newip . ':' . $newport) {
                    $ca[] = $configLine . "\r\n";
                } else {
                    if ($action == 'md' and $edited == false and ($configLine == $olddns . '=' . $oldip . ':' . $oldport or $configLine == $newdns . '=' . $newip . ':' . $newport)) {
                        $edited = true;
                        $ca[] = $newdns . '=' . $newip . ':' . $newport . "\r\n";
                    }
                }
                if ($action == 'li' and $configLine != '' and !preg_match('/^#(|\\s+)(.*)$/', $configLine)) {
                    $dnsconfig = explode('=', $configLine);
                    if (isset($dnsconfig[1])) {
                        $linedns = $dnsconfig[0];
                        $lineserver = $dnsconfig[1];
                        $dnsarray[$lineserver] = $linedns;
                    }
                }
            }
            if ($action == 'md' and $edited == false) {
                $ca[] = $newdns . '=' . $newip . ':' . $newport . "\r\n";
            }
            if ($action != 'li') {
                $ca = array_unique($ca);
                sort($ca);
                $newcfg = '';
                foreach ($ca as $line) {
                    $newcfg .= $line;
                }
                if ($newcfg == '') {
                    $newcfg = '# No TSDNS data entered';
                }
                $sshSftpObject->put($file, $newcfg);
            }
        }
        if ($action == 'mw' and isset($data)) {
            $usedIPs = array();
            foreach (preg_split('/\\n/', $data, -1, PREG_SPLIT_NO_EMPTY) as $configLine) {
                if ($configLine != '' and !preg_match('/^#(|\\s+)(.*)$/', $configLine)) {
                    $splittedLine = preg_split('/\\=/', $configLine, -1, PREG_SPLIT_NO_EMPTY);
                    $usedIPs[] = isset($splittedLine[1]) ? array('dns' => $splittedLine[0], 'address' => $splittedLine[1]) : $configLine;
                } else {
                    $usedIPs[] = $configLine;
                }
            }
            foreach ($tsip as $newLine) {
                $splittedLine = preg_split('/\\=/', strtolower($newLine), -1, PREG_SPLIT_NO_EMPTY);
                if (isset($splittedLine[1]) and !array_key_exists($splittedLine[1], $usedIPs)) {
                    $usedIPs[] = array('dns' => $splittedLine[0], 'address' => $splittedLine[1]);
                }
            }
            function array_multi_dimensional_unique($multi)
            {
                $unique = array();
                foreach ($multi as $sub) {
                    if (!in_array($sub, $unique)) {
                        $unique[] = $sub;
                    }
                }
                return $unique;
            }
            $newCfg = '';
            $usedIPs = array_multi_dimensional_unique($usedIPs);
            sort($usedIPs);
            foreach ($usedIPs as $value) {
                $newCfg .= (isset($value['dns']) and isset($value['address']) and !preg_match('/^#(|\\s+)(.*)$/', $value['dns'])) ? $value['dns'] . '=' . $value['address'] . "\r\n" : $value . "\r\n";
            }
            if ($newCfg == '') {
                $bad = 'Nothing to write';
            } else {
                $sshSftpObject->put($file, $newCfg);
            }
        }
        if (!isset($bad) and $action != 'li') {
            $sshObject = new Net_SSH2($sship, $sshport);
            if ($sshObject->error === false) {
                if ($sshObject->login($sshuser, $sshpw)) {
                    $bin = $bitversion == 32 ? 'tsdnsserver_linux_x86' : 'tsdnsserver_linux_amd64';
                    $ssh2cmd = 'cd ' . $folders . ' && function restart () { if [ "`ps fx | grep ' . $bin . ' | grep -v grep`" == "" ]; then ./' . $bin . ' > /dev/null & else ./' . $bin . ' --update > /dev/null & fi }; restart& ';
                    $sshObject->exec($ssh2cmd);
                    if ($notified > 0) {
                        $query = $sql->prepare("UPDATE `voice_masterserver` SET `notified`=0 WHERE `ssh2ip`=? AND `resellerid`=? LIMIT 1");
                        $query->execute(array($sship, $reseller_id));
                    }
                } else {
                    $bad = 'The login data does not work';
                    $notified++;
                }
            } else {
                $bad = 'Could not connect to Server';
                $notified++;
            }
        }
    } else {
        $bad = 'Could not connect to Server';
    }
    if (isset($bad) and $notified == $maxnotified) {
        if ($reseller_id == 0) {
            $query = $sql->prepare("SELECT `id`,`mail_serverdown` FROM `userdata` WHERE `resellerid`=0 AND `accounttype`='a'");
            $query->execute();
        } else {
            $query = $sql->prepare("SELECT `id`,`mail_serverdown` FROM `userdata` WHERE (`id`=? AND `id`=`resellerid`) OR (`resellerid`=0 AND `accounttype`='a')");
            $query->execute(array($reseller_id));
        }
        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            if ($row['mail_serverdown'] == 'Y') {
                sendmail('emaildown', $row['id'], 'TS3 Master ' . $sship . ' ( ' . $bad . ' )', '');
            }
        }
        $query = $sql->prepare("UPDATE `voice_masterserver` SET `notified`=`notified`+1 WHERE `ssh2ip`=? AND `resellerid`=? LIMIT 1");
        $query->execute(array($sship, $reseller_id));
        return $bad;
    } else {
        if (isset($bad)) {
            return $bad;
        } else {
            if ($action == 'li' and isset($dnsarray)) {
                return $dnsarray;
            }
        }
    }
    return 'ok';
}