protected function write_file($file, $content) {
        // Generate a temp file that is going to be unique. We'll rename it at the end to the desired file name.
        // in this way we avoid partial writes.
        $path = dirname($file);
        while (true) {
            $tempfile = $path.'/'.uniqid(sesskey().'.', true) . '.temp';
            if (!file_exists($tempfile)) {
                break;
            }
        }

        // Open the file with mode=x. This acts to create and open the file for writing only.
        // If the file already exists this will return false.
        // We also force binary.
        $handle = @fopen($tempfile, 'xb+');
        if ($handle === false) {
            // File already exists... lock already exists, return false.
            return false;
        }
        fwrite($handle, $content);
        fflush($handle);
        // Close the handle, we're done.
        fclose($handle);

        if (md5_file($tempfile) !== md5($content)) {
            // The md5 of the content of the file must match the md5 of the content given to be written.
            @unlink($tempfile);
            return false;
        }

        // Finally rename the temp file to the desired file, returning the true|false result.
        $result = rename($tempfile, $file);
        @chmod($file, $this->cfg->filepermissions);
        if (!$result) {
            // Failed to rename, don't leave files lying around.
            @unlink($tempfile);
        }
        return $result;
    }