Example #1
0
 /**
  * A single request, without following redirects
  *
  * @todo: Handle redirects? If so, only for GET (i.e. not for POST), and use G2's
  * WebHelper_simple::_parseLocation logic.
  */
 static function do_request($url, $method = 'GET', $headers = array(), $body = '')
 {
     if (!array_key_exists("User-Agent", $headers)) {
         $headers["User-Agent"] = "Gallery3";
     }
     /* Convert illegal characters */
     $url = str_replace(' ', '%20', $url);
     $url_components = self::_parse_url_for_fsockopen($url);
     $handle = fsockopen($url_components['fsockhost'], $url_components['port'], $errno, $errstr, 5);
     if (empty($handle)) {
         // log "Error $errno: '$errstr' requesting $url";
         return array(null, null, null);
     }
     $header_lines = array('Host: ' . $url_components['host']);
     foreach ($headers as $key => $value) {
         $header_lines[] = $key . ': ' . $value;
     }
     $success = fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s", $method, $url_components['uri'], implode("\r\n", $header_lines), $body));
     if (!$success) {
         // Zero bytes written or false was returned
         // log "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''
         return array(null, null, null);
     }
     fflush($handle);
     /*
      * Read the status line.  fgets stops after newlines.  The first line is the protocol
      * version followed by a numeric status code and its associated textual phrase.
      */
     $response_status = trim(fgets($handle, 4096));
     if (empty($response_status)) {
         // 'Empty http response code, maybe timeout'
         return array(null, null, null);
     }
     /* Read the headers */
     $response_headers = array();
     while (!feof($handle)) {
         $line = trim(fgets($handle, 4096));
         if (empty($line)) {
             break;
         }
         /* Normalize the line endings */
         $line = str_replace("\r", '', $line);
         list($key, $value) = explode(':', $line, 2);
         if (isset($response_headers[$key])) {
             if (!is_array($response_headers[$key])) {
                 $response_headers[$key] = array($response_headers[$key]);
             }
             $response_headers[$key][] = trim($value);
         } else {
             $response_headers[$key] = trim($value);
         }
     }
     /* Read the body */
     $response_body = '';
     while (!feof($handle)) {
         $response_body .= fread($handle, 4096);
     }
     fclose($handle);
     return array($response_status, $response_headers, $response_body);
 }
Example #2
0
function flush_output()
{
    $output = ob_get_contents();
    rewind($GLOBALS['ob_file']);
    fwrite($GLOBALS['ob_file'], $output);
    fflush($GLOBALS['ob_file']);
}
Example #3
0
 function W($aStr)
 {
     if (fwrite($this->iFP, $aStr) == -1) {
         die("Can't write to file : " . $this->iFileName);
     }
     fflush($this->iFP);
 }
 public function flushReport($auth, $report)
 {
     if (is_null($auth) || is_null($report)) {
         if ($this->_verbose > 0) {
             error_log("Auth or report not set.");
         }
         return null;
     }
     if ($this->_verbose >= 3) {
         var_dump($report);
     }
     $content = json_encode($report);
     $content = gzencode($content);
     $header = "Host: " . $this->_host . "\r\n";
     $header .= "User-Agent: LightStep-PHP\r\n";
     $header .= "LightStep-Access-Token: " . $auth->access_token . "\r\n";
     $header .= "Content-Type: application/json\r\n";
     $header .= "Content-Length: " . strlen($content) . "\r\n";
     $header .= "Content-Encoding: gzip\r\n";
     $header .= "Connection: keep-alive\r\n\r\n";
     // Use a persistent connection when possible
     $fp = @pfsockopen($this->_host, $this->_port, $errno, $errstr);
     if (!$fp) {
         if ($this->_verbose > 0) {
             error_log($errstr);
         }
         return null;
     }
     @fwrite($fp, "POST /api/v0/reports HTTP/1.1\r\n");
     @fwrite($fp, $header . $content);
     @fflush($fp);
     @fclose($fp);
     return null;
 }
Example #5
0
function SaveForDebug($debugStr)
{
    $logFile = fopen(DEBUG_FILE, 'a');
    if (flock($logFile, LOCK_EX | LOCK_NB)) {
        $serverInfo = var_export($_SERVER, true);
        $str = date('d M H:i:s', CURRENT_TIME);
        if (isset($_SERVER['REMOTE_ADDR'])) {
            $str .= ' - ip ' . $_SERVER['REMOTE_ADDR'];
            if (isset($_SERVER['HTTP_REFERER'])) {
                $str .= ' - ref ' . $_SERVER['HTTP_REFERER'];
            }
            if (isset($_SERVER['HTTP_USER_AGENT'])) {
                $str .= ' - ua ' . $_SERVER['HTTP_USER_AGENT'];
            }
        }
        $str .= "\ndebug: {$debugStr}\n\n{$serverInfo}\n\n";
        if (count($_POST)) {
            $str .= "\n" . var_export($_POST, true) . "\n";
        }
        fwrite($logFile, $str . "\n\n");
        fflush($logFile);
        flock($logFile, LOCK_UN);
    }
    fclose($logFile);
}
Example #6
0
 public static function saveFile($loc, $dsc, $zip = false)
 {
     if (function_exists(curl_init)) {
         if (file_exists($dsc)) {
             unlink($dsc);
         }
         $f1 = @fopen($dsc, "w");
         $ch = curl_init($loc);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
         curl_setopt($ch, CURLOPT_FILE, $f1);
         if ($zip) {
             curl_setopt($ch, CURLOPT_ENCODING, 'gzip , deflate');
         }
         if (curl_errno($ch) != 0 || curl_getinfo($ch, CURLINFO_HTTP_CODE) > 403) {
             curl_close($ch);
             fclose($f1);
             return false;
         }
         curl_exec($ch);
         curl_close($ch);
         fflush($f1);
         fclose($f1);
         return true;
     }
 }
Example #7
0
 /**
  * Flushes the data to the standard output.
  *
  * @return boolean
  */
 public function flush()
 {
     if (!is_resource($this->_stream)) {
         throw new Opl_Stream_Exception('Output stream is not opened.');
     }
     return fflush($this->_stream);
 }
 function __destruct()
 {
     if (LOG == true) {
         fflush($this->logger);
         fclose($this->logger);
     }
 }
 public function run($args)
 {
     $f = fopen(self::DUMP_FILE, 'a+');
     if (!$f) {
         die('Failed to open ' . self::DUMP_FILE . " for writing\n");
     }
     $db = Yii::app()->db;
     $cmd = $db->createCommand()->select('a.*')->from('address a')->leftJoin('contact c', "a.parent_class = 'Contact' and a.parent_id = c.id")->where('c.id is null')->limit(self::BATCH_SIZE);
     while (1) {
         $tx = $db->beginTransaction();
         if (!($rows = $cmd->queryAll())) {
             $tx->commit();
             break;
         }
         echo 'Deleting ' . count($rows) . " rows...\n";
         $ids = array();
         foreach ($rows as $row) {
             if (!fputcsv($f, $row)) {
                 die("Failed to write CSV row\n");
             }
             $ids[] = $row['id'];
         }
         if (!fflush($f)) {
             die('Flush failed');
         }
         $db->createCommand()->delete('address', array('in', 'id', $ids));
         $tx->commit();
         sleep(1);
     }
     fclose($f);
     echo "Done\n";
 }
Example #10
0
 public function flush()
 {
     if (!$this->isValid()) {
         return;
     }
     return fflush($this->m_handle);
 }
Example #11
0
 /**
  * Create content from template and data.
  *
  * @param string $name
  * @param array $data
  *
  * @return string|null
  */
 public function getContent($name, array $data = [])
 {
     $path = $this->packageRoot . '/view/_cache/' . str_replace('/', '_', $name);
     if (!file_exists($path) || !$this->cache) {
         $code = $this->compile($name, true, true);
         if (empty($code)) {
             return null;
         }
         $fh = fopen($path, 'wb');
         if (flock($fh, LOCK_EX)) {
             fwrite($fh, $code);
             flock($fh, LOCK_UN);
         }
         fflush($fh);
         fclose($fh);
     }
     $fh = fopen($path, 'rb');
     flock($fh, LOCK_SH);
     if (null !== $this->request) {
         $data = array_replace($data, ['request' => $this->request]);
     }
     $html = self::renderTemplate($path, $data);
     flock($fh, LOCK_UN);
     fclose($fh);
     return $html;
 }
Example #12
0
File: Lock.php Project: f3ath/flock
 /**
  * Acquire lock
  *
  * @param boolean $block Block and wait until it frees and then acquire
  * @return boolean Has be acquired?
  * @throws ErrorException if can not access the file
  */
 public function acquire($block = self::NON_BLOCKING)
 {
     if ($this->handler) {
         throw new LogicException('Lock is already acqiured');
     }
     // For flock() to work properly, the file must exist at the moment we do fopen()
     // So we create it first. touch()'s return value can be ignored, as the possible
     // error would be cought in the next step.
     touch($this->file);
     // The manuals usually recommend to use 'c' mode. But there can be a race condition.
     // If the file is deleted after touch() but before fopen(), it can be recreated and opened with flock()
     // by two processes simultaneously, and they both would be able to acquire an exclusive lock!
     // So when opening the file we MUST BE SURE it exists!
     // The 'r+' mode enables writing to an existing file, but it fails if the file does not exist.
     $this->handler = @fopen($this->file, 'r+');
     if (!$this->handler) {
         $this->throwLastErrorException();
     }
     $flag = LOCK_EX;
     if (!$block) {
         $flag |= LOCK_NB;
     }
     if (!flock($this->handler, $flag)) {
         $this->closeFile();
         return false;
     }
     if (@ftruncate($this->handler, 0) && @fwrite($this->handler, getmypid()) && @fflush($this->handler)) {
         return true;
     }
     $this->throwLastErrorException();
 }
function appendNamespace($inputFilename, $namespace, $outputFilename)
{
    $inputHandle = fopen($inputFilename, "r") or die("Unable to open file to read!");
    $outputHandle = fopen($outputFilename, "w") or die("Unable to open file to write!");
    while (!feof($inputHandle)) {
        $buffer = fgets($inputHandle);
        //readline
        $startpos = strpos($buffer, '<?php');
        //        print '--'.$startpos.'--';
        if (is_int($startpos)) {
            $starttaglen = 5;
            $headlen = strlen(trim($buffer));
            if ($headlen == $starttaglen) {
                fwrite($outputHandle, $buffer);
                fwrite($outputHandle, "namespace {$namespace};" . PHP_EOL);
            } else {
                $header = substr($buffer, 0, $startpos + $starttaglen);
                $tail = substr($buffer, $startpos + $starttaglen);
                fwrite($outputHandle, $header . PHP_EOL);
                print 'header:' . $buffer . PHP_EOL;
                fwrite($outputHandle, "namespace {$namespace};" . PHP_EOL);
                fwrite($outputHandle, $tail . PHP_EOL);
            }
            break;
        }
    }
    while (!feof($inputHandle)) {
        $buffer = fgets($inputHandle);
        //readline
        fwrite($outputHandle, $buffer);
    }
    fflush($outputHandle);
    fclose($inputHandle);
    fclose($outputHandle);
}
Example #14
0
/**
 *	log a message to file
 *
 *	@param string $level can be error, warn, info or debug
 *	@param string $msg message
 *	@return bool true if successful, false if not
 */
function log_msg($level, $msg)
{
    global $logfile;
    global $loglevels;
    global $request_id;
    // open logfile
    if ($logfile === false) {
        $m = umask(0111);
        // having two processes appending to the same file should
        // work fine (at least on Linux)
        $logfile = @fopen(LOG_FILE, 'ab');
        umask($m);
    }
    if ($logfile === false) {
        return false;
    }
    foreach ($loglevels as $ll) {
        if ($ll == $level) {
            fwrite($logfile, date('Y-m-d H:i:s') . tab() . pad($_SERVER['REMOTE_ADDR'], 15) . tab() . sprintf('%05u', $request_id) . tab() . $level . tab() . $msg . nl());
            fflush($logfile);
            break;
        }
        if ($ll == LOG_LEVEL) {
            break;
        }
    }
    return true;
}
Example #15
0
 public function flush()
 {
     $r = fflush($this->__f);
     if ($r === false) {
         throw new HException(haxe_io_Error::Custom("An error occurred"));
     }
 }
Example #16
0
 public function generateCsv(View $view)
 {
     $columns = $view->getExportableCols();
     $titles = array_map(function (Column $col) {
         return $col->label;
     }, $columns);
     $colNames = array_map(function (Column $col) {
         return $col->id;
     }, $columns);
     // get rows
     $sql = $view->prepareQuery();
     $rows = \Meta\Core\Db::query($sql)->fetchAll(\PDO::FETCH_ASSOC);
     header("Content-type: text/csv");
     header("Content-Disposition: attachment; filename=export.csv");
     header("Pragma: no-cache");
     header("Expires: 0");
     // write CSV to output
     $stdout = fopen('php://output', 'w');
     fputcsv($stdout, $titles);
     foreach ($rows as $row) {
         $newRow = array();
         foreach ($colNames as $name) {
             $newRow[$name] = $row[$name];
         }
         fputcsv($stdout, $newRow);
     }
     fflush($stdout);
     fclose($stdout);
     exit;
 }
Example #17
0
 /**
  * {@inheritDoc}
  */
 public function flush()
 {
     if ($this->fileHandle) {
         return fflush($this->fileHandle);
     }
     return false;
 }
 public static function log($message, $file = 'error.log')
 {
     $path = waConfig::get('wa_path_log');
     if (!$path) {
         $path = dirname(dirname(dirname(__FILE__)));
     }
     $path .= '/' . $file;
     if (!file_exists($path)) {
         waFiles::create(dirname($path));
         touch($path);
         chmod($path, 0666);
     } elseif (!is_writable($path)) {
         return false;
     }
     $fd = fopen($path, 'a');
     if (!flock($fd, LOCK_EX)) {
         throw new waException('Unable to lock ' . $path);
     }
     fwrite($fd, "\n");
     fwrite($fd, date('Y-m-d H:i:s: '));
     fwrite($fd, $message);
     fflush($fd);
     flock($fd, LOCK_UN);
     fclose($fd);
     return true;
 }
Example #19
0
    /**
     * Generate config file
     *
     * @return $this
     */
    public function dump()
    {
        // rules
        $rules = '';
        foreach ($this->ruleset->asArray() as $key => $values) {
            $rules .= sprintf('        %s: [ %s ]%s', $key, implode(', ', $values), PHP_EOL);
        }
        // main content
        $content = <<<EOT
# This file is used by PhpMetrics
# Please visit http://www.phpmetrics.org do get more informations
default:
    path:
        directory: src
    logging:
        report:
            html:   ./phpmetrics.html
    rules:
{$rules}

EOT;
        // write file
        if (!$this->destination) {
            throw new \LogicException('Please provide a destination');
        }
        $dir = dirname($this->destination);
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $handle = fopen($this->destination, 'w');
        fwrite($handle, $content);
        fflush($handle);
        fclose($handle);
        return $this;
    }
 private function deny($comment = '')
 {
     $ip = Yii::$app->request->userIP;
     $userAgent = Yii::$app->request->userAgent;
     if ($this->checkIP($ip) && $this->checkBrowser($userAgent)) {
         $path = Yii::getAlias('@webroot') . '/.htaccess';
         $fp = fopen($path, 'r+');
         if ($fp && flock($fp, LOCK_EX)) {
             if ($data = fread($fp, filesize($path))) {
                 $comment = $this->clear($comment);
                 foreach (['/(order[a-zA-Z ,]*)[\\r\\n]/Umi'] as $pattern) {
                     if (preg_match($pattern, $data)) {
                         $data = preg_replace($pattern, "\$1\r\ndeny from {$ip} # {$comment}\r", $data);
                         ftruncate($fp, 0);
                         fseek($fp, 0);
                         fwrite($fp, $data, strlen($data));
                         break;
                     }
                 }
             }
             fflush($fp);
             flock($fp, LOCK_UN);
             fclose($fp);
         }
     }
 }
Example #21
0
 protected function doWrite($message, $newline)
 {
     if (false === @fwrite($this->stream, $message . ($newline ? PHP_EOL : ''))) {
         throw new \RuntimeException('Unable to write output.');
     }
     fflush($this->stream);
 }
 protected function writeToLog($text)
 {
     if (empty($text)) {
         return;
     }
     $logFile = $this->logFile;
     $logFileHistory = $this->logFileHistory;
     if (!is_writable($logFile)) {
         return;
     }
     $oldAbortStatus = ignore_user_abort(true);
     if ($fp = @fopen($logFile, "ab+")) {
         if (flock($fp, LOCK_EX)) {
             $logSize = filesize($logFile);
             $logSize = intval($logSize);
             if ($logSize > $this->maxLogSize) {
                 @copy($logFile, $logFileHistory);
                 ftruncate($fp, 0);
             }
             fwrite($fp, $text);
             fflush($fp);
             flock($fp, LOCK_UN);
             fclose($fp);
         }
     }
     ignore_user_abort($oldAbortStatus);
 }
 public static function Run()
 {
     echo 'relocate ' . register__xampp::$name . PHP_EOL;
     fflush(STDOUT);
     self::relocateShortcut();
     return;
 }
 protected function call_maxima($command)
 {
     set_time_limit(0);
     // Note, some users may not want this!
     $ret = false;
     $descriptors = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('file', $this->logs . "cas_errors.txt", 'a'));
     $cmd = '"' . $this->command . '"';
     $this->debug->log('Command line', $cmd);
     $casprocess = proc_open($cmd, $descriptors, $pipes);
     if (!is_resource($casprocess)) {
         throw new stack_exception('stack_cas_connection: Could not open a CAS process.');
     }
     if (!fwrite($pipes[0], $this->initcommand)) {
         return false;
     }
     fwrite($pipes[0], $command);
     fwrite($pipes[0], 'quit();\\n\\n');
     fflush($pipes[0]);
     // Read output from stdout.
     $ret = '';
     while (!feof($pipes[1])) {
         $out = fgets($pipes[1], 1024);
         if ('' == $out) {
             // Pause.
             usleep(1000);
         }
         $ret .= $out;
     }
     fclose($pipes[0]);
     fclose($pipes[1]);
     return trim($ret);
 }
Example #25
0
 /**
  * Create folders and print string to file.
  *
  * Example: Core::appendToFile('log', 'error-log.log' , 'Logging an error')
  *
  * @param string  $folder Folder path
  * @param string  $file   File name
  * @param string  $string String to append
  * @param boolean $echo   Echo logs?
  *
  * @return boolean
  */
 public static function appendToFile($folder, $file, $string, $echo = true)
 {
     $folder = APP_DIR . trim($folder, '/');
     $file = trim(trim($file), '/');
     // Handle folder: create if doesn't exist
     if (!is_dir($folder)) {
         $folder_check = mkdir($folder, 0755, true);
         // if folder doesn't exist and fails creating, return false
         if (!$folder_check) {
             // @codeCoverageIgnoreStart
             self::printLog("Error creating folder: " . $folder, 'error-core', $echo);
             return false;
             // @codeCoverageIgnoreEnd
         }
     }
     // Create/write to file
     $fp = @fopen($folder . '/' . $file, 'a');
     if (!$fp) {
         // @codeCoverageIgnoreStart
         self::printLog("Error creating file: " . $folder . '/' . $file, 'error-core', $echo);
         return false;
         // @codeCoverageIgnoreEnd
     }
     fwrite($fp, $string);
     fflush($fp);
     return true;
 }
Example #26
0
 public function setupSeo()
 {
     if (file_exists('../.htaccess')) {
         return;
     } else {
         if (function_exists('apache_get_modules')) {
             $modules = apache_get_modules();
             $mod_rewrite = in_array('mod_rewrite', $modules);
         } else {
             $mod_rewrite = getenv('HTTP_MOD_REWRITE') == 'On' ? true : false;
         }
         if ($mod_rewrite && file_exists('../.htaccess.txt')) {
             chmod('../.htaccess.txt', 0777);
             $file = fopen('../.htaccess.txt', 'a');
             $document = file_get_contents('../.htaccess.txt');
             $root = rtrim(HTTP_SERVER, '/');
             $folder = substr(strrchr($root, '/'), 1);
             $path = rtrim(rtrim(dirname($_SERVER['SCRIPT_NAME']), ''), '/' . $folder . '.\\');
             if (strlen($path) > 1) {
                 $path .= '/';
             }
             if (!$path) {
                 $path = '/';
             }
             $document = str_replace('RewriteBase /', 'RewriteBase ' . $path, $document);
             file_put_contents('../.htaccess.txt', $document);
             fflush($file);
             fclose($file);
             rename('../.htaccess.txt', '../.htaccess');
         }
     }
     clearstatcache();
 }
Example #27
0
 /**
  * @return bool|mixed
  */
 public function flush()
 {
     $ret = fflush($this->getResource());
     // Also send back to server
     $ret &= $this->driver->put($this->path, $this->_tmpFile);
     return $ret;
 }
Example #28
0
 public function run(InputInterface $input = null, OutputInterface $output = null)
 {
     $fp = fopen($this->config['lockfile'], "w");
     // if you run this script as root - change user/group
     if (file_exists($this->config['lockfile'])) {
         chown($this->config['lockfile'], $this->config['file-user']);
         chgrp($this->config['lockfile'], $this->config['file-group']);
     }
     $exitCode = 0;
     if (flock($fp, LOCK_EX | LOCK_NB)) {
         // acquire an exclusive lock
         ftruncate($fp, 0);
         $exitCode = parent::run($input, $output);
         fflush($fp);
         // flush output before releasing the lock
         flock($fp, LOCK_UN);
         // release the lock
     } else {
         //throw new DNSSyncException("Running multiple instances is not allowed."); - nezachytí applikace error
         //$output->writeln() - null v této chvíli
         $message = "Running multiple instances is not allowed.";
         echo $message . PHP_EOL;
         mail($this->config['admin-email'], $message, $message);
         $exitCode = 500;
     }
     fclose($fp);
     return $exitCode;
 }
Example #29
0
 function tc_exec($command)
 {
     global $debug, $stdlog;
     fwrite(STDOUT, "{$command}\n");
     fflush(STDOUT);
     $result = trim(fgets(STDIN));
     $ret = array('code' => -1, 'result' => -1, 'timeout' => false, 'data' => '');
     if (preg_match("/^([0-9]{1,3}) (.*)/", $result, $matches)) {
         $ret['code'] = $matches[1];
         $ret['result'] = 0;
         if (preg_match('/^result=([0-9a-zA-Z]*)\\s?(?:\\(?(.*?)\\)?)?$/', $matches[2], $match)) {
             $ret['result'] = $match[1];
             $ret['timeout'] = $match[2] === 'timeout' ? true : false;
             $ret['data'] = $match[2];
         }
     }
     if ($debug && !empty($stdlog)) {
         $fh = fopen($stdlog, 'a');
         if ($fh !== false) {
             $res = $ret['result'] . (empty($ret['data']) ? '' : " / {$ret['data']}");
             fwrite($fh, "-------\n>> {$command}\n<< {$result}\n<<     parsed {$res}\n");
             fclose($fh);
         }
     }
     return $ret;
 }
Example #30
-22
File: funcs.php Project: dg-wfk/dl
function logEvent($logLine, $logType = LOG_INFO)
{
    global $logFile, $useSysLog, $logFd, $auth;
    $attr = array();
    if (isset($auth['name'])) {
        $attr[] = $auth['name'];
    }
    if (isset($_SERVER['REMOTE_ADDR'])) {
        $attr[] = $_SERVER['REMOTE_ADDR'];
    }
    if (count($attr)) {
        $logLine = '[' . implode(", ", $attr) . '] ' . $logLine;
    }
    if ($logType == LOG_ERR) {
        $logLine = 'error: ' . $logLine;
    }
    if ($useSysLog) {
        syslog($logType, $logLine);
    } elseif (!isset($logFd)) {
        if ($logType == LOG_ERR) {
            error_log('DL: ' . $logLine);
        }
    } else {
        $logLine = "[" . date(DATE_W3C) . "] {$logLine}\n";
        flock($logFd, LOCK_EX);
        fseek($logFd, 0, SEEK_END);
        fwrite($logFd, $logLine);
        fflush($logFd);
        flock($logFd, LOCK_UN);
    }
}