scratch – Rev 81

Subversion Repositories:
Rev:
<?php

###########################################################################
##  Copyright (C) Wizardry and Steamworks 2015 - License: GNU GPLv3      ##
###########################################################################
function atomized_put_contents($file, $data, $block = 1)
{
    $f = fopen($file, 'a');
    if (!$f || !flock($f, LOCK_EX | LOCK_NB, $block) || $block)
        return;
    ftruncate($f, 0);
    fwrite($f, $data, strlen($data));
    $t = filemtime ($file);
    flock($f, LOCK_UN);
    fclose($f);
    return $t;
}

###########################################################################
##  Copyright (C) Wizardry and Steamworks 2015 - License: GNU GPLv3      ##
###########################################################################
function atomized_get_contents($file, $block = 1)
{
    $f = fopen($file, 'r+');
    if (!$f || !flock($f, LOCK_SH | LOCK_NB, $block) || $block)
        return;
    $s = get_file_size($file);
    if ($s == 0) {
        flock($f, LOCK_UN);
        fclose($f);
        return;
    }
    $c = fread($f, $s);
    flock($f, LOCK_UN);
    fclose($f);
    return $c;
}

###########################################################################
##  Copyright (C) Wizardry and Steamworks 2015 - License: GNU GPLv3      ##
###########################################################################
function get_file_size($file, $block = 1)
{
    $f = fopen($file, 'r+');
    if (!$f || !flock($f, LOCK_SH | LOCK_NB, $block) || $block)
        return;
    
    $s = 1073741824;
    $i = 0;
    fseek($f, 0, SEEK_SET);
    do {
        fseek($f, $s, SEEK_CUR);

        if (fgetc($f) === false) {
            fseek($f, -$s, SEEK_CUR);
            $s = (int)($s / 2);
            continue;
        }
        fseek($f, -1, SEEK_CUR);
        $i += $s;
    } while ($s > 1);

    while (fgetc($f) !== false)
        $i++;
    
    flock($f, LOCK_UN);
    fclose($f);
    return $i;
}