Wrapper for standard fopen() doing error checking.

\private
\static
175061
function fopen( $fileName, $mode )
    {
        error_clear_last();

        if ( ( $handle = @fopen( $fileName, 'wb' ) ) === false )
            $this->FileOpenErrorMsg = implode(',', error_get_last());

        return $handle;
    }
980723
public static function fatalErrorHandler() {
				
		// get fatal error array
		$error = error_get_last();

		if (!is_null($error)) {

			// command line log has date and plain text
			if ('cli' == php_sapi_name()) {
				
				print date(DATE_RFC2822) . "\nFatal error (" . $error['type'] . ') on file ' .
					$error['file'] . ' line ' . $error['line'] . ': ' . $error['message'] . "\n";

			// format for an HTML web print
			} else {

				print '<div style="background-color:#f1f1f1;border:2px solid red;margin:10px 0;padding:12px 16px">' .
						PRODUCT_NAME . ' fatal error: ' . $error['message'] . '</div>';

			}
		
			// get admin emails by options
			$emails = array_filter(explode(',', Options::get('admin_emails')));
			
			if (count($emails)) {

				// get proper server description
				if (isset($_SERVER['SERVER_NAME'])) {
					$server = $_SERVER['SERVER_NAME'];
				} else if (isset($_SERVER['SERVER_ADDR'])) {
					$server = $_SERVER['SERVER_ADDR'];
				} else {
					$server = '[Unknown]';
				}
			
				// build email parameters
				$subject = PRODUCT_NAME . ' fatal error on ' . $server;
				$message = PRODUCT_NAME . ' generated a fatal error on server ' .  BASE_HREF . ' as of ' .
					date(DATE_RFC2822) . " UTC." . PHP_EOL . PHP_EOL .
					'Error [type ' . $error['type'] . ']: ' . PHP_EOL .
					$error['message'] . ' (' . $error['file'] . ' line ' . $error['line'] . ')';
				$headers = 'From: ' . PRODUCT_NAME . ' <' . strtolower(PRODUCT_NAME) . '@' . $server . '>';

				// send email to each admin
				foreach ($emails as $email) {
					mail($email, $subject, $message, $headers);
				}
				
			}
			
		}
	
	}
912529
def open_without_clobber(name, *args):
    
    fd = None
    count = 1
    orig_name = name
    while fd is None:
        try:
            fd = os.open(name, os.O_CREAT | os.O_EXCL, 0o666)
        except OSError as err:
            if err.errno == errno.EEXIST:
                name = "%s.%i" % (orig_name, count)
                count += 1
            else:
                raise IOError(err.errno, err.strerror, err.filename)
    fobj = open(name, *args)
    if fd != fobj.fileno():
        os.close(fd)
    return fobj
1120346
public static function catchFatalErrorsEarly()
    {
        $error = error_get_last();
        if (($error['type'] === E_ERROR || $error['type'] === E_PARSE)) {
            echo nl2br(str_replace(dirname(dirname(__DIR__)), '', $error['message']));
        }
    }
848865
function open_fp($option = 'r')
    {

        if (empty($option) || !is_string($option)) return false;

        switch (true) {
            case (strpos($option, 'r') !== false) :
                $mode = LOCK_SH;
                break;
            case (strpos($option, 'a') !== false || strpos($option, 'w') !== false) :
                $mode = LOCK_EX;
                break;
            default :
                $mode = LOCK_EX;
                break;
        }
        $this->readable = true;

        if (($this->fp = fopen($this->file, $option)) !== false) {
            $this->lock($mode);
            // sets the fopen option based on it reduces
            // reopening of a file
            $this->_option = (string)$option;

            return true;
        }

        return false;
    }
686133
static function GetFileContent($filename,&$error = null,&$error_str = null){
		$error = false;
		$error_str = "";

		$out = "";
		
		settype($filename,"string");

		if(!is_file($filename)){
			$error = true;
			$error_str = "$filename is not a file";
			return null;		
		}

		$filesize = filesize($filename);
		if($filesize==0){ return ""; }

		$f = fopen($filename,"r");
		if(!$f){
			$error = false;
			$error_str = "can't open file $filename for writing";
			return $out;
		}
		$out = fread($f,$filesize);
		fclose($f);

		return $out;
	}
1297770
private function error()
		{
			if (true === $this->_enabled) {
				switch ($this->_archive) {
					case \ZipArchive::ER_CRC:
						$message	= 'ZIP CRC error';
						break;
					case \ZipArchive::ER_EXISTS:
						$message	= 'ZIP archive already exists';
						break;
					case \ZipArchive::ER_INCONS:
						$message	= 'ZIP archive inconsistency';
						break;
					case \ZipArchive::ER_INVAL:
						$message	= 'Invalid arguments';
						break;
					case \ZipArchive::ER_MEMORY:
						$message	= 'Memory allocation failure';
						break;
					case \ZipArchive::ER_MULTIDISK:
						$message	= 'Multi-disk archives are not supported';
						break;
					case \ZipArchive::ER_NOENT:
						$message	= 'File does not exist';
						break;
					case \ZipArchive::ER_NOZIP:
						$message	= 'Not a valid ZIP archive';
						break;
					case \ZipArchive::ER_OPEN:
						$message	= 'Unable to open archive';
						break;
					case \ZipArchive::ER_READ:
						$message	= 'ZIP file read error';
						break;
					case \ZipArchive::ER_SEEK:
						$message	= 'ZIP file seek error';
						break;
					default:
						$message = 'Unknown error: ' . $this->_archive;
				}
			} else {
				$message = 'ZIP library was not detected in your PHP installation';
			}

			trigger_error($message, E_USER_WARNING);
			$this->_enabled = false;

			return $message;
		}
1277630
static function parse_file( $f ){
		$src = file_get_contents( $f, true );
		if( $src === false ){
			throw new Exception("Cannot read file $f");
		}
		return self::parse_string( $src );
	}
785749
static function init() {

		switch( PHP_SAPI ) {
		// Ideally we want to be runnning as CLI
		case 'cli':
			break;
		// Special conditions to ensure CGI runs as CLI
		case 'cgi':
			// Ensure resource constants are defined
			if( ! defined('STDERR') ){
				define( 'STDERR', fopen('php://stderr', 'w') );
			}
			if( ! defined('STDOUT') ){
				define( 'STDOUT', fopen('php://stdout', 'w') );
			}
			break;
		default:
			echo "Command line only\n";
			exit(1);
		}
		
		// Default error logger function
		PLUG::set_error_logger( array(__CLASS__,'format_logline') );
		
		// parse command line arguments from argv global
		global $argv, $argc;
		// first cli arg is always current script. second arg will be script arg passed to shell wrapper
		for( $i = 1; $i < $argc; $i++ ){
			$arg = $argv[ $i ];
			
			// Each command line argument may take following forms:
			//  1. "Any single argument", no point parsing this unless it follows #2 below
			//  2. "-aBCD", one or more switches, parse into 'a'=>true, 'B'=>true, and so on
			//  3. "-a value", flag used with following value, parsed to 'a'=>'value'
			//  4. "--longoption", GNU style long option, parse into 'longoption'=>true
			//  5. "--longoption=value", as above, but parse into 'longoption'=>'value'
			//  6."any variable name = any value" 
			
			$pair = explode( '=', $arg, 2 );
			if( isset($pair[1]) ){
				$name = trim( $pair[0] );
				if( strpos($name,'--') === 0 ){
					// #5. trimming "--" from option, tough luck if you only used one "-"
					$name = trim( $name, '-' );
				}
				// else is #6, any pair
				$name and self::$args[$name] = trim( $pair[1] );
			}
			
			else if( strpos($arg,'--') === 0 ){
				// #4. long option, no value
				$name = trim( $arg, "-\n\r\t " );
				$name and self::$args[ $name ] = true;
			}
			
			else if( $arg && $arg{0} === '-' ){
				$flags = preg_split('//', trim($arg,"-\n\r\t "), -1, PREG_SPLIT_NO_EMPTY );
				foreach( $flags as $flag ){
					self::$args[ $flag ] = true;
				}
				// leave $flag set incase a value follows.
				continue;
			}

			// else is a standard argument. use as value only if it follows a flag, e.g "-a apple"
			else if( isset($flag) ){
				self::$args[ $flag ] = trim( $arg );
			}

			// dispose of last flag
			unset( $flag );
			// next arg 
		}
	}
1361616
public function tell()
	{
		if (!$this->fh)
		{
			throw new \RuntimeException('File not open');
		}

		// Capture PHP errors
		$php_errormsg = '';
		$track_errors = ini_get('track_errors');
		ini_set('track_errors', true);

		switch ($this->processingmethod)
		{
			case 'gz':
				$res = gztell($this->fh);
				break;

			case 'bz':
			case 'f':
			default:
				$res = ftell($this->fh);
				break;
		}

		// May return 0 so check if it's really false
		if ($res === false)
		{
			throw new \RuntimeException($php_errormsg);
		}

		// Restore error tracking to what it was before
		ini_set('track_errors', $track_errors);

		// Return the result
		return $res;
	}
1100329
final function handleError($code, $m, $file = '', $line = 0, $context=[]) {
    	// 2017-07-10
    	// «Magento 2.1 php7.1 will not be supported due to mcrypt deprecation»
		// https://github.com/magento/magento2/issues/5880
		// [PHP 7.1] How to fix the «Function mcrypt_module_open() is deprecated» bug?
		// https://mage2.pro/t/2392
    	if (E_DEPRECATED !== $code || !df_contains($m, 'mcrypt') && !df_contains($m, 'mdecrypt')) {
			$this->ravenClient->breadcrumbs->record([
				'category' => 'error_reporting',
				'message' => $m,
				'level' => $this->ravenClient->translateSeverity($code),
				'data' => ['code' => $code, 'line' => $line, 'file' => $file]
			]);
		}
		return !$this->existingHandler ? false : call_user_func(
			$this->existingHandler, $code, $m, $file, $line, $context
		);
    }
56286
private function open()
    {
        // Used for trapping `fopen()` errors.
        $this->trappedErrorNumber = null;
        $this->trappedErrorString = null;

        set_error_handler(
            function($errorNo, $errorString) {
                $this->trapError($errorNo, $errorString);
            }
        );

        $needsChmod = !file_exists($this->file);
        $file = fopen($this->file, 'a');

        restore_error_handler();

        // Handles trapped `fopen()` errors.
        if ($this->trappedErrorNumber) {
            throw new Exception(
                sprintf(
                    "Logger Error: '%s'",
                    $this->trappedErrorString
                ),
                $this->trappedErrorNumber
            );
        }

        if ($needsChmod) {
            @chmod($this->file, $this->mode & ~umask());
        }

        return $this->file = $file;
    }
172684
private function checkForFluentSetterErrors(File $phpcsFile, int $functionPos, int $classPos): void
    {
        $tokens = $phpcsFile->getTokens();
        $errorData = $phpcsFile->getDeclarationName($classPos) . '::' . $phpcsFile->getDeclarationName($functionPos);

        $functionToken = $tokens[$functionPos];
        $openBracePtr = $functionToken['scope_opener'];
        $closeBracePtr = $functionToken['scope_closer'];

        $returnPtr = $phpcsFile->findNext(T_RETURN, $openBracePtr, $closeBracePtr);

        if ($returnPtr === false) {
            $fixNoReturnFound = $phpcsFile->addFixableError(
                self::ERROR_NO_RETURN_FOUND,
                $functionPos,
                static::CODE_NO_RETURN_FOUND,
                $errorData
            );

            if ($fixNoReturnFound) {
                $this->fixNoReturnFound($phpcsFile, $closeBracePtr);
            }

            return;
        }

        $this->checkAndRegisterEmptyReturnErrors($phpcsFile, $functionPos, $returnPtr, $errorData);
    }
1334524
protected function openFile()
    {
        ini_set('auto_detect_line_endings', 1);
        $this->fileHandle = fopen($this->filename, 'r');

        if ($this->providedHeaderRow) {
            $this->headerRow = $this->remapHeader($this->providedHeaderRow);
        }
    }
1353682
public static function resetStd()
    {
        if (!static::$daemonize || static::$_OS !== OS_TYPE_LINUX) {
            return;
        }
        global $STDOUT, $STDERR;
        $handle = fopen(static::$stdoutFile, "a");
        if ($handle) {
            unset($handle);
            set_error_handler(function(){});
            fclose($STDOUT);
            fclose($STDERR);
            fclose(STDOUT);
            fclose(STDERR);
            $STDOUT = fopen(static::$stdoutFile, "a");
            $STDERR = fopen(static::$stdoutFile, "a");
            // change output stream
            static::$_outputStream = null;
            static::outputStream($STDOUT);
            restore_error_handler();
        } else {
            throw new Exception('can not open stdoutFile ' . static::$stdoutFile);
        }
    }
612937
function popErrorHandling()
    {
        $stack = &$GLOBALS['_PEAR_error_handler_stack'];
        array_pop($stack);
        list($mode, $options) = $stack[sizeof($stack) - 1];
        array_pop($stack);
        if (isset($this) && is_a($this, 'PEAR')) {
            $this->setErrorHandling($mode, $options);
        } else {
            PEAR::setErrorHandling($mode, $options);
        }
        return true;
    }
407001
function readCodeFromFile()
  {
    $fp = @fopen($this->wordlist_file, 'rb');
    if (!$fp) return false;

    $fsize = filesize($this->wordlist_file);
    if ($fsize < 32) return false; // too small of a list to be effective

    if ($fsize < 128) {
      $max = $fsize; // still pretty small but changes the range of seeking
    } else {
      $max = 128;
    }

    fseek($fp, rand(0, $fsize - $max), SEEK_SET);
    $data = fread($fp, 128); // read a random 128 bytes from file
    fclose($fp);
    $data = preg_replace("/\r?\n/", "\n", $data);

    $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
    $end   = strpos($data, "\n", $start);           // find end of word

    return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
  }