function findImageStack($subPrefix, $filesData) { // The order of the image formats determines which will be returned first $imageFormats = array('JP2' => 'jp2', 'TIFF' => 'tif', 'JPEG' => 'jpg'); $imageFormatOrder = array_values($imageFormats); $archiveFormats = array('ZIP' => 'zip', 'Tar' => 'tar'); $imageGroup = implode('|', array_keys($imageFormats)); $archiveGroup = implode('|', array_keys($archiveFormats)); // $$$ Currently only return processed images $imageStackRegex = "/Single Page (Processed) (${imageGroup}) (${archiveGroup})/"; // Strategy: // - Find potential image stacks, regardless of subPrefix // - If not given subPrefix sort based on potential subPrefix and assign based on asciibetical first // - Filter results by subPrefix // - Sort based on image format // - Take best match $imageStacks = array(); foreach ($filesData->file as $file) { if ( preg_match($imageStackRegex, $file->format, $matches) === 1 ) { $imageFormat = $imageFormats[$matches[2]]; $archiveFormat = $archiveFormats[$matches[3]]; $imageStackFile = $file['name'] . ''; if ( preg_match("#(.*)_${imageFormat}\.${archiveFormat}#", $imageStackFile, $matches) === 0) { // stack filename not regular continue; } else { array_push($imageStacks, array( 'imageFormat' => $imageFormat, 'archiveFormat' => $archiveFormat, 'imageStackFile' => $imageStackFile, 'subPrefix' => $matches[1]) ); } } } // print("<pre>"); // print("found subPrefix $subPrefix\n"); // print_r($imageStacks); // die(0); function subPrefixSort($imageStackA, $imageStackB) { return strcmp($imageStackA['subPrefix'], $imageStackB['subPrefix']); } if (! $subPrefix) { usort($imageStacks, 'subPrefixSort'); $subPrefix = $imageStacks[0]['subPrefix']; } self::$cbData = $subPrefix; function subPrefixFilter($imageStack) { return $imageStack['subPrefix'] == BookReaderMeta::$cbData; } $imageStacks = array_filter($imageStacks, 'subPrefixFilter'); function formatSort($imageStackA, $imageStackB) { $formatA = $imageStackA['imageFormat']; $formatB = $imageStackB['imageFormat']; if ($formatA == $formatB) { return 0; } $indexA = array_search($formatA, $imageFormatOrder); $indexB = array_search($formatB, $imageFormatOrder); // We already matched base on format, so both indices should be set if ($indexA == $indexB) { return 0; } return ($indexA < $indexB) ? 1 : -1; } usort($imageStacks, 'formatSort'); // necessary to remap keys if ( count($imageStacks) > 0 ) { return $imageStacks[0]; } else { return array('imageFormat' => 'unknown', 'archiveFormat' => 'unknown', 'imageStackFile' => 'unknown'); } }