Пример #1
2
 function readFromZiraatTxt($tesvikid)
 {
     $sftp = new Net_SFTP(ZIRAAT_FTP_HOST);
     if ($sftp->login(ZIRAAT_FTP_USER, ZIRAAT_FTP_PASS)) {
         //ilk önce doğru txt mi ??
         $directory_temp = EK_FOLDER . "ziraat_eft/temp_bankadan_kuruma/";
         if (!file_exists($directory_temp)) {
             mkdir($directory_temp, 0777, true);
         }
         //$fileTo
         $fileFrom = "/bankadan_kuruma/";
         $filelist = $sftp->nlist($fileFrom);
         $control = false;
         $fileth = count($filelist) - 1;
         do {
             $file = $filelist[$fileth];
             $fileTo = $directory_temp . $file;
             $sftp->get($fileFrom . $file, $fileTo);
             $control = $this->checkTxtFileForTesvik($tesvikid, $fileTo);
             if ($control == false) {
                 unlink($fileTo);
                 $fileth--;
             }
             if ($fileth == 0) {
                 break;
             }
         } while ($control == false);
         if ($control == true) {
             $directory = EK_FOLDER . "ziraat_eft/bankadan_kuruma/" . date('Ymd');
             if (!file_exists($directory)) {
                 mkdir($directory, 0777, true);
             }
             $files = explode('/', $fileTo);
             rename($fileTo, $directory . '/' . end($files));
             $return['FILE'] = date('Ymd') . '/' . end($files);
             $return['STATUS'] = true;
             $return['TEXT'] = "Dosya basariyla indirildi";
         } else {
             $return['STATUS'] = false;
             $return['TEXT'] = "Dosya indirme hatasi";
         }
     } else {
         $return['STATUS'] = false;
         $return['TEXT'] = "ftp bağlanti hatasi";
     }
     return $return;
 }
Пример #2
0
 /**
  * Returns the content of the given directory
  *
  * @param string $dir
  * @param bool   $recursive
  * @param bool   $log whether to log or not the action
  *
  * @return array
  */
 public function nlist($dir, $recursive = false, $log = true)
 {
     $res = $this->_getFromCache(__FUNCTION__, $dir);
     if ($res === null) {
         switch ($this->_connType) {
             case SftpHelper::TYPE_SFTP:
             default:
                 $res = $this->_connection->nlist($dir, $recursive);
                 break;
             case SftpHelper::TYPE_FTP:
                 if ($recursive) {
                     Console::stdout("\n");
                     Log::throwException('Recursive not supported for nlist in ftp mode');
                 }
                 $res = @ftp_nlist($this->_connection, $dir);
                 if (is_array($res)) {
                     // remove the $dir prefix from the results to match the format
                     // of $this->_connection->nlist
                     $res = preg_replace('/^' . str_replace('/', '\\/', $dir) . '[\\/]/', '', $res);
                 } elseif (!$res && $this->isDir($dir)) {
                     // for some reason ftp_nlist returns false if the directory is empty...
                     $res = [];
                 }
                 break;
         }
         $this->_addToCache(__FUNCTION__, $dir, $res);
         if ($log) {
             Log::logger()->addDebug('Performing ' . __METHOD__ . ' // result: {res}', ['res' => var_export($res, true), 'path' => $dir]);
         }
     }
     return $res;
 }
Пример #3
0
 /**
  * Get list of cwd subdirectories and files
  *
  */
 public function ls($grep = null)
 {
     $list = $this->_connection->nlist();
     $pwd = $this->pwd();
     $result = array();
     foreach ($list as $name) {
         $result[] = array('text' => $name, 'id' => "{$pwd}{$name}");
     }
     return $result;
 }
Пример #4
0
 /**
  * Get list of cwd subdirectories and files
  *
  * @param null $grep ignored parameter
  * @return array
  * @SuppressWarnings(PHPMD.ShortMethodName)
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function ls($grep = null)
 {
     $list = $this->_connection->nlist();
     $currentWorkingDir = $this->pwd();
     $result = [];
     foreach ($list as $name) {
         $result[] = ['text' => $name, 'id' => "{$currentWorkingDir}/{$name}"];
     }
     return $result;
 }
Пример #5
0
 public function opendir($path)
 {
     try {
         $list = $this->client->nlist($this->absPath($path));
         $id = md5('sftp:' . $path);
         $dirStream = array();
         foreach ($list as $file) {
             if ($file != '.' && $file != '..') {
                 $dirStream[] = $file;
             }
         }
         \OC\Files\Stream\Dir::register($id, $dirStream);
         return opendir('fakedir://' . $id);
     } catch (\Exception $e) {
         return false;
     }
 }
Пример #6
0
 public function ls($dir)
 {
     return array_flip($this->ftp->nlist($dir));
 }
Пример #7
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);
 }
/**
 * 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 '';
}
/**
 * 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 '';
}
Пример #10
0
 /**
  * This method is called in response to opendir()
  *
  * Opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls
  *
  * NOTES:
  * It loads the entire directory contents into memory.
  * The only $options is "whether or not to enforce safe_mode (0x04)". Since safe mode was deprecated in 5.3 and removed in 5.4 we are going
  * to ignore it
  *
  * @param String $path
  * @param Integer $options
  * @return bool
  * @access public
  */
 public function dir_opendir($path, $options)
 {
     if ($this->stream_open($path, NULL, NULL, $opened_path)) {
         $this->dir_entries = $this->sftp->nlist($this->path);
         return TRUE;
     } else {
         return FALSE;
     }
 }
Пример #11
0
 public function fileList($dir = '.')
 {
     return $this->conn->nlist($dir);
 }
Пример #12
0
<?php

include_once '../settings/autoload.php';
$msql = SafeMySQL::getInstance();
$sftp = new Net_SFTP(PSGlobalCollect::FTP_URL);
if (!$sftp->login(PSGlobalCollect::FTP_LOGIN, PSGlobalCollect::FTP_PASSWORD)) {
    exit('Login Failed');
}
$sftp->chdir('out');
$files = $sftp->nlist();
$wr1 = array();
foreach ($files as $filename) {
    if (substr($filename, 0, 4) == '7760' && substr($filename, -4) == '.wr1') {
        $wr1[] = $filename;
    }
}
sort($wr1);
foreach ($wr1 as $filename) {
    echo $filename . '<br />';
    $sql = "SELECT * FROM `wr1` WHERE `filename` = ?s";
    $result = $msql->query($sql, substr($filename, 0, 8));
    if (!$result->num_rows) {
        $wr1File = $sftp->get($filename);
        if (strlen($wr1File) != 802) {
            preg_match_all('/^.{3}7760.{43}LJ(\\d+).*$/m', $wr1File, $matches);
            $orderIDs = array_unique($matches[1]);
            sort($orderIDs);
            $ordersArr = array();
            foreach ($orderIDs as $order) {
                $ordersArr[] = '(' . (int) $order . ')';
            }
Пример #13
0
<?php

include_once '../settings/autoload.php';
$option = array('server' => '87.83.146.211', 'username' => 'raging-bull', 'password' => 'rck34RBM56', 'download_path' => 'matchback', 'uploadPath' => '');
$fulfillmentID = 9;
$msql = SafeMySQL::getInstance();
$arrayCsvFiles = array();
$arrayCsvFilesClear = array();
$sql = "SELECT *\n        FROM `fulfillment_files`\n        WHERE `fulfillment_id`=?i";
$result = $msql->getInd('filename', $sql, $fulfillmentID);
$sftp = new Net_SFTP($option['server']);
if (!$sftp->login($option['username'], $option['password'])) {
    exit('Login Failed');
}
$dPath = trim($option['download_path'], '/');
$contents = $sftp->nlist("{$dPath}");
if (!$contents) {
    exit('does not have files');
}
echo '<pre>';
print_r($contents);
echo '</pre>';
foreach ($contents as $file) {
    if (substr($file, -4, 4) == '.csv') {
        $arrayCsvFiles[] = $arrayCsvFilesClear[] = $file;
    }
}
foreach ($arrayCsvFiles as $file) {
    if (isset($result["{$file}"])) {
        continue;
    }