Skip to content

Instantly share code, notes, and snippets.

@jaames
Created September 26, 2019 19:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaames/b8fd76baf9cddbed6fc0a03ce43ba389 to your computer and use it in GitHub Desktop.
Save jaames/b8fd76baf9cddbed6fc0a03ce43ba389 to your computer and use it in GitHub Desktop.
<?php
// Project Kaeru KWPCF builder
// Written by James Daniel
// github.com/jaames / rakujira.jp
// ---- USAGE ----
// create a new kaeruPrecache instance:
//
// $precache = new kaeruPrecache;
// open a buffer, this is where the precache data will be written:
//
// $precache->openBuffer("test.kwpcf");
//
// or you can pass in null to write to an in-memory buffer instead:
//
// $precache->openBuffer(null);
// add a resource entry to the cache:
// "url" is the external reference to the resource,
// "file" is the file path to the resource, which will be opened and embedded into the cache
//
// $precache->addEntry([
// "url" => "http://example.com/path/to/image.gif",
// "file" => "./image.gif"
// ]);
// get the buffer content (if using an in-memory buffer)
//
// $precache->getBuffer();
// close the buffer when finished
//
// $precache->closeBuffer();
class kaeruPrecache {
var $buffer = false;
// open up a buffer to write to
function openBuffer($path) {
// if $path is not given then use an in-memory file buffer
if (is_null($path)) {
$this->buffer = fopen("php://memory", "r+");
}
// else open $path as the buffer
else {
$this->buffer = fopen($path, "w+");
}
}
// close the buffer once finished
function closeBuffer() {
if ($this->buffer) {
fclose($this->buffer);
$this->buffer = false;
}
}
// get buffer contents
function getBuffer() {
if ($this->buffer) {
return stream_get_contents($this->buffer, -1, 0);
}
}
// add an entry to the precache buffer
function addEntry($args) {
if ($this->buffer && isset($args["url"]) && isset($args["file"])) {
// write the entry header and URL
// (header is "KPCF" followed by the length of the entry (not counting the 8-byte header) as uint32 LE)
// (following the header is the URL, which is always null-padded to 512 bytes)
fwrite($this->buffer, pack("a4Va512", "KPCF", filesize($args["file"]) + 512, $args["url"]));
// write the entry embed
fwrite($this->buffer, file_get_contents($args["file"]));
}
}
function __destruct() {
// should, hopefully, auto-close the buffer when finished
$this->closeBuffer();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment