Created
January 19, 2022 10:14
-
-
Save atsu666/f3d6f2ec8de9385c30694b21d7af607e to your computer and use it in GitHub Desktop.
php/Services/StaticExport/Compiler/LinkResolver.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acms\Services\StaticExport\Compiler; | |
use Acms\Services\StaticExport\Contracts\Resolver; | |
use ACMS_RAM; | |
use Media; | |
class LinkResolver extends Resolver | |
{ | |
/** | |
* @param string $html | |
* @param string $document_root | |
* @param string $offset_dir | |
* @param string $domain | |
* @param string $blog_code | |
* | |
* @return string | |
*/ | |
public function resolve($html, $document_root, $offset_dir, $domain, $blog_code) | |
{ | |
$regex = $this->getRegex(); | |
$offset = 0; | |
$blogPath = ACMS_RAM::blogDomain(BID); | |
if (DIR_OFFSET) { | |
$blogPath .= '/' . DIR_OFFSET; | |
} | |
while ( preg_match($regex, $html, $match, PREG_OFFSET_CAPTURE, $offset) ) { | |
$offset = $match[0][1] + strlen($match[0][0]); | |
for ( $mpt=1; $mpt <= 2; $mpt++ ) if ( !empty($match[$mpt][0]) ) break; | |
$path = trim($match[$mpt][0], '\'"'); | |
$path = preg_replace('@(https?)?://' . $blogPath . '/?@', '/', $path); | |
if ( empty($path) ) continue; | |
if ( '//' === substr($path, 0, 2) ) continue; | |
if ( is_int(strpos($path, '://')) ) continue; | |
if ( '#' === substr($path, 0, 1) ) continue; | |
if ( '/' !== substr($path, 0, 1) ) continue; | |
if (defined('REWRITE_PATH_EXTENSION')) { | |
$extensionRegex = '/\.(?:acms|'.REWRITE_PATH_EXTENSION.')/'; | |
if (preg_match($extensionRegex, $path)) { | |
continue; // ファイルリンクだった場合は書き換えない | |
} | |
} | |
$mediaDownloadRegex = '/\/' . MEDIA_FILE_SEGMENT . '\/(\d+)\//'; | |
if (preg_match($mediaDownloadRegex, $path, $mediaMatchs)) { | |
$mid = $mediaMatchs[1]; | |
$media = Media::getMedia($mid); | |
$path = '/' . MEDIA_STORAGE_DIR . $media['path']; | |
} | |
$path = substr($path, 1); | |
$path = '/' . $offset_dir . $path; | |
$path = preg_replace('/page\/([\d]+)\/?/', 'page$1.html', $path); | |
$html = substr_replace($html, '"'.$path.'"', $match[$mpt][1], strlen($match[$mpt][0])); | |
$offset -= (strlen($match[$mpt][0]) - strlen($path)); | |
} | |
return $html; | |
} | |
/** | |
* @return string | |
*/ | |
protected function getRegex() | |
{ | |
$regex = '@'. | |
// a要素のhref属性 | |
'<\s*a(?:"[^"]*"|\'[^\']*\'|[^\'">])*href\s*=\s*("[^"]+"|\'[^\']+\'|[^\'"\s>]+)(?:"[^"]*"|\'[^\']*\'|[^\'">])*>|'. | |
// form要素のaction属性 | |
'<\s*form(?:"[^"]*"|\'[^\']*\'|[^\'">])*action\s*=\s*("[^"]+"|\'[^\']+\'|[^\'"\s>]+)(?:"[^"]*"|\'[^\']*\'|[^\'">])*>'. | |
'@'; | |
return $regex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment