Skip to content

Instantly share code, notes, and snippets.

@flozz
Created January 20, 2017 09:59
Show Gist options
  • Save flozz/a2ac6624c773882a619f55bb6b835175 to your computer and use it in GitHub Desktop.
Save flozz/a2ac6624c773882a619f55bb6b835175 to your computer and use it in GitHub Desktop.
Checks that an Obsidian File is coherent (based on header and file size)
<?php
function check_obsidian_project($bytes) {
$HEADERS_LENGTH = 51;
$MIN_SECTION_SIZE = 2;
if (strlen($bytes) <= $HEADERS_LENGTH) {
return false;
}
$unpackString = "a4magic/nversion/A10type";
$unpackString .= "/CmetadataFormat/NmetadataOffset/NmetadataLength";
$unpackString .= "/CprojectFormat/NprojectOffset/NprojectLength";
$unpackString .= "/CblobIndexFormat/NblobIndexOffset/NblobIndexLength";
$unpackString .= "/NblobsOffset/NblobsLength";
$data = unpack($unpackString, $bytes);
// magic
if ($data["magic"] != "WPRJ") {
return false;
}
// metadata*
if ($data["metadataFormat"] != 0 && $data["metadataFormat"] != 1) {
return false;
}
if ($data["metadataOffset"] != $HEADERS_LENGTH) {
return false;
}
if ($data["metadataLength"] < $MIN_SECTION_SIZE) {
return false;
}
// project*
if ($data["projectFormat"] != 0 && $data["projectFormat"] != 1) {
return false;
}
if ($data["projectOffset"] != $data["metadataOffset"] + $data["metadataLength"]) {
return false;
}
if ($data["projectLength"] < $MIN_SECTION_SIZE) {
return false;
}
// blobIndex*
if ($data["blobIndexFormat"] != 0 && $data["blobIndexFormat"] != 1) {
return false;
}
if ($data["blobIndexOffset"] != $data["projectOffset"] + $data["projectLength"]) {
return false;
}
if ($data["blobIndexLength"] < $MIN_SECTION_SIZE) {
return false;
}
// blobs*
if ($data["blobsOffset"] != $data["blobIndexOffset"] + $data["blobIndexLength"]) {
return false;
}
// Check that the file size is coherent
if (strlen($bytes) != $HEADERS_LENGTH + $data["metadataLength"] + $data["projectLength"] + $data["blobIndexLength"] + $data["blobsLength"]) {
return false;
}
return true;
}
function check_obsidian_project_from_file($path) {
$handle = fopen($path, "rb");
$fsize = filesize($path);
$bytes = fread($handle, $fsize);
return check_obsidian_project($bytes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment