diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..43e3edcf4 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI + +on: + push: + branches: + - master + - dev + - 'v*.*' + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v3 + with: + node-version: '20' + check-latest: true + cache: npm + cache-dependency-path: package-lock.json + + - run: npm ci + + - run: npm run format-check diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..5ac2a3cc3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +*.local +*.log +*.swp +.DS_Store +.cache +.env* +.vscode +node_modules diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..c5ec21291 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,16 @@ +**/*.min.* +**/*.ori.* +**/*.tpl.php +assets/js/css_async.js +assets/js/webfontloader.js +lib +tpl/banner +tpl/esi_widget_edit.php +tpl/inc/api_key.php +tpl/inc/check_cache_disabled.php +tpl/inc/check_if_network_disable_all.php +tpl/inc/modal.header.php +!tpl/cache/network_settings-browser.tpl.php +!tpl/cache/network_settings-object.tpl.php +!tpl/cache/settings-browser.tpl.php +!tpl/cache/settings-object.tpl.php diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..09fdb315e --- /dev/null +++ b/.prettierrc @@ -0,0 +1,24 @@ +{ + "overrides": [ + { + "files": ".prettierrc", + "options": { "parser": "json" } + }, + { + "files": "**/*.{yml,yaml}", + "options": { "tabWidth": 2 } + } + ], + "plugins": ["@prettier/plugin-php"], + "arrowParens": "avoid", + "braceStyle": "per-cs", + "endOfLine": "auto", + "phpVersion": "5.3", + "printWidth": 180, + "semi": true, + "singleQuote": true, + "tabWidth": 4, + "trailingComma": "all", + "trailingCommaPHP": true, + "useTabs": true +} diff --git a/assets/css/litespeed-legacy.css b/assets/css/litespeed-legacy.css index af1e5d2a1..2e71731ae 100644 --- a/assets/css/litespeed-legacy.css +++ b/assets/css/litespeed-legacy.css @@ -1,20 +1,18 @@ -.litespeed-wrap h2.nav-tab-wrapper, .litespeed-wrap h3.nav-tab-wrapper{ - margin-bottom:0; +.litespeed-wrap h2.nav-tab-wrapper, +.litespeed-wrap h3.nav-tab-wrapper { + margin-bottom: 0; } -.litespeed-wrap h2 .nav-tab{ - font-size:14px; +.litespeed-wrap h2 .nav-tab { + font-size: 14px; } - .litespeed-wrap .striped > tbody > :nth-child(odd), .litespeed-wrap ul.striped > :nth-child(odd), .litespeed-wrap .alternate { background-color: #f9f9f9; } - - .litespeed-wrap .notice, .litespeed-wrap div.updated, .litespeed-wrap div.error { @@ -55,4 +53,4 @@ .litespeed-wrap .notice-info.notice-alt { background-color: #e5f5fa; -} \ No newline at end of file +} diff --git a/assets/css/litespeed.css b/assets/css/litespeed.css index f3c4a7739..d04573829 100644 --- a/assets/css/litespeed.css +++ b/assets/css/litespeed.css @@ -1,7 +1,8 @@ @font-face { font-family: 'litespeedfont'; src: url('fonts/litespeedfont.eot?rs8ttq'); - src: url('fonts/litespeedfont.eot?rs8ttq#iefix') format('embedded-opentype'), + src: + url('fonts/litespeedfont.eot?rs8ttq#iefix') format('embedded-opentype'), url('fonts/litespeedfont.ttf?rs8ttq') format('truetype'), url('fonts/litespeedfont.woff?rs8ttq') format('woff'), url('fonts/litespeedfont.svg?rs8ttq#litespeedfont') format('svg'); @@ -12,7 +13,7 @@ #adminmenu #toplevel_page_lscache-settings .menu-icon-generic div.wp-menu-image:before, #adminmenu #toplevel_page_litespeed .menu-icon-generic div.wp-menu-image:before, .litespeed-top-toolbar .ab-icon::before { - content: "\e900"; + content: '\e900'; font-family: 'litespeedfont' !important; speak: none; font-style: normal; @@ -24,92 +25,90 @@ /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; - } *[litespeed-accesskey]:before { - content: '['attr(litespeed-accesskey) '] '; + content: '[' attr(litespeed-accesskey) '] '; } - /* ======================================= UTILITIES - toggle UI ======================================= */ -input[type="checkbox"].litespeed-tiny-toggle { - -webkit-appearance: none; - -moz-appearance: none; - appearance: none; - - -webkit-tap-highlight-color: transparent; - - width: auto; - height: auto; - vertical-align: middle; - position: relative; - border: 0; - outline: 0; - cursor: pointer; - margin: 0 4px; - background: none; - box-shadow: none; -} -input[type="checkbox"].litespeed-tiny-toggle:focus { - box-shadow: none; -} -input[type="checkbox"].litespeed-tiny-toggle:after { - content: ''; - font-size: 8px; - font-weight: 400; - line-height: 18px; - text-indent: -14px; - color: #ffffff; - width: 36px; - height: 18px; - display: inline-block; - background-color: #a7aaad; - border-radius: 72px; - box-shadow: 0 0 12px rgb(0 0 0 / 15%) inset; -} -input[type="checkbox"].litespeed-tiny-toggle:before { - content: ''; - width: 14px; - height: 14px; - display: block; - position: absolute; - top: 2px; - left: 2px; - margin: 0; - border-radius: 50%; - background-color: #ffffff; -} - -input[type="checkbox"].litespeed-tiny-toggle:checked:before { - left: 20px; - margin: 0; - background-color: #ffffff; -} - -input[type="checkbox"].litespeed-tiny-toggle, -input[type="checkbox"].litespeed-tiny-toggle:before, -input[type="checkbox"].litespeed-tiny-toggle:after, -input[type="checkbox"].litespeed-tiny-toggle:checked:before, -input[type="checkbox"].litespeed-tiny-toggle:checked:after { - transition: ease .15s; -} -input[type="checkbox"].litespeed-tiny-toggle:checked:after { - /*content: 'ON';*/ - background-color: #2271b1; -} - -.block-editor__container input[type="checkbox"].litespeed-tiny-toggle { +input[type='checkbox'].litespeed-tiny-toggle { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + + -webkit-tap-highlight-color: transparent; + + width: auto; + height: auto; + vertical-align: middle; + position: relative; + border: 0; + outline: 0; + cursor: pointer; + margin: 0 4px; + background: none; + box-shadow: none; +} +input[type='checkbox'].litespeed-tiny-toggle:focus { + box-shadow: none; +} +input[type='checkbox'].litespeed-tiny-toggle:after { + content: ''; + font-size: 8px; + font-weight: 400; + line-height: 18px; + text-indent: -14px; + color: #ffffff; + width: 36px; + height: 18px; + display: inline-block; + background-color: #a7aaad; + border-radius: 72px; + box-shadow: 0 0 12px rgb(0 0 0 / 15%) inset; +} +input[type='checkbox'].litespeed-tiny-toggle:before { + content: ''; + width: 14px; + height: 14px; + display: block; + position: absolute; + top: 2px; + left: 2px; + margin: 0; + border-radius: 50%; + background-color: #ffffff; +} + +input[type='checkbox'].litespeed-tiny-toggle:checked:before { + left: 20px; + margin: 0; + background-color: #ffffff; +} + +input[type='checkbox'].litespeed-tiny-toggle, +input[type='checkbox'].litespeed-tiny-toggle:before, +input[type='checkbox'].litespeed-tiny-toggle:after, +input[type='checkbox'].litespeed-tiny-toggle:checked:before, +input[type='checkbox'].litespeed-tiny-toggle:checked:after { + transition: ease 0.15s; +} +input[type='checkbox'].litespeed-tiny-toggle:checked:after { + /*content: 'ON';*/ + background-color: #2271b1; +} + +.block-editor__container input[type='checkbox'].litespeed-tiny-toggle { border: 0 !important; } -.block-editor__container input[type="checkbox"].litespeed-tiny-toggle:before { +.block-editor__container input[type='checkbox'].litespeed-tiny-toggle:before { top: 5px; left: 7px; } -.block-editor__container input[type="checkbox"].litespeed-tiny-toggle:checked:before { +.block-editor__container input[type='checkbox'].litespeed-tiny-toggle:checked:before { left: 23px; } @@ -117,6 +116,37 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { UTILITIES - structure ======================================= */ +.litespeed_icon:before { + /* content: "\e900"; + font-family: 'litespeedfont' !important; */ + content: ''; + background-image: url('../img/lscwp_grayscale_font-icon_22px.svg'); + /* filter: grayscale(1); */ + background-size: 22px; + background-repeat: no-repeat; + width: 22px; + height: 22px; + vertical-align: middle; + display: inline-block; + position: absolute; + left: 5px; + top: 8px; +} + +.rtl .litespeed_icon:before { + left: initial; + right: 5px; +} + +.litespeed_icon { + padding-left: 30px !important; + position: relative; +} + +.rtl .litespeed_icon { + padding-right: 40px; +} + .litespeed-quic-icon { background-image: url('../img/quic-cloud-icon-16x16.svg'); background-repeat: no-repeat; @@ -126,7 +156,6 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { display: inline-block; } - .litespeed-row { margin-top: 5px; } @@ -146,7 +175,7 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { height: auto; } -.litespeed-flex-container>* { +.litespeed-flex-container > * { box-sizing: border-box; } @@ -268,6 +297,10 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { margin-left: 20px; } +.litespeed-wrap .litespeed-bg-quic-cloud { + background: linear-gradient(rgba(230, 242, 242, 1) 10%, rgba(250, 255, 255, 1) 30%); +} + .litespeed-left50 { margin-left: 50px; } @@ -301,7 +334,6 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { margin-bottom: 0px !important; } - .litespeed-empty-space-xlarge { margin-top: 8em; } @@ -322,7 +354,6 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { margin-top: 1em; } - /* ======================================= UTILITIES - typography ======================================= */ @@ -332,7 +363,7 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { } .litespeed-text-large { - font-size: .75em !important; + font-size: 0.75em !important; } .litespeed-text-md { @@ -360,11 +391,11 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { } .litespeed-primary { - color: #3366CC !important; + color: #3366cc !important; } .litespeed-info { - color: #3FBFBF !important; + color: #3fbfbf !important; } .litespeed-success { @@ -372,7 +403,7 @@ input[type="checkbox"].litespeed-tiny-toggle:checked:after { } .litespeed-warning { - color: #FF8C00 !important; + color: #ff8c00 !important; } .litespeed-danger { @@ -402,7 +433,7 @@ button.litespeed-form-action:hover { } .litespeed-bg-primary { - background-color: #3366CC !important; + background-color: #3366cc !important; } .litespeed-bg-info { @@ -414,7 +445,7 @@ button.litespeed-form-action:hover { } .litespeed-bg-warning { - background-color: #FF8C00 !important; + background-color: #ff8c00 !important; } .litespeed-bg-danger { @@ -433,6 +464,18 @@ button.litespeed-form-action:hover { margin: 10px 20px 0 2px; } +.litespeed-wrap .nav-tab-wrapper { + display: flex; + flex-wrap: wrap-reverse; +} + +.litespeed-wrap .nav-tab { + border-bottom-color: inherit; + border-bottom-style: solid; + border-bottom-width: 1px; + margin: 11px 10px -1px 0; +} + .litespeed-wrap .nav-tab-active { background: #fff; border-bottom-color: #fff; @@ -447,11 +490,11 @@ button.litespeed-form-action:hover { .litespeed-body { background: #fff; border: 1px solid #e5e5e5; - box-shadow: 0 1px 1px rgba(0, 0, 0, .04); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); padding: 1px 20px 20px 20px; } -.litespeed-header+.litespeed-body { +.litespeed-header + .litespeed-body { border-top: none; } @@ -482,11 +525,11 @@ button.litespeed-form-action:hover { /*max-width: 840px;*/ } -.litespeed-desc+.litespeed-desc { - margin-top: -5px +.litespeed-desc + .litespeed-desc { + margin-top: -5px; } -td>.litespeed-desc:first-child { +td > .litespeed-desc:first-child { margin-top: 0px; line-height: 2.24; } @@ -562,7 +605,6 @@ h3 .litespeed-learn-more { padding-right: 50px; padding-left: 3px; padding-bottom: 3px; - } .litespeed-title .button { @@ -614,7 +656,6 @@ h3 .litespeed-learn-more { color: #72777c; } - /* ======================================= LAYOUT - table ======================================= */ @@ -623,7 +664,7 @@ h3 .litespeed-learn-more { font-size: 14px; } -.litespeed-body tbody>tr>th { +.litespeed-body tbody > tr > th { padding-left: 20px; } @@ -641,20 +682,19 @@ h3 .litespeed-learn-more { vertical-align: middle; } -.litespeed-body .widefat td input+p { - margin-top: .8em; +.litespeed-body .widefat td input + p { + margin-top: 0.8em; } -.litespeed-body .striped>tbody>:nth-child(even) .notice { +.litespeed-body .striped > tbody > :nth-child(even) .notice { background-color: #f9f9f9; - box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .05); + box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.05); border-top: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5; border-right: 1px solid #e5e5e5; - } -.litespeed-body .striped>tbody>:nth-child(even) .notice:first-child { +.litespeed-body .striped > tbody > :nth-child(even) .notice:first-child { margin-top: 0; } @@ -754,7 +794,7 @@ h3 .litespeed-learn-more { min-height: 75px; box-sizing: border-box; background: #f9fafc; - transition: .25s; + transition: 0.25s; } .litespeed-panel:hover { @@ -767,7 +807,7 @@ h3 .litespeed-learn-more { height: 100%; } -[class*="litespeed-panel-icon-"] { +[class*='litespeed-panel-icon-'] { background-size: contain; width: 60px; height: 60px; @@ -777,91 +817,95 @@ h3 .litespeed-learn-more { } .litespeed-panel-icon-all { - background-image: url("../img/icons/all.svg"); + background-image: url('../img/icons/all.svg'); } .litespeed-panel-icon-revision { - background-image: url("../img/icons/revision.svg"); + background-image: url('../img/icons/revision.svg'); +} + +.litespeed-panel-icon-orphaned_post_meta { + background-image: url('../img/icons/revision.svg'); } .litespeed-panel-icon-auto_draft { - background-image: url("../img/icons/auto_draft.svg"); + background-image: url('../img/icons/auto_draft.svg'); } .litespeed-panel-icon-trash_post { - background-image: url("../img/icons/trash_post.svg"); + background-image: url('../img/icons/trash_post.svg'); } .litespeed-panel-icon-spam_comment { - background-image: url("../img/icons/spam_comment.svg"); + background-image: url('../img/icons/spam_comment.svg'); } .litespeed-panel-icon-trash_comment { - background-image: url("../img/icons/trash_comment.svg"); + background-image: url('../img/icons/trash_comment.svg'); } .litespeed-panel-icon-trackback-pingback { - background-image: url("../img/icons/trackback-pingback.svg"); + background-image: url('../img/icons/trackback-pingback.svg'); } .litespeed-panel-icon-expired_transient { - background-image: url("../img/icons/expired_transient.svg"); + background-image: url('../img/icons/expired_transient.svg'); } .litespeed-panel-icon-all_transients { - background-image: url("../img/icons/all_transients.svg"); + background-image: url('../img/icons/all_transients.svg'); } .litespeed-panel-icon-optimize_tables { - background-image: url("../img/icons/optimize_tables.svg"); + background-image: url('../img/icons/optimize_tables.svg'); } .litespeed-panel-icon-purge-front { - background-image: url("../img/icons/purge-front.svg"); + background-image: url('../img/icons/purge-front.svg'); } .litespeed-panel-icon-purge-pages { - background-image: url("../img/icons/purge-pages.svg"); + background-image: url('../img/icons/purge-pages.svg'); } .litespeed-panel-icon-purge-cssjs { - background-image: url("../img/icons/purge-cssjs.svg"); + background-image: url('../img/icons/purge-cssjs.svg'); } .litespeed-panel-icon-purge-object { - background-image: url("../img/icons/purge-object.svg"); + background-image: url('../img/icons/purge-object.svg'); } .litespeed-panel-icon-purge-opcache { - background-image: url("../img/icons/purge-opcache.svg"); + background-image: url('../img/icons/purge-opcache.svg'); } .litespeed-panel-icon-purge-all { - background-image: url("../img/icons/purge-all.svg"); + background-image: url('../img/icons/purge-all.svg'); } .litespeed-panel-icon-empty-cache { - background-image: url("../img/icons/empty-cache.svg"); + background-image: url('../img/icons/empty-cache.svg'); } .litespeed-panel-icon-purge-403 { - background-image: url("../img/icons/purge-403.svg"); + background-image: url('../img/icons/purge-403.svg'); } .litespeed-panel-icon-purge-404 { - background-image: url("../img/icons/purge-404.svg"); + background-image: url('../img/icons/purge-404.svg'); } .litespeed-panel-icon-purge-500 { - background-image: url("../img/icons/purge-500.svg"); + background-image: url('../img/icons/purge-500.svg'); } .litespeed-panel-top-right-icon-cross { - background-image: url("../img/icons/cross_icon.svg"); + background-image: url('../img/icons/cross_icon.svg'); } .litespeed-panel-top-right-icon-tick { - background-image: url("../img/icons/success_icon.svg"); + background-image: url('../img/icons/success_icon.svg'); } .litespeed-panel-content { @@ -989,7 +1033,11 @@ h3 .litespeed-learn-more { border-color: #538ac6 #2264ad #2264ad; color: #fff; box-shadow: 0 1px 0 #2264ad; - text-shadow: 0 -1px 1px #2264ad, 1px 0 1px #2264ad, 0 1px 1px #2264ad, -1px 0 1px #2264ad; + text-shadow: + 0 -1px 1px #2264ad, + 1px 0 1px #2264ad, + 0 1px 1px #2264ad, + -1px 0 1px #2264ad; } .litespeed-wrap .button-primary:focus, @@ -1007,7 +1055,9 @@ h3 .litespeed-learn-more { background: #5891ce; border-color: #2264ad; color: #fff; - box-shadow: 0 1px 0 #0073aa, 0 0 2px 1px #33b3db; + box-shadow: + 0 1px 0 #0073aa, + 0 0 2px 1px #33b3db; } .litespeed .litespeed-btn-primary, @@ -1037,7 +1087,7 @@ h3 .litespeed-learn-more { margin-left: 5px; } -.litespeed-wrap .button+.button { +.litespeed-wrap .button + .button { margin-left: 10px; } @@ -1096,8 +1146,8 @@ h3 .litespeed-learn-more { .litespeed-wrap .litespeed-btn-large { font-size: 1.5em; - padding: .75em 1.5em; - margin: 0 .25em; + padding: 0.75em 1.5em; + margin: 0 0.25em; height: auto; } @@ -1106,7 +1156,6 @@ h3 .litespeed-learn-more { width: auto; } - /* ======================================= SWITCH ======================================= */ @@ -1119,17 +1168,23 @@ h3 .litespeed-learn-more { position: relative; } -.litespeed-switch input:checked:active+label { - box-shadow: 0 2px 0 rgba(27, 146, 146, 0.7), inset 0 2px 5px -3px rgba(0, 0, 0, .5); +.litespeed-switch input:checked:active + label { + box-shadow: + 0 2px 0 rgba(27, 146, 146, 0.7), + inset 0 2px 5px -3px rgba(0, 0, 0, 0.5); } -.litespeed-switch input:checked+label { +.litespeed-switch input:checked + label { background-color: #36b0b0; color: #fff; border: 1px solid #36b0b0; box-shadow: 0 2px 0 #1b9292; z-index: 2; - text-shadow: 0 -1px 1px #1b9292, 1px 0 1px #1b9292, 0 1px 1px #1b9292, -1px 0 1px #1b9292; + text-shadow: + 0 -1px 1px #1b9292, + 1px 0 1px #1b9292, + 0 1px 1px #1b9292, + -1px 0 1px #1b9292; } .litespeed-switch label { @@ -1161,37 +1216,35 @@ h3 .litespeed-learn-more { border-bottom-left-radius: 3px; } -.litespeed-switch input:hover+label { +.litespeed-switch input:hover + label { border-color: #1a9292; box-shadow: 0 2px 0 #1a9292; z-index: 2; color: #117171; - } -.litespeed-switch input:focus+label { +.litespeed-switch input:focus + label { color: #117171; box-shadow: 0 0px 0px 2px rgba(28, 138, 128, 0.85); border-color: transparent; z-index: 2; - } -.litespeed-switch input:focus+label+input+input:hover+label, -.litespeed-switch input:focus+label+input:hover+label { +.litespeed-switch input:focus + label + input + input:hover + label, +.litespeed-switch input:focus + label + input:hover + label { z-index: 1; } -.litespeed-switch input:active+label { - box-shadow: 0 2px 0 #1b9292, inset 0 2px 5px -3px rgba(0, 0, 0, .5); +.litespeed-switch input:active + label { + box-shadow: + 0 2px 0 #1b9292, + inset 0 2px 5px -3px rgba(0, 0, 0, 0.5); } -.litespeed-switch input:checked:hover+label, -.litespeed-switch input:checked:focus+label { +.litespeed-switch input:checked:hover + label, +.litespeed-switch input:checked:focus + label { background-color: #36b0b0; color: #fff; - - } .litespeed-switch input { @@ -1224,7 +1277,7 @@ h3 .litespeed-learn-more { align-items: center; } -.litespeed-toggle-wrapper+.litespeed-toggle-wrapper { +.litespeed-toggle-wrapper + .litespeed-toggle-wrapper { margin-top: 0.75rem; } @@ -1346,8 +1399,8 @@ h3 .litespeed-learn-more { .litespeed-toggle-btn.litespeed-toggle-active { background-image: none; outline: 0; - -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); - box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); + box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .litespeed-toggle-btn-default:active, @@ -1358,9 +1411,9 @@ h3 .litespeed-learn-more { /* ======================================= LABEL/TAG ======================================= */ -[class*="litespeed-label-"] { +[class*='litespeed-label-'] { display: inline; - padding: .2em .6em .3em; + padding: 0.2em 0.6em 0.3em; font-size: 75%; font-weight: bold; line-height: 1; @@ -1368,17 +1421,17 @@ h3 .litespeed-learn-more { text-align: center; white-space: nowrap; vertical-align: baseline; - border-radius: .25em; + border-radius: 0.25em; } -[class*="litespeed-label-"]:hover, -[class*="litespeed-label-"]:focus { +[class*='litespeed-label-']:hover, +[class*='litespeed-label-']:focus { color: #fff; text-decoration: none; cursor: pointer; } -[class*="litespeed-label-"]:empty { +[class*='litespeed-label-']:empty { display: none; } @@ -1467,7 +1520,7 @@ h3 .litespeed-learn-more { .litespeed-shell-header-bg { opacity: 0.4; - background-color: #CCCCCC; + background-color: #cccccc; position: absolute; top: 0; bottom: 0; @@ -1485,7 +1538,7 @@ h3 .litespeed-learn-more { left: 0; z-index: 10; height: 2px; - background-color: #F48024; + background-color: #f48024; } .litespeed-shell-header-icon-container { @@ -1508,8 +1561,11 @@ ul.litespeed-shell-body { padding: 5px; list-style: none; background: #141414; - color: #45D40C; - font: 0.8em 'Andale Mono', Consolas, 'Courier New'; + color: #45d40c; + font: + 0.8em 'Andale Mono', + Consolas, + 'Courier New'; line-height: 1.6em; -webkit-border-bottom-right-radius: 3px; @@ -1518,7 +1574,6 @@ ul.litespeed-shell-body { -moz-border-radius-bottomleft: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; - } .litespeed-shell-body li:before { @@ -1541,7 +1596,6 @@ ul.litespeed-shell-body { margin: 5px -15px; } - /* ======================================= CALLOUT / NOTICE ======================================= */ @@ -1610,7 +1664,7 @@ ul.litespeed-shell-body { background: none; } -.litespeed-tick-list .litespeed-tick input[type="checkbox"] { +.litespeed-tick-list .litespeed-tick input[type='checkbox'] { margin-left: 0; } @@ -1618,8 +1672,7 @@ ul.litespeed-shell-body { color: inherit; } - -.litespeed-tick input[type="checkbox"] { +.litespeed-tick input[type='checkbox'] { height: 18px; width: 18px; vertical-align: middle; @@ -1633,20 +1686,19 @@ ul.litespeed-shell-body { cursor: pointer; } -.litespeed-tick input[type="checkbox"]:not(:disabled):hover { +.litespeed-tick input[type='checkbox']:not(:disabled):hover { border-color: #538ac6; - } -.litespeed-tick input[type="checkbox"]:active:not(:disabled) { +.litespeed-tick input[type='checkbox']:active:not(:disabled) { border-color: #538ac6; } -.litespeed-tick input[type="checkbox"]:focus { +.litespeed-tick input[type='checkbox']:focus { outline: none; } -.litespeed-tick input[type="checkbox"]:checked { +.litespeed-tick input[type='checkbox']:checked { border-color: #538ac6; background-color: #538ac6; -moz-box-shadow: none; @@ -1654,7 +1706,7 @@ ul.litespeed-shell-body { box-shadow: none; } -.litespeed-tick input[type="checkbox"]:checked:before { +.litespeed-tick input[type='checkbox']:checked:before { content: ''; display: block; width: 5px; @@ -1689,7 +1741,7 @@ ul.litespeed-shell-body { padding-left: 1.5rem; } -.litespeed-radio-row input[type=radio] { +.litespeed-radio-row input[type='radio'] { margin-top: 0; margin-bottom: 0; position: absolute; @@ -1768,11 +1820,11 @@ ul.litespeed-shell-body { min-width: 110px; } -input.litespeed-input[type="file"] { +input.litespeed-input[type='file'] { padding: 9px; min-width: 500px; border: 1px solid #ddd; - box-shadow: inset 0 1px 2px rgba(0, 0, 0, .07); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.07); background-color: #fff; color: #32373c; outline: 0; @@ -1804,7 +1856,7 @@ input.litespeed-input-warning { margin: 0; } -.litespeed-textarea-recommended>div:first-child { +.litespeed-textarea-recommended > div:first-child { margin-top: 1.7em; font-size: 12px; margin-right: 25px; @@ -1816,7 +1868,7 @@ input.litespeed-input-warning { text-align: center; } -.litespeed-collection-button[data-action="add"] { +.litespeed-collection-button[data-action='add'] { margin-top: -5px; margin-left: -5px; } @@ -1831,11 +1883,8 @@ input.litespeed-input-warning { top: 0; } -@media screen and (max-width: 1023px) and (min-width: 681px) {} - @media screen and (max-width: 680px) { - - .litespeed-body tbody>tr>th { + .litespeed-body tbody > tr > th { display: block; padding: 18px 0 5px 12px; } @@ -1856,7 +1905,7 @@ input.litespeed-input-warning { flex-direction: column; } - .litespeed-textarea-recommended>div:first-child { + .litespeed-textarea-recommended > div:first-child { margin-bottom: 1.7em; margin-top: 0; } @@ -1936,7 +1985,7 @@ input.litespeed-input-warning { } .litespeed-banner-promo-slacklogo { - background-image: url("../img/slack-logo.png"); + background-image: url('../img/slack-logo.png'); background-size: contain; width: 75px; height: 75px; @@ -1964,7 +2013,7 @@ input.litespeed-input-warning { .litespeed-banner-promo-slack-line2 { font-size: 15px; margin: 0px; - line-height: .75em; + line-height: 0.75em; } .litespeed-banner-promo-slack-link { @@ -2035,7 +2084,15 @@ a.litespeed-btn-xs.litespeed-banner-promo-slack-btn { } .litespeed-tweet-text { - font: 14px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu, "Helvetica Neue", sans-serif; + font: + 14px system-ui, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + Roboto, + Ubuntu, + 'Helvetica Neue', + sans-serif; line-height: 1.3125; } @@ -2044,9 +2101,8 @@ a.litespeed-btn-xs.litespeed-banner-promo-slack-btn { margin-top: 1em; } - .litespeed-tweet-cta a { - background-color: #1DA1F2; + background-color: #1da1f2; line-height: 1.3125; color: #fff; font-weight: bold; @@ -2058,7 +2114,7 @@ a.litespeed-btn-xs.litespeed-banner-promo-slack-btn { } .litespeed-tweet-cta a:hover { - background-color: #1E98E1; + background-color: #1e98e1; } .litespeed-tweet-cta a svg { @@ -2082,7 +2138,7 @@ a.litespeed-btn-xs.litespeed-banner-promo-slack-btn { vertical-align: middle; } -.litespeed-tweet-img+p { +.litespeed-tweet-img + p { margin-top: 0; } @@ -2094,7 +2150,7 @@ a.litespeed-btn-xs.litespeed-banner-promo-slack-btn { display: inline-table; } -[class*="litespeed-icon-media-"] { +[class*='litespeed-icon-media-'] { background-size: contain; width: 25px; height: 25px; @@ -2104,24 +2160,24 @@ a.litespeed-btn-xs.litespeed-banner-promo-slack-btn { display: inline-block; } -[class*="litespeed-icon-media-"]:hover { +[class*='litespeed-icon-media-']:hover { opacity: 0.7; } .litespeed-icon-media-webp { - background-image: url("../img/icons/img_webp.svg"); + background-image: url('../img/icons/img_webp.svg'); } .litespeed-icon-media-webp-disabled { - background-image: url("../img/icons/img_webp_disabled.svg"); + background-image: url('../img/icons/img_webp_disabled.svg'); } .litespeed-icon-media-optm { - background-image: url("../img/icons/img_optm.svg"); + background-image: url('../img/icons/img_optm.svg'); } .litespeed-icon-media-optm-disabled { - background-image: url("../img/icons/img_optm_disabled.svg"); + background-image: url('../img/icons/img_optm_disabled.svg'); } p.litespeed-media-p { @@ -2162,7 +2218,6 @@ p.litespeed-txt-disabled { margin: 5px 5px 5px 0; } - circle.litespeed-pie_bg { stroke: #efefef; stroke-width: 2; @@ -2182,7 +2237,6 @@ circle.litespeed-pie_circle { fill: none; } - .litespeed-pie.litespeed-pie-tiny { margin: 0 2px 0 0; } @@ -2190,7 +2244,6 @@ circle.litespeed-pie_circle { .litespeed-pie.litespeed-pie-tiny text { font-weight: bold; fill: #828282; - } .litespeed-pie.litespeed-pie-tiny circle { @@ -2287,7 +2340,7 @@ g.litespeed-pie_info .litespeed-pie-done { margin-left: 10px; } -#cookie_crawler>p:first-child { +#cookie_crawler > p:first-child { margin-top: 5px; } @@ -2309,7 +2362,7 @@ g.litespeed-pie_info .litespeed-pie-done { color: #fff; text-align: center; background-color: #007bff; - transition: width .6s ease; + transition: width 0.6s ease; } .litespeed-progress-bar-yellow { @@ -2322,7 +2375,7 @@ g.litespeed-pie_info .litespeed-pie-done { display: flex; height: 12px; overflow: hidden; - font-size: .75rem; + font-size: 0.75rem; background-color: #e9ecef; border: 1px solid #dddddd; border-radius: 8px; @@ -2378,10 +2431,9 @@ g.litespeed-pie_info .litespeed-pie-done { } .litespeed-guide li.litespeed-guide-done { - opacity: .9; + opacity: 0.9; } - /* ======================================= VIEW - image optimization ======================================= */ @@ -2390,7 +2442,6 @@ g.litespeed-pie_info .litespeed-pie-done { padding: 0; } - .litespeed-cache_page_litespeed-img_optm .nav-tab-wrapper { border-bottom: none; position: relative; @@ -2407,7 +2458,7 @@ g.litespeed-pie_info .litespeed-pie-done { .litespeed-cache_page_litespeed-img_optm [data-litespeed-layout]:not([data-litespeed-layout='summary']) { background: #fff; border: 1px solid #e5e5e5; - box-shadow: 0 1px 1px rgba(0, 0, 0, .04); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); padding: 1px 20px 20px 20px; } @@ -2415,23 +2466,23 @@ g.litespeed-pie_info .litespeed-pie-done { background: #f9fafc; } -.litespeed-column-with-boxes>div:first-child { +.litespeed-column-with-boxes > div:first-child { padding-right: 25px; } -.litespeed-column-with-boxes>div:last-child { +.litespeed-column-with-boxes > div:last-child { background: #f1f1f1; padding-top: 0; padding-right: 0; padding-left: 0; } -.litespeed-column-with-boxes>div:last-child .litespeed-postbox:last-child { +.litespeed-column-with-boxes > div:last-child .litespeed-postbox:last-child { margin-bottom: 0; } .litespeed-image-optim-summary { - box-shadow: 0 1px 1px rgba(0, 0, 0, .04); + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04); position: relative; padding: 1px 20px 20px 20px; background: #fff; @@ -2463,12 +2514,12 @@ g.litespeed-pie_info .litespeed-pie-done { margin-top: 0; } -.litespeed-image-optim-summary>h3:first-child { +.litespeed-image-optim-summary > h3:first-child { margin-top: 1.6em; font-size: 1.2em; } -.litespeed-image-optim-summary>h3:first-child .litespeed-quic-icon { +.litespeed-image-optim-summary > h3:first-child .litespeed-quic-icon { width: 1.2em; height: 1.4em; background-size: contain; @@ -2497,7 +2548,7 @@ g.litespeed-pie_info .litespeed-pie-done { } @media screen and (max-width: 814px) { - .litespeed-column-with-boxes>div:first-child { + .litespeed-column-with-boxes > div:first-child { padding-right: 0; margin-bottom: 1rem; } @@ -2516,7 +2567,7 @@ g.litespeed-pie_info .litespeed-pie-done { margin-top: 0; } -.imgoptm.column-imgoptm p+.row-actions { +.imgoptm.column-imgoptm p + .row-actions { margin-top: 0.5em; } @@ -2549,7 +2600,7 @@ g.litespeed-pie_info .litespeed-pie-done { margin-bottom: 1rem; } -.litespeed-dashboard-group>.litespeed-flex-container { +.litespeed-dashboard-group > .litespeed-flex-container { margin: 0 -10px; min-width: 100%; width: auto; @@ -2557,7 +2608,6 @@ g.litespeed-pie_info .litespeed-pie-done { .litespeed-dashboard .litespeed-postbox { margin: 10px; - } .litespeed-dashboard-title a { @@ -2601,7 +2651,7 @@ g.litespeed-pie_info .litespeed-pie-done { color: #777; } -.litespeed-dashboard-stats h3+p { +.litespeed-dashboard-stats h3 + p { margin-top: 0; margin-bottom: 0; } @@ -2647,7 +2697,7 @@ g.litespeed-pie_info .litespeed-pie-done { height: 60px; } -.litespeed-dashboard-stats-wrapper .litespeed-flex-container+p:not(:last-child) { +.litespeed-dashboard-stats-wrapper .litespeed-flex-container + p:not(:last-child) { margin-bottom: 0.55em; } @@ -2659,12 +2709,11 @@ g.litespeed-pie_info .litespeed-pie-done { color: #444; } -.postbox .inside>p.litespeed-dashboard-stats-payg { +.postbox .inside > p.litespeed-dashboard-stats-payg { margin-top: 1.35em; } -.postbox .inside>p.litespeed-dashboard-stats-payg:last-child { - +.postbox .inside > p.litespeed-dashboard-stats-payg:last-child { margin-bottom: -5px !important; } @@ -2755,16 +2804,16 @@ g.litespeed-pie_info .litespeed-pie-done { .litespeed-label-dashboard { font-size: 0.92em; - padding: .3em .6em .35em .6em; + padding: 0.3em 0.6em 0.35em 0.6em; font-weight: normal; display: inline-block; - margin-left: .2em; + margin-left: 0.2em; min-width: 2em; } .litespeed-label-dashboard:first-child { margin-left: 0; - margin-right: .35em; + margin-right: 0.35em; } .litespeed-postbox .inside { @@ -2786,12 +2835,16 @@ g.litespeed-pie_info .litespeed-pie-done { margin-top: 0; } +.litespeed-postbox-footer a, +a.litespeed-redetect { + text-decoration: none; +} + .litespeed-postbox .inside.litespeed-postbox-footer--compact { padding: 7px 20px 8px 20px; font-size: 12px; } - .litespeed-postbox-imgopt .litespeed-pie { width: 55px; height: 55px; @@ -2802,15 +2855,15 @@ g.litespeed-pie_info .litespeed-pie-done { margin-bottom: 10px; } -.litespeed-postbox-imgopt .litespeed-flex-container .litespeed-icon-vertical-middle+div h3 { +.litespeed-postbox-imgopt .litespeed-flex-container .litespeed-icon-vertical-middle + div h3 { margin-top: 0; } -.litespeed-postbox-imgopt .litespeed-flex-container .litespeed-icon-vertical-middle+div p { +.litespeed-postbox-imgopt .litespeed-flex-container .litespeed-icon-vertical-middle + div p { line-height: 1.2; } -.litespeed-postbox-imgopt .litespeed-postbox-double-col:last-child>*:first-child { +.litespeed-postbox-imgopt .litespeed-postbox-double-col:last-child > *:first-child { margin-top: 7px; } @@ -2854,7 +2907,7 @@ g.litespeed-pie_info .litespeed-pie-done { margin-bottom: 1em; } -.litespeed-links-group>span:not(:last-child):after { +.litespeed-links-group > span:not(:last-child):after { content: '|'; margin: 0 10px; color: #ddd; @@ -2888,11 +2941,11 @@ g.litespeed-pie_info .litespeed-pie-done { line-height: 1; } -span[data-balloon-pos] { +.litespeed-wrap span[data-balloon-pos] { border-bottom: 1px dashed; } -span[aria-label][data-balloon-pos] { +.litespeed-wrap span[aria-label][data-balloon-pos] { cursor: default; } @@ -2915,7 +2968,6 @@ span[aria-label][data-balloon-pos] { } @media screen and (max-width: 1023px) { - .litespeed-dashboard-stats-wrapper { flex-wrap: wrap; } @@ -2969,12 +3021,10 @@ span[aria-label][data-balloon-pos] { /********************************* todo *******************************/ - /* image optimize page */ - .litespeed-column-java { - background: #5CADAD !important; + background: #5cadad !important; } .litespeed-text-shipgrey { @@ -2990,19 +3040,19 @@ span[aria-label][data-balloon-pos] { } .litespeed-text-whisper { - color: #E6E6E6 !important; + color: #e6e6e6 !important; } .litespeed-text-malibu { - color: #5CBDDE !important; + color: #5cbdde !important; } .litespeed-text-morningglory { - color: #99CCCC !important; + color: #99cccc !important; } .litespeed-text-fern { - color: #66CC66 !important; + color: #66cc66 !important; } .litespeed-text-persiangreen { @@ -3032,7 +3082,7 @@ span[aria-label][data-balloon-pos] { .litespeed-hr { padding-bottom: 1.5em; - border-bottom: .5px solid #97CACA; + border-bottom: 0.5px solid #97caca; } .litespeed-hr-with-space { @@ -3047,7 +3097,6 @@ span[aria-label][data-balloon-pos] { margin: 0px 10px 0px 10px; } - .litespeed-column-java .litespeed-danger { color: #c1c53a !important; } @@ -3070,7 +3119,7 @@ span[aria-label][data-balloon-pos] { } .litespeed-refresh:after { - content: "⟳"; + content: '⟳'; width: 20px; height: 20px; color: #40ad3a; @@ -3091,7 +3140,7 @@ span[aria-label][data-balloon-pos] { } .litespeed-silence { - color: #B1B1B1; + color: #b1b1b1; } .litespeed-column-java .litespeed-congratulate { @@ -3117,11 +3166,11 @@ span[aria-label][data-balloon-pos] { } .litespeed-column-java svg.litespeed-pie circle.litespeed-pie_circle { - stroke: #97CACA; + stroke: #97caca; } .litespeed-column-java svg .litespeed-pie_info text { - fill: #F5FFEB; + fill: #f5ffeb; } .litespeed-column-java svg g.litespeed-pie_info .litespeed-pie-done { @@ -3137,12 +3186,12 @@ span[aria-label][data-balloon-pos] { } .litespeed-progress-bar-blue { - background-color: #33ADFF; + background-color: #33adff; } .litespeed-status-current { font-size: 3.5em; - margin: 1.25em 0em .75em 0em; + margin: 1.25em 0em 0.75em 0em; } /* .litespeed-title, .litespeed-title-short { @@ -3152,71 +3201,70 @@ span[aria-label][data-balloon-pos] { } */ .litespeed-column-java .litespeed-desc { - color: #CAE4E4; + color: #cae4e4; } .litespeed-column-java .litespeed-warning { - color: #FFD597 !important; + color: #ffd597 !important; } .litespeed-column-java .litespeed-btn-success { - color: #DDF1E4; - border: 1px solid #33AD5C; - background: #33AD5C; + color: #ddf1e4; + border: 1px solid #33ad5c; + background: #33ad5c; } .litespeed-column-java .litespeed-btn-success:hover { - color: #FFFFFF; - border: 1px solid #7DCA97; + color: #ffffff; + border: 1px solid #7dca97; background: #009933; } .litespeed-column-java .litespeed-btn-warning { - color: #FFF1DD; - border: 1px solid #FF9933; - background-color: #FF9933; + color: #fff1dd; + border: 1px solid #ff9933; + background-color: #ff9933; } .litespeed-column-java .litespeed-btn-warning:hover { - color: #FFFFFF; - border-color: #FFCA7D; - background: #FF9900; + color: #ffffff; + border-color: #ffca7d; + background: #ff9900; } .litespeed-column-java .litespeed-btn-danger { - color: #FFEADD !important; - border: 1px solid #FF6600 !important; - background: #FF5C5C; + color: #ffeadd !important; + border: 1px solid #ff6600 !important; + background: #ff5c5c; } .litespeed-column-java .litespeed-btn-danger:hover { - color: #FFFFFF; - border: 1px solid #FF9797 !important; - background: #FF0000; + color: #ffffff; + border: 1px solid #ff9797 !important; + background: #ff0000; } .litespeed-column-java .litepseed-dash-icon-success, .litepseed-dash-icon-success { - color: #5CDEDE; + color: #5cdede; font-size: 2em; - margin-top: -.25em; + margin-top: -0.25em; } .litespeed-column-java .litepseed-dash-icon-success:hover, .litepseed-dash-icon-success:hover { - color: #7DE5E5; + color: #7de5e5; } .litespeed-dashicons-large { font-size: 2em; } - .litespeed-column-java p { - color: #FFFFFF; + color: #ffffff; } -.litespeed-body tbody>tr>th.litespeed-padding-left { +.litespeed-body tbody > tr > th.litespeed-padding-left { padding-left: 3em; } @@ -3242,9 +3290,9 @@ span[aria-label][data-balloon-pos] { a.litespeed-media-href svg:hover { border-radius: 50%; - background: #F1FCFF; - fill: #5CCAD7; - box-shadow: 0 0 5px 1px #7DD5DF; + background: #f1fcff; + fill: #5ccad7; + box-shadow: 0 0 5px 1px #7dd5df; transition: all 0.2s ease-out; transform: scale(1.05); } @@ -3258,21 +3306,21 @@ a.litespeed-media-href svg:hover { } .litespeed-media-p a .dashicons-trash:hover { - transition: all .2s ease-out; - color: #FFA500 !important; - background: #FFF5E6; - box-shadow: 0 0 10px 1px #FF8C00; + transition: all 0.2s ease-out; + color: #ffa500 !important; + background: #fff5e6; + box-shadow: 0 0 10px 1px #ff8c00; } -.litespeed-media-p div>svg circle.litespeed-pie_bg { +.litespeed-media-p div > svg circle.litespeed-pie_bg { stroke: #ecf2f9; } -.litespeed-media-p div>svg circle.litespeed-pie_circle { +.litespeed-media-p div > svg circle.litespeed-pie_circle { stroke: #9fbfdf; } -.litespeed-media-p div>svg { +.litespeed-media-p div > svg { fill: #538cc6; background: rgba(236, 242, 249, 0.1); border-radius: 50%; @@ -3320,16 +3368,9 @@ a.litespeed-media-href svg:hover { .litespeed-notice-dismiss:hover, .litespeed-notice-dismiss:active, .litespeed-notice-dismiss:focus { - color: #CC2929; + color: #cc2929; } - - - - - - - .litespeed-dot { display: inline-block; border-radius: 50%; @@ -3348,30 +3389,183 @@ a.litespeed-media-href svg:hover { text-align: center; } +/* ======================================= + Comparison Cards - Presets +======================================= */ + +.litespeed-comparison-card { + box-sizing: border-box; +} + +.litespeed-comparison-card-rec .litespeed-card-content > div.litespeed-card-body { + font-size: 14px; +} + +.litespeed-comparison-card-rec .litespeed-card-action { + margin-bottom: 0.25rem; +} + +.litespeed-comparison-card-rec h3 { + font-size: 20px; +} + +.litespeed-card-content > div, +.litespeed-card-action { + padding: 0.85rem 1.25rem; +} + +.litespeed-card-header { + border-bottom: 1px solid #eee; + background: #f9fafc; +} + +.litespeed-card-content > div.litespeed-card-body { + align-self: stretch; + justify-content: flex-end; + font-size: 15px; + padding-bottom: 0.5rem; + padding-top: 1rem; +} + +.litespeed-card-content > div.litespeed-card-footer { + align-self: stretch; + justify-content: flex-end; + padding-bottom: 0; + padding-top: 0.25rem; +} + +.litespeed-card-action { + justify-content: flex-end; +} + +.litespeed-comparison-card ul { + padding-left: 20px; + list-style: none; + list-style-position: outside; + margin: 0; +} + +.litespeed-comparison-card li { + margin-bottom: 0.5em; + line-height: 1.4; +} + +.litespeed-comparison-card li:last-child { + margin-bottom: 0; +} + +.litespeed-comparison-card ul li:before { + content: '✓'; + margin-left: -1em; + margin-right: 0.35em; + color: #329c74; +} + +@media screen and (max-width: 1279px) { + .litespeed-comparison-card { + margin: 0 0 -1px 0; + } +} + +@media screen and (min-width: 640px) and (max-width: 1279px) { + .litespeed-comparison-cards { + max-width: 740px; + } + + .litespeed-card-content { + display: flex; + flex-wrap: wrap; + } + + .litespeed-card-content .litespeed-card-header { + width: 100%; + } + + .litespeed-card-content > div.litespeed-card-body { + align-self: initial; + width: 50%; + box-sizing: border-box; + } + + .litespeed-card-content > div.litespeed-card-footer { + width: 50%; + align-self: initial; + box-sizing: border-box; + } + + .litespeed-card-content > div.litespeed-card-footer h4 { + margin-top: 1rem; + } +} + +@media screen and (min-width: 1280px) { + .litespeed-comparison-cards { + display: flex; + margin: 3rem 0 2rem 0; + max-width: 1720px; + } + + .litespeed-comparison-card { + width: 19%; + min-width: 0; + display: flex; + flex-direction: column; + margin-right: -1px; + justify-content: space-between; + } + + .litespeed-comparison-card:first-child { + border-top-left-radius: 5px; + border-bottom-left-radius: 5px; + overflow: hidden; + } + + .litespeed-comparison-card:last-child { + border-top-right-radius: 5px; + border-bottom-right-radius: 5px; + overflow: hidden; + } + + .litespeed-comparison-card-rec { + width: 23%; + padding-top: 1rem; + padding-bottom: 0.75rem; + margin-top: -1rem; + margin-bottom: 0.25rem; + border-radius: 5px; + overflow: hidden; + } + + .litespeed-comparison-card-rec .litespeed-card-header { + margin-top: -1rem; + padding-top: 1.75rem; + padding-bottom: 0.95rem; + } +} /* ======================================= BALLOON PURE CSS TOOLTIPS ======================================= */ -:root { +.litespeed-wrap { --balloon-color: rgba(16, 16, 16, 0.95); --balloon-font-size: 12px; --balloon-move: 4px; } -button[aria-label][data-balloon-pos] { +.litespeed-wrap button[aria-label][data-balloon-pos] { overflow: visible; } -[aria-label][data-balloon-pos] { +.litespeed-wrap [aria-label][data-balloon-pos] { position: relative; cursor: pointer; } -[aria-label][data-balloon-pos]:after { +.litespeed-wrap [aria-label][data-balloon-pos]:after { opacity: 0; pointer-events: none; - transition: all .2s ease .05s; + transition: all 0.2s ease 0.05s; text-indent: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; font-weight: normal; @@ -3382,55 +3576,66 @@ button[aria-label][data-balloon-pos] { border-radius: 2px; color: #fff; content: attr(aria-label); - padding: .5em 1em; + padding: 0.5em 1em; position: absolute; white-space: nowrap; z-index: 10; line-height: 1.4; } -[aria-label][data-balloon-pos]:before { +.litespeed-wrap [aria-label][data-balloon-pos]:before { width: 0; height: 0; border: 5px solid transparent; border-top-color: var(--balloon-color); opacity: 0; pointer-events: none; - transition: all .2s ease .05s; - content: ""; + transition: all 0.2s ease 0.05s; + content: ''; position: absolute; z-index: 10; } -[aria-label][data-balloon-pos]:hover:before, -[aria-label][data-balloon-pos]:hover:after, -[aria-label][data-balloon-pos][data-balloon-visible]:before, -[aria-label][data-balloon-pos][data-balloon-visible]:after, -[aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:before, -[aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:after { +.litespeed-wrap [aria-label][data-balloon-pos]:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos]:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-visible]:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-visible]:after, +.litespeed-wrap [aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:before, +.litespeed-wrap [aria-label][data-balloon-pos]:not([data-balloon-nofocus]):focus:after { opacity: 1; pointer-events: none; } -[aria-label][data-balloon-pos].font-awesome:after { - font-family: FontAwesome, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; +.litespeed-wrap [aria-label][data-balloon-pos].font-awesome:after { + font-family: + FontAwesome, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + Roboto, + Oxygen, + Ubuntu, + Cantarell, + 'Open Sans', + 'Helvetica Neue', + sans-serif; } -[aria-label][data-balloon-pos][data-balloon-break]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-break]:after { white-space: pre; } -[aria-label][data-balloon-pos][data-balloon-break][data-balloon-length]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-break][data-balloon-length]:after { white-space: pre-line; word-break: break-word; } -[aria-label][data-balloon-pos][data-balloon-blunt]:before, -[aria-label][data-balloon-pos][data-balloon-blunt]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-blunt]:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-blunt]:after { transition: none; } -[aria-label][data-balloon-pos][data-balloon-pos="up"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up']:after { bottom: 100%; left: 50%; margin-bottom: 10px; @@ -3438,24 +3643,24 @@ button[aria-label][data-balloon-pos] { transform-origin: top; } -[aria-label][data-balloon-pos][data-balloon-pos="up"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up']:before { bottom: 100%; left: 50%; transform: translate(-50%, var(--balloon-move)); transform-origin: top; } -[aria-label][data-balloon-pos][data-balloon-pos="up"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="up"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up'][data-balloon-visible]:after { transform: translate(-50%, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="up"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="up"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up'][data-balloon-visible]:before { transform: translate(-50%, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="up-left"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-left']:after { bottom: 100%; left: 0; margin-bottom: 10px; @@ -3463,24 +3668,24 @@ button[aria-label][data-balloon-pos] { transform-origin: top; } -[aria-label][data-balloon-pos][data-balloon-pos="up-left"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-left']:before { bottom: 100%; left: 5px; transform: translate(0, var(--balloon-move)); transform-origin: top; } -[aria-label][data-balloon-pos][data-balloon-pos="up-left"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="up-left"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-left']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-left'][data-balloon-visible]:after { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="up-left"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="up-left"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-left']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-left'][data-balloon-visible]:before { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="up-right"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-right']:after { bottom: 100%; right: 0; margin-bottom: 10px; @@ -3488,31 +3693,31 @@ button[aria-label][data-balloon-pos] { transform-origin: top; } -[aria-label][data-balloon-pos][data-balloon-pos="up-right"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-right']:before { bottom: 100%; right: 5px; transform: translate(0, var(--balloon-move)); transform-origin: top; } -[aria-label][data-balloon-pos][data-balloon-pos="up-right"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="up-right"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-right']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-right'][data-balloon-visible]:after { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="up-right"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="up-right"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-right']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='up-right'][data-balloon-visible]:before { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="down"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down']:after { left: 50%; margin-top: 10px; top: 100%; transform: translate(-50%, calc(var(--balloon-move) * -1)); } -[aria-label][data-balloon-pos][data-balloon-pos="down"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down']:before { width: 0; height: 0; border: 5px solid transparent; @@ -3522,24 +3727,24 @@ button[aria-label][data-balloon-pos] { transform: translate(-50%, calc(var(--balloon-move) * -1)); } -[aria-label][data-balloon-pos][data-balloon-pos="down"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="down"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down'][data-balloon-visible]:after { transform: translate(-50%, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="down"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="down"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down'][data-balloon-visible]:before { transform: translate(-50%, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="down-left"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-left']:after { left: 0; margin-top: 10px; top: 100%; transform: translate(0, calc(var(--balloon-move) * -1)); } -[aria-label][data-balloon-pos][data-balloon-pos="down-left"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-left']:before { width: 0; height: 0; border: 5px solid transparent; @@ -3549,24 +3754,24 @@ button[aria-label][data-balloon-pos] { transform: translate(0, calc(var(--balloon-move) * -1)); } -[aria-label][data-balloon-pos][data-balloon-pos="down-left"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="down-left"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-left']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-left'][data-balloon-visible]:after { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="down-left"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="down-left"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-left']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-left'][data-balloon-visible]:before { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="down-right"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-right']:after { right: 0; margin-top: 10px; top: 100%; transform: translate(0, calc(var(--balloon-move) * -1)); } -[aria-label][data-balloon-pos][data-balloon-pos="down-right"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-right']:before { width: 0; height: 0; border: 5px solid transparent; @@ -3576,24 +3781,24 @@ button[aria-label][data-balloon-pos] { transform: translate(0, calc(var(--balloon-move) * -1)); } -[aria-label][data-balloon-pos][data-balloon-pos="down-right"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="down-right"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-right']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-right'][data-balloon-visible]:after { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="down-right"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="down-right"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-right']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='down-right'][data-balloon-visible]:before { transform: translate(0, 0); } -[aria-label][data-balloon-pos][data-balloon-pos="left"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='left']:after { margin-right: 10px; right: 100%; top: 50%; transform: translate(var(--balloon-move), -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="left"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='left']:before { width: 0; height: 0; border: 5px solid transparent; @@ -3603,24 +3808,24 @@ button[aria-label][data-balloon-pos] { transform: translate(var(--balloon-move), -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="left"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="left"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='left']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='left'][data-balloon-visible]:after { transform: translate(0, -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="left"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="left"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='left']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='left'][data-balloon-visible]:before { transform: translate(0, -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="right"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='right']:after { left: 100%; margin-left: 10px; top: 50%; transform: translate(calc(var(--balloon-move) * -1), -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="right"]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='right']:before { width: 0; height: 0; border: 5px solid transparent; @@ -3630,44 +3835,44 @@ button[aria-label][data-balloon-pos] { transform: translate(calc(var(--balloon-move) * -1), -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="right"]:hover:after, -[aria-label][data-balloon-pos][data-balloon-pos="right"][data-balloon-visible]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='right']:hover:after, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='right'][data-balloon-visible]:after { transform: translate(0, -50%); } -[aria-label][data-balloon-pos][data-balloon-pos="right"]:hover:before, -[aria-label][data-balloon-pos][data-balloon-pos="right"][data-balloon-visible]:before { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='right']:hover:before, +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-pos='right'][data-balloon-visible]:before { transform: translate(0, -50%); } -[aria-label][data-balloon-pos][data-balloon-length="small"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-length='small']:after { white-space: normal; width: 80px; } -[aria-label][data-balloon-pos][data-balloon-length="medium"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-length='medium']:after { white-space: normal; width: 150px; } -[aria-label][data-balloon-pos][data-balloon-length="large"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-length='large']:after { white-space: normal; width: 260px; } -[aria-label][data-balloon-pos][data-balloon-length="xlarge"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-length='xlarge']:after { white-space: normal; width: 380px; } @media screen and (max-width: 768px) { - [aria-label][data-balloon-pos][data-balloon-length="xlarge"]:after { + .litespeed-wrap [aria-label][data-balloon-pos][data-balloon-length='xlarge']:after { white-space: normal; width: 90vw; } } -[aria-label][data-balloon-pos][data-balloon-length="fit"]:after { +.litespeed-wrap [aria-label][data-balloon-pos][data-balloon-length='fit']:after { white-space: normal; width: 100%; -} \ No newline at end of file +} diff --git a/assets/img/iconlscwp.svg b/assets/img/iconlscwp.svg new file mode 100644 index 000000000..af5b1f32a --- /dev/null +++ b/assets/img/iconlscwp.svg @@ -0,0 +1,12 @@ + + + +LiteSpeed Technologies + + + + + + + + diff --git a/assets/img/lscwp_blue_font-icon_22px.svg b/assets/img/lscwp_blue_font-icon_22px.svg new file mode 100644 index 000000000..c30f19191 --- /dev/null +++ b/assets/img/lscwp_blue_font-icon_22px.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/img/lscwp_font-icon_32px.svg b/assets/img/lscwp_font-icon_32px.svg new file mode 100644 index 000000000..7a4d2045d --- /dev/null +++ b/assets/img/lscwp_font-icon_32px.svg @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/assets/img/lscwp_gray-yellow_font-icon_22px.svg b/assets/img/lscwp_gray-yellow_font-icon_22px.svg new file mode 100644 index 000000000..5e459a166 --- /dev/null +++ b/assets/img/lscwp_gray-yellow_font-icon_22px.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/img/lscwp_gray_font-icon_22px.svg b/assets/img/lscwp_gray_font-icon_22px.svg new file mode 100644 index 000000000..3375bf0e2 --- /dev/null +++ b/assets/img/lscwp_gray_font-icon_22px.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/img/lscwp_grayscale_font-icon_22px.svg b/assets/img/lscwp_grayscale_font-icon_22px.svg new file mode 100644 index 000000000..424b1c6cb --- /dev/null +++ b/assets/img/lscwp_grayscale_font-icon_22px.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/assets/img/quic-cloud-logo-light_stack_300px.png b/assets/img/quic-cloud-logo-light_stack_300px.png new file mode 100644 index 000000000..5af6321f6 Binary files /dev/null and b/assets/img/quic-cloud-logo-light_stack_300px.png differ diff --git a/assets/img/quic-cloud-logo.svg b/assets/img/quic-cloud-logo.svg new file mode 100644 index 000000000..12f2c82c8 --- /dev/null +++ b/assets/img/quic-cloud-logo.svg @@ -0,0 +1,120 @@ + + + + + + +]> + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/js/component.cdn.js b/assets/js/component.cdn.js index 36f275f8d..d186dc407 100644 --- a/assets/js/component.cdn.js +++ b/assets/js/component.cdn.js @@ -3,50 +3,51 @@ * @author Hai Zheng */ class CDNMapping extends React.Component { - constructor( props ) { - super( props ); + constructor(props) { + super(props); this.state = { - list: props.list + list: props.list, }; - this.onChange = this.onChange.bind( this ); - this.delRow = this.delRow.bind( this ); - this.addNew = this.addNew.bind( this ); + this.onChange = this.onChange.bind(this); + this.delRow = this.delRow.bind(this); + this.addNew = this.addNew.bind(this); } - onChange( e, index ) { + onChange(e, index) { const target = e.currentTarget; - const value = target.dataset.hasOwnProperty('value') ? Boolean(target.dataset.value*1) : target.value; + const value = target.dataset.hasOwnProperty('value') ? Boolean(target.dataset.value * 1) : target.value; const list = this.state.list; - list[ index ][ target.dataset.type ] = value; + list[index][target.dataset.type] = value; - this.setState( { - list: list - } ); + this.setState({ + list: list, + }); } - delRow( index ) { + delRow(index) { const data = this.state.list; - data.splice( index, 1 ); - this.setState( { list: data } ); + data.splice(index, 1); + this.setState({ list: data }); } addNew() { const list = this.state.list; - list.push( { url: '' } ); - this.setState( { list: list } ); + list.push({ url: '' }); + this.setState({ list: list }); } render() { return ( - { this.state.list.map( (item, i) => ( - - ) ) } + {this.state.list.map((item, i) => ( + + ))}

@@ -56,94 +57,114 @@ class CDNMapping extends React.Component { // { url: '', inc_img: true, inc_css: false, inc_js: false, filetype: [ '.aac', '.eot', ... ] } class CDNMappingBlock extends React.Component { - constructor( props ) { - super( props ); + constructor(props) { + super(props); - this.onChange = this.onChange.bind( this ); - this.delRow = this.delRow.bind( this ); + this.onChange = this.onChange.bind(this); + this.delRow = this.delRow.bind(this); } - onChange( e ) { - this.props.onChange( e, this.props.index ); + onChange(e) { + this.props.onChange(e, this.props.index); } delRow() { - this.props.delRow( this.props.index ); + this.props.delRow(this.props.index); } render() { - const name_prefix = litespeed_data[ 'ids' ][ 'cdn_mapping' ]; + const name_prefix = litespeed_data['ids']['cdn_mapping']; const item = this.props.item; - const filetype = item.filetype ? Array.isArray(item.filetype) ? item.filetype.join("\n") : item.filetype : ''; + const filetype = item.filetype ? (Array.isArray(item.filetype) ? item.filetype.join('\n') : item.filetype) : ''; return (
-
- - +
+ +
- +
-
- { litespeed_data[ 'lang' ][ 'cdn_mapping_inc_img' ] } -
-
- -
- - - +
{litespeed_data['lang']['cdn_mapping_inc_img']}
+
+ +
+ + +
-
- { litespeed_data[ 'lang' ][ 'cdn_mapping_inc_css' ] } -
-
- -
- - - +
{litespeed_data['lang']['cdn_mapping_inc_css']}
+
+ +
+ + +
-
- { litespeed_data[ 'lang' ][ 'cdn_mapping_inc_js' ] } -
-
- -
- - - +
{litespeed_data['lang']['cdn_mapping_inc_js']}
+
+ +
+ + +
- - "; + echo "'; - $this->_check_overwritten( $id ); + $this->_check_overwritten($id); } /** @@ -817,31 +875,31 @@ public function build_textarea( $id, $cols = false, $val = null ) { * @since 1.1.0 * @access public */ - public function build_input( $id, $cls = null, $val = null, $type = 'text', $disabled = false ) { - if ( $val === null ) { - $val = $this->conf( $id, true ); + public function build_input($id, $cls = null, $val = null, $type = 'text', $disabled = false) + { + if ($val === null) { + $val = $this->conf($id, true); // Mask pswds - if ( $this->_conf_pswd( $id ) && $val ) { - $val = str_repeat( '*', strlen( $val ) ); + if ($this->_conf_pswd($id) && $val) { + $val = str_repeat('*', strlen($val)); } } - $label_id = preg_replace( '/\W/', '', $id ); + $label_id = preg_replace('/\W/', '', $id); - if ( $type == 'text' ) { + if ($type == 'text') { $cls = "regular-text $cls"; } - if ( $disabled ) { - echo " "; - } - else { - $this->enroll( $id ); - echo " "; + if ($disabled) { + echo " "; + } else { + $this->enroll($id); + echo " "; } - $this->_check_overwritten( $id ); + $this->_check_overwritten($id); } /** @@ -853,26 +911,27 @@ public function build_input( $id, $cls = null, $val = null, $type = 'text', $dis * @param string $title * @param bool $checked */ - public function build_checkbox( $id, $title, $checked = null, $value = 1 ) { - if ( $checked === null && $this->conf( $id, true ) ) { + public function build_checkbox($id, $title, $checked = null, $value = 1) + { + if ($checked === null && $this->conf($id, true)) { $checked = true; } $checked = $checked ? ' checked ' : ''; - $label_id = preg_replace( '/\W/', '', $id ); + $label_id = preg_replace('/\W/', '', $id); - if ( $value !== 1 ) { + if ($value !== 1) { $label_id .= '_' . $value; } - $this->enroll( $id ); + $this->enroll($id); echo "
"; - $this->_check_overwritten( $id ); + $this->_check_overwritten($id); } /** @@ -880,13 +939,14 @@ public function build_checkbox( $id, $title, $checked = null, $value = 1 ) { * * @since 1.7 */ - public function build_toggle( $id, $checked = null, $title_on = null, $title_off = null ) { - if ( $checked === null && $this->conf( $id, true ) ) { + public function build_toggle($id, $checked = null, $title_on = null, $title_off = null) + { + if ($checked === null && $this->conf($id, true)) { $checked = true; } - if ( $title_on === null ) { - $title_on = __( 'ON', 'litespeed-cache' ); - $title_off = __( 'OFF', 'litespeed-cache' ); + if ($title_on === null) { + $title_on = __('ON', 'litespeed-cache'); + $title_off = __('OFF', 'litespeed-cache'); } $cls = $checked ? 'primary' : 'default litespeed-toggleoff'; echo "
@@ -906,25 +966,23 @@ public function build_toggle( $id, $checked = null, $title_on = null, $title_off * @since 1.7 removed param $disable * @access public */ - public function build_switch( $id, $title_list = false ) { - $this->enroll( $id ); + public function build_switch($id, $title_list = false) + { + $this->enroll($id); echo '
'; - if ( ! $title_list ) { - $title_list = array( - __( 'OFF', 'litespeed-cache' ), - __( 'ON', 'litespeed-cache' ), - ); + if (!$title_list) { + $title_list = array(__('OFF', 'litespeed-cache'), __('ON', 'litespeed-cache')); } - foreach ( $title_list as $k => $v ) { - $this->_build_radio( $id, $k, $v ); + foreach ($title_list as $k => $v) { + $this->_build_radio($id, $k, $v); } echo '
'; - $this->_check_overwritten( $id ); + $this->_check_overwritten($id); } /** @@ -933,16 +991,16 @@ public function build_switch( $id, $title_list = false ) { * @since 1.1.0 * @access private */ - private function _build_radio( $id, $val, $txt ) { - $id_attr = 'input_radio_' . preg_replace( '/\W/', '', $id ) . '_' . $val; + private function _build_radio($id, $val, $txt) + { + $id_attr = 'input_radio_' . preg_replace('/\W/', '', $id) . '_' . $val; - $default = isset( self::$_default_options[ $id ] ) ? self::$_default_options[ $id ] : self::$_default_site_options[ $id ]; + $default = isset(self::$_default_options[$id]) ? self::$_default_options[$id] : self::$_default_site_options[$id]; - if ( ! is_string( $default ) ) { - $checked = (int) $this->conf( $id, true ) === (int) $val ? ' checked ' : ''; - } - else { - $checked = $this->conf( $id, true ) === $val ? ' checked ' : ''; + if (!is_string($default)) { + $checked = (int) $this->conf($id, true) === (int) $val ? ' checked ' : ''; + } else { + $checked = $this->conf($id, true) === $val ? ' checked ' : ''; } echo " "; @@ -953,41 +1011,40 @@ private function _build_radio( $id, $val, $txt ) { * * @since 3.0 */ - protected function _check_overwritten( $id ) { - $const_val = $this->const_overwritten( $id ); - $primary_val = $this->primary_overwritten( $id ); - if ( $const_val === null && $primary_val === null ) { + protected function _check_overwritten($id) + { + $const_val = $this->const_overwritten($id); + $primary_val = $this->primary_overwritten($id); + if ($const_val === null && $primary_val === null) { return; } $val = $const_val !== null ? $const_val : $primary_val; - $default = isset( self::$_default_options[ $id ] ) ? self::$_default_options[ $id ] : self::$_default_site_options[ $id ]; + $default = isset(self::$_default_options[$id]) ? self::$_default_options[$id] : self::$_default_site_options[$id]; - if ( is_bool( $default ) ) { - $val = $val ? __( 'ON', 'litespeed-cache' ) : __( 'OFF', 'litespeed-cache' ); - } - else { - if ( is_array( $default ) ) { - $val = implode( "\n", $val ); + if (is_bool($default)) { + $val = $val ? __('ON', 'litespeed-cache') : __('OFF', 'litespeed-cache'); + } else { + if (is_array($default)) { + $val = implode("\n", $val); } - $val = esc_textarea( $val ); + $val = esc_textarea($val); } echo '
⚠️ '; - if ( $const_val !== null ) { - echo sprintf( __( 'This setting is overwritten by the PHP constant %s', 'litespeed-cache' ), '' . Base::conf_const( $id ) . '' ); + if ($const_val !== null) { + echo sprintf(__('This setting is overwritten by the PHP constant %s', 'litespeed-cache'), '' . Base::conf_const($id) . ''); } else { - if ( get_current_blog_id() != BLOG_ID_CURRENT_SITE && $this->conf( self::NETWORK_O_USE_PRIMARY ) ) { - echo __( 'This setting is overwritten by the primary site setting', 'litespeed-cache' ); - } - else { - echo __( 'This setting is overwritten by the Network setting', 'litespeed-cache' ); + if (get_current_blog_id() != BLOG_ID_CURRENT_SITE && $this->conf(self::NETWORK_O_USE_PRIMARY)) { + echo __('This setting is overwritten by the primary site setting', 'litespeed-cache'); + } else { + echo __('This setting is overwritten by the Network setting', 'litespeed-cache'); } } - echo ', ' . sprintf( __( 'currently set to %s', 'litespeed-cache' ), "$val" ) . '
'; + echo ', ' . sprintf(__('currently set to %s', 'litespeed-cache'), "$val") . '
'; } /** @@ -996,8 +1053,9 @@ protected function _check_overwritten( $id ) { * @since 3.0 * @access public */ - public function readable_seconds() { - echo __( 'seconds', 'litespeed-cache' ); + public function readable_seconds() + { + echo __('seconds', 'litespeed-cache'); echo ' '; } @@ -1007,35 +1065,35 @@ public function readable_seconds() { * @since 1.1.1 * @access public */ - public function recommended( $id ) { - if ( ! $this->default_settings ) { + public function recommended($id) + { + if (!$this->default_settings) { $this->default_settings = $this->load_default_vals(); } - $val = $this->default_settings[ $id ]; + $val = $this->default_settings[$id]; - if ( $val ) { - if ( is_array( $val ) ) { + if ($val) { + if (is_array($val)) { $rows = 5; $cols = 30; // Flexible rows/cols - $lines = count( $val ) + 1; - $rows = min( max( $lines, $rows ), 40 ); - foreach ( $val as $v ) { - $cols = max( strlen( $v ), $cols ); + $lines = count($val) + 1; + $rows = min(max($lines, $rows), 40); + foreach ($val as $v) { + $cols = max(strlen($v), $cols); } - $cols = min( $cols, 150 ); + $cols = min($cols, 150); - $val = implode( "\n", $val ); - $val = esc_textarea( $val ); - $val = '
' . __( 'Default value', 'litespeed-cache' ) . ':
' . ""; - } - else { - $val = esc_textarea( $val ); + $val = implode("\n", $val); + $val = esc_textarea($val); + $val = '
' . __('Default value', 'litespeed-cache') . ':
' . ""; + } else { + $val = esc_textarea($val); $val = "$val"; - $val = __( 'Default value', 'litespeed-cache' ) . ': '.$val; + $val = __('Default value', 'litespeed-cache') . ': ' . $val; } - echo $val; + echo $val; } } @@ -1044,20 +1102,21 @@ public function recommended( $id ) { * * @since 3.0 */ - protected function _validate_syntax( $id ) { - $val = $this->conf( $id, true ); + protected function _validate_syntax($id) + { + $val = $this->conf($id, true); - if ( ! $val ) { + if (!$val) { return; } - if ( ! is_array( $val ) ) { - $val = array( $val ); + if (!is_array($val)) { + $val = array($val); } - foreach ( $val as $v ) { - if ( ! Utility::syntax_checker( $v ) ) { - echo '
❌ ' . __( 'Invalid rewrite rule', 'litespeed-cache' ) . ': ' . $v . ''; + foreach ($val as $v) { + if (!Utility::syntax_checker($v)) { + echo '
❌ ' . __('Invalid rewrite rule', 'litespeed-cache') . ': ' . $v . ''; } } } @@ -1067,14 +1126,15 @@ protected function _validate_syntax( $id ) { * * @since 3.0 */ - protected function _validate_htaccess_path( $id ) { - $val = $this->conf( $id, true ); - if ( ! $val ) { + protected function _validate_htaccess_path($id) + { + $val = $this->conf($id, true); + if (!$val) { return; } - if ( substr( $val, -10 ) !== '/.htaccess' ) { - echo '
❌ ' . sprintf( __( 'Path must end with %s', 'litespeed-cache' ), '/.htaccess' ) . ''; + if (substr($val, -10) !== '/.htaccess') { + echo '
❌ ' . sprintf(__('Path must end with %s', 'litespeed-cache'), '/.htaccess') . ''; } } @@ -1083,44 +1143,43 @@ protected function _validate_htaccess_path( $id ) { * * @since 3.0 */ - protected function _validate_ttl( $id, $min = false, $max = false, $allow_zero = false ) { - $val = $this->conf( $id, true ); + protected function _validate_ttl($id, $min = false, $max = false, $allow_zero = false) + { + $val = $this->conf($id, true); - if ( $allow_zero && ! $val ) { + if ($allow_zero && !$val) { // return; } $tip = array(); - if ( $min && $val < $min && ( ! $allow_zero || $val != 0 ) ) { - $tip[] = __( 'Minimum value', 'litespeed-cache' ) . ': ' . $min . '.'; + if ($min && $val < $min && (!$allow_zero || $val != 0)) { + $tip[] = __('Minimum value', 'litespeed-cache') . ': ' . $min . '.'; } - if ( $max && $val > $max ) { - $tip[] = __( 'Maximum value', 'litespeed-cache' ) . ': ' . $max . '.'; + if ($max && $val > $max) { + $tip[] = __('Maximum value', 'litespeed-cache') . ': ' . $max . '.'; } echo '
'; - if ( $tip ) { - echo ' ❌ ' . implode( ' ', $tip ) . ''; + if ($tip) { + echo ' ❌ ' . implode(' ', $tip) . ''; } $range = ''; - if ( $allow_zero ) { - $range .= __( 'Zero, or', 'litespeed-cache' ) . ' '; + if ($allow_zero) { + $range .= __('Zero, or', 'litespeed-cache') . ' '; } - if ( $min && $max ) { + if ($min && $max) { $range .= $min . ' - ' . $max; - } - elseif ( $min ) { - $range .= __( 'Larger than', 'litespeed-cache' ) . ' ' . $min; - } - elseif ( $max ) { - $range .= __( 'Smaller than', 'litespeed-cache' ) . ' ' . $max; + } elseif ($min) { + $range .= __('Larger than', 'litespeed-cache') . ' ' . $min; + } elseif ($max) { + $range .= __('Smaller than', 'litespeed-cache') . ' ' . $max; } - echo __( 'Value range', 'litespeed-cache' ) . ': ' . $range . ''; + echo __('Value range', 'litespeed-cache') . ': ' . $range . ''; } /** @@ -1128,29 +1187,30 @@ protected function _validate_ttl( $id, $min = false, $max = false, $allow_zero = * * @since 3.0 */ - protected function _validate_ip( $id ) { - $val = $this->conf( $id, true ); - if ( ! $val ) { + protected function _validate_ip($id) + { + $val = $this->conf($id, true); + if (!$val) { return; } - if ( ! is_array( $val ) ) { - $val = array( $val ); + if (!is_array($val)) { + $val = array($val); } $tip = array(); - foreach ( $val as $v ) { - if ( ! $v ) { + foreach ($val as $v) { + if (!$v) { continue; } - if ( ! \WP_Http::is_ip_address( $v ) ) { - $tip[] = __( 'Invalid IP', 'litespeed-cache' ) . ': ' . esc_textarea( $v ) . '.'; + if (!\WP_Http::is_ip_address($v)) { + $tip[] = __('Invalid IP', 'litespeed-cache') . ': ' . esc_textarea($v) . '.'; } } - if ( $tip ) { - echo '
❌ ' . implode( ' ', $tip ) . ''; + if ($tip) { + echo '
❌ ' . implode(' ', $tip) . ''; } } @@ -1160,15 +1220,17 @@ protected function _validate_ip( $id ) { * @since 1.8.3 * @access protected */ - protected function _api_env_var() { + protected function _api_env_var() + { $args = func_get_args(); - $s = '' . implode( ', ', $args ) . ''; + $s = '' . implode(', ', $args) . ''; - echo ' ' - . __( 'API', 'litespeed-cache' ) . ': ' - . sprintf( __( 'Server variable(s) %s available to override this setting.', 'litespeed-cache' ), $s ); + echo ' ' . + __('API', 'litespeed-cache') . + ': ' . + sprintf(__('Server variable(s) %s available to override this setting.', 'litespeed-cache'), $s); - Doc::learn_more( 'https://docs.litespeedtech.com/lscache/lscwp/admin/#limiting-the-crawler' ); + Doc::learn_more('https://docs.litespeedtech.com/lscache/lscwp/admin/#limiting-the-crawler'); } /** @@ -1177,13 +1239,14 @@ protected function _api_env_var() { * @since 2.6.1 * @access protected */ - protected function _uri_usage_example() { - echo __( 'The URLs will be compared to the REQUEST_URI server variable.', 'litespeed-cache' ); - echo ' ' . sprintf( __( 'For example, for %s, %s can be used here.', 'litespeed-cache' ), '/mypath/mypage?aa=bb', 'mypage?aa=' ); + protected function _uri_usage_example() + { + echo __('The URLs will be compared to the REQUEST_URI server variable.', 'litespeed-cache'); + echo ' ' . sprintf(__('For example, for %s, %s can be used here.', 'litespeed-cache'), '/mypath/mypage?aa=bb', 'mypage?aa='); echo '
'; - echo sprintf( __( 'To match the beginning, add %s to the beginning of the item.', 'litespeed-cache' ), '^' ); - echo ' ' . sprintf( __( 'To do an exact match, add %s to the end of the URL.', 'litespeed-cache' ), '$' ); - echo ' ' . __( 'One per line.', 'litespeed-cache' ); + echo sprintf(__('To match the beginning, add %s to the beginning of the item.', 'litespeed-cache'), '^'); + echo ' ' . sprintf(__('To do an exact match, add %s to the end of the URL.', 'litespeed-cache'), '$'); + echo ' ' . __('One per line.', 'litespeed-cache'); echo ''; } @@ -1193,27 +1256,27 @@ protected function _uri_usage_example() { * @since 2.0 * @access public */ - public static function print_plural( $num, $kind = 'group' ) { - if ( $num > 1 ) { - switch ( $kind ) { - case 'group' : - return sprintf( __( '%s groups', 'litespeed-cache' ), $num ); + public static function print_plural($num, $kind = 'group') + { + if ($num > 1) { + switch ($kind) { + case 'group': + return sprintf(__('%s groups', 'litespeed-cache'), $num); - case 'image' : - return sprintf( __( '%s images', 'litespeed-cache' ), $num ); + case 'image': + return sprintf(__('%s images', 'litespeed-cache'), $num); default: return $num; } - } - switch ( $kind ) { - case 'group' : - return sprintf( __( '%s group', 'litespeed-cache' ), $num ); + switch ($kind) { + case 'group': + return sprintf(__('%s group', 'litespeed-cache'), $num); - case 'image' : - return sprintf( __( '%s image', 'litespeed-cache' ), $num ); + case 'image': + return sprintf(__('%s image', 'litespeed-cache'), $num); default: return $num; @@ -1226,22 +1289,20 @@ public static function print_plural( $num, $kind = 'group' ) { * @since 2.0 * @access public */ - public static function guidance( $title, $steps, $current_step ) { - if ( $current_step === 'done' ) { - $current_step = count( $steps ) + 1; + public static function guidance($title, $steps, $current_step) + { + if ($current_step === 'done') { + $current_step = count($steps) + 1; } - $percentage = ' (' . floor( ( $current_step - 1 ) * 100 / count( $steps ) ) . '%)'; + $percentage = ' (' . floor((($current_step - 1) * 100) / count($steps)) . '%)'; - $html = '
' - . '

' . $title . $percentage . '

' - . '
    '; - foreach ( $steps as $k => $v ) { + $html = '
    ' . '

    ' . $title . $percentage . '

    ' . '
      '; + foreach ($steps as $k => $v) { $step = $k + 1; - if ( $current_step > $step ) { + if ($current_step > $step) { $html .= '
    1. '; - } - else { + } else { $html .= '
    2. '; } $html .= $v . '
    3. '; diff --git a/src/admin-settings.cls.php b/src/admin-settings.cls.php index 9ef9b0612..4fda7c85c 100644 --- a/src/admin-settings.cls.php +++ b/src/admin-settings.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; -class Admin_Settings extends Base { +defined('WPINC') || exit(); + +class Admin_Settings extends Base +{ const ENROLL = '_settings-enroll'; /** @@ -24,72 +28,63 @@ class Admin_Settings extends Base { * @since 3.0 * @access public */ - public function save( $raw_data ) { - Debug2::debug( '[Settings] saving' ); + public function save($raw_data) + { + Debug2::debug('[Settings] saving'); - if ( empty( $raw_data[ self::ENROLL ] ) ) { - exit( 'No fields' ); + if (empty($raw_data[self::ENROLL])) { + exit('No fields'); } - $raw_data = Admin::cleanup_text( $raw_data ); + $raw_data = Admin::cleanup_text($raw_data); // Convert data to config format $the_matrix = array(); - foreach ( array_unique( $raw_data[ self::ENROLL ] ) as $id ) { + foreach (array_unique($raw_data[self::ENROLL]) as $id) { $child = false; // Drop array format - if ( strpos( $id, '[' ) !== false ) { - if ( strpos( $id, self::O_CDN_MAPPING ) === 0 || strpos( $id, self::O_CRAWLER_COOKIES ) === 0 ) { // CDN child | Cookie Crawler settings - $child = substr( $id, strpos( $id, '[' ) + 1, strpos( $id, ']' ) - strpos( $id, '[' ) - 1 ); - $id = substr( $id, 0, strpos( $id, '[' ) ); // Drop ending []; Compatible with xx[0] way from CLI - } - else { - $id = substr( $id, 0, strpos( $id, '[' ) ); // Drop ending [] + if (strpos($id, '[') !== false) { + if (strpos($id, self::O_CDN_MAPPING) === 0 || strpos($id, self::O_CRAWLER_COOKIES) === 0) { + // CDN child | Cookie Crawler settings + $child = substr($id, strpos($id, '[') + 1, strpos($id, ']') - strpos($id, '[') - 1); + $id = substr($id, 0, strpos($id, '[')); // Drop ending []; Compatible with xx[0] way from CLI + } else { + $id = substr($id, 0, strpos($id, '[')); // Drop ending [] } } - if ( ! array_key_exists( $id, self::$_default_options ) ) { + if (!array_key_exists($id, self::$_default_options)) { continue; } // Validate $child - if ( $id == self::O_CDN_MAPPING ) { - if ( ! in_array( $child, array( - self::CDN_MAPPING_URL, - self::CDN_MAPPING_INC_IMG, - self::CDN_MAPPING_INC_CSS, - self::CDN_MAPPING_INC_JS, - self::CDN_MAPPING_FILETYPE, - ) ) ) { + if ($id == self::O_CDN_MAPPING) { + if (!in_array($child, array(self::CDN_MAPPING_URL, self::CDN_MAPPING_INC_IMG, self::CDN_MAPPING_INC_CSS, self::CDN_MAPPING_INC_JS, self::CDN_MAPPING_FILETYPE))) { continue; } } - if ( $id == self::O_CRAWLER_COOKIES ) { - if ( ! in_array( $child, array( - self::CRWL_COOKIE_NAME, - self::CRWL_COOKIE_VALS, - ) ) ) { + if ($id == self::O_CRAWLER_COOKIES) { + if (!in_array($child, array(self::CRWL_COOKIE_NAME, self::CRWL_COOKIE_VALS))) { continue; } } $data = false; - if ( $child ) { - $data = ! empty( $raw_data[ $id ][ $child ] ) ? $raw_data[ $id ][ $child ] : false; // []=xxx or [0]=xxx - } - else { - $data = ! empty( $raw_data[ $id ] ) ? $raw_data[ $id ] : false; + if ($child) { + $data = !empty($raw_data[$id][$child]) ? $raw_data[$id][$child] : false; // []=xxx or [0]=xxx + } else { + $data = !empty($raw_data[$id]) ? $raw_data[$id] : false; } /** * Sanitize the value */ - if ( $id == self::O_CDN_MAPPING || $id == self::O_CRAWLER_COOKIES ) { + if ($id == self::O_CDN_MAPPING || $id == self::O_CRAWLER_COOKIES) { // Use existing in queue data if existed (Only available when $child != false) - $data2 = array_key_exists( $id, $the_matrix ) ? $the_matrix[ $id ] : ( defined( 'WP_CLI' ) && WP_CLI ? $this->conf( $id ) : array() ); + $data2 = array_key_exists($id, $the_matrix) ? $the_matrix[$id] : (defined('WP_CLI') && WP_CLI ? $this->conf($id) : array()); } - switch ( $id ) { + switch ($id) { case self::O_CDN_MAPPING: /** * CDN setting @@ -103,27 +98,30 @@ public function save( $raw_data ) { * cdn-mapping[ 0 ][ url ] = 'xxx' * cdn-mapping[ 2 ][ url ] = 'xxx2' */ - if ( $data ) foreach ( $data as $k => $v ) { - if ( $child == self::CDN_MAPPING_FILETYPE ) { - $v = Utility::sanitize_lines( $v ); + if ($data) { + foreach ($data as $k => $v) { + if ($child == self::CDN_MAPPING_FILETYPE) { + $v = Utility::sanitize_lines($v); + } + if ($child == self::CDN_MAPPING_URL) { + # If not a valid URL, turn off CDN + if (strpos($v, 'https://') !== 0) { + self::debug('❌ CDN mapping set to OFF due to invalid URL'); + $the_matrix[self::O_CDN] = false; + } + $v = trailingslashit($v); + } + if (in_array($child, array(self::CDN_MAPPING_INC_IMG, self::CDN_MAPPING_INC_CSS, self::CDN_MAPPING_INC_JS))) { + // Because these can't be auto detected in `config->update()`, need to format here + $v = $v === 'false' ? 0 : (bool) $v; + } + + if (empty($data2[$k])) { + $data2[$k] = array(); + } + + $data2[$k][$child] = $v; } - if ( $child == self::CDN_MAPPING_URL ) { - $v = trailingslashit( $v ); - } - if ( in_array( $child, array( - self::CDN_MAPPING_INC_IMG, - self::CDN_MAPPING_INC_CSS, - self::CDN_MAPPING_INC_JS, - ) ) ) { - // Because these can't be auto detected in `config->update()`, need to format here - $v = $v === 'false' ? 0 : (bool) $v; - } - - if ( empty( $data2[ $k ] ) ) { - $data2[ $k ] = array(); - } - - $data2[ $k ][ $child ] = $v; } $data = $data2; @@ -146,16 +144,18 @@ public function save( $raw_data ) { * * empty line for `vals` use literal `_null` */ - if ( $data ) foreach ( $data as $k => $v ) { - if ( $child == self::CRWL_COOKIE_VALS ) { - $v = Utility::sanitize_lines( $v ); - } + if ($data) { + foreach ($data as $k => $v) { + if ($child == self::CRWL_COOKIE_VALS) { + $v = Utility::sanitize_lines($v); + } - if ( empty( $data2[ $k ] ) ) { - $data2[ $k ] = array(); - } + if (empty($data2[$k])) { + $data2[$k] = array(); + } - $data2[ $k ][ $child ] = $v; + $data2[$k][$child] = $v; + } } $data = $data2; @@ -164,10 +164,10 @@ public function save( $raw_data ) { // Cache exclude cat case self::O_CACHE_EXC_CAT: $data2 = array(); - $data = Utility::sanitize_lines( $data ); - foreach ( $data as $v ) { - $cat_id = get_cat_ID( $v ); - if ( ! $cat_id ) { + $data = Utility::sanitize_lines($data); + foreach ($data as $v) { + $cat_id = get_cat_ID($v); + if (!$cat_id) { continue; } @@ -177,12 +177,12 @@ public function save( $raw_data ) { break; // Cache exclude tag - case self::O_CACHE_EXC_TAG : + case self::O_CACHE_EXC_TAG: $data2 = array(); - $data = Utility::sanitize_lines( $data ); - foreach ( $data as $v ) { - $term = get_term_by( 'name', $v, 'post_tag' ); - if ( ! $term ) { + $data = Utility::sanitize_lines($data); + foreach ($data as $v) { + $term = get_term_by('name', $v, 'post_tag'); + if (!$term) { // todo: can show the error in admin error msg continue; } @@ -196,11 +196,11 @@ public function save( $raw_data ) { break; } - $the_matrix[ $id ] = $data; + $the_matrix[$id] = $data; } // Special handler for CDN/Crawler 2d list to drop empty rows - foreach ( $the_matrix as $id => $data ) { + foreach ($the_matrix as $id => $data) { /** * cdn-mapping[ 0 ][ url ] = 'xxx' * cdn-mapping[ 2 ][ url ] = 'xxx2' @@ -209,41 +209,59 @@ public function save( $raw_data ) { * crawler-cookie[ 0 ][ vals ] = 'xxx' * crawler-cookie[ 2 ][ name ] = 'xxx2' */ - if ( $id == self::O_CDN_MAPPING || $id == self::O_CRAWLER_COOKIES ) { + if ($id == self::O_CDN_MAPPING || $id == self::O_CRAWLER_COOKIES) { // Drop this line if all children elements are empty - foreach ( $data as $k => $v ) { - foreach ( $v as $v2 ) { - if ( $v2 ) { + foreach ($data as $k => $v) { + foreach ($v as $v2) { + if ($v2) { continue 2; } } // If hit here, means all empty - unset( $the_matrix[ $id ][ $k ] ); + unset($the_matrix[$id][$k]); } } // Don't allow repeated cookie name - if ( $id == self::O_CRAWLER_COOKIES ) { + if ($id == self::O_CRAWLER_COOKIES) { $existed = array(); - foreach ( $the_matrix[ $id ] as $k => $v ) { - if ( ! $v[ self::CRWL_COOKIE_NAME ] || in_array( $v[ self::CRWL_COOKIE_NAME ], $existed ) ) { // Filter repeated or empty name - unset( $the_matrix[ $id ][ $k ] ); + foreach ($the_matrix[$id] as $k => $v) { + if (!$v[self::CRWL_COOKIE_NAME] || in_array($v[self::CRWL_COOKIE_NAME], $existed)) { + // Filter repeated or empty name + unset($the_matrix[$id][$k]); continue; } - $existed[] = $v[ self::CRWL_COOKIE_NAME ]; + $existed[] = $v[self::CRWL_COOKIE_NAME]; } } // CDN mapping allow URL values repeated // if ( $id == self::O_CDN_MAPPING ) {} + + // tmp fix the 3rd part woo update hook issue when enabling vary cookie + if ($id == 'wc_cart_vary') { + if ($data) { + add_filter('litespeed_vary_cookies', function ($list) { + $list[] = 'woocommerce_cart_hash'; + return array_unique($list); + }); + } else { + add_filter('litespeed_vary_cookies', function ($list) { + if (in_array('woocommerce_cart_hash', $list)) { + unset($list[array_search('woocommerce_cart_hash', $list)]); + } + return array_unique($list); + }); + } + } } // id validation will be inside - $this->cls( 'Conf' )->update_confs( $the_matrix ); + $this->cls('Conf')->update_confs($the_matrix); - $msg = __( 'Options saved.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + $msg = __('Options saved.', 'litespeed-cache'); + Admin_Display::succeed($msg); } /** @@ -252,32 +270,33 @@ public function save( $raw_data ) { * @since 3.0 * @access public */ - public function network_save( $raw_data ) { - Debug2::debug( '[Settings] network saving' ); + public function network_save($raw_data) + { + Debug2::debug('[Settings] network saving'); - if ( empty( $raw_data[ self::ENROLL ] ) ) { - exit( 'No fields' ); + if (empty($raw_data[self::ENROLL])) { + exit('No fields'); } - $raw_data = Admin::cleanup_text( $raw_data ); + $raw_data = Admin::cleanup_text($raw_data); - foreach ( array_unique( $raw_data[ self::ENROLL ] ) as $id ) { + foreach (array_unique($raw_data[self::ENROLL]) as $id) { // Append current field to setting save - if ( ! array_key_exists( $id, self::$_default_site_options ) ) { + if (!array_key_exists($id, self::$_default_site_options)) { continue; } - $data = ! empty( $raw_data[ $id ] ) ? $raw_data[ $id ] : false; + $data = !empty($raw_data[$id]) ? $raw_data[$id] : false; // id validation will be inside - $this->cls( 'Conf' )->network_update( $id, $data ); + $this->cls('Conf')->network_update($id, $data); } // Update related files Activation::cls()->update_files(); - $msg = __( 'Options saved.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + $msg = __('Options saved.', 'litespeed-cache'); + Admin_Display::succeed($msg); } /** @@ -289,8 +308,9 @@ public function network_save( $raw_data ) { * @param string $location The location string. * @return string the updated location string. */ - public static function widget_save_err( $location ) { - return str_replace( '?message=0', '?error=0', $location ) ; + public static function widget_save_err($location) + { + return str_replace('?message=0', '?error=0', $location); } /** @@ -305,40 +325,41 @@ public static function widget_save_err( $location ) { * @param WP_Widget $widget The widget * @return mixed Updated settings on success, false on error. */ - public static function validate_widget_save( $instance, $new_instance, $old_instance, $widget ) { - if ( empty( $new_instance ) ) { + public static function validate_widget_save($instance, $new_instance, $old_instance, $widget) + { + if (empty($new_instance)) { return $instance; } - if ( ! isset( $new_instance[ ESI::WIDGET_O_ESIENABLE ] ) || ! isset( $new_instance[ ESI::WIDGET_O_TTL ] ) ) { + if (!isset($new_instance[ESI::WIDGET_O_ESIENABLE]) || !isset($new_instance[ESI::WIDGET_O_TTL])) { return $instance; } - $esi = intval( $new_instance[ ESI::WIDGET_O_ESIENABLE ] ) % 3; - $ttl = (int) $new_instance[ ESI::WIDGET_O_TTL ]; + $esi = intval($new_instance[ESI::WIDGET_O_ESIENABLE]) % 3; + $ttl = (int) $new_instance[ESI::WIDGET_O_TTL]; - if ( $ttl != 0 && $ttl < 30 ) { - add_filter( 'wp_redirect', __CLASS__ . '::widget_save_err' ) ; - return false ; // invalid ttl. + if ($ttl != 0 && $ttl < 30) { + add_filter('wp_redirect', __CLASS__ . '::widget_save_err'); + return false; // invalid ttl. } - if ( empty( $instance[ Conf::OPTION_NAME ] ) ) {// todo: to be removed - $instance[ Conf::OPTION_NAME ] = array() ; + if (empty($instance[Conf::OPTION_NAME])) { + // todo: to be removed + $instance[Conf::OPTION_NAME] = array(); } - $instance[ Conf::OPTION_NAME ][ ESI::WIDGET_O_ESIENABLE ] = $esi ; - $instance[ Conf::OPTION_NAME ][ ESI::WIDGET_O_TTL ] = $ttl ; - - $current = ! empty( $old_instance[ Conf::OPTION_NAME ] ) ? $old_instance[ Conf::OPTION_NAME ] : false ; - if ( ! strpos( $_SERVER[ 'HTTP_REFERER' ], '/wp-admin/customize.php') ) { - if ( ! $current || $esi != $current[ ESI::WIDGET_O_ESIENABLE ] ) { - Purge::purge_all( 'Wdiget ESI_enable changed' ) ; - } - elseif ( $ttl != 0 && $ttl != $current[ ESI::WIDGET_O_TTL ] ) { - Purge::add( Tag::TYPE_WIDGET . $widget->id ) ; + $instance[Conf::OPTION_NAME][ESI::WIDGET_O_ESIENABLE] = $esi; + $instance[Conf::OPTION_NAME][ESI::WIDGET_O_TTL] = $ttl; + + $current = !empty($old_instance[Conf::OPTION_NAME]) ? $old_instance[Conf::OPTION_NAME] : false; + if (!strpos($_SERVER['HTTP_REFERER'], '/wp-admin/customize.php')) { + if (!$current || $esi != $current[ESI::WIDGET_O_ESIENABLE]) { + Purge::purge_all('Wdiget ESI_enable changed'); + } elseif ($ttl != 0 && $ttl != $current[ESI::WIDGET_O_TTL]) { + Purge::add(Tag::TYPE_WIDGET . $widget->id); } - Purge::purge_all( 'Wdiget saved' ) ; + Purge::purge_all('Wdiget saved'); } - return $instance ; + return $instance; } } diff --git a/src/admin.cls.php b/src/admin.cls.php index 7e4b69a01..542ee760d 100644 --- a/src/admin.cls.php +++ b/src/admin.cls.php @@ -10,9 +10,10 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Admin extends Root { +class Admin extends Root +{ const LOG_TAG = '👮'; const PAGE_EDIT_HTACCESS = 'litespeed-edit-htaccess'; @@ -23,42 +24,24 @@ class Admin extends Root { * * @since 1.0.0 */ - public function __construct() { + public function __construct() + { // Define LSCWP_MU_PLUGIN if is mu-plugins - if ( defined( 'WPMU_PLUGIN_DIR' ) && dirname( LSCWP_DIR ) == WPMU_PLUGIN_DIR ) { - define( 'LSCWP_MU_PLUGIN', true ); + if (defined('WPMU_PLUGIN_DIR') && dirname(LSCWP_DIR) == WPMU_PLUGIN_DIR) { + define('LSCWP_MU_PLUGIN', true); } - self::debug( 'No cache due to Admin page' ); - defined( 'DONOTCACHEPAGE' ) || define( 'DONOTCACHEPAGE', true ); + self::debug('No cache due to Admin page'); + defined('DONOTCACHEPAGE') || define('DONOTCACHEPAGE', true); // Additional litespeed assets on admin display // Also register menu - $this->cls( 'Admin_Display' ); + $this->cls('Admin_Display'); // initialize admin actions - add_action( 'admin_init', array( $this, 'admin_init' ) ); + add_action('admin_init', array($this, 'admin_init')); // add link to plugin list page - add_filter( 'plugin_action_links_' . LSCWP_BASENAME, array( $this->cls( 'Admin_Display' ), 'add_plugin_links' ) ); - - if ( defined( 'LITESPEED_ON' ) ) { - // register purge_all actions - $purge_all_events = $this->conf( Base::O_PURGE_HOOK_ALL ); - - // purge all on upgrade - if ( $this->conf( Base::O_PURGE_ON_UPGRADE ) ) { - $purge_all_events[] = 'upgrader_process_complete'; - $purge_all_events[] = 'admin_action_do-plugin-upgrade'; - } - foreach ( $purge_all_events as $event ) { - // Don't allow hook to update_option bcos purge_all will cause infinite loop of update_option - if ( in_array( $event, array( 'update_option' ) ) ) { - continue; - } - add_action( $event, __NAMESPACE__ . '\Purge::purge_all' ); - } - // add_filter( 'upgrader_pre_download', 'Purge::filter_with_purge_all' ); - } + add_filter('plugin_action_links_' . LSCWP_BASENAME, array($this->cls('Admin_Display'), 'add_plugin_links')); } /** @@ -67,22 +50,22 @@ public function __construct() { * @since 1.0.0 * @access public */ - public function admin_init() { + public function admin_init() + { // Hook attachment upload - if ( $this->conf( Base::O_IMG_OPTM_AUTO ) ) { - add_filter( 'wp_update_attachment_metadata', array( $this, 'wp_update_attachment_metadata' ), 9999, 2 ); + if ($this->conf(Base::O_IMG_OPTM_AUTO)) { + add_filter('wp_update_attachment_metadata', array($this, 'wp_update_attachment_metadata'), 9999, 2); } $this->_proceed_admin_action(); // Terminate if user doesn't have the access to settings - if( is_network_admin() ) { + if (is_network_admin()) { $capability = 'manage_network_options'; - } - else { + } else { $capability = 'manage_options'; } - if ( ! current_user_can($capability) ) { + if (!current_user_can($capability)) { return; } @@ -91,17 +74,17 @@ public function admin_init() { // Add privacy policy // @since 2.2.6 - if ( function_exists( 'wp_add_privacy_policy_content' ) ) { - wp_add_privacy_policy_content( Core::NAME, Doc::privacy_policy() ); + if (function_exists('wp_add_privacy_policy_content')) { + wp_add_privacy_policy_content(Core::NAME, Doc::privacy_policy()); } - $this->cls( 'Media' )->after_admin_init(); + $this->cls('Media')->after_admin_init(); - do_action( 'litspeed_after_admin_init' ); + do_action('litspeed_after_admin_init'); - if ( $this->cls( 'Router' )->esi_enabled() ) { - add_action( 'in_widget_form', array( $this->cls( 'Admin_Display' ), 'show_widget_edit' ), 100, 3 ); - add_filter( 'widget_update_callback', __NAMESPACE__ . '\Admin_Settings::validate_widget_save', 10, 4 ); + if ($this->cls('Router')->esi_enabled()) { + add_action('in_widget_form', array($this->cls('Admin_Display'), 'show_widget_edit'), 100, 3); + add_filter('widget_update_callback', __NAMESPACE__ . '\Admin_Settings::validate_widget_save', 10, 4); } } @@ -109,8 +92,9 @@ public function admin_init() { * Handle attachment update * @since 4.0 */ - public function wp_update_attachment_metadata( $data, $post_id ) { - $this->cls( 'Img_Optm' )->wp_update_attachment_metadata( $data, $post_id ); + public function wp_update_attachment_metadata($data, $post_id) + { + $this->cls('Img_Optm')->wp_update_attachment_metadata($data, $post_id); return $data; } @@ -119,23 +103,22 @@ public function wp_update_attachment_metadata( $data, $post_id ) { * * @since 1.1.0 */ - private function _proceed_admin_action() { + private function _proceed_admin_action() + { // handle actions - switch ( Router::get_action() ) { + switch (Router::get_action()) { case Router::ACTION_SAVE_SETTINGS: - $this->cls( 'Admin_Settings' )->save( $_POST ); + $this->cls('Admin_Settings')->save($_POST); break; - // Save network settings case Router::ACTION_SAVE_SETTINGS_NETWORK: - $this->cls( 'Admin_Settings' )->network_save( $_POST ); + $this->cls('Admin_Settings')->network_save($_POST); break; default: break; } - } /** @@ -146,58 +129,61 @@ private function _proceed_admin_action() { * @param string $input The input string to clean. * @return string The cleaned up input. */ - public static function cleanup_text( $input ) { - if ( is_array( $input ) ) { - return array_map( __CLASS__ . '::cleanup_text', $input ); + public static function cleanup_text($input) + { + if (is_array($input)) { + return array_map(__CLASS__ . '::cleanup_text', $input); } - return stripslashes( trim( $input ) ); + return stripslashes(trim($input)); } /** * After a LSCWP_CTRL action, need to redirect back to the same page * without the nonce and action in the query string. * + * If the redirect url cannot be determined, redirects to the homepage. + * * @since 1.0.12 * @access public * @global string $pagenow */ - public static function redirect( $url = false ) { + public static function redirect($url = false) + { global $pagenow; - if ( ! empty( $_GET[ '_litespeed_ori' ] ) ) { - wp_redirect( $_SERVER[ 'HTTP_REFERER' ] ); - exit; + if (!empty($_GET['_litespeed_ori'])) { + wp_safe_redirect(wp_get_referer() ?: get_home_url()); + exit(); } $qs = ''; - if ( ! $url ) { - if ( ! empty( $_GET ) ) { - if ( isset( $_GET[ Router::ACTION ] ) ) { - unset( $_GET[ Router::ACTION ] ); + if (!$url) { + if (!empty($_GET)) { + if (isset($_GET[Router::ACTION])) { + unset($_GET[Router::ACTION]); } - if ( isset( $_GET[ Router::NONCE ] ) ) { - unset( $_GET[ Router::NONCE ] ); + if (isset($_GET[Router::NONCE])) { + unset($_GET[Router::NONCE]); } - if ( isset( $_GET[ Router::TYPE ] ) ) { - unset( $_GET[ Router::TYPE ] ); + if (isset($_GET[Router::TYPE])) { + unset($_GET[Router::TYPE]); } - if ( isset( $_GET[ 'litespeed_i' ] ) ) { - unset( $_GET[ 'litespeed_i' ] ); + if (isset($_GET['litespeed_i'])) { + unset($_GET['litespeed_i']); } - if ( ! empty( $_GET ) ) { - $qs = '?' . http_build_query( $_GET ); + if (!empty($_GET)) { + $qs = '?' . http_build_query($_GET); } } - if ( is_network_admin() ) { - $url = network_admin_url( $pagenow . $qs ); - } - else { - $url = admin_url( $pagenow . $qs ); + if (is_network_admin()) { + $url = network_admin_url($pagenow . $qs); + } else { + $url = admin_url($pagenow . $qs); } } - wp_redirect( $url ); - exit; + wp_redirect($url); + exit(); } } diff --git a/src/api.cls.php b/src/api.cls.php index 728ec303f..ad44a8a01 100644 --- a/src/api.cls.php +++ b/src/api.cls.php @@ -10,37 +10,39 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; - -class API extends Base { - const VERSION = Core::VER; - - const TYPE_FEED = Tag::TYPE_FEED ; - const TYPE_FRONTPAGE = Tag::TYPE_FRONTPAGE ; - const TYPE_HOME = Tag::TYPE_HOME ; - const TYPE_PAGES = Tag::TYPE_PAGES ; - const TYPE_PAGES_WITH_RECENT_POSTS = Tag::TYPE_PAGES_WITH_RECENT_POSTS ; - const TYPE_HTTP = Tag::TYPE_HTTP ; - const TYPE_ARCHIVE_POSTTYPE = Tag::TYPE_ARCHIVE_POSTTYPE ; - const TYPE_ARCHIVE_TERM = Tag::TYPE_ARCHIVE_TERM ; - const TYPE_AUTHOR = Tag::TYPE_AUTHOR ; - const TYPE_ARCHIVE_DATE = Tag::TYPE_ARCHIVE_DATE ; - const TYPE_BLOG = Tag::TYPE_BLOG ; - const TYPE_LOGIN = Tag::TYPE_LOGIN ; - const TYPE_URL = Tag::TYPE_URL ; - - const TYPE_ESI = Tag::TYPE_ESI ; - - const PARAM_NAME = ESI::PARAM_NAME ; - const WIDGET_O_ESIENABLE = ESI::WIDGET_O_ESIENABLE ; - const WIDGET_O_TTL = ESI::WIDGET_O_TTL ; +defined('WPINC') || exit(); + +class API extends Base +{ + const VERSION = Core::VER; + + const TYPE_FEED = Tag::TYPE_FEED; + const TYPE_FRONTPAGE = Tag::TYPE_FRONTPAGE; + const TYPE_HOME = Tag::TYPE_HOME; + const TYPE_PAGES = Tag::TYPE_PAGES; + const TYPE_PAGES_WITH_RECENT_POSTS = Tag::TYPE_PAGES_WITH_RECENT_POSTS; + const TYPE_HTTP = Tag::TYPE_HTTP; + const TYPE_ARCHIVE_POSTTYPE = Tag::TYPE_ARCHIVE_POSTTYPE; + const TYPE_ARCHIVE_TERM = Tag::TYPE_ARCHIVE_TERM; + const TYPE_AUTHOR = Tag::TYPE_AUTHOR; + const TYPE_ARCHIVE_DATE = Tag::TYPE_ARCHIVE_DATE; + const TYPE_BLOG = Tag::TYPE_BLOG; + const TYPE_LOGIN = Tag::TYPE_LOGIN; + const TYPE_URL = Tag::TYPE_URL; + + const TYPE_ESI = Tag::TYPE_ESI; + + const PARAM_NAME = ESI::PARAM_NAME; + const WIDGET_O_ESIENABLE = ESI::WIDGET_O_ESIENABLE; + const WIDGET_O_TTL = ESI::WIDGET_O_TTL; /** * Instance * * @since 3.0 */ - public function __construct() { + public function __construct() + { } /** @@ -50,7 +52,8 @@ public function __construct() { * * @since 3.0 */ - public function init() { + public function init() + { /** * Init */ @@ -59,110 +62,110 @@ public function init() { /** * Conf */ - add_filter( 'litespeed_conf', array( $this, 'conf' ) ); // @previous API::config($id) + add_filter('litespeed_conf', array($this, 'conf')); // @previous API::config($id) // Action `litespeed_conf_append` // @previous API::conf_append( $name, $default ) - add_action( 'litespeed_conf_multi_switch', __NAMESPACE__ . '\Base::set_multi_switch', 10, 2 ); + add_action('litespeed_conf_multi_switch', __NAMESPACE__ . '\Base::set_multi_switch', 10, 2); // Action ``litespeed_conf_force` // @previous API::force_option( $k, $v ) /** * Cache Control Hooks */ // Action `litespeed_control_finalize` // @previous API::hook_control($tags) && action `litespeed_api_control` - add_action( 'litespeed_control_set_private', __NAMESPACE__ . '\Control::set_private' ); // @previous API::set_cache_private() - add_action( 'litespeed_control_set_nocache', __NAMESPACE__ . '\Control::set_nocache' ); // @previous API::set_nocache( $reason = false ) - add_action( 'litespeed_control_set_cacheable', array( $this, 'set_cacheable' ) ); // Might needed if not call hook `wp` // @previous API::set_cacheable( $reason ) - add_action( 'litespeed_control_force_cacheable', __NAMESPACE__ . '\Control::force_cacheable' ); // Set cache status to force cacheable ( Will ignore most kinds of non-cacheable conditions ) // @previous API::set_force_cacheable( $reason ) - add_action( 'litespeed_control_force_public', __NAMESPACE__ . '\Control::set_public_forced' ); // Set cache to force public cache if cacheable ( Will ignore most kinds of non-cacheable conditions ) // @previous API::set_force_public( $reason ) - add_filter( 'litespeed_control_cacheable', __NAMESPACE__ . '\Control::is_cacheable', 3 ); // Note: Read-Only. Directly append to this filter won't work. Call actions above to set cacheable or not // @previous API::not_cacheable() - add_action( 'litespeed_control_set_ttl', __NAMESPACE__ . '\Control::set_custom_ttl', 10, 2 ); // @previous API::set_ttl( $val ) - add_filter( 'litespeed_control_ttl', array( $this, 'get_ttl' ), 3 ); // @previous API::get_ttl() + add_action('litespeed_control_set_private', __NAMESPACE__ . '\Control::set_private'); // @previous API::set_cache_private() + add_action('litespeed_control_set_nocache', __NAMESPACE__ . '\Control::set_nocache'); // @previous API::set_nocache( $reason = false ) + add_action('litespeed_control_set_cacheable', array($this, 'set_cacheable')); // Might needed if not call hook `wp` // @previous API::set_cacheable( $reason ) + add_action('litespeed_control_force_cacheable', __NAMESPACE__ . '\Control::force_cacheable'); // Set cache status to force cacheable ( Will ignore most kinds of non-cacheable conditions ) // @previous API::set_force_cacheable( $reason ) + add_action('litespeed_control_force_public', __NAMESPACE__ . '\Control::set_public_forced'); // Set cache to force public cache if cacheable ( Will ignore most kinds of non-cacheable conditions ) // @previous API::set_force_public( $reason ) + add_filter('litespeed_control_cacheable', __NAMESPACE__ . '\Control::is_cacheable', 3); // Note: Read-Only. Directly append to this filter won't work. Call actions above to set cacheable or not // @previous API::not_cacheable() + add_action('litespeed_control_set_ttl', __NAMESPACE__ . '\Control::set_custom_ttl', 10, 2); // @previous API::set_ttl( $val ) + add_filter('litespeed_control_ttl', array($this, 'get_ttl'), 3); // @previous API::get_ttl() /** * Tag Hooks */ // Action `litespeed_tag_finalize` // @previous API::hook_tag( $hook ) - add_action( 'litespeed_tag', __NAMESPACE__ . '\Tag::add' ); // Shorter alias of `litespeed_tag_add` - add_action( 'litespeed_tag_post', __NAMESPACE__ . '\Tag::add_post' ); // Shorter alias of `litespeed_tag_add_post` - add_action( 'litespeed_tag_widget', __NAMESPACE__ . '\Tag::add_widget' ); // Shorter alias of `litespeed_tag_add_widget` - add_action( 'litespeed_tag_private', __NAMESPACE__ . '\Tag::add_private' ); // Shorter alias of `litespeed_tag_add_private` - add_action( 'litespeed_tag_private_esi', __NAMESPACE__ . '\Tag::add_private_esi' ); // Shorter alias of `litespeed_tag_add_private_esi` - - add_action( 'litespeed_tag_add', __NAMESPACE__ . '\Tag::add' ); // @previous API::tag_add( $tag ) - add_action( 'litespeed_tag_add_post', __NAMESPACE__ . '\Tag::add_post' ); - add_action( 'litespeed_tag_add_widget', __NAMESPACE__ . '\Tag::add_widget' ); - add_action( 'litespeed_tag_add_private', __NAMESPACE__ . '\Tag::add_private' ); // @previous API::tag_add_private( $tags ) - add_action( 'litespeed_tag_add_private_esi', __NAMESPACE__ . '\Tag::add_private_esi' ); + add_action('litespeed_tag', __NAMESPACE__ . '\Tag::add'); // Shorter alias of `litespeed_tag_add` + add_action('litespeed_tag_post', __NAMESPACE__ . '\Tag::add_post'); // Shorter alias of `litespeed_tag_add_post` + add_action('litespeed_tag_widget', __NAMESPACE__ . '\Tag::add_widget'); // Shorter alias of `litespeed_tag_add_widget` + add_action('litespeed_tag_private', __NAMESPACE__ . '\Tag::add_private'); // Shorter alias of `litespeed_tag_add_private` + add_action('litespeed_tag_private_esi', __NAMESPACE__ . '\Tag::add_private_esi'); // Shorter alias of `litespeed_tag_add_private_esi` + + add_action('litespeed_tag_add', __NAMESPACE__ . '\Tag::add'); // @previous API::tag_add( $tag ) + add_action('litespeed_tag_add_post', __NAMESPACE__ . '\Tag::add_post'); + add_action('litespeed_tag_add_widget', __NAMESPACE__ . '\Tag::add_widget'); + add_action('litespeed_tag_add_private', __NAMESPACE__ . '\Tag::add_private'); // @previous API::tag_add_private( $tags ) + add_action('litespeed_tag_add_private_esi', __NAMESPACE__ . '\Tag::add_private_esi'); /** * Purge Hooks */ // Action `litespeed_purge_finalize` // @previous API::hook_purge($tags) - add_action( 'litespeed_purge', __NAMESPACE__ . '\Purge::add' ); // @previous API::purge($tags) - add_action( 'litespeed_purge_all', __NAMESPACE__ . '\Purge::purge_all' ); - add_action( 'litespeed_purge_post', array( $this, 'purge_post' ) ); // @previous API::purge_post( $pid ) - add_action( 'litespeed_purge_posttype', __NAMESPACE__ . '\Purge::purge_posttype' ); - add_action( 'litespeed_purge_url', array( $this, 'purge_url' ) ); - add_action( 'litespeed_purge_widget', __NAMESPACE__ . '\Purge::purge_widget' ); - add_action( 'litespeed_purge_esi', __NAMESPACE__ . '\Purge::purge_esi' ); - add_action( 'litespeed_purge_private', __NAMESPACE__ . '\Purge::add_private' ); // @previous API::purge_private( $tags ) - add_action( 'litespeed_purge_private_esi', __NAMESPACE__ . '\Purge::add_private_esi' ); - add_action( 'litespeed_purge_private_all', __NAMESPACE__ . '\Purge::add_private_all' ); // @previous API::purge_private_all() + add_action('litespeed_purge', __NAMESPACE__ . '\Purge::add'); // @previous API::purge($tags) + add_action('litespeed_purge_all', __NAMESPACE__ . '\Purge::purge_all'); + add_action('litespeed_purge_post', array($this, 'purge_post')); // @previous API::purge_post( $pid ) + add_action('litespeed_purge_posttype', __NAMESPACE__ . '\Purge::purge_posttype'); + add_action('litespeed_purge_url', array($this, 'purge_url')); + add_action('litespeed_purge_widget', __NAMESPACE__ . '\Purge::purge_widget'); + add_action('litespeed_purge_esi', __NAMESPACE__ . '\Purge::purge_esi'); + add_action('litespeed_purge_private', __NAMESPACE__ . '\Purge::add_private'); // @previous API::purge_private( $tags ) + add_action('litespeed_purge_private_esi', __NAMESPACE__ . '\Purge::add_private_esi'); + add_action('litespeed_purge_private_all', __NAMESPACE__ . '\Purge::add_private_all'); // @previous API::purge_private_all() // Action `litespeed_api_purge_post` // Triggered when purge a post // @previous API::hook_purge_post($hook) // Action `litespeed_purged_all` // Triggered after purged all. - add_action( 'litespeed_purge_all_object', __NAMESPACE__ . '\Purge::purge_all_object' ); - add_action( 'litespeed_purge_ucss', __NAMESPACE__ . '\Purge::purge_ucss' ); + add_action('litespeed_purge_all_object', __NAMESPACE__ . '\Purge::purge_all_object'); + add_action('litespeed_purge_ucss', __NAMESPACE__ . '\Purge::purge_ucss'); /** * ESI */ // Action `litespeed_nonce` // @previous API::nonce_action( $action ) & API::nonce( $action = -1, $defence_for_html_filter = true ) // NOTE: only available after `init` hook - add_filter( 'litespeed_esi_status', array( $this, 'esi_enabled' ) ); // Get ESI enable status // @previous API::esi_enabled() - add_filter( 'litespeed_esi_url', array( $this, 'sub_esi_block' ), 10, 8 ); // Generate ESI block url // @previous API::esi_url( $block_id, $wrapper, $params = array(), $control = 'private,no-vary', $silence = false, $preserved = false, $svar = false, $inline_val = false ) + add_filter('litespeed_esi_status', array($this, 'esi_enabled')); // Get ESI enable status // @previous API::esi_enabled() + add_filter('litespeed_esi_url', array($this, 'sub_esi_block'), 10, 8); // Generate ESI block url // @previous API::esi_url( $block_id, $wrapper, $params = array(), $control = 'private,no-vary', $silence = false, $preserved = false, $svar = false, $inline_val = false ) // Filter `litespeed_widget_default_options` // Hook widget default settings value. Currently used in Woo 3rd // @previous API::hook_widget_default_options( $hook ) // Filter `litespeed_esi_params` // @previous API::hook_esi_param( $hook ) // Action `litespeed_tpl_normal` // @previous API::hook_tpl_not_esi($hook) && Action `litespeed_is_not_esi_template` // Action `litespeed_esi_load-$block` // @usage add_action( 'litespeed_esi_load-' . $block, $hook ) // @previous API::hook_tpl_esi($block, $hook) - add_action( 'litespeed_esi_combine', __NAMESPACE__ . '\ESI::combine' ); + add_action('litespeed_esi_combine', __NAMESPACE__ . '\ESI::combine'); /** * Vary * * To modify default vary, There are two ways: Action `litespeed_vary_append` or Filter `litespeed_vary` */ - add_action( 'litespeed_vary_ajax_force', __NAMESPACE__ . '\Vary::can_ajax_vary' ); // API::force_vary() -> Action `litespeed_vary_ajax_force` // Force finalize vary even if its in an AJAX call + add_action('litespeed_vary_ajax_force', __NAMESPACE__ . '\Vary::can_ajax_vary'); // API::force_vary() -> Action `litespeed_vary_ajax_force` // Force finalize vary even if its in an AJAX call // Filter `litespeed_vary_curr_cookies` to generate current in use vary, which will be used for response vary header. // Filter `litespeed_vary_cookies` to register the final vary cookies, which will be written to rewrite rule. (litespeed_vary_curr_cookies are always equal to or less than litespeed_vary_cookies) // Filter `litespeed_vary` // Previous API::hook_vary_finalize( $hook ) - add_action( 'litespeed_vary_no', __NAMESPACE__ . '\Control::set_no_vary' ); // API::set_cache_no_vary() -> Action `litespeed_vary_no` // Set cache status to no vary + add_action('litespeed_vary_no', __NAMESPACE__ . '\Control::set_no_vary'); // API::set_cache_no_vary() -> Action `litespeed_vary_no` // Set cache status to no vary // add_filter( 'litespeed_is_mobile', __NAMESPACE__ . '\Control::is_mobile' ); // API::set_mobile() -> Filter `litespeed_is_mobile` /** * Cloud */ - add_filter( 'litespeed_is_from_cloud', array( $this, 'is_from_cloud' ) ); // Check if current request is from QC (usally its to check REST access) // @see https://wordpress.org/support/topic/image-optimization-not-working-3/ + add_filter('litespeed_is_from_cloud', array($this, 'is_from_cloud')); // Check if current request is from QC (usally its to check REST access) // @see https://wordpress.org/support/topic/image-optimization-not-working-3/ /** * Media */ - add_action( 'litespeed_media_reset', __NAMESPACE__ . '\Media::delete_attachment' ); // Reset one media row + add_action('litespeed_media_reset', __NAMESPACE__ . '\Media::delete_attachment'); // Reset one media row /** * GUI */ // API::clean_wrapper_begin( $counter = false ) -> Filter `litespeed_clean_wrapper_begin` // Start a to-be-removed html wrapper - add_filter( 'litespeed_clean_wrapper_begin', __NAMESPACE__ . '\GUI::clean_wrapper_begin' ); + add_filter('litespeed_clean_wrapper_begin', __NAMESPACE__ . '\GUI::clean_wrapper_begin'); // API::clean_wrapper_end( $counter = false ) -> Filter `litespeed_clean_wrapper_end` // End a to-be-removed html wrapper - add_filter( 'litespeed_clean_wrapper_end', __NAMESPACE__ . '\GUI::clean_wrapper_end' ); + add_filter('litespeed_clean_wrapper_end', __NAMESPACE__ . '\GUI::clean_wrapper_end'); /** * Mist */ - add_action( 'litespeed_debug', __NAMESPACE__ . '\Debug2::debug', 10, 2 ); // API::debug()-> Action `litespeed_debug` - add_action( 'litespeed_debug2', __NAMESPACE__ . '\Debug2::debug2', 10, 2 ); // API::debug2()-> Action `litespeed_debug2` - add_action( 'litespeed_disable_all', array( $this, '_disable_all' ) ); // API::disable_all( $reason ) -> Action `litespeed_disable_all` + add_action('litespeed_debug', __NAMESPACE__ . '\Debug2::debug', 10, 2); // API::debug()-> Action `litespeed_debug` + add_action('litespeed_debug2', __NAMESPACE__ . '\Debug2::debug2', 10, 2); // API::debug2()-> Action `litespeed_debug2` + add_action('litespeed_disable_all', array($this, '_disable_all')); // API::disable_all( $reason ) -> Action `litespeed_disable_all` - add_action( 'litspeed_after_admin_init', array( $this, '_after_admin_init' ) ); + add_action('litspeed_after_admin_init', array($this, '_after_admin_init')); } /** @@ -171,12 +174,13 @@ public function init() { * @since 3.0 * @access public */ - public function _after_admin_init() { + public function _after_admin_init() + { /** * GUI */ - add_action( 'litespeed_setting_enroll', array( $this->cls( 'Admin_Display' ), 'enroll' ), 10, 4 ); // API::enroll( $id ) // Register a field in setting form to save - add_action( 'litespeed_build_switch', array( $this->cls( 'Admin_Display' ), 'build_switch' ) ); // API::build_switch( $id ) // Build a switch div html snippet + add_action('litespeed_setting_enroll', array($this->cls('Admin_Display'), 'enroll'), 10, 4); // API::enroll( $id ) // Register a field in setting form to save + add_action('litespeed_build_switch', array($this->cls('Admin_Display'), 'build_switch')); // API::build_switch( $id ) // Build a switch div html snippet // API::hook_setting_content( $hook, $priority = 10, $args = 1 ) -> Action `litespeed_settings_content` // API::hook_setting_tab( $hook, $priority = 10, $args = 1 ) -> Action `litespeed_settings_tab` } @@ -187,17 +191,19 @@ public function _after_admin_init() { * @since 2.9.7.2 * @access public */ - public function _disable_all( $reason ) { - do_action( 'litespeed_debug', '[API] Disabled_all due to ' . $reason ); + public function _disable_all($reason) + { + do_action('litespeed_debug', '[API] Disabled_all due to ' . $reason); - ! defined( 'LITESPEED_DISABLE_ALL' ) && define( 'LITESPEED_DISABLE_ALL', true ); + !defined('LITESPEED_DISABLE_ALL') && define('LITESPEED_DISABLE_ALL', true); } /** * @since 3.0 */ - public static function vary_append_commenter() { - Vary::cls()->append_commenter() ; + public static function vary_append_commenter() + { + Vary::cls()->append_commenter(); } /** @@ -205,32 +211,46 @@ public static function vary_append_commenter() { * * @since 4.2 */ - public function is_from_cloud() { - return $this->cls( 'Cloud' )->is_from_cloud(); + public function is_from_cloud() + { + return $this->cls('Cloud')->is_from_cloud(); } - public function purge_post( $pid ) { - $this->cls( 'Purge' )->purge_post( $pid ); + public function purge_post($pid) + { + $this->cls('Purge')->purge_post($pid); } - public function purge_url( $url ) { - $this->cls( 'Purge' )->purge_url( $url ); + public function purge_url($url) + { + $this->cls('Purge')->purge_url($url); } - public function set_cacheable( $reason = false ) { - $this->cls( 'Control' )->set_cacheable( $reason ); + public function set_cacheable($reason = false) + { + $this->cls('Control')->set_cacheable($reason); } - public function esi_enabled() { - return $this->cls( 'Router' )->esi_enabled(); + public function esi_enabled() + { + return $this->cls('Router')->esi_enabled(); } - public function get_ttl() { - return $this->cls( 'Control' )->get_ttl(); + public function get_ttl() + { + return $this->cls('Control')->get_ttl(); } - public function sub_esi_block( $block_id, $wrapper, $params = array(), $control = 'private,no-vary', $silence = false, $preserved = false, $svar = false, $inline_param = array() ) { - return $this->cls( 'ESI' )->sub_esi_block( $block_id, $wrapper, $params, $control, $silence, $preserved, $svar, $inline_param ); + public function sub_esi_block( + $block_id, + $wrapper, + $params = array(), + $control = 'private,no-vary', + $silence = false, + $preserved = false, + $svar = false, + $inline_param = array() + ) { + return $this->cls('ESI')->sub_esi_block($block_id, $wrapper, $params, $control, $silence, $preserved, $svar, $inline_param); } - } diff --git a/src/avatar.cls.php b/src/avatar.cls.php index 621dfd1da..5ddc6a1c4 100644 --- a/src/avatar.cls.php +++ b/src/avatar.cls.php @@ -9,9 +9,10 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Avatar extends Base { +class Avatar extends Base +{ const TYPE_GENERATE = 'generate'; private $_conf_cache_ttl; @@ -25,18 +26,19 @@ class Avatar extends Base { * * @since 1.4 */ - public function __construct() { - if ( ! $this->conf( self::O_DISCUSS_AVATAR_CACHE ) ) { + public function __construct() + { + if (!$this->conf(self::O_DISCUSS_AVATAR_CACHE)) { return; } - Debug2::debug2( '[Avatar] init' ); + Debug2::debug2('[Avatar] init'); - $this->_tb = $this->cls( 'Data' )->tb( 'avatar' ); + $this->_tb = $this->cls('Data')->tb('avatar'); - $this->_conf_cache_ttl = $this->conf( self::O_DISCUSS_AVATAR_CACHE_TTL ); + $this->_conf_cache_ttl = $this->conf(self::O_DISCUSS_AVATAR_CACHE_TTL); - add_filter( 'get_avatar_url', array( $this, 'crawl_avatar' ) ); + add_filter('get_avatar_url', array($this, 'crawl_avatar')); $this->_summary = self::get_summary(); } @@ -47,8 +49,9 @@ public function __construct() { * @since 3.0 * @access public */ - public function need_db() { - if ( $this->conf( self::O_DISCUSS_AVATAR_CACHE ) ) { + public function need_db() + { + if ($this->conf(self::O_DISCUSS_AVATAR_CACHE)) { return true; } @@ -60,28 +63,29 @@ public function need_db() { * @since 3.0 * @access public */ - public function serve_static( $md5 ) { + public function serve_static($md5) + { global $wpdb; - Debug2::debug( '[Avatar] is avatar request' ); + Debug2::debug('[Avatar] is avatar request'); - if ( strlen( $md5 ) !== 32 ) { - Debug2::debug( '[Avatar] wrong md5 ' . $md5 ); + if (strlen($md5) !== 32) { + Debug2::debug('[Avatar] wrong md5 ' . $md5); return; } $q = "SELECT url FROM `$this->_tb` WHERE md5=%s"; - $url = $wpdb->get_var( $wpdb->prepare( $q, $md5 ) ); + $url = $wpdb->get_var($wpdb->prepare($q, $md5)); - if ( ! $url ) { - Debug2::debug( '[Avatar] no matched url for md5 ' . $md5 ); + if (!$url) { + Debug2::debug('[Avatar] no matched url for md5 ' . $md5); return; } - $url = $this->_generate( $url ); + $url = $this->_generate($url); - wp_redirect( $url ); - exit; + wp_redirect($url); + exit(); } /** @@ -90,38 +94,39 @@ public function serve_static( $md5 ) { * @since 3.0 * @access public */ - public function crawl_avatar( $url ) { - if ( ! $url ) { + public function crawl_avatar($url) + { + if (!$url) { return $url; } // Check if its already in dict or not - if ( ! empty( $this->_avatar_realtime_gen_dict[ $url ] ) ) { - Debug2::debug2( '[Avatar] already in dict [url] ' . $url ); + if (!empty($this->_avatar_realtime_gen_dict[$url])) { + Debug2::debug2('[Avatar] already in dict [url] ' . $url); - return $this->_avatar_realtime_gen_dict[ $url ]; + return $this->_avatar_realtime_gen_dict[$url]; } - $realpath = $this->_realpath( $url ); - if ( file_exists( $realpath ) && time() - filemtime( $realpath ) <= $this->_conf_cache_ttl ) { - Debug2::debug2( '[Avatar] cache file exists [url] ' . $url ); - return $this->_rewrite( $url, filemtime( $realpath ) ); + $realpath = $this->_realpath($url); + if (file_exists($realpath) && time() - filemtime($realpath) <= $this->_conf_cache_ttl) { + Debug2::debug2('[Avatar] cache file exists [url] ' . $url); + return $this->_rewrite($url, filemtime($realpath)); } - if ( ! strpos( $url, 'gravatar.com' ) ) { + if (!strpos($url, 'gravatar.com')) { return $url; } // Send request - if ( ! empty( $this->_summary[ 'curr_request' ] ) && time() - $this->_summary[ 'curr_request' ] < 300 ) { - Debug2::debug2( '[Avatar] Bypass generating due to interval limit [url] ' . $url ); + if (!empty($this->_summary['curr_request']) && time() - $this->_summary['curr_request'] < 300) { + Debug2::debug2('[Avatar] Bypass generating due to interval limit [url] ' . $url); return $url; } // Generate immediately - $this->_avatar_realtime_gen_dict[ $url ] = $this->_generate( $url ); + $this->_avatar_realtime_gen_dict[$url] = $this->_generate($url); - return $this->_avatar_realtime_gen_dict[ $url ]; + return $this->_avatar_realtime_gen_dict[$url]; } /** @@ -130,16 +135,17 @@ public function crawl_avatar( $url ) { * @since 3.0 * @access public */ - public function queue_count() { + public function queue_count() + { global $wpdb; // If var not exists, mean table not exists // todo: not true - if ( ! $this->_tb ) { + if (!$this->_tb) { return false; } - $q = "SELECT COUNT(*) FROM `$this->_tb` WHERE dateline<" . ( time() - $this->_conf_cache_ttl ); - return $wpdb->get_var( $q ); + $q = "SELECT COUNT(*) FROM `$this->_tb` WHERE dateline<" . (time() - $this->_conf_cache_ttl); + return $wpdb->get_var($q); } /** @@ -149,8 +155,9 @@ public function queue_count() { * * @since 3.0 */ - private function _rewrite( $url, $time = null ) { - return LITESPEED_STATIC_URL . '/avatar/' . $this->_filepath( $url ) . ( $time ? '?ver=' . $time : '' ); + private function _rewrite($url, $time = null) + { + return LITESPEED_STATIC_URL . '/avatar/' . $this->_filepath($url) . ($time ? '?ver=' . $time : ''); } /** @@ -159,8 +166,9 @@ private function _rewrite( $url, $time = null ) { * @since 3.0 * @access private */ - private function _realpath( $url ) { - return LITESPEED_STATIC_DIR . '/avatar/' . $this->_filepath( $url ); + private function _realpath($url) + { + return LITESPEED_STATIC_DIR . '/avatar/' . $this->_filepath($url); } /** @@ -168,9 +176,10 @@ private function _realpath( $url ) { * * @since 4.0 */ - private function _filepath( $url ) { - $filename = md5( $url ) . '.jpg'; - if ( is_multisite() ) { + private function _filepath($url) + { + $filename = md5($url) . '.jpg'; + if (is_multisite()) { $filename = get_current_blog_id() . '/' . $filename; } return $filename; @@ -182,33 +191,34 @@ private function _filepath( $url ) { * @since 3.0 * @access public */ - public static function cron( $force = false ) { + public static function cron($force = false) + { global $wpdb; $_instance = self::cls(); - if ( ! $_instance->queue_count() ) { - Debug2::debug( '[Avatar] no queue' ); + if (!$_instance->queue_count()) { + Debug2::debug('[Avatar] no queue'); return; } // For cron, need to check request interval too - if ( ! $force ) { - if ( ! empty( $_instance->_summary[ 'curr_request' ] ) && time() - $_instance->_summary[ 'curr_request' ] < 300 ) { - Debug2::debug( '[Avatar] curr_request too close' ); + if (!$force) { + if (!empty($_instance->_summary['curr_request']) && time() - $_instance->_summary['curr_request'] < 300) { + Debug2::debug('[Avatar] curr_request too close'); return; } } $q = "SELECT url FROM `$_instance->_tb` WHERE dateline < %d ORDER BY id DESC LIMIT %d"; - $q = $wpdb->prepare( $q, array( time() - $_instance->_conf_cache_ttl, apply_filters( 'litespeed_avatar_limit', 30 ) ) ); + $q = $wpdb->prepare($q, array(time() - $_instance->_conf_cache_ttl, apply_filters('litespeed_avatar_limit', 30))); - $list = $wpdb->get_results( $q ); - Debug2::debug( '[Avatar] cron job [count] ' . count( $list ) ); + $list = $wpdb->get_results($q); + Debug2::debug('[Avatar] cron job [count] ' . count($list)); - foreach ( $list as $v ) { - Debug2::debug( '[Avatar] cron job [url] ' . $v->url ); + foreach ($list as $v) { + Debug2::debug('[Avatar] cron job [url] ' . $v->url); - $_instance->_generate( $v->url ); + $_instance->_generate($v->url); } } @@ -218,50 +228,51 @@ public static function cron( $force = false ) { * @since 3.0 * @access private */ - private function _generate( $url ) { + private function _generate($url) + { global $wpdb; // Record the data - $file = $this->_realpath( $url ); + $file = $this->_realpath($url); // Update request status - self::save_summary( array( 'curr_request' => time() ) ); + self::save_summary(array('curr_request' => time())); // Generate - $this->_maybe_mk_cache_folder( 'avatar' ); + $this->_maybe_mk_cache_folder('avatar'); - $response = wp_remote_get( $url, array( 'timeout' => 180, 'stream' => true, 'filename' => $file ) ); + $response = wp_remote_get($url, array('timeout' => 180, 'stream' => true, 'filename' => $file)); - Debug2::debug( '[Avatar] _generate [url] ' . $url ); + Debug2::debug('[Avatar] _generate [url] ' . $url); // Parse response data - if ( is_wp_error( $response ) ) { + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - file_exists( $file ) && unlink( $file ); - Debug2::debug( '[Avatar] failed to get: ' . $error_message ); + file_exists($file) && unlink($file); + Debug2::debug('[Avatar] failed to get: ' . $error_message); return $url; } // Save summary data - self::save_summary( array( - 'last_spent' => time() - $this->_summary[ 'curr_request' ], - 'last_request' => $this->_summary[ 'curr_request' ], + self::save_summary(array( + 'last_spent' => time() - $this->_summary['curr_request'], + 'last_request' => $this->_summary['curr_request'], 'curr_request' => 0, - ) ); + )); // Update DB - $md5 = md5( $url ); + $md5 = md5($url); $q = "UPDATE `$this->_tb` SET dateline=%d WHERE md5=%s"; - $existed = $wpdb->query( $wpdb->prepare( $q, array( time(), $md5 ) ) ); - if ( ! $existed ) { + $existed = $wpdb->query($wpdb->prepare($q, array(time(), $md5))); + if (!$existed) { $q = "INSERT INTO `$this->_tb` SET url=%s, md5=%s, dateline=%d"; - $wpdb->query( $wpdb->prepare( $q, array( $url, $md5, time() ) ) ); + $wpdb->query($wpdb->prepare($q, array($url, $md5, time()))); } - Debug2::debug( '[Avatar] saved avatar ' . $file ); + Debug2::debug('[Avatar] saved avatar ' . $file); - return $this->_rewrite( $url ); + return $this->_rewrite($url); } /** @@ -270,12 +281,13 @@ private function _generate( $url ) { * @since 3.0 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { - case self::TYPE_GENERATE : - self::cron( true ); + switch ($type) { + case self::TYPE_GENERATE: + self::cron(true); break; default: @@ -284,5 +296,4 @@ public function handler() { Admin::redirect(); } - } diff --git a/src/base.cls.php b/src/base.cls.php index e20a782da..870f9f960 100644 --- a/src/base.cls.php +++ b/src/base.cls.php @@ -1,14 +1,17 @@ '', - self::HASH => '', - self::O_AUTO_UPGRADE => false, - self::O_API_KEY => '', - self::O_SERVER_IP => '', - self::O_GUEST => false, - self::O_GUEST_OPTM => false, - self::O_NEWS => false, - self::O_GUEST_UAS => array(), - self::O_GUEST_IPS => array(), + self::_VER => '', + self::HASH => '', + self::O_AUTO_UPGRADE => false, + self::O_API_KEY => '', + self::O_SERVER_IP => '', + self::O_GUEST => false, + self::O_GUEST_OPTM => false, + self::O_NEWS => false, + self::O_GUEST_UAS => array(), + self::O_GUEST_IPS => array(), // Cache - self::O_CACHE => false, - self::O_CACHE_PRIV => false, - self::O_CACHE_COMMENTER => false, - self::O_CACHE_REST => false, - self::O_CACHE_PAGE_LOGIN => false, - self::O_CACHE_FAVICON => false, - self::O_CACHE_RES => false, - self::O_CACHE_MOBILE => false, - self::O_CACHE_MOBILE_RULES => array(), - self::O_CACHE_BROWSER => false, - self::O_CACHE_EXC_USERAGENTS => array(), - self::O_CACHE_EXC_COOKIES => array(), - self::O_CACHE_EXC_QS => array(), - self::O_CACHE_EXC_CAT => array(), - self::O_CACHE_EXC_TAG => array(), - self::O_CACHE_FORCE_URI => array(), - self::O_CACHE_FORCE_PUB_URI => array(), - self::O_CACHE_PRIV_URI => array(), - self::O_CACHE_EXC => array(), - self::O_CACHE_EXC_ROLES => array(), - self::O_CACHE_DROP_QS => array(), - self::O_CACHE_TTL_PUB => 0, - self::O_CACHE_TTL_PRIV => 0, - self::O_CACHE_TTL_FRONTPAGE => 0, - self::O_CACHE_TTL_FEED => 0, - self::O_CACHE_TTL_REST => 0, - self::O_CACHE_TTL_BROWSER => 0, - self::O_CACHE_TTL_STATUS => array(), - self::O_CACHE_LOGIN_COOKIE => '', - self::O_CACHE_VARY_GROUP => array(), + self::O_CACHE => false, + self::O_CACHE_PRIV => false, + self::O_CACHE_COMMENTER => false, + self::O_CACHE_REST => false, + self::O_CACHE_PAGE_LOGIN => false, + self::O_CACHE_FAVICON => false, + self::O_CACHE_RES => false, + self::O_CACHE_MOBILE => false, + self::O_CACHE_MOBILE_RULES => array(), + self::O_CACHE_BROWSER => false, + self::O_CACHE_EXC_USERAGENTS => array(), + self::O_CACHE_EXC_COOKIES => array(), + self::O_CACHE_EXC_QS => array(), + self::O_CACHE_EXC_CAT => array(), + self::O_CACHE_EXC_TAG => array(), + self::O_CACHE_FORCE_URI => array(), + self::O_CACHE_FORCE_PUB_URI => array(), + self::O_CACHE_PRIV_URI => array(), + self::O_CACHE_EXC => array(), + self::O_CACHE_EXC_ROLES => array(), + self::O_CACHE_DROP_QS => array(), + self::O_CACHE_TTL_PUB => 0, + self::O_CACHE_TTL_PRIV => 0, + self::O_CACHE_TTL_FRONTPAGE => 0, + self::O_CACHE_TTL_FEED => 0, + self::O_CACHE_TTL_REST => 0, + self::O_CACHE_TTL_BROWSER => 0, + self::O_CACHE_TTL_STATUS => array(), + self::O_CACHE_LOGIN_COOKIE => '', + self::O_CACHE_VARY_COOKIES => array(), + self::O_CACHE_VARY_GROUP => array(), // Purge - self::O_PURGE_ON_UPGRADE => false, - self::O_PURGE_STALE => false, - self::O_PURGE_POST_ALL => false, - self::O_PURGE_POST_FRONTPAGE => false, - self::O_PURGE_POST_HOMEPAGE => false, - self::O_PURGE_POST_PAGES => false, - self::O_PURGE_POST_PAGES_WITH_RECENT_POSTS => false, - self::O_PURGE_POST_AUTHOR => false, - self::O_PURGE_POST_YEAR => false, - self::O_PURGE_POST_MONTH => false, - self::O_PURGE_POST_DATE => false, - self::O_PURGE_POST_TERM => false, - self::O_PURGE_POST_POSTTYPE => false, - self::O_PURGE_TIMED_URLS => array(), - self::O_PURGE_TIMED_URLS_TIME => '', - self::O_PURGE_HOOK_ALL => array(), + self::O_PURGE_ON_UPGRADE => false, + self::O_PURGE_STALE => false, + self::O_PURGE_POST_ALL => false, + self::O_PURGE_POST_FRONTPAGE => false, + self::O_PURGE_POST_HOMEPAGE => false, + self::O_PURGE_POST_PAGES => false, + self::O_PURGE_POST_PAGES_WITH_RECENT_POSTS => false, + self::O_PURGE_POST_AUTHOR => false, + self::O_PURGE_POST_YEAR => false, + self::O_PURGE_POST_MONTH => false, + self::O_PURGE_POST_DATE => false, + self::O_PURGE_POST_TERM => false, + self::O_PURGE_POST_POSTTYPE => false, + self::O_PURGE_TIMED_URLS => array(), + self::O_PURGE_TIMED_URLS_TIME => '', + self::O_PURGE_HOOK_ALL => array(), // ESI - self::O_ESI => false, - self::O_ESI_CACHE_ADMBAR => false, - self::O_ESI_CACHE_COMMFORM => false, - self::O_ESI_NONCE => array(), + self::O_ESI => false, + self::O_ESI_CACHE_ADMBAR => false, + self::O_ESI_CACHE_COMMFORM => false, + self::O_ESI_NONCE => array(), // Util - self::O_UTIL_INSTANT_CLICK => false, - self::O_UTIL_NO_HTTPS_VARY => false, + self::O_UTIL_INSTANT_CLICK => false, + self::O_UTIL_NO_HTTPS_VARY => false, // Debug - self::O_DEBUG_DISABLE_ALL => false, - self::O_DEBUG => false, - self::O_DEBUG_IPS => array(), - self::O_DEBUG_LEVEL => false, - self::O_DEBUG_FILESIZE => 0, - self::O_DEBUG_COOKIE => false, - self::O_DEBUG_COLLAPS_QS => false, - self::O_DEBUG_INC => array(), - self::O_DEBUG_EXC => array(), - self::O_DEBUG_EXC_STRINGS => array(), + self::O_DEBUG_DISABLE_ALL => false, + self::O_DEBUG => false, + self::O_DEBUG_IPS => array(), + self::O_DEBUG_LEVEL => false, + self::O_DEBUG_FILESIZE => 0, + self::O_DEBUG_COOKIE => false, + self::O_DEBUG_COLLAPS_QS => false, + self::O_DEBUG_INC => array(), + self::O_DEBUG_EXC => array(), + self::O_DEBUG_EXC_STRINGS => array(), // DB Optm - self::O_DB_OPTM_REVISIONS_MAX => 0, - self::O_DB_OPTM_REVISIONS_AGE => 0, + self::O_DB_OPTM_REVISIONS_MAX => 0, + self::O_DB_OPTM_REVISIONS_AGE => 0, // HTML Optm - self::O_OPTM_CSS_MIN => false, - self::O_OPTM_CSS_COMB => false, - self::O_OPTM_CSS_COMB_EXT_INL => false, - self::O_OPTM_UCSS => false, - self::O_OPTM_UCSS_INLINE => false, - self::O_OPTM_UCSS_WHITELIST => array(), - self::O_OPTM_UCSS_EXC => array(), - self::O_OPTM_CSS_EXC => array(), - self::O_OPTM_JS_MIN => false, - self::O_OPTM_JS_COMB => false, - self::O_OPTM_JS_COMB_EXT_INL => false, - self::O_OPTM_JS_EXC => array(), - self::O_OPTM_HTML_MIN => false, - self::O_OPTM_HTML_LAZY => array(), - self::O_OPTM_QS_RM => false, - self::O_OPTM_GGFONTS_RM => false, - self::O_OPTM_CSS_ASYNC => false, - self::O_OPTM_CCSS_PER_URL => false, - self::O_OPTM_CCSS_SEP_POSTTYPE => array(), - self::O_OPTM_CCSS_SEP_URI => array(), - self::O_OPTM_CSS_ASYNC_INLINE => false, - self::O_OPTM_CSS_FONT_DISPLAY => false, - self::O_OPTM_JS_DEFER => false, - self::O_OPTM_EMOJI_RM => false, - self::O_OPTM_NOSCRIPT_RM => false, - self::O_OPTM_GGFONTS_ASYNC => false, - self::O_OPTM_EXC_ROLES => array(), - self::O_OPTM_CCSS_CON => '', - self::O_OPTM_JS_DEFER_EXC => array(), - self::O_OPTM_GM_JS_EXC => array(), - self::O_OPTM_DNS_PREFETCH => array(), - self::O_OPTM_DNS_PREFETCH_CTRL => false, - self::O_OPTM_EXC => array(), - self::O_OPTM_GUEST_ONLY => false, + self::O_OPTM_CSS_MIN => false, + self::O_OPTM_CSS_COMB => false, + self::O_OPTM_CSS_COMB_EXT_INL => false, + self::O_OPTM_UCSS => false, + self::O_OPTM_UCSS_INLINE => false, + self::O_OPTM_UCSS_SELECTOR_WHITELIST => array(), + self::O_OPTM_UCSS_FILE_EXC_INLINE => array(), + self::O_OPTM_UCSS_EXC => array(), + self::O_OPTM_CSS_EXC => array(), + self::O_OPTM_JS_MIN => false, + self::O_OPTM_JS_COMB => false, + self::O_OPTM_JS_COMB_EXT_INL => false, + self::O_OPTM_JS_DELAY_INC => array(), + self::O_OPTM_JS_EXC => array(), + self::O_OPTM_HTML_MIN => false, + self::O_OPTM_HTML_LAZY => array(), + self::O_OPTM_QS_RM => false, + self::O_OPTM_GGFONTS_RM => false, + self::O_OPTM_CSS_ASYNC => false, + self::O_OPTM_CCSS_PER_URL => false, + self::O_OPTM_CCSS_SEP_POSTTYPE => array(), + self::O_OPTM_CCSS_SEP_URI => array(), + self::O_OPTM_CSS_ASYNC_INLINE => false, + self::O_OPTM_CSS_FONT_DISPLAY => false, + self::O_OPTM_JS_DEFER => false, + self::O_OPTM_EMOJI_RM => false, + self::O_OPTM_NOSCRIPT_RM => false, + self::O_OPTM_GGFONTS_ASYNC => false, + self::O_OPTM_EXC_ROLES => array(), + self::O_OPTM_CCSS_CON => '', + self::O_OPTM_JS_DEFER_EXC => array(), + self::O_OPTM_GM_JS_EXC => array(), + self::O_OPTM_DNS_PREFETCH => array(), + self::O_OPTM_DNS_PREFETCH_CTRL => false, + self::O_OPTM_DNS_PRECONNECT => array(), + self::O_OPTM_EXC => array(), + self::O_OPTM_GUEST_ONLY => false, // Object - self::O_OBJECT => false, - self::O_OBJECT_KIND => false, - self::O_OBJECT_HOST => '', - self::O_OBJECT_PORT => 0, - self::O_OBJECT_LIFE => 0, - self::O_OBJECT_PERSISTENT => false, - self::O_OBJECT_ADMIN => false, - self::O_OBJECT_TRANSIENTS => false, - self::O_OBJECT_DB_ID => 0, - self::O_OBJECT_USER => '', - self::O_OBJECT_PSWD => '', - self::O_OBJECT_GLOBAL_GROUPS => array(), + self::O_OBJECT => false, + self::O_OBJECT_KIND => false, + self::O_OBJECT_HOST => '', + self::O_OBJECT_PORT => 0, + self::O_OBJECT_LIFE => 0, + self::O_OBJECT_PERSISTENT => false, + self::O_OBJECT_ADMIN => false, + self::O_OBJECT_TRANSIENTS => false, + self::O_OBJECT_DB_ID => 0, + self::O_OBJECT_USER => '', + self::O_OBJECT_PSWD => '', + self::O_OBJECT_GLOBAL_GROUPS => array(), self::O_OBJECT_NON_PERSISTENT_GROUPS => array(), // Discuss - self::O_DISCUSS_AVATAR_CACHE => false, - self::O_DISCUSS_AVATAR_CRON => false, - self::O_DISCUSS_AVATAR_CACHE_TTL => 0, - self::O_OPTM_LOCALIZE => false, - self::O_OPTM_LOCALIZE_DOMAINS => array(), + self::O_DISCUSS_AVATAR_CACHE => false, + self::O_DISCUSS_AVATAR_CRON => false, + self::O_DISCUSS_AVATAR_CACHE_TTL => 0, + self::O_OPTM_LOCALIZE => false, + self::O_OPTM_LOCALIZE_DOMAINS => array(), // Media - self::O_MEDIA_LAZY => false, - self::O_MEDIA_LAZY_PLACEHOLDER => '', - self::O_MEDIA_PLACEHOLDER_RESP => false, - self::O_MEDIA_PLACEHOLDER_RESP_COLOR => '', - self::O_MEDIA_PLACEHOLDER_RESP_SVG => '', - self::O_MEDIA_LQIP => false, - self::O_MEDIA_LQIP_QUAL => 0, - self::O_MEDIA_LQIP_MIN_W => 0, - self::O_MEDIA_LQIP_MIN_H => 0, - self::O_MEDIA_PLACEHOLDER_RESP_ASYNC => false, - self::O_MEDIA_IFRAME_LAZY => false, - self::O_MEDIA_ADD_MISSING_SIZES => false, - self::O_MEDIA_LAZY_EXC => array(), - self::O_MEDIA_LAZY_CLS_EXC => array(), - self::O_MEDIA_LAZY_PARENT_CLS_EXC => array(), - self::O_MEDIA_IFRAME_LAZY_CLS_EXC => array(), - self::O_MEDIA_IFRAME_LAZY_PARENT_CLS_EXC => array(), - self::O_MEDIA_LAZY_URI_EXC => array(), - self::O_MEDIA_LQIP_EXC => array(), - self::O_MEDIA_VPI => false, - self::O_MEDIA_VPI_CRON => false, + self::O_MEDIA_PRELOAD_FEATURED => false, + self::O_MEDIA_LAZY => false, + self::O_MEDIA_LAZY_PLACEHOLDER => '', + self::O_MEDIA_PLACEHOLDER_RESP => false, + self::O_MEDIA_PLACEHOLDER_RESP_COLOR => '', + self::O_MEDIA_PLACEHOLDER_RESP_SVG => '', + self::O_MEDIA_LQIP => false, + self::O_MEDIA_LQIP_QUAL => 0, + self::O_MEDIA_LQIP_MIN_W => 0, + self::O_MEDIA_LQIP_MIN_H => 0, + self::O_MEDIA_PLACEHOLDER_RESP_ASYNC => false, + self::O_MEDIA_IFRAME_LAZY => false, + self::O_MEDIA_ADD_MISSING_SIZES => false, + self::O_MEDIA_LAZY_EXC => array(), + self::O_MEDIA_LAZY_CLS_EXC => array(), + self::O_MEDIA_LAZY_PARENT_CLS_EXC => array(), + self::O_MEDIA_IFRAME_LAZY_CLS_EXC => array(), + self::O_MEDIA_IFRAME_LAZY_PARENT_CLS_EXC => array(), + self::O_MEDIA_LAZY_URI_EXC => array(), + self::O_MEDIA_LQIP_EXC => array(), + self::O_MEDIA_VPI => false, + self::O_MEDIA_VPI_CRON => false, // Image Optm - self::O_IMG_OPTM_AUTO => false, - self::O_IMG_OPTM_CRON => false, - self::O_IMG_OPTM_ORI => false, - self::O_IMG_OPTM_RM_BKUP => false, - self::O_IMG_OPTM_WEBP => false, - self::O_IMG_OPTM_LOSSLESS => false, - self::O_IMG_OPTM_EXIF => false, - self::O_IMG_OPTM_WEBP_REPLACE => false, - self::O_IMG_OPTM_WEBP_ATTR => array(), - self::O_IMG_OPTM_WEBP_REPLACE_SRCSET => false, - self::O_IMG_OPTM_JPG_QUALITY => 0, + self::O_IMG_OPTM_AUTO => false, + self::O_IMG_OPTM_CRON => false, + self::O_IMG_OPTM_ORI => false, + self::O_IMG_OPTM_RM_BKUP => false, + self::O_IMG_OPTM_WEBP => false, + self::O_IMG_OPTM_LOSSLESS => false, + self::O_IMG_OPTM_EXIF => false, + self::O_IMG_OPTM_WEBP_ATTR => array(), + self::O_IMG_OPTM_WEBP_REPLACE_SRCSET => false, + self::O_IMG_OPTM_JPG_QUALITY => 0, // Crawler - self::O_CRAWLER => false, - self::O_CRAWLER_USLEEP => 0, - self::O_CRAWLER_RUN_DURATION => 0, - self::O_CRAWLER_RUN_INTERVAL => 0, - self::O_CRAWLER_CRAWL_INTERVAL => 0, - self::O_CRAWLER_THREADS => 0, - self::O_CRAWLER_TIMEOUT => 0, - self::O_CRAWLER_LOAD_LIMIT => 0, - self::O_CRAWLER_SITEMAP => '', - self::O_CRAWLER_DROP_DOMAIN => false, - self::O_CRAWLER_MAP_TIMEOUT => 0, - self::O_CRAWLER_ROLES => array(), - self::O_CRAWLER_COOKIES => array(), + self::O_CRAWLER => false, + self::O_CRAWLER_USLEEP => 0, + self::O_CRAWLER_RUN_DURATION => 0, + self::O_CRAWLER_RUN_INTERVAL => 0, + self::O_CRAWLER_CRAWL_INTERVAL => 0, + self::O_CRAWLER_THREADS => 0, + self::O_CRAWLER_TIMEOUT => 0, + self::O_CRAWLER_LOAD_LIMIT => 0, + self::O_CRAWLER_SITEMAP => '', + self::O_CRAWLER_DROP_DOMAIN => false, + self::O_CRAWLER_MAP_TIMEOUT => 0, + self::O_CRAWLER_ROLES => array(), + self::O_CRAWLER_COOKIES => array(), // Misc - self::O_MISC_HEARTBEAT_FRONT => false, - self::O_MISC_HEARTBEAT_FRONT_TTL => 0, - self::O_MISC_HEARTBEAT_BACK => false, - self::O_MISC_HEARTBEAT_BACK_TTL => 0, - self::O_MISC_HEARTBEAT_EDITOR => false, - self::O_MISC_HEARTBEAT_EDITOR_TTL => 0, + self::O_MISC_HEARTBEAT_FRONT => false, + self::O_MISC_HEARTBEAT_FRONT_TTL => 0, + self::O_MISC_HEARTBEAT_BACK => false, + self::O_MISC_HEARTBEAT_BACK_TTL => 0, + self::O_MISC_HEARTBEAT_EDITOR => false, + self::O_MISC_HEARTBEAT_EDITOR_TTL => 0, // CDN - self::O_CDN => false, - self::O_CDN_ORI => array(), - self::O_CDN_ORI_DIR => array(), - self::O_CDN_EXC => array(), - self::O_CDN_QUIC => false, - self::O_CDN_CLOUDFLARE => false, + self::O_CDN => false, + self::O_CDN_ORI => array(), + self::O_CDN_ORI_DIR => array(), + self::O_CDN_EXC => array(), + self::O_CDN_QUIC => false, + self::O_CDN_CLOUDFLARE => false, self::O_CDN_CLOUDFLARE_EMAIL => '', - self::O_CDN_CLOUDFLARE_KEY => '', + self::O_CDN_CLOUDFLARE_KEY => '', self::O_CDN_CLOUDFLARE_NAME => '', self::O_CDN_CLOUDFLARE_ZONE => '', - self::O_CDN_MAPPING => array(), - self::O_CDN_ATTR => array(), - - self::O_QC_TOKEN => '', - self::O_QC_NAMESERVERS => '', + self::O_CDN_MAPPING => array(), + self::O_CDN_ATTR => array(), + self::O_QC_TOKEN => '', + self::O_QC_NAMESERVERS => '', ); protected static $_default_site_options = array( - self::_VER => '', - self::O_CACHE => false, - self::NETWORK_O_USE_PRIMARY => false, - self::O_AUTO_UPGRADE => false, - self::O_GUEST => false, - - self::O_CACHE_FAVICON => false, - self::O_CACHE_RES => false, - self::O_CACHE_BROWSER => false, - self::O_CACHE_MOBILE => false, - self::O_CACHE_MOBILE_RULES => array(), - self::O_CACHE_LOGIN_COOKIE => '', - self::O_CACHE_EXC_COOKIES => array(), - self::O_CACHE_EXC_USERAGENTS => array(), - self::O_CACHE_TTL_BROWSER => 0, - - self::O_PURGE_ON_UPGRADE => false, - - self::O_OBJECT => false, - self::O_OBJECT_KIND => false, - self::O_OBJECT_HOST => '', - self::O_OBJECT_PORT => 0, - self::O_OBJECT_LIFE => 0, - self::O_OBJECT_PERSISTENT => false, - self::O_OBJECT_ADMIN => false, - self::O_OBJECT_TRANSIENTS => false, - self::O_OBJECT_DB_ID => 0, - self::O_OBJECT_USER => '', - self::O_OBJECT_PSWD => '', - self::O_OBJECT_GLOBAL_GROUPS => array(), + self::_VER => '', + self::O_CACHE => false, + self::NETWORK_O_USE_PRIMARY => false, + self::O_AUTO_UPGRADE => false, + self::O_GUEST => false, + + self::O_CACHE_FAVICON => false, + self::O_CACHE_RES => false, + self::O_CACHE_BROWSER => false, + self::O_CACHE_MOBILE => false, + self::O_CACHE_MOBILE_RULES => array(), + self::O_CACHE_LOGIN_COOKIE => '', + self::O_CACHE_VARY_COOKIES => array(), + self::O_CACHE_EXC_COOKIES => array(), + self::O_CACHE_EXC_USERAGENTS => array(), + self::O_CACHE_TTL_BROWSER => 0, + + self::O_PURGE_ON_UPGRADE => false, + + self::O_OBJECT => false, + self::O_OBJECT_KIND => false, + self::O_OBJECT_HOST => '', + self::O_OBJECT_PORT => 0, + self::O_OBJECT_LIFE => 0, + self::O_OBJECT_PERSISTENT => false, + self::O_OBJECT_ADMIN => false, + self::O_OBJECT_TRANSIENTS => false, + self::O_OBJECT_DB_ID => 0, + self::O_OBJECT_USER => '', + self::O_OBJECT_PSWD => '', + self::O_OBJECT_GLOBAL_GROUPS => array(), self::O_OBJECT_NON_PERSISTENT_GROUPS => array(), // Debug - self::O_DEBUG_DISABLE_ALL => false, - self::O_DEBUG => false, - self::O_DEBUG_IPS => array(), - self::O_DEBUG_LEVEL => false, - self::O_DEBUG_FILESIZE => 0, - self::O_DEBUG_COOKIE => false, - self::O_DEBUG_COLLAPS_QS => false, - self::O_DEBUG_INC => array(), - self::O_DEBUG_EXC => array(), - self::O_DEBUG_EXC_STRINGS => array(), - - self::O_IMG_OPTM_WEBP_REPLACE => false, - + self::O_DEBUG_DISABLE_ALL => false, + self::O_DEBUG => false, + self::O_DEBUG_IPS => array(), + self::O_DEBUG_LEVEL => false, + self::O_DEBUG_FILESIZE => 0, + self::O_DEBUG_COOKIE => false, + self::O_DEBUG_COLLAPS_QS => false, + self::O_DEBUG_INC => array(), + self::O_DEBUG_EXC => array(), + self::O_DEBUG_EXC_STRINGS => array(), + + self::O_IMG_OPTM_WEBP => false, ); // NOTE: all the val of following items will be int while not bool protected static $_multi_switch_list = array( - self::O_DEBUG => 2, - self::O_OPTM_JS_DEFER => 2, + self::O_DEBUG => 2, + self::O_OPTM_JS_DEFER => 2, ); - /** * Correct the option type * @@ -606,37 +615,34 @@ class Base extends Root { * * @since 3.0.3 */ - protected function type_casting( $val, $id, $is_site_conf = false ) { - $default_v = ! $is_site_conf ? self::$_default_options[ $id ] : self::$_default_site_options[ $id ]; - if ( is_bool( $default_v ) ) { - if ( $val === 'true' ) { + protected function type_casting($val, $id, $is_site_conf = false) + { + $default_v = !$is_site_conf ? self::$_default_options[$id] : self::$_default_site_options[$id]; + if (is_bool($default_v)) { + if ($val === 'true') { $val = true; } - if ( $val === 'false' ) { + if ($val === 'false') { $val = false; } - $max = $this->_conf_multi_switch( $id ); - if ( $max ) { + $max = $this->_conf_multi_switch($id); + if ($max) { $val = (int) $val; $val %= $max + 1; - } - else { + } else { $val = (bool) $val; } - } - elseif ( is_array( $default_v ) ) { + } elseif (is_array($default_v)) { // from textarea input - if ( ! is_array( $val ) ) { - $val = Utility::sanitize_lines( $val, $this->_conf_filter( $id ) ); + if (!is_array($val)) { + $val = Utility::sanitize_lines($val, $this->_conf_filter($id)); } - } - elseif ( ! is_string( $default_v ) ) { + } elseif (!is_string($default_v)) { $val = (int) $val; - } - else { + } else { // Check if the string has a limit set - $val = $this->_conf_string_val( $id, $val ); + $val = $this->_conf_string_val($id, $val); } return $val; @@ -647,28 +653,28 @@ protected function type_casting( $val, $id, $is_site_conf = false ) { * * @since 3.0 */ - public function load_default_site_vals() { + public function load_default_site_vals() + { // Load network_default.ini - if ( file_exists( LSCWP_DIR . 'data/const.network_default.ini' ) ) { - $default_ini_cfg = parse_ini_file( LSCWP_DIR . 'data/const.network_default.ini', true ); - foreach ( self::$_default_site_options as $k => $v ) { - if ( ! array_key_exists( $k, $default_ini_cfg ) ) { + if (file_exists(LSCWP_DIR . 'data/const.network_default.ini')) { + $default_ini_cfg = parse_ini_file(LSCWP_DIR . 'data/const.network_default.ini', true); + foreach (self::$_default_site_options as $k => $v) { + if (!array_key_exists($k, $default_ini_cfg)) { continue; } // Parse value in ini file - $ini_v = $this->type_casting( $default_ini_cfg[ $k ], $k, true ); + $ini_v = $this->type_casting($default_ini_cfg[$k], $k, true); - if ( $ini_v == $v ) { + if ($ini_v == $v) { continue; } - self::$_default_site_options[ $k ] = $ini_v; - + self::$_default_site_options[$k] = $ini_v; } } - self::$_default_site_options[ self::_VER ] = Core::VER; + self::$_default_site_options[self::_VER] = Core::VER; return self::$_default_site_options; } @@ -679,17 +685,18 @@ public function load_default_site_vals() { * @since 3.0 * @access public */ - public function load_default_vals() { + public function load_default_vals() + { // Load default.ini - if ( file_exists( LSCWP_DIR . 'data/const.default.ini' ) ) { - $default_ini_cfg = parse_ini_file( LSCWP_DIR . 'data/const.default.ini', true ); - foreach ( self::$_default_options as $k => $v ) { - if ( ! array_key_exists( $k, $default_ini_cfg ) ) { + if (file_exists(LSCWP_DIR . 'data/const.default.ini')) { + $default_ini_cfg = parse_ini_file(LSCWP_DIR . 'data/const.default.ini', true); + foreach (self::$_default_options as $k => $v) { + if (!array_key_exists($k, $default_ini_cfg)) { continue; } // Parse value in ini file - $ini_v = $this->type_casting( $default_ini_cfg[ $k ], $k ); + $ini_v = $this->type_casting($default_ini_cfg[$k], $k); // NOTE: Multiple lines value must be stored as array /** @@ -706,7 +713,7 @@ public function load_default_vals() { * format out: * [0] = [ 'url' => 'https://example.com', 'inc_js' => true, 'filetype' => [ '.css', '.js', '.jpg' ] ] */ - if ( $k == self::O_CDN_MAPPING ) { + if ($k == self::O_CDN_MAPPING) { $mapping_fields = array( self::CDN_MAPPING_URL, self::CDN_MAPPING_INC_IMG, @@ -715,49 +722,49 @@ public function load_default_vals() { self::CDN_MAPPING_FILETYPE, // Array ); $ini_v2 = array(); - foreach ( $ini_v[ self::CDN_MAPPING_URL ] as $k2 => $v2 ) {// $k2 is numeric + foreach ($ini_v[self::CDN_MAPPING_URL] as $k2 => $v2) { + // $k2 is numeric $this_row = array(); - foreach ( $mapping_fields as $v3 ) { - $this_v = ! empty( $ini_v[ $v3 ][ $k2 ] ) ? $ini_v[ $v3 ][ $k2 ] : false; - if ( $v3 == self::CDN_MAPPING_URL ) { - $this_v = $this_v ? : ''; + foreach ($mapping_fields as $v3) { + $this_v = !empty($ini_v[$v3][$k2]) ? $ini_v[$v3][$k2] : false; + if ($v3 == self::CDN_MAPPING_URL) { + $this_v = $this_v ?: ''; } - if ( $v3 == self::CDN_MAPPING_FILETYPE ) { - $this_v = $this_v ? Utility::sanitize_lines( $this_v ) : array(); // Note: Since v3.0 its already an array + if ($v3 == self::CDN_MAPPING_FILETYPE) { + $this_v = $this_v ? Utility::sanitize_lines($this_v) : array(); // Note: Since v3.0 its already an array } - $this_row[ $v3 ] = $this_v; + $this_row[$v3] = $this_v; } - $ini_v2[ $k2 ] = $this_row; + $ini_v2[$k2] = $this_row; } $ini_v = $ini_v2; } - if ( $ini_v == $v ) { + if ($ini_v == $v) { continue; } - self::$_default_options[ $k ] = $ini_v; + self::$_default_options[$k] = $ini_v; } - } // Load internal default vals // Setting the default bool to int is also to avoid type casting override it back to bool - self::$_default_options[ self::O_CACHE ] = is_multisite() ? self::VAL_ON2 : self::VAL_ON; //For multi site, default is 2 (Use Network Admin Settings). For single site, default is 1 (Enabled). + self::$_default_options[self::O_CACHE] = is_multisite() ? self::VAL_ON2 : self::VAL_ON; //For multi site, default is 2 (Use Network Admin Settings). For single site, default is 1 (Enabled). // Load default vals containing variables - if ( ! self::$_default_options[ self::O_CDN_ORI_DIR ] ) { - self::$_default_options[ self::O_CDN_ORI_DIR ] = LSCWP_CONTENT_FOLDER . "\nwp-includes"; - self::$_default_options[ self::O_CDN_ORI_DIR ] = explode( "\n", self::$_default_options[ self::O_CDN_ORI_DIR ] ); - self::$_default_options[ self::O_CDN_ORI_DIR ] = array_map( 'trim', self::$_default_options[ self::O_CDN_ORI_DIR ] ); + if (!self::$_default_options[self::O_CDN_ORI_DIR]) { + self::$_default_options[self::O_CDN_ORI_DIR] = LSCWP_CONTENT_FOLDER . "\nwp-includes"; + self::$_default_options[self::O_CDN_ORI_DIR] = explode("\n", self::$_default_options[self::O_CDN_ORI_DIR]); + self::$_default_options[self::O_CDN_ORI_DIR] = array_map('trim', self::$_default_options[self::O_CDN_ORI_DIR]); } // Set security key if not initialized yet - if ( ! self::$_default_options[ self::HASH ] ) { - self::$_default_options[ self::HASH ] = Str::rrand( 32 ); + if (!self::$_default_options[self::HASH]) { + self::$_default_options[self::HASH] = Str::rrand(32); } - self::$_default_options[ self::_VER ] = Core::VER; + self::$_default_options[self::_VER] = Core::VER; return self::$_default_options; } @@ -767,7 +774,8 @@ public function load_default_vals() { * * @since 3.0 */ - protected function _conf_string_val( $id, $val ) { + protected function _conf_string_val($id, $val) + { return $val; } @@ -776,12 +784,13 @@ protected function _conf_string_val( $id, $val ) { * * @since 3.0 */ - protected function _conf_multi_switch( $id ) { - if ( ! empty( self::$_multi_switch_list[ $id ] ) ) { - return self::$_multi_switch_list[ $id ]; + protected function _conf_multi_switch($id) + { + if (!empty(self::$_multi_switch_list[$id])) { + return self::$_multi_switch_list[$id]; } - if ( $id == self::O_CACHE && is_multisite() ) { + if ($id == self::O_CACHE && is_multisite()) { return self::VAL_ON2; } @@ -793,8 +802,9 @@ protected function _conf_multi_switch( $id ) { * * @since 3.0 */ - public static function set_multi_switch( $id, $v ) { - self::$_multi_switch_list[ $id ] = $v; + public static function set_multi_switch($id, $v) + { + self::$_multi_switch_list[$id] = $v; } /** @@ -802,8 +812,9 @@ public static function set_multi_switch( $id, $v ) { * * @since 3.0 */ - public static function conf_const( $id ) { - return 'LITESPEED_CONF__' . strtoupper( str_replace( '-', '__', $id ) ); + public static function conf_const($id) + { + return 'LITESPEED_CONF__' . strtoupper(str_replace('-', '__', $id)); } /** @@ -811,31 +822,32 @@ public static function conf_const( $id ) { * * @since 3.0 */ - protected function _conf_filter( $id ) { + protected function _conf_filter($id) + { $filters = array( - self::O_MEDIA_LAZY_EXC => 'uri', - self::O_DEBUG_INC => 'relative', - self::O_DEBUG_EXC => 'relative', - self::O_MEDIA_LAZY_URI_EXC => 'relative', - self::O_CACHE_PRIV_URI => 'relative', - self::O_PURGE_TIMED_URLS => 'relative', - self::O_CACHE_FORCE_URI => 'relative', - self::O_CACHE_FORCE_PUB_URI => 'relative', - self::O_CACHE_EXC => 'relative', + self::O_MEDIA_LAZY_EXC => 'uri', + self::O_DEBUG_INC => 'relative', + self::O_DEBUG_EXC => 'relative', + self::O_MEDIA_LAZY_URI_EXC => 'relative', + self::O_CACHE_PRIV_URI => 'relative', + self::O_PURGE_TIMED_URLS => 'relative', + self::O_CACHE_FORCE_URI => 'relative', + self::O_CACHE_FORCE_PUB_URI => 'relative', + self::O_CACHE_EXC => 'relative', // self::O_OPTM_CSS_EXC => 'uri', // Need to comment out for inline & external CSS // self::O_OPTM_JS_EXC => 'uri', - self::O_OPTM_EXC => 'relative', - self::O_OPTM_CCSS_SEP_URI => 'uri', + self::O_OPTM_EXC => 'relative', + self::O_OPTM_CCSS_SEP_URI => 'uri', // self::O_OPTM_JS_DEFER_EXC => 'uri', - self::O_OPTM_DNS_PREFETCH => 'domain', - self::O_CDN_ORI => 'noprotocol,trailingslash', // `Original URLs` + self::O_OPTM_DNS_PREFETCH => 'domain', + self::O_CDN_ORI => 'noprotocol,trailingslash', // `Original URLs` // self::O_OPTM_LOCALIZE_DOMAINS => 'noprotocol', // `Localize Resources` // self:: => '', // self:: => '', ); - if ( ! empty( $filters[ $id ] ) ) { - return $filters[ $id ]; + if (!empty($filters[$id])) { + return $filters[$id]; } return false; @@ -846,7 +858,8 @@ protected function _conf_filter( $id ) { * * @since 3.0 */ - protected function _conf_purge( $id ) { + protected function _conf_purge($id) + { $check_ids = array( self::O_MEDIA_LAZY_URI_EXC, self::O_OPTM_EXC, @@ -857,7 +870,7 @@ protected function _conf_purge( $id ) { self::O_CACHE_EXC, ); - return in_array( $id, $check_ids ); + return in_array($id, $check_ids); } /** @@ -865,15 +878,11 @@ protected function _conf_purge( $id ) { * * @since 3.0 */ - protected function _conf_purge_all( $id ) { - $check_ids = array( - self::O_CACHE, - self::O_ESI, - self::O_DEBUG_DISABLE_ALL, - self::NETWORK_O_USE_PRIMARY, - ); + protected function _conf_purge_all($id) + { + $check_ids = array(self::O_CACHE, self::O_ESI, self::O_DEBUG_DISABLE_ALL, self::NETWORK_O_USE_PRIMARY); - return in_array( $id, $check_ids ); + return in_array($id, $check_ids); } /** @@ -881,15 +890,11 @@ protected function _conf_purge_all( $id ) { * * @since 3.0 */ - protected function _conf_pswd( $id ) { - $check_ids = array( - self::O_CDN_CLOUDFLARE_KEY, - self::O_OBJECT_PSWD, - self::O_API_KEY, - self::O_QC_TOKEN, - ); + protected function _conf_pswd($id) + { + $check_ids = array(self::O_CDN_CLOUDFLARE_KEY, self::O_OBJECT_PSWD, self::O_API_KEY, self::O_QC_TOKEN); - return in_array( $id, $check_ids ); + return in_array($id, $check_ids); } /** @@ -897,7 +902,8 @@ protected function _conf_pswd( $id ) { * * @since 3.0 */ - protected function _conf_cron( $id ) { + protected function _conf_cron($id) + { $check_ids = array( self::O_IMG_OPTM_CRON, self::O_OPTM_CSS_ASYNC, @@ -907,7 +913,7 @@ protected function _conf_cron( $id ) { self::O_CRAWLER, ); - return in_array( $id, $check_ids ); + return in_array($id, $check_ids); } /** @@ -915,13 +921,14 @@ protected function _conf_cron( $id ) { * * @since 3.0 */ - protected function _conf_purge_tag( $id ) { + protected function _conf_purge_tag($id) + { $check_ids = array( - self::O_CACHE_PAGE_LOGIN => Tag::TYPE_LOGIN, + self::O_CACHE_PAGE_LOGIN => Tag::TYPE_LOGIN, ); - if ( ! empty( $check_ids[ $id ] ) ) { - return $check_ids[ $id ]; + if (!empty($check_ids[$id])) { + return $check_ids[$id]; } return false; @@ -932,7 +939,8 @@ protected function _conf_purge_tag( $id ) { * * @since 2.4.1 */ - public function server_vars() { + public function server_vars() + { $consts = array( 'WP_SITEURL', 'WP_HOME', @@ -950,11 +958,10 @@ public function server_vars() { 'COOKIEHASH', ); $server_vars = array(); - foreach ( $consts as $v ) { - $server_vars[ $v ] = defined( $v ) ? constant( $v ) : NULL; + foreach ($consts as $v) { + $server_vars[$v] = defined($v) ? constant($v) : null; } return $server_vars; } - -} \ No newline at end of file +} diff --git a/src/cdn-setup.cls.php b/src/cdn-setup.cls.php index 697fc9a7a..d77b0b829 100644 --- a/src/cdn-setup.cls.php +++ b/src/cdn-setup.cls.php @@ -1,21 +1,25 @@ _setup_token = $this->conf( self::O_QC_TOKEN ); + public function __construct() + { + $this->_setup_token = $this->conf(self::O_QC_TOKEN); $this->_summary = self::get_summary(); } @@ -35,15 +40,15 @@ public function __construct() { * * @since 3.0 */ - public function maybe_extract_token() { - $params = $this->cls( 'Cloud' )->parse_qc_redir( [ 'token' ] ); - - if ( isset( $params[ 'token' ] ) ) { - $this->_setup_token = $params[ 'token' ]; - $this->cls( 'Conf' )->update_confs( array( self::O_QC_TOKEN => $this->_setup_token ) ); - unset( $_GET[ 'token' ] ); + public function maybe_extract_token() + { + $params = $this->cls('Cloud')->parse_qc_redir(array('token')); + + if (isset($params['token'])) { + $this->_setup_token = $params['token']; + $this->cls('Conf')->update_confs(array(self::O_QC_TOKEN => $this->_setup_token)); + unset($_GET['token']); } - } /** @@ -52,17 +57,28 @@ public function maybe_extract_token() { * @since 4.7 * @access public */ - public function update_cdn_status() { + public function update_cdn_status() + { + if (empty($_POST['hash'])) { + self::debug('Lack of hash param'); + return self::err('lack_of_param'); + } - if ( !isset( $_POST[ 'success' ] ) || !isset( $_POST[ 'result' ] ) ) { - self::save_summary( array( 'cdn_setup_err' => __( 'Received invalid message from the cloud server. Please submit a ticket.', 'litespeed-cache' ) ) ); - return self::err( 'lack_of_param' ); + if ($_POST['hash'] !== md5(substr($this->conf(self::O_API_KEY), 3, 8))) { + self::debug('token validate failed: token mismatch hash !== ' . $_POST['hash']); + return self::err('callback_fail_hash'); } - if (!$_POST[ 'success' ]) { - self::save_summary( array( 'cdn_setup_err' => $_POST[ 'result' ][ '_msg' ] ) ); - Admin_Display::error( __( 'There was an error during CDN setup: ', 'litespeed-cache' ) . $_POST[ 'result' ][ '_msg' ] ); + + if (!isset($_POST['success']) || !isset($_POST['result'])) { + self::save_summary(array('cdn_setup_err' => __('Received invalid message from the cloud server. Please submit a ticket.', 'litespeed-cache'))); + return self::err('lack_of_param'); + } + if (!$_POST['success'] && !empty($_POST['result']['_msg'])) { + $msg = wp_kses_post($_POST['result']['_msg']); + self::save_summary(array('cdn_setup_err' => $msg)); + Admin_Display::error(__('There was an error during CDN setup: ', 'litespeed-cache') . $msg); } else { - $this->_process_cdn_status($_POST[ 'result' ]); + $this->_process_cdn_status($_POST['result']); } return self::ok(); @@ -74,14 +90,14 @@ public function update_cdn_status() { * @since 4.7 * @access private */ - private function _qc_refresh() { - + private function _qc_refresh() + { $json = $this->cls('Cloud')->req_rest_api('/user/cdn/status'); if (!$json) { return; - } else if (is_string($json)) { - self::save_summary( array( 'cdn_setup_err' => $json ) ); + } elseif (is_string($json)) { + self::save_summary(array('cdn_setup_err' => $json)); return; } @@ -98,38 +114,41 @@ private function _qc_refresh() { * @since 4.7 * @access private */ - private function _process_cdn_status($result) { - - if ( isset($result[ 'nameservers' ] ) ) { + private function _process_cdn_status($result) + { + if (isset($result['nameservers'])) { if (isset($this->_summary['cdn_setup_err'])) { unset($this->_summary['cdn_setup_err']); } - if (isset($result[ 'summary' ])) { - $this->_summary[ 'cdn_dns_summary' ] = $result[ 'summary' ]; + if (isset($result['summary'])) { + $this->_summary['cdn_dns_summary'] = $result['summary']; } - $this->cls( 'Cloud' )->set_linked(); - $this->cls( 'Conf' )->update_confs( array( self::O_QC_NAMESERVERS => $result[ 'nameservers' ], self::O_CDN_QUIC => true ) ); - Admin_Display::succeed( '🎊 ' . __( 'Congratulations, QUIC.cloud successfully set this domain up for the CDN. Please update your nameservers to:', 'litespeed-cache' ) . $result[ 'nameservers' ] ); - } else if ( isset($result[ 'done' ] ) ) { - if ( isset( $this->_summary[ 'cdn_setup_err' ] ) ) { - unset( $this->_summary[ 'cdn_setup_err' ] ); + $this->cls('Cloud')->set_linked(); + $nameservers = esc_html($result['nameservers']); + $this->cls('Conf')->update_confs(array(self::O_QC_NAMESERVERS => $nameservers, self::O_CDN_QUIC => true)); + Admin_Display::succeed( + '🎊 ' . __('Congratulations, QUIC.cloud successfully set this domain up for the CDN. Please update your nameservers to:', 'litespeed-cache') . $nameservers + ); + } elseif (isset($result['done'])) { + if (isset($this->_summary['cdn_setup_err'])) { + unset($this->_summary['cdn_setup_err']); } - if ( isset( $this->_summary[ 'cdn_verify_msg' ] ) ) { - unset( $this->_summary[ 'cdn_verify_msg' ] ); + if (isset($this->_summary['cdn_verify_msg'])) { + unset($this->_summary['cdn_verify_msg']); } - $this->_summary[ 'cdn_setup_done_ts' ] = time(); + $this->_summary['cdn_setup_done_ts'] = time(); $this->_setup_token = ''; - $this->cls( 'Conf' )->update_confs( array( self::O_QC_TOKEN => '', self::O_QC_NAMESERVERS => '' ) ); - } else if ( isset($result[ '_msg' ] ) ) { - $notice = $result[ '_msg' ]; - if ( $this->conf( Base::O_QC_NAMESERVERS )) { - $this->_summary[ 'cdn_verify_msg' ] = $result[ '_msg' ]; - $notice = array('cdn_verify_msg' => $result[ '_msg' ]); + $this->cls('Conf')->update_confs(array(self::O_QC_TOKEN => '', self::O_QC_NAMESERVERS => '')); + } elseif (isset($result['_msg'])) { + $notice = esc_html($result['_msg']); + if ($this->conf(Base::O_QC_NAMESERVERS)) { + $this->_summary['cdn_verify_msg'] = $notice; + $notice = array('cdn_verify_msg' => $notice); } - Admin_Display::succeed( $notice ); + Admin_Display::succeed($notice); } else { - Admin_Display::succeed( __( 'CDN Setup is running.', 'litespeed-cache' ) ); + Admin_Display::succeed(__('CDN Setup is running.', 'litespeed-cache')); } self::save_summary(); } @@ -140,7 +159,8 @@ private function _process_cdn_status($result) { * @since 4.7 * @access private */ - private function _qc_reset($delete) { + private function _qc_reset($delete) + { $data = array( 'site_url' => home_url(), ); @@ -150,58 +170,61 @@ private function _qc_reset($delete) { } if (!empty($this->_setup_token)) { - $data['rest'] = function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : apply_filters( 'rest_url_prefix', 'wp-json' ); + $data['rest'] = function_exists('rest_get_url_prefix') ? rest_get_url_prefix() : apply_filters('rest_url_prefix', 'wp-json'); $json = $this->cls('Cloud')->req_rest_api('/user/cdn/reset', $data); if (!$json) { return; - } else if (is_string($json)) { - self::save_summary( array( 'cdn_setup_err' => $json ) ); + } elseif (is_string($json) && $json != 'unauthorized access to REST API.') { + self::save_summary(array('cdn_setup_err' => $json)); return; } - } else if ( ! isset( $this->_summary[ 'cdn_setup_done_ts' ] ) || ! $this->_summary[ 'cdn_setup_done_ts' ] ) { - Admin_Display::info( __( 'Notice: CDN Setup only reset locally.', 'litespeed-cache')); - } else if ( ! Cloud::get_summary( 'is_linked' ) ) { - - Admin_Display::error( __( 'Cannot delete, site is not linked.', 'litespeed-cache' ) ); + } elseif (!isset($this->_summary['cdn_setup_done_ts']) || !$this->_summary['cdn_setup_done_ts']) { + Admin_Display::info(__('Notice: CDN Setup only reset locally.', 'litespeed-cache')); + } elseif (!Cloud::get_summary('is_linked')) { + Admin_Display::error(__('Cannot delete, site is not linked.', 'litespeed-cache')); return; - } else { - - $json = Cloud::post( Cloud::SVC_D_DEL_CDN_DNS, $data); + $json = Cloud::post(Cloud::SVC_D_DEL_CDN_DNS, $data); if (!is_array($json)) { return; } } - if ( isset( $this->_summary[ 'cdn_setup_ts' ] ) ) { - unset( $this->_summary[ 'cdn_setup_ts' ] ); + if (isset($this->_summary['cdn_setup_ts'])) { + unset($this->_summary['cdn_setup_ts']); } - if ( isset( $this->_summary[ 'cdn_setup_done_ts' ] ) ) { - unset( $this->_summary[ 'cdn_setup_done_ts' ] ); + if (isset($this->_summary['cdn_setup_done_ts'])) { + unset($this->_summary['cdn_setup_done_ts']); } - if ( isset( $this->_summary[ 'cdn_setup_err' ] ) ) { - unset( $this->_summary[ 'cdn_setup_err' ] ); + if (isset($this->_summary['cdn_setup_err'])) { + unset($this->_summary['cdn_setup_err']); } - if ( isset( $this->_summary[ 'cdn_verify_msg' ] ) ) { - unset( $this->_summary[ 'cdn_verify_msg' ] ); + if (isset($this->_summary['cdn_verify_msg'])) { + unset($this->_summary['cdn_verify_msg']); } - if ( isset( $this->_summary[ 'cdn_dns_summary' ] ) ) { - unset( $this->_summary[ 'cdn_dns_summary' ] ); + if (isset($this->_summary['cdn_dns_summary'])) { + unset($this->_summary['cdn_dns_summary']); } - self::save_summary(); + self::save_summary($this->_summary, false, true); $this->_setup_token = ''; - $this->cls( 'Conf' )->update_confs( array( self::O_QC_TOKEN => '', self::O_QC_NAMESERVERS => '', self::O_CDN_QUIC => false ) ); + $this->cls('Conf')->update_confs(array(self::O_QC_TOKEN => '', self::O_QC_NAMESERVERS => '', self::O_CDN_QUIC => false)); $msg = ''; if ($delete) { - $msg = __( 'CDN Setup Token and DNS zone deleted. Note: if my.quic.cloud account deletion is desired, that the account still exists and must be deleted separately.', 'litespeed-cache' ); + $msg = __( + 'CDN Setup Token and DNS zone deleted. Note: if my.quic.cloud account deletion is desired, that the account still exists and must be deleted separately.', + 'litespeed-cache' + ); } else { - $msg = __( 'CDN Setup Token reset. Note: if my.quic.cloud account deletion is desired, that the account still exists and must be deleted separately.', 'litespeed-cache' ); + $msg = __( + 'CDN Setup Token reset. Note: if my.quic.cloud account deletion is desired, that the account still exists and must be deleted separately.', + 'litespeed-cache' + ); } - Admin_Display::succeed( $msg ); + Admin_Display::succeed($msg); return self::ok(); } @@ -210,8 +233,9 @@ private function _qc_reset($delete) { * * @since 4.7 */ - public function has_cdn_setup_token() { - return !empty( $this->_setup_token ); + public function has_cdn_setup_token() + { + return !empty($this->_setup_token); } /** @@ -221,22 +245,23 @@ public function has_cdn_setup_token() { * * @since 4.7 */ - private function _qc_link() { - if ( $this->has_cdn_setup_token() ) { + private function _qc_link() + { + if ($this->has_cdn_setup_token()) { return; } $data = array( - 'site_url' => home_url(), - 'ref' => get_admin_url( null, 'admin.php?page=litespeed-cdn' ), + 'site_url' => home_url(), + 'ref' => get_admin_url(null, 'admin.php?page=litespeed-cdn'), ); - - if ($this->_api_key) { - $data['domain_hash'] = md5( substr( $this->_api_key, 0, 8 ) ); + $api_key = $this->conf(self::O_API_KEY); + if ($api_key) { + $data['domain_hash'] = md5(substr($api_key, 0, 8)); } - wp_redirect( Cloud::CLOUD_SERVER_DASH . '/u/wptoken?data=' . Utility::arr2str( $data ) ); - exit; + wp_redirect(Cloud::CLOUD_SERVER_DASH . '/u/wptoken?data=' . Utility::arr2str($data)); + exit(); } /** @@ -246,21 +271,22 @@ private function _qc_link() { * * @since 4.7 */ - private function _qc_nolink() { - if ( $this->has_cdn_setup_token() ) { + private function _qc_nolink() + { + if ($this->has_cdn_setup_token()) { return; } $data = array( - 'site_url' => home_url(), + 'site_url' => home_url(), ); - $json = Cloud::post( Cloud::SVC_D_SETUP_TOKEN, $data); + $json = Cloud::post(Cloud::SVC_D_SETUP_TOKEN, $data); - if (isset($json[ 'token' ])) { - self::save_summary( array( 'cdn_setup_ts' => time() ) ); - $this->_setup_token = $json[ 'token' ]; - $this->cls( 'Conf' )->update_confs( array( self::O_QC_TOKEN => $this->_setup_token ) ); + if (isset($json['token'])) { + self::save_summary(array('cdn_setup_ts' => time())); + $this->_setup_token = $json['token']; + $this->cls('Conf')->update_confs(array(self::O_QC_TOKEN => $this->_setup_token)); } } @@ -269,29 +295,30 @@ private function _qc_nolink() { * * @since 4.7 */ - private function _qc_run() { - + private function _qc_run() + { $data = array( 'site_url' => home_url(), - 'rest' => function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : apply_filters( 'rest_url_prefix', 'wp-json' ), - 'server_ip' => $this->conf( self::O_SERVER_IP ), + 'rest' => function_exists('rest_get_url_prefix') ? rest_get_url_prefix() : apply_filters('rest_url_prefix', 'wp-json'), + 'server_ip' => $this->conf(self::O_SERVER_IP), ); - if ( $this->_api_key ) { - $data['domain_hash'] = md5( substr( $this->_api_key, 0, 8 ) ); + $api_key = $this->conf(self::O_API_KEY); + if ($api_key) { + $data['domain_hash'] = md5(substr($api_key, 0, 8)); } - $__cloud = $this->cls( 'Cloud' ); + $__cloud = $this->cls('Cloud'); $json = $__cloud->req_rest_api('/user/cdn/', $data); if (!$json) { return; - } else if (is_string($json)) { - self::save_summary( array( 'cdn_setup_err' => $json ) ); + } elseif (is_string($json)) { + self::save_summary(array('cdn_setup_err' => $json)); return; } - $this->_summary[ 'cdn_setup_ts' ] = time(); + $this->_summary['cdn_setup_ts'] = time(); $msg = ''; if (isset($json['info']['messages'])) { @@ -300,30 +327,30 @@ private function _qc_run() { $json = $json['result']; - if ( isset( $this->_summary[ 'cdn_setup_err' ] ) ) { - unset( $this->_summary[ 'cdn_setup_err' ] ); + if (isset($this->_summary['cdn_setup_err'])) { + unset($this->_summary['cdn_setup_err']); } - if ( isset( $this->_summary[ 'cdn_verify_msg' ] ) ) { - unset( $this->_summary[ 'cdn_verify_msg' ] ); + if (isset($this->_summary['cdn_verify_msg'])) { + unset($this->_summary['cdn_verify_msg']); } self::save_summary(); // Save token option - if ( ! empty( $json[ 'token' ] ) ) { - $__cloud->set_keygen_token( $json[ 'token' ] ); + if (!empty($json['token'])) { + $__cloud->set_keygen_token($json['token']); } // This is a ok msg - if ( ! empty( $msg ) ) { - self::debug( '_msg: ' . $msg ); + if (!empty($msg)) { + self::debug('_msg: ' . $msg); - $msg = __( 'Message from QUIC.cloud server', 'litespeed-cache' ) . ': ' . $msg; - Admin_Display::info( $msg ); + $msg = __('Message from QUIC.cloud server', 'litespeed-cache') . ': ' . $msg; + Admin_Display::info($msg); return; } - self::debug( '✅ Successfully start CDN setup.' ); + self::debug('✅ Successfully start CDN setup.'); } /** @@ -331,8 +358,9 @@ private function _qc_run() { * * @since 3.0 */ - public static function ok( $data = array() ) { - $data[ '_res' ] = 'ok'; + public static function ok($data = array()) + { + $data['_res'] = 'ok'; return $data; } @@ -341,8 +369,9 @@ public static function ok( $data = array() ) { * * @since 3.0 */ - public static function err( $code ) { - return array( '_res' => 'err', '_msg' => $code ); + public static function err($code) + { + return array('_res' => 'err', '_msg' => $code); } /** @@ -351,11 +380,11 @@ public static function err( $code ) { * @since 3.0 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { - + switch ($type) { case self::TYPE_LINK: $this->_qc_link(); break; diff --git a/src/cdn.cls.php b/src/cdn.cls.php index a32bc5c18..36543562b 100644 --- a/src/cdn.cls.php +++ b/src/cdn.cls.php @@ -10,9 +10,10 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class CDN extends Root { +class CDN extends Root +{ const BYPASS = 'LITESPEED_BYPASS_CDN'; private $content; @@ -30,108 +31,105 @@ class CDN extends Root { * * @since 1.2.3 */ - public function init() { - Debug2::debug2( '[CDN] init' ); + public function init() + { + Debug2::debug2('[CDN] init'); - if ( defined( self::BYPASS ) ) { - Debug2::debug2( 'CDN bypass' ); + if (defined(self::BYPASS)) { + Debug2::debug2('CDN bypass'); return; } - if ( ! Router::can_cdn() ) { - if ( ! defined( self::BYPASS ) ) { - define( self::BYPASS, true ); + if (!Router::can_cdn()) { + if (!defined(self::BYPASS)) { + define(self::BYPASS, true); } return; } - $this->_cfg_cdn = $this->conf( Base::O_CDN ); - if ( ! $this->_cfg_cdn ) { - if ( ! defined( self::BYPASS ) ) { - define( self::BYPASS, true ); + $this->_cfg_cdn = $this->conf(Base::O_CDN); + if (!$this->_cfg_cdn) { + if (!defined(self::BYPASS)) { + define(self::BYPASS, true); } return; } - $this->_cfg_url_ori = $this->conf( Base::O_CDN_ORI ); + $this->_cfg_url_ori = $this->conf(Base::O_CDN_ORI); // Parse cdn mapping data to array( 'filetype' => 'url' ) - $mapping_to_check = array( - Base::CDN_MAPPING_INC_IMG, - Base::CDN_MAPPING_INC_CSS, - Base::CDN_MAPPING_INC_JS - ); - foreach ( $this->conf( Base::O_CDN_MAPPING ) as $v ) { - if ( ! $v[ Base::CDN_MAPPING_URL ] ) { + $mapping_to_check = array(Base::CDN_MAPPING_INC_IMG, Base::CDN_MAPPING_INC_CSS, Base::CDN_MAPPING_INC_JS); + foreach ($this->conf(Base::O_CDN_MAPPING) as $v) { + if (!$v[Base::CDN_MAPPING_URL]) { continue; } - $this_url = $v[ Base::CDN_MAPPING_URL ]; - $this_host = parse_url( $this_url, PHP_URL_HOST ); + $this_url = $v[Base::CDN_MAPPING_URL]; + $this_host = parse_url($this_url, PHP_URL_HOST); // Check img/css/js - foreach ( $mapping_to_check as $to_check ) { - if ( $v[ $to_check ] ) { - Debug2::debug2( '[CDN] mapping ' . $to_check . ' -> ' . $this_url ); + foreach ($mapping_to_check as $to_check) { + if ($v[$to_check]) { + Debug2::debug2('[CDN] mapping ' . $to_check . ' -> ' . $this_url); // If filetype to url is one to many, make url be an array - $this->_append_cdn_mapping( $to_check, $this_url ); + $this->_append_cdn_mapping($to_check, $this_url); - if ( ! in_array( $this_host, $this->cdn_mapping_hosts ) ) { + if (!in_array($this_host, $this->cdn_mapping_hosts)) { $this->cdn_mapping_hosts[] = $this_host; } } } // Check file types - if ( $v[ Base::CDN_MAPPING_FILETYPE ] ) { - foreach ( $v[ Base::CDN_MAPPING_FILETYPE ] as $v2 ) { - $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_FILETYPE ] = true; + if ($v[Base::CDN_MAPPING_FILETYPE]) { + foreach ($v[Base::CDN_MAPPING_FILETYPE] as $v2) { + $this->_cfg_cdn_mapping[Base::CDN_MAPPING_FILETYPE] = true; // If filetype to url is one to many, make url be an array - $this->_append_cdn_mapping( $v2, $this_url ); + $this->_append_cdn_mapping($v2, $this_url); - if ( ! in_array( $this_host, $this->cdn_mapping_hosts ) ) { + if (!in_array($this_host, $this->cdn_mapping_hosts)) { $this->cdn_mapping_hosts[] = $this_host; } } - Debug2::debug2( '[CDN] mapping ' . implode( ',', $v[ Base::CDN_MAPPING_FILETYPE ] ) . ' -> ' . $this_url ); + Debug2::debug2('[CDN] mapping ' . implode(',', $v[Base::CDN_MAPPING_FILETYPE]) . ' -> ' . $this_url); } } - if ( ! $this->_cfg_url_ori || ! $this->_cfg_cdn_mapping ) { - if ( ! defined( self::BYPASS ) ) { - define( self::BYPASS, true ); + if (!$this->_cfg_url_ori || !$this->_cfg_cdn_mapping) { + if (!defined(self::BYPASS)) { + define(self::BYPASS, true); } return; } - $this->_cfg_ori_dir = $this->conf( Base::O_CDN_ORI_DIR ); + $this->_cfg_ori_dir = $this->conf(Base::O_CDN_ORI_DIR); // In case user customized upload path - if ( defined( 'UPLOADS' ) ) { + if (defined('UPLOADS')) { $this->_cfg_ori_dir[] = UPLOADS; } // Check if need preg_replace - $this->_cfg_url_ori = Utility::wildcard2regex( $this->_cfg_url_ori ); + $this->_cfg_url_ori = Utility::wildcard2regex($this->_cfg_url_ori); - $this->_cfg_cdn_exclude = $this->conf( Base::O_CDN_EXC ); + $this->_cfg_cdn_exclude = $this->conf(Base::O_CDN_EXC); - if ( ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_INC_IMG ] ) ) { + if (!empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_INC_IMG])) { // Hook to srcset - if ( function_exists( 'wp_calculate_image_srcset' ) ) { - add_filter( 'wp_calculate_image_srcset', array( $this, 'srcset' ), 999 ); + if (function_exists('wp_calculate_image_srcset')) { + add_filter('wp_calculate_image_srcset', array($this, 'srcset'), 999); } // Hook to mime icon - add_filter( 'wp_get_attachment_image_src', array( $this, 'attach_img_src' ), 999 ); - add_filter( 'wp_get_attachment_url', array( $this, 'url_img' ), 999 ); + add_filter('wp_get_attachment_image_src', array($this, 'attach_img_src'), 999); + add_filter('wp_get_attachment_url', array($this, 'url_img'), 999); } - if ( ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_INC_CSS ] ) ) { - add_filter( 'style_loader_src', array( $this, 'url_css' ), 999 ); + if (!empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_INC_CSS])) { + add_filter('style_loader_src', array($this, 'url_css'), 999); } - if ( ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_INC_JS ] ) ) { - add_filter( 'script_loader_src', array( $this, 'url_js' ), 999 ); + if (!empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_INC_JS])) { + add_filter('script_loader_src', array($this, 'url_js'), 999); } - add_filter( 'litespeed_buffer_finalize', array( $this, 'finalize' ), 30 ); + add_filter('litespeed_buffer_finalize', array($this, 'finalize'), 30); } /** @@ -140,18 +138,17 @@ public function init() { * @since 2.0 * @access private */ - private function _append_cdn_mapping( $filetype, $url ) { + private function _append_cdn_mapping($filetype, $url) + { // If filetype to url is one to many, make url be an array - if ( empty( $this->_cfg_cdn_mapping[ $filetype ] ) ) { - $this->_cfg_cdn_mapping[ $filetype ] = $url; - } - elseif ( is_array( $this->_cfg_cdn_mapping[ $filetype ] ) ) { + if (empty($this->_cfg_cdn_mapping[$filetype])) { + $this->_cfg_cdn_mapping[$filetype] = $url; + } elseif (is_array($this->_cfg_cdn_mapping[$filetype])) { // Append url to filetype - $this->_cfg_cdn_mapping[ $filetype ][] = $url; - } - else { + $this->_cfg_cdn_mapping[$filetype][] = $url; + } else { // Convert _cfg_cdn_mapping from string to array - $this->_cfg_cdn_mapping[ $filetype ] = array( $this->_cfg_cdn_mapping[ $filetype ], $url ); + $this->_cfg_cdn_mapping[$filetype] = array($this->_cfg_cdn_mapping[$filetype], $url); } } @@ -161,12 +158,13 @@ private function _append_cdn_mapping( $filetype, $url ) { * @since 1.6.2.1 * @return bool true if included in CDN */ - public function inc_type( $type ) { - if ( $type == 'css' && ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_INC_CSS ] ) ) { + public function inc_type($type) + { + if ($type == 'css' && !empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_INC_CSS])) { return true; } - if ( $type == 'js' && ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_INC_JS ] ) ) { + if ($type == 'js' && !empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_INC_JS])) { return true; } @@ -181,7 +179,8 @@ public function inc_type( $type ) { * @access public * @return string The content that is after optimization */ - public function finalize( $content ) { + public function finalize($content) + { $this->content = $content; $this->_finalize(); @@ -194,23 +193,23 @@ public function finalize( $content ) { * @since 1.2.3 * @access private */ - private function _finalize() { - if ( defined( self::BYPASS ) ) { + private function _finalize() + { + if (defined(self::BYPASS)) { return; } - Debug2::debug( 'CDN _finalize' ); + Debug2::debug('CDN _finalize'); // Start replacing img src - if ( ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_INC_IMG ] ) ) { + if (!empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_INC_IMG])) { $this->_replace_img(); $this->_replace_inline_css(); } - if ( ! empty( $this->_cfg_cdn_mapping[ Base::CDN_MAPPING_FILETYPE ] ) ) { + if (!empty($this->_cfg_cdn_mapping[Base::CDN_MAPPING_FILETYPE])) { $this->_replace_file_types(); } - } /** @@ -219,48 +218,48 @@ private function _finalize() { * @since 1.2.3 * @access private */ - private function _replace_file_types() { - $ele_to_check = $this->conf( Base::O_CDN_ATTR ); + private function _replace_file_types() + { + $ele_to_check = $this->conf(Base::O_CDN_ATTR); - foreach ( $ele_to_check as $v ) { - if ( ! $v || strpos( $v, '.' ) === false ) { - Debug2::debug2( '[CDN] replace setting bypassed: no . attribute ' . $v ); + foreach ($ele_to_check as $v) { + if (!$v || strpos($v, '.') === false) { + Debug2::debug2('[CDN] replace setting bypassed: no . attribute ' . $v); continue; } - Debug2::debug2( '[CDN] replace attribute ' . $v ); + Debug2::debug2('[CDN] replace attribute ' . $v); - $v = explode( '.', $v ); - $attr = preg_quote( $v[ 1 ], '#' ); - if ( $v[ 0 ] ) { - $pattern = '#<' . preg_quote( $v[ 0 ], '#' ) . '([^>]+)' . $attr . '=([\'"])(.+)\g{2}#iU'; - } - else { + $v = explode('.', $v); + $attr = preg_quote($v[1], '#'); + if ($v[0]) { + $pattern = '#<' . preg_quote($v[0], '#') . '([^>]+)' . $attr . '=([\'"])(.+)\g{2}#iU'; + } else { $pattern = '# ' . $attr . '=([\'"])(.+)\g{1}#iU'; } - preg_match_all( $pattern, $this->content, $matches ); + preg_match_all($pattern, $this->content, $matches); - if ( empty( $matches[ $v[ 0 ] ? 3 : 2 ] ) ) { + if (empty($matches[$v[0] ? 3 : 2])) { continue; } - foreach ( $matches[ $v[ 0 ] ? 3 : 2 ] as $k2 => $url ) { + foreach ($matches[$v[0] ? 3 : 2] as $k2 => $url) { // Debug2::debug2( '[CDN] check ' . $url ); - $postfix = '.' . pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ); - if ( ! array_key_exists( $postfix, $this->_cfg_cdn_mapping ) ) { + $postfix = '.' . pathinfo((string) parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); + if (!array_key_exists($postfix, $this->_cfg_cdn_mapping)) { // Debug2::debug2( '[CDN] non-existed postfix ' . $postfix ); continue; } - Debug2::debug2( '[CDN] matched file_type ' . $postfix . ' : ' . $url ); + Debug2::debug2('[CDN] matched file_type ' . $postfix . ' : ' . $url); - if( ! $url2 = $this->rewrite( $url, Base::CDN_MAPPING_FILETYPE, $postfix ) ) { + if (!($url2 = $this->rewrite($url, Base::CDN_MAPPING_FILETYPE, $postfix))) { continue; } - $attr = str_replace( $url, $url2, $matches[ 0 ][ $k2 ] ); - $this->content = str_replace( $matches[ 0 ][ $k2 ], $attr, $this->content ); + $attr = str_replace($url, $url2, $matches[0][$k2]); + $this->content = str_replace($matches[0][$k2], $attr, $this->content); } } } @@ -271,25 +270,21 @@ private function _replace_file_types() { * @since 1.2.3 * @access private */ - private function _replace_img() { - preg_match_all( '#]+?)src=([\'"\\\]*)([^\'"\s\\\>]+)([\'"\\\]*)([^>]*)>#i', $this->content, $matches ); - foreach ( $matches[ 3 ] as $k => $url ) { + private function _replace_img() + { + preg_match_all('#]+?)src=([\'"\\\]*)([^\'"\s\\\>]+)([\'"\\\]*)([^>]*)>#i', $this->content, $matches); + foreach ($matches[3] as $k => $url) { // Check if is a DATA-URI - if ( strpos( $url, 'data:image' ) !== false ) { + if (strpos($url, 'data:image') !== false) { continue; } - if ( ! $url2 = $this->rewrite( $url, Base::CDN_MAPPING_INC_IMG ) ) { + if (!($url2 = $this->rewrite($url, Base::CDN_MAPPING_INC_IMG))) { continue; } - $html_snippet = sprintf( - '', - $matches[ 1 ][ $k ], - $matches[ 2 ][ $k ] . $url2 . $matches[ 4 ][ $k ], - $matches[ 5 ][ $k ] - ); - $this->content = str_replace( $matches[ 0 ][ $k ], $html_snippet, $this->content ); + $html_snippet = sprintf('', $matches[1][$k], $matches[2][$k] . $url2 . $matches[4][$k], $matches[5][$k]); + $this->content = str_replace($matches[0][$k], $html_snippet, $this->content); } } @@ -299,8 +294,9 @@ private function _replace_img() { * @since 1.2.3 * @access private */ - private function _replace_inline_css() { - Debug2::debug2( '[CDN] _replace_inline_css', $this->_cfg_cdn_mapping ); + private function _replace_inline_css() + { + Debug2::debug2('[CDN] _replace_inline_css', $this->_cfg_cdn_mapping); /** * Excludes `\` from URL matching @@ -308,26 +304,25 @@ private function _replace_inline_css() { * @see #685485 * @since 3.0 */ - preg_match_all( '/url\((?![\'"]?data)[\'"]?([^\)\'"\\\]+)[\'"]?\)/i', $this->content, $matches ); - foreach ( $matches[ 1 ] as $k => $url ) { - $url = str_replace( array( ' ', '\t', '\n', '\r', '\0', '\x0B', '"', "'", '"', ''' ), '', $url ); + preg_match_all('/url\((?![\'"]?data)[\'"]?([^\)\'"\\\]+)[\'"]?\)/i', $this->content, $matches); + foreach ($matches[1] as $k => $url) { + $url = str_replace(array(' ', '\t', '\n', '\r', '\0', '\x0B', '"', "'", '"', '''), '', $url); // Parse file postfix - $postfix = '.' . pathinfo( parse_url( $url, PHP_URL_PATH ), PATHINFO_EXTENSION ); - if ( array_key_exists( $postfix, $this->_cfg_cdn_mapping ) ) { - Debug2::debug2( '[CDN] matched file_type ' . $postfix . ' : ' . $url ); - if( ! $url2 = $this->rewrite( $url, Base::CDN_MAPPING_FILETYPE, $postfix ) ) { + $postfix = '.' . pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); + if (array_key_exists($postfix, $this->_cfg_cdn_mapping)) { + Debug2::debug2('[CDN] matched file_type ' . $postfix . ' : ' . $url); + if (!($url2 = $this->rewrite($url, Base::CDN_MAPPING_FILETYPE, $postfix))) { continue; } - } - else { - if ( ! $url2 = $this->rewrite( $url, Base::CDN_MAPPING_INC_IMG ) ) { + } else { + if (!($url2 = $this->rewrite($url, Base::CDN_MAPPING_INC_IMG))) { continue; } } - $attr = str_replace( $matches[ 1 ][ $k ], $url2, $matches[ 0 ][ $k ] ); - $this->content = str_replace( $matches[ 0 ][ $k ], $attr, $this->content ); + $attr = str_replace($matches[1][$k], $url2, $matches[0][$k]); + $this->content = str_replace($matches[0][$k], $attr, $this->content); } } @@ -340,9 +335,10 @@ private function _replace_inline_css() { * @param array $img The URL of the attachment image src, the width, the height * @return array */ - public function attach_img_src( $img ) { - if ( $img && $url = $this->rewrite( $img[ 0 ], Base::CDN_MAPPING_INC_IMG ) ) { - $img[ 0 ] = $url; + public function attach_img_src($img) + { + if ($img && ($url = $this->rewrite($img[0], Base::CDN_MAPPING_INC_IMG))) { + $img[0] = $url; } return $img; } @@ -353,8 +349,9 @@ public function attach_img_src( $img ) { * @since 1.7 * @access public */ - public function url_img( $url ) { - if ( $url && $url2 = $this->rewrite( $url, Base::CDN_MAPPING_INC_IMG ) ) { + public function url_img($url) + { + if ($url && ($url2 = $this->rewrite($url, Base::CDN_MAPPING_INC_IMG))) { $url = $url2; } return $url; @@ -366,8 +363,9 @@ public function url_img( $url ) { * @since 1.7 * @access public */ - public function url_css( $url ) { - if ( $url && $url2 = $this->rewrite( $url, Base::CDN_MAPPING_INC_CSS ) ) { + public function url_css($url) + { + if ($url && ($url2 = $this->rewrite($url, Base::CDN_MAPPING_INC_CSS))) { $url = $url2; } return $url; @@ -379,8 +377,9 @@ public function url_css( $url ) { * @since 1.7 * @access public */ - public function url_js( $url ) { - if ( $url && $url2 = $this->rewrite( $url, Base::CDN_MAPPING_INC_JS ) ) { + public function url_js($url) + { + if ($url && ($url2 = $this->rewrite($url, Base::CDN_MAPPING_INC_JS))) { $url = $url2; } return $url; @@ -395,13 +394,14 @@ public function url_js( $url ) { * @param array $srcs * @return array */ - public function srcset( $srcs ) { - if ( $srcs ) { - foreach ( $srcs as $w => $data ) { - if( ! $url = $this->rewrite( $data[ 'url' ], Base::CDN_MAPPING_INC_IMG ) ) { + public function srcset($srcs) + { + if ($srcs) { + foreach ($srcs as $w => $data) { + if (!($url = $this->rewrite($data['url'], Base::CDN_MAPPING_INC_IMG))) { continue; } - $srcs[ $w ][ 'url' ] = $url; + $srcs[$w]['url'] = $url; } } return $srcs; @@ -415,76 +415,75 @@ public function srcset( $srcs ) { * @param string $url * @return string Replaced URL */ - public function rewrite( $url, $mapping_kind, $postfix = false ) { - Debug2::debug2( '[CDN] rewrite ' . $url ); - $url_parsed = parse_url( $url ); + public function rewrite($url, $mapping_kind, $postfix = false) + { + Debug2::debug2('[CDN] rewrite ' . $url); + $url_parsed = parse_url($url); - if ( empty( $url_parsed[ 'path' ] ) ) { - Debug2::debug2( '[CDN] -rewrite bypassed: no path' ); + if (empty($url_parsed['path'])) { + Debug2::debug2('[CDN] -rewrite bypassed: no path'); return false; } // Only images under wp-cotnent/wp-includes can be replaced - $is_internal_folder = Utility::str_hit_array( $url_parsed[ 'path' ], $this->_cfg_ori_dir ); - if ( ! $is_internal_folder ) { - Debug2::debug2( '[CDN] -rewrite failed: path not match: ' . LSCWP_CONTENT_FOLDER ); + $is_internal_folder = Utility::str_hit_array($url_parsed['path'], $this->_cfg_ori_dir); + if (!$is_internal_folder) { + Debug2::debug2('[CDN] -rewrite failed: path not match: ' . LSCWP_CONTENT_FOLDER); return false; } // Check if is external url - if ( ! empty( $url_parsed[ 'host' ] ) ) { - if ( ! Utility::internal( $url_parsed[ 'host' ] ) && ! $this->_is_ori_url( $url ) ) { - Debug2::debug2( '[CDN] -rewrite failed: host not internal' ); + if (!empty($url_parsed['host'])) { + if (!Utility::internal($url_parsed['host']) && !$this->_is_ori_url($url)) { + Debug2::debug2('[CDN] -rewrite failed: host not internal'); return false; } } - $exclude = Utility::str_hit_array( $url, $this->_cfg_cdn_exclude ); - if ( $exclude ) { - Debug2::debug2( '[CDN] -abort excludes ' . $exclude ); + $exclude = Utility::str_hit_array($url, $this->_cfg_cdn_exclude); + if ($exclude) { + Debug2::debug2('[CDN] -abort excludes ' . $exclude); return false; } // Fill full url before replacement - if ( empty( $url_parsed[ 'host' ] ) ) { - $url = Utility::uri2url( $url ); - Debug2::debug2( '[CDN] -fill before rewritten: ' . $url ); + if (empty($url_parsed['host'])) { + $url = Utility::uri2url($url); + Debug2::debug2('[CDN] -fill before rewritten: ' . $url); - $url_parsed = parse_url( $url ); + $url_parsed = parse_url($url); } - $scheme = ! empty( $url_parsed[ 'scheme' ] ) ? $url_parsed[ 'scheme' ] . ':' : ''; - if ( $scheme ) { + $scheme = !empty($url_parsed['scheme']) ? $url_parsed['scheme'] . ':' : ''; + if ($scheme) { // Debug2::debug2( '[CDN] -scheme from url: ' . $scheme ); } // Find the mapping url to be replaced to - if ( empty( $this->_cfg_cdn_mapping[ $mapping_kind ] ) ) { + if (empty($this->_cfg_cdn_mapping[$mapping_kind])) { return false; } - if ( $mapping_kind !== Base::CDN_MAPPING_FILETYPE ) { - $final_url = $this->_cfg_cdn_mapping[ $mapping_kind ]; - } - else { + if ($mapping_kind !== Base::CDN_MAPPING_FILETYPE) { + $final_url = $this->_cfg_cdn_mapping[$mapping_kind]; + } else { // select from file type - $final_url = $this->_cfg_cdn_mapping[ $postfix ]; + $final_url = $this->_cfg_cdn_mapping[$postfix]; } // If filetype to url is one to many, need to random one - if ( is_array( $final_url ) ) { - $final_url = $final_url[ mt_rand( 0, count( $final_url ) - 1 ) ]; + if (is_array($final_url)) { + $final_url = $final_url[mt_rand(0, count($final_url) - 1)]; } // Now lets replace CDN url - foreach ( $this->_cfg_url_ori as $v ) { - if ( strpos( $v, '*' ) !== false ) { - $url = preg_replace( '#' . $scheme . $v . '#iU', $final_url, $url ); - } - else { - $url = str_replace( $scheme . $v, $final_url, $url ); + foreach ($this->_cfg_url_ori as $v) { + if (strpos($v, '*') !== false) { + $url = preg_replace('#' . $scheme . $v . '#iU', $final_url, $url); + } else { + $url = str_replace($scheme . $v, $final_url, $url); } } - Debug2::debug2( '[CDN] -rewritten: ' . $url ); + Debug2::debug2('[CDN] -rewritten: ' . $url); return $url; } @@ -495,20 +494,20 @@ public function rewrite( $url, $mapping_kind, $postfix = false ) { * @since 2.1 * @access private */ - private function _is_ori_url( $url ) { - $url_parsed = parse_url( $url ); + private function _is_ori_url($url) + { + $url_parsed = parse_url($url); - $scheme = ! empty( $url_parsed[ 'scheme' ] ) ? $url_parsed[ 'scheme' ] . ':' : ''; + $scheme = !empty($url_parsed['scheme']) ? $url_parsed['scheme'] . ':' : ''; - foreach ( $this->_cfg_url_ori as $v ) { + foreach ($this->_cfg_url_ori as $v) { $needle = $scheme . $v; - if ( strpos( $v, '*' ) !== false ) { - if( preg_match( '#' . $needle . '#iU', $url ) ) { + if (strpos($v, '*') !== false) { + if (preg_match('#' . $needle . '#iU', $url)) { return true; } - } - else { - if ( strpos( $url, $needle ) === 0 ) { + } else { + if (strpos($url, $needle) === 0) { return true; } } @@ -523,14 +522,14 @@ private function _is_ori_url( $url ) { * @since 1.2.3 * */ - public static function internal( $host ) { - if ( defined( self::BYPASS ) ) { + public static function internal($host) + { + if (defined(self::BYPASS)) { return false; } $instance = self::cls(); - return in_array( $host, $instance->cdn_mapping_hosts );// todo: can add $this->_is_ori_url() check in future + return in_array($host, $instance->cdn_mapping_hosts); // todo: can add $this->_is_ori_url() check in future } - } diff --git a/src/cdn/cloudflare.cls.php b/src/cdn/cloudflare.cls.php index 2282328be..527f7df06 100644 --- a/src/cdn/cloudflare.cls.php +++ b/src/cdn/cloudflare.cls.php @@ -16,9 +16,10 @@ use LiteSpeed\Admin; use LiteSpeed\Admin_Display; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Cloudflare extends Base { +class Cloudflare extends Base +{ const TYPE_PURGE_ALL = 'purge_all'; const TYPE_GET_DEVMODE = 'get_devmode'; const TYPE_SET_DEVMODE_ON = 'set_devmode_on'; @@ -32,24 +33,23 @@ class Cloudflare extends Base { * @since 3.0 * @access public */ - public function try_refresh_zone() { - if ( ! $this->conf( self::O_CDN_CLOUDFLARE ) ) { + public function try_refresh_zone() + { + if (!$this->conf(self::O_CDN_CLOUDFLARE)) { return; } $zone = $this->_fetch_zone(); - if ( $zone ) { - $this->cls( 'Conf' )->update( self::O_CDN_CLOUDFLARE_NAME, $zone[ 'name' ] ); + if ($zone) { + $this->cls('Conf')->update(self::O_CDN_CLOUDFLARE_NAME, $zone['name']); - $this->cls( 'Conf' )->update( self::O_CDN_CLOUDFLARE_ZONE, $zone[ 'id' ] ); + $this->cls('Conf')->update(self::O_CDN_CLOUDFLARE_ZONE, $zone['id']); - Debug2::debug( "[Cloudflare] Get zone successfully \t\t[ID] $zone[id]" ); + Debug2::debug("[Cloudflare] Get zone successfully \t\t[ID] $zone[id]"); + } else { + $this->cls('Conf')->update(self::O_CDN_CLOUDFLARE_ZONE, ''); + Debug2::debug('[Cloudflare] ❌ Get zone failed, clean zone'); } - else { - $this->cls( 'Conf' )->update( self::O_CDN_CLOUDFLARE_ZONE, '' ); - Debug2::debug( '[Cloudflare] ❌ Get zone failed, clean zone' ); - } - } /** @@ -58,29 +58,29 @@ public function try_refresh_zone() { * @since 1.7.2 * @access private */ - private function _get_devmode( $show_msg = true ) { - Debug2::debug( '[Cloudflare] _get_devmode' ); + private function _get_devmode($show_msg = true) + { + Debug2::debug('[Cloudflare] _get_devmode'); $zone = $this->_zone(); - if ( ! $zone ) { + if (!$zone) { return; } $url = 'https://api.cloudflare.com/client/v4/zones/' . $zone . '/settings/development_mode'; - $res = $this->_cloudflare_call( $url, 'GET', false, $show_msg ); + $res = $this->_cloudflare_call($url, 'GET', false, $show_msg); - if ( ! $res ) { + if (!$res) { return; } - Debug2::debug( '[Cloudflare] _get_devmode result ', $res ); + Debug2::debug('[Cloudflare] _get_devmode result ', $res); - $curr_status = self::get_option( self::ITEM_STATUS, array() ); - $curr_status[ 'devmode' ] = $res[ 'value' ]; - $curr_status[ 'devmode_expired' ] = $res[ 'time_remaining' ] + time(); + $curr_status = self::get_option(self::ITEM_STATUS, array()); + $curr_status['devmode'] = $res['value']; + $curr_status['devmode_expired'] = $res['time_remaining'] + time(); // update status - self::update_option( self::ITEM_STATUS, $curr_status ); - + self::update_option(self::ITEM_STATUS, $curr_status); } /** @@ -89,30 +89,30 @@ private function _get_devmode( $show_msg = true ) { * @since 1.7.2 * @access private */ - private function _set_devmode( $type ) { - Debug2::debug( '[Cloudflare] _set_devmode' ); + private function _set_devmode($type) + { + Debug2::debug('[Cloudflare] _set_devmode'); $zone = $this->_zone(); - if ( ! $zone ) { + if (!$zone) { return; } $url = 'https://api.cloudflare.com/client/v4/zones/' . $zone . '/settings/development_mode'; $new_val = $type == self::TYPE_SET_DEVMODE_ON ? 'on' : 'off'; - $data = array( 'value' => $new_val ); - $res = $this->_cloudflare_call( $url, 'PATCH', $data ); + $data = array('value' => $new_val); + $res = $this->_cloudflare_call($url, 'PATCH', $data); - if ( ! $res ) { + if (!$res) { return; } - $res = $this->_get_devmode( false ); + $res = $this->_get_devmode(false); - if ( $res ) { - $msg = sprintf( __( 'Notified Cloudflare to set development mode to %s successfully.', 'litespeed-cache' ), strtoupper( $new_val ) ); - Admin_Display::succeed( $msg ); + if ($res) { + $msg = sprintf(__('Notified Cloudflare to set development mode to %s successfully.', 'litespeed-cache'), strtoupper($new_val)); + Admin_Display::succeed($msg); } - } /** @@ -121,29 +121,30 @@ private function _set_devmode( $type ) { * @since 1.7.2 * @access private */ - private function _purge_all() { - Debug2::debug( '[Cloudflare] _purge_all' ); - - $cf_on = $this->conf( self::O_CDN_CLOUDFLARE ); - if ( ! $cf_on ) { - $msg = __( 'Cloudflare API is set to off.', 'litespeed-cache' ); - Admin_Display::error( $msg ); + private function _purge_all() + { + Debug2::debug('[Cloudflare] _purge_all'); + + $cf_on = $this->conf(self::O_CDN_CLOUDFLARE); + if (!$cf_on) { + $msg = __('Cloudflare API is set to off.', 'litespeed-cache'); + Admin_Display::error($msg); return; } $zone = $this->_zone(); - if ( ! $zone ) { + if (!$zone) { return; } $url = 'https://api.cloudflare.com/client/v4/zones/' . $zone . '/purge_cache'; - $data = array( 'purge_everything' => true ); + $data = array('purge_everything' => true); - $res = $this->_cloudflare_call( $url, 'DELETE', $data ); + $res = $this->_cloudflare_call($url, 'DELETE', $data); - if ( $res ) { - $msg = __( 'Notified Cloudflare to purge all successfully.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + if ($res) { + $msg = __('Notified Cloudflare to purge all successfully.', 'litespeed-cache'); + Admin_Display::succeed($msg); } } @@ -153,11 +154,12 @@ private function _purge_all() { * @since 1.7.2 * @access private */ - private function _zone() { - $zone = $this->conf( self::O_CDN_CLOUDFLARE_ZONE ); - if ( ! $zone ) { - $msg = __( 'No available Cloudflare zone', 'litespeed-cache' ); - Admin_Display::error( $msg ); + private function _zone() + { + $zone = $this->conf(self::O_CDN_CLOUDFLARE_ZONE); + if (!$zone) { + $msg = __('No available Cloudflare zone', 'litespeed-cache'); + Admin_Display::error($msg); return false; } @@ -170,43 +172,44 @@ private function _zone() { * @since 1.7.2 * @access private */ - private function _fetch_zone() { - $kw = $this->conf( self::O_CDN_CLOUDFLARE_NAME ); + private function _fetch_zone() + { + $kw = $this->conf(self::O_CDN_CLOUDFLARE_NAME); $url = 'https://api.cloudflare.com/client/v4/zones?status=active&match=all'; // Try exact match first - if ( $kw && strpos( $kw, '.' ) ) { - $zones = $this->_cloudflare_call( $url . '&name=' . $kw, 'GET', false, false ); - if ( $zones ) { - Debug2::debug( '[Cloudflare] fetch_zone exact matched' ); - return $zones[ 0 ]; + if ($kw && strpos($kw, '.')) { + $zones = $this->_cloudflare_call($url . '&name=' . $kw, 'GET', false, false); + if ($zones) { + Debug2::debug('[Cloudflare] fetch_zone exact matched'); + return $zones[0]; } } // Can't find, try to get default one - $zones = $this->_cloudflare_call( $url, 'GET', false, false ); + $zones = $this->_cloudflare_call($url, 'GET', false, false); - if ( ! $zones ) { - Debug2::debug( '[Cloudflare] fetch_zone no zone' ); + if (!$zones) { + Debug2::debug('[Cloudflare] fetch_zone no zone'); return false; } - if ( ! $kw ) { - Debug2::debug( '[Cloudflare] fetch_zone no set name, use first one by default' ); - return $zones[ 0 ]; + if (!$kw) { + Debug2::debug('[Cloudflare] fetch_zone no set name, use first one by default'); + return $zones[0]; } - foreach ( $zones as $v ) { - if ( strpos( $v[ 'name' ], $kw ) !== false ) { - Debug2::debug( '[Cloudflare] fetch_zone matched ' . $kw . ' [name] ' . $v[ 'name' ] ); + foreach ($zones as $v) { + if (strpos($v['name'], $kw) !== false) { + Debug2::debug('[Cloudflare] fetch_zone matched ' . $kw . ' [name] ' . $v['name']); return $v; } } // Can't match current name, return default one - Debug2::debug( '[Cloudflare] fetch_zone failed match name, use first one by default' ); - return $zones[ 0 ]; + Debug2::debug('[Cloudflare] fetch_zone failed match name, use first one by default'); + return $zones[0]; } /** @@ -215,20 +218,20 @@ private function _fetch_zone() { * @since 1.7.2 * @access private */ - private function _cloudflare_call( $url, $method = 'GET', $data = false, $show_msg = true ) { - Debug2::debug( "[Cloudflare] _cloudflare_call \t\t[URL] $url" ); + private function _cloudflare_call($url, $method = 'GET', $data = false, $show_msg = true) + { + Debug2::debug("[Cloudflare] _cloudflare_call \t\t[URL] $url"); - if ( 40 == strlen($this->conf( self::O_CDN_CLOUDFLARE_KEY ))){ + if (40 == strlen($this->conf(self::O_CDN_CLOUDFLARE_KEY))) { $headers = array( 'Content-Type' => 'application/json', - 'Authorization' => 'Bearer ' . $this->conf( self::O_CDN_CLOUDFLARE_KEY ), + 'Authorization' => 'Bearer ' . $this->conf(self::O_CDN_CLOUDFLARE_KEY), ); - } - else { + } else { $headers = array( 'Content-Type' => 'application/json', - 'X-Auth-Email' => $this->conf( self::O_CDN_CLOUDFLARE_EMAIL ), - 'X-Auth-Key' => $this->conf( self::O_CDN_CLOUDFLARE_KEY ), + 'X-Auth-Email' => $this->conf(self::O_CDN_CLOUDFLARE_EMAIL), + 'X-Auth-Key' => $this->conf(self::O_CDN_CLOUDFLARE_KEY), ); } @@ -237,40 +240,40 @@ private function _cloudflare_call( $url, $method = 'GET', $data = false, $show_m 'headers' => $headers, ); - if ( $data ) { - if ( is_array( $data ) ) { - $data = json_encode( $data ); + if ($data) { + if (is_array($data)) { + $data = json_encode($data); } - $wp_args[ 'body' ] = $data; + $wp_args['body'] = $data; } - $resp = wp_remote_request( $url, $wp_args ); - if ( is_wp_error( $resp ) ) { - Debug2::debug( '[Cloudflare] error in response' ); - if ( $show_msg ) { - $msg = __( 'Failed to communicate with Cloudflare', 'litespeed-cache' ); - Admin_Display::error( $msg ); + $resp = wp_remote_request($url, $wp_args); + if (is_wp_error($resp)) { + Debug2::debug('[Cloudflare] error in response'); + if ($show_msg) { + $msg = __('Failed to communicate with Cloudflare', 'litespeed-cache'); + Admin_Display::error($msg); } return false; } - $result = wp_remote_retrieve_body( $resp ); + $result = wp_remote_retrieve_body($resp); - $json = json_decode( $result, true ); + $json = json_decode($result, true); - if ( $json && $json[ 'success' ] && $json[ 'result' ] ) { - Debug2::debug( "[Cloudflare] _cloudflare_call called successfully" ); - if ( $show_msg ) { - $msg = __( 'Communicated with Cloudflare successfully.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + if ($json && $json['success'] && $json['result']) { + Debug2::debug('[Cloudflare] _cloudflare_call called successfully'); + if ($show_msg) { + $msg = __('Communicated with Cloudflare successfully.', 'litespeed-cache'); + Admin_Display::succeed($msg); } - return $json[ 'result' ]; + return $json['result']; } - Debug2::debug( "[Cloudflare] _cloudflare_call called failed: $result" ); - if ( $show_msg ) { - $msg = __( 'Failed to communicate with Cloudflare', 'litespeed-cache' ); - Admin_Display::error( $msg ); + Debug2::debug("[Cloudflare] _cloudflare_call called failed: $result"); + if ($show_msg) { + $msg = __('Failed to communicate with Cloudflare', 'litespeed-cache'); + Admin_Display::error($msg); } return false; @@ -282,21 +285,22 @@ private function _cloudflare_call( $url, $method = 'GET', $data = false, $show_m * @since 1.7.2 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { - case self::TYPE_PURGE_ALL : + switch ($type) { + case self::TYPE_PURGE_ALL: $this->_purge_all(); break; - case self::TYPE_GET_DEVMODE : + case self::TYPE_GET_DEVMODE: $this->_get_devmode(); break; - case self::TYPE_SET_DEVMODE_ON : - case self::TYPE_SET_DEVMODE_OFF : - $this->_set_devmode( $type ); + case self::TYPE_SET_DEVMODE_ON: + case self::TYPE_SET_DEVMODE_OFF: + $this->_set_devmode($type); break; default: @@ -305,5 +309,4 @@ public function handler() { Admin::redirect(); } - } diff --git a/src/cdn/quic.cls.php b/src/cdn/quic.cls.php index 8bb14c3fc..58b2d8236 100644 --- a/src/cdn/quic.cls.php +++ b/src/cdn/quic.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed\CDN; use LiteSpeed\Cloud; use LiteSpeed\Base; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Quic extends Base { +class Quic extends Base +{ const LOG_TAG = '☁️'; const TYPE_REG = 'reg'; protected $_summary; - public function __construct() { + public function __construct() + { $this->_summary = self::get_summary(); } @@ -29,49 +33,61 @@ public function __construct() { * * @access public */ - public static function try_sync_config() { + public static function try_sync_config() + { self::cls()->try_sync_conf(); } - public function try_sync_conf() { + public function try_sync_conf($force = false) + { $options = $this->get_options(); - if ( ! $options[ self::O_CDN_QUIC ] ) { + if (!$options[self::O_CDN_QUIC]) { + if (!empty($this->_summary['conf_md5'])) { + self::save_summary(array('conf_md5' => '')); + } return false; } // Security: Remove cf key in report - $secure_fields = array( - self::O_CDN_CLOUDFLARE_KEY, - self::O_OBJECT_PSWD, - ); - foreach ( $secure_fields as $v ) { - if ( ! empty( $options[ $v ] ) ) { - $options[ $v ] = str_repeat( '*', strlen( $options[ $v ] ) ); + $secure_fields = array(self::O_CDN_CLOUDFLARE_KEY, self::O_OBJECT_PSWD); + foreach ($secure_fields as $v) { + if (!empty($options[$v])) { + $options[$v] = str_repeat('*', strlen($options[$v])); + } + } + unset($options[self::O_MEDIA_LQIP_EXC]); + + // Remove overflow multi lines fields + foreach ($options as $k => $v) { + if (is_array($v) && count($v) > 30) { + $v = array_slice($v, 0, 30); + $options[$k] = $v; } } - unset( $options[ self::O_MEDIA_LQIP_EXC ] ); // Rest url - $options[ '_rest' ] = function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : apply_filters( 'rest_url_prefix', 'wp-json' ); - $options[ '_home_url' ] = home_url( '/' ); + $options['_rest'] = function_exists('rest_get_url_prefix') ? rest_get_url_prefix() : apply_filters('rest_url_prefix', 'wp-json'); + $options['_home_url'] = home_url('/'); // Add server env vars - $options[ '_server' ] = $this->server_vars(); + $options['_server'] = $this->server_vars(); // Append hooks - $options[ '_tp_cookies' ] = apply_filters( 'litespeed_vary_cookies', array() ); + $options['_tp_cookies'] = apply_filters('litespeed_vary_cookies', array()); - $conf_md5 = md5( json_encode( $options ) ); - if ( ! empty( $this->_summary[ 'conf_md5' ] ) && $conf_md5 == $this->_summary[ 'conf_md5' ] ) { - self::debug( 'Bypass sync conf to QC due to same md5', $conf_md5 ); - return; + $conf_md5 = md5(json_encode($options)); + if (!empty($this->_summary['conf_md5']) && $conf_md5 == $this->_summary['conf_md5']) { + if (!$force) { + self::debug('Bypass sync conf to QC due to same md5', $conf_md5); + return; + } + self::debug('!!!Force sync conf even same md5'); } - self::save_summary( array( 'conf_md5' => $conf_md5 ) ); + self::save_summary(array('conf_md5' => $conf_md5)); self::debug('sync conf to QC', $options); - Cloud::post( Cloud::SVC_D_SYNC_CONF, $options ); + Cloud::post(Cloud::SVC_D_SYNC_CONF, $options); } - -} \ No newline at end of file +} diff --git a/src/cloud.cls.php b/src/cloud.cls.php index 379ef0aa3..836026f99 100644 --- a/src/cloud.cls.php +++ b/src/cloud.cls.php @@ -1,50 +1,54 @@ _api_key = $this->conf( self::O_API_KEY ); - $this->_setup_token = $this->conf( self::O_QC_TOKEN ); + public function __construct() + { + $this->_setup_token = $this->conf(self::O_QC_TOKEN); $this->_summary = self::get_summary(); } + /** + * Get api key from conf + * @since 5.3 + */ + private function _api_key() + { + return $this->conf(self::O_API_KEY); + } + /** * Show latest commit version always if is on dev * * @since 3.0 */ - public function check_dev_version() { - if ( ! preg_match( '/[^\d\.]/', Core::VER ) ) { + public function check_dev_version() + { + if (!preg_match('/[^\d\.]/', Core::VER)) { return; } - $last_check = empty( $this->_summary[ 'last_request.' . self::API_VER ] ) ? 0 : $this->_summary[ 'last_request.' . self::API_VER ] ; + $last_check = empty($this->_summary['last_request.' . self::API_VER]) ? 0 : $this->_summary['last_request.' . self::API_VER]; - if ( time() - $last_check > 86400 ) { - $auto_v = self::version_check( 'dev' ); - if ( ! empty( $auto_v[ 'dev' ] ) ) { - self::save_summary( array( 'version.dev' => $auto_v[ 'dev' ] ) ); + if (time() - $last_check > 86400) { + $auto_v = self::version_check('dev'); + if (!empty($auto_v['dev'])) { + self::save_summary(array('version.dev' => $auto_v['dev'])); } } - if ( empty( $this->_summary[ 'version.dev' ] ) ) { + if (empty($this->_summary['version.dev'])) { return; } - self::debug( 'Latest dev version ' . $this->_summary[ 'version.dev' ] ); + self::debug('Latest dev version ' . $this->_summary['version.dev']); - if ( version_compare( $this->_summary[ 'version.dev' ], Core::VER, '<=' ) ) { + if (version_compare($this->_summary['version.dev'], Core::VER, '<=')) { return; } @@ -158,15 +159,16 @@ public function check_dev_version() { * @since 2.9 * @access public */ - public static function version_check( $src = false ) { + public static function version_check($src = false) + { $req_data = array( - 'v' => defined( 'LSCWP_CUR_V' ) ? LSCWP_CUR_V : '', - 'src' => $src, + 'v' => defined('LSCWP_CUR_V') ? LSCWP_CUR_V : '', + 'src' => $src, ); - if ( defined( 'LITESPEED_ERR' ) ) { - $req_data[ 'err' ] = base64_encode( ! is_string( LITESPEED_ERR ) ? json_encode( LITESPEED_ERR ) : LITESPEED_ERR ) ; + if (defined('LITESPEED_ERR')) { + $req_data['err'] = base64_encode(!is_string(LITESPEED_ERR) ? json_encode(LITESPEED_ERR) : LITESPEED_ERR); } - $data = self::get( self::API_VER, $req_data ); + $data = self::get(self::API_VER, $req_data); return $data; } @@ -176,18 +178,19 @@ public static function version_check( $src = false ) { * * @since 3.0 */ - public function news() { + public function news() + { $this->_update_news(); - if ( empty( $this->_summary[ 'news.new' ] ) ) { + if (empty($this->_summary['news.new'])) { return; } - if ( ! empty( $this->_summary[ 'news.plugin' ] ) && Activation::cls()->dash_notifier_is_plugin_active( $this->_summary[ 'news.plugin' ] ) ) { + if (!empty($this->_summary['news.plugin']) && Activation::cls()->dash_notifier_is_plugin_active($this->_summary['news.plugin'])) { return; } - require_once LSCWP_DIR . 'tpl/banner/cloud_news.tpl.php' ; + require_once LSCWP_DIR . 'tpl/banner/cloud_news.tpl.php'; } /** @@ -195,34 +198,35 @@ public function news() { * * @since 2.9.9.1 */ - private function _update_news() { - if ( ! empty( $this->_summary[ 'news.utime' ] ) && time() - $this->_summary[ 'news.utime' ] < 86400 * 7 ) { + private function _update_news() + { + if (!empty($this->_summary['news.utime']) && time() - $this->_summary['news.utime'] < 86400 * 7) { return; } - self::save_summary( array( 'news.utime' => time() ) ); + self::save_summary(array('news.utime' => time())); - $data = self::get( self::API_NEWS ); - if ( empty( $data[ 'id' ] ) ) { + $data = self::get(self::API_NEWS); + if (empty($data['id'])) { return; } // Save news - if ( ! empty( $this->_summary[ 'news.id' ] ) && $this->_summary[ 'news.id' ] == $data[ 'id' ] ) { + if (!empty($this->_summary['news.id']) && $this->_summary['news.id'] == $data['id']) { return; } - $this->_summary[ 'news.id' ] = $data[ 'id' ]; - $this->_summary[ 'news.plugin' ] = ! empty( $data[ 'plugin' ] ) ? $data[ 'plugin' ] : ''; - $this->_summary[ 'news.title' ] = ! empty( $data[ 'title' ] ) ? $data[ 'title' ] : ''; - $this->_summary[ 'news.content' ] = ! empty( $data[ 'content' ] ) ? $data[ 'content' ] : ''; - $this->_summary[ 'news.zip' ] = ! empty( $data[ 'zip' ] ) ? $data[ 'zip' ] : ''; - $this->_summary[ 'news.new' ] = 1; + $this->_summary['news.id'] = $data['id']; + $this->_summary['news.plugin'] = !empty($data['plugin']) ? $data['plugin'] : ''; + $this->_summary['news.title'] = !empty($data['title']) ? $data['title'] : ''; + $this->_summary['news.content'] = !empty($data['content']) ? $data['content'] : ''; + $this->_summary['news.zip'] = !empty($data['zip']) ? $data['zip'] : ''; + $this->_summary['news.new'] = 1; - if ( $this->_summary[ 'news.plugin' ] ) { - $plugin_info = Activation::cls()->dash_notifier_get_plugin_info( $this->_summary[ 'news.plugin' ] ); - if ( $plugin_info && ! empty( $plugin_info->name ) ) { - $this->_summary[ 'news.plugin_name' ] = $plugin_info->name; + if ($this->_summary['news.plugin']) { + $plugin_info = Activation::cls()->dash_notifier_get_plugin_info($this->_summary['news.plugin']); + if ($plugin_info && !empty($plugin_info->name)) { + $this->_summary['news.plugin_name'] = $plugin_info->name; } } @@ -234,8 +238,9 @@ private function _update_news() { * * @since 4.0 */ - public function has_pkg( $service, $pkg ) { - if ( ! empty( $this->_summary[ 'usage.' . $service ][ 'pkgs' ] ) && $this->_summary[ 'usage.' . $service ][ 'pkgs' ] & $pkg ) { + public function has_pkg($service, $pkg) + { + if (!empty($this->_summary['usage.' . $service]['pkgs']) && $this->_summary['usage.' . $service]['pkgs'] & $pkg) { return true; } @@ -248,43 +253,45 @@ public function has_pkg( $service, $pkg ) { * @since 3.0 * @access private */ - public function allowance( $service, &$err = false ) { + public function allowance($service, &$err = false) + { // Only auto sync usage at most one time per day - if ( empty( $this->_summary[ 'last_request.' . self::SVC_D_USAGE ] ) || time() - $this->_summary[ 'last_request.' . self::SVC_D_USAGE ] > 86400 ) { + if (empty($this->_summary['last_request.' . self::SVC_D_USAGE]) || time() - $this->_summary['last_request.' . self::SVC_D_USAGE] > 86400) { $this->sync_usage(); } - if ( in_array( $service, array( self::SVC_CCSS, self::SVC_UCSS, self::SVC_VPI ) ) ) { // @since 4.2 + if (in_array($service, array(self::SVC_CCSS, self::SVC_UCSS, self::SVC_VPI))) { + // @since 4.2 $service = self::SVC_PAGE_OPTM; } - if ( empty( $this->_summary[ 'usage.' . $service ] ) ) { + if (empty($this->_summary['usage.' . $service])) { return 0; } - $usage = $this->_summary[ 'usage.' . $service ]; + $usage = $this->_summary['usage.' . $service]; // Image optm is always free $allowance_max = 0; - if ( $service == self::SVC_IMG_OPTM ) { + if ($service == self::SVC_IMG_OPTM) { $allowance_max = self::IMG_OPTM_DEFAULT_GROUP; - if ( ! empty( $usage[ 'pkgs' ] ) && $usage[ 'pkgs' ] & self::BM_IMG_OPTM_JUMBO_GROUP ) { + if (!empty($usage['pkgs']) && $usage['pkgs'] & self::BM_IMG_OPTM_JUMBO_GROUP) { $allowance_max = self::IMG_OPTM_JUMBO_GROUP; } } - $allowance = $usage[ 'quota' ] - $usage[ 'used' ]; + $allowance = $usage['quota'] - $usage['used']; $err = 'out_of_quota'; - if ( $allowance > 0 ) { - if ( $allowance_max && $allowance_max < $allowance ) { + if ($allowance > 0) { + if ($allowance_max && $allowance_max < $allowance) { $allowance = $allowance_max; } // Daily limit @since 4.2 - if ( isset( $usage[ 'remaining_daily_quota' ] ) && $usage[ 'remaining_daily_quota' ] >= 0 && $usage[ 'remaining_daily_quota' ] < $allowance ) { - $allowance = $usage[ 'remaining_daily_quota' ]; - if ( ! $allowance ) { + if (isset($usage['remaining_daily_quota']) && $usage['remaining_daily_quota'] >= 0 && $usage['remaining_daily_quota'] < $allowance) { + $allowance = $usage['remaining_daily_quota']; + if (!$allowance) { $err = 'out_of_daily_quota'; } } @@ -293,15 +300,15 @@ public function allowance( $service, &$err = false ) { } // Check Pay As You Go balance - if ( empty( $usage[ 'pag_bal' ] ) ) { + if (empty($usage['pag_bal'])) { return $allowance_max; } - if ( $allowance_max && $allowance_max < $usage[ 'pag_bal' ] ) { + if ($allowance_max && $allowance_max < $usage['pag_bal']) { return $allowance_max; } - return $usage[ 'pag_bal' ]; + return $usage['pag_bal']; } /** @@ -310,16 +317,17 @@ public function allowance( $service, &$err = false ) { * @since 3.0 * @access public */ - public function sync_usage() { - $usage = $this->_post( self::SVC_D_USAGE ); - if ( ! $usage ) { + public function sync_usage() + { + $usage = $this->_post(self::SVC_D_USAGE); + if (!$usage) { return; } - self::debug( 'sync_usage ' . json_encode( $usage ) ); + self::debug('sync_usage ' . json_encode($usage)); - foreach ( self::$SERVICES as $v ) { - $this->_summary[ 'usage.' . $v ] = ! empty( $usage[ $v ] ) ? $usage[ $v ] : false; + foreach (self::$SERVICES as $v) { + $this->_summary['usage.' . $v] = !empty($usage[$v]) ? $usage[$v] : false; } self::save_summary(); @@ -333,18 +341,19 @@ public function sync_usage() { * @since 3.0 * @access public */ - public function clear_cloud() { - foreach ( self::$SERVICES as $service ) { - if ( isset( $this->_summary[ 'server.' . $service ] ) ) { - unset( $this->_summary[ 'server.' . $service ] ); + public function clear_cloud() + { + foreach (self::$SERVICES as $service) { + if (isset($this->_summary['server.' . $service])) { + unset($this->_summary['server.' . $service]); } - if ( isset( $this->_summary[ 'server_date.' . $service ] ) ) { - unset( $this->_summary[ 'server_date.' . $service ] ); + if (isset($this->_summary['server_date.' . $service])) { + unset($this->_summary['server_date.' . $service]); } } self::save_summary(); - self::debug( 'Cleared all local service node caches' ); + self::debug('Cleared all local service node caches'); } /** @@ -353,136 +362,142 @@ public function clear_cloud() { * @since 3.0 * @access public */ - public function detect_cloud( $service, $force = false ) { - if ( in_array( $service, self::$CENTER_SVC_SET ) ) { + public function detect_cloud($service, $force = false) + { + if (in_array($service, self::$CENTER_SVC_SET)) { return self::CLOUD_SERVER; } - if ( in_array( $service, self::$WP_SVC_SET ) ) { + if (in_array($service, self::$WP_SVC_SET)) { return self::CLOUD_SERVER_WP; } // Check if the stored server needs to be refreshed - if ( ! $force ) { - if ( ! empty( $this->_summary[ 'server.' . $service ] ) && ! empty( $this->_summary[ 'server_date.' . $service ] ) && $this->_summary[ 'server_date.' . $service ] > time() - 86400 * self::TTL_NODE ) { - return $this->_summary[ 'server.' . $service ]; + if (!$force) { + if ( + !empty($this->_summary['server.' . $service]) && + !empty($this->_summary['server_date.' . $service]) && + $this->_summary['server_date.' . $service] > time() - 86400 * self::TTL_NODE + ) { + return $this->_summary['server.' . $service]; } } - if ( ! $service || ! in_array( $service, self::$SERVICES ) ) { - $msg = __( 'Cloud Error', 'litespeed-cache' ) . ': ' . $service; - Admin_Display::error( $msg ); + if (!$service || !in_array($service, self::$SERVICES)) { + $msg = __('Cloud Error', 'litespeed-cache') . ': ' . $service; + Admin_Display::error($msg); return false; } // Send request to Quic Online Service - $json = $this->_post( self::SVC_D_NODES, array( 'svc' => $this->_maybe_queue( $service ) ) ); + $json = $this->_post(self::SVC_D_NODES, array('svc' => $this->_maybe_queue($service))); // Check if get list correctly - if ( empty( $json[ 'list' ] ) || ! is_array( $json[ 'list' ] ) ) { - self::debug( 'request cloud list failed: ', $json ); + if (empty($json['list']) || !is_array($json['list'])) { + self::debug('request cloud list failed: ', $json); - if ( $json ) { - $msg = __( 'Cloud Error', 'litespeed-cache' ) . ": [Service] $service [Info] " . json_encode( $json ); - Admin_Display::error( $msg ); + if ($json) { + $msg = __('Cloud Error', 'litespeed-cache') . ": [Service] $service [Info] " . json_encode($json); + Admin_Display::error($msg); } return false; } - // Ping closest cloud $speed_list = array(); - foreach ( $json[ 'list' ] as $v ) { + foreach ($json['list'] as $v) { // Exclude possible failed 503 nodes - if ( ! empty( $this->_summary['disabled_node'] ) && ! empty($this->_summary['disabled_node'][$v]) && time() - $this->_summary['disabled_node'][$v] < 86400 ) { + if (!empty($this->_summary['disabled_node']) && !empty($this->_summary['disabled_node'][$v]) && time() - $this->_summary['disabled_node'][$v] < 86400) { continue; } - $speed_list[ $v ] = Utility::ping( $v ); + $speed_list[$v] = Utility::ping($v); } - if ( ! $speed_list ) { - self::debug( 'nodes are in 503 failed nodes' ); + if (!$speed_list) { + self::debug('nodes are in 503 failed nodes'); return false; } - $min = min( $speed_list ); + $min = min($speed_list); - if ( $min == 99999 ) { - self::debug( 'failed to ping all clouds' ); + if ($min == 99999) { + self::debug('failed to ping all clouds'); return false; } // Random pick same time range ip (230ms 250ms) - $range_len = strlen( $min ); - $range_num = substr( $min, 0, 1 ); + $range_len = strlen($min); + $range_num = substr($min, 0, 1); $valid_clouds = array(); - foreach ($speed_list as $node => $speed ) { - if ( strlen( $speed ) == $range_len && substr( $speed, 0, 1 ) == $range_num ) { + foreach ($speed_list as $node => $speed) { + if (strlen($speed) == $range_len && substr($speed, 0, 1) == $range_num) { $valid_clouds[] = $node; } // Append the lower speed ones - else if ( $speed < $min * 4 ) { + elseif ($speed < $min * 4) { $valid_clouds[] = $node; } } - if ( ! $valid_clouds ) { - $msg = __( 'Cloud Error', 'litespeed-cache' ) . ": [Service] $service [Info] " . __( 'No available Cloud Node.', 'litespeed-cache' ); - Admin_Display::error( $msg ); + if (!$valid_clouds) { + $msg = __('Cloud Error', 'litespeed-cache') . ": [Service] $service [Info] " . __('No available Cloud Node.', 'litespeed-cache'); + Admin_Display::error($msg); return false; } - self::debug( 'Closest nodes list', $valid_clouds ); + self::debug('Closest nodes list', $valid_clouds); // Check server load - if ( in_array( $service, self::$SERVICES_LOAD_CHECK ) ) { + if (in_array($service, self::$SERVICES_LOAD_CHECK)) { $valid_cloud_loads = array(); - foreach ( $valid_clouds as $k => $v ) { - $response = wp_remote_get( $v, array( 'timeout' => 5, 'sslverify' => true ) ); - if ( is_wp_error( $response ) ) { + foreach ($valid_clouds as $k => $v) { + $response = wp_remote_get($v, array('timeout' => 5, 'sslverify' => true)); + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - self::debug( 'failed to do load checker: ' . $error_message ); + self::debug('failed to do load checker: ' . $error_message); continue; } - $curr_load = json_decode( $response[ 'body' ], true ); - if ( ! empty( $curr_load[ '_res' ] ) && $curr_load[ '_res' ] == 'ok' && isset( $curr_load[ 'load' ] ) ) { - $valid_cloud_loads[ $v ] = $curr_load[ 'load' ]; + $curr_load = json_decode($response['body'], true); + if (!empty($curr_load['_res']) && $curr_load['_res'] == 'ok' && isset($curr_load['load'])) { + $valid_cloud_loads[$v] = $curr_load['load']; } } - if ( ! $valid_cloud_loads ) { - $msg = __( 'Cloud Error', 'litespeed-cache' ) . ": [Service] $service [Info] " . __( 'No available Cloud Node after checked server load.', 'litespeed-cache' ); - Admin_Display::error( $msg ); + if (!$valid_cloud_loads) { + $msg = __('Cloud Error', 'litespeed-cache') . ": [Service] $service [Info] " . __('No available Cloud Node after checked server load.', 'litespeed-cache'); + Admin_Display::error($msg); return false; } - self::debug( 'Closest nodes list after load check', $valid_cloud_loads ); + self::debug('Closest nodes list after load check', $valid_cloud_loads); - $qualified_list = array_keys( $valid_cloud_loads, min( $valid_cloud_loads ) ); - } - else { + $qualified_list = array_keys($valid_cloud_loads, min($valid_cloud_loads)); + } else { $qualified_list = $valid_clouds; } - $closest = $qualified_list[ array_rand( $qualified_list ) ]; + $closest = $qualified_list[array_rand($qualified_list)]; - self::debug( 'Chose node: ' . $closest ); + self::debug('Chose node: ' . $closest); // store data into option locally - $this->_summary[ 'server.' . $service ] = $closest; - $this->_summary[ 'server_date.' . $service ] = time(); + $this->_summary['server.' . $service] = $closest; + $this->_summary['server_date.' . $service] = time(); self::save_summary(); - return $this->_summary[ 'server.' . $service ]; + return $this->_summary['server.' . $service]; } /** * May need to convert to queue service */ - private function _maybe_queue( $service ) { - if ( in_array( $service, self::$_QUEUE_SVC_SET ) ) return self::SVC_QUEUE; + private function _maybe_queue($service) + { + if (in_array($service, self::$_QUEUE_SVC_SET)) { + return self::SVC_QUEUE; + } return $service; } @@ -492,9 +507,10 @@ private function _maybe_queue( $service ) { * @since 3.0 * @access public */ - public static function get( $service, $data = array() ) { + public static function get($service, $data = array()) + { $instance = self::cls(); - return $instance->_get( $service, $data ); + return $instance->_get($service, $data); } /** @@ -503,43 +519,44 @@ public static function get( $service, $data = array() ) { * @since 3.0 * @access private */ - private function _get( $service, $data = false ) { + private function _get($service, $data = false) + { $service_tag = $service; - if ( ! empty( $data[ 'action' ] ) ) { - $service_tag .= '-' . $data[ 'action' ]; + if (!empty($data['action'])) { + $service_tag .= '-' . $data['action']; } - if ( ! $this->_maybe_cloud( $service_tag ) ) { + if (!$this->_maybe_cloud($service_tag)) { return; } - $server = $this->detect_cloud( $service ); - if ( ! $server ) { + $server = $this->detect_cloud($service); + if (!$server) { return; } $url = $server . '/' . $service; $param = array( - 'site_url' => home_url(), - 'domain_key' => $this->_api_key, - 'main_domain' => ! empty( $this->_summary[ 'main_domain' ] ) ? $this->_summary[ 'main_domain' ] : '', - 'ver' => Core::VER, + 'site_url' => home_url(), + 'domain_key' => $this->_api_key(), + 'main_domain' => !empty($this->_summary['main_domain']) ? $this->_summary['main_domain'] : '', + 'ver' => Core::VER, ); - if ( $data ) { - $param[ 'data' ] = $data; + if ($data) { + $param['data'] = $data; } - $url .= '?' . http_build_query( $param ); + $url .= '?' . http_build_query($param); - self::debug( 'getting from : ' . $url ); + self::debug('getting from : ' . $url); - self::save_summary( array( 'curr_request.' . $service_tag => time() ) ); + self::save_summary(array('curr_request.' . $service_tag => time())); - $response = wp_remote_get( $url, array( 'timeout' => 15, 'sslverify' => true ) ); + $response = wp_remote_get($url, array('timeout' => 15, 'sslverify' => true)); - return $this->_parse_response( $response, $service, $service_tag, $server ); + return $this->_parse_response($response, $service, $service_tag, $server); } /** @@ -548,63 +565,76 @@ private function _get( $service, $data = false ) { * @since 3.0 * @access private */ - private function _maybe_cloud( $service_tag ) { + private function _maybe_cloud($service_tag) + { $home_url = home_url(); - if ( ! wp_http_validate_url( $home_url ) ) { + if (!wp_http_validate_url($home_url)) { + self::debug('wp_http_validate_url failed: ' . $home_url); + return false; + } + + // Deny if is IP + if (preg_match('#^(([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)$#', Utility::parse_url_safe($home_url, PHP_URL_HOST))) { + self::debug('IP home url is not allowed for cloud service.'); + $msg = __('In order to use QC services, need a real domain name, cannot use an IP.', 'litespeed-cache'); + Admin_Display::error($msg); return false; } /** @since 5.0 If in valid err_domains, bypass request */ - if ( $this->_is_err_domain( $home_url ) ) { + if ($this->_is_err_domain($home_url)) { + self::debug('home url is in err_domains, bypass request: ' . $home_url); return false; } // we don't want the `img_optm-taken` to fail at any given time - if ( $service_tag == self::IMGOPTM_TAKEN ) { + if ($service_tag == self::IMGOPTM_TAKEN) { return true; } - if ( $service_tag == self::SVC_D_SYNC_CONF && $this->_setup_token && ! $this->_api_key ) { - self::debug( "Skip sync conf if API key is not available yet." ); + if ($service_tag == self::SVC_D_SYNC_CONF && $this->_setup_token && !$this->_api_key()) { + self::debug('Skip sync conf if API key is not available yet.'); return false; } $expiration_req = self::EXPIRATION_REQ; // Limit frequent unfinished request to 5min $timestamp_tag = 'curr_request.'; - if ( $service_tag == self::SVC_IMG_OPTM . '-' . Img_Optm::TYPE_NEW_REQ ) { + if ($service_tag == self::SVC_IMG_OPTM . '-' . Img_Optm::TYPE_NEW_REQ) { $timestamp_tag = 'last_request.'; - if ( $this->has_pkg( self::SVC_IMG_OPTM, self::BM_IMG_OPTM_PRIO ) ) { + if ($this->has_pkg(self::SVC_IMG_OPTM, self::BM_IMG_OPTM_PRIO)) { $expiration_req /= 10; } - } - else { + } else { // For all other requests, if is under debug mode, will always allow - if ( $this->conf( self::O_DEBUG ) && $this->_api_key ) { + if ($this->conf(self::O_DEBUG) && $this->_api_key()) { return true; } } - if ( ! empty( $this->_summary[ $timestamp_tag . $service_tag ] ) ) { - $expired = $this->_summary[ $timestamp_tag . $service_tag ] + $expiration_req - time(); - if ( $expired > 0 ) { - self::debug( "❌ try [$service_tag] after $expired seconds" ); + if (!empty($this->_summary[$timestamp_tag . $service_tag])) { + $expired = $this->_summary[$timestamp_tag . $service_tag] + $expiration_req - time(); + if ($expired > 0) { + self::debug("❌ try [$service_tag] after $expired seconds"); - if ( $service_tag !== self::API_VER ) { - $msg = __( 'Cloud Error', 'litespeed-cache' ) . ': ' . sprintf( __( 'Please try after %1$s for service %2$s.', 'litespeed-cache' ), Utility::readable_time( $expired, 0, true ), '' . $service_tag . '' ); - Admin_Display::error( array( 'cloud_trylater' => $msg ) ); + if ($service_tag !== self::API_VER) { + $msg = + __('Cloud Error', 'litespeed-cache') . + ': ' . + sprintf(__('Please try after %1$s for service %2$s.', 'litespeed-cache'), Utility::readable_time($expired, 0, true), '' . $service_tag . ''); + Admin_Display::error(array('cloud_trylater' => $msg)); } return false; } } - if ( in_array( $service_tag, self::$_PUB_SVC_SET ) ) { + if (in_array($service_tag, self::$_PUB_SVC_SET)) { return true; } - if ( ! $this->_api_key ) { - Admin_Display::error( Error::msg( 'lack_of_api_key' ) ); + if (!$this->_api_key()) { + Admin_Display::error(Error::msg('lack_of_api_key')); return false; } @@ -617,9 +647,10 @@ private function _maybe_cloud( $service_tag ) { * @since 3.0 * @access public */ - public static function post( $service, $data = false, $time_out = false ) { + public static function post($service, $data = false, $time_out = false) + { $instance = self::cls(); - return $instance->_post( $service, $data, $time_out ); + return $instance->_post($service, $data, $time_out); } /** @@ -628,42 +659,43 @@ public static function post( $service, $data = false, $time_out = false ) { * @since 3.0 * @access private */ - private function _post( $service, $data = false, $time_out = false ) { + private function _post($service, $data = false, $time_out = false) + { $service_tag = $service; - if ( ! empty( $data[ 'action' ] ) ) { - $service_tag .= '-' . $data[ 'action' ]; + if (!empty($data['action'])) { + $service_tag .= '-' . $data['action']; } - if ( ! $this->_maybe_cloud( $service_tag ) ) { + if (!$this->_maybe_cloud($service_tag)) { return; } - $server = $this->detect_cloud( $service ); - if ( ! $server ) { + $server = $this->detect_cloud($service); + if (!$server) { return; } - $url = $server . '/' . $this->_maybe_queue( $service ); + $url = $server . '/' . $this->_maybe_queue($service); - self::debug( 'posting to : ' . $url ); + self::debug('posting to : ' . $url); - if ( $data ) { - $data[ 'service_type' ] = $service; // For queue distribution usage + if ($data) { + $data['service_type'] = $service; // For queue distribution usage } $param = array( - 'site_url' => home_url(), - 'domain_key' => $this->_api_key, - 'main_domain' => ! empty( $this->_summary[ 'main_domain' ] ) ? $this->_summary[ 'main_domain' ] : '', - 'ver' => Core::VER, - 'data' => $data, + 'site_url' => home_url(), + 'domain_key' => $this->_api_key(), + 'main_domain' => !empty($this->_summary['main_domain']) ? $this->_summary['main_domain'] : '', + 'ver' => Core::VER, + 'data' => $data, ); - self::save_summary( array( 'curr_request.' . $service_tag => time() ) ); + self::save_summary(array('curr_request.' . $service_tag => time())); - $response = wp_remote_post( $url, array( 'body' => $param, 'timeout' => $time_out ?: 15, 'sslverify' => true ) ); + $response = wp_remote_post($url, array('body' => $param, 'timeout' => $time_out ?: 15, 'sslverify' => true)); - return $this->_parse_response( $response, $service, $service_tag, $server ); + return $this->_parse_response($response, $service, $service_tag, $server); } /** @@ -672,85 +704,113 @@ private function _post( $service, $data = false, $time_out = false ) { * * @since 3.0 */ - private function _parse_response( $response, $service, $service_tag, $server ) { - if ( is_wp_error( $response ) ) { + private function _parse_response($response, $service, $service_tag, $server) + { + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - self::debug( 'failed to request: ' . $error_message ); + self::debug('failed to request: ' . $error_message); - if ( $service !== self::API_VER ) { - $msg = __( 'Failed to request via WordPress', 'litespeed-cache' ) . ': ' . $error_message . " [server] $server [service] $service"; - Admin_Display::error( $msg ); + if ($service !== self::API_VER) { + $msg = __('Failed to request via WordPress', 'litespeed-cache') . ': ' . $error_message . " [server] $server [service] $service"; + Admin_Display::error($msg); // Tmp disabled this node from reusing in 1 day - if (empty($this->_summary['disabled_node'])) $this->_summary['disabled_node'] = array(); + if (empty($this->_summary['disabled_node'])) { + $this->_summary['disabled_node'] = array(); + } $this->_summary['disabled_node'][$server] = time(); self::save_summary(); // Force redetect node - self::debug( 'Node error, redetecting node [svc] ' . $service ); - $this->detect_cloud( $service, true ); + self::debug('Node error, redetecting node [svc] ' . $service); + $this->detect_cloud($service, true); } return; } - $json = json_decode( $response[ 'body' ], true ); + $json = json_decode($response['body'], true); - if ( ! is_array( $json ) ) { - self::debug( 'failed to decode response json: ' . $response[ 'body' ] ); + if (!is_array($json)) { + self::debug('failed to decode response json: ' . $response['body']); - if ( $service !== self::API_VER ) { - $msg = __( 'Failed to request via WordPress', 'litespeed-cache' ) . ': ' . $response[ 'body' ] . " [server] $server [service] $service"; - Admin_Display::error( $msg ); + if ($service !== self::API_VER) { + $msg = __('Failed to request via WordPress', 'litespeed-cache') . ': ' . $response['body'] . " [server] $server [service] $service"; + Admin_Display::error($msg); // Tmp disabled this node from reusing in 1 day - if (empty($this->_summary['disabled_node'])) $this->_summary['disabled_node'] = array(); + if (empty($this->_summary['disabled_node'])) { + $this->_summary['disabled_node'] = array(); + } $this->_summary['disabled_node'][$server] = time(); self::save_summary(); // Force redetect node - self::debug( 'Node error, redetecting node [svc] ' . $service ); - $this->detect_cloud( $service, true ); + self::debug('Node error, redetecting node [svc] ' . $service); + $this->detect_cloud($service, true); } return; } - if ( ! empty( $json[ '_code' ] ) ) { - if ( $json[ '_code' ] == 'heavy_load' || $json[ '_code' ] == 'redetect_node' ) { + if (!empty($json['_code'])) { + self::debug('Hit err _code: ' . $json['_code']); + if ($json['_code'] == 'unpulled_images') { + $msg = __('Cloud server refused the current request due to unpulled images. Please pull the images first.', 'litespeed-cache'); + Admin_Display::error($msg); + return; + } + if ($json['_code'] == 'blocklisted') { + $msg = __('Your domain_key has been temporarily blocklisted to prevent abuse. You may contact support at QUIC.cloud to learn more.', 'litespeed-cache'); + Admin_Display::error($msg); + return; + } + + if ($json['_code'] == 'rate_limit') { + self::debug('Cloud server rate limit exceeded.'); + $msg = __('Cloud server refused the current request due to rate limiting. Please try again later.', 'litespeed-cache'); + Admin_Display::error($msg); + return; + } + + if ($json['_code'] == 'heavy_load' || $json['_code'] == 'redetect_node') { // Force redetect node - self::debug( 'Node redetecting node [svc] ' . $service ); - Admin_Display::info( __( 'Redetected node', 'litespeed-cache' ) . ': ' . Error::msg( $json[ '_code' ] ) ); - $this->detect_cloud( $service, true ); + self::debug('Node redetecting node [svc] ' . $service); + Admin_Display::info(__('Redetected node', 'litespeed-cache') . ': ' . Error::msg($json['_code'])); + $this->detect_cloud($service, true); } } - if ( ! empty( $json[ '_503' ] ) ) { - self::debug( 'service 503 unavailable temporarily. ' . $json[ '_503' ] ); + if (!empty($json['_503'])) { + self::debug('service 503 unavailable temporarily. ' . $json['_503']); - $msg = __( 'We are working hard to improve your online service experience. The service will be unavailable while we work. We apologize for any inconvenience.', 'litespeed-cache' ); - $msg .= ' ' . $json[ '_503' ] . " [server] $server [service] $service"; - Admin_Display::error( $msg ); + $msg = __( + 'We are working hard to improve your online service experience. The service will be unavailable while we work. We apologize for any inconvenience.', + 'litespeed-cache' + ); + $msg .= ' ' . $json['_503'] . " [server] $server [service] $service"; + Admin_Display::error($msg); // Force redetect node - self::debug( 'Node error, redetecting node [svc] ' . $service ); - $this->detect_cloud( $service, true ); + self::debug('Node error, redetecting node [svc] ' . $service); + $this->detect_cloud($service, true); return; } - list( $json, $return ) = $this->extract_msg( $json, $service, $server ); - if ( $return ) return; + list($json, $return) = $this->extract_msg($json, $service, $server); + if ($return) { + return; + } - self::save_summary( array( - 'last_request.' . $service_tag => $this->_summary[ 'curr_request.' . $service_tag ], - 'curr_request.' . $service_tag => 0 + self::save_summary(array( + 'last_request.' . $service_tag => $this->_summary['curr_request.' . $service_tag], + 'curr_request.' . $service_tag => 0, )); - if ( $json ) { - self::debug2( 'response ok', $json ); - } - else { - self::debug2( 'response ok' ); + if ($json) { + self::debug2('response ok', $json); + } else { + self::debug2('response ok'); } // Only successful request return Array @@ -761,74 +821,77 @@ private function _parse_response( $response, $service, $service_tag, $server ) { * Extract msg from json * @since 5.0 */ - public function extract_msg( $json, $service, $server = false, $is_callback = false ) { - if ( ! empty( $json[ '_info' ] ) ) { - self::debug( '_info: ' . $json[ '_info' ] ); - $msg = __( 'Message from QUIC.cloud server', 'litespeed-cache' ) . ': ' . $json[ '_info' ]; - $msg .= $this->_parse_link( $json ); - Admin_Display::info( $msg ); - unset( $json[ '_info' ] ); + public function extract_msg($json, $service, $server = false, $is_callback = false) + { + if (!empty($json['_info'])) { + self::debug('_info: ' . $json['_info']); + $msg = __('Message from QUIC.cloud server', 'litespeed-cache') . ': ' . $json['_info']; + $msg .= $this->_parse_link($json); + Admin_Display::info($msg); + unset($json['_info']); } - if ( ! empty( $json[ '_note' ] ) ) { - self::debug( '_note: ' . $json[ '_note' ] ); - $msg = __( 'Message from QUIC.cloud server', 'litespeed-cache' ) . ': ' . $json[ '_note' ]; - $msg .= $this->_parse_link( $json ); - Admin_Display::note( $msg ); - unset( $json[ '_note' ] ); + if (!empty($json['_note'])) { + self::debug('_note: ' . $json['_note']); + $msg = __('Message from QUIC.cloud server', 'litespeed-cache') . ': ' . $json['_note']; + $msg .= $this->_parse_link($json); + Admin_Display::note($msg); + unset($json['_note']); } - if ( ! empty( $json[ '_success' ] ) ) { - self::debug( '_success: ' . $json[ '_success' ] ); - $msg = __( 'Good news from QUIC.cloud server', 'litespeed-cache' ) . ': ' . $json[ '_success' ]; - $msg .= $this->_parse_link( $json ); - Admin_Display::succeed( $msg ); - unset( $json[ '_success' ] ); + if (!empty($json['_success'])) { + self::debug('_success: ' . $json['_success']); + $msg = __('Good news from QUIC.cloud server', 'litespeed-cache') . ': ' . $json['_success']; + $msg .= $this->_parse_link($json); + Admin_Display::succeed($msg); + unset($json['_success']); } // Upgrade is required - if ( ! empty( $json[ '_err_req_v' ] ) ) { - self::debug( '_err_req_v: ' . $json[ '_err_req_v' ] ); - $msg = sprintf( __( '%1$s plugin version %2$s required for this action.', 'litespeed-cache' ), Core::NAME, 'v' . $json[ '_err_req_v' ] . '+' ) . " [server] $server [service] $service"; + if (!empty($json['_err_req_v'])) { + self::debug('_err_req_v: ' . $json['_err_req_v']); + $msg = + sprintf(__('%1$s plugin version %2$s required for this action.', 'litespeed-cache'), Core::NAME, 'v' . $json['_err_req_v'] . '+') . + " [server] $server [service] $service"; // Append upgrade link - $msg2 = ' ' . GUI::plugin_upgrade_link( Core::NAME, Core::PLUGIN_NAME, $json[ '_err_req_v' ] ); + $msg2 = ' ' . GUI::plugin_upgrade_link(Core::NAME, Core::PLUGIN_NAME, $json['_err_req_v']); - $msg2 .= $this->_parse_link( $json ); - Admin_Display::error( $msg . $msg2 ); - return array( $json, true ); + $msg2 .= $this->_parse_link($json); + Admin_Display::error($msg . $msg2); + return array($json, true); } // Parse _carry_on info - if ( ! empty( $json[ '_carry_on' ] ) ) { - self::debug( 'Carry_on usage', $json[ '_carry_on' ] ); + if (!empty($json['_carry_on'])) { + self::debug('Carry_on usage', $json['_carry_on']); // Store generic info - foreach ( array( 'usage', 'promo', 'partner', '_err', '_info', '_note', '_success' ) as $v ) { - if ( ! empty( $json[ '_carry_on' ][ $v ] ) ) { - switch ( $v ) { + foreach (array('usage', 'promo', 'partner', '_err', '_info', '_note', '_success') as $v) { + if (!empty($json['_carry_on'][$v])) { + switch ($v) { case 'usage': - $usage_svc_tag = in_array( $service, array( self::SVC_CCSS, self::SVC_UCSS, self::SVC_VPI ) ) ? self::SVC_PAGE_OPTM : $service; - $this->_summary[ 'usage.' . $usage_svc_tag ] = $json[ '_carry_on' ][ $v ]; + $usage_svc_tag = in_array($service, array(self::SVC_CCSS, self::SVC_UCSS, self::SVC_VPI)) ? self::SVC_PAGE_OPTM : $service; + $this->_summary['usage.' . $usage_svc_tag] = $json['_carry_on'][$v]; break; case 'promo': - if ( empty( $this->_summary[ $v ] ) || ! is_array( $this->_summary[ $v ] ) ) { - $this->_summary[ $v ] = array(); + if (empty($this->_summary[$v]) || !is_array($this->_summary[$v])) { + $this->_summary[$v] = array(); } - $this->_summary[ $v ][] = $json[ '_carry_on' ][ $v ]; + $this->_summary[$v][] = $json['_carry_on'][$v]; break; case 'partner': - $this->_summary[ $v ] = $json[ '_carry_on' ][ $v ]; + $this->_summary[$v] = $json['_carry_on'][$v]; break; case '_error': case '_info': case '_note': case '_success': - $color_mode = substr( $v, 1 ); - $msgs = $json[ '_carry_on' ][ $v ]; - Admin_Display::add_unique_notice( $color_mode, $msgs, true ); + $color_mode = substr($v, 1); + $msgs = $json['_carry_on'][$v]; + Admin_Display::add_unique_notice($color_mode, $msgs, true); break; default: @@ -837,98 +900,103 @@ public function extract_msg( $json, $service, $server = false, $is_callback = fa } } self::save_summary(); - unset( $json[ '_carry_on' ] ); + unset($json['_carry_on']); } // Parse general error msg - if ( !$is_callback && ( empty( $json[ '_res' ] ) || $json[ '_res' ] !== 'ok' ) ) { - $json_msg = ! empty( $json[ '_msg' ] ) ? $json[ '_msg' ] : 'unknown'; - self::debug( '❌ _err: ' . $json_msg, $json ); + if (!$is_callback && (empty($json['_res']) || $json['_res'] !== 'ok')) { + $json_msg = !empty($json['_msg']) ? $json['_msg'] : 'unknown'; + self::debug('❌ _err: ' . $json_msg, $json); - $str_translated = Error::msg( $json_msg ); - $msg = __( 'Failed to communicate with QUIC.cloud server', 'litespeed-cache' ) . ': ' . $str_translated . " [server] $server [service] $service"; - $msg .= $this->_parse_link( $json ); - Admin_Display::error( $msg ); + $str_translated = Error::msg($json_msg); + $msg = __('Failed to communicate with QUIC.cloud server', 'litespeed-cache') . ': ' . $str_translated . " [server] $server [service] $service"; + $msg .= $this->_parse_link($json); + Admin_Display::error($msg); // QC may try auto alias /** @since 5.0 Store the domain as `err_domains` only for QC auto alias feature */ - if ( $json_msg == 'err_alias' ) { - if ( empty( $this->_summary[ 'err_domains' ] ) ) { - $this->_summary[ 'err_domains' ] = array(); + if ($json_msg == 'err_alias') { + if (empty($this->_summary['err_domains'])) { + $this->_summary['err_domains'] = array(); } $home_url = home_url(); - if ( ! array_key_exists( $home_url, $this->_summary[ 'err_domains' ] ) ) { - $this->_summary[ 'err_domains' ][ $home_url ] = time(); + if (!array_key_exists($home_url, $this->_summary['err_domains'])) { + $this->_summary['err_domains'][$home_url] = time(); } self::save_summary(); } // Site not on QC, delete invalid domain key - if ( $json_msg == 'site_not_registered' || $json_msg == 'err_key' ) { + if ($json_msg == 'site_not_registered' || $json_msg == 'err_key') { $this->_clean_api_key(); } - return array( $json, true ); + return array($json, true); } - unset( $json[ '_res' ] ); - if ( ! empty( $json[ '_msg' ] ) ) { - unset( $json[ '_msg' ] ); + unset($json['_res']); + if (!empty($json['_msg'])) { + unset($json['_msg']); } - return array( $json, false ); + return array($json, false); } /** * Clear API key and QC linked status * @since 5.0 */ - private function _clean_api_key() { - $this->cls( 'Conf' )->update_confs( array( self::O_API_KEY => '' ) ); + private function _clean_api_key() + { + $this->cls('Conf')->update_confs(array(self::O_API_KEY => '')); $this->_summary['is_linked'] = 0; self::save_summary(); - $msg = __( 'Site not recognized. Domain Key has been automatically removed. Please request a new one.', 'litespeed-cache' ); - $msg .= Doc::learn_more( admin_url( 'admin.php?page=litespeed-general' ), __( 'Click here to set.', 'litespeed-cache' ), true, false, true ); - $msg .= Doc::learn_more( 'https://docs.litespeedtech.com/lscache/lscwp/general/#domain-key', false, false, false, true ); - Admin_Display::error( $msg, false, true ); + $msg = __('Site not recognized. Domain Key has been automatically removed. Please request a new one.', 'litespeed-cache'); + $msg .= Doc::learn_more(admin_url('admin.php?page=litespeed-general'), __('Click here to set.', 'litespeed-cache'), true, false, true); + $msg .= Doc::learn_more('https://docs.litespeedtech.com/lscache/lscwp/general/#domain-key', false, false, false, true); + Admin_Display::error($msg, false, true); } /** * REST call: check if the error domain is valid call for auto alias purpose * @since 5.0 */ - public function rest_err_domains() { + public function rest_err_domains() + { // Validate token hash first - if ( empty( $_POST[ 'hash' ] ) || empty( $_POST[ 'main_domain' ] ) || empty( $_POST[ 'alias' ] ) ) { - return self::err( 'lack_of_param' ); + if (empty($_POST['hash']) || empty($_POST['main_domain']) || empty($_POST['alias'])) { + return self::err('lack_of_param'); } - if ( ! $this->_api_key || $_POST[ 'hash' ] !== md5( substr( $this->_api_key, 1, 8 ) ) ) { - return self::err( 'wrong_hash' ); + if (!$this->_api_key() || $_POST['hash'] !== md5(substr($this->_api_key(), 1, 8))) { + return self::err('wrong_hash'); } - list( $post_data ) = $this->extract_msg( $_POST, 'Quic.cloud', false, true ); + list($post_data) = $this->extract_msg($_POST, 'Quic.cloud', false, true); - if ( $this->_is_err_domain( $_POST[ 'alias' ] ) ) { - $this->_remove_domain_from_err_list( $_POST[ 'alias' ] ); + if ($this->_is_err_domain($_POST['alias'])) { + if ($_POST['alias'] == home_url()) { + $this->_remove_domain_from_err_list($_POST['alias']); + } - $res_hash = substr( $this->_api_key, 2, 4 ); + $res_hash = substr($this->_api_key(), 2, 4); - self::debug( '__callback IP request hash: md5(' . $res_hash . ')' ); + self::debug('__callback IP request hash: md5(' . $res_hash . ')'); - return self::ok( array( 'hash' => md5( $res_hash ) ) ); + return self::ok(array('hash' => md5($res_hash))); } - return self::err( 'Not an alias req from here' ); + return self::err('Not an alias req from here'); } /** * Remove a domain from err domain * @since 5.0 */ - private function _remove_domain_from_err_list( $url ) { - unset( $this->_summary[ 'err_domains' ][ $url ] ); + private function _remove_domain_from_err_list($url) + { + unset($this->_summary['err_domains'][$url]); self::save_summary(); } @@ -936,25 +1004,30 @@ private function _remove_domain_from_err_list( $url ) { * Check if is err domain * @since 5.0 */ - private function _is_err_domain( $home_url ) { - if ( empty( $this->_summary[ 'err_domains' ] ) ) return false; - if ( ! array_key_exists( $home_url, $this->_summary[ 'err_domains' ] ) ) return false; + private function _is_err_domain($home_url) + { + if (empty($this->_summary['err_domains'])) { + return false; + } + if (!array_key_exists($home_url, $this->_summary['err_domains'])) { + return false; + } // Auto delete if too long ago - if ( time() - $this->_summary[ 'err_domains' ][ $home_url ] > 86400 * 10 ) { - $this->_remove_domain_from_err_list( $home_url ); + if (time() - $this->_summary['err_domains'][$home_url] > 86400 * 10) { + $this->_remove_domain_from_err_list($home_url); + } + if (time() - $this->_summary['err_domains'][$home_url] > 86400) { + return false; } - if ( time() - $this->_summary[ 'err_domains' ][ $home_url ] > 86400 ) return false; return true; } public function req_rest_api($api, $body = array()) { - $token = $this->_setup_token; if (empty($token)) { - - Admin_Display::error( __( 'Cannot request REST API, no token saved.', 'litespeed-cache' )); + Admin_Display::error(__('Cannot request REST API, no token saved.', 'litespeed-cache')); return; } $req_args = array( @@ -976,27 +1049,36 @@ public function req_rest_api($api, $body = array()) private function _parse_rest_response($response) { - if ( is_wp_error( $response ) ) { - + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - self::debug( 'failed to request REST API: ' . $error_message ); - Admin_Display::error( __( 'Cloud REST Error', 'litespeed-cache' ) . ': ' . $error_message ); + self::debug('failed to request REST API: ' . $error_message); + Admin_Display::error(__('Cloud REST Error', 'litespeed-cache') . ': ' . $error_message); return $error_message; + } elseif (wp_remote_retrieve_response_code($response) == '401') { + return 'unauthorized access to REST API.'; } - $json = json_decode( $response[ 'body' ], true ); + $json = json_decode($response['body'], true); if (!$json['success']) { + $contactSupport = false; if (isset($json['info']['errors'])) { $errs = array(); foreach ($json['info']['errors'] as $err) { $errs[] = 'Error ' . $err['code'] . ': ' . $err['message']; + if ($err['code'] == 1113) { + $contactSupport = true; + } } $error_message = implode('
      ', $errs); } else { - $error_message = 'Unknown error, contact QUIC.cloud support.'; + $error_message = __('Unknown error.', 'litespeed-cache'); + $contactSupport = true; } - Admin_Display::error( __( 'Cloud REST API returned error: ', 'litespeed-cache' ) . $error_message ); + if ($contactSupport) { + $error_message .= ' ' . __('Contact QUIC.cloud support', 'litespeed-cache') . ''; + } + Admin_Display::error(__('Cloud REST API returned error: ', 'litespeed-cache') . $error_message); return $error_message; } @@ -1009,16 +1091,17 @@ private function _parse_rest_response($response) * @since 3.0 * @access public */ - public function show_promo() { - // if ( ! $this->_api_key && ! defined( 'LITESPEED_DISMISS_DOMAIN_KEY' ) ) { + public function show_promo() + { + // if ( ! $this->_api_key() && ! defined( 'LITESPEED_DISMISS_DOMAIN_KEY' ) ) { // Admin_Display::error( Error::msg( 'lack_of_api_key' ), true ); // } - if ( empty( $this->_summary[ 'promo' ] ) ) { + if (empty($this->_summary['promo'])) { return; } - require_once LSCWP_DIR . 'tpl/banner/cloud_promo.tpl.php' ; + require_once LSCWP_DIR . 'tpl/banner/cloud_promo.tpl.php'; } /** @@ -1027,12 +1110,12 @@ public function show_promo() { * @since 3.0 * @access private */ - private function _clear_promo() { - if ( count( $this->_summary[ 'promo' ] ) > 1 ) { - array_shift( $this->_summary[ 'promo' ] ); - } - else { - $this->_summary[ 'promo' ] = array(); + private function _clear_promo() + { + if (count($this->_summary['promo']) > 1) { + array_shift($this->_summary['promo']); + } else { + $this->_summary['promo'] = array(); } self::save_summary(); } @@ -1044,15 +1127,16 @@ private function _clear_promo() { * @since 1.6.7 Self clean the parameter * @access private */ - private function _parse_link( &$json ) { + private function _parse_link(&$json) + { $msg = ''; - if ( ! empty( $json[ '_links' ] ) ) { - foreach ( $json[ '_links' ] as $v ) { - $msg .= ' ' . sprintf( '%s', $v[ 'link' ], ! empty( $v[ 'cls' ] ) ? $v[ 'cls' ] : '', $v[ 'title' ] ); + if (!empty($json['_links'])) { + foreach ($json['_links'] as $v) { + $msg .= ' ' . sprintf('%s', $v['link'], !empty($v['cls']) ? $v['cls'] : '', $v['title']); } - unset( $json[ '_links' ] ); + unset($json['_links']); } return $msg; @@ -1064,30 +1148,31 @@ private function _parse_link( &$json ) { * @since 3.0 * @access public */ - public function ip_validate() { - if ( empty( $_POST[ 'hash' ] ) ) { - self::debug( 'Lack of hash param' ); - return self::err( 'lack_of_param' ); + public function ip_validate() + { + if (empty($_POST['hash'])) { + self::debug('Lack of hash param'); + return self::err('lack_of_param'); } - if ( empty( $this->_api_key ) ) { - self::debug( 'Lack of API key' ); - return self::err( 'lack_of_api_key' ); + if (empty($this->_api_key())) { + self::debug('Lack of API key'); + return self::err('lack_of_api_key'); } - $to_validate = substr( $this->_api_key, 0, 4 ); - if ( $_POST[ 'hash' ] !== md5( $to_validate ) ) { - self::debug( '__callback IP request hash wrong: md5(' . $to_validate . ') !== ' . $_POST[ 'hash' ] ); - return self::err( 'err_hash' ); + $to_validate = substr($this->_api_key(), 0, 4); + if ($_POST['hash'] !== md5($to_validate)) { + self::debug('__callback IP request hash wrong: md5(' . $to_validate . ') !== ' . $_POST['hash']); + return self::err('err_hash'); } - Control::set_nocache( 'Cloud IP hash validation' ); + Control::set_nocache('Cloud IP hash validation'); - $res_hash = substr( $this->_api_key, 2, 4 ); + $res_hash = substr($this->_api_key(), 2, 4); - self::debug( '__callback IP request hash: md5(' . $res_hash . ')' ); + self::debug('__callback IP request hash: md5(' . $res_hash . ')'); - return self::ok( array( 'hash' => md5( $res_hash ) ) ); + return self::ok(array('hash' => md5($res_hash))); } /** @@ -1095,16 +1180,17 @@ public function ip_validate() { * * @since 3.0 */ - public function can_token() { - return empty( $this->_summary[ 'token_ts' ] ) || time() - $this->_summary[ 'token_ts' ] > self::EXPIRATION_TOKEN; + public function can_token() + { + return empty($this->_summary['token_ts']) || time() - $this->_summary['token_ts'] > self::EXPIRATION_TOKEN; } public function set_keygen_token($token) { - $this->_summary[ 'token' ] = $token; - $this->_summary[ 'token_ts' ] = time(); - if ( ! empty( $this->_summary[ 'apikey_ts' ] ) ) { - unset( $this->_summary[ 'apikey_ts' ] ); + $this->_summary['token'] = $token; + $this->_summary['token_ts'] = time(); + if (!empty($this->_summary['apikey_ts'])) { + unset($this->_summary['apikey_ts']); } self::save_summary(); } @@ -1115,60 +1201,61 @@ public function set_keygen_token($token) * @since 3.0 * @access public */ - public function gen_key() { + public function gen_key() + { $data = array( - 'site_url' => home_url(), - 'rest' => function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : apply_filters( 'rest_url_prefix', 'wp-json' ), - 'server_ip' => $this->conf( self::O_SERVER_IP ), + 'site_url' => home_url(), + 'rest' => function_exists('rest_get_url_prefix') ? rest_get_url_prefix() : apply_filters('rest_url_prefix', 'wp-json'), + 'server_ip' => $this->conf(self::O_SERVER_IP), ); - if ( ! empty( $this->_summary[ 'token' ] ) ) { - $data[ 'token' ] = $this->_summary[ 'token' ]; + if (!empty($this->_summary['token'])) { + $data['token'] = $this->_summary['token']; } - $response = wp_remote_get( self::CLOUD_SERVER . '/d/req_key?data=' . Utility::arr2str( $data ) ); - if ( is_wp_error( $response ) ) { + $response = wp_remote_get(self::CLOUD_SERVER . '/d/req_key?data=' . Utility::arr2str($data)); + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - self::debug( 'failed to gen_key: ' . $error_message ); - Admin_Display::error( __( 'Cloud Error', 'litespeed-cache' ) . ': ' . $error_message ); + self::debug('failed to gen_key: ' . $error_message); + Admin_Display::error(__('Cloud Error', 'litespeed-cache') . ': ' . $error_message); return; } - $json = json_decode( $response[ 'body' ], true ); + $json = json_decode($response['body'], true); // Save token option - if ( ! empty( $json[ 'token' ] ) ) { - $this->set_keygen_token( $json[ 'token' ] ); + if (!empty($json['token'])) { + $this->set_keygen_token($json['token']); } // Parse general error msg - if ( empty( $json[ '_res' ] ) || $json[ '_res' ] !== 'ok' ) { + if (empty($json['_res']) || $json['_res'] !== 'ok') { // clear current token - unset( $this->_summary[ 'token' ] ); + unset($this->_summary['token']); self::save_summary(); - $json_msg = ! empty( $json[ '_msg' ] ) ? $json[ '_msg' ] : 'unknown'; - self::debug( '❌ _err: ' . $json_msg ); + $json_msg = !empty($json['_msg']) ? $json['_msg'] : 'unknown'; + self::debug('❌ _err: ' . $json_msg); - $msg = __( 'Failed to communicate with QUIC.cloud server', 'litespeed-cache' ) . ': ' . Error::msg( $json_msg ); - $msg .= $this->_parse_link( $json ); - Admin_Display::error( $msg ); + $msg = __('Failed to communicate with QUIC.cloud server', 'litespeed-cache') . ': ' . Error::msg($json_msg); + $msg .= $this->_parse_link($json); + Admin_Display::error($msg); return; } // This is a ok msg - if ( ! empty( $json[ '_msg' ] ) ) { - self::debug( '_msg: ' . $json[ '_msg' ] ); + if (!empty($json['_msg'])) { + self::debug('_msg: ' . $json['_msg']); - $msg = __( 'Message from QUIC.cloud server', 'litespeed-cache' ) . ': ' . Error::msg( $json[ '_msg' ] ); - $msg .= $this->_parse_link( $json ); - Admin_Display::info( $msg ); + $msg = __('Message from QUIC.cloud server', 'litespeed-cache') . ': ' . Error::msg($json['_msg']); + $msg .= $this->_parse_link($json); + Admin_Display::info($msg); return; } - self::debug( '✅ send request for key successfully.' ); + self::debug('✅ send request for key successfully.'); - Admin_Display::succeed( __( 'Applied for Domain Key successfully. Please wait for result. Domain Key will be automatically sent to your WordPress.', 'litespeed-cache' ) ); + Admin_Display::succeed(__('Applied for Domain Key successfully. Please wait for result. Domain Key will be automatically sent to your WordPress.', 'litespeed-cache')); } /** @@ -1177,18 +1264,19 @@ public function gen_key() { * @since 3.0 * @access public */ - public function token_validate() { + public function token_validate() + { try { - $this->_validate_hash(); - } catch( \Exception $e ) { - return self::err( $e->getMessage() ); + $this->validate_hash(); + } catch (\Exception $e) { + return self::err($e->getMessage()); } - Control::set_nocache( 'Cloud token validation' ); + Control::set_nocache('Cloud token validation'); - self::debug( '✅ __callback token validation passed' ); + self::debug('✅ __callback token validation passed'); - return self::ok( array( 'hash' => md5( substr( $this->_summary[ 'token' ], 3, 8 ) ) ) ); + return self::ok(array('hash' => md5(substr($this->_summary['token'], 3, 8)))); } /** @@ -1197,32 +1285,33 @@ public function token_validate() { * @since 3.0 * @access public */ - public function save_apikey() { + public function save_apikey() + { // Validate token hash first - if ( empty( $_POST[ 'domain_key' ] ) || ! isset( $_POST[ 'is_linked' ] ) ) { - return self::err( 'lack_of_param' ); + if (empty($_POST['domain_key']) || !isset($_POST['is_linked'])) { + return self::err('lack_of_param'); } try { - $this->_validate_hash( 1 ); - } catch( \Exception $e ) { - return self::err( $e->getMessage() ); + $this->validate_hash(1); + } catch (\Exception $e) { + return self::err($e->getMessage()); } // This doesn't need to sync QUIC conf but need to clear nodes - $this->cls( 'Conf' )->update_confs( array( self::O_API_KEY => $_POST[ 'domain_key' ] ) ); + $this->cls('Conf')->update_confs(array(self::O_API_KEY => $_POST['domain_key'])); - $this->_summary[ 'is_linked' ] = $_POST[ 'is_linked' ] ? 1 : 0; - $this->_summary[ 'apikey_ts' ] = time(); - if ( ! empty( $_POST[ 'main_domain' ] ) ) { - $this->_summary[ 'main_domain' ] = $_POST[ 'main_domain' ]; + $this->_summary['is_linked'] = $_POST['is_linked'] ? 1 : 0; + $this->_summary['apikey_ts'] = time(); + if (!empty($_POST['main_domain'])) { + $this->_summary['main_domain'] = $_POST['main_domain']; } // Clear token - unset( $this->_summary[ 'token' ] ); + unset($this->_summary['token']); self::save_summary(); - self::debug( '✅ saved auth_key' ); - Admin_Display::succeed( '🎊 ' . __( 'Congratulations, your Domain Key has been approved! The setting has been updated accordingly.', 'litespeed-cache' ) ); + self::debug('✅ saved auth_key'); + Admin_Display::succeed('🎊 ' . __('Congratulations, your Domain Key has been approved! The setting has been updated accordingly.', 'litespeed-cache')); return self::ok(); } @@ -1232,20 +1321,21 @@ public function save_apikey() { * * @since 3.0 */ - private function _validate_hash( $offset = 0 ) { - if ( empty( $_POST[ 'hash' ] ) ) { - self::debug( 'Lack of hash param' ); - throw new \Exception( 'lack_of_param' ); + public function validate_hash($offset = 0) + { + if (empty($_POST['hash'])) { + self::debug('Lack of hash param'); + throw new \Exception('lack_of_param'); } - if ( empty( $this->_summary[ 'token' ] ) ) { - self::debug( 'token validate failed: token not exist' ); - throw new \Exception( 'lack_of_local_token' ); + if (empty($this->_summary['token'])) { + self::debug('token validate failed: token not exist'); + throw new \Exception('lack_of_local_token'); } - if ( $_POST[ 'hash' ] !== md5( substr( $this->_summary[ 'token' ], $offset, 8 ) ) ) { - self::debug( 'token validate failed: token mismatch hash !== ' . $_POST[ 'hash' ] ); - throw new \Exception( 'mismatch' ); + if ($_POST['hash'] !== md5(substr($this->_summary['token'], $offset, 8))) { + self::debug('token validate failed: token mismatch hash !== ' . $_POST['hash']); + throw new \Exception('mismatch'); } } @@ -1254,8 +1344,9 @@ private function _validate_hash( $offset = 0 ) { * * @since 3.0 */ - public function can_link_qc() { - return empty( $this->_summary[ 'is_linked' ] ) && $this->_api_key; + public function can_link_qc() + { + return empty($this->_summary['is_linked']) && $this->_api_key(); } /** @@ -1263,24 +1354,39 @@ public function can_link_qc() { * * @since 3.0 */ - private function _link_to_qc() { - if ( ! $this->can_link_qc() ) { + private function _link_to_qc() + { + if (!$this->can_link_qc()) { return; } $data = array( - 'site_url' => home_url(), - 'domain_hash' => md5( substr( $this->_api_key, 0, 8 ) ), - 'ref' => get_admin_url( null, 'admin.php?page=litespeed-general' ), + 'site_url' => home_url(), + 'domain_hash' => md5(substr($this->_api_key(), 0, 8)), + 'ref' => get_admin_url(null, 'admin.php?page=litespeed-general'), ); - wp_redirect( self::CLOUD_SERVER_DASH . '/u/wp?data=' . Utility::arr2str( $data ) ); - exit; + wp_redirect(self::CLOUD_SERVER_DASH . '/u/wp?data=' . Utility::arr2str($data)); + exit(); } - public function set_linked() { - $this->_summary[ 'is_linked' ] = 1; + public function qc_link() + { + $data = array( + 'site_url' => home_url(), + 'domain_hash' => md5(substr($this->_api_key(), 0, 8)), + 'ver' => LSCWP_V, + ); + return self::CLOUD_SERVER_DASH . '/u/wp?data=' . Utility::arr2str($data); // . (!empty($this->_summary['is_linked']) ? '?wplogin=1' : ''); + } + + public function set_linked() + { + $this->_summary['is_linked'] = 1; self::save_summary(); + + # Force resync qc conf + $this->cls('CDN\Quic')->try_sync_conf(true); } /** @@ -1289,36 +1395,44 @@ public function set_linked() { * @since 3.0 * @since 5.0 renamed update_is_linked_status -> parse_qc_redir, add param for additional args. Return args if exist. */ - public function parse_qc_redir($extra = array()) { - + public function parse_qc_redir($extra = array()) + { $extraRet = array(); $qsDrop = array(); - if ( ! $this->_api_key && ! empty( $this->_summary[ 'is_linked' ] ) ) { - $this->_summary[ 'is_linked' ] = 0; + if (!$this->_api_key() && !empty($this->_summary['is_linked'])) { + $this->_summary['is_linked'] = 0; self::save_summary(); } - if ( empty( $_GET[ 'qc_res' ] ) ) { + if (empty($_GET['qc_res'])) { return $extraRet; } - $qsDrop[] = ".replace( '&qc_res=" . sanitize_key( $_GET[ 'qc_res' ] ) . ', \'\' )'; - if ( ! empty( $_GET[ 'domain_hash' ] ) ) { + if ($_GET['qc_res'] == 'registered') { + if (!empty($_GET['qc_new'])) { + Admin_Display::succeed(__('QUIC.cloud account has been created and successfully linked.', 'litespeed-cache'), true); + } else { + Admin_Display::succeed(__('QUIC.cloud account has been successfully linked.', 'litespeed-cache'), true); + } + } + + $qsDrop[] = ".replace( '&qc_res=" . sanitize_key($_GET['qc_res']) . ', \'\' )'; - if ( md5( substr( $this->_api_key, 2, 8 ) ) !== $_GET[ 'domain_hash' ] ) { - Admin_Display::error( __( 'Domain Key hash mismatch', 'litespeed-cache' ), true ); + if (!empty($_GET['domain_hash'])) { + if (md5(substr($this->_api_key(), 2, 8)) !== $_GET['domain_hash']) { + Admin_Display::error(__('Domain Key hash mismatch', 'litespeed-cache'), true); return $extraRet; } $this->set_linked(); - $qsDrop[] = ".replace( '&domain_hash=" . sanitize_key( $_GET[ 'domain_hash' ] ) . ', \'\' )'; + $qsDrop[] = ".replace( '&domain_hash=" . sanitize_key($_GET['domain_hash']) . ', \'\' )'; } - if ( ! empty( $extra ) ) { - foreach ( $extra as $key ) { - if ( ! empty( $_GET[ $key ] ) ) { - $extraRet[ $key ] = $_GET[ $key ]; - $qsDrop[] = ".replace( '&$key=" . urlencode( $_GET[ $key ] ) . ', \'\' )'; + if (!empty($extra)) { + foreach ($extra as $key) { + if (!empty($_GET[$key])) { + $extraRet[$key] = $_GET[$key]; + $qsDrop[] = ".replace( '&$key=" . urlencode($_GET[$key]) . ', \'\' )'; } } } @@ -1326,7 +1440,7 @@ public function parse_qc_redir($extra = array()) { $replaceStr = implode('', $qsDrop); // Drop QS - echo ""; + echo "'; return $extraRet; } @@ -1335,20 +1449,20 @@ public function parse_qc_redir($extra = array()) { * * @since 3.0 */ - public function is_from_cloud() { - if ( empty( $this->_summary[ 'ips' ] ) || empty( $this->_summary[ 'ips_ts' ] ) || time() - $this->_summary[ 'ips_ts' ] > 86400 * self::TTL_IPS ) { + public function is_from_cloud() + { + if (empty($this->_summary['ips']) || empty($this->_summary['ips_ts']) || time() - $this->_summary['ips_ts'] > 86400 * self::TTL_IPS) { $this->_update_ips(); } - $res = $this->cls( 'Router' )->ip_access( $this->_summary[ 'ips' ] ); - if ( ! $res ) { - self::debug( '❌ Not our cloud IP' ); + $res = $this->cls('Router')->ip_access($this->_summary['ips']); + if (!$res) { + self::debug('❌ Not our cloud IP'); // Refresh IP list for future detection $this->_update_ips(); - } - else { - self::debug( '✅ Passed Cloud IP verification' ); + } else { + self::debug('✅ Passed Cloud IP verification'); } return $res; @@ -1359,19 +1473,20 @@ public function is_from_cloud() { * * @since 4.2 */ - private function _update_ips() { - self::debug( 'Load remote Cloud IP list from ' . self::CLOUD_IPS ); + private function _update_ips() + { + self::debug('Load remote Cloud IP list from ' . self::CLOUD_IPS); - $response = wp_remote_get( self::CLOUD_IPS . '?json' ); - if ( is_wp_error( $response ) ) { + $response = wp_remote_get(self::CLOUD_IPS . '?json'); + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - self::debug( 'failed to get ip whitelist: ' . $error_message ); - throw new \Exception( 'Failed to fetch QUIC.cloud whitelist ' . $error_message ); + self::debug('failed to get ip whitelist: ' . $error_message); + throw new \Exception('Failed to fetch QUIC.cloud whitelist ' . $error_message); } - $json = json_decode( $response[ 'body' ], true ); + $json = json_decode($response['body'], true); - self::save_summary( array( 'ips_ts' => time(), 'ips' => $json ) ); + self::save_summary(array('ips_ts' => time(), 'ips' => $json)); } /** @@ -1379,8 +1494,9 @@ private function _update_ips() { * * @since 3.0 */ - public static function ok( $data = array() ) { - $data[ '_res' ] = 'ok'; + public static function ok($data = array()) + { + $data['_res'] = 'ok'; return $data; } @@ -1389,8 +1505,9 @@ public static function ok( $data = array() ) { * * @since 3.0 */ - public static function err( $code ) { - return array( '_res' => 'err', '_msg' => $code ); + public static function err($code) + { + return array('_res' => 'err', '_msg' => $code); } /** @@ -1399,17 +1516,18 @@ public static function err( $code ) { * @since 3.0 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_CLEAR_CLOUD: $this->clear_cloud(); break; case self::TYPE_REDETECT_CLOUD: - if ( ! empty( $_GET[ 'svc' ] ) ) { - $this->detect_cloud( $_GET[ 'svc' ], true ); + if (!empty($_GET['svc'])) { + $this->detect_cloud($_GET['svc'], true); } break; @@ -1428,8 +1546,8 @@ public function handler() { case self::TYPE_SYNC_USAGE: $this->sync_usage(); - $msg = __( 'Sync credit allowance with Cloud Server successfully.', 'litespeed-cache' ) ; - Admin_Display::succeed( $msg ) ; + $msg = __('Sync credit allowance with Cloud Server successfully.', 'litespeed-cache'); + Admin_Display::succeed($msg); break; default: diff --git a/src/conf.cls.php b/src/conf.cls.php index 7638da987..897b6fcce 100644 --- a/src/conf.cls.php +++ b/src/conf.cls.php @@ -1,4 +1,5 @@ */ -namespace LiteSpeed; -defined( 'WPINC' ) || exit; +namespace LiteSpeed; +defined('WPINC') || exit(); -class Conf extends Base { +class Conf extends Base +{ const TYPE_SET = 'set'; private $_updated_ids = array(); @@ -27,7 +29,8 @@ class Conf extends Base { * @since 3.0 * @access public */ - public function init() { + public function init() + { // Check if conf exists or not. If not, create them in DB (won't change version if is converting v2.9- data) // Conf may be stale, upgrade later $this->_conf_db_init(); @@ -36,12 +39,12 @@ public function init() { * Detect if has quic.cloud set * @since 2.9.7 */ - if ( $this->conf( self::O_CDN_QUIC ) ) { - ! defined( 'LITESPEED_ALLOWED' ) && define( 'LITESPEED_ALLOWED', true ); + if ($this->conf(self::O_CDN_QUIC)) { + !defined('LITESPEED_ALLOWED') && define('LITESPEED_ALLOWED', true); } - add_action( 'litespeed_conf_append', array( $this, 'option_append' ), 10, 2 ); - add_action( 'litespeed_conf_force', array( $this, 'force_option' ), 10, 2 ); + add_action('litespeed_conf_append', array($this, 'option_append'), 10, 2); + add_action('litespeed_conf_force', array($this, 'force_option'), 10, 2); $this->define_cache(); } @@ -52,7 +55,8 @@ public function init() { * @since 3.0 * @access private */ - private function _conf_db_init() { + private function _conf_db_init() + { /** * Try to load options first, network sites can override this later * @@ -60,25 +64,26 @@ private function _conf_db_init() { */ $this->load_options(); - $ver = $this->conf( self::_VER ); + $ver = $this->conf(self::_VER); /** * Don't upgrade or run new installations other than from backend visit at the 2nd time (delay the update) * In this case, just use default conf */ - $has_delay_conf_tag = self::get_option( '__activation' ); - if ( ! $ver || $ver != Core::VER ) { - if ( ( ! is_admin() && ! defined( 'LITESPEED_CLI' ) ) || ( ! $has_delay_conf_tag || $has_delay_conf_tag == -1 ) ) { // Reuse __activation to control the delay conf update - if ( ! $has_delay_conf_tag || $has_delay_conf_tag == -1 ) { - self::update_option( '__activation', Core::VER ); + $has_delay_conf_tag = self::get_option('__activation'); + if (!$ver || $ver != Core::VER) { + if ((!is_admin() && !defined('LITESPEED_CLI')) || (!$has_delay_conf_tag || $has_delay_conf_tag == -1)) { + // Reuse __activation to control the delay conf update + if (!$has_delay_conf_tag || $has_delay_conf_tag == -1) { + self::update_option('__activation', Core::VER); } - $this->set_conf( $this->load_default_vals() ); + $this->set_conf($this->load_default_vals()); $this->_try_load_site_options(); // Disable new installation auto upgrade to avoid overwritten to customized data.ini - if ( ! $ver ) { - defined( 'LITESPEED_BYPASS_AUTO_V' ) || define( 'LITESPEED_BYPASS_AUTO_V', true ); + if (!$ver) { + defined('LITESPEED_BYPASS_AUTO_V') || define('LITESPEED_BYPASS_AUTO_V', true); } return; } @@ -87,42 +92,42 @@ private function _conf_db_init() { /** * Version is less than v3.0, or, is a new installation */ - if ( ! $ver ) { + if (!$ver) { // Try upgrade first (network will upgrade inside too) Data::cls()->try_upgrade_conf_3_0(); - } - else { - defined( 'LSCWP_CUR_V' ) || define( 'LSCWP_CUR_V', $ver ); + } else { + defined('LSCWP_CUR_V') || define('LSCWP_CUR_V', $ver); /** * Upgrade conf */ - if ( $ver != Core::VER ) { + if ($ver != Core::VER) { // Plugin version will be set inside // Site plugin upgrade & version change will do in load_site_conf - Data::cls()->conf_upgrade( $ver ); + Data::cls()->conf_upgrade($ver); } } /** * Sync latest new options */ - if ( ! $ver || $ver != Core::VER ) { + if (!$ver || $ver != Core::VER) { // Load default values $this->load_default_vals(); - if ( ! $ver ) { // New install - $this->set_conf( self::$_default_options ); + if (!$ver) { + // New install + $this->set_conf(self::$_default_options); } // Init new default/missing options - foreach ( self::$_default_options as $k => $v ) { + foreach (self::$_default_options as $k => $v) { // If the option existed, bypass updating // Bcos we may ask clients to deactivate for debug temporarily, we need to keep the current cfg in deactivation, hence we need to only try adding default cfg when activating. - self::add_option( $k, $v ); + self::add_option($k, $v); } // Force correct version in case a rare unexpected case that `_ver` exists but empty - self::update_option( Base::_VER, Core::VER ); + self::update_option(Base::_VER, Core::VER); } /** @@ -133,21 +138,21 @@ private function _conf_db_init() { $this->_try_load_site_options(); // Mark as conf loaded - defined( 'LITESPEED_CONF_LOADED' ) || define( 'LITESPEED_CONF_LOADED', true ); + defined('LITESPEED_CONF_LOADED') || define('LITESPEED_CONF_LOADED', true); /** * Activation delayed file update * Pros: This is to avoid file correction script changed in new versions * Cons: Conf upgrade won't get file correction if there is new values that are used in file */ - if ( $has_delay_conf_tag && $has_delay_conf_tag != -1 ) { + if ($has_delay_conf_tag && $has_delay_conf_tag != -1) { // Check new version @since 2.9.3 - Cloud::version_check( 'activate' . ( defined( 'LSCWP_REF' ) ? '_' . LSCWP_REF : '' ) ); + Cloud::version_check('activate' . (defined('LSCWP_REF') ? '_' . LSCWP_REF : '')); $this->update_confs(); // Files only get corrected in activation or saving settings actions. } - if ( $has_delay_conf_tag != -1 ) { - self::update_option( '__activation', -1 ); + if ($has_delay_conf_tag != -1) { + self::update_option('__activation', -1); } } @@ -157,42 +162,41 @@ private function _conf_db_init() { * @since 3.0 * @access public */ - public function load_options( $blog_id = null, $dry_run = false ) { + public function load_options($blog_id = null, $dry_run = false) + { $options = array(); - foreach ( self::$_default_options as $k => $v ) { - if ( ! is_null( $blog_id ) ) { - $options[ $k ] = self::get_blog_option( $blog_id, $k, $v ); - } - else { - $options[ $k ] = self::get_option( $k, $v ); + foreach (self::$_default_options as $k => $v) { + if (!is_null($blog_id)) { + $options[$k] = self::get_blog_option($blog_id, $k, $v); + } else { + $options[$k] = self::get_option($k, $v); } // Correct value type - $options[ $k ] = $this->type_casting( $options[ $k ], $k ); + $options[$k] = $this->type_casting($options[$k], $k); } - if ( $dry_run ) { + if ($dry_run) { return $options; } // Bypass site special settings - if ( $blog_id !== null ) { // This is to load the primary settings ONLY + if ($blog_id !== null) { + // This is to load the primary settings ONLY // These options are the ones that can be overwritten by primary - $options = array_diff_key( $options, array_flip( self::$SINGLE_SITE_OPTIONS ) ); + $options = array_diff_key($options, array_flip(self::$SINGLE_SITE_OPTIONS)); - $this->set_primary_conf( $options ); - } - else { - $this->set_conf( $options ); + $this->set_primary_conf($options); + } else { + $this->set_conf($options); } - // Append const options - if ( defined( 'LITESPEED_CONF' ) && LITESPEED_CONF ) { - foreach ( self::$_default_options as $k => $v ) { - $const = Base::conf_const( $k ); - if ( defined( $const ) ) { - $this->set_const_conf( $k, $this->type_casting( constant( $const ), $k ) ); + if (defined('LITESPEED_CONF') && LITESPEED_CONF) { + foreach (self::$_default_options as $k => $v) { + $const = Base::conf_const($k); + if (defined($const)) { + $this->set_const_conf($k, $this->type_casting(constant($const), $k)); } } } @@ -204,8 +208,9 @@ public function load_options( $blog_id = null, $dry_run = false ) { * @since 1.0.13 * @access private */ - private function _try_load_site_options() { - if ( ! $this->_if_need_site_options() ) { + private function _try_load_site_options() + { + if (!$this->_if_need_site_options()) { return; } @@ -214,36 +219,36 @@ private function _try_load_site_options() { $this->_is_primary = get_current_blog_id() == BLOG_ID_CURRENT_SITE; // If network set to use primary setting - if ( $this->network_conf( self::NETWORK_O_USE_PRIMARY ) && ! $this->_is_primary ) { // subsites or network admin + if ($this->network_conf(self::NETWORK_O_USE_PRIMARY) && !$this->_is_primary) { + // subsites or network admin // Get the primary site settings // If it's just upgraded, 2nd blog is being visited before primary blog, can just load default config (won't hurt as this could only happen shortly) - $this->load_options( BLOG_ID_CURRENT_SITE ); + $this->load_options(BLOG_ID_CURRENT_SITE); } // Overwrite single blog options with site options - foreach ( self::$_default_options as $k => $v ) { - if ( ! $this->has_network_conf( $k ) ) { + foreach (self::$_default_options as $k => $v) { + if (!$this->has_network_conf($k)) { continue; } // $this->_options[ $k ] = $this->_network_options[ $k ]; // Special handler to `Enable Cache` option if the value is set to OFF - if ( $k == self::O_CACHE ) { - if ( $this->_is_primary ) { - if ( $this->conf( $k ) != $this->network_conf( $k ) ) { - if ( $this->conf( $k ) != self::VAL_ON2 ) { + if ($k == self::O_CACHE) { + if ($this->_is_primary) { + if ($this->conf($k) != $this->network_conf($k)) { + if ($this->conf($k) != self::VAL_ON2) { continue; } } - } - else { - if ( $this->network_conf( self::NETWORK_O_USE_PRIMARY ) ) { - if ( $this->has_primary_conf( $k ) && $this->primary_conf( $k ) != self::VAL_ON2 ) { // This case will use primary_options override always + } else { + if ($this->network_conf(self::NETWORK_O_USE_PRIMARY)) { + if ($this->has_primary_conf($k) && $this->primary_conf($k) != self::VAL_ON2) { + // This case will use primary_options override always continue; } - } - else { - if ( $this->conf( $k ) != self::VAL_ON2 ) { + } else { + if ($this->conf($k) != self::VAL_ON2) { continue; } } @@ -251,7 +256,7 @@ private function _try_load_site_options() { } // primary_options will store primary settings + network settings, OR, store the network settings for subsites - $this->set_primary_conf( $k, $this->network_conf( $k ) ); + $this->set_primary_conf($k, $this->network_conf($k)); } // var_dump($this->_options); } @@ -262,8 +267,9 @@ private function _try_load_site_options() { * @since 3.0 * @access private */ - private function _if_need_site_options() { - if ( ! is_multisite() ) { + private function _if_need_site_options() + { + if (!is_multisite()) { return false; } @@ -275,13 +281,14 @@ private function _if_need_site_options() { * @see https://codex.wordpress.org/Function_Reference/is_plugin_active_for_network * @since 2.0 */ - if ( ! function_exists( 'is_plugin_active_for_network' ) ) { - require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); + if (!function_exists('is_plugin_active_for_network')) { + require_once ABSPATH . '/wp-admin/includes/plugin.php'; } // If is not activated on network, it will not have site options - if ( ! is_plugin_active_for_network( Core::PLUGIN_FILE ) ) { - if ( (int)$this->conf( self::O_CACHE ) == self::VAL_ON2 ) { // Default to cache on - $this->set_conf( self::_CACHE, true ); + if (!is_plugin_active_for_network(Core::PLUGIN_FILE)) { + if ((int) $this->conf(self::O_CACHE) == self::VAL_ON2) { + // Default to cache on + $this->set_conf(self::_CACHE, true); } return false; } @@ -295,18 +302,19 @@ private function _if_need_site_options() { * @since 3.0 * @access private */ - private function _conf_site_db_init() { + private function _conf_site_db_init() + { $this->load_site_options(); - $ver = $this->network_conf( self::_VER ); + $ver = $this->network_conf(self::_VER); /** * Don't upgrade or run new installations other than from backend visit * In this case, just use default conf */ - if ( ! $ver || $ver != Core::VER ) { - if ( ! is_admin() && ! defined( 'LITESPEED_CLI' ) ) { - $this->set_network_conf( $this->load_default_site_vals() ); + if (!$ver || $ver != Core::VER) { + if (!is_admin() && !defined('LITESPEED_CLI')) { + $this->set_network_conf($this->load_default_site_vals()); return; } } @@ -314,22 +322,22 @@ private function _conf_site_db_init() { /** * Upgrade conf */ - if ( $ver && $ver != Core::VER ) { + if ($ver && $ver != Core::VER) { // Site plugin versin will change inside - Data::cls()->conf_site_upgrade( $ver ); + Data::cls()->conf_site_upgrade($ver); } /** * Is a new installation */ - if ( ! $ver || $ver != Core::VER ) { + if (!$ver || $ver != Core::VER) { // Load default values $this->load_default_site_vals(); // Init new default/missing options - foreach ( self::$_default_site_options as $k => $v ) { + foreach (self::$_default_site_options as $k => $v) { // If the option existed, bypass updating - self::add_site_option( $k, $v ); + self::add_site_option($k, $v); } } } @@ -342,16 +350,17 @@ private function _conf_site_db_init() { * @since 1.0.2 * @access public */ - public function load_site_options() { - if ( ! is_multisite() ) { + public function load_site_options() + { + if (!is_multisite()) { return null; } // Load all site options - foreach ( self::$_default_site_options as $k => $v ) { - $val = self::get_site_option( $k, $v ); - $val = $this->type_casting( $val, $k, true ); - $this->set_network_conf( $k, $val ); + foreach (self::$_default_site_options as $k => $v) { + $val = self::get_site_option($k, $v); + $val = $this->type_casting($val, $k, true); + $this->set_network_conf($k, $val); } } @@ -365,10 +374,11 @@ public function load_site_options() { * @since 3.0 * @access public */ - public function option_append( $name, $default ) { - self::$_default_options[ $name ] = $default; - $this->set_conf( $name, self::get_option( $name, $default ) ); - $this->set_conf( $name, $this->type_casting( $this->conf( $name ), $name ) ); + public function option_append($name, $default) + { + self::$_default_options[$name] = $default; + $this->set_conf($name, self::get_option($name, $default)); + $this->set_conf($name, $this->type_casting($this->conf($name), $name)); } /** @@ -377,20 +387,21 @@ public function option_append( $name, $default ) { * @since 2.6 * @access public */ - public function force_option( $k, $v ) { - if ( ! $this->has_conf( $k ) ) { + public function force_option($k, $v) + { + if (!$this->has_conf($k)) { return; } - $v = $this->type_casting( $v, $k ); + $v = $this->type_casting($v, $k); - if ( $this->conf( $k ) === $v ) { + if ($this->conf($k) === $v) { return; } - Debug2::debug( "[Conf] ** $k forced from " . var_export( $this->conf( $k ), true ) . ' to ' . var_export( $v, true ) ); + Debug2::debug("[Conf] ** $k forced from " . var_export($this->conf($k), true) . ' to ' . var_export($v, true)); - $this->set_conf( $k, $v ); + $this->set_conf($k, $v); } /** @@ -399,23 +410,24 @@ public function force_option( $k, $v ) { * @since 3.0 * @access public */ - public function define_cache() { + public function define_cache() + { // Init global const cache on setting - $this->set_conf( self::_CACHE, false ); - if ( (int) $this->conf( self::O_CACHE ) == self::VAL_ON || $this->conf( self::O_CDN_QUIC ) ) { - $this->set_conf( self::_CACHE, true ); + $this->set_conf(self::_CACHE, false); + if ((int) $this->conf(self::O_CACHE) == self::VAL_ON || $this->conf(self::O_CDN_QUIC)) { + $this->set_conf(self::_CACHE, true); } // Check network - if ( ! $this->_if_need_site_options() ) { + if (!$this->_if_need_site_options()) { // Set cache on $this->_define_cache_on(); return; } // If use network setting - if ( (int) $this->conf( self::O_CACHE ) == self::VAL_ON2 && $this->network_conf( self::O_CACHE ) ) { - $this->set_conf( self::_CACHE, true ); + if ((int) $this->conf(self::O_CACHE) == self::VAL_ON2 && $this->network_conf(self::O_CACHE)) { + $this->set_conf(self::_CACHE, true); } $this->_define_cache_on(); @@ -427,12 +439,13 @@ public function define_cache() { * @since 2.1 * @access private */ - private function _define_cache_on() { - if ( ! $this->conf( self::_CACHE ) ) { + private function _define_cache_on() + { + if (!$this->conf(self::_CACHE)) { return; } - defined( 'LITESPEED_ALLOWED' ) && ! defined( 'LITESPEED_ON' ) && define( 'LITESPEED_ON', true ); + defined('LITESPEED_ALLOWED') && !defined('LITESPEED_ON') && define('LITESPEED_ON', true); } /** @@ -442,9 +455,10 @@ private function _define_cache_on() { * @access public * @deprecated 4.0 Use $this->conf() instead */ - public static function val( $id, $ori = false ) { - error_log( 'Called deprecated function \LiteSpeed\Conf::val(). Please use API call instead.' ); - return self::cls()->conf( $id, $ori ); + public static function val($id, $ori = false) + { + error_log('Called deprecated function \LiteSpeed\Conf::val(). Please use API call instead.'); + return self::cls()->conf($id, $ori); } /** @@ -453,66 +467,66 @@ public static function val( $id, $ori = false ) { * @since 3.0 * @access public */ - public function update_confs( $the_matrix = false ) { - if ( $the_matrix ) { - foreach ( $the_matrix as $id => $val ) { - $this->update( $id, $val ); + public function update_confs($the_matrix = false) + { + if ($the_matrix) { + foreach ($the_matrix as $id => $val) { + $this->update($id, $val); } } - if ( $this->_updated_ids ) { - foreach ( $this->_updated_ids as $id ) { + if ($this->_updated_ids) { + foreach ($this->_updated_ids as $id) { // Special handler for QUIC.cloud domain key to clear all existing nodes - if ( $id == self::O_API_KEY ) { - $this->cls( 'Cloud' )->clear_cloud(); + if ($id == self::O_API_KEY) { + $this->cls('Cloud')->clear_cloud(); } // Special handler for crawler: reset sitemap when drop_domain setting changed - if ( $id == self::O_CRAWLER_DROP_DOMAIN ) { - $this->cls( 'Crawler_Map' )->empty_map(); + if ($id == self::O_CRAWLER_DROP_DOMAIN) { + $this->cls('Crawler_Map')->empty_map(); } // Check if need to do a purge all or not - if ( $this->_conf_purge_all( $id ) ) { - Purge::purge_all( 'conf changed [id] ' . $id ); + if ($this->_conf_purge_all($id)) { + Purge::purge_all('conf changed [id] ' . $id); } // Check if need to purge a tag - if ( $tag = $this->_conf_purge_tag( $id ) ) { - Purge::add( $tag ); + if ($tag = $this->_conf_purge_tag($id)) { + Purge::add($tag); } // Update cron - if ( $this->_conf_cron( $id ) ) { - $this->cls( 'Task' )->try_clean( $id ); + if ($this->_conf_cron($id)) { + $this->cls('Task')->try_clean($id); } // Reset crawler bypassed list when any of the options WebP replace, guest mode, or cache mobile got changed - if ( $id == self::O_IMG_OPTM_WEBP_REPLACE || $id == self::O_GUEST || $id == self::O_CACHE_MOBILE ) { - $this->cls( 'Crawler' )->clear_disabled_list(); + if ($id == self::O_IMG_OPTM_WEBP || $id == self::O_GUEST || $id == self::O_CACHE_MOBILE) { + $this->cls('Crawler')->clear_disabled_list(); } } } - do_action( 'litespeed_update_confs', $the_matrix ); + do_action('litespeed_update_confs', $the_matrix); // Update related tables - $this->cls( 'Data' )->correct_tb_existance(); + $this->cls('Data')->correct_tb_existance(); // Update related files - $this->cls( 'Activation' )->update_files(); + $this->cls('Activation')->update_files(); /** * CDN related actions - Cloudflare */ - $this->cls( 'CDN\Cloudflare' )->try_refresh_zone(); + $this->cls('CDN\Cloudflare')->try_refresh_zone(); /** * CDN related actions - QUIC.cloud * @since 2.3 */ - $this->cls( 'CDN\Quic' )->try_sync_conf(); - + $this->cls('CDN\Quic')->try_sync_conf(); } /** @@ -523,60 +537,69 @@ public function update_confs( $the_matrix = false ) { * @since 3.0 * @access public */ - public function update( $id, $val ) { + public function update($id, $val) + { // Bypassed this bcos $this->_options could be changed by force_option() // if ( $this->_options[ $id ] === $val ) { // return; // } - if ( $id == self::_VER ) { + if ($id == self::_VER) { return; } - if ( ! array_key_exists( $id, self::$_default_options ) ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Conf] Invalid option ID ' . $id ); + if ($id == self::O_SERVER_IP) { + if ($val && !Utility::valid_ipv4($val)) { + $msg = sprintf(__('Saving option failed. IPv4 only for %s.', 'litespeed-cache'), Lang::title(Base::O_SERVER_IP)); + Admin_Display::error($msg); + return; + } + } + + if (!array_key_exists($id, self::$_default_options)) { + defined('LSCWP_LOG') && Debug2::debug('[Conf] Invalid option ID ' . $id); return; } - if ( $val && $this->_conf_pswd( $id ) && ! preg_match( '/[^\*]/', $val ) ) { + if ($val && $this->_conf_pswd($id) && !preg_match('/[^\*]/', $val)) { return; } // Special handler for CDN Original URLs - if ( $id == self::O_CDN_ORI && ! $val ) { - $home_url = home_url( '/' ); - $parsed = parse_url( $home_url ); - $home_url = str_replace( $parsed[ 'scheme' ] . ':', '', $home_url ); + if ($id == self::O_CDN_ORI && !$val) { + $home_url = home_url('/'); + $parsed = parse_url($home_url); + $home_url = str_replace($parsed['scheme'] . ':', '', $home_url); $val = $home_url; } // Validate type - $val = $this->type_casting( $val, $id ); + $val = $this->type_casting($val, $id); // Save data - self::update_option( $id, $val ); + self::update_option($id, $val); // Handle purge if setting changed - if ( $this->conf( $id ) != $val ) { + if ($this->conf($id) != $val) { $this->_updated_ids[] = $id; // Check if need to fire a purge or not (Here has to stay inside `update()` bcos need comparing old value) - if ( $this->_conf_purge( $id ) ) { - $diff = array_diff( $val, $this->conf( $id ) ); - $diff2 = array_diff( $this->conf( $id ), $val ); - $diff = array_merge( $diff, $diff2 ); + if ($this->_conf_purge($id)) { + $diff = array_diff($val, $this->conf($id)); + $diff2 = array_diff($this->conf($id), $val); + $diff = array_merge($diff, $diff2); // If has difference - foreach ( $diff as $v ) { - $v = ltrim( $v, '^' ); - $v = rtrim( $v, '$' ); - $this->cls( 'Purge' )->purge_url( $v ); + foreach ($diff as $v) { + $v = ltrim($v, '^'); + $v = rtrim($v, '$'); + $this->cls('Purge')->purge_url($v); } } } // Update in-memory data - $this->set_conf( $id, $val ); + $this->set_conf($id, $val); } /** @@ -585,59 +608,55 @@ public function update( $id, $val ) { * @since 3.0 * @access public */ - public function network_update( $id, $val ) { - if ( ! array_key_exists( $id, self::$_default_site_options ) ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Conf] Invalid network option ID ' . $id ); + public function network_update($id, $val) + { + if (!array_key_exists($id, self::$_default_site_options)) { + defined('LSCWP_LOG') && Debug2::debug('[Conf] Invalid network option ID ' . $id); return; } - if ( $val && $this->_conf_pswd( $id ) && ! preg_match( '/[^\*]/', $val ) ) { + if ($val && $this->_conf_pswd($id) && !preg_match('/[^\*]/', $val)) { return; } // Validate type - if ( is_bool( self::$_default_site_options[ $id ] ) ) { - $max = $this->_conf_multi_switch( $id ); - if ( $max && $val > 1 ) { + if (is_bool(self::$_default_site_options[$id])) { + $max = $this->_conf_multi_switch($id); + if ($max && $val > 1) { $val %= $max + 1; - } - else { + } else { $val = (bool) $val; } - } - elseif ( is_array( self::$_default_site_options[ $id ] ) ) { + } elseif (is_array(self::$_default_site_options[$id])) { // from textarea input - if ( ! is_array( $val ) ) { - $val = Utility::sanitize_lines( $val, $this->_conf_filter( $id ) ); + if (!is_array($val)) { + $val = Utility::sanitize_lines($val, $this->_conf_filter($id)); } - } - elseif ( ! is_string( self::$_default_site_options[ $id ] ) ) { + } elseif (!is_string(self::$_default_site_options[$id])) { $val = (int) $val; - } - else { + } else { // Check if the string has a limit set - $val = $this->_conf_string_val( $id, $val ); + $val = $this->_conf_string_val($id, $val); } // Save data - self::update_site_option( $id, $val ); + self::update_site_option($id, $val); // Handle purge if setting changed - if ( $this->network_conf( $id ) != $val ) { + if ($this->network_conf($id) != $val) { // Check if need to do a purge all or not - if ( $this->_conf_purge_all( $id ) ) { - Purge::purge_all( '[Conf] Network conf changed [id] ' . $id ); + if ($this->_conf_purge_all($id)) { + Purge::purge_all('[Conf] Network conf changed [id] ' . $id); } // Update in-memory data - $this->set_network_conf( $id, $val ); + $this->set_network_conf($id, $val); } // No need to update cron here, Cron will register in each init - - if ( $this->has_conf( $id ) ) { - $this->set_conf( $id, $val ); + if ($this->has_conf($id)) { + $this->set_conf($id, $val); } } @@ -649,17 +668,21 @@ public function network_update( $id, $val ) { * @param string $role The user role * @return int The set value if already set */ - public function in_optm_exc_roles( $role = null ) { + public function in_optm_exc_roles($role = null) + { // Get user role - if ( $role === null ) { + if ($role === null) { $role = Router::get_role(); } - if ( ! $role ) { + if (!$role) { return false; } - return in_array( $role, $this->conf( self::O_OPTM_EXC_ROLES ) ) ? $role : false; + $roles = explode(',', $role); + $found = array_intersect($roles, $this->conf(self::O_OPTM_EXC_ROLES)); + + return $found ? implode(',', $found) : false; } /** @@ -668,48 +691,48 @@ public function in_optm_exc_roles( $role = null ) { * @since 2.9 * @access private */ - private function _set_conf() { + private function _set_conf() + { /** * NOTE: For URL Query String setting, * 1. If append lines to an array setting e.g. `cache-force_uri`, use `set[cache-force_uri][]=the_url`. * 2. If replace the array setting with one line, use `set[cache-force_uri]=the_url`. * 3. If replace the array setting with multi lines value, use 2 then 1. */ - if ( empty( $_GET[ self::TYPE_SET ] ) || ! is_array( $_GET[ self::TYPE_SET ] ) ) { + if (empty($_GET[self::TYPE_SET]) || !is_array($_GET[self::TYPE_SET])) { return; } $the_matrix = array(); - foreach ( $_GET[ self::TYPE_SET ] as $id => $v ) { - if ( ! $this->has_conf( $id ) ) { + foreach ($_GET[self::TYPE_SET] as $id => $v) { + if (!$this->has_conf($id)) { continue; } // Append new item to array type settings - if ( is_array( $v ) && is_array( $this->conf( $id ) ) ) { - $v = array_merge( $this->conf( $id ), $v ); + if (is_array($v) && is_array($this->conf($id))) { + $v = array_merge($this->conf($id), $v); - Debug2::debug( '[Conf] Appended to settings [' . $id . ']: ' . var_export( $v, true ) ); - } - else { - Debug2::debug( '[Conf] Set setting [' . $id . ']: ' . var_export( $v, true ) ); + Debug2::debug('[Conf] Appended to settings [' . $id . ']: ' . var_export($v, true)); + } else { + Debug2::debug('[Conf] Set setting [' . $id . ']: ' . var_export($v, true)); } - $the_matrix[ $id ] = $v; + $the_matrix[$id] = $v; } - if ( ! $the_matrix ) { + if (!$the_matrix) { return; } - $this->update_confs( $the_matrix ); + $this->update_confs($the_matrix); - $msg = __( 'Changed setting successfully.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + $msg = __('Changed setting successfully.', 'litespeed-cache'); + Admin_Display::succeed($msg); // Redirect if changed frontend URL - if ( ! empty( $_GET[ 'redirect' ] ) ) { - wp_redirect( $_GET[ 'redirect' ] ); + if (!empty($_GET['redirect'])) { + wp_redirect($_GET['redirect']); exit(); } } @@ -720,11 +743,12 @@ private function _set_conf() { * @since 2.9 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { - case self::TYPE_SET : + switch ($type) { + case self::TYPE_SET: $this->_set_conf(); break; diff --git a/src/control.cls.php b/src/control.cls.php index e2440d834..323475fe0 100644 --- a/src/control.cls.php +++ b/src/control.cls.php @@ -9,9 +9,12 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); + +class Control extends Root +{ + const LOG_TAG = '💵'; -class Control extends Root { const BM_CACHEABLE = 1; const BM_PRIVATE = 2; const BM_SHARED = 4; @@ -33,27 +36,28 @@ class Control extends Root { * * @since 1.6.2 */ - public function init() { + public function init() + { /** * Add vary filter for Role Excludes * @since 1.6.2 */ - add_filter( 'litespeed_vary', array( $this, 'vary_add_role_exclude' ) ); + add_filter('litespeed_vary', array($this, 'vary_add_role_exclude')); // 301 redirect hook - add_filter( 'wp_redirect', array( $this, 'check_redirect' ), 10, 2 ); + add_filter('wp_redirect', array($this, 'check_redirect'), 10, 2); // Load response header conf - $this->_response_header_ttls = $this->conf( Base::O_CACHE_TTL_STATUS ); - foreach ( $this->_response_header_ttls as $k => $v ) { - $v = explode( ' ', $v ); - if ( empty( $v[ 0 ] ) || empty( $v[ 1 ] ) ) { + $this->_response_header_ttls = $this->conf(Base::O_CACHE_TTL_STATUS); + foreach ($this->_response_header_ttls as $k => $v) { + $v = explode(' ', $v); + if (empty($v[0]) || empty($v[1])) { continue; } - $this->_response_header_ttls[ $v[ 0 ] ] = $v[ 1 ]; + $this->_response_header_ttls[$v[0]] = $v[1]; } - if ( $this->conf( Base::O_PURGE_STALE ) ) { + if ($this->conf(Base::O_PURGE_STALE)) { $this->set_stale(); } } @@ -64,9 +68,10 @@ public function init() { * @since 1.6.2 * @access public */ - public function vary_add_role_exclude( $vary ) { - if ( $this->in_cache_exc_roles() ) { - $vary[ 'role_exclude_cache' ] = 1; + public function vary_add_role_exclude($vary) + { + if ($this->in_cache_exc_roles()) { + $vary['role_exclude_cache'] = 1; } return $vary; @@ -81,17 +86,21 @@ public function vary_add_role_exclude( $vary ) { * @param string $role The user role * @return int The set value if already set */ - public function in_cache_exc_roles( $role = null ) { + public function in_cache_exc_roles($role = null) + { // Get user role - if ( $role === null ) { + if ($role === null) { $role = Router::get_role(); } - if ( ! $role ) { + if (!$role) { return false; } - return in_array( $role, $this->conf( Base::O_CACHE_EXC_ROLES ) ) ? $role : false; + $roles = explode(',', $role); + $found = array_intersect($roles, $this->conf(Base::O_CACHE_EXC_ROLES)); + + return $found ? implode(',', $found) : false; } /** @@ -101,32 +110,32 @@ public function in_cache_exc_roles( $role = null ) { * @since 1.1.3 * @access public */ - public function init_cacheable() { + public function init_cacheable() + { // Hook `wp` to mark default cacheable status // NOTE: Any process that does NOT run into `wp` hook will not get cacheable by default - add_action( 'wp', array( $this, 'set_cacheable' ), 5 ); + add_action('wp', array($this, 'set_cacheable'), 5); // Hook WP REST to be cacheable - if ( $this->conf( Base::O_CACHE_REST ) ) { - add_action( 'rest_api_init', array( $this, 'set_cacheable' ), 5 ); + if ($this->conf(Base::O_CACHE_REST)) { + add_action('rest_api_init', array($this, 'set_cacheable'), 5); } // Cache resources // NOTE: If any strange resource doesn't use normal WP logic `wp_loaded` hook, rewrite rule can handle it - $cache_res = $this->conf( Base::O_CACHE_RES ); - if ( $cache_res ) { - $uri = esc_url( $_SERVER["REQUEST_URI"] );// todo: check if need esc_url() + $cache_res = $this->conf(Base::O_CACHE_RES); + if ($cache_res) { + $uri = esc_url($_SERVER['REQUEST_URI']); // todo: check if need esc_url() $pattern = '!' . LSCWP_CONTENT_FOLDER . Htaccess::RW_PATTERN_RES . '!'; - if ( preg_match( $pattern, $uri ) ) { - add_action( 'wp_loaded', array( $this, 'set_cacheable' ), 5 ); + if (preg_match($pattern, $uri)) { + add_action('wp_loaded', array($this, 'set_cacheable'), 5); } } // Check error page - add_filter( 'status_header', array( $this, 'check_error_codes' ), 10, 2 ); + add_filter('status_header', array($this, 'check_error_codes'), 10, 2); } - /** * Check if the page returns any error code. * @@ -136,18 +145,23 @@ public function init_cacheable() { * @param $code * @return $eror_status */ - public function check_error_codes( $status_header, $code ) { - if ( array_key_exists( $code, $this->_response_header_ttls ) ) { - if ( self::is_cacheable() && ! $this->_response_header_ttls[ $code ] ) { - self::set_nocache( '[Ctrl] TTL is set to no cache [status_header] ' . $code ); + public function check_error_codes($status_header, $code) + { + if (array_key_exists($code, $this->_response_header_ttls)) { + if (self::is_cacheable() && !$this->_response_header_ttls[$code]) { + self::set_nocache('[Ctrl] TTL is set to no cache [status_header] ' . $code); } // Set TTL - self::set_custom_ttl( $this->_response_header_ttls[ $code ] ); + self::set_custom_ttl($this->_response_header_ttls[$code]); + } elseif (self::is_cacheable()) { + if (substr($code, 0, 1) == 4 || substr($code, 0, 1) == 5) { + self::set_nocache('[Ctrl] 4xx/5xx default to no cache [status_header] ' . $code); + } } // Set cache tag - Tag::add( Tag::TYPE_HTTP . $code ); + Tag::add(Tag::TYPE_HTTP . $code); // Give the default status_header back return $status_header; @@ -159,12 +173,13 @@ public function check_error_codes( $status_header, $code ) { * @access public * @since 1.1.3 */ - public static function set_no_vary() { - if ( self::is_no_vary() ) { + public static function set_no_vary() + { + if (self::is_no_vary()) { return; } self::$_control |= self::BM_NO_VARY; - Debug2::debug( '[Ctrl] X Cache_control -> no-vary', 3 ); + Debug2::debug('[Ctrl] X Cache_control -> no-vary', 3); } /** @@ -173,7 +188,8 @@ public static function set_no_vary() { * @access public * @since 1.1.3 */ - public static function is_no_vary() { + public static function is_no_vary() + { return self::$_control & self::BM_NO_VARY; } @@ -183,8 +199,9 @@ public static function is_no_vary() { * @access public * @since 1.1.3 */ - public function set_stale() { - if ( self::is_stale() ) { + public function set_stale() + { + if (self::is_stale()) { return; } self::$_control |= self::BM_STALE; @@ -197,7 +214,8 @@ public function set_stale() { * @access public * @since 1.1.3 */ - public static function is_stale() { + public static function is_stale() + { return self::$_control & self::BM_STALE; } @@ -208,21 +226,22 @@ public static function is_stale() { * @since 1.1.3 * @param string $reason The reason to no cache */ - public static function set_shared( $reason = false ) { - if ( self::is_shared() ) { + public static function set_shared($reason = false) + { + if (self::is_shared()) { return; } self::$_control |= self::BM_SHARED; self::set_private(); - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = "( $reason )"; } - Debug2::debug( '[Ctrl] X Cache_control -> shared ' . $reason ); + Debug2::debug('[Ctrl] X Cache_control -> shared ' . $reason); } /** @@ -231,8 +250,9 @@ public static function set_shared( $reason = false ) { * @access public * @since 1.1.3 */ - public static function is_shared() { - return (self::$_control & self::BM_SHARED) && self::is_private(); + public static function is_shared() + { + return self::$_control & self::BM_SHARED && self::is_private(); } /** @@ -241,20 +261,21 @@ public static function is_shared() { * @access public * @since 1.7.1 */ - public static function set_public_forced( $reason = false ) { - if ( self::is_public_forced() ) { + public static function set_public_forced($reason = false) + { + if (self::is_public_forced()) { return; } self::$_control |= self::BM_PUBLIC_FORCED; - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = "( $reason )"; } - Debug2::debug( '[Ctrl] X Cache_control -> public forced ' . $reason ); + Debug2::debug('[Ctrl] X Cache_control -> public forced ' . $reason); } /** @@ -263,7 +284,8 @@ public static function set_public_forced( $reason = false ) { * @access public * @since 1.7.1 */ - public static function is_public_forced() { + public static function is_public_forced() + { return self::$_control & self::BM_PUBLIC_FORCED; } @@ -274,20 +296,21 @@ public static function is_public_forced() { * @since 1.1.3 * @param string $reason The reason to no cache */ - public static function set_private( $reason = false ) { - if ( self::is_private() ) { + public static function set_private($reason = false) + { + if (self::is_private()) { return; } self::$_control |= self::BM_PRIVATE; - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = "( $reason )"; } - Debug2::debug( '[Ctrl] X Cache_control -> private ' . $reason ); + Debug2::debug('[Ctrl] X Cache_control -> private ' . $reason); } /** @@ -296,12 +319,13 @@ public static function set_private( $reason = false ) { * @access public * @since 1.1.3 */ - public static function is_private() { - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST ) { + public static function is_private() + { + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { // return false; } - return self::$_control & self::BM_PRIVATE && ! self::is_public_forced(); + return self::$_control & self::BM_PRIVATE && !self::is_public_forced(); } /** @@ -310,17 +334,18 @@ public static function is_private() { * @access public * @since 1.1.3 */ - public function set_cacheable( $reason = false ) { + public function set_cacheable($reason = false) + { self::$_control |= self::BM_CACHEABLE; - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = ' [reason] ' . $reason; } - Debug2::debug( '[Ctrl] X Cache_control init on' . $reason ); + Debug2::debug('[Ctrl] X Cache_control init on' . $reason); } /** @@ -329,17 +354,18 @@ public function set_cacheable( $reason = false ) { * @access public * @since 2.2 */ - public static function force_cacheable( $reason = false ) { + public static function force_cacheable($reason = false) + { self::$_control |= self::BM_FORCED_CACHEABLE; - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = ' [reason] ' . $reason; } - Debug2::debug( '[Ctrl] Forced cacheable' . $reason ); + Debug2::debug('[Ctrl] Forced cacheable' . $reason); } /** @@ -349,17 +375,18 @@ public static function force_cacheable( $reason = false ) { * @since 1.1.3 * @param string $reason The reason to no cache */ - public static function set_nocache( $reason = false ) { + public static function set_nocache($reason = false) + { self::$_control |= self::BM_NOTCACHEABLE; - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = "( $reason )"; } - Debug2::debug( '[Ctrl] X Cache_control -> no Cache ' . $reason, 5 ); + Debug2::debug('[Ctrl] X Cache_control -> no Cache ' . $reason, 5); } /** @@ -369,7 +396,8 @@ public static function set_nocache( $reason = false ) { * @since 1.1.3 * @return bool True if notcacheable bit is set, otherwise false. */ - public static function isset_notcacheable() { + public static function isset_notcacheable() + { return self::$_control & self::BM_NOTCACHEABLE; } @@ -379,7 +407,8 @@ public static function isset_notcacheable() { * @access public * @since 2.2 */ - public static function is_forced_cacheable() { + public static function is_forced_cacheable() + { return self::$_control & self::BM_FORCED_CACHEABLE; } @@ -390,28 +419,29 @@ public static function is_forced_cacheable() { * @since 1.1.3 * @return bool True if is still cacheable, otherwise false. */ - public static function is_cacheable() { - if ( defined( 'LSCACHE_NO_CACHE' ) && LSCACHE_NO_CACHE ) { - Debug2::debug( '[Ctrl] LSCACHE_NO_CACHE constant defined' ); + public static function is_cacheable() + { + if (defined('LSCACHE_NO_CACHE') && LSCACHE_NO_CACHE) { + Debug2::debug('[Ctrl] LSCACHE_NO_CACHE constant defined'); return false; } // Guest mode always cacheable - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST ) { + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { // return true; } // If its forced public cacheable - if ( self::is_public_forced() ) { + if (self::is_public_forced()) { return true; } // If its forced cacheable - if ( self::is_forced_cacheable() ) { + if (self::is_forced_cacheable()) { return true; } - return ! self::isset_notcacheable() && self::$_control & self::BM_CACHEABLE; + return !self::isset_notcacheable() && self::$_control & self::BM_CACHEABLE; } /** @@ -421,10 +451,11 @@ public static function is_cacheable() { * @since 1.1.3 * @param mixed $ttl An integer or string to use as the TTL. Must be numeric. */ - public static function set_custom_ttl( $ttl, $reason = false ) { - if ( is_numeric( $ttl ) ) { + public static function set_custom_ttl($ttl, $reason = false) + { + if (is_numeric($ttl)) { self::$_custom_ttl = $ttl; - Debug2::debug( '[Ctrl] X Cache_control TTL -> ' . $ttl . ( $reason ? ' [reason] ' . $ttl : '' ) ); + Debug2::debug('[Ctrl] X Cache_control TTL -> ' . $ttl . ($reason ? ' [reason] ' . $ttl : '')); } } @@ -434,32 +465,32 @@ public static function set_custom_ttl( $ttl, $reason = false ) { * @access public * @since 1.1.3 */ - public function get_ttl() { - if ( self::$_custom_ttl != 0 ) { + public function get_ttl() + { + if (self::$_custom_ttl != 0) { return self::$_custom_ttl; } // Check if is in timed url list or not - $timed_urls = Utility::wildcard2regex( $this->conf( Base::O_PURGE_TIMED_URLS ) ); - $timed_urls_time = $this->conf( Base::O_PURGE_TIMED_URLS_TIME ); - if ( $timed_urls && $timed_urls_time ) { - $current_url = Tag::build_uri_tag( true ); + $timed_urls = Utility::wildcard2regex($this->conf(Base::O_PURGE_TIMED_URLS)); + $timed_urls_time = $this->conf(Base::O_PURGE_TIMED_URLS_TIME); + if ($timed_urls && $timed_urls_time) { + $current_url = Tag::build_uri_tag(true); // Use time limit ttl - $scheduled_time = strtotime( $timed_urls_time ); + $scheduled_time = strtotime($timed_urls_time); $ttl = $scheduled_time - time(); - if ( $ttl < 0 ) { - $ttl += 86400;// add one day + if ($ttl < 0) { + $ttl += 86400; // add one day } - foreach ( $timed_urls as $v ) { - if ( strpos( $v, '*' ) !== false ) { - if( preg_match( '#' . $v . '#iU', $current_url ) ) { - Debug2::debug( '[Ctrl] X Cache_control TTL is limited to ' . $ttl . ' due to scheduled purge regex ' . $v ); + foreach ($timed_urls as $v) { + if (strpos($v, '*') !== false) { + if (preg_match('#' . $v . '#iU', $current_url)) { + Debug2::debug('[Ctrl] X Cache_control TTL is limited to ' . $ttl . ' due to scheduled purge regex ' . $v); return $ttl; } - } - else { - if ( $v == $current_url ) { - Debug2::debug( '[Ctrl] X Cache_control TTL is limited to ' . $ttl . ' due to scheduled purge rule ' . $v ); + } else { + if ($v == $current_url) { + Debug2::debug('[Ctrl] X Cache_control TTL is limited to ' . $ttl . ' due to scheduled purge rule ' . $v); return $ttl; } } @@ -467,24 +498,24 @@ public function get_ttl() { } // Private cache uses private ttl setting - if ( self::is_private() ) { - return $this->conf( Base::O_CACHE_TTL_PRIV ); + if (self::is_private()) { + return $this->conf(Base::O_CACHE_TTL_PRIV); } - if ( is_front_page() ){ - return $this->conf( Base::O_CACHE_TTL_FRONTPAGE ); + if (is_front_page()) { + return $this->conf(Base::O_CACHE_TTL_FRONTPAGE); } - $feed_ttl = $this->conf( Base::O_CACHE_TTL_FEED ); - if ( is_feed() && $feed_ttl > 0 ) { + $feed_ttl = $this->conf(Base::O_CACHE_TTL_FEED); + if (is_feed() && $feed_ttl > 0) { return $feed_ttl; } - if ( $this->cls( 'REST' )->is_rest() || $this->cls( 'REST' )->is_internal_rest() ) { - return $this->conf( Base::O_CACHE_TTL_REST ); + if ($this->cls('REST')->is_rest() || $this->cls('REST')->is_internal_rest()) { + return $this->conf(Base::O_CACHE_TTL_REST); } - return $this->conf( Base::O_CACHE_TTL_PUB ); + return $this->conf(Base::O_CACHE_TTL_PUB); } /** @@ -493,30 +524,38 @@ public function get_ttl() { * @access public * @since 1.1.3 */ - public function check_redirect( $location, $status ) { // TODO: some env don't have SCRIPT_URI but only REQUEST_URI, need to be compatible - if ( ! empty( $_SERVER[ 'SCRIPT_URI' ] ) ) { // dont check $status == '301' anymore - Debug2::debug( "[Ctrl] 301 from " . $_SERVER[ 'SCRIPT_URI' ] ); - Debug2::debug( "[Ctrl] 301 to $location" ); - - $to_check = array( - PHP_URL_SCHEME, - PHP_URL_HOST, - PHP_URL_PATH, - PHP_URL_QUERY, - ); + public function check_redirect($location, $status) + { + // TODO: some env don't have SCRIPT_URI but only REQUEST_URI, need to be compatible + if (!empty($_SERVER['SCRIPT_URI'])) { + // dont check $status == '301' anymore + self::debug('301 from ' . $_SERVER['SCRIPT_URI']); + self::debug("301 to $location"); + + $to_check = array(PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PATH, PHP_URL_QUERY); $is_same_redirect = true; - foreach ( $to_check as $v ) { - if ( parse_url( $_SERVER[ 'SCRIPT_URI' ], $v ) != parse_url( $location, $v ) ) { + foreach ($to_check as $v) { + $url_parsed = $v == PHP_URL_QUERY ? $_SERVER['QUERY_STRING'] : parse_url($_SERVER['SCRIPT_URI'], $v); + $target = parse_url($location, $v); + + self::debug("Compare [from] $url_parsed [to] $target"); + + if ($v == PHP_URL_QUERY) { + $url_parsed = urldecode($url_parsed); + $target = urldecode($target); + } + + if ($url_parsed != $target) { $is_same_redirect = false; - Debug2::debug( "[Ctrl] 301 different redirection" ); + self::debug('301 different redirection'); break; } } - if ( $is_same_redirect ) { - self::set_nocache( '301 to same url' ); + if ($is_same_redirect) { + self::set_nocache('301 to same url'); } } @@ -530,16 +569,17 @@ public function check_redirect( $location, $status ) { // TODO: some env don't h * @access public * @return string empty string if empty, otherwise the cache control header. */ - public function output() { + public function output() + { $esi_hdr = ''; - if ( ESI::has_esi() ) { + if (ESI::has_esi()) { $esi_hdr = ',esi=on'; } $hdr = self::X_HEADER . ': '; - if ( defined( 'DONOTCACHEPAGE' ) && apply_filters( 'litespeed_const_DONOTCACHEPAGE', DONOTCACHEPAGE ) ) { - Debug2::debug( "[Ctrl] ❌ forced no cache [reason] DONOTCACHEPAGE const" ); + if (defined('DONOTCACHEPAGE') && apply_filters('litespeed_const_DONOTCACHEPAGE', DONOTCACHEPAGE)) { + Debug2::debug('[Ctrl] ❌ forced no cache [reason] DONOTCACHEPAGE const'); $hdr .= 'no-cache' . $esi_hdr; return $hdr; } @@ -567,22 +607,20 @@ public function output() { // Fix cli `uninstall --deactivate` fatal err - if ( ! self::is_cacheable() ) { + if (!self::is_cacheable()) { $hdr .= 'no-cache' . $esi_hdr; return $hdr; } - if ( self::is_shared() ) { + if (self::is_shared()) { $hdr .= 'shared,private'; - } - elseif ( self::is_private() ) { + } elseif (self::is_private()) { $hdr .= 'private'; - } - else { + } else { $hdr .= 'public'; } - if ( self::is_no_vary() ) { + if (self::is_no_vary()) { $hdr .= ',no-vary'; } @@ -596,105 +634,104 @@ public function output() { * @access public * @since 1.1.3 */ - public function finalize() { - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST ) { + public function finalize() + { + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { // return; } - if ( is_preview() ) { - self::set_nocache( 'preview page' ); + if (is_preview()) { + self::set_nocache('preview page'); return; } // Check if has metabox non-cacheable setting or not - if ( file_exists( LSCWP_DIR . 'src/metabox.cls.php' ) && $this->cls( 'Metabox' )->setting( 'litespeed_no_cache' ) ) { - self::set_nocache( 'per post metabox setting' ); + if (file_exists(LSCWP_DIR . 'src/metabox.cls.php') && $this->cls('Metabox')->setting('litespeed_no_cache')) { + self::set_nocache('per post metabox setting'); return; } // Check if URI is forced public cache - $excludes = $this->conf( Base::O_CACHE_FORCE_PUB_URI ); - $hit = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $excludes, true ); - if ( $hit ) { - list( $result, $this_ttl ) = $hit; - self::set_public_forced( 'Setting: ' . $result ); - Debug2::debug( '[Ctrl] Forced public cacheable due to setting: ' . $result ); - if ( $this_ttl ) { - self::set_custom_ttl( $this_ttl ); + $excludes = $this->conf(Base::O_CACHE_FORCE_PUB_URI); + $hit = Utility::str_hit_array($_SERVER['REQUEST_URI'], $excludes, true); + if ($hit) { + list($result, $this_ttl) = $hit; + self::set_public_forced('Setting: ' . $result); + Debug2::debug('[Ctrl] Forced public cacheable due to setting: ' . $result); + if ($this_ttl) { + self::set_custom_ttl($this_ttl); } } - if ( self::is_public_forced() ) { + if (self::is_public_forced()) { return; } // Check if URI is forced cache - $excludes = $this->conf( Base::O_CACHE_FORCE_URI ); - $hit = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $excludes, true ); - if ( $hit ) { - list( $result, $this_ttl ) = $hit; + $excludes = $this->conf(Base::O_CACHE_FORCE_URI); + $hit = Utility::str_hit_array($_SERVER['REQUEST_URI'], $excludes, true); + if ($hit) { + list($result, $this_ttl) = $hit; self::force_cacheable(); - Debug2::debug( '[Ctrl] Forced cacheable due to setting: ' . $result ); - if ( $this_ttl ) { - self::set_custom_ttl( $this_ttl ); + Debug2::debug('[Ctrl] Forced cacheable due to setting: ' . $result); + if ($this_ttl) { + self::set_custom_ttl($this_ttl); } } // if is not cacheable, terminate check // Even no need to run 3rd party hook - if ( ! self::is_cacheable() ) { - Debug2::debug( '[Ctrl] not cacheable before ctrl finalize' ); + if (!self::is_cacheable()) { + Debug2::debug('[Ctrl] not cacheable before ctrl finalize'); return; } // Apply 3rd party filter // NOTE: Hook always needs to run asap because some 3rd party set is_mobile in this hook - do_action('litespeed_control_finalize', defined( 'LSCACHE_IS_ESI' ) ? LSCACHE_IS_ESI : false ); // Pass ESI block id + do_action('litespeed_control_finalize', defined('LSCACHE_IS_ESI') ? LSCACHE_IS_ESI : false); // Pass ESI block id // if is not cacheable, terminate check - if ( ! self::is_cacheable() ) { - Debug2::debug( '[Ctrl] not cacheable after api_control' ); + if (!self::is_cacheable()) { + Debug2::debug('[Ctrl] not cacheable after api_control'); return; } // Check litespeed setting to set cacheable status - if ( ! $this->_setting_cacheable() ) { + if (!$this->_setting_cacheable()) { self::set_nocache(); return; } // If user has password cookie, do not cache (moved from vary) global $post; - if ( ! empty($post->post_password) && isset($_COOKIE['wp-postpass_' . COOKIEHASH]) ) { + if (!empty($post->post_password) && isset($_COOKIE['wp-postpass_' . COOKIEHASH])) { // If user has password cookie, do not cache self::set_nocache('pswd cookie'); return; } // The following check to the end is ONLY for mobile - $is_mobile = apply_filters( 'litespeed_is_mobile', false ); - if ( ! $this->conf( Base::O_CACHE_MOBILE ) ) { - if ( $is_mobile ) { - self::set_nocache( 'mobile' ); + $is_mobile = apply_filters('litespeed_is_mobile', false); + if (!$this->conf(Base::O_CACHE_MOBILE)) { + if ($is_mobile) { + self::set_nocache('mobile'); } return; } - $env_vary = isset( $_SERVER[ 'LSCACHE_VARY_VALUE' ] ) ? $_SERVER[ 'LSCACHE_VARY_VALUE' ] : false; - if ( ! $env_vary ) { - $env_vary = isset( $_SERVER[ 'HTTP_X_LSCACHE_VARY_VALUE' ] ) ? $_SERVER[ 'HTTP_X_LSCACHE_VARY_VALUE' ] : false; + $env_vary = isset($_SERVER['LSCACHE_VARY_VALUE']) ? $_SERVER['LSCACHE_VARY_VALUE'] : false; + if (!$env_vary) { + $env_vary = isset($_SERVER['HTTP_X_LSCACHE_VARY_VALUE']) ? $_SERVER['HTTP_X_LSCACHE_VARY_VALUE'] : false; } - if ( $env_vary && strpos( $env_vary, 'ismobile' ) !== false ) { - if ( ! wp_is_mobile() && ! $is_mobile ) { - self::set_nocache( 'is not mobile' ); // todo: no need to uncache, it will correct vary value in vary finalize anyways + if ($env_vary && strpos($env_vary, 'ismobile') !== false) { + if (!wp_is_mobile() && !$is_mobile) { + self::set_nocache('is not mobile'); // todo: no need to uncache, it will correct vary value in vary finalize anyways return; } - } - elseif ( wp_is_mobile() || $is_mobile ) { - self::set_nocache( 'is mobile' ); + } elseif (wp_is_mobile() || $is_mobile) { + self::set_nocache('is mobile'); return; } - } /** @@ -703,7 +740,8 @@ public function finalize() { * @since 3.0 * @access public */ - public static function is_mobile() { + public static function is_mobile() + { return wp_is_mobile(); } @@ -714,84 +752,85 @@ public static function is_mobile() { * @access private * @return boolean True if cacheable, false otherwise. */ - private function _setting_cacheable() { + private function _setting_cacheable() + { // logged_in users already excluded, no hook added - if( ! empty( $_REQUEST[ Router::ACTION ] ) ) { - return $this->_no_cache_for( 'Query String Action' ); + if (!empty($_REQUEST[Router::ACTION])) { + return $this->_no_cache_for('Query String Action'); } - if ( $_SERVER[ 'REQUEST_METHOD' ] !== 'GET' ) { - return $this->_no_cache_for('not GET method:' . $_SERVER["REQUEST_METHOD"]); + $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'unknown'; + if ('GET' !== $method && 'HEAD' !== $method) { + return $this->_no_cache_for('Not GET method: ' . $method); } - if ( is_feed() && $this->conf( Base::O_CACHE_TTL_FEED ) == 0 ) { + if (is_feed() && $this->conf(Base::O_CACHE_TTL_FEED) == 0) { return $this->_no_cache_for('feed'); } - if ( is_trackback() ) { + if (is_trackback()) { return $this->_no_cache_for('trackback'); } - if ( is_search() ) { + if (is_search()) { return $this->_no_cache_for('search'); } -// if ( !defined('WP_USE_THEMES') || !WP_USE_THEMES ) { -// return $this->_no_cache_for('no theme used'); -// } + // if ( !defined('WP_USE_THEMES') || !WP_USE_THEMES ) { + // return $this->_no_cache_for('no theme used'); + // } // Check private cache URI setting - $excludes = $this->conf( Base::O_CACHE_PRIV_URI ); - $result = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $excludes ); - if ( $result ) { - self::set_private( 'Admin cfg Private Cached URI: ' . $result ); + $excludes = $this->conf(Base::O_CACHE_PRIV_URI); + $result = Utility::str_hit_array($_SERVER['REQUEST_URI'], $excludes); + if ($result) { + self::set_private('Admin cfg Private Cached URI: ' . $result); } - if ( ! self::is_forced_cacheable() ) { - + if (!self::is_forced_cacheable()) { // Check if URI is excluded from cache - $excludes = $this->conf( Base::O_CACHE_EXC ); - $result = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $excludes ); - if ( $result ) { - return $this->_no_cache_for( 'Admin configured URI Do not cache: ' . $result ); + $excludes = $this->conf(Base::O_CACHE_EXC); + $result = Utility::str_hit_array($_SERVER['REQUEST_URI'], $excludes); + if ($result) { + return $this->_no_cache_for('Admin configured URI Do not cache: ' . $result); } // Check QS excluded setting - $excludes = $this->conf( Base::O_CACHE_EXC_QS ); - if ( ! empty( $excludes ) && $qs = $this->_is_qs_excluded( $excludes ) ) { - return $this->_no_cache_for( 'Admin configured QS Do not cache: ' . $qs ); + $excludes = $this->conf(Base::O_CACHE_EXC_QS); + if (!empty($excludes) && ($qs = $this->_is_qs_excluded($excludes))) { + return $this->_no_cache_for('Admin configured QS Do not cache: ' . $qs); } - $excludes = $this->conf( Base::O_CACHE_EXC_CAT ); - if ( ! empty( $excludes ) && has_category( $excludes ) ) { - return $this->_no_cache_for( 'Admin configured Category Do not cache.' ); + $excludes = $this->conf(Base::O_CACHE_EXC_CAT); + if (!empty($excludes) && has_category($excludes)) { + return $this->_no_cache_for('Admin configured Category Do not cache.'); } - $excludes = $this->conf( Base::O_CACHE_EXC_TAG ); - if ( ! empty( $excludes ) && has_tag( $excludes ) ) { - return $this->_no_cache_for( 'Admin configured Tag Do not cache.' ); + $excludes = $this->conf(Base::O_CACHE_EXC_TAG); + if (!empty($excludes) && has_tag($excludes)) { + return $this->_no_cache_for('Admin configured Tag Do not cache.'); } - $excludes = $this->conf( Base::O_CACHE_EXC_COOKIES ); - if ( ! empty( $excludes ) && ! empty( $_COOKIE ) ) { - $cookie_hit = array_intersect( array_keys( $_COOKIE ), $excludes ); - if ( $cookie_hit ) { - return $this->_no_cache_for( 'Admin configured Cookie Do not cache.' ); + $excludes = $this->conf(Base::O_CACHE_EXC_COOKIES); + if (!empty($excludes) && !empty($_COOKIE)) { + $cookie_hit = array_intersect(array_keys($_COOKIE), $excludes); + if ($cookie_hit) { + return $this->_no_cache_for('Admin configured Cookie Do not cache.'); } } - $excludes = $this->conf( Base::O_CACHE_EXC_USERAGENTS ); - if ( ! empty( $excludes ) && isset( $_SERVER[ 'HTTP_USER_AGENT' ] ) ) { - $nummatches = preg_match( Utility::arr2regex( $excludes ), $_SERVER[ 'HTTP_USER_AGENT' ] ); - if ( $nummatches ) { - return $this->_no_cache_for('Admin configured User Agent Do not cache.'); + $excludes = $this->conf(Base::O_CACHE_EXC_USERAGENTS); + if (!empty($excludes) && isset($_SERVER['HTTP_USER_AGENT'])) { + $nummatches = preg_match(Utility::arr2regex($excludes), $_SERVER['HTTP_USER_AGENT']); + if ($nummatches) { + return $this->_no_cache_for('Admin configured User Agent Do not cache.'); } } // Check if is exclude roles ( Need to set Vary too ) - if ( $result = $this->in_cache_exc_roles() ) { - return $this->_no_cache_for( 'Role Excludes setting ' . $result ); + if ($result = $this->in_cache_exc_roles()) { + return $this->_no_cache_for('Role Excludes setting ' . $result); } } @@ -806,7 +845,8 @@ private function _setting_cacheable() { * @param string $reason An explanation for why the page is not cacheable. * @return boolean Return false. */ - private function _no_cache_for( $reason ) { + private function _no_cache_for($reason) + { Debug2::debug('[Ctrl] X Cache_control off - ' . $reason); return false; } @@ -819,11 +859,11 @@ private function _no_cache_for( $reason ) { * @param array $excludes QS excludes setting * @return boolean|string False if not excluded, otherwise the hit qs list */ - private function _is_qs_excluded( $excludes ) { - if ( ! empty( $_GET ) && $intersect = array_intersect( array_keys( $_GET ), $excludes ) ) { - return implode( ',', $intersect ); + private function _is_qs_excluded($excludes) + { + if (!empty($_GET) && ($intersect = array_intersect(array_keys($_GET), $excludes))) { + return implode(',', $intersect); } return false; } - -} \ No newline at end of file +} diff --git a/src/core.cls.php b/src/core.cls.php index 15272cfc4..bd40ff0ff 100644 --- a/src/core.cls.php +++ b/src/core.cls.php @@ -1,4 +1,5 @@ cls( 'Conf' )->init(); + public function __construct() + { + !defined('LSCWP_TS_0') && define('LSCWP_TS_0', microtime(true)); + $this->cls('Conf')->init(); // Check if debug is on - if ( $this->conf( Base::O_DEBUG ) ) { - $this->cls( 'Debug2' )->init(); + if ($this->conf(Base::O_DEBUG)) { + $this->cls('Debug2')->init(); } /** * Load API hooks * @since 3.0 */ - $this->cls( 'API' )->init(); + $this->cls('API')->init(); - if ( defined( 'LITESPEED_ON' ) ) { + if (defined('LITESPEED_ON')) { // Load third party detection if lscache enabled. include_once LSCWP_DIR . 'thirdparty/entry.inc.php'; } - if ( $this->conf( Base::O_DEBUG_DISABLE_ALL ) ) { - ! defined( 'LITESPEED_DISABLE_ALL' ) && define( 'LITESPEED_DISABLE_ALL', true ); + if ($this->conf(Base::O_DEBUG_DISABLE_ALL)) { + !defined('LITESPEED_DISABLE_ALL') && define('LITESPEED_DISABLE_ALL', true); } /** @@ -70,37 +76,73 @@ public function __construct() { */ // if( is_admin() || defined( 'LITESPEED_CLI' ) ) { $plugin_file = LSCWP_DIR . 'litespeed-cache.php'; - register_activation_hook( $plugin_file, array( __NAMESPACE__ . '\Activation', 'register_activation' ) ); - register_deactivation_hook( $plugin_file, array(__NAMESPACE__ . '\Activation', 'register_deactivation' ) ); - register_uninstall_hook( $plugin_file, __NAMESPACE__ . '\Activation::uninstall_litespeed_cache' ); + register_activation_hook($plugin_file, array(__NAMESPACE__ . '\Activation', 'register_activation')); + register_deactivation_hook($plugin_file, array(__NAMESPACE__ . '\Activation', 'register_deactivation')); + register_uninstall_hook($plugin_file, __NAMESPACE__ . '\Activation::uninstall_litespeed_cache'); // } - add_action( 'plugins_loaded', array( $this, 'plugins_loaded' ) ); - add_action( 'after_setup_theme', array( $this, 'init' ) ); + add_action('plugins_loaded', array($this, 'plugins_loaded')); - // Check if there is a purge request in queue - $purge_queue = Purge::get_option( Purge::DB_QUEUE ); - if ( $purge_queue && $purge_queue != -1 ) { - @header( $purge_queue ); - Debug2::debug( '[Core] Purge Queue found&sent: ' . $purge_queue ); - } - if ( $purge_queue != -1 ) { - Purge::update_option( Purge::DB_QUEUE, -1 ); // Use 0 to bypass purge while still enable db update as WP's update_option will check value===false to bypass update - } - $purge_queue = Purge::get_option( Purge::DB_QUEUE2 ); - if ( $purge_queue && $purge_queue != -1 ) { - @header( $purge_queue ); - Debug2::debug( '[Core] Purge2 Queue found&sent: ' . $purge_queue ); + if (defined('LITESPEED_ON')) { + // register purge_all actions + $purge_all_events = $this->conf(Base::O_PURGE_HOOK_ALL); + + // purge all on upgrade + if ($this->conf(Base::O_PURGE_ON_UPGRADE)) { + $purge_all_events[] = 'automatic_updates_complete'; + $purge_all_events[] = 'upgrader_process_complete'; + $purge_all_events[] = 'admin_action_do-plugin-upgrade'; + } + foreach ($purge_all_events as $event) { + // Don't allow hook to update_option bcos purge_all will cause infinite loop of update_option + if (in_array($event, array('update_option'))) { + continue; + } + add_action($event, __NAMESPACE__ . '\Purge::purge_all'); + } + // add_filter( 'upgrader_pre_download', 'Purge::filter_with_purge_all' ); + + // Add headers to site health check for full page cache + // @since 5.4 + add_filter('site_status_page_cache_supported_cache_headers', function ($cache_headers) { + $is_cache_hit = function ($header_value) { + return false !== strpos(strtolower($header_value), 'hit'); + }; + $cache_headers['x-litespeed-cache'] = $is_cache_hit; + $cache_headers['x-lsadc-cache'] = $is_cache_hit; + $cache_headers['x-qc-cache'] = $is_cache_hit; + return $cache_headers; + }); } - if ( $purge_queue != -1 ) { - Purge::update_option( Purge::DB_QUEUE2, -1 ); + + add_action('after_setup_theme', array($this, 'init')); + + // Check if there is a purge request in queue + if (!defined('LITESPEED_CLI')) { + $purge_queue = Purge::get_option(Purge::DB_QUEUE); + if ($purge_queue && $purge_queue != -1) { + $this->_http_header($purge_queue); + Debug2::debug('[Core] Purge Queue found&sent: ' . $purge_queue); + } + if ($purge_queue != -1) { + Purge::update_option(Purge::DB_QUEUE, -1); // Use 0 to bypass purge while still enable db update as WP's update_option will check value===false to bypass update + } + + $purge_queue = Purge::get_option(Purge::DB_QUEUE2); + if ($purge_queue && $purge_queue != -1) { + $this->_http_header($purge_queue); + Debug2::debug('[Core] Purge2 Queue found&sent: ' . $purge_queue); + } + if ($purge_queue != -1) { + Purge::update_option(Purge::DB_QUEUE2, -1); + } } /** * Hook internal REST * @since 2.9.4 */ - $this->cls( 'REST' ); + $this->cls('REST'); /** * Hook wpnonce function @@ -108,8 +150,8 @@ public function __construct() { * Note: ESI nonce won't be available until hook after_setup_theme ESI init due to Guest Mode concern * @since v4.1 */ - if ( $this->cls( 'Router' )->esi_enabled() && ! function_exists( 'wp_create_nonce' ) ) { - Debug2::debug( '[ESI] Overwrite wp_create_nonce()' ); + if ($this->cls('Router')->esi_enabled() && !function_exists('wp_create_nonce')) { + Debug2::debug('[ESI] Overwrite wp_create_nonce()'); litespeed_define_nonce_func(); } } @@ -118,8 +160,9 @@ public function __construct() { * Plugin loaded hooks * @since 3.0 */ - public function plugins_loaded() { - load_plugin_textdomain( Core::PLUGIN_NAME, false, 'litespeed-cache/lang/' ); + public function plugins_loaded() + { + load_plugin_textdomain(Core::PLUGIN_NAME, false, 'litespeed-cache/lang/'); } /** @@ -132,64 +175,70 @@ public function plugins_loaded() { * @since 1.0.0 * @access public */ - public function init() { + public function init() + { /** * Added hook before init * 3rd party preload hooks will be fired here too (e.g. Divi disable all in edit mode) * @since 1.6.6 * @since 2.6 Added filter to all config values in Conf */ - do_action( 'litespeed_init' ); + do_action('litespeed_init'); + add_action('wp_ajax_async_litespeed', 'LiteSpeed\Task::async_litespeed_handler'); + add_action('wp_ajax_nopriv_async_litespeed', 'LiteSpeed\Task::async_litespeed_handler'); // in `after_setup_theme`, before `init` hook - if ( ! defined( 'LITESPEED_BYPASS_AUTO_V' ) ) { - $this->cls( 'Activation' )->auto_update(); + if (!defined('LITESPEED_BYPASS_AUTO_V')) { + $this->cls('Activation')->auto_update(); } - if( is_admin() ) { - $this->cls( 'Admin' ); + if (is_admin()) { + $this->cls('Admin'); } - if ( defined( 'LITESPEED_DISABLE_ALL' ) ) { - Debug2::debug( '[Core] Bypassed due to debug disable all setting' ); + if (defined('LITESPEED_DISABLE_ALL')) { + Debug2::debug('[Core] Bypassed due to debug disable all setting'); return; } - do_action( 'litespeed_initing' ); + do_action('litespeed_initing'); - ob_start( array( $this, 'send_headers_force' ) ); - add_action( 'shutdown', array( $this, 'send_headers' ), 0 ); - add_action( 'wp_footer', array( $this, 'footer_hook' ) ); + ob_start(array($this, 'send_headers_force')); + add_action('shutdown', array($this, 'send_headers'), 0); + add_action('wp_footer', array($this, 'footer_hook')); /** * Check if is non optm simulator * @since 2.9 */ - if ( ! empty( $_GET[ Router::ACTION ] ) && $_GET[ Router::ACTION ] == 'before_optm' && ! apply_filters( 'litespeed_qs_forbidden', false ) ) { - Debug2::debug( '[Core] ⛑️ bypass_optm due to QS CTRL' ); - ! defined( 'LITESPEED_NO_OPTM' ) && define( 'LITESPEED_NO_OPTM', true ); + if (!empty($_GET[Router::ACTION]) && $_GET[Router::ACTION] == 'before_optm' && !apply_filters('litespeed_qs_forbidden', false)) { + Debug2::debug('[Core] ⛑️ bypass_optm due to QS CTRL'); + !defined('LITESPEED_NO_OPTM') && define('LITESPEED_NO_OPTM', true); } /** * Register vary filter * @since 1.6.2 */ - $this->cls( 'Control' )->init(); + $this->cls('Control')->init(); // 1. Init vary // 2. Init cacheable status - $this->cls( 'Vary' )->init(); + $this->cls('Vary')->init(); // Init Purge hooks - $this->cls( 'Purge' )->init(); + $this->cls('Purge')->init(); - $this->cls( 'Tag' )->init(); + $this->cls('Tag')->init(); // Load hooks that may be related to users - add_action( 'init', array( $this, 'after_user_init' ), 5 ); + add_action('init', array($this, 'after_user_init'), 5); // Load 3rd party hooks - add_action( 'wp_loaded', array( $this, 'load_thirdparty' ), 2 ); + add_action('wp_loaded', array($this, 'load_thirdparty'), 2); + + // test: Simulate a purge all + // if (defined( 'LITESPEED_CLI' )) Purge::add('test'.date('Ymd.His')); } /** @@ -198,64 +247,64 @@ public function init() { * @since 2.9.8 * @access public */ - public function after_user_init() { - $this->cls( 'Router' )->is_role_simulation(); + public function after_user_init() + { + $this->cls('Router')->is_role_simulation(); // Detect if is Guest mode or not also - $this->cls( 'Vary' )->after_user_init(); + $this->cls('Vary')->after_user_init(); /** * Preload ESI functionality for ESI request uri recovery * @since 1.8.1 * @since 4.0 ESI init needs to be after Guest mode detection to bypass ESI if is under Guest mode */ - $this->cls( 'ESI' )->init(); + $this->cls('ESI')->init(); - if ( ! is_admin() && ! defined( 'LITESPEED_GUEST_OPTM' ) && $result = $this->cls( 'Conf' )->in_optm_exc_roles() ) { - Debug2::debug( '[Core] ⛑️ bypass_optm: hit Role Excludes setting: ' . $result ); - ! defined( 'LITESPEED_NO_OPTM' ) && define( 'LITESPEED_NO_OPTM', true ); + if (!is_admin() && !defined('LITESPEED_GUEST_OPTM') && ($result = $this->cls('Conf')->in_optm_exc_roles())) { + Debug2::debug('[Core] ⛑️ bypass_optm: hit Role Excludes setting: ' . $result); + !defined('LITESPEED_NO_OPTM') && define('LITESPEED_NO_OPTM', true); } // Heartbeat control - $this->cls( 'Tool' )->heartbeat(); + $this->cls('Tool')->heartbeat(); /** * Backward compatibility for v4.2- @Ruikai * TODO: Will change to hook in future versions to make it revertable */ - if ( defined( 'LITESPEED_BYPASS_OPTM' ) && ! defined( 'LITESPEED_NO_OPTM' ) ) { - defined( 'LITESPEED_NO_OPTM', LITESPEED_BYPASS_OPTM ); + if (defined('LITESPEED_BYPASS_OPTM') && !defined('LITESPEED_NO_OPTM')) { + defined('LITESPEED_NO_OPTM', LITESPEED_BYPASS_OPTM); } - if ( ! defined( 'LITESPEED_NO_OPTM' ) || ! LITESPEED_NO_OPTM ) { + if (!defined('LITESPEED_NO_OPTM') || !LITESPEED_NO_OPTM) { // Check missing static files - $this->cls( 'Router' )->serve_static(); + $this->cls('Router')->serve_static(); - $this->cls( 'Media' )->init(); + $this->cls('Media')->init(); - $this->cls( 'Placeholder' )->init(); + $this->cls('Placeholder')->init(); - $this->cls( 'Router' )->can_optm() && $this->cls( 'Optimize' )->init(); + $this->cls('Router')->can_optm() && $this->cls('Optimize')->init(); - $this->cls( 'Localization' )->init(); + $this->cls('Localization')->init(); // Hook cdn for attachements - $this->cls( 'CDN' )->init(); + $this->cls('CDN')->init(); // load cron tasks - $this->cls( 'Task' )->init(); + $this->cls('Task')->init(); } // load litespeed actions - if ( $action = Router::get_action() ) { - $this->proceed_action( $action ); + if ($action = Router::get_action()) { + $this->proceed_action($action); } // Load frontend GUI - if ( ! is_admin() ) { - $this->cls( 'GUI' )->init(); + if (!is_admin()) { + $this->cls('GUI')->init(); } - } /** @@ -264,10 +313,11 @@ public function after_user_init() { * @since 1.1.0 * @access public */ - public function proceed_action( $action ) { + public function proceed_action($action) + { $msg = false; // handle actions - switch ( $action ) { + switch ($action) { case self::ACTION_QS_PURGE: Purge::set_purge_related(); break; @@ -286,32 +336,32 @@ public function proceed_action( $action ) { case self::ACTION_PURGE_EMPTYCACHE: case self::ACTION_QS_PURGE_EMPTYCACHE: - define( 'LSWCP_EMPTYCACHE', true );// clear all sites caches + define('LSWCP_EMPTYCACHE', true); // clear all sites caches Purge::purge_all(); - $msg = __( 'Notified LiteSpeed Web Server to purge everything.', 'litespeed-cache' ); + $msg = __('Notified LiteSpeed Web Server to purge everything.', 'litespeed-cache'); break; case self::ACTION_PURGE_BY: - $this->cls( 'Purge' )->purge_list(); - $msg = __( 'Notified LiteSpeed Web Server to purge the list.', 'litespeed-cache' ); + $this->cls('Purge')->purge_list(); + $msg = __('Notified LiteSpeed Web Server to purge the list.', 'litespeed-cache'); break; - case self::ACTION_DISMISS:// Even its from ajax, we don't need to register wp ajax callback function but directly use our action + case self::ACTION_DISMISS: // Even its from ajax, we don't need to register wp ajax callback function but directly use our action GUI::dismiss(); break; default: - $msg = $this->cls( 'Router' )->handler( $action ); + $msg = $this->cls('Router')->handler($action); break; } - if ( $msg && ! Router::is_ajax() ) { - Admin_Display::add_notice( Admin_Display::NOTICE_GREEN, $msg ); + if ($msg && !Router::is_ajax()) { + Admin_Display::add_notice(Admin_Display::NOTICE_GREEN, $msg); Admin::redirect(); return; } - if ( Router::is_ajax() ) { - exit; + if (Router::is_ajax()) { + exit(); } } @@ -323,8 +373,9 @@ public function proceed_action( $action ) { * @since 1.0.5 * @access public */ - public function load_thirdparty() { - do_action( 'litespeed_load_thirdparty' ); + public function load_thirdparty() + { + do_action('litespeed_load_thirdparty'); } /** @@ -333,10 +384,11 @@ public function load_thirdparty() { * @since 1.3 * @access public */ - public function footer_hook() { - Debug2::debug( '[Core] Footer hook called' ); - if ( ! defined( 'LITESPEED_FOOTER_CALLED' ) ) { - define( 'LITESPEED_FOOTER_CALLED', true ); + public function footer_hook() + { + Debug2::debug('[Core] Footer hook called'); + if (!defined('LITESPEED_FOOTER_CALLED')) { + define('LITESPEED_FOOTER_CALLED', true); } } @@ -346,53 +398,54 @@ public function footer_hook() { * @since 1.3 * @access private */ - private function _check_is_html( $buffer = null ) { - if ( ! defined( 'LITESPEED_FOOTER_CALLED' ) ) { - Debug2::debug2( '[Core] CHK html bypass: miss footer const' ); + private function _check_is_html($buffer = null) + { + if (!defined('LITESPEED_FOOTER_CALLED')) { + Debug2::debug2('[Core] CHK html bypass: miss footer const'); return; } - if ( defined( 'DOING_AJAX' ) ) { - Debug2::debug2( '[Core] CHK html bypass: doing ajax' ); + if (defined('DOING_AJAX')) { + Debug2::debug2('[Core] CHK html bypass: doing ajax'); return; } - if ( defined( 'DOING_CRON' ) ) { - Debug2::debug2( '[Core] CHK html bypass: doing cron' ); + if (defined('DOING_CRON')) { + Debug2::debug2('[Core] CHK html bypass: doing cron'); return; } - if ( $_SERVER[ 'REQUEST_METHOD' ] !== 'GET' ) { - Debug2::debug2( '[Core] CHK html bypass: not get method ' . $_SERVER[ 'REQUEST_METHOD' ] ); + if ($_SERVER['REQUEST_METHOD'] !== 'GET') { + Debug2::debug2('[Core] CHK html bypass: not get method ' . $_SERVER['REQUEST_METHOD']); return; } - if ( $buffer === null ) { + if ($buffer === null) { $buffer = ob_get_contents(); } // double check to make sure it is a html file - if ( strlen( $buffer ) > 300 ) { - $buffer = substr( $buffer, 0, 300 ); + if (strlen($buffer) > 300) { + $buffer = substr($buffer, 0, 300); } - if ( strstr( $buffer, '/s', '', $buffer ); + if (strstr($buffer, '/s', '', $buffer); } - $buffer = trim( $buffer ); + $buffer = trim($buffer); - $buffer = File::remove_zero_space( $buffer ); + $buffer = File::remove_zero_space($buffer); - $is_html = stripos( $buffer, '_check_is_html( $buffer ); + public function send_headers_force($buffer) + { + $this->_check_is_html($buffer); // Hook to modify buffer before $buffer = apply_filters('litespeed_buffer_before', $buffer); @@ -418,20 +472,43 @@ public function send_headers_force( $buffer ) { * Optimize * CDN */ - if ( ! defined( 'LITESPEED_NO_OPTM' ) || ! LITESPEED_NO_OPTM ) { - $buffer = apply_filters( 'litespeed_buffer_finalize', $buffer ); + if (!defined('LITESPEED_NO_OPTM') || !LITESPEED_NO_OPTM) { + Debug2::debug('[Core] run hook litespeed_buffer_finalize'); + $buffer = apply_filters('litespeed_buffer_finalize', $buffer); } /** * Replace ESI preserved list * @since 3.3 Replace this in the end to avoid `Inline JS Defer` or other Page Optm features encoded ESI tags wrongly, which caused LSWS can't recognize ESI */ - $buffer = $this->cls( 'ESI' )->finalize( $buffer ); + $buffer = $this->cls('ESI')->finalize($buffer); + + $this->send_headers(true); - $this->send_headers( true ); + // Log ESI nonce buffer empty issue + if (defined('LSCACHE_IS_ESI') && strlen($buffer) == 0) { + // TODO: log ref somewhere + } - if ( $this->footer_comment ) { - $buffer .= $this->footer_comment; + // Init comment info + $running_info_showing = defined('LITESPEED_IS_HTML') || defined('LSCACHE_IS_ESI'); + if (defined('LSCACHE_ESI_SILENCE')) { + $running_info_showing = false; + Debug2::debug('[Core] ESI silence'); + } + /** + * Silence comment for json req + * @since 2.9.3 + */ + if (REST::cls()->is_rest() || Router::is_ajax()) { + $running_info_showing = false; + Debug2::debug('[Core] Silence Comment due to REST/AJAX'); + } + $running_info_showing = apply_filters('litespeed_comment', $running_info_showing); + if ($running_info_showing) { + if ($this->_footer_comment) { + $buffer .= $this->_footer_comment; + } } /** @@ -439,26 +516,23 @@ public function send_headers_force( $buffer ) { * @since 2.9.3 * @since 2.9.4 ESI req could be from internal REST call, so moved json_encode out of this cond */ - if ( defined( 'LSCACHE_IS_ESI' ) ) { - Debug2::debug( '[Core] ESI Start 👇' ); - if ( strlen( $buffer ) > 500 ) { - Debug2::debug( trim( substr( $buffer, 0, 500 ) ) . '.....' ); + if (defined('LSCACHE_IS_ESI')) { + Debug2::debug('[Core] ESI Start 👇'); + if (strlen($buffer) > 500) { + Debug2::debug(trim(substr($buffer, 0, 500)) . '.....'); + } else { + Debug2::debug($buffer); } - else { - Debug2::debug( $buffer ); - } - Debug2::debug( '[Core] ESI End 👆' ); - Debug2::debug( $buffer ); + Debug2::debug('[Core] ESI End 👆'); } - if ( apply_filters( 'litespeed_is_json', false ) ) { - if ( json_decode( $buffer, true ) == NULL ) { - Debug2::debug( '[Core] Buffer converting to JSON' ); - $buffer = json_encode( $buffer ); - $buffer = trim( $buffer, '"' ); - } - else { - Debug2::debug( '[Core] JSON Buffer' ); + if (apply_filters('litespeed_is_json', false)) { + if (json_decode($buffer, true) == null) { + Debug2::debug('[Core] Buffer converting to JSON'); + $buffer = json_encode($buffer); + $buffer = trim($buffer, '"'); + } else { + Debug2::debug('[Core] JSON Buffer'); } } @@ -479,148 +553,184 @@ public function send_headers_force( $buffer ) { * @access public * @param boolean $is_forced If the header is sent following our normal finalizing logic */ - public function send_headers( $is_forced = false ) { + public function send_headers($is_forced = false) + { // Make sure header output only run once - if ( ! defined( 'LITESPEED_DID_' . __FUNCTION__ ) ) { - define( 'LITESPEED_DID_' . __FUNCTION__, true ); + if (!defined('LITESPEED_DID_' . __FUNCTION__)) { + define('LITESPEED_DID_' . __FUNCTION__, true); + } else { + return; } - else { + + // Avoid PHP warning for header sent out already + if (headers_sent()) { + self::debug('❌ !!! Err: Header sent out already'); return; } $this->_check_is_html(); // NOTE: cache ctrl output needs to be done first, as currently some varies are added in 3rd party hook `litespeed_api_control`. - $this->cls( 'Control' )->finalize(); + $this->cls('Control')->finalize(); - $vary_header = $this->cls( 'Vary' )->finalize(); + $vary_header = $this->cls('Vary')->finalize(); // If is not cacheable but Admin QS is `purge` or `purgesingle`, `tag` still needs to be generated - $tag_header = $this->cls( 'Tag' )->output(); - if ( ! $tag_header && Control::is_cacheable() ) { - Control::set_nocache( 'empty tag header' ); + $tag_header = $this->cls('Tag')->output(); + if (!$tag_header && Control::is_cacheable()) { + Control::set_nocache('empty tag header'); } // NOTE: `purge` output needs to be after `tag` output as Admin QS may need to send `tag` header $purge_header = Purge::output(); // generate `control` header in the end in case control status is changed by other headers. - $control_header = $this->cls( 'Control' )->output(); + $control_header = $this->cls('Control')->output(); - // Init comment info - $running_info_showing = defined( 'LITESPEED_IS_HTML' ) || defined( 'LSCACHE_IS_ESI' ); - if ( defined( 'LSCACHE_ESI_SILENCE' ) ) { - $running_info_showing = false; - Debug2::debug( '[Core] ESI silence' ); - } - /** - * Silence comment for json req - * @since 2.9.3 - */ - if ( REST::cls()->is_rest() || Router::is_ajax() ) { - $running_info_showing = false; - Debug2::debug( '[Core] Silence Comment due to REST/AJAX' ); + // Give one more break to avoid ff crash + if (!defined('LSCACHE_IS_ESI')) { + $this->_footer_comment .= "\n"; } - $running_info_showing = apply_filters( 'litespeed_comment', $running_info_showing ); - - if ( $running_info_showing ) { - // Give one more break to avoid ff crash - if ( ! defined( 'LSCACHE_IS_ESI' ) ) { - $this->footer_comment .= "\n"; - } - - $cache_support = 'supported'; - if ( defined( 'LITESPEED_ON' ) ) { - $cache_support = Control::is_cacheable() ? 'generated' : 'uncached'; - } + $cache_support = 'supported'; + if (defined('LITESPEED_ON')) { + $cache_support = Control::is_cacheable() ? 'cached' : 'uncached'; + } - $this->footer_comment .= sprintf( - '', - defined( 'LSCACHE_IS_ESI' ) ? 'Block' : 'Page', + $this->_comment( + sprintf( + '%1$s %2$s by LiteSpeed Cache %4$s on %3$s', + defined('LSCACHE_IS_ESI') ? 'Block' : 'Page', $cache_support, - date( 'Y-m-d H:i:s', time() + LITESPEED_TIME_OFFSET ), + date('Y-m-d H:i:s', time() + LITESPEED_TIME_OFFSET), self::VER - ); - } + ) + ); // send Control header - if ( defined( 'LITESPEED_ON' ) && $control_header ) { - @header( $control_header ); - if ( defined( 'LSCWP_LOG' ) ) { - Debug2::debug( '💰 ' . $control_header ); - if ( $running_info_showing ) { - $this->footer_comment .= "\n"; - } + if (defined('LITESPEED_ON') && $control_header) { + $this->_http_header($control_header); + if (defined('LSCWP_LOG')) { + $this->_comment($control_header); } } // send PURGE header (Always send regardless of cache setting disabled/enabled) - if ( defined( 'LITESPEED_ON' ) && $purge_header ) { - @header( $purge_header ); - Debug2::log_purge( $purge_header ); - - if ( defined( 'LSCWP_LOG' ) ) { - Debug2::debug( '💰 ' . $purge_header ); - if ( $running_info_showing ) { - $this->footer_comment .= "\n"; - } + if (defined('LITESPEED_ON') && $purge_header) { + $this->_http_header($purge_header); + Debug2::log_purge($purge_header); + + if (defined('LSCWP_LOG')) { + $this->_comment($purge_header); } } // send Vary header - if ( defined( 'LITESPEED_ON' ) && $vary_header ) { - @header( $vary_header ); - if ( defined( 'LSCWP_LOG' ) ) { - Debug2::debug( '💰 ' . $vary_header ); - if ( $running_info_showing ) { - $this->footer_comment .= "\n"; - } + if (defined('LITESPEED_ON') && $vary_header) { + $this->_http_header($vary_header); + if (defined('LSCWP_LOG')) { + $this->_comment($vary_header); + } + } + + if (defined('LITESPEED_ON') && defined('LSCWP_LOG')) { + $vary = $this->cls('Vary')->finalize_full_varies(); + if ($vary) { + $this->_comment('Full varies: ' . $vary); } } // Admin QS show header action - if ( self::$_debug_show_header ) { + if (self::$_debug_show_header) { $debug_header = self::HEADER_DEBUG . ': '; - if ( $control_header ) { + if ($control_header) { $debug_header .= $control_header . '; '; } - if ( $purge_header ) { + if ($purge_header) { $debug_header .= $purge_header . '; '; } - if ( $tag_header ) { + if ($tag_header) { $debug_header .= $tag_header . '; '; } - if ( $vary_header ) { + if ($vary_header) { $debug_header .= $vary_header . '; '; } - @header( $debug_header ); - Debug2::debug( $debug_header ); - } - else { + $this->_http_header($debug_header); + } else { // Control header - if ( defined( 'LITESPEED_ON' ) && Control::is_cacheable() && $tag_header ) { - @header( $tag_header ); - if ( defined( 'LSCWP_LOG' ) ) { - Debug2::debug( '💰 ' . $tag_header ); - if ( $running_info_showing ) { - $this->footer_comment .= "\n"; - } + if (defined('LITESPEED_ON') && Control::is_cacheable() && $tag_header) { + $this->_http_header($tag_header); + if (defined('LSCWP_LOG')) { + $this->_comment($tag_header); } } } - // Object cache comment - if ( $running_info_showing && defined( 'LSCWP_LOG' ) && defined( 'LSCWP_OBJECT_CACHE' ) && method_exists( 'WP_Object_Cache', 'debug' ) ) { - $this->footer_comment .= "\n"; + // Object cache _comment + if (defined('LSCWP_LOG') && defined('LSCWP_OBJECT_CACHE') && method_exists('WP_Object_Cache', 'debug')) { + $this->_comment('Object Cache ' . \WP_Object_Cache::get_instance()->debug()); + } + + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { + $this->_comment('Guest Mode'); } - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST && $running_info_showing ) { - $this->footer_comment .= "\n"; + if ($is_forced) { + Debug2::debug('--forced--'); } - if ( $is_forced ) { - Debug2::debug( '--forced--' ); + /** + * If is CLI and contains Purge Header, then issue a HTTP req to Purge + * @since v5.3 + */ + if (defined('LITESPEED_CLI')) { + $purge_queue = Purge::get_option(Purge::DB_QUEUE); + if (!$purge_queue || $purge_queue == -1) { + $purge_queue = Purge::get_option(Purge::DB_QUEUE2); + } + if ($purge_queue && $purge_queue != -1) { + self::debug('[Core] Purge Queue found, issue a HTTP req to purge: ' . $purge_queue); + // Kick off HTTP req + $url = admin_url('admin-ajax.php'); + $resp = wp_remote_get($url); + if (is_wp_error($resp)) { + $error_message = $resp->get_error_message(); + self::debug('[URL]' . $url); + self::debug('failed to request: ' . $error_message); + } else { + self::debug('HTTP req res: ' . $resp['body']); + } + } } + } + + /** + * Append one HTML comment + * @since 5.5 + */ + public static function comment($data) + { + self::cls()->_comment($data); + } + private function _comment($data) + { + $this->_footer_comment .= "\n'; } + /** + * Send HTTP header + * @since 5.3 + */ + private function _http_header($header) + { + if (defined('LITESPEED_CLI')) { + return; + } + + @header($header); + + if (!defined('LSCWP_LOG')) { + return; + } + Debug2::debug('💰 ' . $header); + } } diff --git a/src/crawler-map.cls.php b/src/crawler-map.cls.php index bff60c188..633b10088 100644 --- a/src/crawler-map.cls.php +++ b/src/crawler-map.cls.php @@ -1,19 +1,26 @@ _home_url = get_home_url(); $this->__data = Data::cls(); - $this->_tb = $this->__data->tb( 'crawler' ); - $this->_tb_blacklist = $this->__data->tb( 'crawler_blacklist' ); - $this->_conf_map_timeout = $this->conf( Base::O_CRAWLER_MAP_TIMEOUT ); + $this->_tb = $this->__data->tb('crawler'); + $this->_tb_blacklist = $this->__data->tb('crawler_blacklist'); + $this->_conf_map_timeout = $this->conf(Base::O_CRAWLER_MAP_TIMEOUT); } /** @@ -37,94 +45,102 @@ public function __construct() { * @since 3.0 * @access public */ - public function save_map_status( $list, $curr_crawler ) { + public function save_map_status($list, $curr_crawler) + { global $wpdb; Utility::compatibility(); - $total_crawler = count( Crawler::cls()->list_crawlers() ); + $total_crawler = count(Crawler::cls()->list_crawlers()); $total_crawler_pos = $total_crawler - 1; // Replace current crawler's position $curr_crawler = (int) $curr_crawler; - foreach ( $list as $bit => $ids ) { // $ids = [ id => [ url, code ], ... ] - if ( ! $ids ) { + foreach ($list as $bit => $ids) { + // $ids = [ id => [ url, code ], ... ] + if (!$ids) { continue; } - Debug2::debug( "🐞🗺️ Update map [crawler] $curr_crawler [bit] $bit [count] " . count( $ids ) ); + self::debug("Update map [crawler] $curr_crawler [bit] $bit [count] " . count($ids)); // Update res first, then reason $right_pos = $total_crawler_pos - $curr_crawler; $sql_res = "CONCAT( LEFT( res, $curr_crawler ), '$bit', RIGHT( res, $right_pos ) )"; - $id_all = implode( ',', array_map( 'intval', array_keys( $ids ) ) ); + $id_all = implode(',', array_map('intval', array_keys($ids))); - $wpdb->query( "UPDATE `$this->_tb` SET res = $sql_res WHERE id IN ( $id_all )" ); + $wpdb->query("UPDATE `$this->_tb` SET res = $sql_res WHERE id IN ( $id_all )"); // Add blacklist - if ( $bit == 'B' || $bit == 'N' ) { + if ($bit == 'B' || $bit == 'N') { $q = "SELECT a.id, a.url FROM `$this->_tb_blacklist` a LEFT JOIN `$this->_tb` b ON b.url=a.url WHERE b.id IN ( $id_all )"; - $existing = $wpdb->get_results( $q, ARRAY_A ); + $existing = $wpdb->get_results($q, ARRAY_A); // Update current crawler status tag in existing blacklist - if ( $existing ) { - $count = $wpdb->query( "UPDATE `$this->_tb_blacklist` SET res = $sql_res WHERE id IN ( " . implode( ',', array_column( $existing, 'id' ) ) . " )" ); - Debug2::debug( '🐞🗺️ Update blacklist [count] ' . $count ); + if ($existing) { + $count = $wpdb->query("UPDATE `$this->_tb_blacklist` SET res = $sql_res WHERE id IN ( " . implode(',', array_column($existing, 'id')) . ' )'); + self::debug('Update blacklist [count] ' . $count); } // Append new blacklist - if ( count( $ids ) > count( $existing ) ) { - $new_urls = array_diff( array_column( $ids, 'url' ), array_column( $existing, 'url') ); + if (count($ids) > count($existing)) { + $new_urls = array_diff(array_column($ids, 'url'), array_column($existing, 'url')); - Debug2::debug( '🐞🗺️ Insert into blacklist [count] ' . count( $new_urls ) ); + self::debug('Insert into blacklist [count] ' . count($new_urls)); - $q = "INSERT INTO `$this->_tb_blacklist` ( url, res, reason ) VALUES " . implode( ',', array_fill( 0, count( $new_urls ), '( %s, %s, %s )' ) ); + $q = "INSERT INTO `$this->_tb_blacklist` ( url, res, reason ) VALUES " . implode(',', array_fill(0, count($new_urls), '( %s, %s, %s )')); $data = array(); - $res = array_fill( 0, $total_crawler, '-' ); - $res[ $curr_crawler ] = $bit; - $res = implode( '', $res ); - $default_reason = $total_crawler > 1 ? str_repeat( ',', $total_crawler - 1 ) : ''; // Pre-populate default reason value first, update later - foreach ( $new_urls as $url ) { + $res = array_fill(0, $total_crawler, '-'); + $res[$curr_crawler] = $bit; + $res = implode('', $res); + $default_reason = $total_crawler > 1 ? str_repeat(',', $total_crawler - 1) : ''; // Pre-populate default reason value first, update later + foreach ($new_urls as $url) { $data[] = $url; $data[] = $res; $data[] = $default_reason; } - $wpdb->query( $wpdb->prepare( $q, $data ) ); + $wpdb->query($wpdb->prepare($q, $data)); } } // Update sitemap reason w/ HTTP code $reason_array = array(); - foreach ( $ids as $id => $v2 ) { - $code = (int)$v2[ 'code' ]; - if ( empty( $reason_array[ $code ] ) ) { - $reason_array[ $code ] = array(); + foreach ($ids as $id => $v2) { + $code = (int) $v2['code']; + if (empty($reason_array[$code])) { + $reason_array[$code] = array(); } - $reason_array[ $code ][] = (int)$id; + $reason_array[$code][] = (int) $id; } - foreach ( $reason_array as $code => $v2 ) { + foreach ($reason_array as $code => $v2) { // Complement comma - if ( $curr_crawler ) { + if ($curr_crawler) { $code = ',' . $code; } - if ( $curr_crawler < $total_crawler_pos ) { + if ($curr_crawler < $total_crawler_pos) { $code .= ','; } - $count = $wpdb->query( "UPDATE `$this->_tb` SET reason = CONCAT( SUBSTRING_INDEX( reason, ',', $curr_crawler ), '$code', SUBSTRING_INDEX( reason, ',', -$right_pos ) ) WHERE id IN (" . implode( ',', $v2 ) . ")" ); + $count = $wpdb->query( + "UPDATE `$this->_tb` SET reason=CONCAT(SUBSTRING_INDEX(reason, ',', $curr_crawler), '$code', SUBSTRING_INDEX(reason, ',', -$right_pos)) WHERE id IN (" . + implode(',', $v2) . + ')' + ); - Debug2::debug( "🐞🗺️ Update map reason [code] $code [pos] left $curr_crawler right -$right_pos [count] $count" ); + self::debug("Update map reason [code] $code [pos] left $curr_crawler right -$right_pos [count] $count"); // Update blacklist reason - if ( $bit == 'B' || $bit == 'N' ) { - $count = $wpdb->query( "UPDATE `$this->_tb_blacklist` a LEFT JOIN `$this->_tb` b ON b.url = a.url SET a.reason = CONCAT( SUBSTRING_INDEX( a.reason, ',', $curr_crawler ), '$code', SUBSTRING_INDEX( a.reason, ',', -$right_pos ) ) WHERE b.id IN (" . implode( ',', $v2 ) . ")" ); - - Debug2::debug( "🐞🗺️ Update blacklist [code] $code [pos] left $curr_crawler right -$right_pos [count] $count" ); + if ($bit == 'B' || $bit == 'N') { + $count = $wpdb->query( + "UPDATE `$this->_tb_blacklist` a LEFT JOIN `$this->_tb` b ON b.url = a.url SET a.reason=CONCAT(SUBSTRING_INDEX(a.reason, ',', $curr_crawler), '$code', SUBSTRING_INDEX(a.reason, ',', -$right_pos)) WHERE b.id IN (" . + implode(',', $v2) . + ')' + ); + + self::debug("Update blacklist [code] $code [pos] left $curr_crawler right -$right_pos [count] $count"); } } - - // Reset list - $list[ $bit ] = array(); + $list[$bit] = array(); } return $list; @@ -137,37 +153,35 @@ public function save_map_status( $list, $curr_crawler ) { * @since 3.0 * @access public */ - public function blacklist_add( $id ) { + public function blacklist_add($id) + { global $wpdb; - $id = (int)$id; + $id = (int) $id; // Build res&reason - $total_crawler = count( Crawler::cls()->list_crawlers() ); - $res = str_repeat( 'B', $total_crawler ); - $reason = implode( ',', array_fill( 0, $total_crawler, 'Man' ) ); - - $row = $wpdb->get_row( "SELECT a.url, b.id FROM `$this->_tb` a LEFT JOIN `$this->_tb_blacklist` b ON b.url = a.url WHERE a.id = '$id'", ARRAY_A ); + $total_crawler = count(Crawler::cls()->list_crawlers()); + $res = str_repeat('B', $total_crawler); + $reason = implode(',', array_fill(0, $total_crawler, 'Man')); - if ( ! $row ) { - Debug2::debug( '🐞🗺️ blacklist failed to add [id] ' . $id ); + $row = $wpdb->get_row("SELECT a.url, b.id FROM `$this->_tb` a LEFT JOIN `$this->_tb_blacklist` b ON b.url = a.url WHERE a.id = '$id'", ARRAY_A); + if (!$row) { + self::debug('blacklist failed to add [id] ' . $id); return; } - Debug2::debug( '🐞🗺️ Add to blacklist [url] ' . $row[ 'url' ] ); + self::debug('Add to blacklist [url] ' . $row['url']); $q = "UPDATE `$this->_tb` SET res = %s, reason = %s WHERE id = %d"; - $wpdb->query( $wpdb->prepare( $q, array( $res, $reason, $id ) ) ); + $wpdb->query($wpdb->prepare($q, array($res, $reason, $id))); - if ( $row[ 'id' ] ) { + if ($row['id']) { $q = "UPDATE `$this->_tb_blacklist` SET res = %s, reason = %s WHERE id = %d"; - $wpdb->query( $wpdb->prepare( $q, array( $res, $reason, $row[ 'id' ] ) ) ); - } - else { + $wpdb->query($wpdb->prepare($q, array($res, $reason, $row['id']))); + } else { $q = "INSERT INTO `$this->_tb_blacklist` (url, res, reason) VALUES (%s, %s, %s)"; - $wpdb->query( $wpdb->prepare( $q, array( $row[ 'url' ], $res, $reason ) ) ); + $wpdb->query($wpdb->prepare($q, array($row['url'], $res, $reason))); } - } /** @@ -176,20 +190,18 @@ public function blacklist_add( $id ) { * @since 3.0 * @access public */ - public function blacklist_del( $id ) { + public function blacklist_del($id) + { global $wpdb; - - if ( ! $this->__data->tb_exist( 'crawler_blacklist' ) ) { + if (!$this->__data->tb_exist('crawler_blacklist')) { return; } - $id = (int)$id; - - Debug2::debug( '🐞🗺️ blacklist delete [id] ' . $id ); - - $wpdb->query( "UPDATE `$this->_tb` SET res = REPLACE( REPLACE( res, 'N', '-' ), 'B', '-' ) WHERE url = ( SELECT url FROM `$this->_tb_blacklist` WHERE id = '$id' )" ); + $id = (int) $id; + self::debug('blacklist delete [id] ' . $id); - $wpdb->query( "DELETE FROM `$this->_tb_blacklist` WHERE id = '$id'" ); + $wpdb->query("UPDATE `$this->_tb` SET res=REPLACE(REPLACE(res, 'N', '-'), 'B', '-') WHERE url=(SELECT url FROM `$this->_tb_blacklist` WHERE id='$id')"); + $wpdb->query("DELETE FROM `$this->_tb_blacklist` WHERE id='$id'"); } /** @@ -198,18 +210,17 @@ public function blacklist_del( $id ) { * @since 3.0 * @access public */ - public function blacklist_empty() { + public function blacklist_empty() + { global $wpdb; - if ( ! $this->__data->tb_exist( 'crawler_blacklist' ) ) { + if (!$this->__data->tb_exist('crawler_blacklist')) { return; } - Debug2::debug( '🐞🗺️ Truncate blacklist' ); - - $wpdb->query( "UPDATE `$this->_tb` SET res = REPLACE( REPLACE( res, 'N', '-' ), 'B', '-' )" ); - - $wpdb->query( "TRUNCATE `$this->_tb_blacklist`" ); + self::debug('Truncate blacklist'); + $wpdb->query("UPDATE `$this->_tb` SET res=REPLACE(REPLACE(res, 'N', '-'), 'B', '-')"); + $wpdb->query("TRUNCATE `$this->_tb_blacklist`"); } /** @@ -218,39 +229,40 @@ public function blacklist_empty() { * @since 3.0 * @access public */ - public function list_blacklist( $limit = false, $offset = false ) { + public function list_blacklist($limit = false, $offset = false) + { global $wpdb; - if ( ! $this->__data->tb_exist( 'crawler_blacklist' ) ) { + if (!$this->__data->tb_exist('crawler_blacklist')) { return array(); } $q = "SELECT * FROM `$this->_tb_blacklist` ORDER BY id DESC"; - if ( $limit !== false ) { - if ( $offset === false ) { + if ($limit !== false) { + if ($offset === false) { $total = $this->count_blacklist(); - $offset = Utility::pagination( $total, $limit, true ); + $offset = Utility::pagination($total, $limit, true); } - $q .= " LIMIT %d, %d"; - $q = $wpdb->prepare( $q, $offset, $limit ); + $q .= ' LIMIT %d, %d'; + $q = $wpdb->prepare($q, $offset, $limit); } - return $wpdb->get_results( $q, ARRAY_A ); - + return $wpdb->get_results($q, ARRAY_A); } /** * Count blacklist */ - public function count_blacklist() { + public function count_blacklist() + { global $wpdb; - if ( ! $this->__data->tb_exist( 'crawler_blacklist' ) ) { + if (!$this->__data->tb_exist('crawler_blacklist')) { return false; } $q = "SELECT COUNT(*) FROM `$this->_tb_blacklist`"; - return $wpdb->get_var( $q ); + return $wpdb->get_var($q); } /** @@ -259,11 +271,12 @@ public function count_blacklist() { * @since 3.0 * @access public */ - public function empty_map() { - Data::cls()->tb_del( 'crawler' ); + public function empty_map() + { + Data::cls()->tb_del('crawler'); - $msg = __( 'Sitemap cleaned successfully', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + $msg = __('Sitemap cleaned successfully', 'litespeed-cache'); + Admin_Display::succeed($msg); } /** @@ -272,36 +285,44 @@ public function empty_map() { * @since 3.0 * @access public */ - public function list_map( $limit, $offset = false ) { + public function list_map($limit, $offset = false) + { global $wpdb; - if ( ! $this->__data->tb_exist( 'crawler' ) ) { + if (!$this->__data->tb_exist('crawler')) { return array(); } - if ( $offset === false ) { + if ($offset === false) { $total = $this->count_map(); - $offset = Utility::pagination( $total, $limit, true ); + $offset = Utility::pagination($total, $limit, true); } + $where = ''; + if (!empty($_POST['kw'])) { + $q = "SELECT * FROM `$this->_tb` WHERE url LIKE %s ORDER BY id LIMIT %d, %d"; + $where = '%' . $wpdb->esc_like($_POST['kw']) . '%'; + return $wpdb->get_results($wpdb->prepare($q, $where, $offset, $limit), ARRAY_A); + } $q = "SELECT * FROM `$this->_tb` ORDER BY id LIMIT %d, %d"; - return $wpdb->get_results( $wpdb->prepare( $q, $offset, $limit ), ARRAY_A ); - + // self::debug("q=$q offset=$offset, limit=$limit"); + return $wpdb->get_results($wpdb->prepare($q, $offset, $limit), ARRAY_A); } /** * Count sitemap */ - public function count_map() { + public function count_map() + { global $wpdb; - if ( ! $this->__data->tb_exist( 'crawler' ) ) { + if (!$this->__data->tb_exist('crawler')) { return false; } $q = "SELECT COUNT(*) FROM `$this->_tb`"; - return $wpdb->get_var( $q ); + return $wpdb->get_var($q); } /** @@ -310,16 +331,19 @@ public function count_map() { * @since 1.1.0 * @access public */ - public function gen() { + public function gen() + { $count = $this->_gen(); - if ( ! $count ) { - Admin_Display::error( __( 'No valid sitemap parsed for crawler.', 'litespeed-cache' ) ); + if (!$count) { + Admin_Display::error(__('No valid sitemap parsed for crawler.', 'litespeed-cache')); return; } - $msg = sprintf( __( 'Sitemap created successfully: %d items', 'litespeed-cache' ), $count ); - Admin_Display::succeed( $msg ); + if (!defined('DOING_CRON')) { + $msg = sprintf(__('Sitemap created successfully: %d items', 'litespeed-cache'), $count); + Admin_Display::succeed($msg); + } } /** @@ -328,93 +352,99 @@ public function gen() { * @since 1.1.0 * @access private */ - private function _gen() { + private function _gen() + { global $wpdb; - if ( ! $this->__data->tb_exist( 'crawler' ) ) { - $this->__data->tb_create( 'crawler' ); + if (!$this->__data->tb_exist('crawler')) { + $this->__data->tb_create('crawler'); } - if ( ! $this->__data->tb_exist( 'crawler_blacklist' ) ) { - $this->__data->tb_create( 'crawler_blacklist' ); + if (!$this->__data->tb_exist('crawler_blacklist')) { + $this->__data->tb_create('crawler_blacklist'); } // use custom sitemap - if ( ! $sitemap = $this->conf( Base::O_CRAWLER_SITEMAP ) ) { + if (!($sitemap = $this->conf(Base::O_CRAWLER_SITEMAP))) { return false; } - $offset = strlen( $this->_home_url ); + $offset = strlen($this->_home_url); + $sitemap = Utility::sanitize_lines($sitemap); try { - $this->_parse( $sitemap ); - } catch( \Exception $e ) { - Debug2::debug( '🐞🗺️ ❌ failed to parse custom sitemap: ' . $e->getMessage() ); + foreach ($sitemap as $this_map) { + $this->_parse($this_map); + } + } catch (\Exception $e) { + self::debug('❌ failed to parse custom sitemap: ' . $e->getMessage()); } - if ( is_array( $this->_urls ) && ! empty( $this->_urls ) ) { - if ( $this->conf( Base::O_CRAWLER_DROP_DOMAIN ) ) { - foreach ( $this->_urls as $k => $v ) { - if ( stripos( $v, $this->_home_url ) !== 0 ) { - unset( $this->_urls[ $k ] ); + if (is_array($this->_urls) && !empty($this->_urls)) { + if ($this->conf(Base::O_CRAWLER_DROP_DOMAIN)) { + foreach ($this->_urls as $k => $v) { + if (stripos($v, $this->_home_url) !== 0) { + unset($this->_urls[$k]); continue; } - $this->_urls[ $k ] = substr( $v, $offset ); + $this->_urls[$k] = substr($v, $offset); } } - $this->_urls = array_unique( $this->_urls ); + $this->_urls = array_unique($this->_urls); } - Debug2::debug( '🐞🗺️ Truncate sitemap' ); - $wpdb->query( "TRUNCATE `$this->_tb`" ); + self::debug('Truncate sitemap'); + $wpdb->query("TRUNCATE `$this->_tb`"); - Debug2::debug( '🐞🗺️ Generate sitemap' ); + self::debug('Generate sitemap'); // Filter URLs in blacklist $blacklist = $this->list_blacklist(); $full_blacklisted = array(); $partial_blacklisted = array(); - foreach ( $blacklist as $v ) { - if ( strpos( $v[ 'res' ], '-' ) === false ) { // Full blacklisted - $full_blacklisted[] = $v[ 'url' ]; - } - else { + foreach ($blacklist as $v) { + if (strpos($v['res'], '-') === false) { + // Full blacklisted + $full_blacklisted[] = $v['url']; + } else { // Replace existing reason - $v[ 'reason' ] = explode( ',', $v[ 'reason' ] ); - $v[ 'reason' ] = array_map( function( $element ){ return $element ? 'Existed' : ''; }, $v[ 'reason' ] ); - $v[ 'reason' ] = implode( ',', $v[ 'reason' ] ); - $partial_blacklisted[ $v[ 'url' ] ] = array( - 'res' => $v[ 'res' ], - 'reason' => $v[ 'reason' ], + $v['reason'] = explode(',', $v['reason']); + $v['reason'] = array_map(function ($element) { + return $element ? 'Existed' : ''; + }, $v['reason']); + $v['reason'] = implode(',', $v['reason']); + $partial_blacklisted[$v['url']] = array( + 'res' => $v['res'], + 'reason' => $v['reason'], ); } } // Drop all blacklisted URLs - $this->_urls = array_diff( $this->_urls, $full_blacklisted ); + $this->_urls = array_diff($this->_urls, $full_blacklisted); // Default res & reason - $crawler_count = count( Crawler::cls()->list_crawlers() ); - $default_res = str_repeat( '-', $crawler_count ); - $default_reason = $crawler_count > 1 ? str_repeat( ',', $crawler_count - 1 ) : ''; + $crawler_count = count(Crawler::cls()->list_crawlers()); + $default_res = str_repeat('-', $crawler_count); + $default_reason = $crawler_count > 1 ? str_repeat(',', $crawler_count - 1) : ''; $data = array(); - foreach ( $this->_urls as $url ) { + foreach ($this->_urls as $url) { $data[] = $url; - $data[] = array_key_exists( $url, $partial_blacklisted ) ? $partial_blacklisted[ $url ][ 'res' ] : $default_res; - $data[] = array_key_exists( $url, $partial_blacklisted ) ? $partial_blacklisted[ $url ][ 'reason' ] : $default_reason; + $data[] = array_key_exists($url, $partial_blacklisted) ? $partial_blacklisted[$url]['res'] : $default_res; + $data[] = array_key_exists($url, $partial_blacklisted) ? $partial_blacklisted[$url]['reason'] : $default_reason; } - foreach ( array_chunk( $data, 300 ) as $data2 ) { - $this->_save( $data2 ); + foreach (array_chunk($data, 300) as $data2) { + $this->_save($data2); } // Reset crawler Crawler::cls()->reset_pos(); - return count( $this->_urls ); + return count($this->_urls); } /** @@ -423,20 +453,21 @@ private function _gen() { * @since 3.0 * @access private */ - private function _save( $data, $fields = 'url,res,reason' ) { + private function _save($data, $fields = 'url,res,reason') + { global $wpdb; - if ( empty( $data ) ) { + if (empty($data)) { return; } $q = "INSERT INTO `$this->_tb` ( $fields ) VALUES "; // Add placeholder - $q .= Utility::chunk_placeholder( $data, $fields ); + $q .= Utility::chunk_placeholder($data, $fields); // Store data - $wpdb->query( $wpdb->prepare( $q, $data ) ); + $wpdb->query($wpdb->prepare($q, $data)); } /** @@ -445,61 +476,60 @@ private function _save( $data, $fields = 'url,res,reason' ) { * @since 1.1.1 * @access private */ - private function _parse( $sitemap ) { + private function _parse($sitemap) + { /** * Read via wp func to avoid allow_url_fopen = off * @since 2.2.7 */ - $response = wp_remote_get( $sitemap, array( 'timeout' => $this->_conf_map_timeout ) ); - if ( is_wp_error( $response ) ) { + $response = wp_remote_get($sitemap, array('timeout' => $this->_conf_map_timeout, 'sslverify' => false)); + if (is_wp_error($response)) { $error_message = $response->get_error_message(); - Debug2::debug( '🐞🗺️ failed to read sitemap: ' . $error_message ); - - throw new \Exception( 'Failed to remote read ' . $sitemap ); + self::debug('failed to read sitemap: ' . $error_message); + throw new \Exception('Failed to remote read ' . $sitemap); } - $xml_object = simplexml_load_string( $response[ 'body' ], null, LIBXML_NOCDATA ); - if ( ! $xml_object ) { - if ( $this->_urls ) { + $xml_object = simplexml_load_string($response['body'], null, LIBXML_NOCDATA); + if (!$xml_object) { + if ($this->_urls) { return; } - - throw new \Exception( 'Failed to parse xml ' . $sitemap ); + throw new \Exception('Failed to parse xml ' . $sitemap); } // start parsing $xml_array = (array) $xml_object; - if ( ! empty( $xml_array[ 'sitemap' ] ) ) { // parse sitemap set - if ( is_object( $xml_array[ 'sitemap' ] ) ) { - $xml_array[ 'sitemap' ] = (array) $xml_array[ 'sitemap' ]; + if (!empty($xml_array['sitemap'])) { + // parse sitemap set + if (is_object($xml_array['sitemap'])) { + $xml_array['sitemap'] = (array) $xml_array['sitemap']; } - if ( ! empty( $xml_array[ 'sitemap' ][ 'loc' ] ) ) { // is single sitemap - $this->_parse( $xml_array[ 'sitemap' ][ 'loc' ] ); - } - else { + if (!empty($xml_array['sitemap']['loc'])) { + // is single sitemap + $this->_parse($xml_array['sitemap']['loc']); + } else { // parse multiple sitemaps - foreach ( $xml_array[ 'sitemap' ] as $val ) { + foreach ($xml_array['sitemap'] as $val) { $val = (array) $val; - if ( ! empty( $val[ 'loc' ] ) ) { - $this->_parse( $val[ 'loc' ] ); // recursive parse sitemap + if (!empty($val['loc'])) { + $this->_parse($val['loc']); // recursive parse sitemap } } } - } - elseif ( ! empty( $xml_array[ 'url' ] ) ) { // parse url set - if ( is_object( $xml_array[ 'url' ] ) ) { - $xml_array[ 'url' ] = (array) $xml_array[ 'url' ]; + } elseif (!empty($xml_array['url'])) { + // parse url set + if (is_object($xml_array['url'])) { + $xml_array['url'] = (array) $xml_array['url']; } // if only 1 element - if ( ! empty( $xml_array[ 'url' ][ 'loc' ] ) ) { - $this->_urls[] = $xml_array[ 'url' ][ 'loc' ]; - } - else { - foreach ( $xml_array[ 'url' ] as $val ) { + if (!empty($xml_array['url']['loc'])) { + $this->_urls[] = $xml_array['url']['loc']; + } else { + foreach ($xml_array['url'] as $val) { $val = (array) $val; - if ( ! empty( $val[ 'loc' ] ) ) { - $this->_urls[] = $val[ 'loc' ]; + if (!empty($val['loc'])) { + $this->_urls[] = $val['loc']; } } } diff --git a/src/crawler.cls.php b/src/crawler.cls.php index 920ae4df8..7791d76d9 100644 --- a/src/crawler.cls.php +++ b/src/crawler.cls.php @@ -1,13 +1,17 @@ array(), 'headers' => array(), - 'ua' => '', + 'ua' => '', ); private $_crawlers = array(); private $_cur_threads = -1; private $_max_run_time; private $_cur_thread_time; private $_map_status_list = array( - 'H' => array(), - 'M' => array(), - 'B' => array(), - 'N' => array(), + 'H' => array(), + 'M' => array(), + 'B' => array(), + 'N' => array(), ); protected $_summary; @@ -49,8 +53,9 @@ class Crawler extends Root { * * @since 1.1.0 */ - public function __construct() { - if ( is_multisite() ) { + public function __construct() + { + if (is_multisite()) { $this->_sitemeta = 'meta' . get_current_blog_id() . '.data'; } @@ -60,26 +65,30 @@ public function __construct() { $this->_ncpu = $this->_get_server_cpu(); - self::debug( 'Init w/ CPU cores=' . $this->_ncpu ); + self::debug('Init w/ CPU cores=' . $this->_ncpu); } /** * Try get server CPUs * @since 5.2 */ - private function _get_server_cpu(){ + private function _get_server_cpu() + { $cpuinfo_file = '/proc/cpuinfo'; $setting_open_dir = ini_get('open_basedir'); - if ( $setting_open_dir ) return 1; // Server has limit + if ($setting_open_dir) { + return 1; + } // Server has limit try { - if ( ! @is_file( $cpuinfo_file ) ) return 1; - } - catch ( \Exception $e ) { + if (!@is_file($cpuinfo_file)) { + return 1; + } + } catch (\Exception $e) { return 1; } - $cpuinfo = file_get_contents( $cpuinfo_file ); + $cpuinfo = file_get_contents($cpuinfo_file); preg_match_all('/^processor/m', $cpuinfo, $matches); return count($matches[0]) ?: 1; } @@ -89,9 +98,10 @@ private function _get_server_cpu(){ * * @since 4.3 */ - public function is_active( $curr ){ - $bypass_list = self::get_option( 'bypass_list' , array() ); - return ! in_array( $curr, $bypass_list ); + public function is_active($curr) + { + $bypass_list = self::get_option('bypass_list', array()); + return !in_array($curr, $bypass_list); } /** @@ -99,16 +109,20 @@ public function is_active( $curr ){ * * @since 4.3 */ - public function toggle_activeness( $curr ) { // param type: int - $bypass_list = self::get_option( 'bypass_list' , array() ); - if ( in_array( $curr, $bypass_list ) ) { // when the ith opt was off / in the bypassed list, turn it on / remove it from the list - unset( $bypass_list[ array_search( $curr, $bypass_list ) ] ); - $bypass_list = array_values( $bypass_list ); - self::update_option( 'bypass_list' , $bypass_list ); + public function toggle_activeness($curr) + { + // param type: int + $bypass_list = self::get_option('bypass_list', array()); + if (in_array($curr, $bypass_list)) { + // when the ith opt was off / in the bypassed list, turn it on / remove it from the list + unset($bypass_list[array_search($curr, $bypass_list)]); + $bypass_list = array_values($bypass_list); + self::update_option('bypass_list', $bypass_list); return true; - } else { // when the ith opt was on / not in the bypassed list, turn it off / add it to the list - $bypass_list[] = ( int ) $curr; - self::update_option( 'bypass_list' , $bypass_list ); + } else { + // when the ith opt was on / not in the bypassed list, turn it off / add it to the list + $bypass_list[] = (int) $curr; + self::update_option('bypass_list', $bypass_list); return false; } } @@ -119,13 +133,14 @@ public function toggle_activeness( $curr ) { // param type: int * @since 4.3 * @access public */ - public function clear_disabled_list() { - self::update_option( 'bypass_list', array() ); + public function clear_disabled_list() + { + self::update_option('bypass_list', array()); - $msg = __( 'Crawler disabled list is cleared! All crawlers are set to active! ', 'litespeed-cache' ); - Admin_Display::note( $msg ); + $msg = __('Crawler disabled list is cleared! All crawlers are set to active! ', 'litespeed-cache'); + Admin_Display::note($msg); - self::debug( 'All crawlers are set to active...... ' ); + self::debug('All crawlers are set to active...... '); } /** @@ -134,37 +149,39 @@ public function clear_disabled_list() { * @since 3.0 * @access public */ - public static function get_summary( $field = false ) { + public static function get_summary($field = false) + { $_default = array( - 'list_size' => 0, - 'last_update_time' => 0, - 'curr_crawler' => 0, - 'curr_crawler_beginning_time' => 0, - 'last_pos' => 0, - 'last_count' => 0, - 'last_crawled' => 0, - 'last_start_time' => 0, - 'last_status' => '', - 'is_running' => 0, - 'end_reason' => '', - 'meta_save_time' => 0, - 'pos_reset_check' => 0, - 'done' => 0, - 'this_full_beginning_time' => 0, - 'last_full_time_cost' => 0, - 'last_crawler_total_cost' => 0, - 'crawler_stats' => array(), // this will store all crawlers hit/miss crawl status + 'list_size' => 0, + 'last_update_time' => 0, + 'curr_crawler' => 0, + 'curr_crawler_beginning_time' => 0, + 'last_pos' => 0, + 'last_count' => 0, + 'last_crawled' => 0, + 'last_start_time' => 0, + 'last_status' => '', + 'is_running' => 0, + 'end_reason' => '', + 'meta_save_time' => 0, + 'pos_reset_check' => 0, + 'done' => 0, + 'this_full_beginning_time' => 0, + 'last_full_time_cost' => 0, + 'last_crawler_total_cost' => 0, + 'crawler_stats' => array(), // this will store all crawlers hit/miss crawl status ); + wp_cache_delete('alloptions', 'options'); // ensure the summary is current $summary = parent::get_summary(); - $summary = array_merge( $_default, $summary ); + $summary = array_merge($_default, $summary); - if ( ! $field ) { + if (!$field) { return $summary; } - if ( array_key_exists( $field, $summary ) ) { - return $summary[ $field ]; + if (array_key_exists($field, $summary)) { + return $summary[$field]; } return null; @@ -176,17 +193,58 @@ public static function get_summary( $field = false ) { * @since 3.0 * @access public */ - public static function save_summary( $data = false, $reload = false, $overwrite = false ) { + public static function save_summary($data = false, $reload = false, $overwrite = false) + { $instance = self::cls(); - $instance->_summary[ 'meta_save_time' ] = time(); + $instance->_summary['meta_save_time'] = time(); - if ( ! $data ) { + if (!$data) { $data = $instance->_summary; } - parent::save_summary( $data, $reload, $overwrite ); + parent::save_summary($data, $reload, $overwrite); - File::save( LITESPEED_STATIC_DIR . '/crawler/' . $instance->_sitemeta, json_encode( $data ), true ); + File::save(LITESPEED_STATIC_DIR . '/crawler/' . $instance->_sitemeta, json_encode($data), true); + } + + /** + * Cron start async crawling + * + * @since 5.5 + */ + public static function start_async_cron() + { + Task::async_call('crawler'); + } + + /** + * Manually start async crawling + * + * @since 5.5 + */ + public static function start_async() + { + Task::async_call('crawler_force'); + + $msg = __('Started async crawling', 'litespeed-cache'); + Admin_Display::success($msg); + } + + /** + * Ajax crawl handler + * + * @since 5.5 + */ + public static function async_handler($manually_run = false) + { + self::debug('------------async-------------start_async_handler'); + // self::debug('-------------async------------ check_ajax_referer'); + // add_action('check_ajax_referer', function ($a, $b) { + // \LiteSpeed\Crawler::debug('---------------' . $a . $b); + // }); + // check_ajax_referer('async_crawler', 'nonce'); + // self::debug('--------------async----------- start async crawling'); + self::start($manually_run); } /** @@ -195,17 +253,24 @@ public static function save_summary( $data = false, $reload = false, $overwrite * @since 1.1.0 * @access public */ - public static function start( $force = false ) { - if ( ! Router::can_crawl() ) { - self::debug( '......crawler is NOT allowed by the server admin......' ); + public static function start($manually_run = false) + { + if (!Router::can_crawl()) { + self::debug('......crawler is NOT allowed by the server admin......'); return false; } - if ( $force ) { - self::debug( '......crawler manually ran......' ); + if ($manually_run) { + self::debug('......crawler manually ran......'); } + // $i = 0; + // while ($i < 100) { + // self::debug('......sleep ' . ($i++) . '......' . time()); + // sleep(1); + // } + // return; - self::cls()->_crawl_data( $force ); + self::cls()->_crawl_data($manually_run); } /** @@ -214,48 +279,75 @@ public static function start( $force = false ) { * @since 1.1.0 * @access private */ - private function _crawl_data( $force ) { - self::debug( '......crawler started......' ); + private function _crawl_data($manually_run) + { + if (!defined('LITESPEED_LANE_HASH')) { + define('LITESPEED_LANE_HASH', Str::rrand(8)); + } + if ($this->_check_valid_lane()) { + $this->_take_over_lane(); + } else { + self::debug('⚠️ lane in use'); + return; + // if ($manually_run) { + // self::debug('......crawler started (manually_rund)......'); + // // Log pid to prevent from multi running + // if (defined('LITESPEED_CLI')) { + // // Take over lane + // self::debug('⚠️⚠️⚠️ Forced take over lane (CLI)'); + // $this->_take_over_lane(); + // } + // } + } + self::debug('......crawler started......'); + // for the first time running - if ( ! $this->_summary || ! Data::cls()->tb_exist( 'crawler' ) || ! Data::cls()->tb_exist( 'crawler_blacklist' ) ) { - $this->cls( 'Crawler_Map' )->gen(); + if (!$this->_summary || !Data::cls()->tb_exist('crawler') || !Data::cls()->tb_exist('crawler_blacklist')) { + $this->cls('Crawler_Map')->gen(); } // if finished last time, regenerate sitemap - if ( $this->_summary['done'] === 'touchedEnd' ) { + if ($this->_summary['done'] === 'touchedEnd') { // check whole crawling interval - $last_fnished_at = $this->_summary[ 'last_full_time_cost' ] + $this->_summary[ 'this_full_beginning_time' ]; - if ( ! $force && time() - $last_fnished_at < $this->conf( Base::O_CRAWLER_CRAWL_INTERVAL ) ) { - self::debug( 'Cron abort: cache warmed already.' ); + $last_fnished_at = $this->_summary['last_full_time_cost'] + $this->_summary['this_full_beginning_time']; + if (!$manually_run && time() - $last_fnished_at < $this->conf(Base::O_CRAWLER_CRAWL_INTERVAL)) { + self::debug('Cron abort: cache warmed already.'); // if not reach whole crawling interval, exit + $this->Release_lane(); return; } - self::debug( 'TouchedEnd. regenerate sitemap....' ); - $this->cls( 'Crawler_Map' )->gen(); + self::debug('TouchedEnd. regenerate sitemap....'); + $this->cls('Crawler_Map')->gen(); } $this->list_crawlers(); // Skip the crawlers that in bypassed list - while ( ! $this->is_active( $this->_summary[ 'curr_crawler' ] ) && $this->_summary[ 'curr_crawler' ] < count( $this->_crawlers ) ) { - self::debug( 'Skipped the Crawler #' . $this->_summary[ 'curr_crawler' ] . ' ......' ); - $this->_summary[ 'curr_crawler' ]++; + while (!$this->is_active($this->_summary['curr_crawler']) && $this->_summary['curr_crawler'] < count($this->_crawlers)) { + self::debug('Skipped the Crawler #' . $this->_summary['curr_crawler'] . ' ......'); + $this->_summary['curr_crawler']++; } - if ( $this->_summary[ 'curr_crawler' ] >= count( $this->_crawlers ) ) { + if ($this->_summary['curr_crawler'] >= count($this->_crawlers)) { $this->_end_reason = 'end'; $this->_terminate_running(); + $this->Release_lane(); return; } // In case crawlers are all done but not reload, reload it - if ( empty( $this->_summary[ 'curr_crawler' ] ) || empty( $this->_crawlers[ $this->_summary[ 'curr_crawler' ] ] ) ) { - $this->_summary[ 'curr_crawler' ] = 0; - $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ] = array(); + if (empty($this->_summary['curr_crawler']) || empty($this->_crawlers[$this->_summary['curr_crawler']])) { + $this->_summary['curr_crawler'] = 0; + $this->_summary['crawler_stats'][$this->_summary['curr_crawler']] = array(); } $this->load_conf(); - $this->_engine_start(); + try { + $this->_engine_start(); + $this->Release_lane(); + } catch (\Exception $e) { + self::debug('🛑 ' . $e->getMessage()); + } } /** @@ -264,74 +356,73 @@ private function _crawl_data( $force ) { * @since 3.0 * @access private */ - private function load_conf() { - $this->_crawler_conf[ 'base' ] = home_url(); + private function load_conf() + { + $this->_crawler_conf['base'] = home_url(); - $current_crawler = $this->_crawlers[ $this->_summary[ 'curr_crawler' ] ]; + $current_crawler = $this->_crawlers[$this->_summary['curr_crawler']]; /** * Set role simulation * @since 1.9.1 */ - if ( ! empty( $current_crawler[ 'uid' ] ) ) { + if (!empty($current_crawler['uid'])) { // Get role simulation vary name - $vary_name = $this->cls( 'Vary' )->get_vary_name(); - $vary_val = $this->cls( 'Vary' )->finalize_default_vary( $current_crawler[ 'uid' ] ); - $this->_crawler_conf[ 'cookies' ][ $vary_name ] = $vary_val; - $this->_crawler_conf[ 'cookies' ][ 'litespeed_role' ] = $current_crawler[ 'uid' ]; + $vary_name = $this->cls('Vary')->get_vary_name(); + $vary_val = $this->cls('Vary')->finalize_default_vary($current_crawler['uid']); + $this->_crawler_conf['cookies'][$vary_name] = $vary_val; + $this->_crawler_conf['cookies']['litespeed_role'] = $current_crawler['uid']; } /** * Check cookie crawler * @since 2.8 */ - foreach ( $current_crawler as $k => $v ) { - if ( strpos( $k, 'cookie:') !== 0 ) { + foreach ($current_crawler as $k => $v) { + if (strpos($k, 'cookie:') !== 0) { continue; } - if ( $v == '_null' ) { + if ($v == '_null') { continue; } - $this->_crawler_conf[ 'cookies' ][ substr( $k, 7 ) ] = $v; + $this->_crawler_conf['cookies'][substr($k, 7)] = $v; } /** * Set WebP simulation * @since 1.9.1 */ - if ( ! empty( $current_crawler[ 'webp' ] ) ) { - $this->_crawler_conf[ 'headers' ][] = 'Accept: image/webp,*/*'; + if (!empty($current_crawler['webp'])) { + $this->_crawler_conf['headers'][] = 'Accept: image/webp,*/*'; } /** * Set mobile crawler * @since 2.8 */ - if ( ! empty( $current_crawler[ 'mobile' ] ) ) { - $this->_crawler_conf[ 'ua' ] = 'Mobile iPhone'; + if (!empty($current_crawler['mobile'])) { + $this->_crawler_conf['ua'] = 'Mobile iPhone'; } /** * Limit delay to use server setting * @since 1.8.3 */ - $this->_crawler_conf[ 'run_delay' ] = $this->conf( Base::O_CRAWLER_USLEEP ); // microseconds - if ( ! empty( $_SERVER[ Base::ENV_CRAWLER_USLEEP ] ) && $_SERVER[ Base::ENV_CRAWLER_USLEEP ] > $this->_crawler_conf[ 'run_delay' ] ) { - $this->_crawler_conf[ 'run_delay' ] = $_SERVER[ Base::ENV_CRAWLER_USLEEP ]; + $this->_crawler_conf['run_delay'] = $this->conf(Base::O_CRAWLER_USLEEP); // microseconds + if (!empty($_SERVER[Base::ENV_CRAWLER_USLEEP]) && $_SERVER[Base::ENV_CRAWLER_USLEEP] > $this->_crawler_conf['run_delay']) { + $this->_crawler_conf['run_delay'] = $_SERVER[Base::ENV_CRAWLER_USLEEP]; } - $this->_crawler_conf[ 'run_duration' ] = $this->conf( Base::O_CRAWLER_RUN_DURATION ); + $this->_crawler_conf['run_duration'] = $this->conf(Base::O_CRAWLER_RUN_DURATION); - $this->_crawler_conf[ 'load_limit' ] = $this->conf( Base::O_CRAWLER_LOAD_LIMIT ); - if ( ! empty( $_SERVER[ Base::ENV_CRAWLER_LOAD_LIMIT_ENFORCE ] ) ) { - $this->_crawler_conf[ 'load_limit' ] = $_SERVER[ Base::ENV_CRAWLER_LOAD_LIMIT_ENFORCE ]; + $this->_crawler_conf['load_limit'] = $this->conf(Base::O_CRAWLER_LOAD_LIMIT); + if (!empty($_SERVER[Base::ENV_CRAWLER_LOAD_LIMIT_ENFORCE])) { + $this->_crawler_conf['load_limit'] = $_SERVER[Base::ENV_CRAWLER_LOAD_LIMIT_ENFORCE]; + } elseif (!empty($_SERVER[Base::ENV_CRAWLER_LOAD_LIMIT]) && $_SERVER[Base::ENV_CRAWLER_LOAD_LIMIT] < $this->_crawler_conf['load_limit']) { + $this->_crawler_conf['load_limit'] = $_SERVER[Base::ENV_CRAWLER_LOAD_LIMIT]; } - elseif ( ! empty( $_SERVER[ Base::ENV_CRAWLER_LOAD_LIMIT ] ) && $_SERVER[ Base::ENV_CRAWLER_LOAD_LIMIT ] < $this->_crawler_conf[ 'load_limit' ] ) { - $this->_crawler_conf[ 'load_limit' ] = $_SERVER[ Base::ENV_CRAWLER_LOAD_LIMIT ]; - } - } /** @@ -340,43 +431,42 @@ private function load_conf() { * @since 1.1.0 * @access private */ - private function _engine_start() { + private function _engine_start() + { // check if is running - if ( $this->_summary['is_running'] && time() - $this->_summary['is_running'] < $this->_crawler_conf[ 'run_duration' ] ) { - $this->_end_reason = 'stopped'; - self::debug( 'The crawler is running.' ); - return; - } + // if ($this->_summary['is_running'] && time() - $this->_summary['is_running'] < $this->_crawler_conf['run_duration']) { + // $this->_end_reason = 'stopped'; + // self::debug('The crawler is running.'); + // return; + // } // check current load $this->_adjust_current_threads(); - if ( $this->_cur_threads == 0 ) { + if ($this->_cur_threads == 0) { $this->_end_reason = 'stopped_highload'; - self::debug( 'Stopped due to heavy load.' ); + self::debug('Stopped due to heavy load.'); return; } // log started time - self::save_summary( array( 'last_start_time' => time() ) ); + self::save_summary(array('last_start_time' => time())); // set time limit - $maxTime = (int) ini_get( 'max_execution_time' ); - self::debug( 'ini_get max_execution_time=' . $maxTime ); - if ( $maxTime == 0 ) { + $maxTime = (int) ini_get('max_execution_time'); + self::debug('ini_get max_execution_time=' . $maxTime); + if ($maxTime == 0) { $maxTime = 300; // hardlimit - } - else { + } else { $maxTime -= 5; } - if ( $maxTime >= $this->_crawler_conf[ 'run_duration' ] ) { - $maxTime = $this->_crawler_conf[ 'run_duration' ]; - self::debug( 'Use run_duration setting as max_execution_time=' . $maxTime ); + if ($maxTime >= $this->_crawler_conf['run_duration']) { + $maxTime = $this->_crawler_conf['run_duration']; + self::debug('Use run_duration setting as max_execution_time=' . $maxTime); + } elseif (ini_set('max_execution_time', $this->_crawler_conf['run_duration'] + 15) !== false) { + $maxTime = $this->_crawler_conf['run_duration']; + self::debug('ini_set max_execution_time=' . $maxTime); } - elseif ( ini_set( 'max_execution_time', $this->_crawler_conf[ 'run_duration' ] + 15 ) !== false ) { - $maxTime = $this->_crawler_conf[ 'run_duration' ]; - self::debug( 'ini_set max_execution_time=' . $maxTime ); - } - self::debug( 'final max_execution_time=' . $maxTime ); + self::debug('final max_execution_time=' . $maxTime); $this->_max_run_time = $maxTime + time(); // mark running @@ -387,61 +477,71 @@ private function _engine_start() { } /** - * Adjust threads dynamically + * Get server load * - * @since 1.1.0 - * @access private + * @since 5.5 */ - private function _adjust_current_threads() { + public function get_server_load() + { /** * If server is windows, exit * @see https://wordpress.org/support/topic/crawler-keeps-causing-crashes/ */ - if ( ! function_exists( 'sys_getloadavg' ) ) { - self::debug( 'set threads=0 due to func sys_getloadavg not exist!' ); - $this->_cur_threads = 0; - return; + if (!function_exists('sys_getloadavg')) { + return -1; } $curload = sys_getloadavg(); $curload = $curload[0]; - self::debug( 'Server load: ' . $curload ); - $curload /= $this->_ncpu; + self::debug('Server load: ' . $curload); + return $curload; + } + /** + * Adjust threads dynamically + * + * @since 1.1.0 + * @access private + */ + private function _adjust_current_threads() + { + $curload = $this->get_server_load(); + if ($curload == -1) { + self::debug('set threads=0 due to func sys_getloadavg not exist!'); + $this->_cur_threads = 0; + return; + } + + $curload /= $this->_ncpu; // $curload = 1; - if ( $this->_cur_threads == -1 ) { + if ($this->_cur_threads == -1) { // init - if ( $curload > $this->_crawler_conf[ 'load_limit' ] ) { + if ($curload > $this->_crawler_conf['load_limit']) { $curthreads = 0; - } - elseif ( $curload >= ( $this->_crawler_conf[ 'load_limit' ] - 1 ) ) { + } elseif ($curload >= $this->_crawler_conf['load_limit'] - 1) { $curthreads = 1; - } - else { - $curthreads = intval( $this->_crawler_conf[ 'load_limit' ] - $curload ); - if ( $curthreads > $this->conf( Base::O_CRAWLER_THREADS ) ) { - $curthreads = $this->conf( Base::O_CRAWLER_THREADS ); + } else { + $curthreads = intval($this->_crawler_conf['load_limit'] - $curload); + if ($curthreads > $this->conf(Base::O_CRAWLER_THREADS)) { + $curthreads = $this->conf(Base::O_CRAWLER_THREADS); } } - } - else { + } else { // adjust $curthreads = $this->_cur_threads; - if ( $curload >= $this->_crawler_conf[ 'load_limit' ] + 1 ) { - sleep( 5 ); // sleep 5 secs - if ( $curthreads >= 1 ) { - $curthreads --; + if ($curload >= $this->_crawler_conf['load_limit'] + 1) { + sleep(5); // sleep 5 secs + if ($curthreads >= 1) { + $curthreads--; } - } - elseif ( $curload >= $this->_crawler_conf[ 'load_limit' ] ) { + } elseif ($curload >= $this->_crawler_conf['load_limit']) { // if ( $curthreads > 1 ) {// if already 1, keep - $curthreads --; + $curthreads--; // } - } - elseif ( ($curload + 1) < $this->_crawler_conf[ 'load_limit' ] ) { - if ( $curthreads < $this->conf( Base::O_CRAWLER_THREADS ) ) { - $curthreads ++; + } elseif ($curload + 1 < $this->_crawler_conf['load_limit']) { + if ($curthreads < $this->conf(Base::O_CRAWLER_THREADS)) { + $curthreads++; } } } @@ -459,130 +559,209 @@ private function _adjust_current_threads() { * @since 1.1.0 * @access private */ - private function _prepare_running() { - $this->_summary[ 'is_running' ] = time(); - $this->_summary[ 'done' ] = 0;// reset done status - $this->_summary[ 'last_status' ] = 'prepare running'; - $this->_summary[ 'last_crawled' ] = 0; + private function _prepare_running() + { + $this->_summary['is_running'] = time(); + $this->_summary['done'] = 0; // reset done status + $this->_summary['last_status'] = 'prepare running'; + $this->_summary['last_crawled'] = 0; // Current crawler starttime mark - if ( $this->_summary[ 'last_pos' ] == 0 ) { - $this->_summary[ 'curr_crawler_beginning_time' ] = time(); + if ($this->_summary['last_pos'] == 0) { + $this->_summary['curr_crawler_beginning_time'] = time(); } - if ( $this->_summary[ 'curr_crawler' ] == 0 && $this->_summary[ 'last_pos' ] == 0 ) { - $this->_summary[ 'this_full_beginning_time' ] = time(); - $this->_summary[ 'list_size' ] = $this->cls( 'Crawler_Map' )->count_map(); + if ($this->_summary['curr_crawler'] == 0 && $this->_summary['last_pos'] == 0) { + $this->_summary['this_full_beginning_time'] = time(); + $this->_summary['list_size'] = $this->cls('Crawler_Map')->count_map(); } - if ( $this->_summary[ 'end_reason' ] == 'end' && $this->_summary[ 'last_pos' ] == 0 ) { - $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ] = array(); + if ($this->_summary['end_reason'] == 'end' && $this->_summary['last_pos'] == 0) { + $this->_summary['crawler_stats'][$this->_summary['curr_crawler']] = array(); } self::save_summary(); } + /** + * Take over lane + * @since 6.1 + */ + private function _take_over_lane() + { + self::debug('Take over lane as lane is free: ' . $this->json_local_path() . '.pid'); + file::save($this->json_local_path() . '.pid', LITESPEED_LANE_HASH); + } + + /** + * Update lane file + * @since 6.1 + */ + private function _touch_lane() + { + touch($this->json_local_path() . '.pid'); + } + + /** + * Release lane file + * @since 6.1 + */ + public function Release_lane() + { + $lane_file = $this->json_local_path() . '.pid'; + if (!file_exists($lane_file)) { + return; + } + + self::debug('Release lane'); + unlink($lane_file); + } + + /** + * Check if lane is used by other crawlers + * @since 6.1 + */ + private function _check_valid_lane($strict_mode = false) + { + // Check lane hash + $lane_file = $this->json_local_path() . '.pid'; + if ($strict_mode) { + if (!file_exists($lane_file)) { + self::debug("lane file not existed, strict mode is false [file] $lane_file"); + return false; + } + } + $pid = file::read($lane_file); + if ($pid && LITESPEED_LANE_HASH != $pid) { + // If lane file is older than 1h, ignore + if (time() - filemtime($lane_file) > 3600) { + self::debug('Lane file is older than 1h, releasing lane'); + $this->Release_lane(); + return true; + } + return false; + } + return true; + } + /** * Run crawler * * @since 1.1.0 * @access private */ - private function _do_running() { - $options = $this->_get_curl_options( true ); + private function _do_running() + { + $options = $this->_get_curl_options(true); - while ( $urlChunks = $this->cls( 'Crawler_Map' )->list_map( self::CHUNKS, $this->_summary['last_pos'] ) ) { + while ($urlChunks = $this->cls('Crawler_Map')->list_map(self::CHUNKS, $this->_summary['last_pos'])) { + // self::debug('$urlChunks=' . count($urlChunks) . ' $this->_cur_threads=' . $this->_cur_threads); // start crawling - $urlChunks = array_chunk( $urlChunks, $this->_cur_threads ); - foreach ( $urlChunks as $rows ) { + $urlChunks = array_chunk($urlChunks, $this->_cur_threads); + // self::debug('$urlChunks after array_chunk: ' . count($urlChunks)); + foreach ($urlChunks as $rows) { + if (!$this->_check_valid_lane(true)) { + $this->_end_reason = 'lane_invalid'; + self::debug('🛑 The crawler lane is used by newer crawler.'); + throw new \Exception('invalid crawler lane'); + } + // Update time + $this->_touch_lane(); + + // self::debug('chunk fetching count($rows)= ' . count($rows)); // multi curl - $rets = $this->_multi_request( $rows, $options ); + $rets = $this->_multi_request($rows, $options); // check result headers - foreach ( $rows as $row ) { - if ( empty( $rets[ $row[ 'id' ] ] ) ) { // If already in blacklist, no curl happened, no corresponding record + foreach ($rows as $row) { + // self::debug('chunk fetching 553'); + if (empty($rets[$row['id']])) { + // If already in blacklist, no curl happened, no corresponding record continue; } - + // self::debug('chunk fetching 557'); // check response - if ( $rets[ $row[ 'id' ] ][ 'code' ] == 428 ) { // HTTP/1.1 428 Precondition Required (need to test) + if ($rets[$row['id']]['code'] == 428) { + // HTTP/1.1 428 Precondition Required (need to test) $this->_end_reason = 'crawler_disabled'; - self::debug( 'crawler_disabled' ); + self::debug('crawler_disabled'); return; } - $status = $this->_status_parse( $rets[ $row[ 'id' ] ][ 'header' ], $rets[ $row[ 'id' ] ][ 'code' ], $row[ 'url' ] ); // B or H or M or N(nocache) - $this->_map_status_list[ $status ][ $row[ 'id' ] ] = array( - 'url' => $row[ 'url' ], - 'code' => $rets[ $row[ 'id' ] ][ 'code' ], // 201 or 200 or 404 + $status = $this->_status_parse($rets[$row['id']]['header'], $rets[$row['id']]['code'], $row['url']); // B or H or M or N(nocache) + self::debug('[status] ' . $this->_status2title($status) . "\t\t [url] " . $row['url']); + $this->_map_status_list[$status][$row['id']] = array( + 'url' => $row['url'], + 'code' => $rets[$row['id']]['code'], // 201 or 200 or 404 ); - if ( empty( $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ][ $status ] ) ) { - $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ][ $status ] = 0; + if (empty($this->_summary['crawler_stats'][$this->_summary['curr_crawler']][$status])) { + $this->_summary['crawler_stats'][$this->_summary['curr_crawler']][$status] = 0; } - $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ][ $status ]++; + $this->_summary['crawler_stats'][$this->_summary['curr_crawler']][$status]++; } // update offset position $_time = time(); - $this->_summary[ 'last_pos' ] += $this->_cur_threads; - $this->_summary[ 'last_count' ] = $this->_cur_threads; - $this->_summary[ 'last_crawled' ] += $this->_cur_threads; - $this->_summary[ 'last_update_time' ] = $_time; - $this->_summary[ 'last_status' ] = 'updated position'; - + $this->_summary['last_count'] = count($rows); + $this->_summary['last_pos'] += $this->_summary['last_count']; + $this->_summary['last_crawled'] += $this->_summary['last_count']; + $this->_summary['last_update_time'] = $_time; + $this->_summary['last_status'] = 'updated position'; + // self::debug("chunk fetching 604 last_pos:{$this->_summary['last_pos']} last_count:{$this->_summary['last_count']} last_crawled:{$this->_summary['last_crawled']}"); // check duration - if ( $this->_summary[ 'last_update_time' ] > $this->_max_run_time ) { + if ($this->_summary['last_update_time'] > $this->_max_run_time) { $this->_end_reason = 'stopped_maxtime'; - self::debug( 'Terminated due to maxtime' ); + self::debug('Terminated due to maxtime'); return; // return __('Stopped due to exceeding defined Maximum Run Time', 'litespeed-cache'); } // make sure at least each 10s save meta & map status once - if ( $_time - $this->_summary[ 'meta_save_time' ] > 10 ) { - $this->_map_status_list = $this->cls( 'Crawler_Map' )->save_map_status( $this->_map_status_list, $this->_summary[ 'curr_crawler' ] ); + if ($_time - $this->_summary['meta_save_time'] > 10) { + $this->_map_status_list = $this->cls('Crawler_Map')->save_map_status($this->_map_status_list, $this->_summary['curr_crawler']); self::save_summary(); } - + // self::debug('chunk fetching 597'); // check if need to reset pos each 5s - if ( $_time > $this->_summary[ 'pos_reset_check' ] ) { - $this->_summary[ 'pos_reset_check' ] = $_time + 5; - if ( file_exists( $this->_resetfile ) && unlink( $this->_resetfile ) ) { - self::debug( 'Terminated due to reset file' ); - - $this->_summary[ 'last_pos' ] = 0; - $this->_summary[ 'curr_crawler' ] = 0; - $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ] = array(); + if ($_time > $this->_summary['pos_reset_check']) { + $this->_summary['pos_reset_check'] = $_time + 5; + if (file_exists($this->_resetfile) && unlink($this->_resetfile)) { + self::debug('Terminated due to reset file'); + + $this->_summary['last_pos'] = 0; + $this->_summary['curr_crawler'] = 0; + $this->_summary['crawler_stats'][$this->_summary['curr_crawler']] = array(); // reset done status - $this->_summary[ 'done' ] = 0; - $this->_summary[ 'this_full_beginning_time' ] = 0; + $this->_summary['done'] = 0; + $this->_summary['this_full_beginning_time'] = 0; $this->_end_reason = 'stopped_reset'; return; // return __('Stopped due to reset meta position', 'litespeed-cache'); } } - + // self::debug('chunk fetching 615'); // check loads - if ( $this->_summary[ 'last_update_time' ] - $this->_cur_thread_time > 60 ) { + if ($this->_summary['last_update_time'] - $this->_cur_thread_time > 60) { $this->_adjust_current_threads(); - if ( $this->_cur_threads == 0 ) { + if ($this->_cur_threads == 0) { $this->_end_reason = 'stopped_highload'; - self::debug( 'Terminated due to highload' ); + self::debug('🛑 Terminated due to highload'); return; // return __('Stopped due to load over limit', 'litespeed-cache'); } } - $this->_summary[ 'last_status' ] = 'sleeping ' . $this->_crawler_conf[ 'run_delay' ] . 'ms'; + $this->_summary['last_status'] = 'sleeping ' . $this->_crawler_conf['run_delay'] . 'ms'; - usleep( $this->_crawler_conf[ 'run_delay' ] ); + usleep($this->_crawler_conf['run_delay']); } + // self::debug('chunk fetching done'); } // All URLs are done for current crawler $this->_end_reason = 'end'; - $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ][ 'W' ] = 0; - self::debug( 'Crawler #' . $this->_summary['curr_crawler'] . ' touched end' ); + $this->_summary['crawler_stats'][$this->_summary['curr_crawler']]['W'] = 0; + self::debug('Crawler #' . $this->_summary['curr_crawler'] . ' touched end'); } /** @@ -592,110 +771,136 @@ private function _do_running() { * @since 1.1.0 * @access private */ - private function _multi_request( $rows, $options ) { - if (!function_exists('curl_multi_init')) exit('curl_multi_init disabled'); + private function _multi_request($rows, $options) + { + if (!function_exists('curl_multi_init')) { + exit('curl_multi_init disabled'); + } $mh = curl_multi_init(); $curls = array(); - foreach ( $rows as $row ) { - if ( substr( $row[ 'res' ], $this->_summary[ 'curr_crawler' ], 1 ) == 'B' ) { + foreach ($rows as $row) { + if (substr($row['res'], $this->_summary['curr_crawler'], 1) == 'B') { continue; } - if ( substr( $row[ 'res' ], $this->_summary[ 'curr_crawler' ], 1 ) == 'N' ) { + if (substr($row['res'], $this->_summary['curr_crawler'], 1) == 'N') { continue; } - if (!function_exists('curl_init')) exit('curl_init disabled'); + if (!function_exists('curl_init')) { + exit('curl_init disabled'); + } - $curls[ $row[ 'id' ] ] = curl_init(); + $curls[$row['id']] = curl_init(); // Append URL - $url = $row[ 'url' ]; - if ( $this->conf( Base::O_CRAWLER_DROP_DOMAIN ) ) { - $url = $this->_crawler_conf[ 'base' ] . $row[ 'url' ]; + $url = $row['url']; + if ($this->conf(Base::O_CRAWLER_DROP_DOMAIN)) { + $url = $this->_crawler_conf['base'] . $row['url']; } - curl_setopt( $curls[ $row[ 'id' ] ], CURLOPT_URL, $url ); - self::debug( 'Crawling [url] ' . $url . ( $url == $row[ 'url' ] ? '' : ' [ori] ' . $row[ 'url' ] ) ); + curl_setopt($curls[$row['id']], CURLOPT_URL, $url); + self::debug('Crawling [url] ' . $url . ($url == $row['url'] ? '' : ' [ori] ' . $row['url'])); - curl_setopt_array( $curls[ $row[ 'id' ] ], $options ); + curl_setopt_array($curls[$row['id']], $options); - curl_multi_add_handle( $mh, $curls[ $row[ 'id' ] ] ); + curl_multi_add_handle($mh, $curls[$row['id']]); } - + // self::debug('-----debug1'); // execute curl - if ( $curls ) { - $last_start_time = null; + if ($curls) { do { - curl_multi_exec( $mh, $last_start_time ); - if ( curl_multi_select( $mh ) == -1 ) { - usleep( 1 ); + $status = curl_multi_exec($mh, $active); + if ($active) { + curl_multi_select($mh); } - } while ( $last_start_time > 0 ); + } while ($active && $status == CURLM_OK); } - + // self::debug('-----debug2'); // curl done $ret = array(); - foreach ( $rows as $row ) { - if ( substr( $row[ 'res' ], $this->_summary[ 'curr_crawler' ], 1 ) == 'B' ) { + foreach ($rows as $row) { + if (substr($row['res'], $this->_summary['curr_crawler'], 1) == 'B') { continue; } - if ( substr( $row[ 'res' ], $this->_summary[ 'curr_crawler' ], 1 ) == 'N' ) { + if (substr($row['res'], $this->_summary['curr_crawler'], 1) == 'N') { continue; } - - $ch = $curls[ $row[ 'id' ] ]; + // self::debug('-----debug3'); + $ch = $curls[$row['id']]; // Parse header - $header_size = curl_getinfo( $ch, CURLINFO_HEADER_SIZE ); - $content = curl_multi_getcontent( $ch ); - $header = substr( $content, 0, $header_size ); + $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + $content = curl_multi_getcontent($ch); + $header = substr($content, 0, $header_size); - $ret[ $row[ 'id' ] ] = array( + $ret[$row['id']] = array( 'header' => $header, - 'code' => curl_getinfo( $ch, CURLINFO_HTTP_CODE ), + 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), ); - - curl_multi_remove_handle( $mh, $ch ); - curl_close( $ch ); + // self::debug('-----debug4'); + curl_multi_remove_handle($mh, $ch); + curl_close($ch); } - curl_multi_close( $mh ); - + // self::debug('-----debug5'); + curl_multi_close($mh); + // self::debug('-----debug6'); return $ret; } + /** + * Translate the status to title + * @since 6.0 + */ + private function _status2title($status) + { + if ($status == 'H') { + return '✅ Hit'; + } + if ($status == 'M') { + return '😊 Miss'; + } + if ($status == 'B') { + return '😅 Blacklisted'; + } + if ($status == 'N') { + return '😅 Blacklisted'; + } + return '🛸 Unknown'; + } + /** * Check returned curl header to find if cached or not * * @since 2.0 * @access private */ - private function _status_parse( $header, $code, $url ) { - if ( $code == 201 ) { + private function _status_parse($header, $code, $url) + { + if ($code == 201) { return 'H'; } - if ( stripos( $header, 'X-Litespeed-Cache-Control: no-cache' ) !== false ) { + if (stripos($header, 'X-Litespeed-Cache-Control: no-cache') !== false) { // If is from DIVI, taken as miss - if ( defined( 'LITESPEED_CRAWLER_IGNORE_NONCACHEABLE' ) && LITESPEED_CRAWLER_IGNORE_NONCACHEABLE ) { + if (defined('LITESPEED_CRAWLER_IGNORE_NONCACHEABLE') && LITESPEED_CRAWLER_IGNORE_NONCACHEABLE) { return 'M'; } // If blacklist is disabled - if ( ( defined( 'LITESPEED_CRAWLER_DISABLE_BLOCKLIST' ) && LITESPEED_CRAWLER_DISABLE_BLOCKLIST ) || apply_filters( 'litespeed_crawler_disable_blocklist', '__return_false', $url ) ) { + if ( + (defined('LITESPEED_CRAWLER_DISABLE_BLOCKLIST') && LITESPEED_CRAWLER_DISABLE_BLOCKLIST) || + apply_filters('litespeed_crawler_disable_blocklist', '__return_false', $url) + ) { return 'M'; } return 'N'; // Blacklist } - $_cache_headers = array( - 'x-litespeed-cache', - 'x-lsadc-cache', - 'x-qc-cache', - ); + $_cache_headers = array('x-litespeed-cache', 'x-lsadc-cache', 'x-qc-cache'); - foreach ( $_cache_headers as $_header ) { - if ( stripos( $header, $_header ) !== false ) { - if ( stripos( $header, $_header . ': miss' ) !== false ) { + foreach ($_cache_headers as $_header) { + if (stripos($header, $_header) !== false) { + if (stripos($header, $_header . ': miss') !== false) { return 'M'; // Miss } return 'H'; // Hit @@ -703,7 +908,10 @@ private function _status_parse( $header, $code, $url ) { } // If blacklist is disabled - if ( ( defined( 'LITESPEED_CRAWLER_DISABLE_BLOCKLIST' ) && LITESPEED_CRAWLER_DISABLE_BLOCKLIST ) || apply_filters( 'litespeed_crawler_disable_blocklist', '__return_false', $url ) ) { + if ( + (defined('LITESPEED_CRAWLER_DISABLE_BLOCKLIST') && LITESPEED_CRAWLER_DISABLE_BLOCKLIST) || + apply_filters('litespeed_crawler_disable_blocklist', '__return_false', $url) + ) { return 'M'; } @@ -716,7 +924,8 @@ private function _status_parse( $header, $code, $url ) { * @since 1.1.0 * @access private */ - private function _get_curl_options( $crawler_only = false ) { + private function _get_curl_options($crawler_only = false) + { $options = array( CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, @@ -724,13 +933,13 @@ private function _get_curl_options( $crawler_only = false ) { CURLOPT_FOLLOWLOCATION => false, CURLOPT_ENCODING => 'gzip', CURLOPT_CONNECTTIMEOUT => 10, - CURLOPT_TIMEOUT => $this->conf( Base::O_CRAWLER_TIMEOUT ), // Larger timeout to avoid incorrect blacklist addition #900171 + CURLOPT_TIMEOUT => $this->conf(Base::O_CRAWLER_TIMEOUT), // Larger timeout to avoid incorrect blacklist addition #900171 CURLOPT_SSL_VERIFYHOST => 0, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_NOBODY => false, - CURLOPT_HTTPHEADER => $this->_crawler_conf[ 'headers' ], + CURLOPT_HTTPHEADER => $this->_crawler_conf['headers'], ); - $options[ CURLOPT_HTTPHEADER ][] = 'Cache-Control: max-age=0'; + $options[CURLOPT_HTTPHEADER][] = 'Cache-Control: max-age=0'; /** * Try to enable http2 connection (only available since PHP7+) @@ -738,23 +947,23 @@ private function _get_curl_options( $crawler_only = false ) { * @since 2.2.7 Commented due to cause no-cache issue * @since 2.9.1+ Fixed wrongly usage of CURL_HTTP_VERSION_1_1 const */ - $options[ CURLOPT_HTTP_VERSION ] = CURL_HTTP_VERSION_1_1; + $options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1; // $options[ CURL_HTTP_VERSION_2 ] = 1; // IP resolve - if ( $this->conf( Base::O_SERVER_IP ) ) { + if ($this->conf(Base::O_SERVER_IP)) { Utility::compatibility(); - if ( ( $this->conf( Base::O_CRAWLER_DROP_DOMAIN ) || ! $crawler_only ) && $this->_crawler_conf[ 'base' ] ) { + if (($this->conf(Base::O_CRAWLER_DROP_DOMAIN) || !$crawler_only) && $this->_crawler_conf['base']) { // Resolve URL to IP - $parsed_url = parse_url( $this->_crawler_conf[ 'base' ] ); + $parsed_url = parse_url($this->_crawler_conf['base']); - if ( ! empty( $parsed_url[ 'host' ] ) ) { - $dom = $parsed_url[ 'host' ]; - $port = $parsed_url[ 'scheme' ] == 'https' ? '443' : '80'; - $url = $dom . ':' . $port . ':' . $this->conf( Base::O_SERVER_IP ); + if (!empty($parsed_url['host'])) { + $dom = $parsed_url['host']; + $port = $parsed_url['scheme'] == 'https' ? '443' : '80'; + $url = $dom . ':' . $port . ':' . $this->conf(Base::O_SERVER_IP); - $options[ CURLOPT_RESOLVE ] = array( $url ); - $options[ CURLOPT_DNS_USE_GLOBAL_CACHE ] = false; + $options[CURLOPT_RESOLVE] = array($url); + $options[CURLOPT_DNS_USE_GLOBAL_CACHE] = false; } } } @@ -763,36 +972,36 @@ private function _get_curl_options( $crawler_only = false ) { // $options[ CURLOPT_FRESH_CONNECT ] = true; // Referer - if ( isset( $_SERVER[ 'HTTP_HOST' ] ) && isset( $_SERVER[ 'REQUEST_URI' ] ) ) { - $options[ CURLOPT_REFERER ] = 'http://' . $_SERVER[ 'HTTP_HOST' ] . $_SERVER[ 'REQUEST_URI' ]; + if (isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) { + $options[CURLOPT_REFERER] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; } // User Agent - if ( $crawler_only ) { - if ( strpos( $this->_crawler_conf[ 'ua' ], Crawler::FAST_USER_AGENT ) !== 0 ) { - $this->_crawler_conf[ 'ua' ] = Crawler::FAST_USER_AGENT . ' ' . $this->_crawler_conf[ 'ua' ]; + if ($crawler_only) { + if (strpos($this->_crawler_conf['ua'], Crawler::FAST_USER_AGENT) !== 0) { + $this->_crawler_conf['ua'] = Crawler::FAST_USER_AGENT . ' ' . $this->_crawler_conf['ua']; } } - $options[ CURLOPT_USERAGENT ] = $this->_crawler_conf[ 'ua' ]; + $options[CURLOPT_USERAGENT] = $this->_crawler_conf['ua']; /** * Append hash to cookie for validation * @since 1.9.1 */ - if ( $crawler_only ) { - $this->_crawler_conf[ 'cookies' ][ 'litespeed_hash' ] = Router::get_hash(); + if ($crawler_only) { + $this->_crawler_conf['cookies']['litespeed_hash'] = Router::get_hash(); } // Cookies $cookies = array(); - foreach ( $this->_crawler_conf[ 'cookies' ] as $k => $v ) { - if ( ! $v ) { + foreach ($this->_crawler_conf['cookies'] as $k => $v) { + if (!$v) { continue; } - $cookies[] = $k . '=' . urlencode( $v ); + $cookies[] = $k . '=' . urlencode($v); } - if ( $cookies ) { - $options[ CURLOPT_COOKIE ] = implode( '; ', $cookies ); + if ($cookies) { + $options[CURLOPT_COOKIE] = implode('; ', $cookies); } return $options; @@ -803,30 +1012,32 @@ private function _get_curl_options( $crawler_only = false ) { * * @since 3.3 */ - public function self_curl( $url, $ua, $uid = false, $accept = false ) { // $accept not in use yet - $this->_crawler_conf[ 'base' ] = home_url(); - $this->_crawler_conf[ 'ua' ] = $ua; - if ( $accept ) { - $this->_crawler_conf[ 'headers' ] = array( 'Accept: ' . $accept ); + public function self_curl($url, $ua, $uid = false, $accept = false) + { + // $accept not in use yet + $this->_crawler_conf['base'] = home_url(); + $this->_crawler_conf['ua'] = $ua; + if ($accept) { + $this->_crawler_conf['headers'] = array('Accept: ' . $accept); } - if ( $uid ) { - $this->_crawler_conf[ 'cookies' ][ 'litespeed_role' ] = $uid; - $this->_crawler_conf[ 'cookies' ][ 'litespeed_hash' ] = Router::get_hash(); + if ($uid) { + $this->_crawler_conf['cookies']['litespeed_role'] = $uid; + $this->_crawler_conf['cookies']['litespeed_hash'] = Router::get_hash(); } $options = $this->_get_curl_options(); - $options[ CURLOPT_HEADER ] = false; - $options[ CURLOPT_FOLLOWLOCATION ] = true; + $options[CURLOPT_HEADER] = false; + $options[CURLOPT_FOLLOWLOCATION] = true; $ch = curl_init(); - curl_setopt_array( $ch, $options ); - curl_setopt( $ch, CURLOPT_URL, $url ); - $result = curl_exec( $ch ); - $code = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); - curl_close( $ch ); - - if ( $code != 200 ) { - self::debug('❌ Response code is not 200 in self_curl() [code] ' . var_export( $code, true ) ); + curl_setopt_array($ch, $options); + curl_setopt($ch, CURLOPT_URL, $url); + $result = curl_exec($ch); + $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + + if ($code != 200) { + self::debug('❌ Response code is not 200 in self_curl() [code] ' . var_export($code, true)); return false; } @@ -839,27 +1050,29 @@ public function self_curl( $url, $ua, $uid = false, $accept = false ) { // $acce * @since 1.1.0 * @access private */ - private function _terminate_running() { - $this->_map_status_list = $this->cls( 'Crawler_Map' )->save_map_status( $this->_map_status_list, $this->_summary[ 'curr_crawler' ] ); + private function _terminate_running() + { + $this->_map_status_list = $this->cls('Crawler_Map')->save_map_status($this->_map_status_list, $this->_summary['curr_crawler']); - if ( $this->_end_reason == 'end' ) { // Current crawler is fully done + if ($this->_end_reason == 'end') { + // Current crawler is fully done // $end_reason = sprintf( __( 'Crawler %s reached end of sitemap file.', 'litespeed-cache' ), '#' . ( $this->_summary['curr_crawler'] + 1 ) ); - $this->_summary[ 'curr_crawler' ]++; // Jump to next cralwer + $this->_summary['curr_crawler']++; // Jump to next cralwer // $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ] = array(); // reset this at next crawl time - $this->_summary[ 'last_pos' ] = 0;// reset last position - $this->_summary[ 'last_crawler_total_cost' ] = time() - $this->_summary[ 'curr_crawler_beginning_time' ]; - $count_crawlers = count( $this->list_crawlers() ); - if ( $this->_summary[ 'curr_crawler' ] >= $count_crawlers ) { - self::debug( '_terminate_running Touched end, whole crawled. Reload crawler!' ); - $this->_summary[ 'curr_crawler' ] = 0; + $this->_summary['last_pos'] = 0; // reset last position + $this->_summary['last_crawler_total_cost'] = time() - $this->_summary['curr_crawler_beginning_time']; + $count_crawlers = count($this->list_crawlers()); + if ($this->_summary['curr_crawler'] >= $count_crawlers) { + self::debug('_terminate_running Touched end, whole crawled. Reload crawler!'); + $this->_summary['curr_crawler'] = 0; // $this->_summary[ 'crawler_stats' ][ $this->_summary[ 'curr_crawler' ] ] = array(); - $this->_summary[ 'done' ] = 'touchedEnd';// log done status - $this->_summary[ 'last_full_time_cost' ] = time() - $this->_summary[ 'this_full_beginning_time' ]; + $this->_summary['done'] = 'touchedEnd'; // log done status + $this->_summary['last_full_time_cost'] = time() - $this->_summary['this_full_beginning_time']; } } - $this->_summary[ 'last_status' ] = 'stopped'; - $this->_summary[ 'is_running' ] = 0; - $this->_summary[ 'end_reason' ] = $this->_end_reason; + $this->_summary['last_status'] = 'stopped'; + $this->_summary['is_running'] = 0; + $this->_summary['end_reason'] = $this->_end_reason; self::save_summary(); } @@ -869,69 +1082,71 @@ private function _terminate_running() { * @since 1.9.1 * @access public */ - public function list_crawlers() { - if ( $this->_crawlers ) { + public function list_crawlers() + { + if ($this->_crawlers) { return $this->_crawlers; } $crawler_factors = array(); // Add default Guest crawler - $crawler_factors[ 'uid' ] = array( 0 => __( 'Guest', 'litespeed-cache' ) ); + $crawler_factors['uid'] = array(0 => __('Guest', 'litespeed-cache')); // WebP on/off - if ( $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE ) ) { - $crawler_factors[ 'webp' ] = array( 1 => 'WebP', 0 => '' ); + if (($this->conf(Base::O_GUEST) && $this->conf(Base::O_GUEST_OPTM)) || $this->conf(Base::O_IMG_OPTM_WEBP)) { + $crawler_factors['webp'] = array(1 => 'WebP', 0 => ''); } // Guest Mode on/off - if ( $this->conf( Base::O_GUEST ) ) { - $vary_name = $this->cls( 'Vary' )->get_vary_name(); + if ($this->conf(Base::O_GUEST)) { + $vary_name = $this->cls('Vary')->get_vary_name(); $vary_val = 'guest_mode:1'; - if ( ! defined( 'LSCWP_LOG' ) ) { - $vary_val = md5( $this->conf( Base::HASH ) . $vary_val ); + if (!defined('LSCWP_LOG')) { + $vary_val = md5($this->conf(Base::HASH) . $vary_val); } - $crawler_factors[ 'cookie:' . $vary_name ] = array( $vary_val => '', '_null' => '👒' ); + $crawler_factors['cookie:' . $vary_name] = array($vary_val => '', '_null' => '👒'); } // Mobile crawler - if ( $this->conf( Base::O_CACHE_MOBILE ) ) { - $crawler_factors[ 'mobile' ] = array( 1 => '📱', 0 => '' ); + if ($this->conf(Base::O_CACHE_MOBILE)) { + $crawler_factors['mobile'] = array(1 => '📱', 0 => ''); } // Get roles set // List all roles - foreach ( $this->conf( Base::O_CRAWLER_ROLES ) as $v ) { + foreach ($this->conf(Base::O_CRAWLER_ROLES) as $v) { $role_title = ''; - $udata = get_userdata( $v ); - if ( isset( $udata->roles ) && is_array( $udata->roles ) ) { - $tmp = array_values( $udata->roles ); - $role_title = array_shift( $tmp ); + $udata = get_userdata($v); + if (isset($udata->roles) && is_array($udata->roles)) { + $tmp = array_values($udata->roles); + $role_title = array_shift($tmp); } - if ( ! $role_title ) { + if (!$role_title) { continue; } - $crawler_factors[ 'uid' ][ $v ] = ucfirst( $role_title ); + $crawler_factors['uid'][$v] = ucfirst($role_title); } // Cookie crawler - foreach ( $this->conf( Base::O_CRAWLER_COOKIES ) as $v ) { - if ( empty( $v[ 'name' ] ) ) { + foreach ($this->conf(Base::O_CRAWLER_COOKIES) as $v) { + if (empty($v['name'])) { continue; } - $this_cookie_key = 'cookie:' . $v[ 'name' ]; + $this_cookie_key = 'cookie:' . $v['name']; - $crawler_factors[ $this_cookie_key ] = array(); + $crawler_factors[$this_cookie_key] = array(); - foreach ( $v[ 'vals' ] as $v2 ) { - $crawler_factors[ $this_cookie_key ][ $v2 ] = $v2 == '_null' ? '' : '🍪' . esc_html( $v[ 'name' ] ) . '=' . esc_html( $v2 ); + foreach ($v['vals'] as $v2) { + $crawler_factors[$this_cookie_key][$v2] = + $v2 == '_null' ? '' : '🍪' . esc_html($v['name']) . '=' . esc_html($v2); } } // Crossing generate the crawler list - $this->_crawlers = $this->_recursive_build_crawler( $crawler_factors ); + $this->_crawlers = $this->_recursive_build_crawler($crawler_factors); return $this->_crawlers; } @@ -942,65 +1157,79 @@ public function list_crawlers() { * @since 2.8 * @access private */ - private function _recursive_build_crawler( $crawler_factors, $group = array(), $i = 0 ) { - $current_factor = array_keys( $crawler_factors ); - $current_factor = $current_factor[ $i ]; + private function _recursive_build_crawler($crawler_factors, $group = array(), $i = 0) + { + $current_factor = array_keys($crawler_factors); + $current_factor = $current_factor[$i]; - $if_touch_end = $i + 1 >= count( $crawler_factors ); + $if_touch_end = $i + 1 >= count($crawler_factors); $final_list = array(); - foreach ( $crawler_factors[ $current_factor ] as $k => $v ) { - + foreach ($crawler_factors[$current_factor] as $k => $v) { // Don't alter $group bcos of loop usage $item = $group; - $item[ 'title' ] = ! empty( $group[ 'title' ] ) ? $group[ 'title' ] : ''; - if ( $v ) { - if ( $item[ 'title' ] ) { - $item[ 'title' ] .= ' - '; + $item['title'] = !empty($group['title']) ? $group['title'] : ''; + if ($v) { + if ($item['title']) { + $item['title'] .= ' - '; } - $item[ 'title' ] .= $v; + $item['title'] .= $v; } - $item[ $current_factor ] = $k; + $item[$current_factor] = $k; - if ( $if_touch_end ) { + if ($if_touch_end) { $final_list[] = $item; - } - else { + } else { // Inception: next layer - $final_list = array_merge( $final_list, $this->_recursive_build_crawler( $crawler_factors, $item, $i + 1 ) ); + $final_list = array_merge($final_list, $this->_recursive_build_crawler($crawler_factors, $item, $i + 1)); } - } return $final_list; } + /** + * Return crawler meta file local path + * + * @since 6.1 + * @access public + */ + public function json_local_path() + { + if (!file_exists(LITESPEED_STATIC_DIR . '/crawler/' . $this->_sitemeta)) { + return false; + } + + return LITESPEED_STATIC_DIR . '/crawler/' . $this->_sitemeta; + } + /** * Return crawler meta file * * @since 1.1.0 * @access public */ - public function json_path() { - if ( ! file_exists( LITESPEED_STATIC_DIR . '/crawler/' . $this->_sitemeta ) ) { + public function json_path() + { + if (!file_exists(LITESPEED_STATIC_DIR . '/crawler/' . $this->_sitemeta)) { return false; } return LITESPEED_STATIC_URL . '/crawler/' . $this->_sitemeta; } - /** * Create reset pos file * * @since 1.1.0 * @access public */ - public function reset_pos() { - File::save( $this->_resetfile, time() , true ); + public function reset_pos() + { + File::save($this->_resetfile, time(), true); - self::save_summary( array( 'is_running' => 0 ) ); + self::save_summary(array('is_running' => 0)); } /** @@ -1009,8 +1238,9 @@ public function reset_pos() { * @since 3.0 * @access public */ - public function display_status( $status_row, $reason_set ) { - if ( ! $status_row ) { + public function display_status($status_row, $reason_set) + { + if (!$status_row) { return ''; } @@ -1022,21 +1252,21 @@ public function display_status( $status_row, $reason_set ) { 'N' => 'warning', ); - $reason_set = explode( ',', $reason_set ); + $reason_set = explode(',', $reason_set); $status = ''; - foreach ( str_split( $status_row ) as $k => $v ) { - $reason = $reason_set[ $k ]; - if ( $reason == 'Man' ) { - $reason = __( 'Manually added to blocklist', 'litespeed-cache' ); + foreach (str_split($status_row) as $k => $v) { + $reason = $reason_set[$k]; + if ($reason == 'Man') { + $reason = __('Manually added to blocklist', 'litespeed-cache'); } - if ( $reason == 'Existed' ) { - $reason = __( 'Previously existed in blocklist', 'litespeed-cache' ); + if ($reason == 'Existed') { + $reason = __('Previously existed in blocklist', 'litespeed-cache'); } - if ( $reason ) { + if ($reason) { $reason = 'data-balloon-pos="up" aria-label="' . $reason . '"'; } - $status .= '' . ( $k + 1 ) . ''; + $status .= '' . ($k + 1) . ''; } return $status; @@ -1049,12 +1279,12 @@ public function display_status( $status_row, $reason_set ) { * @access protected * @param string $error Error info */ - protected function output($msg) { - if ( defined('DOING_CRON') ) { + protected function output($msg) + { + if (defined('DOING_CRON')) { echo $msg; // exit(); - } - else { + } else { echo ""; // exit; } @@ -1066,37 +1296,38 @@ protected function output($msg) { * @since 3.0 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_REFRESH_MAP: - $this->cls( 'Crawler_Map' )->gen(); + $this->cls('Crawler_Map')->gen(); break; case self::TYPE_EMPTY: - $this->cls( 'Crawler_Map' )->empty_map(); + $this->cls('Crawler_Map')->empty_map(); break; case self::TYPE_BLACKLIST_EMPTY: - $this->cls( 'Crawler_Map' )->blacklist_empty(); + $this->cls('Crawler_Map')->blacklist_empty(); break; case self::TYPE_BLACKLIST_DEL: - if ( ! empty( $_GET[ 'id' ] ) ) { - $this->cls( 'Crawler_Map' )->blacklist_del( $_GET[ 'id' ] ); + if (!empty($_GET['id'])) { + $this->cls('Crawler_Map')->blacklist_del($_GET['id']); } break; case self::TYPE_BLACKLIST_ADD: - if ( ! empty( $_GET[ 'id' ] ) ) { - $this->cls( 'Crawler_Map' )->blacklist_add( $_GET[ 'id' ] ); + if (!empty($_GET['id'])) { + $this->cls('Crawler_Map')->blacklist_add($_GET['id']); } break; // Handle the ajax request to proceed crawler manually by admin case self::TYPE_START: - self::start( true ); + self::start_async(); break; case self::TYPE_RESET: @@ -1109,5 +1340,4 @@ public function handler() { Admin::redirect(); } - } diff --git a/src/css.cls.php b/src/css.cls.php index 590d55595..c244b5884 100644 --- a/src/css.cls.php +++ b/src/css.cls.php @@ -1,13 +1,17 @@ _summary = self::get_summary(); } @@ -29,8 +35,9 @@ public function __construct() { * HTML lazyload CSS * @since 4.0 */ - public function prepare_html_lazy() { - return ''; + public function prepare_html_lazy() + { + return ''; } /** @@ -39,21 +46,23 @@ public function prepare_html_lazy() { * @since 1.3 * @access public */ - public function prepare_ccss() { + public function prepare_ccss() + { // Get critical css for current page // Note: need to consider mobile $rules = $this->_ccss(); - if ( ! $rules ) { + if (!$rules) { return null; } $error_tag = ''; - if ( substr( $rules, 0, 2 ) == '/*' && substr( $rules, -2 ) == '*/' ) { + if (substr($rules, 0, 2) == '/*' && substr($rules, -2) == '*/') { + Core::comment('QUIC.cloud CCSS bypassed due to generation error ❌'); $error_tag = ' data-error="failed to generate"'; } // Append default critical css - $rules .= $this->conf( self::O_OPTM_CCSS_CON ); + $rules .= $this->conf(self::O_OPTM_CCSS_CON); return ''; } @@ -63,26 +72,27 @@ public function prepare_ccss() { * * @since 4.0 */ - private function _gen_ccss_file_tag( $request_url ) { - if ( is_404() ) { + private function _gen_ccss_file_tag($request_url) + { + if (is_404()) { return '404'; } - if ( $this->conf( self::O_OPTM_CCSS_PER_URL ) ) { + if ($this->conf(self::O_OPTM_CCSS_PER_URL)) { return $request_url; } - $sep_uri = $this->conf( self::O_OPTM_CCSS_SEP_URI ); - if ( $sep_uri && $hit = Utility::str_hit_array( $request_url, $sep_uri ) ) { - Debug2::debug( '[CCSS] Separate CCSS due to separate URI setting: ' . $hit ); + $sep_uri = $this->conf(self::O_OPTM_CCSS_SEP_URI); + if ($sep_uri && ($hit = Utility::str_hit_array($request_url, $sep_uri))) { + Debug2::debug('[CCSS] Separate CCSS due to separate URI setting: ' . $hit); return $request_url; } $pt = Utility::page_type(); - $sep_pt = $this->conf( self::O_OPTM_CCSS_SEP_POSTTYPE ); - if ( in_array( $pt, $sep_pt ) ) { - Debug2::debug( '[CCSS] Separate CCSS due to posttype setting: ' . $pt ); + $sep_pt = $this->conf(self::O_OPTM_CCSS_SEP_POSTTYPE); + if (in_array($pt, $sep_pt)) { + Debug2::debug('[CCSS] Separate CCSS due to posttype setting: ' . $pt); return $request_url; } @@ -95,62 +105,64 @@ private function _gen_ccss_file_tag( $request_url ) { * * @since 2.3 */ - private function _ccss() { + private function _ccss() + { global $wp; - $request_url = home_url( $wp->request ); + $request_url = home_url($wp->request); - $filepath_prefix = $this->_build_filepath_prefix( 'ccss' ); - $url_tag = $this->_gen_ccss_file_tag( $request_url ); - $vary = $this->cls( 'Vary' )->finalize_full_varies(); - $filename = $this->cls( 'Data' )->load_url_file( $url_tag, $vary, 'ccss' ); - if ( $filename ) { + $filepath_prefix = $this->_build_filepath_prefix('ccss'); + $url_tag = $this->_gen_ccss_file_tag($request_url); + $vary = $this->cls('Vary')->finalize_full_varies(); + $filename = $this->cls('Data')->load_url_file($url_tag, $vary, 'ccss'); + if ($filename) { $static_file = LITESPEED_STATIC_DIR . $filepath_prefix . $filename . '.css'; - if ( file_exists( $static_file ) ) { - Debug2::debug2( '[CSS] existing ccss ' . $static_file ); - return File::read( $static_file ); + if (file_exists($static_file)) { + Debug2::debug2('[CSS] existing ccss ' . $static_file); + Core::comment('QUIC.cloud CCSS loaded ✅ ' . $filepath_prefix . $filename . '.css'); + return File::read($static_file); } } $uid = get_current_user_id(); - $ua = ! empty( $_SERVER[ 'HTTP_USER_AGENT' ] ) ? $_SERVER[ 'HTTP_USER_AGENT' ] : ''; - + $ua = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; // Store it to prepare for cron - $this->_queue = $this->load_queue( 'ccss' ); + Core::comment('QUIC.cloud CCSS in queue'); + $this->_queue = $this->load_queue('ccss'); - if ( count( $this->_queue ) > 500 ) { - self::debug( 'CCSS Queue is full - 500' ); + if (count($this->_queue) > 500) { + self::debug('CCSS Queue is full - 500'); return null; } - $queue_k = ( strlen( $vary ) > 32 ? md5( $vary ) : $vary ) . ' ' . $url_tag; - $this->_queue[ $queue_k ] = array( - 'url' => apply_filters( 'litespeed_ccss_url', $request_url ), - 'user_agent' => substr( $ua, 0, 200 ), - 'is_mobile' => $this->_separate_mobile(), - 'is_webp' => $this->cls( 'Media' )->webp_support() ? 1 : 0, - 'uid' => $uid, - 'vary' => $vary, - 'url_tag' => $url_tag, + $queue_k = (strlen($vary) > 32 ? md5($vary) : $vary) . ' ' . $url_tag; + $this->_queue[$queue_k] = array( + 'url' => apply_filters('litespeed_ccss_url', $request_url), + 'user_agent' => substr($ua, 0, 200), + 'is_mobile' => $this->_separate_mobile(), + 'is_webp' => $this->cls('Media')->webp_support() ? 1 : 0, + 'uid' => $uid, + 'vary' => $vary, + 'url_tag' => $url_tag, ); // Current UA will be used to request - $this->save_queue( 'ccss', $this->_queue ); - self::debug( 'Added queue_ccss [url_tag] ' . $url_tag . ' [UA] ' . $ua . ' [vary] ' . $vary . ' [uid] ' . $uid ); + $this->save_queue('ccss', $this->_queue); + self::debug('Added queue_ccss [url_tag] ' . $url_tag . ' [UA] ' . $ua . ' [vary] ' . $vary . ' [uid] ' . $uid); // Prepare cache tag for later purge - Tag::add( 'CCSS.' . md5( $queue_k ) ); + Tag::add('CCSS.' . md5($queue_k)); // For v4.1- clean up - if ( isset( $this->_summary[ 'ccss_type_history' ] ) || isset( $this->_summary[ 'ccss_history' ] ) || isset( $this->_summary[ 'queue_ccss' ] ) ) { - if ( isset( $this->_summary[ 'ccss_type_history' ] ) ) { - unset( $this->_summary[ 'ccss_type_history' ] ); + if (isset($this->_summary['ccss_type_history']) || isset($this->_summary['ccss_history']) || isset($this->_summary['queue_ccss'])) { + if (isset($this->_summary['ccss_type_history'])) { + unset($this->_summary['ccss_type_history']); } - if ( isset( $this->_summary[ 'ccss_history' ] ) ) { - unset( $this->_summary[ 'ccss_history' ] ); + if (isset($this->_summary['ccss_history'])) { + unset($this->_summary['ccss_history']); } - if ( isset( $this->_summary[ 'queue_ccss' ] ) ) { - unset( $this->_summary[ 'queue_ccss' ] ); + if (isset($this->_summary['queue_ccss'])) { + unset($this->_summary['queue_ccss']); } self::save_summary(); } @@ -164,9 +176,10 @@ private function _ccss() { * @since 2.3 * @access private */ - public static function cron_ccss( $continue = false ) { + public static function cron_ccss($continue = false) + { $_instance = self::cls(); - return $_instance->_cron_handler( 'ccss', $continue ); + return $_instance->_cron_handler('ccss', $continue); } /** @@ -174,76 +187,89 @@ public static function cron_ccss( $continue = false ) { * * @since 4.2 */ - private function _cron_handler( $type, $continue ) { - $this->_queue = $this->load_queue( $type ); + private function _cron_handler($type, $continue) + { + $this->_queue = $this->load_queue($type); - if ( empty( $this->_queue ) ) { + if (empty($this->_queue)) { return; } - $type_tag = strtoupper( $type ); + $type_tag = strtoupper($type); // For cron, need to check request interval too - if ( ! $continue ) { - if ( ! empty( $this->_summary[ 'curr_request_' . $type ] ) && time() - $this->_summary[ 'curr_request_' . $type ] < 300 && ! $this->conf( self::O_DEBUG ) ) { - Debug2::debug( '[' . $type_tag . '] Last request not done' ); + if (!$continue) { + if (!empty($this->_summary['curr_request_' . $type]) && time() - $this->_summary['curr_request_' . $type] < 300 && !$this->conf(self::O_DEBUG)) { + Debug2::debug('[' . $type_tag . '] Last request not done'); return; } } $i = 0; - foreach ( $this->_queue as $k => $v ) { - if ( ! empty( $v[ '_status' ] ) ) { + $timeoutLimit = ini_get('max_execution_time'); + $this->_endts = time() + $timeoutLimit; + foreach ($this->_queue as $k => $v) { + if (!empty($v['_status'])) { continue; } - Debug2::debug( '[' . $type_tag . '] cron job [tag] ' . $k . ' [url] ' . $v[ 'url' ] . ( $v[ 'is_mobile' ] ? ' 📱 ' : '' ) . ' [UA] ' . $v[ 'user_agent' ] ); + if (function_exists('set_time_limit')) { + $this->_endts += 120; + set_time_limit(120); + } + if ($this->_endts - time() < 10) { + // self::debug("🚨 End loop due to timeout limit reached " . $timeoutLimit . "s"); + // return; + } + + Debug2::debug('[' . $type_tag . '] cron job [tag] ' . $k . ' [url] ' . $v['url'] . ($v['is_mobile'] ? ' 📱 ' : '') . ' [UA] ' . $v['user_agent']); - if ( $type == 'ccss' && empty( $v[ 'url_tag' ] ) ) { - unset( $this->_queue[ $k ] ); - $this->save_queue( $type, $this->_queue ); - Debug2::debug( '[CCSS] wrong queue_ccss format' ); + if ($type == 'ccss' && empty($v['url_tag'])) { + unset($this->_queue[$k]); + $this->save_queue($type, $this->_queue); + Debug2::debug('[CCSS] wrong queue_ccss format'); continue; } - if ( ! isset( $v[ 'is_webp' ] ) ) { - $v[ 'is_webp' ] = false; + if (!isset($v['is_webp'])) { + $v['is_webp'] = false; } - $i ++; - $res = $this->_send_req( $v[ 'url' ], $k, $v[ 'uid' ], $v[ 'user_agent' ], $v[ 'vary' ], $v[ 'url_tag' ], $type, $v[ 'is_mobile' ], $v[ 'is_webp' ] ); - if ( ! $res ) { // Status is wrong, drop this this->_queue - unset( $this->_queue[ $k ] ); - $this->save_queue( $type, $this->_queue ); + $i++; + $res = $this->_send_req($v['url'], $k, $v['uid'], $v['user_agent'], $v['vary'], $v['url_tag'], $type, $v['is_mobile'], $v['is_webp']); + if (!$res) { + // Status is wrong, drop this this->_queue + unset($this->_queue[$k]); + $this->save_queue($type, $this->_queue); - if ( ! $continue ) { + if (!$continue) { return; } - if ( $i > 3 ) { - GUI::print_loading( count( $this->_queue ), $type_tag ); - return Router::self_redirect( Router::ACTION_CSS, CSS::TYPE_GEN_CCSS ); + if ($i > 3) { + GUI::print_loading(count($this->_queue), $type_tag); + return Router::self_redirect(Router::ACTION_CSS, CSS::TYPE_GEN_CCSS); } continue; } // Exit queue if out of quota - if ( $res === 'out_of_quota' ) { + if ($res === 'out_of_quota') { return; } - $this->_queue[ $k ][ '_status' ] = 'requested'; - $this->save_queue( $type, $this->_queue ); + $this->_queue[$k]['_status'] = 'requested'; + $this->save_queue($type, $this->_queue); // only request first one - if ( ! $continue ) { + if (!$continue) { return; } - if ( $i > 3 ) { - GUI::print_loading( count( $this->_queue ), $type_tag ); - return Router::self_redirect( Router::ACTION_CSS, CSS::TYPE_GEN_CCSS ); + if ($i > 3) { + GUI::print_loading(count($this->_queue), $type_tag); + return Router::self_redirect(Router::ACTION_CSS, CSS::TYPE_GEN_CCSS); } } } @@ -254,59 +280,58 @@ private function _cron_handler( $type, $continue ) { * @since 2.3 * @access private */ - private function _send_req( $request_url, $queue_k, $uid, $user_agent, $vary, $url_tag, $type, $is_mobile, $is_webp ) { + private function _send_req($request_url, $queue_k, $uid, $user_agent, $vary, $url_tag, $type, $is_mobile, $is_webp) + { // Check if has credit to push or not $err = false; - $allowance = $this->cls( 'Cloud' )->allowance( Cloud::SVC_CCSS, $err ); - if ( ! $allowance ) { - Debug2::debug( '[CCSS] ❌ No credit: ' . $err ); - $err && Admin_Display::error( Error::msg( $err ) ); + $allowance = $this->cls('Cloud')->allowance(Cloud::SVC_CCSS, $err); + if (!$allowance) { + Debug2::debug('[CCSS] ❌ No credit: ' . $err); + $err && Admin_Display::error(Error::msg($err)); return 'out_of_quota'; } - set_time_limit( 120 ); - // Update css request status - $this->_summary[ 'curr_request_' . $type ] = time(); + $this->_summary['curr_request_' . $type] = time(); self::save_summary(); // Gather guest HTML to send - $html = $this->prepare_html( $request_url, $user_agent, $uid ); + $html = $this->prepare_html($request_url, $user_agent, $uid); - if ( ! $html ) { + if (!$html) { return false; } // Parse HTML to gather all CSS content before requesting - list( $css, $html ) = $this->prepare_css( $html, $is_webp ); + list($css, $html) = $this->prepare_css($html, $is_webp); - if ( ! $css ) { - Debug2::debug( '[UCSS] ❌ No combined css' ); + if (!$css) { + Debug2::debug('[UCSS] ❌ No combined css'); return false; } // Generate critical css $data = array( - 'url' => $request_url, - 'queue_k' => $queue_k, - 'user_agent' => $user_agent, - 'is_mobile' => $is_mobile ? 1 : 0, // todo:compatible w/ tablet - 'is_webp' => $is_webp ? 1 : 0, - 'html' => $html, - 'css' => $css, + 'url' => $request_url, + 'queue_k' => $queue_k, + 'user_agent' => $user_agent, + 'is_mobile' => $is_mobile ? 1 : 0, // todo:compatible w/ tablet + 'is_webp' => $is_webp ? 1 : 0, + 'html' => $html, + 'css' => $css, ); - self::debug( 'Generating: ', $data ); + self::debug('Generating: ', $data); - $json = Cloud::post( Cloud::SVC_CCSS, $data, 30 ); - if ( ! is_array( $json ) ) { + $json = Cloud::post(Cloud::SVC_CCSS, $data, 30); + if (!is_array($json)) { return false; } // Old version compatibility - if ( empty( $json[ 'status' ] ) ) { - if ( ! empty( $json[ $type ] ) ) { - $this->_save_con( $type, $json[ $type ], $queue_k, $is_mobile, $is_webp ); + if (empty($json['status'])) { + if (!empty($json[$type])) { + $this->_save_con($type, $json[$type], $queue_k, $is_mobile, $is_webp); } // Delete the row @@ -314,14 +339,14 @@ private function _send_req( $request_url, $queue_k, $uid, $user_agent, $vary, $u } // Unknown status, remove this line - if ( $json[ 'status' ] != 'queued' ) { + if ($json['status'] != 'queued') { return false; } // Save summary data - $this->_summary[ 'last_spent_' . $type ] = time() - $this->_summary[ 'curr_request_' . $type ]; - $this->_summary[ 'last_request_' . $type ] = $this->_summary[ 'curr_request_' . $type ]; - $this->_summary[ 'curr_request_' . $type ] = 0; + $this->_summary['last_spent_' . $type] = time() - $this->_summary['curr_request_' . $type]; + $this->_summary['last_request_' . $type] = $this->_summary['curr_request_' . $type]; + $this->_summary['curr_request_' . $type] = 0; self::save_summary(); return true; @@ -332,31 +357,32 @@ private function _send_req( $request_url, $queue_k, $uid, $user_agent, $vary, $u * * @since 4.2 */ - private function _save_con( $type, $css, $queue_k, $mobile, $webp ) { + private function _save_con($type, $css, $queue_k, $mobile, $webp) + { // Add filters - $css = apply_filters( 'litespeed_' . $type, $css, $queue_k ); - Debug2::debug2( '[CSS] con: ' . $css ); + $css = apply_filters('litespeed_' . $type, $css, $queue_k); + Debug2::debug2('[CSS] con: ' . $css); - if ( substr( $css, 0, 2 ) == '/*' && substr( $css, -2 ) == '*/' ) { - self::debug( '❌ empty ' . $type . ' [content] ' . $css ); + if (substr($css, 0, 2) == '/*' && substr($css, -2) == '*/') { + self::debug('❌ empty ' . $type . ' [content] ' . $css); // continue; // Save the error info too } // Write to file - $filecon_md5 = md5( $css ); + $filecon_md5 = md5($css); - $filepath_prefix = $this->_build_filepath_prefix( $type ); + $filepath_prefix = $this->_build_filepath_prefix($type); $static_file = LITESPEED_STATIC_DIR . $filepath_prefix . $filecon_md5 . '.css'; - File::save( $static_file, $css, true ); + File::save($static_file, $css, true); - $url_tag = $this->_queue[ $queue_k ][ 'url_tag' ]; - $vary = $this->_queue[ $queue_k ][ 'vary' ]; - Debug2::debug2( "[CSS] Save URL to file [file] $static_file [vary] $vary" ); + $url_tag = $this->_queue[$queue_k]['url_tag']; + $vary = $this->_queue[$queue_k]['vary']; + Debug2::debug2("[CSS] Save URL to file [file] $static_file [vary] $vary"); - $this->cls( 'Data' )->save_url( $url_tag, $vary, $type, $filecon_md5, dirname( $static_file ), $mobile, $webp ); + $this->cls('Data')->save_url($url_tag, $vary, $type, $filecon_md5, dirname($static_file), $mobile, $webp); - Purge::add( strtoupper( $type ) . '.' . md5( $queue_k ) ); + Purge::add(strtoupper($type) . '.' . md5($queue_k)); } /** @@ -364,31 +390,32 @@ private function _save_con( $type, $css, $queue_k, $mobile, $webp ) { * * @since 3.4.3 */ - public function test_url( $request_url ) { - $user_agent = $_SERVER[ 'HTTP_USER_AGENT' ]; - $html = $this->prepare_html( $request_url, $user_agent ); - list( $css, $html ) = $this->prepare_css( $html, true, true ); + public function test_url($request_url) + { + $user_agent = $_SERVER['HTTP_USER_AGENT']; + $html = $this->prepare_html($request_url, $user_agent); + list($css, $html) = $this->prepare_css($html, true, true); // var_dump( $css ); -// $html = << $request_url, - 'ccss_type' => 'test', - 'user_agent' => $user_agent, - 'is_mobile' => 0, - 'html' => $html, - 'css' => $css, - 'type' => 'CCSS', + 'url' => $request_url, + 'ccss_type' => 'test', + 'user_agent' => $user_agent, + 'is_mobile' => 0, + 'html' => $html, + 'css' => $css, + 'type' => 'CCSS', ); // self::debug( 'Generating: ', $data ); - $json = Cloud::post( Cloud::SVC_CCSS, $data, 180 ); + $json = Cloud::post(Cloud::SVC_CCSS, $data, 180); var_dump($json); } @@ -398,14 +425,18 @@ public function test_url( $request_url ) { * * @since 3.4.3 */ - public function prepare_html( $request_url, $user_agent, $uid = false ) { - $html = $this->cls( 'Crawler' )->self_curl( add_query_arg( 'LSCWP_CTRL', 'before_optm', $request_url ), $user_agent, $uid ); - Debug2::debug2( '[CSS] self_curl result....', $html ); + public function prepare_html($request_url, $user_agent, $uid = false) + { + $html = $this->cls('Crawler')->self_curl(add_query_arg('LSCWP_CTRL', 'before_optm', $request_url), $user_agent, $uid); + Debug2::debug2('[CSS] self_curl result....', $html); + if (!$html) { + return false; + } - $html = $this->cls( 'Optimizer' )->html_min( $html, true ); + $html = $this->cls('Optimizer')->html_min($html, true); // Drop - $html = preg_replace( '##isU', '', $html ); + $html = preg_replace('##isU', '', $html); return $html; } @@ -416,83 +447,83 @@ public function prepare_html( $request_url, $user_agent, $uid = false ) { * * @since 3.4.3 */ - public function prepare_css( $html, $is_webp = false, $dryrun = false ) { + public function prepare_css($html, $is_webp = false, $dryrun = false) + { $css = ''; - preg_match_all( '#]+)/?>|]*)>([^<]+)#isU', $html, $matches, PREG_SET_ORDER ); - foreach ( $matches as $match ) { + preg_match_all('#]+)/?>|]*)>([^<]+)#isU', $html, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { $debug_info = ''; - if ( strpos( $match[ 0 ], 'cls( 'Optimizer' )->load_file( $attrs[ 'href' ] ); - if ( ! $con ) { + if (!$dryrun) { + // Dryrun will not load CSS but just drop them + $con = $this->cls('Optimizer')->load_file($attrs['href']); + if (!$con) { continue; } - } - else { + } else { $con = ''; } - } - else { // Inline style - $attrs = Utility::parse_attr( $match[ 2 ] ); + } else { + // Inline style + $attrs = Utility::parse_attr($match[2]); - if ( ! empty( $attrs[ 'media' ] ) && strpos( $attrs[ 'media' ], 'print' ) !== false ) { + if (!empty($attrs['media']) && strpos($attrs['media'], 'print') !== false) { continue; } - Debug2::debug2( '[CSS] Load inline CSS ' . substr( $match[ 3 ], 0, 100 ) . '...', $attrs ); - $con = $match[ 3 ]; + Debug2::debug2('[CSS] Load inline CSS ' . substr($match[3], 0, 100) . '...', $attrs); + $con = $match[3]; $debug_info = '__INLINE__'; } - $con = Optimizer::minify_css( $con ); - if ( $is_webp && $this->cls( 'Media' )->webp_support() ) { - $con = $this->cls( 'Media' )->replace_background_webp( $con ); + $con = Optimizer::minify_css($con); + if ($is_webp && $this->cls('Media')->webp_support()) { + $con = $this->cls('Media')->replace_background_webp($con); } - if ( ! empty( $attrs[ 'media' ] ) && $attrs[ 'media' ] !== 'all' ) { - $con = '@media ' . $attrs[ 'media' ] . '{' . $con . "}\n"; - } - else { + if (!empty($attrs['media']) && $attrs['media'] !== 'all') { + $con = '@media ' . $attrs['media'] . '{' . $con . "}\n"; + } else { $con = $con . "\n"; } $con = '/* ' . $debug_info . ' */' . $con; $css .= $con; - $html = str_replace( $match[ 0 ], '', $html ); + $html = str_replace($match[0], '', $html); } - return array( $css, $html ); + return array($css, $html); } /** @@ -501,16 +532,17 @@ public function prepare_css( $html, $is_webp = false, $dryrun = false ) { * @since 2.3 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_GEN_CCSS: - self::cron_ccss( true ); + self::cron_ccss(true); break; case self::TYPE_CLEAR_Q_CCSS: - $this->clear_q( 'ccss' ); + $this->clear_q('ccss'); break; default: @@ -519,5 +551,4 @@ public function handler() { Admin::redirect(); } - } diff --git a/src/data.cls.php b/src/data.cls.php index 546e351bd..e9c4d5d7e 100644 --- a/src/data.cls.php +++ b/src/data.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; -class Data extends Root { +defined('WPINC') || exit(); + +class Data extends Root +{ const LOG_TAG = '[Data]'; private $_db_updater = array( - '3.5.0.3' => array( - 'litespeed_update_3_5', - ), - '4.0' => array( - 'litespeed_update_4', - ), - '4.1' => array( - 'litespeed_update_4_1', - ), - '4.3' => array( - 'litespeed_update_4_3', - ), - '4.4.4-b1' => array( - 'litespeed_update_4_4_4', - ), - '5.3-a5' => array( - 'litespeed_update_5_3', - ), + '3.5.0.3' => array('litespeed_update_3_5'), + '4.0' => array('litespeed_update_4'), + '4.1' => array('litespeed_update_4_1'), + '4.3' => array('litespeed_update_4_3'), + '4.4.4-b1' => array('litespeed_update_4_4_4'), + '5.3-a5' => array('litespeed_update_5_3'), ); private $_db_site_updater = array( @@ -61,7 +53,8 @@ class Data extends Root { * * @since 1.3.1 */ - public function __construct() { + public function __construct() + { } /** @@ -73,21 +66,22 @@ public function __construct() { * @since 3.0 * @access public */ - public function correct_tb_existance() { + public function correct_tb_existance() + { // Gravatar - if ( $this->conf( Base::O_DISCUSS_AVATAR_CACHE ) ) { - $this->tb_create( 'avatar' ); + if ($this->conf(Base::O_DISCUSS_AVATAR_CACHE)) { + $this->tb_create('avatar'); } // Crawler - if ( $this->conf( Base::O_CRAWLER ) ) { - $this->tb_create( 'crawler' ); - $this->tb_create( 'crawler_blacklist' ); + if ($this->conf(Base::O_CRAWLER)) { + $this->tb_create('crawler'); + $this->tb_create('crawler_blacklist'); } // URL mapping - $this->tb_create( 'url' ); - $this->tb_create( 'url_file' ); + $this->tb_create('url'); + $this->tb_create('url_file'); // Image optm is a bit different. Only trigger creation when sending requests. Drop when destroying. } @@ -100,56 +94,57 @@ public function correct_tb_existance() { * @since 3.0 * @access public */ - public function conf_upgrade( $ver ) { + public function conf_upgrade($ver) + { // Skip count check if `Use Primary Site Configurations` is on // Deprecated since v3.0 as network primary site didn't override the subsites conf yet // if ( ! is_main_site() && ! empty ( $this->_site_options[ self::NETWORK_O_USE_PRIMARY ] ) ) { // return; // } - if ( $this->_get_upgrade_lock() ) { + if ($this->_get_upgrade_lock()) { return; } - $this->_set_upgrade_lock( true ); + $this->_set_upgrade_lock(true); require_once LSCWP_DIR . 'src/data.upgrade.func.php'; // Init log manually - if ( $this->conf( Base::O_DEBUG ) ) { - $this->cls( 'Debug2' )->init(); + if ($this->conf(Base::O_DEBUG)) { + $this->cls('Debug2')->init(); } - foreach ( $this->_db_updater as $k => $v ) { - if ( version_compare( $ver, $k, '<' ) ) { + foreach ($this->_db_updater as $k => $v) { + if (version_compare($ver, $k, '<')) { // run each callback - foreach ( $v as $v2 ) { - Debug2::debug( "[Data] Updating [ori_v] $ver \t[to] $k \t[func] $v2" ); - call_user_func( $v2 ); + foreach ($v as $v2) { + Debug2::debug("[Data] Updating [ori_v] $ver \t[to] $k \t[func] $v2"); + call_user_func($v2); } } } // Reload options - $this->cls( 'Conf' )->load_options(); + $this->cls('Conf')->load_options(); $this->correct_tb_existance(); // Update related files - $this->cls( 'Activation' )->update_files(); + $this->cls('Activation')->update_files(); // Update version to latest - Conf::delete_option( Base::_VER ); - Conf::add_option( Base::_VER, Core::VER ); + Conf::delete_option(Base::_VER); + Conf::add_option(Base::_VER, Core::VER); - Debug2::debug( '[Data] Updated version to ' . Core::VER ); + Debug2::debug('[Data] Updated version to ' . Core::VER); - $this->_set_upgrade_lock( false ); + $this->_set_upgrade_lock(false); - ! defined( 'LSWCP_EMPTYCACHE') && define( 'LSWCP_EMPTYCACHE', true );// clear all sites caches + !defined('LSWCP_EMPTYCACHE') && define('LSWCP_EMPTYCACHE', true); // clear all sites caches Purge::purge_all(); - Cloud::version_check( 'upgrade' ); + Cloud::version_check('upgrade'); } /** @@ -160,36 +155,37 @@ public function conf_upgrade( $ver ) { * @since 3.0 * @access public */ - public function conf_site_upgrade( $ver ) { - if ( $this->_get_upgrade_lock() ) { + public function conf_site_upgrade($ver) + { + if ($this->_get_upgrade_lock()) { return; } - $this->_set_upgrade_lock( true ); + $this->_set_upgrade_lock(true); require_once LSCWP_DIR . 'src/data.upgrade.func.php'; - foreach ( $this->_db_site_updater as $k => $v ) { - if ( version_compare( $ver, $k, '<' ) ) { + foreach ($this->_db_site_updater as $k => $v) { + if (version_compare($ver, $k, '<')) { // run each callback - foreach ( $v as $v2 ) { - Debug2::debug( "[Data] Updating site [ori_v] $ver \t[to] $k \t[func] $v2" ); - call_user_func( $v2 ); + foreach ($v as $v2) { + Debug2::debug("[Data] Updating site [ori_v] $ver \t[to] $k \t[func] $v2"); + call_user_func($v2); } } } // Reload options - $this->cls( 'Conf' )->load_site_options(); + $this->cls('Conf')->load_site_options(); - Conf::delete_site_option( Base::_VER ); - Conf::add_site_option( Base::_VER, Core::VER ); + Conf::delete_site_option(Base::_VER); + Conf::add_site_option(Base::_VER, Core::VER); - Debug2::debug( '[Data] Updated site_version to ' . Core::VER ); + Debug2::debug('[Data] Updated site_version to ' . Core::VER); - $this->_set_upgrade_lock( false ); + $this->_set_upgrade_lock(false); - ! defined( 'LSWCP_EMPTYCACHE') && define( 'LSWCP_EMPTYCACHE', true );// clear all sites caches + !defined('LSWCP_EMPTYCACHE') && define('LSWCP_EMPTYCACHE', true); // clear all sites caches Purge::purge_all(); } @@ -198,12 +194,13 @@ public function conf_site_upgrade( $ver ) { * * @since 3.0.1 */ - private function _get_upgrade_lock() { - $is_upgrading = get_option( 'litespeed.data.upgrading' ); - if ( ! $is_upgrading ) { - $this->_set_upgrade_lock( false ); // set option value to existed to avoid repeated db query next time + private function _get_upgrade_lock() + { + $is_upgrading = get_option('litespeed.data.upgrading'); + if (!$is_upgrading) { + $this->_set_upgrade_lock(false); // set option value to existed to avoid repeated db query next time } - if ( $is_upgrading && time() - $is_upgrading < 3600 ) { + if ($is_upgrading && time() - $is_upgrading < 3600) { return $is_upgrading; } @@ -215,13 +212,20 @@ private function _get_upgrade_lock() { * * @since 3.0.1 */ - public function check_upgrading_msg() { + public function check_upgrading_msg() + { $is_upgrading = $this->_get_upgrade_lock(); - if ( ! $is_upgrading ) { + if (!$is_upgrading) { return; } - Admin_Display::info( sprintf( __( 'The database has been upgrading in the background since %s. This message will disappear once upgrade is complete.', 'litespeed-cache' ), '' . Utility::readable_time( $is_upgrading ) . '' ) . ' [LiteSpeed]', true ); + Admin_Display::info( + sprintf( + __('The database has been upgrading in the background since %s. This message will disappear once upgrade is complete.', 'litespeed-cache'), + '' . Utility::readable_time($is_upgrading) . '' + ) . ' [LiteSpeed]', + true + ); } /** @@ -229,12 +233,12 @@ public function check_upgrading_msg() { * * @since 3.0.1 */ - private function _set_upgrade_lock( $lock ) { - if ( ! $lock ) { - update_option( 'litespeed.data.upgrading', -1 ); - } - else { - update_option( 'litespeed.data.upgrading', time() ); + private function _set_upgrade_lock($lock) + { + if (!$lock) { + update_option('litespeed.data.upgrading', -1); + } else { + update_option('litespeed.data.upgrading', time()); } } @@ -246,53 +250,53 @@ private function _set_upgrade_lock( $lock ) { * @since 3.0 * @access public */ - public function try_upgrade_conf_3_0() { - $previous_options = get_option( 'litespeed-cache-conf' ); - if ( ! $previous_options ) { - Cloud::version_check( 'new' ); + public function try_upgrade_conf_3_0() + { + $previous_options = get_option('litespeed-cache-conf'); + if (!$previous_options) { + Cloud::version_check('new'); return; } - $ver = $previous_options[ 'version' ]; + $ver = $previous_options['version']; - ! defined( 'LSCWP_CUR_V' ) && define( 'LSCWP_CUR_V', $ver ); + !defined('LSCWP_CUR_V') && define('LSCWP_CUR_V', $ver); // Init log manually - if ( $this->conf( Base::O_DEBUG ) ) { - $this->cls( 'Debug2' )->init(); + if ($this->conf(Base::O_DEBUG)) { + $this->cls('Debug2')->init(); } - Debug2::debug( '[Data] Upgrading previous settings [from] ' . $ver . ' [to] v3.0' ); + Debug2::debug('[Data] Upgrading previous settings [from] ' . $ver . ' [to] v3.0'); - if ( $this->_get_upgrade_lock() ) { + if ($this->_get_upgrade_lock()) { return; } - $this->_set_upgrade_lock( true ); + $this->_set_upgrade_lock(true); require_once LSCWP_DIR . 'src/data.upgrade.func.php'; // Here inside will update the version to v3.0 - litespeed_update_3_0( $ver ); + litespeed_update_3_0($ver); - $this->_set_upgrade_lock( false ); + $this->_set_upgrade_lock(false); - Debug2::debug( '[Data] Upgraded to v3.0' ); + Debug2::debug('[Data] Upgraded to v3.0'); // Upgrade from 3.0 to latest version $ver = '3.0'; - if ( Core::VER != $ver ) { - $this->conf_upgrade( $ver ); - } - else { + if (Core::VER != $ver) { + $this->conf_upgrade($ver); + } else { // Reload options - $this->cls( 'Conf' )->load_options(); + $this->cls('Conf')->load_options(); $this->correct_tb_existance(); - ! defined( 'LSWCP_EMPTYCACHE') && define( 'LSWCP_EMPTYCACHE', true );// clear all sites caches + !defined('LSWCP_EMPTYCACHE') && define('LSWCP_EMPTYCACHE', true); // clear all sites caches Purge::purge_all(); - Cloud::version_check( 'upgrade' ); + Cloud::version_check('upgrade'); } } @@ -302,10 +306,11 @@ public function try_upgrade_conf_3_0() { * @since 3.0 * @access public */ - public function tb( $tb ) { + public function tb($tb) + { global $wpdb; - switch ( $tb ) { + switch ($tb) { case 'img_optm': return $wpdb->prefix . self::TB_IMG_OPTM; break; @@ -337,7 +342,6 @@ public function tb( $tb ) { default: break; } - } /** @@ -346,9 +350,10 @@ public function tb( $tb ) { * @since 3.0 * @access public */ - public function tb_exist( $tb ) { + public function tb_exist($tb) + { global $wpdb; - return $wpdb->get_var( "SHOW TABLES LIKE '" . $this->tb( $tb ) . "'" ); + return $wpdb->get_var("SHOW TABLES LIKE '" . $this->tb($tb) . "'"); } /** @@ -357,8 +362,9 @@ public function tb_exist( $tb ) { * @since 2.0 * @access private */ - private function _tb_structure( $tb ) { - return File::read( LSCWP_DIR . 'src/data_structure/' . $tb . '.sql' ); + private function _tb_structure($tb) + { + return File::read(LSCWP_DIR . 'src/data_structure/' . $tb . '.sql'); } /** @@ -367,29 +373,30 @@ private function _tb_structure( $tb ) { * @since 3.0 * @access public */ - public function tb_create( $tb ) { + public function tb_create($tb) + { global $wpdb; - Debug2::debug2( '[Data] Checking table ' . $tb ); + Debug2::debug2('[Data] Checking table ' . $tb); // Check if table exists first - if ( $this->tb_exist( $tb ) ) { - Debug2::debug2( '[Data] Existed' ); + if ($this->tb_exist($tb)) { + Debug2::debug2('[Data] Existed'); return; } - Debug2::debug( '[Data] Creating ' . $tb ); + Debug2::debug('[Data] Creating ' . $tb); $sql = sprintf( - 'CREATE TABLE IF NOT EXISTS `%1$s` (' . $this->_tb_structure( $tb ) . ') %2$s;', - $this->tb( $tb ), + 'CREATE TABLE IF NOT EXISTS `%1$s` (' . $this->_tb_structure($tb) . ') %2$s;', + $this->tb($tb), $wpdb->get_charset_collate() // 'DEFAULT CHARSET=utf8' ); - $res = $wpdb->query( $sql ); - if ( $res !== true ) { - Debug2::debug( '[Data] Warning! Creating table failed!', $sql ); - Admin_Display::error( Error::msg( 'failed_tb_creation', array( '' . $tb . '', '' . $sql . '' ) ) ); + $res = $wpdb->query($sql); + if ($res !== true) { + Debug2::debug('[Data] Warning! Creating table failed!', $sql); + Admin_Display::error(Error::msg('failed_tb_creation', array('' . $tb . '', '' . $sql . ''))); } } @@ -399,17 +406,18 @@ public function tb_create( $tb ) { * @since 3.0 * @access public */ - public function tb_del( $tb ) { + public function tb_del($tb) + { global $wpdb; - if ( ! $this->tb_exist( $tb ) ) { + if (!$this->tb_exist($tb)) { return; } - Debug2::debug( '[Data] Deleting table ' . $tb ); + Debug2::debug('[Data] Deleting table ' . $tb); - $q = 'DROP TABLE IF EXISTS ' . $this->tb( $tb ); - $wpdb->query( $q ); + $q = 'DROP TABLE IF EXISTS ' . $this->tb($tb); + $wpdb->query($q); } /** @@ -418,12 +426,13 @@ public function tb_del( $tb ) { * @since 3.0 * @access public */ - public function tables_del() { - $this->tb_del( 'avatar' ); - $this->tb_del( 'crawler' ); - $this->tb_del( 'crawler_blacklist' ); - $this->tb_del( 'url' ); - $this->tb_del( 'url_file' ); + public function tables_del() + { + $this->tb_del('avatar'); + $this->tb_del('crawler'); + $this->tb_del('crawler_blacklist'); + $this->tb_del('url'); + $this->tb_del('url_file'); // Deleting img_optm only can be done when destroy all optm images } @@ -433,10 +442,11 @@ public function tables_del() { * * @since 4.0 */ - public function table_truncate( $tb ) { + public function table_truncate($tb) + { global $wpdb; - $q = 'TRUNCATE TABLE ' . $this->tb( $tb ); - $wpdb->query( $q ); + $q = 'TRUNCATE TABLE ' . $this->tb($tb); + $wpdb->query($q); } /** @@ -444,88 +454,94 @@ public function table_truncate( $tb ) { * * @since 4.0 */ - public function url_file_clean( $file_type ) { + public function url_file_clean($file_type) + { global $wpdb; - $type = $this->_url_file_types[ $file_type ]; - $q = 'DELETE FROM ' . $this->tb( 'url_file' ) . ' WHERE `type` = %d'; - $wpdb->query( $wpdb->prepare( $q, $type ) ); + + if (!$this->tb_exist('url_file')) { + return; + } + + $type = $this->_url_file_types[$file_type]; + $q = 'DELETE FROM ' . $this->tb('url_file') . ' WHERE `type` = %d'; + $wpdb->query($wpdb->prepare($q, $type)); } /** * Generate filename based on URL, if content md5 existed, reuse existing file. * @since 4.0 */ - public function save_url( $request_url, $vary, $file_type, $filecon_md5, $path, $mobile = false, $webp = false ) { + public function save_url($request_url, $vary, $file_type, $filecon_md5, $path, $mobile = false, $webp = false) + { global $wpdb; - if ( strlen( $vary ) > 32 ) { - $vary = md5( $vary ); + if (strlen($vary) > 32) { + $vary = md5($vary); } - $type = $this->_url_file_types[ $file_type ]; + $type = $this->_url_file_types[$file_type]; - $tb_url = $this->tb( 'url' ); - $tb_url_file = $this->tb( 'url_file' ); + $tb_url = $this->tb('url'); + $tb_url_file = $this->tb('url_file'); $q = "SELECT * FROM `$tb_url` WHERE url=%s"; - $url_row = $wpdb->get_row( $wpdb->prepare( $q, $request_url ), ARRAY_A ); - if ( ! $url_row ) { + $url_row = $wpdb->get_row($wpdb->prepare($q, $request_url), ARRAY_A); + if (!$url_row) { $q = "INSERT INTO `$tb_url` SET url=%s"; - $wpdb->query( $wpdb->prepare( $q, $request_url ) ); + $wpdb->query($wpdb->prepare($q, $request_url)); $url_id = $wpdb->insert_id; - } - else { - $url_id = $url_row[ 'id' ]; + } else { + $url_id = $url_row['id']; } $q = "SELECT * FROM `$tb_url_file` WHERE url_id=%d AND vary=%s AND type=%d AND expired=0"; - $file_row = $wpdb->get_row( $wpdb->prepare( $q, array( $url_id, $vary, $type ) ), ARRAY_A ); + $file_row = $wpdb->get_row($wpdb->prepare($q, array($url_id, $vary, $type)), ARRAY_A); // Check if has previous file or not - if ( $file_row && $file_row[ 'filename' ] == $filecon_md5 ) { + if ($file_row && $file_row['filename'] == $filecon_md5) { return; } // If the new $filecon_md5 is marked as expired by previous records, clear those records $q = "DELETE FROM `$tb_url_file` WHERE filename = %s AND expired > 0"; - $wpdb->query( $wpdb->prepare( $q, $filecon_md5 ) ); + $wpdb->query($wpdb->prepare($q, $filecon_md5)); // Check if there is any other record used the same filename or not $q = "SELECT id FROM `$tb_url_file` WHERE filename = %s AND expired = 0 AND id != %d LIMIT 1"; - if ( $file_row && $wpdb->get_var( $wpdb->prepare( $q, array( $file_row[ 'filename' ], $file_row[ 'id' ] ) ) ) ) { + if ($file_row && $wpdb->get_var($wpdb->prepare($q, array($file_row['filename'], $file_row['id'])))) { $q = "UPDATE `$tb_url_file` SET filename=%s WHERE id=%d"; - $wpdb->query( $wpdb->prepare( $q, array( $filecon_md5, $file_row[ 'id' ] ) ) ); + $wpdb->query($wpdb->prepare($q, array($filecon_md5, $file_row['id']))); return; } // New record needed $q = "INSERT INTO `$tb_url_file` SET url_id=%d, vary=%s, filename=%s, type=%d, mobile=%d, webp=%d, expired=0"; - $wpdb->query( $wpdb->prepare( $q, array( $url_id, $vary, $filecon_md5, $type, $mobile?1:0, $webp?1:0 ) ) ); + $wpdb->query($wpdb->prepare($q, array($url_id, $vary, $filecon_md5, $type, $mobile ? 1 : 0, $webp ? 1 : 0))); // Mark existing rows as expired - if ( $file_row ) { + if ($file_row) { $q = "UPDATE `$tb_url_file` SET expired=%d WHERE id=%d"; - $expired = time() + 86400 * apply_filters( 'litespeed_url_file_expired_days', 20 ); - $wpdb->query( $wpdb->prepare( $q, array( $expired, $file_row[ 'id' ] ) ) ); + $expired = time() + 86400 * apply_filters('litespeed_url_file_expired_days', 20); + $wpdb->query($wpdb->prepare($q, array($expired, $file_row['id']))); // Also check if has other files expired already to be deleted $q = "SELECT * FROM `$tb_url_file` WHERE url_id = %d AND expired BETWEEN 1 AND %d"; - $q = $wpdb->prepare( $q, array( $url_id, time() ) ); - $list = $wpdb->get_results( $q, ARRAY_A ); - if ( $list ) { - foreach ( $list as $v ) { - $file_to_del = $path . '/' . $v[ 'filename' ] . '.' . ( $file_type == 'js' ? 'js' : 'css' ); - if ( file_exists( $file_to_del ) ) { + $q = $wpdb->prepare($q, array($url_id, time())); + $list = $wpdb->get_results($q, ARRAY_A); + if ($list) { + foreach ($list as $v) { + $file_to_del = $path . '/' . $v['filename'] . '.' . ($file_type == 'js' ? 'js' : 'css'); + if (file_exists($file_to_del)) { // Safe to delete - Debug2::debug( '[Data] Delete expired unused file: ' . $file_to_del ); + Debug2::debug('[Data] Delete expired unused file: ' . $file_to_del); // Clear related lscache first to avoid cache copy of same URL w/ diff QS // Purge::add( Tag::TYPE_MIN . '.' . $file_row[ 'filename' ] . '.' . $file_type ); - unlink( $file_to_del ); + unlink($file_to_del); } } $q = "DELETE FROM `$tb_url_file` WHERE url_id = %d AND expired BETWEEN 1 AND %d"; - $wpdb->query( $wpdb->prepare( $q, array( $url_id, time() ) ) ); + $wpdb->query($wpdb->prepare($q, array($url_id, time()))); } } @@ -537,65 +553,67 @@ public function save_url( $request_url, $vary, $file_type, $filecon_md5, $path, * Load CCSS related file * @since 4.0 */ - public function load_url_file( $request_url, $vary, $file_type ) { + public function load_url_file($request_url, $vary, $file_type) + { global $wpdb; - if ( strlen( $vary ) > 32 ) { - $vary = md5( $vary ); + if (strlen($vary) > 32) { + $vary = md5($vary); } - $type = $this->_url_file_types[ $file_type ]; + $type = $this->_url_file_types[$file_type]; - self::debug2( 'load url file: ' . $request_url ); + self::debug2('load url file: ' . $request_url); - $tb_url = $this->tb( 'url' ); + $tb_url = $this->tb('url'); $q = "SELECT * FROM `$tb_url` WHERE url=%s"; - $url_row = $wpdb->get_row( $wpdb->prepare( $q, $request_url ), ARRAY_A ); - if ( ! $url_row ) { + $url_row = $wpdb->get_row($wpdb->prepare($q, $request_url), ARRAY_A); + if (!$url_row) { return false; } - $url_id = $url_row[ 'id' ]; + $url_id = $url_row['id']; - $tb_url_file = $this->tb( 'url_file' ); + $tb_url_file = $this->tb('url_file'); $q = "SELECT * FROM `$tb_url_file` WHERE url_id=%d AND vary=%s AND type=%d AND expired=0"; - $file_row = $wpdb->get_row( $wpdb->prepare( $q, array( $url_id, $vary, $type ) ), ARRAY_A ); - if ( ! $file_row ) { + $file_row = $wpdb->get_row($wpdb->prepare($q, array($url_id, $vary, $type)), ARRAY_A); + if (!$file_row) { return false; } - return $file_row[ 'filename' ]; + return $file_row['filename']; } /** * Mark all entries of one URL to expired * @since 4.5 */ - public function mark_as_expired( $request_url, $auto_q = false ) { + public function mark_as_expired($request_url, $auto_q = false) + { global $wpdb; - Debug2::debug( '[Data] Try to mark as expired: ' . $request_url ); - $tb_url = $this->tb( 'url' ); + Debug2::debug('[Data] Try to mark as expired: ' . $request_url); + $tb_url = $this->tb('url'); $q = "SELECT * FROM `$tb_url` WHERE url=%s"; - $url_row = $wpdb->get_row( $wpdb->prepare( $q, $request_url ), ARRAY_A ); - if ( ! $url_row ) { + $url_row = $wpdb->get_row($wpdb->prepare($q, $request_url), ARRAY_A); + if (!$url_row) { return; } - Debug2::debug( '[Data] Mark url_id=' . $url_row[ 'id' ] . ' as expired' ); + Debug2::debug('[Data] Mark url_id=' . $url_row['id'] . ' as expired'); - $tb_url = $this->tb( 'url' ); - $tb_url_file = $this->tb( 'url_file' ); + $tb_url = $this->tb('url'); + $tb_url_file = $this->tb('url_file'); $existing_url_files = array(); - if ( $auto_q ) { + if ($auto_q) { $q = "SELECT a.*, b.url FROM `$tb_url_file` a LEFT JOIN `$tb_url` b ON b.id=a.url_id WHERE a.url_id=%d AND a.type=4 AND a.expired=0"; - $q = $wpdb->prepare( $q, $url_row[ 'id' ] ); - $existing_url_files = $wpdb->get_results( $q, ARRAY_A ); + $q = $wpdb->prepare($q, $url_row['id']); + $existing_url_files = $wpdb->get_results($q, ARRAY_A); } $q = "UPDATE `$tb_url_file` SET expired=%d WHERE url_id=%d AND type=4 AND expired=0"; - $expired = time() + 86400 * apply_filters( 'litespeed_url_file_expired_days', 20 ); - $wpdb->query( $wpdb->prepare( $q, array( $expired, $url_row[ 'id' ] ) ) ); + $expired = time() + 86400 * apply_filters('litespeed_url_file_expired_days', 20); + $wpdb->query($wpdb->prepare($q, array($expired, $url_row['id']))); return $existing_url_files; } @@ -605,10 +623,11 @@ public function mark_as_expired( $request_url, $auto_q = false ) { * * @since 3.6 */ - public function load_css_exc( $list ) { - $data = $this->_load_per_line( 'css_excludes.txt' ); - if ( $data ) { - $list = array_unique( array_filter( array_merge( $list, $data ) ) ); + public function load_css_exc($list) + { + $data = $this->_load_per_line('css_excludes.txt'); + if ($data) { + $list = array_unique(array_filter(array_merge($list, $data))); } return $list; @@ -619,10 +638,11 @@ public function load_css_exc( $list ) { * * @since 4.0 */ - public function load_ucss_whitelist( $list ) { - $data = $this->_load_per_line( 'ucss_whitelist.txt' ); - if ( $data ) { - $list = array_unique( array_filter( array_merge( $list, $data ) ) ); + public function load_ucss_whitelist($list) + { + $data = $this->_load_per_line('ucss_whitelist.txt'); + if ($data) { + $list = array_unique(array_filter(array_merge($list, $data))); } return $list; @@ -633,10 +653,11 @@ public function load_ucss_whitelist( $list ) { * * @since 3.5 */ - public function load_js_exc( $list ) { - $data = $this->_load_per_line( 'js_excludes.txt' ); - if ( $data ) { - $list = array_unique( array_filter( array_merge( $list, $data ) ) ); + public function load_js_exc($list) + { + $data = $this->_load_per_line('js_excludes.txt'); + if ($data) { + $list = array_unique(array_filter(array_merge($list, $data))); } return $list; @@ -647,10 +668,26 @@ public function load_js_exc( $list ) { * * @since 3.6 */ - public function load_js_defer_exc( $list ) { - $data = $this->_load_per_line( 'js_defer_excludes.txt' ); - if ( $data ) { - $list = array_unique( array_filter( array_merge( $list, $data ) ) ); + public function load_js_defer_exc($list) + { + $data = $this->_load_per_line('js_defer_excludes.txt'); + if ($data) { + $list = array_unique(array_filter(array_merge($list, $data))); + } + + return $list; + } + + /** + * Get list from `data/optm_uri_exc.txt` + * + * @since 5.4 + */ + public function load_optm_uri_exc($list) + { + $data = $this->_load_per_line('optm_uri_exc.txt'); + if ($data) { + $list = array_unique(array_filter(array_merge($list, $data))); } return $list; @@ -661,10 +698,11 @@ public function load_js_defer_exc( $list ) { * * @since 3.5 */ - public function load_esi_nonces( $list ) { - $data = $this->_load_per_line( 'esi.nonces.txt' ); - if ( $data ) { - $list = array_unique( array_filter( array_merge( $list, $data ) ) ); + public function load_esi_nonces($list) + { + $data = $this->_load_per_line('esi.nonces.txt'); + if ($data) { + $list = array_unique(array_filter(array_merge($list, $data))); } return $list; @@ -679,20 +717,21 @@ public function load_esi_nonces( $list ) { * * @since 3.5 */ - private function _load_per_line( $file ) { - $data = File::read( LSCWP_DIR . 'data/' . $file ); - $data = explode( PHP_EOL, $data ); + private function _load_per_line($file) + { + $data = File::read(LSCWP_DIR . 'data/' . $file); + $data = explode(PHP_EOL, $data); $list = array(); - foreach ( $data as $v ) { + foreach ($data as $v) { // Drop two kinds of comments - if ( strpos( $v, '##' ) !== false ) { - $v = trim( substr( $v, 0, strpos( $v, '##' ) ) ); + if (strpos($v, '##') !== false) { + $v = trim(substr($v, 0, strpos($v, '##'))); } - if ( strpos( $v, '# ' ) !== false ) { - $v = trim( substr( $v, 0, strpos( $v, '# ' ) ) ); + if (strpos($v, '# ') !== false) { + $v = trim(substr($v, 0, strpos($v, '# '))); } - if ( ! $v ) { + if (!$v) { continue; } @@ -701,5 +740,4 @@ private function _load_per_line( $file ) { return $list; } - -} \ No newline at end of file +} diff --git a/src/data.upgrade.func.php b/src/data.upgrade.func.php index 9ea58b6d2..60cff570a 100644 --- a/src/data.upgrade.func.php +++ b/src/data.upgrade.func.php @@ -6,7 +6,7 @@ * * @since 3.0 */ -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); use LiteSpeed\Debug2; use LiteSpeed\Conf; @@ -17,16 +17,20 @@ * Append webp/mobile to url_file * @since 5.3 */ -function litespeed_update_5_3() { +function litespeed_update_5_3() +{ global $wpdb; - Debug2::debug( "[Data] Upgrade url_file table" ); - $tb_exists = $wpdb->get_var( 'SHOW TABLES LIKE "' . $wpdb->prefix . 'litespeed_url_file"' ); - if ( $tb_exists ) { - $q = 'ALTER TABLE `' . $wpdb->prefix . 'litespeed_url_file` + Debug2::debug('[Data] Upgrade url_file table'); + $tb_exists = $wpdb->get_var('SHOW TABLES LIKE "' . $wpdb->prefix . 'litespeed_url_file"'); + if ($tb_exists) { + $q = + 'ALTER TABLE `' . + $wpdb->prefix . + 'litespeed_url_file` ADD COLUMN `mobile` tinyint(4) NOT NULL COMMENT "mobile=1", ADD COLUMN `webp` tinyint(4) NOT NULL COMMENT "webp=1" '; - $wpdb->query( $q ); + $wpdb->query($q); } } @@ -34,17 +38,21 @@ function litespeed_update_5_3() { * Add expired to url_file table * @since 4.4.4 */ -function litespeed_update_4_4_4() { +function litespeed_update_4_4_4() +{ global $wpdb; - Debug2::debug( "[Data] Upgrade url_file table" ); - $tb_exists = $wpdb->get_var( 'SHOW TABLES LIKE "' . $wpdb->prefix . 'litespeed_url_file"' ); - if ( $tb_exists ) { - $q = 'ALTER TABLE `' . $wpdb->prefix . 'litespeed_url_file` + Debug2::debug('[Data] Upgrade url_file table'); + $tb_exists = $wpdb->get_var('SHOW TABLES LIKE "' . $wpdb->prefix . 'litespeed_url_file"'); + if ($tb_exists) { + $q = + 'ALTER TABLE `' . + $wpdb->prefix . + 'litespeed_url_file` ADD COLUMN `expired` int(11) NOT NULL DEFAULT 0, ADD KEY `filename_2` (`filename`,`expired`), ADD KEY `url_id` (`url_id`,`expired`) '; - $wpdb->query( $q ); + $wpdb->query($q); } } @@ -52,9 +60,10 @@ function litespeed_update_4_4_4() { * Drop cssjs table and rm cssjs folder * @since 4.3 */ -function litespeed_update_4_3() { - if ( file_exists( LITESPEED_STATIC_DIR . '/ccsjs' ) ) { - File::rrmdir( LITESPEED_STATIC_DIR . '/ccsjs' ); +function litespeed_update_4_3() +{ + if (file_exists(LITESPEED_STATIC_DIR . '/ccsjs')) { + File::rrmdir(LITESPEED_STATIC_DIR . '/ccsjs'); } } @@ -62,9 +71,10 @@ function litespeed_update_4_3() { * Drop object cache data file * @since 4.1 */ -function litespeed_update_4_1() { - if ( file_exists( WP_CONTENT_DIR . '/.object-cache.ini' ) ) { - unlink( WP_CONTENT_DIR . '/.object-cache.ini' ); +function litespeed_update_4_1() +{ + if (file_exists(WP_CONTENT_DIR . '/.object-cache.ini')) { + unlink(WP_CONTENT_DIR . '/.object-cache.ini'); } } @@ -72,19 +82,20 @@ function litespeed_update_4_1() { * Drop cssjs table and rm cssjs folder * @since 4.0 */ -function litespeed_update_4() { +function litespeed_update_4() +{ global $wpdb; $tb = $wpdb->prefix . 'litespeed_cssjs'; - $existed = $wpdb->get_var( "SHOW TABLES LIKE '$tb'" ); - if ( ! $existed ) { + $existed = $wpdb->get_var("SHOW TABLES LIKE '$tb'"); + if (!$existed) { return; } $q = 'DROP TABLE IF EXISTS ' . $tb; - $wpdb->query( $q ); + $wpdb->query($q); - if ( file_exists( LITESPEED_STATIC_DIR . '/ccsjs' ) ) { - File::rrmdir( LITESPEED_STATIC_DIR . '/ccsjs' ); + if (file_exists(LITESPEED_STATIC_DIR . '/ccsjs')) { + File::rrmdir(LITESPEED_STATIC_DIR . '/ccsjs'); } } @@ -94,30 +105,38 @@ function litespeed_update_4() { * * @since 3.5.1 */ -function litespeed_update_3_5() { +function litespeed_update_3_5() +{ $__conf = Conf::cls(); // Excludes jQuery - foreach ( array( 'optm-js_exc', 'optm-js_defer_exc' ) as $v ) { - $curr_setting = $__conf->conf( $v ); + foreach (array('optm-js_exc', 'optm-js_defer_exc') as $v) { + $curr_setting = $__conf->conf($v); $curr_setting[] = 'jquery.js'; $curr_setting[] = 'jquery.min.js'; - $__conf->update( $v, $curr_setting ); + $__conf->update($v, $curr_setting); } // Turn off JS Combine and defer $show_msg = false; - foreach ( array( 'optm-js_comb', 'optm-js_defer', 'optm-js_inline_defer' ) as $v ) { - $curr_setting = $__conf->conf( $v ); - if ( ! $curr_setting ) { + foreach (array('optm-js_comb', 'optm-js_defer', 'optm-js_inline_defer') as $v) { + $curr_setting = $__conf->conf($v); + if (!$curr_setting) { continue; } $show_msg = true; - $__conf->update( $v, false ); + $__conf->update($v, false); } - if ( $show_msg ) { - $msg = sprintf( __( 'LiteSpeed Cache upgraded successfully. NOTE: Due to changes in this version, the settings %1$s and %2$s have been turned OFF. Please turn them back on manually and verify that your site layout is correct, and you have no JS errors.', 'litespeed-cache' ), '' . __( 'JS Combine', 'litespeed-cache' ) . '', '' . __( 'JS Defer', 'litespeed-cache' ) . '' ); - $msg .= sprintf( ' %s.', __( 'Click here to settings', 'litespeed-cache' ) ); - Admin_Display::info( $msg, false, true ); + if ($show_msg) { + $msg = sprintf( + __( + 'LiteSpeed Cache upgraded successfully. NOTE: Due to changes in this version, the settings %1$s and %2$s have been turned OFF. Please turn them back on manually and verify that your site layout is correct, and you have no JS errors.', + 'litespeed-cache' + ), + '' . __('JS Combine', 'litespeed-cache') . '', + '' . __('JS Defer', 'litespeed-cache') . '' + ); + $msg .= sprintf(' %s.', __('Click here to settings', 'litespeed-cache')); + Admin_Display::info($msg, false, true); } } @@ -126,327 +145,318 @@ function litespeed_update_3_5() { * * @since 3.0 */ -function litespeed_update_2_0( $ver ) { - global $wpdb ; +function litespeed_update_2_0($ver) +{ + global $wpdb; // Table version only exists after all old data migrated // Last modified is v2.4.2 - if ( version_compare( $ver, '2.4.2', '<' ) ) { + if (version_compare($ver, '2.4.2', '<')) { /** * Convert old data from postmeta to img_optm table * @since 2.0 */ // Migrate data from `wp_postmeta` to `wp_litespeed_img_optm` - $mids_to_del = array() ; - $q = "SELECT * FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_id" ; - $meta_value_list = $wpdb->get_results( $wpdb->prepare( $q, 'litespeed-optimize-data' ) ) ; - if ( $meta_value_list ) { - $max_k = count( $meta_value_list ) - 1 ; - foreach ( $meta_value_list as $k => $v ) { - $md52src_list = maybe_unserialize( $v->meta_value ) ; - foreach ( $md52src_list as $md5 => $v2 ) { + $mids_to_del = array(); + $q = "SELECT * FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_id"; + $meta_value_list = $wpdb->get_results($wpdb->prepare($q, 'litespeed-optimize-data')); + if ($meta_value_list) { + $max_k = count($meta_value_list) - 1; + foreach ($meta_value_list as $k => $v) { + $md52src_list = maybe_unserialize($v->meta_value); + foreach ($md52src_list as $md5 => $v2) { $f = array( - 'post_id' => $v->post_id, - 'optm_status' => $v2[ 1 ], - 'src' => $v2[ 0 ], - 'srcpath_md5' => md5( $v2[ 0 ] ), - 'src_md5' => $md5, - 'server' => $v2[ 2 ], - ) ; - $wpdb->replace( $wpdb->prefix . 'litespeed_img_optm', $f ) ; + 'post_id' => $v->post_id, + 'optm_status' => $v2[1], + 'src' => $v2[0], + 'srcpath_md5' => md5($v2[0]), + 'src_md5' => $md5, + 'server' => $v2[2], + ); + $wpdb->replace($wpdb->prefix . 'litespeed_img_optm', $f); } - $mids_to_del[] = $v->meta_id ; + $mids_to_del[] = $v->meta_id; // Delete from postmeta - if ( count( $mids_to_del ) > 100 || $k == $max_k ) { - $q = "DELETE FROM $wpdb->postmeta WHERE meta_id IN ( " . implode( ',', array_fill( 0, count( $mids_to_del ), '%s' ) ) . " ) " ; - $wpdb->query( $wpdb->prepare( $q, $mids_to_del ) ) ; + if (count($mids_to_del) > 100 || $k == $max_k) { + $q = "DELETE FROM $wpdb->postmeta WHERE meta_id IN ( " . implode(',', array_fill(0, count($mids_to_del), '%s')) . ' ) '; + $wpdb->query($wpdb->prepare($q, $mids_to_del)); - $mids_to_del = array() ; + $mids_to_del = array(); } } - Debug2::debug( '[Data] img_optm inserted records: ' . $k ) ; + Debug2::debug('[Data] img_optm inserted records: ' . $k); } - $q = "DELETE FROM $wpdb->postmeta WHERE meta_key = %s" ; - $rows = $wpdb->query( $wpdb->prepare( $q, 'litespeed-optimize-status' ) ) ; - Debug2::debug( '[Data] img_optm delete optm_status records: ' . $rows ) ; - + $q = "DELETE FROM $wpdb->postmeta WHERE meta_key = %s"; + $rows = $wpdb->query($wpdb->prepare($q, 'litespeed-optimize-status')); + Debug2::debug('[Data] img_optm delete optm_status records: ' . $rows); } /** * Add target_md5 field to table * @since 2.4.2 */ - if ( version_compare( $ver, '2.4.2', '<' ) && version_compare( $ver, '2.0', '>=' ) ) {// NOTE: For new users, need to bypass this section - $sql = sprintf( - 'ALTER TABLE `%1$s` ADD `server_info` text NOT NULL, DROP COLUMN `server`', - $wpdb->prefix . 'litespeed_img_optm' - ) ; - - $res = $wpdb->query( $sql ) ; - if ( $res !== true ) { - Debug2::debug( '[Data] Warning: Alter table img_optm failed!', $sql ) ; + if (version_compare($ver, '2.4.2', '<') && version_compare($ver, '2.0', '>=')) { + // NOTE: For new users, need to bypass this section + $sql = sprintf('ALTER TABLE `%1$s` ADD `server_info` text NOT NULL, DROP COLUMN `server`', $wpdb->prefix . 'litespeed_img_optm'); + + $res = $wpdb->query($sql); + if ($res !== true) { + Debug2::debug('[Data] Warning: Alter table img_optm failed!', $sql); + } else { + Debug2::debug('[Data] Successfully upgraded table img_optm.'); } - else { - Debug2::debug( '[Data] Successfully upgraded table img_optm.' ) ; - } - } // Delete img optm tb version - delete_option( $wpdb->prefix . 'litespeed_img_optm' ) ; - + delete_option($wpdb->prefix . 'litespeed_img_optm'); // Delete possible HTML optm data from wp_options - delete_option( 'litespeed-cache-optimized' ) ; + delete_option('litespeed-cache-optimized'); // Delete HTML optm tb version - delete_option( $wpdb->prefix . 'litespeed_optimizer' ) ; - + delete_option($wpdb->prefix . 'litespeed_optimizer'); } - - /** * Move all options in litespeed-cache-conf from v3.0- to separate records * * @since 3.0 */ -function litespeed_update_3_0( $ver ) { +function litespeed_update_3_0($ver) +{ global $wpdb; // Upgrade v2.0- to v2.0 first - if ( version_compare( $ver, '2.0', '<' ) ) { - litespeed_update_2_0( $ver ) ; + if (version_compare($ver, '2.0', '<')) { + litespeed_update_2_0($ver); } - set_time_limit( 86400 ); + set_time_limit(86400); // conv items to litespeed.conf.* - Debug2::debug( "[Data] Conv items to litespeed.conf.*" ); + Debug2::debug('[Data] Conv items to litespeed.conf.*'); $data = array( - 'litespeed-cache-exclude-cache-roles' => 'cache-exc_roles', - 'litespeed-cache-drop_qs' => 'cache-drop_qs', - 'litespeed-forced_cache_uri' => 'cache-force_uri', - 'litespeed-cache_uri_priv' => 'cache-priv_uri', - 'litespeed-excludes_uri' => 'cache-exc', - 'litespeed-cache-vary-group' => 'cache-vary_group', - 'litespeed-adv-purge_all_hooks' => 'purge-hook_all', - 'litespeed-object_global_groups' => 'object-global_groups', - 'litespeed-object_non_persistent_groups' => 'object-non_persistent_groups', - 'litespeed-media-lazy-img-excludes' => 'media-lazy_exc', - 'litespeed-media-lazy-img-cls-excludes' => 'media-lazy_cls_exc', - 'litespeed-media-webp_attribute' => 'img_optm-webp_attr', - 'litespeed-optm-css' => 'optm-ccss_con', - 'litespeed-optm_excludes' => 'optm-exc', - 'litespeed-optm-ccss-separate_posttype' => 'optm-ccss_sep_posttype', - 'litespeed-optm-css-separate_uri' => 'optm-ccss_sep_uri', - 'litespeed-optm-js-defer-excludes' => 'optm-js_defer_exc', - 'litespeed-cache-dns_prefetch' => 'optm-dns_prefetch', + 'litespeed-cache-exclude-cache-roles' => 'cache-exc_roles', + 'litespeed-cache-drop_qs' => 'cache-drop_qs', + 'litespeed-forced_cache_uri' => 'cache-force_uri', + 'litespeed-cache_uri_priv' => 'cache-priv_uri', + 'litespeed-excludes_uri' => 'cache-exc', + 'litespeed-cache-vary-group' => 'cache-vary_group', + 'litespeed-adv-purge_all_hooks' => 'purge-hook_all', + 'litespeed-object_global_groups' => 'object-global_groups', + 'litespeed-object_non_persistent_groups' => 'object-non_persistent_groups', + 'litespeed-media-lazy-img-excludes' => 'media-lazy_exc', + 'litespeed-media-lazy-img-cls-excludes' => 'media-lazy_cls_exc', + 'litespeed-media-webp_attribute' => 'img_optm-webp_attr', + 'litespeed-optm-css' => 'optm-ccss_con', + 'litespeed-optm_excludes' => 'optm-exc', + 'litespeed-optm-ccss-separate_posttype' => 'optm-ccss_sep_posttype', + 'litespeed-optm-css-separate_uri' => 'optm-ccss_sep_uri', + 'litespeed-optm-js-defer-excludes' => 'optm-js_defer_exc', + 'litespeed-cache-dns_prefetch' => 'optm-dns_prefetch', 'litespeed-cache-exclude-optimization-roles' => 'optm-exc_roles', - 'litespeed-log_ignore_filters' => 'debug-log_no_filters', // depreciated - 'litespeed-log_ignore_part_filters' => 'debug-log_no_part_filters', // depreciated - 'litespeed-cdn-ori_dir' => 'cdn-ori_dir', - 'litespeed-cache-cdn_mapping' => 'cdn-mapping', - 'litespeed-crawler-as-uids' => 'crawler-roles', - 'litespeed-crawler-cookies' => 'crawler-cookies', - ) ; - foreach ( $data as $k => $v ) { - $old_data = get_option( $k ) ; - if ( $old_data ) { - Debug2::debug( "[Data] Convert $k" ); + 'litespeed-log_ignore_filters' => 'debug-log_no_filters', // depreciated + 'litespeed-log_ignore_part_filters' => 'debug-log_no_part_filters', // depreciated + 'litespeed-cdn-ori_dir' => 'cdn-ori_dir', + 'litespeed-cache-cdn_mapping' => 'cdn-mapping', + 'litespeed-crawler-as-uids' => 'crawler-roles', + 'litespeed-crawler-cookies' => 'crawler-cookies', + ); + foreach ($data as $k => $v) { + $old_data = get_option($k); + if ($old_data) { + Debug2::debug("[Data] Convert $k"); // They must be an array - if ( ! is_array( $old_data ) && $v != 'optm-ccss_con' ) { - $old_data = explode( "\n", $old_data ) ; + if (!is_array($old_data) && $v != 'optm-ccss_con') { + $old_data = explode("\n", $old_data); } - if ( $v == 'crawler-cookies' ) { - $tmp = array() ; - $i = 0 ; - foreach ( $old_data as $k2 => $v2 ) { - $tmp[ $i ][ 'name' ] = $k2 ; - $tmp[ $i ][ 'vals' ] = explode( "\n", $v2 ) ; - $i ++ ; + if ($v == 'crawler-cookies') { + $tmp = array(); + $i = 0; + foreach ($old_data as $k2 => $v2) { + $tmp[$i]['name'] = $k2; + $tmp[$i]['vals'] = explode("\n", $v2); + $i++; } - $old_data = $tmp ; + $old_data = $tmp; } - add_option( 'litespeed.conf.' . $v, $old_data ) ; + add_option('litespeed.conf.' . $v, $old_data); } - Debug2::debug( "[Data] Delete $k" ); - delete_option( $k ) ; + Debug2::debug("[Data] Delete $k"); + delete_option($k); } // conv other items $data = array( - 'litespeed-setting-mode' => 'litespeed.setting.mode', - 'litespeed-media-need-pull' => 'litespeed.img_optm.need_pull', - 'litespeed-env-ref' => 'litespeed.env.ref', + 'litespeed-setting-mode' => 'litespeed.setting.mode', + 'litespeed-media-need-pull' => 'litespeed.img_optm.need_pull', + 'litespeed-env-ref' => 'litespeed.env.ref', 'litespeed-cache-cloudflare_status' => 'litespeed.cdn.cloudflare.status', - - ) ; - foreach ( $data as $k => $v ) { - $old_data = get_option( $k ) ; - if ( $old_data ) { - add_option( $v, $old_data ) ; + ); + foreach ($data as $k => $v) { + $old_data = get_option($k); + if ($old_data) { + add_option($v, $old_data); } - delete_option( $k ) ; + delete_option($k); } // Conv conf from litespeed-cache-conf child to litespeed.conf.* - Debug2::debug( "[Data] Conv conf from litespeed-cache-conf child to litespeed.conf.*" ); - $previous_options = get_option( 'litespeed-cache-conf' ) ; + Debug2::debug('[Data] Conv conf from litespeed-cache-conf child to litespeed.conf.*'); + $previous_options = get_option('litespeed-cache-conf'); $data = array( - 'radio_select' => 'cache', - 'hash' => 'hash', - 'auto_upgrade' => 'auto_upgrade', - 'news' => 'news', - 'crawler_domain_ip' => 'server_ip', - - 'esi_enabled' => 'esi', - 'esi_cached_admbar' => 'esi-cache_admbar', - 'esi_cached_commform' => 'esi-cache_commform', - - 'heartbeat' => 'misc-heartbeat_front', - - 'cache_browser' => 'cache-browser', - 'cache_browser_ttl' => 'cache-ttl_browser', - 'instant_click' => 'util-instant_click', - 'use_http_for_https_vary' => 'util-no_https_vary', - - 'purge_upgrade' => 'purge-upgrade', - 'timed_urls' => 'purge-timed_urls', - 'timed_urls_time' => 'purge-timed_urls_time', - - 'cache_priv' => 'cache-priv', - 'cache_commenter' => 'cache-commenter', - 'cache_rest' => 'cache-rest', - 'cache_page_login' => 'cache-page_login', - 'cache_favicon' => 'cache-favicon', - 'cache_resources' => 'cache-resources', - 'mobileview_enabled' => 'cache-mobile', - 'mobileview_rules' => 'cache-mobile_rules', - 'nocache_useragents' => 'cache-exc_useragents', - 'nocache_cookies' => 'cache-exc_cookies', - 'excludes_qs' => 'cache-exc_qs', - 'excludes_cat' => 'cache-exc_cat', - 'excludes_tag' => 'cache-exc_tag', - 'public_ttl' => 'cache-ttl_pub', - 'private_ttl' => 'cache-ttl_priv', - 'front_page_ttl' => 'cache-ttl_frontpage', - 'feed_ttl' => 'cache-ttl_feed', - 'login_cookie' => 'cache-login_cookie', - - 'debug_disable_all' => 'debug-disable_all', - 'debug' => 'debug', - 'admin_ips' => 'debug-ips', - 'debug_level' => 'debug-level', - 'log_file_size' => 'debug-filesize', - 'debug_cookie' => 'debug-cookie', - 'collaps_qs' => 'debug-collaps_qs', + 'radio_select' => 'cache', + 'hash' => 'hash', + 'auto_upgrade' => 'auto_upgrade', + 'news' => 'news', + 'crawler_domain_ip' => 'server_ip', + + 'esi_enabled' => 'esi', + 'esi_cached_admbar' => 'esi-cache_admbar', + 'esi_cached_commform' => 'esi-cache_commform', + + 'heartbeat' => 'misc-heartbeat_front', + + 'cache_browser' => 'cache-browser', + 'cache_browser_ttl' => 'cache-ttl_browser', + 'instant_click' => 'util-instant_click', + 'use_http_for_https_vary' => 'util-no_https_vary', + + 'purge_upgrade' => 'purge-upgrade', + 'timed_urls' => 'purge-timed_urls', + 'timed_urls_time' => 'purge-timed_urls_time', + + 'cache_priv' => 'cache-priv', + 'cache_commenter' => 'cache-commenter', + 'cache_rest' => 'cache-rest', + 'cache_page_login' => 'cache-page_login', + 'cache_favicon' => 'cache-favicon', + 'cache_resources' => 'cache-resources', + 'mobileview_enabled' => 'cache-mobile', + 'mobileview_rules' => 'cache-mobile_rules', + 'nocache_useragents' => 'cache-exc_useragents', + 'nocache_cookies' => 'cache-exc_cookies', + 'excludes_qs' => 'cache-exc_qs', + 'excludes_cat' => 'cache-exc_cat', + 'excludes_tag' => 'cache-exc_tag', + 'public_ttl' => 'cache-ttl_pub', + 'private_ttl' => 'cache-ttl_priv', + 'front_page_ttl' => 'cache-ttl_frontpage', + 'feed_ttl' => 'cache-ttl_feed', + 'login_cookie' => 'cache-login_cookie', + + 'debug_disable_all' => 'debug-disable_all', + 'debug' => 'debug', + 'admin_ips' => 'debug-ips', + 'debug_level' => 'debug-level', + 'log_file_size' => 'debug-filesize', + 'debug_cookie' => 'debug-cookie', + 'collaps_qs' => 'debug-collaps_qs', // 'log_filters' => 'debug-log_filters', - 'crawler_cron_active' => 'crawler', + 'crawler_cron_active' => 'crawler', // 'crawler_include_posts' => 'crawler-inc_posts', // 'crawler_include_pages' => 'crawler-inc_pages', // 'crawler_include_cats' => 'crawler-inc_cats', // 'crawler_include_tags' => 'crawler-inc_tags', // 'crawler_excludes_cpt' => 'crawler-exc_cpt', // 'crawler_order_links' => 'crawler-order_links', - 'crawler_usleep' => 'crawler-usleep', - 'crawler_run_duration' => 'crawler-run_duration', - 'crawler_run_interval' => 'crawler-run_interval', - 'crawler_crawl_interval' => 'crawler-crawl_interval', - 'crawler_threads' => 'crawler-threads', - 'crawler_load_limit' => 'crawler-load_limit', - 'crawler_custom_sitemap' => 'crawler-sitemap', - - 'cache_object' => 'object', - 'cache_object_kind' => 'object-kind', - 'cache_object_host' => 'object-host', - 'cache_object_port' => 'object-port', - 'cache_object_life' => 'object-life', - 'cache_object_persistent' => 'object-persistent', - 'cache_object_admin' => 'object-admin', - 'cache_object_transients' => 'object-transients', - 'cache_object_db_id' => 'object-db_id', - 'cache_object_user' => 'object-user', - 'cache_object_pswd' => 'object-psw', - - 'cdn' => 'cdn', - 'cdn_ori' => 'cdn-ori', - 'cdn_exclude' => 'cdn-exc', + 'crawler_usleep' => 'crawler-usleep', + 'crawler_run_duration' => 'crawler-run_duration', + 'crawler_run_interval' => 'crawler-run_interval', + 'crawler_crawl_interval' => 'crawler-crawl_interval', + 'crawler_threads' => 'crawler-threads', + 'crawler_load_limit' => 'crawler-load_limit', + 'crawler_custom_sitemap' => 'crawler-sitemap', + + 'cache_object' => 'object', + 'cache_object_kind' => 'object-kind', + 'cache_object_host' => 'object-host', + 'cache_object_port' => 'object-port', + 'cache_object_life' => 'object-life', + 'cache_object_persistent' => 'object-persistent', + 'cache_object_admin' => 'object-admin', + 'cache_object_transients' => 'object-transients', + 'cache_object_db_id' => 'object-db_id', + 'cache_object_user' => 'object-user', + 'cache_object_pswd' => 'object-psw', + + 'cdn' => 'cdn', + 'cdn_ori' => 'cdn-ori', + 'cdn_exclude' => 'cdn-exc', // 'cdn_remote_jquery' => 'cdn-remote_jq', - 'cdn_quic' => 'cdn-quic', - 'cdn_cloudflare' => 'cdn-cloudflare', - 'cdn_cloudflare_email' => 'cdn-cloudflare_email', - 'cdn_cloudflare_key' => 'cdn-cloudflare_key', - 'cdn_cloudflare_name' => 'cdn-cloudflare_name', - 'cdn_cloudflare_zone' => 'cdn-cloudflare_zone', - - 'media_img_lazy' => 'media-lazy', - 'media_img_lazy_placeholder' => 'media-lazy_placeholder', - 'media_placeholder_resp' => 'media-placeholder_resp', - 'media_placeholder_resp_color' => 'media-placeholder_resp_color', - 'media_placeholder_resp_async' => 'media-placeholder_resp_async', - 'media_iframe_lazy' => 'media-iframe_lazy', + 'cdn_quic' => 'cdn-quic', + 'cdn_cloudflare' => 'cdn-cloudflare', + 'cdn_cloudflare_email' => 'cdn-cloudflare_email', + 'cdn_cloudflare_key' => 'cdn-cloudflare_key', + 'cdn_cloudflare_name' => 'cdn-cloudflare_name', + 'cdn_cloudflare_zone' => 'cdn-cloudflare_zone', + + 'media_img_lazy' => 'media-lazy', + 'media_img_lazy_placeholder' => 'media-lazy_placeholder', + 'media_placeholder_resp' => 'media-placeholder_resp', + 'media_placeholder_resp_color' => 'media-placeholder_resp_color', + 'media_placeholder_resp_async' => 'media-placeholder_resp_async', + 'media_iframe_lazy' => 'media-iframe_lazy', // 'media_img_lazyjs_inline' => 'media-lazyjs_inline', - 'media_optm_auto' => 'img_optm-auto', - 'media_optm_cron' => 'img_optm-cron', - 'media_optm_ori' => 'img_optm-ori', - 'media_rm_ori_bkup' => 'img_optm-rm_bkup', - 'media_optm_webp' => 'img_optm-webp', - 'media_optm_lossless' => 'img_optm-lossless', - 'media_optm_exif' => 'img_optm-exif', - 'media_webp_replace' => 'img_optm-webp_replace', - 'media_webp_replace_srcset' => 'img_optm-webp_replace_srcset', - - 'css_minify' => 'optm-css_min', + 'media_optm_auto' => 'img_optm-auto', + 'media_optm_cron' => 'img_optm-cron', + 'media_optm_ori' => 'img_optm-ori', + 'media_rm_ori_bkup' => 'img_optm-rm_bkup', + // 'media_optm_webp' => 'img_optm-webp', + 'media_webp_replace' => 'img_optm-webp', + 'media_optm_lossless' => 'img_optm-lossless', + 'media_optm_exif' => 'img_optm-exif', + 'media_webp_replace_srcset' => 'img_optm-webp_replace_srcset', + + 'css_minify' => 'optm-css_min', // 'css_inline_minify' => 'optm-css_inline_min', - 'css_combine' => 'optm-css_comb', + 'css_combine' => 'optm-css_comb', // 'css_combined_priority' => 'optm-css_comb_priority', // 'css_http2' => 'optm-css_http2', - 'css_exclude' => 'optm-css_exc', - 'js_minify' => 'optm-js_min', + 'css_exclude' => 'optm-css_exc', + 'js_minify' => 'optm-js_min', // 'js_inline_minify' => 'optm-js_inline_min', - 'js_combine' => 'optm-js_comb', + 'js_combine' => 'optm-js_comb', // 'js_combined_priority' => 'optm-js_comb_priority', // 'js_http2' => 'optm-js_http2', - 'js_exclude' => 'optm-js_exc', + 'js_exclude' => 'optm-js_exc', // 'optimize_ttl' => 'optm-ttl', - 'html_minify' => 'optm-html_min', - 'optm_qs_rm' => 'optm-qs_rm', - 'optm_ggfonts_rm' => 'optm-ggfonts_rm', - 'optm_css_async' => 'optm-css_async', + 'html_minify' => 'optm-html_min', + 'optm_qs_rm' => 'optm-qs_rm', + 'optm_ggfonts_rm' => 'optm-ggfonts_rm', + 'optm_css_async' => 'optm-css_async', // 'optm_ccss_gen' => 'optm-ccss_gen', // 'optm_ccss_async' => 'optm-ccss_async', - 'optm_css_async_inline' => 'optm-css_async_inline', - 'optm_js_defer' => 'optm-js_defer', - 'optm_emoji_rm' => 'optm-emoji_rm', + 'optm_css_async_inline' => 'optm-css_async_inline', + 'optm_js_defer' => 'optm-js_defer', + 'optm_emoji_rm' => 'optm-emoji_rm', // 'optm_exclude_jquery' => 'optm-exc_jq', - 'optm_ggfonts_async' => 'optm-ggfonts_async', + 'optm_ggfonts_async' => 'optm-ggfonts_async', // 'optm_max_size' => 'optm-max_size', // 'optm_rm_comment' => 'optm-rm_comment', - ) ; - foreach ( $data as $k => $v ) { - if ( ! isset( $previous_options[ $k ] ) ) { - continue ; + ); + foreach ($data as $k => $v) { + if (!isset($previous_options[$k])) { + continue; } // The folllowing values must be array - if ( ! is_array( $previous_options[ $k ] ) ) { - if ( in_array( $v, array( 'cdn-ori', 'cache-exc_cat', 'cache-exc_tag' ) ) ) { - $previous_options[ $k ] = explode( ',', $previous_options[ $k ] ) ; - $previous_options[ $k ] = array_filter( $previous_options[ $k ] ) ; - } - elseif ( in_array( $v, array( 'cache-mobile_rules', 'cache-exc_useragents', 'cache-exc_cookies' ) ) ) { - $previous_options[ $k ] = explode( '|', str_replace( '\\ ', ' ', $previous_options[ $k ] ) ) ; - $previous_options[ $k ] = array_filter( $previous_options[ $k ] ) ; - } - elseif ( in_array( $v, array( + if (!is_array($previous_options[$k])) { + if (in_array($v, array('cdn-ori', 'cache-exc_cat', 'cache-exc_tag'))) { + $previous_options[$k] = explode(',', $previous_options[$k]); + $previous_options[$k] = array_filter($previous_options[$k]); + } elseif (in_array($v, array('cache-mobile_rules', 'cache-exc_useragents', 'cache-exc_cookies'))) { + $previous_options[$k] = explode('|', str_replace('\\ ', ' ', $previous_options[$k])); + $previous_options[$k] = array_filter($previous_options[$k]); + } elseif ( + in_array($v, array( 'purge-timed_urls', 'cache-exc_qs', 'debug-ips', @@ -454,59 +464,60 @@ function litespeed_update_3_0( $ver ) { 'cdn-exc', 'optm-css_exc', 'optm-js_exc', - ) ) ) { - $previous_options[ $k ] = explode( "\n", $previous_options[ $k ] ) ; - $previous_options[ $k ] = array_filter( $previous_options[ $k ] ) ; + )) + ) { + $previous_options[$k] = explode("\n", $previous_options[$k]); + $previous_options[$k] = array_filter($previous_options[$k]); } } // Special handler for heartbeat - if ( $v == 'misc-heartbeat_front' ) { - if ( ! $previous_options[ $k ] ) { - add_option( 'litespeed.conf.misc-heartbeat_front', true ) ; - add_option( 'litespeed.conf.misc-heartbeat_back', true ) ; - add_option( 'litespeed.conf.misc-heartbeat_editor', true ) ; - add_option( 'litespeed.conf.misc-heartbeat_front_ttl', 0 ) ; - add_option( 'litespeed.conf.misc-heartbeat_back_ttl', 0 ) ; - add_option( 'litespeed.conf.misc-heartbeat_editor_ttl', 0 ) ; + if ($v == 'misc-heartbeat_front') { + if (!$previous_options[$k]) { + add_option('litespeed.conf.misc-heartbeat_front', true); + add_option('litespeed.conf.misc-heartbeat_back', true); + add_option('litespeed.conf.misc-heartbeat_editor', true); + add_option('litespeed.conf.misc-heartbeat_front_ttl', 0); + add_option('litespeed.conf.misc-heartbeat_back_ttl', 0); + add_option('litespeed.conf.misc-heartbeat_editor_ttl', 0); } - continue ; + continue; } - add_option( 'litespeed.conf.' . $v, $previous_options[ $k ] ) ; + add_option('litespeed.conf.' . $v, $previous_options[$k]); } // Conv purge_by_post $data = array( - '-' => 'purge-post_all', - 'F' => 'purge-post_f', - 'H' => 'purge-post_h', - 'PGS' => 'purge-post_p', - 'PGSRP' => 'purge-post_pwrp', - 'A' => 'purge-post_a', - 'Y' => 'purge-post_y', - 'M' => 'purge-post_m', - 'D' => 'purge-post_d', - 'T' => 'purge-post_t', - 'PT' => 'purge-post_pt', - ) ; - if ( isset( $previous_options[ 'purge_by_post' ] ) ) { - $purge_by_post = explode( '.', $previous_options[ 'purge_by_post' ] ) ; - foreach ( $data as $k => $v ) { - add_option( 'litespeed.conf.' . $v, in_array( $k, $purge_by_post ) ) ; + '-' => 'purge-post_all', + 'F' => 'purge-post_f', + 'H' => 'purge-post_h', + 'PGS' => 'purge-post_p', + 'PGSRP' => 'purge-post_pwrp', + 'A' => 'purge-post_a', + 'Y' => 'purge-post_y', + 'M' => 'purge-post_m', + 'D' => 'purge-post_d', + 'T' => 'purge-post_t', + 'PT' => 'purge-post_pt', + ); + if (isset($previous_options['purge_by_post'])) { + $purge_by_post = explode('.', $previous_options['purge_by_post']); + foreach ($data as $k => $v) { + add_option('litespeed.conf.' . $v, in_array($k, $purge_by_post)); } } // Conv 404/403/500 TTL - $ttl_status = array() ; - if ( isset( $previous_options[ '403_ttl' ] ) ) { - $ttl_status[] = '403 ' . $previous_options[ '403_ttl' ] ; + $ttl_status = array(); + if (isset($previous_options['403_ttl'])) { + $ttl_status[] = '403 ' . $previous_options['403_ttl']; } - if ( isset( $previous_options[ '404_ttl' ] ) ) { - $ttl_status[] = '404 ' . $previous_options[ '404_ttl' ] ; + if (isset($previous_options['404_ttl'])) { + $ttl_status[] = '404 ' . $previous_options['404_ttl']; } - if ( isset( $previous_options[ '500_ttl' ] ) ) { - $ttl_status[] = '500 ' . $previous_options[ '500_ttl' ] ; + if (isset($previous_options['500_ttl'])) { + $ttl_status[] = '500 ' . $previous_options['500_ttl']; } - add_option( 'litespeed.conf.cache-ttl_status', $ttl_status ) ; + add_option('litespeed.conf.cache-ttl_status', $ttl_status); /** * Resave cdn cfg from lscfg to separate cfg when upgrade to v1.7 @@ -515,16 +526,16 @@ function litespeed_update_3_0( $ver ) { * * @since 1.7 */ - if ( isset( $previous_options[ 'cdn_url' ] ) ) { + if (isset($previous_options['cdn_url'])) { $cdn_mapping = array( - 'url' => $previous_options[ 'cdn_url' ], - 'inc_img' => $previous_options[ 'cdn_inc_img' ], - 'inc_css' => $previous_options[ 'cdn_inc_css' ], - 'inc_js' => $previous_options[ 'cdn_inc_js' ], - 'filetype' => $previous_options[ 'cdn_filetype' ], - ) ; - add_option( 'litespeed.conf.cdn-mapping', array( $cdn_mapping ) ) ; - Debug2::debug( "[Data] plugin_upgrade option adding CDN map" ) ; + 'url' => $previous_options['cdn_url'], + 'inc_img' => $previous_options['cdn_inc_img'], + 'inc_css' => $previous_options['cdn_inc_css'], + 'inc_js' => $previous_options['cdn_inc_js'], + 'filetype' => $previous_options['cdn_filetype'], + ); + add_option('litespeed.conf.cdn-mapping', array($cdn_mapping)); + Debug2::debug('[Data] plugin_upgrade option adding CDN map'); } /** @@ -534,122 +545,121 @@ function litespeed_update_3_0( $ver ) { * * @since 2.3 */ - if ( isset( $previous_options[ 'forced_cache_uri' ] ) ) { - add_option( 'litespeed.conf.cache-force_uri', $previous_options[ 'forced_cache_uri' ] ) ; + if (isset($previous_options['forced_cache_uri'])) { + add_option('litespeed.conf.cache-force_uri', $previous_options['forced_cache_uri']); } - if ( isset( $previous_options[ 'cache_uri_priv' ] ) ) { - add_option( 'litespeed.conf.cache-priv_uri', $previous_options[ 'cache_uri_priv' ] ) ; + if (isset($previous_options['cache_uri_priv'])) { + add_option('litespeed.conf.cache-priv_uri', $previous_options['cache_uri_priv']); } - if ( isset( $previous_options[ 'optm_excludes' ] ) ) { - add_option( 'litespeed.conf.optm-exc', $previous_options[ 'optm_excludes' ] ) ; + if (isset($previous_options['optm_excludes'])) { + add_option('litespeed.conf.optm-exc', $previous_options['optm_excludes']); } - if ( isset( $previous_options[ 'excludes_uri' ] ) ) { - add_option( 'litespeed.conf.cache-exc', $previous_options[ 'excludes_uri' ] ) ; + if (isset($previous_options['excludes_uri'])) { + add_option('litespeed.conf.cache-exc', $previous_options['excludes_uri']); } // Backup stale conf - Debug2::debug( "[Data] Backup stale conf" ); - delete_option( 'litespeed-cache-conf' ); - add_option( 'litespeed-cache-conf.bk', $previous_options ); + Debug2::debug('[Data] Backup stale conf'); + delete_option('litespeed-cache-conf'); + add_option('litespeed-cache-conf.bk', $previous_options); // Upgrade site_options if is network - if ( is_multisite() ) { - $ver = get_site_option( 'litespeed.conf._version' ) ; - if ( ! $ver ) { - Debug2::debug( "[Data] Conv multisite" ); - $previous_site_options = get_site_option( 'litespeed-cache-conf' ) ; + if (is_multisite()) { + $ver = get_site_option('litespeed.conf._version'); + if (!$ver) { + Debug2::debug('[Data] Conv multisite'); + $previous_site_options = get_site_option('litespeed-cache-conf'); $data = array( - 'network_enabled' => 'cache', - 'use_primary_settings' => 'use_primary_settings', - 'auto_upgrade' => 'auto_upgrade', - 'purge_upgrade' => 'purge-upgrade', - - 'cache_favicon' => 'cache-favicon', - 'cache_resources' => 'cache-resources', - 'mobileview_enabled' => 'cache-mobile', - 'mobileview_rules' => 'cache-mobile_rules', - 'login_cookie' => 'cache-login_cookie', - 'nocache_cookies' => 'cache-exc_cookies', - 'nocache_useragents' => 'cache-exc_useragents', - - 'cache_object' => 'object', - 'cache_object_kind' => 'object-kind', - 'cache_object_host' => 'object-host', - 'cache_object_port' => 'object-port', - 'cache_object_life' => 'object-life', - 'cache_object_persistent' => 'object-persistent', - 'cache_object_admin' => 'object-admin', - 'cache_object_transients' => 'object-transients', - 'cache_object_db_id' => 'object-db_id', - 'cache_object_user' => 'object-user', - 'cache_object_pswd' => 'object-psw', - - 'cache_browser' => 'cache-browser', - 'cache_browser_ttl' => 'cache-ttl_browser', - - 'media_webp_replace' => 'img_optm-webp_replace', - ) ; - foreach ( $data as $k => $v ) { - if ( ! isset( $previous_site_options[ $k ] ) ) { - continue ; + 'network_enabled' => 'cache', + 'use_primary_settings' => 'use_primary_settings', + 'auto_upgrade' => 'auto_upgrade', + 'purge_upgrade' => 'purge-upgrade', + + 'cache_favicon' => 'cache-favicon', + 'cache_resources' => 'cache-resources', + 'mobileview_enabled' => 'cache-mobile', + 'mobileview_rules' => 'cache-mobile_rules', + 'login_cookie' => 'cache-login_cookie', + 'nocache_cookies' => 'cache-exc_cookies', + 'nocache_useragents' => 'cache-exc_useragents', + + 'cache_object' => 'object', + 'cache_object_kind' => 'object-kind', + 'cache_object_host' => 'object-host', + 'cache_object_port' => 'object-port', + 'cache_object_life' => 'object-life', + 'cache_object_persistent' => 'object-persistent', + 'cache_object_admin' => 'object-admin', + 'cache_object_transients' => 'object-transients', + 'cache_object_db_id' => 'object-db_id', + 'cache_object_user' => 'object-user', + 'cache_object_pswd' => 'object-psw', + + 'cache_browser' => 'cache-browser', + 'cache_browser_ttl' => 'cache-ttl_browser', + + 'media_webp_replace' => 'img_optm-webp', + ); + foreach ($data as $k => $v) { + if (!isset($previous_site_options[$k])) { + continue; } // The folllowing values must be array - if ( ! is_array( $previous_site_options[ $k ] ) ) { - if ( in_array( $v, array( 'cache-mobile_rules', 'cache-exc_useragents', 'cache-exc_cookies' ) ) ) { - $previous_site_options[ $k ] = explode( '|', str_replace( '\\ ', ' ', $previous_site_options[ $k ] ) ) ; - $previous_site_options[ $k ] = array_filter( $previous_site_options[ $k ] ) ; + if (!is_array($previous_site_options[$k])) { + if (in_array($v, array('cache-mobile_rules', 'cache-exc_useragents', 'cache-exc_cookies'))) { + $previous_site_options[$k] = explode('|', str_replace('\\ ', ' ', $previous_site_options[$k])); + $previous_site_options[$k] = array_filter($previous_site_options[$k]); } } - add_site_option( 'litespeed.conf.' . $v, $previous_site_options[ $k ] ) ; + add_site_option('litespeed.conf.' . $v, $previous_site_options[$k]); } // These are already converted to single record in single site - $data = array( - 'object-global_groups', - 'object-non_persistent_groups', - ) ; - foreach ( $data as $v ) { - $old_data = get_option( $v ) ; - if ( $old_data ) { - add_site_option( 'litespeed.conf.' . $v, $old_data ) ; + $data = array('object-global_groups', 'object-non_persistent_groups'); + foreach ($data as $v) { + $old_data = get_option($v); + if ($old_data) { + add_site_option('litespeed.conf.' . $v, $old_data); } } - delete_site_option( 'litespeed-cache-conf' ) ; + delete_site_option('litespeed-cache-conf'); - add_site_option( 'litespeed.conf._version', '3.0' ) ; + add_site_option('litespeed.conf._version', '3.0'); } - } // delete tables - Debug2::debug( "[Data] Drop litespeed_optimizer" ); - $q = 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'litespeed_optimizer' ; - $wpdb->query( $q ) ; + Debug2::debug('[Data] Drop litespeed_optimizer'); + $q = 'DROP TABLE IF EXISTS ' . $wpdb->prefix . 'litespeed_optimizer'; + $wpdb->query($q); // Update image optm table - Debug2::debug( "[Data] Upgrade img_optm table" ); - $tb_exists = $wpdb->get_var( 'SHOW TABLES LIKE "' . $wpdb->prefix . 'litespeed_img_optm"' ); - if ( $tb_exists ) { + Debug2::debug('[Data] Upgrade img_optm table'); + $tb_exists = $wpdb->get_var('SHOW TABLES LIKE "' . $wpdb->prefix . 'litespeed_img_optm"'); + if ($tb_exists) { $status_mapping = array( - 'requested' => 3, - 'notified' => 6, - 'pulled' => 9, - 'failed' => -1, - 'miss' => -3, - 'err' => -9, - 'err_fetch' => -5, - 'err_optm' => -7, - 'xmeta' => -8, + 'requested' => 3, + 'notified' => 6, + 'pulled' => 9, + 'failed' => -1, + 'miss' => -3, + 'err' => -9, + 'err_fetch' => -5, + 'err_optm' => -7, + 'xmeta' => -8, ); - foreach ( $status_mapping as $k => $v ) { - $q = "UPDATE `" . $wpdb->prefix . "litespeed_img_optm` SET optm_status='$v' WHERE optm_status='$k'"; - $wpdb->query( $q ) ; + foreach ($status_mapping as $k => $v) { + $q = 'UPDATE `' . $wpdb->prefix . "litespeed_img_optm` SET optm_status='$v' WHERE optm_status='$k'"; + $wpdb->query($q); } - $q = 'ALTER TABLE `' . $wpdb->prefix . 'litespeed_img_optm` + $q = + 'ALTER TABLE `' . + $wpdb->prefix . + 'litespeed_img_optm` DROP INDEX `post_id_2`, DROP INDEX `root_id`, DROP INDEX `src_md5`, @@ -664,36 +674,12 @@ function litespeed_update_3_0( $ver ) { MODIFY COLUMN `optm_status` tinyint(4) NOT NULL DEFAULT 0, MODIFY COLUMN `src` text COLLATE utf8mb4_unicode_ci NOT NULL '; - $wpdb->query( $q ) ; + $wpdb->query($q); } - delete_option( 'litespeed-recommended' ); - - Debug2::debug( "[Data] litespeed_update_3_0 done!" ); + delete_option('litespeed-recommended'); - add_option( 'litespeed.conf._version', '3.0' ) ; + Debug2::debug('[Data] litespeed_update_3_0 done!'); + add_option('litespeed.conf._version', '3.0'); } - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/db-optm.cls.php b/src/db-optm.cls.php index a1204061c..d62337e44 100644 --- a/src/db-optm.cls.php +++ b/src/db-optm.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class DB_Optm extends Root { +class DB_Optm extends Root +{ private static $_hide_more = false; - private static $TYPES = array( 'revision', 'auto_draft', 'trash_post', 'spam_comment', 'trash_comment', 'trackback-pingback', 'expired_transient', 'all_transients', 'optimize_tables' ); + private static $TYPES = array( + 'revision', + 'orphaned_post_meta', + 'auto_draft', + 'trash_post', + 'spam_comment', + 'trash_comment', + 'trackback-pingback', + 'expired_transient', + 'all_transients', + 'optimize_tables', + ); const TYPE_CONV_TB = 'conv_innodb'; /** @@ -23,7 +37,8 @@ class DB_Optm extends Root { * * @since 3.0 */ - public static function hide_more() { + public static function hide_more() + { return self::$_hide_more; } @@ -36,27 +51,28 @@ public static function hide_more() { * @param bool $ignore_multisite If ignore multisite check * @return int The rows that will be affected */ - public function db_count( $type, $ignore_multisite = false ) { - if ( $type === 'all' ) { + public function db_count($type, $ignore_multisite = false) + { + if ($type === 'all') { $num = 0; - foreach ( self::$TYPES as $v ) { - $num += $this->db_count( $v ); + foreach (self::$TYPES as $v) { + $num += $this->db_count($v); } return $num; } - if ( ! $ignore_multisite ) { - if ( is_multisite() && is_network_admin() ) { + if (!$ignore_multisite) { + if (is_multisite() && is_network_admin()) { $num = 0; $blogs = Activation::get_network_ids(); - foreach ( $blogs as $k => $blog_id ) { - if ( $k > 3 ) { + foreach ($blogs as $k => $blog_id) { + if ($k > 3) { self::$_hide_more = true; break; } - switch_to_blog( $blog_id ); - $num += $this->db_count( $type, true ); + switch_to_blog($blog_id); + $num += $this->db_count($type, true); restore_current_blog(); } return $num; @@ -65,48 +81,51 @@ public function db_count( $type, $ignore_multisite = false ) { global $wpdb; - switch ( $type ) { + switch ($type) { case 'revision': - $rev_max = (int) $this->conf( Base::O_DB_OPTM_REVISIONS_MAX ); - $rev_age = (int) $this->conf( Base::O_DB_OPTM_REVISIONS_AGE ); + $rev_max = (int) $this->conf(Base::O_DB_OPTM_REVISIONS_MAX); + $rev_age = (int) $this->conf(Base::O_DB_OPTM_REVISIONS_AGE); $sql_add = ''; - if ( $rev_age ) { + if ($rev_age) { $sql_add = " and post_modified < DATE_SUB( NOW(), INTERVAL $rev_age DAY ) "; } $sql = "SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_type = 'revision' $sql_add"; - if ( ! $rev_max ) { - return $wpdb->get_var( $sql ); + if (!$rev_max) { + return $wpdb->get_var($sql); } // Has count limit $sql = "SELECT COUNT(*)-$rev_max FROM `$wpdb->posts` WHERE post_type = 'revision' $sql_add GROUP BY post_parent HAVING count(*)>$rev_max"; - $res = $wpdb->get_results( $sql, ARRAY_N ); + $res = $wpdb->get_results($sql, ARRAY_N); Utility::compatibility(); - return array_sum( array_column( $res, 0 ) ); + return array_sum(array_column($res, 0)); + + case 'orphaned_post_meta': + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->postmeta` a LEFT JOIN `$wpdb->posts` b ON b.ID=a.post_id WHERE b.ID IS NULL"); case 'auto_draft': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'auto-draft'" ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'auto-draft'"); case 'trash_post': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'trash'" ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'trash'"); case 'spam_comment': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'spam'" ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'spam'"); case 'trash_comment': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'trash'" ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'trash'"); case 'trackback-pingback': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback'" ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback'"); case 'expired_transient': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time() ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time()); case 'all_transients': - return $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '%_transient_%'" ); + return $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '%_transient_%'"); case 'optimize_tables': - return $wpdb->get_var( "SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" . DB_NAME . "' and ENGINE <> 'InnoDB' and DATA_FREE > 0" ); + return $wpdb->get_var("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" . DB_NAME . "' and ENGINE <> 'InnoDB' and DATA_FREE > 0"); } return '-'; @@ -119,79 +138,113 @@ public function db_count( $type, $ignore_multisite = false ) { * @since 3.0 changed to private * @access private */ - private function _db_clean( $type ) { - if ( $type === 'all' ) { - foreach ( self::$TYPES as $v ) { - $this->_db_clean( $v ); + private function _db_clean($type) + { + if ($type === 'all') { + foreach (self::$TYPES as $v) { + $this->_db_clean($v); } - return __( 'Clean all successfully.', 'litespeed-cache' ); + return __('Clean all successfully.', 'litespeed-cache'); } global $wpdb; - switch ( $type ) { + switch ($type) { case 'revision': - $rev_max = (int) $this->conf( Base::O_DB_OPTM_REVISIONS_MAX ); - $rev_age = (int) $this->conf( Base::O_DB_OPTM_REVISIONS_AGE ); - - $sql_add = ''; - if ( $rev_age ) { - $sql_add = " and post_modified < DATE_SUB( NOW(), INTERVAL $rev_age DAY ) "; - } - - if ( ! $rev_max ) { - $sql = "DELETE FROM `$wpdb->posts` WHERE post_type = 'revision' $sql_add"; - $wpdb->query( $sql ); - } - else { // Has count limit - $sql = "SELECT COUNT(*)-$rev_max as del_max,post_parent FROM `$wpdb->posts` WHERE post_type = 'revision' $sql_add GROUP BY post_parent HAVING count(*)>$rev_max"; - $res = $wpdb->get_results( $sql ); - foreach ( $res as $v ) { - $sql = "DELETE FROM `$wpdb->posts` WHERE post_type = 'revision' AND post_parent = %d ORDER BY ID LIMIT %d"; - $wpdb->query( $wpdb->prepare( $sql, array( $v->post_parent, $v->del_max ) ) ); + $rev_max = (int) $this->conf(Base::O_DB_OPTM_REVISIONS_MAX); + $rev_age = (int) $this->conf(Base::O_DB_OPTM_REVISIONS_AGE); + + $postmeta = "`$wpdb->postmeta`"; + $posts = "`$wpdb->posts`"; + + $sql_postmeta_join = function ($table) use ($postmeta, $posts) { + return " + $postmeta + CROSS JOIN $table + ON $posts.ID = $postmeta.post_id + "; + }; + + $sql_where = "WHERE $posts.post_type = 'revision'"; + + $sql_add = $rev_age ? "AND $posts.post_modified < DATE_SUB( NOW(), INTERVAL $rev_age DAY )" : ''; + + if (!$rev_max) { + $sql_where = "$sql_where $sql_add"; + $sql_postmeta = $sql_postmeta_join($posts); + $wpdb->query("DELETE $postmeta FROM $sql_postmeta $sql_where"); + $wpdb->query("DELETE FROM $posts $sql_where"); + } else { + // Has count limit + $sql = " + SELECT COUNT(*) - $rev_max + AS del_max, post_parent + FROM $posts + WHERE post_type = 'revision' + $sql_add + GROUP BY post_parent + HAVING COUNT(*) > $rev_max + "; + $res = $wpdb->get_results($sql); + $sql_where = " + $sql_where + AND post_parent = %d + ORDER BY ID + LIMIT %d + "; + $sql_postmeta = $sql_postmeta_join("(SELECT ID FROM $posts $sql_where) AS $posts"); + foreach ($res as $v) { + $args = array($v->post_parent, $v->del_max); + $sql = $wpdb->prepare("DELETE $postmeta FROM $sql_postmeta", $args); + $wpdb->query($sql); + $sql = $wpdb->prepare("DELETE FROM $posts $sql_where", $args); + $wpdb->query($sql); } } - return __( 'Clean post revisions successfully.', 'litespeed-cache' ); + return __('Clean post revisions successfully.', 'litespeed-cache'); + + case 'orphaned_post_meta': + $wpdb->query("DELETE a FROM `$wpdb->postmeta` a LEFT JOIN `$wpdb->posts` b ON b.ID=a.post_id WHERE b.ID IS NULL"); + return __('Clean orphaned post meta successfully.', 'litespeed-cache'); case 'auto_draft': - $wpdb->query( "DELETE FROM `$wpdb->posts` WHERE post_status = 'auto-draft'" ); - return __( 'Clean auto drafts successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->posts` WHERE post_status = 'auto-draft'"); + return __('Clean auto drafts successfully.', 'litespeed-cache'); case 'trash_post': - $wpdb->query( "DELETE FROM `$wpdb->posts` WHERE post_status = 'trash'" ); - return __( 'Clean trashed posts and pages successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->posts` WHERE post_status = 'trash'"); + return __('Clean trashed posts and pages successfully.', 'litespeed-cache'); case 'spam_comment': - $wpdb->query( "DELETE FROM `$wpdb->comments` WHERE comment_approved = 'spam'" ); - return __( 'Clean spam comments successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_approved = 'spam'"); + return __('Clean spam comments successfully.', 'litespeed-cache'); case 'trash_comment': - $wpdb->query( "DELETE FROM `$wpdb->comments` WHERE comment_approved = 'trash'" ); - return __( 'Clean trashed comments successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_approved = 'trash'"); + return __('Clean trashed comments successfully.', 'litespeed-cache'); case 'trackback-pingback': - $wpdb->query( "DELETE FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback'" ); - return __( 'Clean trackbacks and pingbacks successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback'"); + return __('Clean trackbacks and pingbacks successfully.', 'litespeed-cache'); case 'expired_transient': - $wpdb->query( "DELETE FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time() ); - return __( 'Clean expired transients successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time()); + return __('Clean expired transients successfully.', 'litespeed-cache'); case 'all_transients': - $wpdb->query( "DELETE FROM `$wpdb->options` WHERE option_name LIKE '%\\_transient\\_%'" ); - return __( 'Clean all transients successfully.', 'litespeed-cache' ); + $wpdb->query("DELETE FROM `$wpdb->options` WHERE option_name LIKE '%\\_transient\\_%'"); + return __('Clean all transients successfully.', 'litespeed-cache'); case 'optimize_tables': $sql = "SELECT table_name, DATA_FREE FROM information_schema.tables WHERE TABLE_SCHEMA = '" . DB_NAME . "' and ENGINE <> 'InnoDB' and DATA_FREE > 0"; - $result = $wpdb->get_results( $sql ); - if ( $result ) { - foreach ( $result as $row ) { - $wpdb->query( 'OPTIMIZE TABLE ' . $row->table_name ); + $result = $wpdb->get_results($sql); + if ($result) { + foreach ($result as $row) { + $wpdb->query('OPTIMIZE TABLE ' . $row->table_name); } } - return __( 'Optimized all tables.', 'litespeed-cache' ); + return __('Optimized all tables.', 'litespeed-cache'); } - } /** @@ -200,10 +253,11 @@ private function _db_clean( $type ) { * @since 3.0 * @access public */ - public function list_myisam() { + public function list_myisam() + { global $wpdb; $q = "SELECT * FROM information_schema.tables WHERE TABLE_SCHEMA = '" . DB_NAME . "' and ENGINE = 'myisam' AND TABLE_NAME LIKE '{$wpdb->prefix}%'"; - return $wpdb->get_results( $q ); + return $wpdb->get_results($q); } /** @@ -212,37 +266,37 @@ public function list_myisam() { * @since 3.0 * @access private */ - private function _conv_innodb() { + private function _conv_innodb() + { global $wpdb; - if ( empty( $_GET[ 'tb' ] ) ) { - Admin_Display::error( 'No table to convert' ); + if (empty($_GET['tb'])) { + Admin_Display::error('No table to convert'); return; } $tb = false; $list = $this->list_myisam(); - foreach ( $list as $v ) { - if ( $v->TABLE_NAME == $_GET[ 'tb' ] ) { + foreach ($list as $v) { + if ($v->TABLE_NAME == $_GET['tb']) { $tb = $v->TABLE_NAME; break; } } - if ( ! $tb ) { - Admin_Display::error( 'No existing table' ); + if (!$tb) { + Admin_Display::error('No existing table'); return; } $q = 'ALTER TABLE ' . DB_NAME . '.' . $tb . ' ENGINE = InnoDB'; - $wpdb->query( $q ); - - Debug2::debug( "[DB] Converted $tb to InnoDB" ); + $wpdb->query($q); - $msg = __( 'Converted to InnoDB successfully.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + Debug2::debug("[DB] Converted $tb to InnoDB"); + $msg = __('Converted to InnoDB successfully.', 'litespeed-cache'); + Admin_Display::succeed($msg); } /** @@ -251,12 +305,15 @@ private function _conv_innodb() { * @since 3.0 * @access public */ - public function autoload_summary() { + public function autoload_summary() + { global $wpdb; - $summary = $wpdb->get_row( "SELECT SUM(LENGTH(option_value)) AS autoload_size,COUNT(*) AS autload_entries FROM `$wpdb->options` WHERE autoload='yes'" ); + $summary = $wpdb->get_row("SELECT SUM(LENGTH(option_value)) AS autoload_size,COUNT(*) AS autload_entries FROM `$wpdb->options` WHERE autoload='yes'"); - $summary->autoload_toplist = $wpdb->get_results( "SELECT option_name, LENGTH(option_value) AS option_value_length FROM `$wpdb->options` WHERE autoload='yes' ORDER BY option_value_length DESC LIMIT 20" ); + $summary->autoload_toplist = $wpdb->get_results( + "SELECT option_name, LENGTH(option_value) AS option_value_length FROM `$wpdb->options` WHERE autoload='yes' ORDER BY option_value_length DESC LIMIT 20" + ); return $summary; } @@ -267,27 +324,27 @@ public function autoload_summary() { * @since 3.0 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case 'all': - case in_array( $type, self::$TYPES ): - if ( is_multisite() && is_network_admin() ) { + case in_array($type, self::$TYPES): + if (is_multisite() && is_network_admin()) { $blogs = Activation::get_network_ids(); - foreach ( $blogs as $blog_id ) { - switch_to_blog( $blog_id ); - $msg = $this->_db_clean( $type ); + foreach ($blogs as $blog_id) { + switch_to_blog($blog_id); + $msg = $this->_db_clean($type); restore_current_blog(); } + } else { + $msg = $this->_db_clean($type); } - else { - $msg = $this->_db_clean( $type ); - } - Admin_Display::succeed( $msg ); + Admin_Display::succeed($msg); break; - case self::TYPE_CONV_TB : + case self::TYPE_CONV_TB: $this->_conv_innodb(); break; @@ -297,6 +354,4 @@ public function handler() { Admin::redirect(); } - } - diff --git a/src/debug2.cls.php b/src/debug2.cls.php index bdfffa48f..d7a1b3c1b 100644 --- a/src/debug2.cls.php +++ b/src/debug2.cls.php @@ -1,12 +1,15 @@ conf( Base::O_DEBUG_LEVEL ) ) { - ! defined( 'LSCWP_LOG_MORE' ) && define( 'LSCWP_LOG_MORE', true ); + if ($this->conf(Base::O_DEBUG_LEVEL)) { + !defined('LSCWP_LOG_MORE') && define('LSCWP_LOG_MORE', true); } - defined( 'LSCWP_DEBUG_EXC_STRINGS' ) || define( 'LSCWP_DEBUG_EXC_STRINGS', $this->conf( Base::O_DEBUG_EXC_STRINGS ) ); + defined('LSCWP_DEBUG_EXC_STRINGS') || define('LSCWP_DEBUG_EXC_STRINGS', $this->conf(Base::O_DEBUG_EXC_STRINGS)); } /** @@ -47,9 +51,12 @@ public function __construct() { * @since 4.7 * @access public */ - public static function ended() { - self::debug( 'Response headers', headers_list() ); - self::debug( "End response\n--------------------------------------------------------------------------------\n" ); + public static function ended() + { + self::debug('Response headers', headers_list()); + + $elapsed_time = number_format((microtime(true) - LSCWP_TS_0) * 1000, 2); + self::debug("End response\n--------------------------------------------------Duration: " . $elapsed_time . " ms------------------------------\n"); } /** @@ -58,33 +65,33 @@ public static function ended() { * @since 2.9.5 * @access public */ - public function beta_test( $zip = false ) { - if ( ! $zip ) { - if ( empty( $_REQUEST[ self::BETA_TEST_URL ] ) ) { + public function beta_test($zip = false) + { + if (!$zip) { + if (empty($_REQUEST[self::BETA_TEST_URL])) { return; } - $zip = $_REQUEST[ self::BETA_TEST_URL ]; - if ( $zip !== Debug2::BETA_TEST_URL_WP ) { - if ( $zip === 'latest' ) { + $zip = $_REQUEST[self::BETA_TEST_URL]; + if ($zip !== Debug2::BETA_TEST_URL_WP) { + if ($zip === 'latest') { $zip = Debug2::BETA_TEST_URL_WP; - } - else { + } else { // Generate zip url - $zip = $this->_package_zip( $zip ); + $zip = $this->_package_zip($zip); } } } - if ( ! $zip ) { - Debug2::debug( '[Debug2] ❌ No ZIP file' ); + if (!$zip) { + Debug2::debug('[Debug2] ❌ No ZIP file'); return; } - Debug2::debug( '[Debug2] ZIP file ' . $zip ); + Debug2::debug('[Debug2] ZIP file ' . $zip); - $update_plugins = get_site_transient( 'update_plugins' ); - if ( ! is_object( $update_plugins ) ) { + $update_plugins = get_site_transient('update_plugins'); + if (!is_object($update_plugins)) { $update_plugins = new \stdClass(); } @@ -95,9 +102,9 @@ public function beta_test( $zip = false ) { $plugin_info->package = $zip; $plugin_info->url = 'https://wordpress.org/plugins/litespeed-cache/'; - $update_plugins->response[ Core::PLUGIN_FILE ] = $plugin_info; + $update_plugins->response[Core::PLUGIN_FILE] = $plugin_info; - set_site_transient( 'update_plugins', $update_plugins ); + set_site_transient('update_plugins', $update_plugins); // Run upgrade Activation::cls()->upgrade(); @@ -109,17 +116,18 @@ public function beta_test( $zip = false ) { * @since 2.9.5 * @access private */ - private function _package_zip( $commit ) { + private function _package_zip($commit) + { $data = array( - 'commit' => $commit, + 'commit' => $commit, ); - $res = Cloud::get( Cloud::API_BETA_TEST, $data ); + $res = Cloud::get(Cloud::API_BETA_TEST, $data); - if ( empty( $res[ 'zip' ] ) ) { + if (empty($res['zip'])) { return false; } - return $res[ 'zip' ]; + return $res['zip']; } /** @@ -128,20 +136,20 @@ private function _package_zip( $commit ) { * @since 2.7 * @access public */ - public static function log_purge( $purge_header ) { + public static function log_purge($purge_header) + { // Check if debug is ON - if ( ! defined( 'LSCWP_LOG' ) && ! defined( 'LSCWP_LOG_BYPASS_NOTADMIN' ) ) { + if (!defined('LSCWP_LOG') && !defined('LSCWP_LOG_BYPASS_NOTADMIN')) { return; } $purge_file = self::$log_path_prefix . '/debug.purge.log'; - self::cls()->_init_request( $purge_file ); - - $msg = $purge_header . self::_backtrace_info( 6 ); + self::cls()->_init_request($purge_file); - File::append( $purge_file, self::format_message( $msg ) ); + $msg = $purge_header . self::_backtrace_info(6); + File::append($purge_file, self::format_message($msg)); } /** @@ -150,11 +158,12 @@ public static function log_purge( $purge_header ) { * @since 1.1.0 * @access public */ - public function init() { - $debug = $this->conf( Base::O_DEBUG ); - if ( $debug == Base::VAL_ON2 ) { - if ( ! $this->cls( 'Router' )->is_admin_ip() ) { - defined( 'LSCWP_LOG_BYPASS_NOTADMIN' ) || define( 'LSCWP_LOG_BYPASS_NOTADMIN', true ); + public function init() + { + $debug = $this->conf(Base::O_DEBUG); + if ($debug == Base::VAL_ON2) { + if (!$this->cls('Router')->is_admin_ip()) { + defined('LSCWP_LOG_BYPASS_NOTADMIN') || define('LSCWP_LOG_BYPASS_NOTADMIN', true); return; } } @@ -164,26 +173,26 @@ public function init() { * This is after LSCWP_LOG_BYPASS_NOTADMIN to make `log_purge()` still work * @since 3.0 */ - $list = $this->conf( Base::O_DEBUG_INC ); - if ( $list ) { - $result = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $list ); - if ( ! $result ) { + $list = $this->conf(Base::O_DEBUG_INC); + if ($list) { + $result = Utility::str_hit_array($_SERVER['REQUEST_URI'], $list); + if (!$result) { return; } } - $list = $this->conf( Base::O_DEBUG_EXC ); - if ( $list ) { - $result = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $list ); - if ( $result ) { + $list = $this->conf(Base::O_DEBUG_EXC); + if ($list) { + $result = Utility::str_hit_array($_SERVER['REQUEST_URI'], $list); + if ($result) { return; } } - if ( ! defined( 'LSCWP_LOG' ) ) {// If not initialized, do it now + if (!defined('LSCWP_LOG')) { + // If not initialized, do it now $this->_init_request(); - define( 'LSCWP_LOG', true ); - + define('LSCWP_LOG', true); } } @@ -193,23 +202,24 @@ public function init() { * @since 1.0.12 * @access private */ - private function _init_request( $log_file = null ) { - if ( ! $log_file ) { + private function _init_request($log_file = null) + { + if (!$log_file) { $log_file = self::$log_path; } // Check log file size - $log_file_size = $this->conf( Base::O_DEBUG_FILESIZE ); - if ( file_exists( $log_file ) && filesize( $log_file ) > $log_file_size * 1000000 ) { - File::save( $log_file, '' ); + $log_file_size = $this->conf(Base::O_DEBUG_FILESIZE); + if (file_exists($log_file) && filesize($log_file) > $log_file_size * 1000000) { + File::save($log_file, ''); } // For more than 2s's requests, add more break - if ( file_exists( $log_file ) && time() - filemtime( $log_file ) > 2 ) { - File::append( $log_file, "\n\n\n\n" ); + if (file_exists($log_file) && time() - filemtime($log_file) > 2) { + File::append($log_file, "\n\n\n\n"); } - if ( PHP_SAPI == 'cli' ) { + if (PHP_SAPI == 'cli') { return; } @@ -219,66 +229,67 @@ private function _init_request( $log_file = null ) { 'HTTP_USER_AGENT' => '', 'HTTP_ACCEPT_ENCODING' => '', 'HTTP_COOKIE' => '', + 'REQUEST_METHOD' => '', + 'SERVER_PROTOCOL' => '', 'X-LSCACHE' => '', 'LSCACHE_VARY_COOKIE' => '', 'LSCACHE_VARY_VALUE' => '', 'ESI_CONTENT_TYPE' => '', ); - $server = array_merge( $servervars, $_SERVER ); + $server = array_merge($servervars, $_SERVER); $params = array(); - if ( isset( $_SERVER[ 'HTTPS' ] ) && $_SERVER[ 'HTTPS' ] == 'on' ) { + if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') { $server['SERVER_PROTOCOL'] .= ' (HTTPS) '; } - $param = sprintf( '💓 ------%s %s %s', $server['REQUEST_METHOD'], $server['SERVER_PROTOCOL'], strtok( $server['REQUEST_URI'], '?' ) ); + $param = sprintf('💓 ------%s %s %s', $server['REQUEST_METHOD'], $server['SERVER_PROTOCOL'], strtok($server['REQUEST_URI'], '?')); - $qs = ! empty( $server['QUERY_STRING'] ) ? $server['QUERY_STRING'] : ''; - if ( $this->conf( Base::O_DEBUG_COLLAPS_QS ) ) { - if ( strlen( $qs ) > 53 ) { - $qs = substr( $qs, 0, 53 ) . '...'; + $qs = !empty($server['QUERY_STRING']) ? $server['QUERY_STRING'] : ''; + if ($this->conf(Base::O_DEBUG_COLLAPS_QS)) { + if (strlen($qs) > 53) { + $qs = substr($qs, 0, 53) . '...'; } - if ( $qs ) { + if ($qs) { $param .= ' ? ' . $qs; } $params[] = $param; - } - else { + } else { $params[] = $param; $params[] = 'Query String: ' . $qs; } - if ( ! empty( $_SERVER[ 'HTTP_REFERER' ] ) ) { - $params[] = 'HTTP_REFERER: ' . $server[ 'HTTP_REFERER' ]; + if (!empty($_SERVER['HTTP_REFERER'])) { + $params[] = 'HTTP_REFERER: ' . $server['HTTP_REFERER']; } - if ( defined( 'LSCWP_LOG_MORE' ) ) { - $params[] = 'User Agent: ' . $server[ 'HTTP_USER_AGENT' ]; + if (defined('LSCWP_LOG_MORE')) { + $params[] = 'User Agent: ' . $server['HTTP_USER_AGENT']; $params[] = 'Accept: ' . $server['HTTP_ACCEPT']; $params[] = 'Accept Encoding: ' . $server['HTTP_ACCEPT_ENCODING']; } - if ( $this->conf( Base::O_DEBUG_COOKIE ) ) { + if ($this->conf(Base::O_DEBUG_COOKIE)) { $params[] = 'Cookie: ' . $server['HTTP_COOKIE']; } - if ( isset( $_COOKIE[ '_lscache_vary' ] ) ) { - $params[] = 'Cookie _lscache_vary: ' . $_COOKIE[ '_lscache_vary' ]; + if (isset($_COOKIE['_lscache_vary'])) { + $params[] = 'Cookie _lscache_vary: ' . $_COOKIE['_lscache_vary']; } - if ( defined( 'LSCWP_LOG_MORE' ) ) { - $params[] = 'X-LSCACHE: ' . ( ! empty( $server[ 'X-LSCACHE' ] ) ? 'true' : 'false' ); + if (defined('LSCWP_LOG_MORE')) { + $params[] = 'X-LSCACHE: ' . (!empty($server['X-LSCACHE']) ? 'true' : 'false'); } - if( $server['LSCACHE_VARY_COOKIE'] ) { + if ($server['LSCACHE_VARY_COOKIE']) { $params[] = 'LSCACHE_VARY_COOKIE: ' . $server['LSCACHE_VARY_COOKIE']; } - if( $server['LSCACHE_VARY_VALUE'] ) { + if ($server['LSCACHE_VARY_VALUE']) { $params[] = 'LSCACHE_VARY_VALUE: ' . $server['LSCACHE_VARY_VALUE']; } - if( $server['ESI_CONTENT_TYPE'] ) { + if ($server['ESI_CONTENT_TYPE']) { $params[] = 'ESI_CONTENT_TYPE: ' . $server['ESI_CONTENT_TYPE']; } - $request = array_map( __CLASS__ . '::format_message', $params ); + $request = array_map(__CLASS__ . '::format_message', $params); - File::append( $log_file, $request ); + File::append($log_file, $request); } /** @@ -289,32 +300,33 @@ private function _init_request( $log_file = null ) { * @param string $msg The log message to write. * @return string The formatted log message. */ - private static function format_message( $msg ) { + private static function format_message($msg) + { // If call here without calling get_enabled() first, improve compatibility - if ( ! defined( 'LSCWP_LOG_TAG' ) ) { + if (!defined('LSCWP_LOG_TAG')) { return $msg . "\n"; } - if ( ! isset( self::$_prefix ) ) { + if (!isset(self::$_prefix)) { // address - if ( PHP_SAPI == 'cli' ) { + if (PHP_SAPI == 'cli') { $addr = '=CLI='; - if ( isset( $_SERVER[ 'USER' ] ) ) { - $addr .= $_SERVER[ 'USER' ]; - } - elseif ( $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] ) { - $addr .= $_SERVER[ 'HTTP_X_FORWARDED_FOR' ]; + if (isset($_SERVER['USER'])) { + $addr .= $_SERVER['USER']; + } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $addr .= $_SERVER['HTTP_X_FORWARDED_FOR']; } - } - else { - $addr = $_SERVER[ 'REMOTE_ADDR' ] . ':' . $_SERVER[ 'REMOTE_PORT' ]; + } else { + $addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; + $port = isset($_SERVER['REMOTE_PORT']) ? $_SERVER['REMOTE_PORT'] : ''; + $addr = "$addr:$port"; } // Generate a unique string per request - self::$_prefix = sprintf( " [%s %s %s] ", $addr, LSCWP_LOG_TAG, Str::rrand( 3 ) ); + self::$_prefix = sprintf(' [%s %s %s] ', $addr, LSCWP_LOG_TAG, Str::rrand(3)); } - list( $usec, $sec ) = explode(' ', microtime() ); - return date( 'm/d/y H:i:s', $sec + LITESPEED_TIME_OFFSET ) . substr( $usec, 1, 4 ) . self::$_prefix . $msg . "\n"; + list($usec, $sec) = explode(' ', microtime()); + return date('m/d/y H:i:s', $sec + LITESPEED_TIME_OFFSET) . substr($usec, 1, 4) . self::$_prefix . $msg . "\n"; } /** @@ -323,45 +335,46 @@ private static function format_message( $msg ) { * @since 1.1.3 * @access public */ - public static function debug( $msg, $backtrace_limit = false ) { - if ( ! defined( 'LSCWP_LOG' ) ) { + public static function debug($msg, $backtrace_limit = false) + { + if (!defined('LSCWP_LOG')) { return; } - if ( defined( 'LSCWP_DEBUG_EXC_STRINGS' ) && Utility::str_hit_array( $msg, LSCWP_DEBUG_EXC_STRINGS ) ) { + if (defined('LSCWP_DEBUG_EXC_STRINGS') && Utility::str_hit_array($msg, LSCWP_DEBUG_EXC_STRINGS)) { return; } - if ( $backtrace_limit !== false ) { - if ( ! is_numeric( $backtrace_limit ) ) { - $backtrace_limit = self::trim_longtext( $backtrace_limit ); - if ( is_array( $backtrace_limit ) && count( $backtrace_limit ) == 1 && ! empty( $backtrace_limit[ 0 ] ) ) { - $msg .= ' --- ' . $backtrace_limit[ 0 ]; + if ($backtrace_limit !== false) { + if (!is_numeric($backtrace_limit)) { + $backtrace_limit = self::trim_longtext($backtrace_limit); + if (is_array($backtrace_limit) && count($backtrace_limit) == 1 && !empty($backtrace_limit[0])) { + $msg .= ' --- ' . $backtrace_limit[0]; + } else { + $msg .= ' --- ' . var_export($backtrace_limit, true); } - else { - $msg .= ' --- ' . var_export( $backtrace_limit, true ); - } - self::push( $msg ); + self::push($msg); return; } - self::push( $msg, $backtrace_limit + 1 ); + self::push($msg, $backtrace_limit + 1); return; } - self::push( $msg ); + self::push($msg); } /** * Trim long string before array dump * @since 3.3 */ - public static function trim_longtext( $backtrace_limit ) { - if ( is_array( $backtrace_limit ) ) { - $backtrace_limit = array_map( __CLASS__ . '::trim_longtext', $backtrace_limit ); + public static function trim_longtext($backtrace_limit) + { + if (is_array($backtrace_limit)) { + $backtrace_limit = array_map(__CLASS__ . '::trim_longtext', $backtrace_limit); } - if ( is_string( $backtrace_limit ) && strlen( $backtrace_limit ) > 500 ) { - $backtrace_limit = substr( $backtrace_limit, 0, 1000 ) . '...'; + if (is_string($backtrace_limit) && strlen($backtrace_limit) > 500) { + $backtrace_limit = substr($backtrace_limit, 0, 1000) . '...'; } return $backtrace_limit; } @@ -372,11 +385,12 @@ public static function trim_longtext( $backtrace_limit ) { * @since 1.2.0 * @access public */ - public static function debug2( $msg, $backtrace_limit = false ) { - if ( ! defined( 'LSCWP_LOG_MORE' ) ) { + public static function debug2($msg, $backtrace_limit = false) + { + if (!defined('LSCWP_LOG_MORE')) { return; } - self::debug( $msg, $backtrace_limit ); + self::debug($msg, $backtrace_limit); } /** @@ -387,13 +401,14 @@ public static function debug2( $msg, $backtrace_limit = false ) { * @param string $msg The debug message. * @param int $backtrace_limit Backtrace depth. */ - private static function push( $msg, $backtrace_limit = false ) { + private static function push($msg, $backtrace_limit = false) + { // backtrace handler - if ( defined( 'LSCWP_LOG_MORE' ) && $backtrace_limit !== false ) { - $msg .= self::_backtrace_info( $backtrace_limit ); + if (defined('LSCWP_LOG_MORE') && $backtrace_limit !== false) { + $msg .= self::_backtrace_info($backtrace_limit); } - File::append( self::$log_path, self::format_message( $msg ) ); + File::append(self::$log_path, self::format_message($msg)); } /** @@ -401,40 +416,41 @@ private static function push( $msg, $backtrace_limit = false ) { * * @since 2.7 */ - private static function _backtrace_info( $backtrace_limit ) { + private static function _backtrace_info($backtrace_limit) + { $msg = ''; - $trace = version_compare( PHP_VERSION, '5.4.0', '<' ) ? debug_backtrace() : debug_backtrace( false, $backtrace_limit + 3 ); - for ( $i=2; $i <= $backtrace_limit + 2; $i++ ) {// 0st => _backtrace_info(), 1st => push() - if ( empty( $trace[ $i ][ 'class' ] ) ) { - if ( empty( $trace[ $i ][ 'file' ] ) ) { + $trace = version_compare(PHP_VERSION, '5.4.0', '<') ? debug_backtrace() : debug_backtrace(false, $backtrace_limit + 3); + for ($i = 2; $i <= $backtrace_limit + 2; $i++) { + // 0st => _backtrace_info(), 1st => push() + if (empty($trace[$i]['class'])) { + if (empty($trace[$i]['file'])) { break; } - $log = "\n" . $trace[ $i ][ 'file' ]; - } - else { - if ( $trace[$i]['class'] == __CLASS__ ) { + $log = "\n" . $trace[$i]['file']; + } else { + if ($trace[$i]['class'] == __CLASS__) { continue; } $args = ''; - if ( ! empty( $trace[ $i ][ 'args' ] ) ) { - foreach ( $trace[ $i ][ 'args' ] as $v ) { - if ( is_array( $v ) ) { + if (!empty($trace[$i]['args'])) { + foreach ($trace[$i]['args'] as $v) { + if (is_array($v)) { $v = 'ARRAY'; } - if ( is_string( $v ) || is_numeric( $v ) ) { + if (is_string($v) || is_numeric($v)) { $args .= $v . ','; } } - $args = substr( $args, 0, strlen( $args ) > 100 ? 100 : -1 ); + $args = substr($args, 0, strlen($args) > 100 ? 100 : -1); } $log = str_replace('Core', 'LSC', $trace[$i]['class']) . $trace[$i]['type'] . $trace[$i]['function'] . '(' . $args . ')'; } - if ( ! empty( $trace[$i-1]['line'] ) ) { - $log .= '@' . $trace[$i-1]['line']; + if (!empty($trace[$i - 1]['line'])) { + $log .= '@' . $trace[$i - 1]['line']; } $msg .= " => $log"; } @@ -448,10 +464,11 @@ private static function _backtrace_info( $backtrace_limit ) { * @since 1.6.6 * @access private */ - private function _clear_log() { - $logs = array( 'debug', 'debug.purge', 'crawler' ); - foreach ( $logs as $log ) { - File::save( self::$log_path_prefix . "/{$log}.log", '' ); + private function _clear_log() + { + $logs = array('debug', 'debug.purge', 'crawler'); + foreach ($logs as $log) { + File::save(self::$log_path_prefix . "/{$log}.log", ''); } } @@ -461,15 +478,16 @@ private function _clear_log() { * @since 1.6.6 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { - case self::TYPE_CLEAR_LOG : + switch ($type) { + case self::TYPE_CLEAR_LOG: $this->_clear_log(); break; - case self::TYPE_BETA_TEST : + case self::TYPE_BETA_TEST: $this->beta_test(); break; diff --git a/src/doc.cls.php b/src/doc.cls.php index 6bcc4d316..28d61ab38 100644 --- a/src/doc.cls.php +++ b/src/doc.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Doc { +class Doc +{ // protected static $_instance; + /** + * Show option is actually ON by GM + * + * @since 5.5 + * @access public + */ + public static function maybe_on_by_gm($id) + { + if (apply_filters('litespeed_conf', $id)) { + return; + } + if (!apply_filters('litespeed_conf', Base::O_GUEST)) { + return; + } + if (!apply_filters('litespeed_conf', Base::O_GUEST_OPTM)) { + return; + } + echo ''; + echo '⚠️ ' . + sprintf( + __('This setting is %1$s for certain qualifying requests due to %2$s!', 'litespeed-cache'), + '' . __('ON', 'litespeed-cache') . '', + Lang::title(Base::O_GUEST_OPTM) + ); + self::learn_more('https://docs.litespeedtech.com/lscache/lscwp/general/#guest-optimization'); + echo ''; + } + /** * Changes affect crawler list warning * * @since 4.3 * @access public */ - public static function crawler_affected() { + public static function crawler_affected() + { echo ''; - echo '⚠️ ' . __( 'This setting will regenerate crawler list and clear the disabled list!' , 'litespeed-cache' ); + echo '⚠️ ' . __('This setting will regenerate crawler list and clear the disabled list!', 'litespeed-cache'); echo ''; } @@ -32,32 +64,39 @@ public static function crawler_affected() { * @since 2.2.7 * @access public */ - public static function privacy_policy() { - return __( 'This site utilizes caching in order to facilitate a faster response time and better user experience. Caching potentially stores a duplicate copy of every web page that is on display on this site. All cache files are temporary, and are never accessed by any third party, except as necessary to obtain technical support from the cache plugin vendor. Cache files expire on a schedule set by the site administrator, but may easily be purged by the admin before their natural expiration, if necessary. We may use QUIC.cloud services to process & cache your data temporarily.', 'litespeed-cache' ) - . sprintf( __( 'Please see %s for more details.', 'litespeed-cache' ), 'https://quic.cloud/privacy-policy/' ); + public static function privacy_policy() + { + return __( + 'This site utilizes caching in order to facilitate a faster response time and better user experience. Caching potentially stores a duplicate copy of every web page that is on display on this site. All cache files are temporary, and are never accessed by any third party, except as necessary to obtain technical support from the cache plugin vendor. Cache files expire on a schedule set by the site administrator, but may easily be purged by the admin before their natural expiration, if necessary. We may use QUIC.cloud services to process & cache your data temporarily.', + 'litespeed-cache' + ) . + sprintf( + __('Please see %s for more details.', 'litespeed-cache'), + 'https://quic.cloud/privacy-policy/' + ); } - /** * Learn more link * * @since 2.4.2 * @access public */ - public static function learn_more( $url, $title = false, $self = false, $class = false, $return = false ) { - if ( ! $class ) { + public static function learn_more($url, $title = false, $self = false, $class = false, $return = false) + { + if (!$class) { $class = 'litespeed-learn-more'; } - if ( ! $title ) { - $title = __( 'Learn More', 'litespeed-cache' ); + if (!$title) { + $title = __('Learn More', 'litespeed-cache'); } $self = $self ? '' : "target='_blank'"; $txt = " $title"; - if ( $return ) { + if ($return) { return $txt; } @@ -70,9 +109,10 @@ public static function learn_more( $url, $title = false, $self = false, $class = * @since 3.0 * @access public */ - public static function one_per_line( $return = false ) { - $str = __( 'One per line.', 'litespeed-cache' ); - if ( $return ) { + public static function one_per_line($return = false) + { + $str = __('One per line.', 'litespeed-cache'); + if ($return) { return $str; } echo $str; @@ -84,12 +124,12 @@ public static function one_per_line( $return = false ) { * @since 3.4 * @access public */ - public static function full_or_partial_url( $string_only = false ) { - if ( $string_only ) { - echo __( 'Both full and partial strings can be used.', 'litespeed-cache' ); - } - else { - echo __( 'Both full URLs and partial strings can be used.', 'litespeed-cache' ); + public static function full_or_partial_url($string_only = false) + { + if ($string_only) { + echo __('Both full and partial strings can be used.', 'litespeed-cache'); + } else { + echo __('Both full URLs and partial strings can be used.', 'litespeed-cache'); } } @@ -99,10 +139,13 @@ public static function full_or_partial_url( $string_only = false ) { * @since 3.0 * @access public */ - public static function notice_htaccess() { + public static function notice_htaccess() + { echo ''; - echo '⚠️ ' . __( 'This setting will edit the .htaccess file.', 'litespeed-cache' ); - echo ' ' . __( 'Learn More', 'litespeed-cache' ) . ''; + echo '⚠️ ' . __('This setting will edit the .htaccess file.', 'litespeed-cache'); + echo ' ' . + __('Learn More', 'litespeed-cache') . + ''; echo ''; } @@ -112,12 +155,31 @@ public static function notice_htaccess() { * @since 3.0 * @access public */ - public static function notice_ips() { + public static function notice_ips() + { echo '
      '; - echo '⚠️ ' . sprintf( __( 'For online services to work correctly, you must allowlist all %s server IPs.', 'litespeed-cache' ), 'QUIC.cloud' ) . '
      '; - echo '     ' . __( 'Before generating key, please verify all IPs on this list are allowlisted', 'litespeed-cache' ) . ': '; - echo '' . __( 'Current Online Server IPs', 'litespeed-cache' ) . ''; + echo '⚠️ ' . sprintf(__('For online services to work correctly, you must allowlist all %s server IPs.', 'litespeed-cache'), 'QUIC.cloud') . '
      '; + echo '     ' . __('Before generating key, please verify all IPs on this list are allowlisted', 'litespeed-cache') . ': '; + echo '' . __('Current Online Server IPs', 'litespeed-cache') . ''; echo '
      '; } + /** + * Gentle reminder that web services run asynchronously + * + * @since 5.3.1 + * @access public + */ + public static function queue_issues($return = false) + { + $str = + '
      ' . + esc_html__('The queue is processed asynchronously. It may take time.', 'litespeed-cache') . + self::learn_more('https://docs.litespeedtech.com/lscache/lscwp/troubleshoot/#quiccloud-queue-issues', false, false, false, true) . + '
      '; + if ($return) { + return $str; + } + echo $str; + } } diff --git a/src/error.cls.php b/src/error.cls.php index 52b6729ce..df72b0f3a 100644 --- a/src/error.cls.php +++ b/src/error.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Error { +class Error +{ private static $CODE_SET = array( 'HTA_LOGIN_COOKIE_INVALID' => 4300, // .htaccess did not find. - 'HTA_DNF' => 4500, // .htaccess did not find. - 'HTA_BK' => 9010, // backup - 'HTA_R' => 9041, // read htaccess - 'HTA_W' => 9042, // write - 'HTA_GET' => 9030, // failed to get + 'HTA_DNF' => 4500, // .htaccess did not find. + 'HTA_BK' => 9010, // backup + 'HTA_R' => 9041, // read htaccess + 'HTA_W' => 9042, // write + 'HTA_GET' => 9030, // failed to get ); /** @@ -26,8 +29,9 @@ class Error { * * @since 3.0 */ - public static function t( $code, $args = null ) { - throw new \Exception( self::msg( $code, $args ) ); + public static function t($code, $args = null) + { + throw new \Exception(self::msg($code, $args)); } /** @@ -35,161 +39,180 @@ public static function t( $code, $args = null ) { * * @since 3.0 */ - public static function msg( $code, $args = null ) { - switch ( $code ) { - + public static function msg($code, $args = null) + { + switch ($code) { case 'disabled_all': - $msg = sprintf( __( 'The setting %s is currently enabled.', 'litespeed-cache' ), '' . Lang::title( Base::O_DEBUG_DISABLE_ALL ) . '' ) . - Doc::learn_more( admin_url( 'admin.php?page=litespeed-toolbox' ), __( 'Click here to change.', 'litespeed-cache' ), true, false, true ); + $msg = + sprintf(__('The setting %s is currently enabled.', 'litespeed-cache'), '' . Lang::title(Base::O_DEBUG_DISABLE_ALL) . '') . + Doc::learn_more( + is_network_admin() ? network_admin_url('admin.php?page=litespeed-toolbox') : admin_url('admin.php?page=litespeed-toolbox'), + __('Click here to change.', 'litespeed-cache'), + true, + false, + true + ); break; case 'lack_of_api_key': - $msg = sprintf( __( 'You will need to set %s to use the online services.', 'litespeed-cache' ), '' . Lang::title( Base::O_API_KEY ) . '' ) . - Doc::learn_more( admin_url( 'admin.php?page=litespeed-general' ), __( 'Click here to set.', 'litespeed-cache' ), true, false, true ); + $msg = + sprintf(__('You will need to set %s to use the online services.', 'litespeed-cache'), '' . Lang::title(Base::O_API_KEY) . '') . + Doc::learn_more(admin_url('admin.php?page=litespeed-general'), __('Click here to set.', 'litespeed-cache'), true, false, true); break; case 'out_of_daily_quota': - $msg = __( 'You don\'t have enough daily quota left for current service today.', 'litespeed-cache' ); + $msg = __('You don\'t have enough daily quota left for current service today.', 'litespeed-cache'); break; case 'out_of_quota': - $msg = __( 'You don\'t have enough quota left for current service this month.', 'litespeed-cache' ); + $msg = __('You don\'t have enough quota left for current service this month.', 'litespeed-cache'); break; case 'too_many_requested': - $msg = __( 'You have too many requested images, please try again in a few minutes.', 'litespeed-cache' ); + $msg = __('You have too many requested images, please try again in a few minutes.', 'litespeed-cache'); break; case 'too_many_notified': - $msg = __( 'You have too many notified images, please pull down notified images first.', 'litespeed-cache' ); + $msg = __('You have too many notified images, please pull down notified images first.', 'litespeed-cache'); break; case 'empty_list': - $msg = __( 'The image list is empty.', 'litespeed-cache' ); + $msg = __('The image list is empty.', 'litespeed-cache'); break; case 'lack_of_param': - $msg = __( 'Not enough parameters. Please check if the domain key is set correctly', 'litespeed-cache' ); + $msg = __('Not enough parameters. Please check if the domain key is set correctly', 'litespeed-cache'); break; case 'unfinished_queue': - $msg = __( 'There is proceeding queue not pulled yet.', 'litespeed-cache' ); + $msg = __('There is proceeding queue not pulled yet.', 'litespeed-cache'); break; - case strpos( $code, 'unfinished_queue ' ) === 0: - $msg = sprintf( __( 'There is proceeding queue not pulled yet. Queue info: %s.', 'litespeed-cache' ), '' . substr( $code, strlen( 'unfinished_queue ' ) ) . '' ); + case strpos($code, 'unfinished_queue ') === 0: + $msg = sprintf( + __('There is proceeding queue not pulled yet. Queue info: %s.', 'litespeed-cache'), + '' . substr($code, strlen('unfinished_queue ')) . '' + ); break; case 'err_alias': - $msg = __( 'The site is not a valid alias on QUIC.cloud.', 'litespeed-cache' ); + $msg = __('The site is not a valid alias on QUIC.cloud.', 'litespeed-cache'); break; case 'site_not_registered': - $msg = __( 'The site is not registered on QUIC.cloud.', 'litespeed-cache' ); + $msg = __('The site is not registered on QUIC.cloud.', 'litespeed-cache'); break; case 'err_key': - $msg = __( 'The domain key is not correct. Please try to sync your domain key again.', 'litespeed-cache' ); + $msg = __('The domain key is not correct. Please try to sync your domain key again.', 'litespeed-cache'); break; case 'heavy_load': - $msg = __( 'The current server is under heavy load.', 'litespeed-cache' ); + $msg = __('The current server is under heavy load.', 'litespeed-cache'); break; case 'redetect_node': - $msg = __( 'Online node needs to be redetected.', 'litespeed-cache' ); + $msg = __('Online node needs to be redetected.', 'litespeed-cache'); break; case 'err_overdraw': - $msg = __( 'Credits are not enough to proceed the current request.', 'litespeed-cache' ); + $msg = __('Credits are not enough to proceed the current request.', 'litespeed-cache'); break; case 'W': - $msg = __( '%s file not writable.', 'litespeed-cache' ); + $msg = __('%s file not writable.', 'litespeed-cache'); break; case 'HTA_DNF': - if ( ! is_array( $args ) ) { - $args = array( '' . $args . '' ); + if (!is_array($args)) { + $args = array('' . $args . ''); } $args[] = '.htaccess'; - $msg = __( 'Could not find %1$s in %2$s.', 'litespeed-cache' ); + $msg = __('Could not find %1$s in %2$s.', 'litespeed-cache'); break; case 'HTA_LOGIN_COOKIE_INVALID': - $msg = sprintf( __( 'Invalid login cookie. Please check the %s file.', 'litespeed-cache' ), '.htaccess' ); + $msg = sprintf(__('Invalid login cookie. Please check the %s file.', 'litespeed-cache'), '.htaccess'); break; case 'HTA_BK': - $msg = sprintf( __( 'Failed to back up %s file, aborted changes.', 'litespeed-cache' ), '.htaccess' ); + $msg = sprintf(__('Failed to back up %s file, aborted changes.', 'litespeed-cache'), '.htaccess'); break; case 'HTA_R': - $msg = sprintf( __( '%s file not readable.', 'litespeed-cache' ), '.htaccess' ); + $msg = sprintf(__('%s file not readable.', 'litespeed-cache'), '.htaccess'); break; case 'HTA_W': - $msg = sprintf( __( '%s file not writable.', 'litespeed-cache' ), '.htaccess' ); + $msg = sprintf(__('%s file not writable.', 'litespeed-cache'), '.htaccess'); break; case 'HTA_GET': - $msg = sprintf( __( 'Failed to get %s file contents.', 'litespeed-cache' ), '.htaccess' ); + $msg = sprintf(__('Failed to get %s file contents.', 'litespeed-cache'), '.htaccess'); break; case 'failed_tb_creation': - $msg = __( 'Failed to create table %s! SQL: %s.', 'litespeed-cache' ); + $msg = __('Failed to create table %s! SQL: %s.', 'litespeed-cache'); break; case 'crawler_disabled': - $msg = __( 'Crawler disabled by the server admin.', 'litespeed-cache' ); + $msg = __('Crawler disabled by the server admin.', 'litespeed-cache'); break; /*** QC error code ***/ case 'try_later': - $msg = __( 'Previous request too recent. Please try again later.', 'litespeed-cache' ); + $msg = __('Previous request too recent. Please try again later.', 'litespeed-cache'); break; - case strpos( $code, 'try_later ' ) === 0: - $msg = sprintf( __( 'Previous request too recent. Please try again after %s.', 'litespeed-cache' ), '' . Utility::readable_time( substr( $code, strlen( 'try_later ' ) ), 3600, true ) . '' ); + case strpos($code, 'try_later ') === 0: + $msg = sprintf( + __('Previous request too recent. Please try again after %s.', 'litespeed-cache'), + '' . Utility::readable_time(substr($code, strlen('try_later ')), 3600, true) . '' + ); break; case 'waiting_for_approval': - $msg = __( 'Your application is waiting for approval.', 'litespeed-cache' ); + $msg = __('Your application is waiting for approval.', 'litespeed-cache'); break; case 'callback_fail_hash': - $msg = __( 'The callback validation to your domain failed due to hash mismatch.', 'litespeed-cache' ); + $msg = __('The callback validation to your domain failed due to hash mismatch.', 'litespeed-cache'); break; case 'callback_fail': - $msg = __( 'The callback validation to your domain failed. Please make sure there is no firewall blocking our servers.', 'litespeed-cache' ); + $msg = __('The callback validation to your domain failed. Please make sure there is no firewall blocking our servers.', 'litespeed-cache'); break; - case substr( $code, 0, 14 ) === 'callback_fail ': - $msg = __( 'The callback validation to your domain failed. Please make sure there is no firewall blocking our servers. Response code: ', 'litespeed-cache' ) . substr( $code, 14 ); + case substr($code, 0, 14) === 'callback_fail ': + $msg = + __('The callback validation to your domain failed. Please make sure there is no firewall blocking our servers. Response code: ', 'litespeed-cache') . + substr($code, 14); break; case 'forbidden': - $msg = __( 'Your domain has been forbidden from using our services due to a previous policy violation.', 'litespeed-cache' ); + $msg = __('Your domain has been forbidden from using our services due to a previous policy violation.', 'litespeed-cache'); break; case 'err_dns_active': - $msg = __( 'You cannot remove this DNS zone, because it is still in use. Please update the domain\'s nameservers, then try to delete this zone again, otherwise your site will become inaccessible.', 'litespeed-cache' ); + $msg = __( + 'You cannot remove this DNS zone, because it is still in use. Please update the domain\'s nameservers, then try to delete this zone again, otherwise your site will become inaccessible.', + 'litespeed-cache' + ); break; default: - $msg = __( 'Unknown error', 'litespeed-cache' ) . ': ' . $code; + $msg = __('Unknown error', 'litespeed-cache') . ': ' . $code; break; } - if ( $args !== null ) { - $msg = is_array( $args ) ? vsprintf( $msg, $args ) : sprintf( $msg, $args ); + if ($args !== null) { + $msg = is_array($args) ? vsprintf($msg, $args) : sprintf($msg, $args); } - if ( isset( self::$CODE_SET[ $code ] ) ) { - $msg = 'ERROR ' . self::$CODE_SET[ $code ] . ': ' . $msg; + if (isset(self::$CODE_SET[$code])) { + $msg = 'ERROR ' . self::$CODE_SET[$code] . ': ' . $msg; } return $msg; } -} \ No newline at end of file +} diff --git a/src/esi.cls.php b/src/esi.cls.php index 42fbc7718..25e724acb 100644 --- a/src/esi.cls.php +++ b/src/esi.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); + +class ESI extends Root +{ + const LOG_TAG = '⏺'; -class ESI extends Root { private static $has_esi = false; private static $_combine_ids = array(); private $esi_args = null; private $_esi_preserve_list = array(); - private $_nonce_actions = array( -1 => '' ); // val is cache control + private $_nonce_actions = array(-1 => ''); // val is cache control const QS_ACTION = 'lsesi'; const QS_PARAMS = 'esi'; @@ -38,21 +43,22 @@ class ESI extends Root { * @since 1.2.0 * @since 4.0 Change to be after Vary init in hook 'after_setup_theme' */ - public function init() { + public function init() + { /** * Bypass ESI related funcs if disabled ESI to fix potential DIVI compatibility issue * @since 2.9.7.2 */ - if ( Router::is_ajax() || ! $this->cls( 'Router' )->esi_enabled() ) { + if (Router::is_ajax() || !$this->cls('Router')->esi_enabled()) { return; } // Guest mode, don't need to use ESI - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST ) { + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { return; } - if ( defined( 'LITESPEED_ESI_OFF' ) ) { + if (defined('LITESPEED_ESI_OFF')) { return; } @@ -65,7 +71,7 @@ public function init() { */ $this->_transform_nonce(); - ! defined( 'LITESPEED_ESI_INITED' ) && define( 'LITESPEED_ESI_INITED', true ); + !defined('LITESPEED_ESI_INITED') && define('LITESPEED_ESI_INITED', true); } /** @@ -77,17 +83,19 @@ public function init() { * @since 4.0 Changed to private from public * @access private */ - private function _hooks() { - add_filter( 'template_include', array( $this, 'esi_template' ), 99999 ); + private function _hooks() + { + add_filter('template_include', array($this, 'esi_template'), 99999); - add_action( 'load-widgets.php', __NAMESPACE__ . '\Purge::purge_widget' ); - add_action( 'wp_update_comment_count', __NAMESPACE__ . '\Purge::purge_comment_widget' ); + add_action('load-widgets.php', __NAMESPACE__ . '\Purge::purge_widget'); + add_action('wp_update_comment_count', __NAMESPACE__ . '\Purge::purge_comment_widget'); /** * Recover REQUEST_URI * @since 1.8.1 */ - if ( ! empty( $_GET[ self::QS_ACTION ] ) ) { + if (!empty($_GET[self::QS_ACTION])) { + self::debug('ESI req'); $this->_register_esi_actions(); } @@ -105,10 +113,9 @@ private function _hooks() { * @since 2.8 * @since 2.8.1 Check is_admin for Elementor compatibility #726013 */ - if ( ! is_admin() ) { - add_shortcode( 'esi', array( $this, 'shortcode' ) ); + if (!is_admin()) { + add_shortcode('esi', array($this, 'shortcode')); } - } /** @@ -116,21 +123,22 @@ private function _hooks() { * * @since 2.9.5 */ - private function _transform_nonce() { - if ( is_admin() ) { + private function _transform_nonce() + { + if (is_admin()) { return; } // Load ESI nonces in conf - $nonces = $this->conf( Base::O_ESI_NONCE ); - add_filter( 'litespeed_esi_nonces', array( $this->cls( 'Data' ), 'load_esi_nonces' ) ); - if ( $nonces = apply_filters( 'litespeed_esi_nonces', $nonces ) ) { - foreach ( $nonces as $action ) { - $this->nonce_action( $action ); + $nonces = $this->conf(Base::O_ESI_NONCE); + add_filter('litespeed_esi_nonces', array($this->cls('Data'), 'load_esi_nonces')); + if ($nonces = apply_filters('litespeed_esi_nonces', $nonces)) { + foreach ($nonces as $action) { + $this->nonce_action($action); } } - add_action( 'litespeed_nonce', array( $this, 'nonce_action' ) ); + add_action('litespeed_nonce', array($this, 'nonce_action')); } /** @@ -138,22 +146,23 @@ private function _transform_nonce() { * * @since 2.9.5 */ - public function nonce_action( $action ) { + public function nonce_action($action) + { // Split the Cache Control - $action = explode( ' ', $action ); - $control = ! empty( $action[ 1 ] ) ? $action[ 1 ] : ''; - $action = $action[ 0 ]; + $action = explode(' ', $action); + $control = !empty($action[1]) ? $action[1] : ''; + $action = $action[0]; // Wildcard supported - $action = Utility::wildcard2regex( $action ); + $action = Utility::wildcard2regex($action); - if ( array_key_exists( $action, $this->_nonce_actions ) ) { + if (array_key_exists($action, $this->_nonce_actions)) { return; } - $this->_nonce_actions[ $action ] = $control; + $this->_nonce_actions[$action] = $control; - Debug2::debug( '[ESI] Appended nonce action to nonce list [action] ' . $action ); + Debug2::debug('[ESI] Appended nonce action to nonce list [action] ' . $action); } /** @@ -161,28 +170,28 @@ public function nonce_action( $action ) { * * @since 2.9.5 */ - public function is_nonce_action( $action ) { + public function is_nonce_action($action) + { // If GM not run yet, then ESI not init yet, then ESI nonce will not be allowed even nonce func replaced. - if ( ! defined( 'LITESPEED_ESI_INITED' ) ) { + if (!defined('LITESPEED_ESI_INITED')) { return null; } - if ( is_admin() ) { + if (is_admin()) { return null; } - if ( defined( 'LITESPEED_ESI_OFF' ) ) { + if (defined('LITESPEED_ESI_OFF')) { return null; } - foreach ( $this->_nonce_actions as $k => $v ) { - if ( strpos( $k, '*' ) !== false ) { - if( preg_match( '#' . $k . '#iU', $action ) ) { + foreach ($this->_nonce_actions as $k => $v) { + if (strpos($k, '*') !== false) { + if (preg_match('#' . $k . '#iU', $action)) { return $v; } - } - else { - if ( $k == $action ) { + } else { + if ($k == $action) { return $v; } } @@ -197,27 +206,28 @@ public function is_nonce_action( $action ) { * @since 2.8 * @access public */ - public function shortcode( $atts ) { - if ( empty( $atts[ 0 ] ) ) { - Debug2::debug( '[ESI] ===shortcode wrong format', $atts ); + public function shortcode($atts) + { + if (empty($atts[0])) { + Debug2::debug('[ESI] ===shortcode wrong format', $atts); return 'Wrong shortcode esi format'; } $cache = 'public,no-vary'; - if ( ! empty( $atts[ 'cache' ] ) ) { - $cache = $atts[ 'cache' ]; - unset( $atts[ 'cache' ] ); + if (!empty($atts['cache'])) { + $cache = $atts['cache']; + unset($atts['cache']); } $silence = false; - if ( ! empty( $atts[ '_ls_silence' ] ) ) { + if (!empty($atts['_ls_silence'])) { $silence = true; } - do_action( 'litespeed_esi_shortcode-' . $atts[ 0 ] ); + do_action('litespeed_esi_shortcode-' . $atts[0]); // Show ESI link - return $this->sub_esi_block( 'esi', 'esi-shortcode', $atts, $cache, $silence ); + return $this->sub_esi_block('esi', 'esi-shortcode', $atts, $cache, $silence); } /** @@ -228,7 +238,8 @@ public function shortcode( $atts ) { * @access public * @return string Esi On header if request has esi, empty string otherwise. */ - public static function has_esi() { + public static function has_esi() + { return self::$has_esi; } @@ -238,7 +249,8 @@ public static function has_esi() { * @since 1.1.3 * @access public */ - public static function set_has_esi() { + public static function set_has_esi() + { self::$has_esi = true; } @@ -249,21 +261,39 @@ public static function set_has_esi() { * @since 1.1.3 * @access private */ - private function _register_esi_actions() { - ! defined( 'LSCACHE_IS_ESI' ) && define( 'LSCACHE_IS_ESI', $_GET[ self::QS_ACTION ] );// Reused this to ESI block ID + private function _register_esi_actions() + { + /** + * This hook is in `init` + * For any plugin need to check if page is ESI, use `LSCACHE_IS_ESI` check after `init` hook + */ + !defined('LSCACHE_IS_ESI') && define('LSCACHE_IS_ESI', $_GET[self::QS_ACTION]); // Reused this to ESI block ID - ! empty( $_SERVER[ 'ESI_REFERER' ] ) && defined( 'LSCWP_LOG' ) && Debug2::debug( '[ESI] ESI_REFERER: ' . $_SERVER[ 'ESI_REFERER' ] ); + !empty($_SERVER['ESI_REFERER']) && defined('LSCWP_LOG') && Debug2::debug('[ESI] ESI_REFERER: ' . $_SERVER['ESI_REFERER']); /** * Only when ESI's parent is not REST, replace REQUEST_URI to avoid breaking WP5 editor REST call * @since 2.9.3 */ - if ( ! empty( $_SERVER[ 'ESI_REFERER' ] ) && ! $this->cls( 'REST' )->is_rest( $_SERVER[ 'ESI_REFERER' ] ) ) { - $_SERVER[ 'REQUEST_URI' ] = $_SERVER[ 'ESI_REFERER' ]; + if (!empty($_SERVER['ESI_REFERER']) && !$this->cls('REST')->is_rest($_SERVER['ESI_REFERER'])) { + self::debug('overwrite REQUEST_URI to ESI_REFERER [from] ' . $_SERVER['REQUEST_URI'] . ' [to] ' . $_SERVER['ESI_REFERER']); + if (!empty($_SERVER['ESI_REFERER'])) { + $_SERVER['REQUEST_URI'] = + substr(get_option('permalink_structure'), -1) === '/' && strpos($_SERVER['ESI_REFERER'], '?') === false + ? trailingslashit($_SERVER['ESI_REFERER']) + : $_SERVER['ESI_REFERER']; + } + # Prevent from 301 redirecting + if (!empty($_SERVER['SCRIPT_URI'])) { + $SCRIPT_URI = parse_url($_SERVER['SCRIPT_URI']); + $SCRIPT_URI['path'] = $_SERVER['REQUEST_URI']; + Utility::compatibility(); + $_SERVER['SCRIPT_URI'] = http_build_url($SCRIPT_URI); + } } - if ( ! empty( $_SERVER[ 'ESI_CONTENT_TYPE' ] ) && strpos( $_SERVER[ 'ESI_CONTENT_TYPE' ], 'application/json' ) === 0 ) { - add_filter( 'litespeed_is_json', '__return_true' ); + if (!empty($_SERVER['ESI_CONTENT_TYPE']) && strpos($_SERVER['ESI_CONTENT_TYPE'], 'application/json') === 0) { + add_filter('litespeed_is_json', '__return_true'); } /** @@ -271,17 +301,17 @@ private function _register_esi_actions() { * NOTE: Not effective due to ESI req are all to `/` yet * @since 2.9.4 */ - add_action( 'rest_api_init', array( $this, 'load_esi_block' ), 101 ); + add_action('rest_api_init', array($this, 'load_esi_block'), 101); // Register ESI blocks add_action('litespeed_esi_load-widget', array($this, 'load_widget_block')); add_action('litespeed_esi_load-admin-bar', array($this, 'load_admin_bar_block')); add_action('litespeed_esi_load-comment-form', array($this, 'load_comment_form_block')); - add_action('litespeed_esi_load-nonce', array( $this, 'load_nonce_block' ) ); - add_action('litespeed_esi_load-esi', array( $this, 'load_esi_shortcode' ) ); + add_action('litespeed_esi_load-nonce', array($this, 'load_nonce_block')); + add_action('litespeed_esi_load-esi', array($this, 'load_esi_shortcode')); - add_action('litespeed_esi_load-' . self::COMBO, array( $this, 'load_combo' ) ); + add_action('litespeed_esi_load-' . self::COMBO, array($this, 'load_combo')); } /** @@ -293,13 +323,15 @@ private function _register_esi_actions() { * @param string $template The template path filtered. * @return string The new template path. */ - public function esi_template( $template ) { + public function esi_template($template) + { // Check if is an ESI request - if ( defined( 'LSCACHE_IS_ESI' ) ) { - Debug2::debug( '[ESI] calling template' ); + if (defined('LSCACHE_IS_ESI')) { + self::debug('calling ESI template'); return LSCWP_DIR . 'tpl/esi.tpl.php'; } + self::debug('calling default template'); $this->_register_not_esi_actions(); return $template; } @@ -311,30 +343,30 @@ public function esi_template( $template ) { * @since 1.1.3 * @access private */ - private function _register_not_esi_actions() { - do_action( 'litespeed_tpl_normal' ); + private function _register_not_esi_actions() + { + do_action('litespeed_tpl_normal'); - if ( ! Control::is_cacheable() ) { + if (!Control::is_cacheable()) { return; } - if ( Router::is_ajax() ) { + if (Router::is_ajax()) { return; } - add_filter('widget_display_callback', array( $this, 'sub_widget_block' ), 0, 3); + add_filter('widget_display_callback', array($this, 'sub_widget_block'), 0, 3); // Add admin_bar esi - if ( Router::is_logged_in() ) { + if (Router::is_logged_in()) { remove_action('wp_footer', 'wp_admin_bar_render', 1000); add_action('wp_footer', array($this, 'sub_admin_bar_block'), 1000); } // Add comment forum esi for logged-in user or commenter - if ( ! Router::is_ajax() && Vary::has_vary() ) { - add_filter( 'comment_form_defaults', array( $this, 'register_comment_form_actions' ) ); + if (!Router::is_ajax() && Vary::has_vary()) { + add_filter('comment_form_defaults', array($this, 'register_comment_form_actions')); } - } /** @@ -342,12 +374,13 @@ private function _register_not_esi_actions() { * * @since 3.4.2 */ - public static function combine( $block_id ) { - if ( ! isset( $_SERVER[ 'X-LSCACHE' ] ) || strpos( $_SERVER[ 'X-LSCACHE' ], 'combine' ) === false ) { + public static function combine($block_id) + { + if (!isset($_SERVER['X-LSCACHE']) || strpos($_SERVER['X-LSCACHE'], 'combine') === false) { return; } - if ( in_array( $block_id, self::$_combine_ids ) ) { + if (in_array($block_id, self::$_combine_ids)) { return; } @@ -359,29 +392,30 @@ public static function combine( $block_id ) { * * @since 3.4.2 */ - public function load_combo() { - Control::set_nocache( 'ESI combine request' ); + public function load_combo() + { + Control::set_nocache('ESI combine request'); - if ( empty( $_POST[ 'esi_include' ] ) ) { + if (empty($_POST['esi_include'])) { return; } self::set_has_esi(); - Debug2::debug( '[ESI] 🍔 Load combo', $_POST[ 'esi_include' ] ); + Debug2::debug('[ESI] 🍔 Load combo', $_POST['esi_include']); $output = ''; - foreach ( $_POST[ 'esi_include' ] as $url ) { - $qs = parse_url( htmlspecialchars_decode( $url ), PHP_URL_QUERY ); - parse_str( $qs, $qs ); - if ( empty( $qs[ self::QS_ACTION ] ) ) { + foreach ($_POST['esi_include'] as $url) { + $qs = parse_url(htmlspecialchars_decode($url), PHP_URL_QUERY); + parse_str($qs, $qs); + if (empty($qs[self::QS_ACTION])) { continue; } - $esi_id = $qs[ self::QS_ACTION ]; - $esi_param = ! empty( $qs[ self::QS_PARAMS ] ) ? $this->_parse_esi_param( $qs[ self::QS_PARAMS ] ) : false; - $inline_param = apply_filters( 'litespeed_esi_inline-' . $esi_id, array(), $esi_param ); // Returned array need to be [ val, control, tag ] - if ( $inline_param ) { - $output .= self::_build_inline( $url, $inline_param ); + $esi_id = $qs[self::QS_ACTION]; + $esi_param = !empty($qs[self::QS_PARAMS]) ? $this->_parse_esi_param($qs[self::QS_PARAMS]) : false; + $inline_param = apply_filters('litespeed_esi_inline-' . $esi_id, array(), $esi_param); // Returned array need to be [ val, control, tag ] + if ($inline_param) { + $output .= self::_build_inline($url, $inline_param); } } @@ -393,12 +427,17 @@ public function load_combo() { * * @since 3.4.2 */ - private static function _build_inline( $url, $inline_param ) { - if ( ! $url || empty( $inline_param[ 'val' ] ) || empty( $inline_param[ 'control' ] ) || empty( $inline_param[ 'tag' ] ) ) { + private static function _build_inline($url, $inline_param) + { + if (!$url || empty($inline_param['val']) || empty($inline_param['control']) || empty($inline_param['tag'])) { return ''; } - return "" . $inline_param[ 'val' ] . ""; + $url = esc_attr($url); + $control = esc_attr($inline_param['control']); + $tag = esc_attr($inline_param['tag']); + + return "" . $inline_param['val'] . ''; } /** @@ -417,94 +456,104 @@ private static function _build_inline( $url, $inline_param ) { * @param bool $svar If store the value in memory or not, in memory wil be faster * @param array $inline_val If show the current value for current request( this can avoid multiple esi requests in first time cache generating process ) */ - public function sub_esi_block( $block_id, $wrapper, $params = array(), $control = 'private,no-vary', $silence = false, $preserved = false, $svar = false, $inline_param = array() ) { - if ( empty($block_id) || ! is_array($params) || preg_match('/[^\w-]/', $block_id) ) { + public function sub_esi_block( + $block_id, + $wrapper, + $params = array(), + $control = 'private,no-vary', + $silence = false, + $preserved = false, + $svar = false, + $inline_param = array() + ) { + if (empty($block_id) || !is_array($params) || preg_match('/[^\w-]/', $block_id)) { return false; } - if ( defined( 'LITESPEED_ESI_OFF' ) ) { - Debug2::debug( '[ESI] ESI OFF so force loading [block_id] ' . $block_id ); - do_action( 'litespeed_esi_load-' . $block_id, $params ); + if (defined('LITESPEED_ESI_OFF')) { + Debug2::debug('[ESI] ESI OFF so force loading [block_id] ' . $block_id); + do_action('litespeed_esi_load-' . $block_id, $params); return; } - if ( $silence ) { + if ($silence) { // Don't add comment to esi block ( original for nonce used in tag property data-nonce='esi_block' ) - $params[ '_ls_silence' ] = true; + $params['_ls_silence'] = true; } - if ( $this->cls( 'REST' )->is_rest() || $this->cls( 'REST' )->is_internal_rest() ) { - $params[ 'is_json' ] = 1; + if ($this->cls('REST')->is_rest() || $this->cls('REST')->is_internal_rest()) { + $params['is_json'] = 1; } - $params = apply_filters( 'litespeed_esi_params', $params, $block_id ); - $control = apply_filters('litespeed_esi_control', $control, $block_id ); + $params = apply_filters('litespeed_esi_params', $params, $block_id); + $control = apply_filters('litespeed_esi_control', $control, $block_id); - if ( !is_array($params) || !is_string($control) ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( "[ESI] 🛑 Sub hooks returned Params: \n" . var_export($params, true) . "\ncache control: \n" . var_export($control, true) ); + if (!is_array($params) || !is_string($control)) { + defined('LSCWP_LOG') && Debug2::debug("[ESI] 🛑 Sub hooks returned Params: \n" . var_export($params, true) . "\ncache control: \n" . var_export($control, true)); return false; } // Build params for URL $appended_params = array( - self::QS_ACTION => $block_id, + self::QS_ACTION => $block_id, ); - if ( ! empty( $control ) ) { - $appended_params[ '_control' ] = $control; + if (!empty($control)) { + $appended_params['_control'] = $control; } - if ( $params ) { - $appended_params[ self::QS_PARAMS ] = base64_encode( json_encode( $params ) ); - Debug2::debug2( '[ESI] param ', $params ); + if ($params) { + $appended_params[self::QS_PARAMS] = base64_encode(json_encode($params)); + Debug2::debug2('[ESI] param ', $params); } // Append hash - $appended_params[ '_hash' ] = $this->_gen_esi_md5( $appended_params ); + $appended_params['_hash'] = $this->_gen_esi_md5($appended_params); /** * Escape potential chars * @since 2.9.4 */ - $appended_params = array_map( 'urlencode', $appended_params ); + $appended_params = array_map('urlencode', $appended_params); // Generate ESI URL - $url = add_query_arg( $appended_params, trailingslashit( wp_make_link_relative( home_url() ) ) ); + $url = add_query_arg($appended_params, trailingslashit(wp_make_link_relative(home_url()))); $output = ''; - if ( $inline_param ) { - $output .= self::_build_inline( $url, $inline_param ); + if ($inline_param) { + $output .= self::_build_inline($url, $inline_param); } $output .= "_esi_preserve_list[ $hash ] = $output; - Debug2::debug( "[ESI] Preserved to $hash" ); + if ($preserved) { + $hash = md5($output); + $this->_esi_preserve_list[$hash] = $output; + self::debug("Preserved to $hash"); return $hash; } @@ -518,22 +567,19 @@ public function sub_esi_block( $block_id, $wrapper, $params = array(), $control * @since 2.9.6 * @access private */ - private function _gen_esi_md5( $params ) { - $keys = array( - self::QS_ACTION, - '_control', - self::QS_PARAMS, - ); + private function _gen_esi_md5($params) + { + $keys = array(self::QS_ACTION, '_control', self::QS_PARAMS); $str = ''; - foreach ( $keys as $v ) { - if ( isset( $params[ $v ] ) && is_string( $params[ $v ] ) ) { - $str .= $params[ $v ]; + foreach ($keys as $v) { + if (isset($params[$v]) && is_string($params[$v])) { + $str .= $params[$v]; } } - Debug2::debug2( '[ESI] md5_string=' . $str ); + Debug2::debug2('[ESI] md5_string=' . $str); - return md5( $this->conf( Base::HASH ) . $str ); + return md5($this->conf(Base::HASH) . $str); } /** @@ -542,27 +588,27 @@ private function _gen_esi_md5( $params ) { * @since 1.1.3 * @access private */ - private function _parse_esi_param( $qs_params = false ) { + private function _parse_esi_param($qs_params = false) + { $req_params = false; - if ( $qs_params ) { + if ($qs_params) { $req_params = $qs_params; - } - elseif ( isset( $_REQUEST[ self::QS_PARAMS ] ) ) { - $req_params = $_REQUEST[ self::QS_PARAMS ]; + } elseif (isset($_REQUEST[self::QS_PARAMS])) { + $req_params = $_REQUEST[self::QS_PARAMS]; } - if ( ! $req_params ) { + if (!$req_params) { return false; } - $unencrypted = base64_decode( $req_params ); - if ( $unencrypted === false ) { + $unencrypted = base64_decode($req_params); + if ($unencrypted === false) { return false; } - Debug2::debug2( '[ESI] parms', $unencrypted ); + Debug2::debug2('[ESI] parms', $unencrypted); // $unencoded = urldecode($unencrypted); no need to do this as $_GET is already parsed - $params = json_decode( $unencrypted, true ); + $params = json_decode($unencrypted, true); return $params; } @@ -573,41 +619,42 @@ private function _parse_esi_param( $qs_params = false ) { * @since 1.1.3 * @access public */ - public function load_esi_block() { + public function load_esi_block() + { /** * Validate if is a legal ESI req * @since 2.9.6 */ - if ( empty( $_GET[ '_hash' ] ) || $this->_gen_esi_md5( $_GET ) != $_GET[ '_hash' ] ) { - Debug2::debug( '[ESI] ❌ Failed to validate _hash' ); + if (empty($_GET['_hash']) || $this->_gen_esi_md5($_GET) != $_GET['_hash']) { + Debug2::debug('[ESI] ❌ Failed to validate _hash'); return; } $params = $this->_parse_esi_param(); - if ( defined( 'LSCWP_LOG' ) ) { + if (defined('LSCWP_LOG')) { $logInfo = '[ESI] ⭕ '; - if( ! empty( $params[ self::PARAM_NAME ] ) ) { - $logInfo .= ' Name: ' . $params[ self::PARAM_NAME ] . ' ----- '; + if (!empty($params[self::PARAM_NAME])) { + $logInfo .= ' Name: ' . $params[self::PARAM_NAME] . ' ----- '; } $logInfo .= ' [ID] ' . LSCACHE_IS_ESI; - Debug2::debug( $logInfo ); + Debug2::debug($logInfo); } - if ( ! empty( $params[ '_ls_silence' ] ) ) { - ! defined( 'LSCACHE_ESI_SILENCE' ) && define( 'LSCACHE_ESI_SILENCE', true ); + if (!empty($params['_ls_silence'])) { + !defined('LSCACHE_ESI_SILENCE') && define('LSCACHE_ESI_SILENCE', true); } /** * Buffer needs to be JSON format * @since 2.9.4 */ - if ( ! empty( $params[ 'is_json' ] ) ) { - add_filter( 'litespeed_is_json', '__return_true' ); + if (!empty($params['is_json'])) { + add_filter('litespeed_is_json', '__return_true'); } - Tag::add( rtrim( Tag::TYPE_ESI, '.' ) ); - Tag::add( Tag::TYPE_ESI . LSCACHE_IS_ESI ); + Tag::add(rtrim(Tag::TYPE_ESI, '.')); + Tag::add(Tag::TYPE_ESI . LSCACHE_IS_ESI); // Debug2::debug(var_export($params, true )); @@ -616,13 +663,13 @@ public function load_esi_block() { * * @since 2.2.3 */ - if ( ! empty( $_GET[ '_control' ] ) ) { - $control = explode( ',', $_GET[ '_control' ] ); - if ( in_array( 'private', $control ) ) { + if (!empty($_GET['_control'])) { + $control = explode(',', $_GET['_control']); + if (in_array('private', $control)) { Control::set_private(); } - if ( in_array( 'no-vary', $control ) ) { + if (in_array('no-vary', $control)) { Control::set_no_vary(); } } @@ -630,8 +677,8 @@ public function load_esi_block() { do_action('litespeed_esi_load-' . LSCACHE_IS_ESI, $params); } -// The *_sub_* functions are helpers for the sub_* functions. -// The *_load_* functions are helpers for the load_* functions. + // The *_sub_* functions are helpers for the sub_* functions. + // The *_load_* functions are helpers for the load_* functions. /** * Loads the default options for default WordPress widgets. @@ -639,19 +686,20 @@ public function load_esi_block() { * @since 1.1.3 * @access public */ - public static function widget_default_options($options, $widget) { - if ( ! is_array($options) ) { + public static function widget_default_options($options, $widget) + { + if (!is_array($options)) { return $options; } $widget_name = get_class($widget); switch ($widget_name) { - case 'WP_Widget_Recent_Posts' : - case 'WP_Widget_Recent_Comments' : + case 'WP_Widget_Recent_Posts': + case 'WP_Widget_Recent_Comments': $options[self::WIDGET_O_ESIENABLE] = Base::VAL_OFF; $options[self::WIDGET_O_TTL] = 86400; break; - default : + default: break; } return $options; @@ -669,33 +717,34 @@ public static function widget_default_options($options, $widget) { * @param array $args Parameter used to build the widget. * @return mixed Return false if display through esi, instance otherwise. */ - public function sub_widget_block( $instance, $widget, $args ) { + public function sub_widget_block($instance, $widget, $args) + { // #210407 - if ( ! is_array( $instance ) ) { + if (!is_array($instance)) { return $instance; } - $name = get_class( $widget ); - if ( ! isset( $instance[ Base::OPTION_NAME ] ) ) { + $name = get_class($widget); + if (!isset($instance[Base::OPTION_NAME])) { return $instance; } - $options = $instance[ Base::OPTION_NAME ]; - if ( ! isset( $options ) || ! $options[ self::WIDGET_O_ESIENABLE ] ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( 'ESI 0 ' . $name . ': '. ( ! isset( $options ) ? 'not set' : 'set off' ) ); + $options = $instance[Base::OPTION_NAME]; + if (!isset($options) || !$options[self::WIDGET_O_ESIENABLE]) { + defined('LSCWP_LOG') && Debug2::debug('ESI 0 ' . $name . ': ' . (!isset($options) ? 'not set' : 'set off')); return $instance; } - $esi_private = $options[ self::WIDGET_O_ESIENABLE ] == Base::VAL_ON2 ? 'private,' : ''; + $esi_private = $options[self::WIDGET_O_ESIENABLE] == Base::VAL_ON2 ? 'private,' : ''; $params = array( self::PARAM_NAME => $name, self::PARAM_ID => $widget->id, self::PARAM_INSTANCE => $instance, - self::PARAM_ARGS => $args + self::PARAM_ARGS => $args, ); - echo $this->sub_esi_block( 'widget', 'widget ' . $name, $params, $esi_private . 'no-vary' ); + echo $this->sub_esi_block('widget', 'widget ' . $name, $params, $esi_private . 'no-vary'); return false; } @@ -708,19 +757,20 @@ public function sub_widget_block( $instance, $widget, $args ) { * @since 1.1.3 * @global type $wp_admin_bar */ - public function sub_admin_bar_block() { + public function sub_admin_bar_block() + { global $wp_admin_bar; - if ( ! is_admin_bar_showing() || ! is_object($wp_admin_bar) ) { + if (!is_admin_bar_showing() || !is_object($wp_admin_bar)) { return; } // To make each admin bar ESI request different for `Edit` button different link $params = array( - 'ref' => $_SERVER[ 'REQUEST_URI' ], + 'ref' => $_SERVER['REQUEST_URI'], ); - echo $this->sub_esi_block( 'admin-bar', 'adminbar', $params ); + echo $this->sub_esi_block('admin-bar', 'adminbar', $params); } /** @@ -731,28 +781,28 @@ public function sub_admin_bar_block() { * @global $wp_widget_factory * @param array $params Input parameters needed to correctly display widget */ - public function load_widget_block( $params ) { + public function load_widget_block($params) + { // global $wp_widget_factory; // $widget = $wp_widget_factory->widgets[ $params[ self::PARAM_NAME ] ]; - $option = $params[ self::PARAM_INSTANCE ]; - $option = $option[ Base::OPTION_NAME ]; + $option = $params[self::PARAM_INSTANCE]; + $option = $option[Base::OPTION_NAME]; // Since we only reach here via esi, safe to assume setting exists. - $ttl = $option[ self::WIDGET_O_TTL ]; - defined( 'LSCWP_LOG' ) && Debug2::debug( 'ESI widget render: name ' . $params[ self::PARAM_NAME ] . ', id ' . $params[ self::PARAM_ID ] . ', ttl ' . $ttl ); - if ( $ttl == 0 ) { - Control::set_nocache( 'ESI Widget time to live set to 0' ); - } - else { - Control::set_custom_ttl( $ttl ); - - if ( $option[ self::WIDGET_O_ESIENABLE ] == Base::VAL_ON2 ) { + $ttl = $option[self::WIDGET_O_TTL]; + defined('LSCWP_LOG') && Debug2::debug('ESI widget render: name ' . $params[self::PARAM_NAME] . ', id ' . $params[self::PARAM_ID] . ', ttl ' . $ttl); + if ($ttl == 0) { + Control::set_nocache('ESI Widget time to live set to 0'); + } else { + Control::set_custom_ttl($ttl); + + if ($option[self::WIDGET_O_ESIENABLE] == Base::VAL_ON2) { Control::set_private(); } Control::set_no_vary(); - Tag::add( Tag::TYPE_WIDGET . $params[ self::PARAM_ID ] ); + Tag::add(Tag::TYPE_WIDGET . $params[self::PARAM_ID]); } - the_widget( $params[ self::PARAM_NAME ], $params[ self::PARAM_INSTANCE ], $params[ self::PARAM_ARGS ] ); + the_widget($params[self::PARAM_NAME], $params[self::PARAM_INSTANCE], $params[self::PARAM_ARGS]); } /** @@ -761,34 +811,34 @@ public function load_widget_block( $params ) { * @access public * @since 1.1.3 */ - public function load_admin_bar_block( $params ) { - - if ( ! empty( $params[ 'ref' ] ) ) { - $ref_qs = parse_url( $params[ 'ref' ], PHP_URL_QUERY ); - if ( ! empty( $ref_qs ) ) { - parse_str( $ref_qs, $ref_qs_arr ); - - if ( ! empty( $ref_qs_arr ) ) { - foreach ( $ref_qs_arr as $k => $v ) { - $_GET[ $k ] = $v; + public function load_admin_bar_block($params) + { + if (!empty($params['ref'])) { + $ref_qs = parse_url($params['ref'], PHP_URL_QUERY); + if (!empty($ref_qs)) { + parse_str($ref_qs, $ref_qs_arr); + + if (!empty($ref_qs_arr)) { + foreach ($ref_qs_arr as $k => $v) { + $_GET[$k] = $v; } } } } + // Needed when permalink structure is "Plain" + wp(); wp_admin_bar_render(); - if ( ! $this->conf( Base::O_ESI_CACHE_ADMBAR ) ) { - Control::set_nocache( 'build-in set to not cacheable' ); - } - else { + if (!$this->conf(Base::O_ESI_CACHE_ADMBAR)) { + Control::set_nocache('build-in set to not cacheable'); + } else { Control::set_private(); Control::set_no_vary(); } - defined( 'LSCWP_LOG' ) && Debug2::debug( 'ESI: adminbar ref: ' . $_SERVER[ 'REQUEST_URI' ] ); + defined('LSCWP_LOG') && Debug2::debug('ESI: adminbar ref: ' . $_SERVER['REQUEST_URI']); } - /** * Parses the esi input parameters and generates the comment form for esi display. * @@ -796,15 +846,15 @@ public function load_admin_bar_block( $params ) { * @since 1.1.3 * @param array $params Input parameters needed to correctly display comment form */ - public function load_comment_form_block( $params ) { - comment_form( $params[ self::PARAM_ARGS ], $params[ self::PARAM_ID ] ); + public function load_comment_form_block($params) + { + comment_form($params[self::PARAM_ARGS], $params[self::PARAM_ID]); - if ( ! $this->conf( Base::O_ESI_CACHE_COMMFORM ) ) { - Control::set_nocache( 'build-in set to not cacheable' ); - } - else { + if (!$this->conf(Base::O_ESI_CACHE_COMMFORM)) { + Control::set_nocache('build-in set to not cacheable'); + } else { // by default comment form is public - if ( Vary::has_vary() ) { + if (Vary::has_vary()) { Control::set_private(); Control::set_no_vary(); } @@ -817,23 +867,23 @@ public function load_comment_form_block( $params ) { * @access public * @since 2.6 */ - public function load_nonce_block( $params ) { - $action = $params[ 'action' ]; + public function load_nonce_block($params) + { + $action = $params['action']; - Debug2::debug( '[ESI] load_nonce_block [action] ' . $action ); + Debug2::debug('[ESI] load_nonce_block [action] ' . $action); // set nonce TTL to half day - Control::set_custom_ttl( 43200 ); + Control::set_custom_ttl(43200); - if ( Router::is_logged_in() ) { + if (Router::is_logged_in()) { Control::set_private(); } - if ( function_exists( 'wp_create_nonce_litespeed_esi' ) ) { - echo wp_create_nonce_litespeed_esi( $action ); - } - else { - echo wp_create_nonce( $action ); + if (function_exists('wp_create_nonce_litespeed_esi')) { + echo wp_create_nonce_litespeed_esi($action); + } else { + echo wp_create_nonce($action); } } @@ -843,32 +893,32 @@ public function load_nonce_block( $params ) { * @access public * @since 2.8 */ - public function load_esi_shortcode( $params ) { - if ( isset( $params[ 'ttl' ] ) ) { - if ( ! $params[ 'ttl' ] ) { - Control::set_nocache( 'ESI shortcode att ttl=0' ); - } - else { - Control::set_custom_ttl( $params[ 'ttl' ] ); + public function load_esi_shortcode($params) + { + if (isset($params['ttl'])) { + if (!$params['ttl']) { + Control::set_nocache('ESI shortcode att ttl=0'); + } else { + Control::set_custom_ttl($params['ttl']); } - unset( $params[ 'ttl' ] ); + unset($params['ttl']); } // Replace to original shortcode - $shortcode = $params[ 0 ]; + $shortcode = $params[0]; $atts_ori = array(); - foreach ( $params as $k => $v ) { - if ( $k === 0 ) { + foreach ($params as $k => $v) { + if ($k === 0) { continue; } - $atts_ori[] = is_string( $k ) ? "$k='" . addslashes( $v ) . "'" : $v; + $atts_ori[] = is_string($k) ? "$k='" . addslashes($v) . "'" : $v; } - Tag::add( Tag::TYPE_ESI . "esi.$shortcode" ); + Tag::add(Tag::TYPE_ESI . "esi.$shortcode"); // Output original shortcode final content - echo do_shortcode( "[$shortcode " . implode( ' ', $atts_ori ) . " ]" ); + echo do_shortcode("[$shortcode " . implode(' ', $atts_ori) . ' ]'); } /** @@ -880,11 +930,12 @@ public function load_esi_shortcode( $params ) { * @since 1.1.3 * @access public */ - public function register_comment_form_actions( $defaults ) { + public function register_comment_form_actions($defaults) + { $this->esi_args = $defaults; echo GUI::clean_wrapper_begin(); - add_filter( 'comment_form_submit_button', array( $this, 'sub_comment_form_btn' ), 1000, 2 ); // To save the params passed in - add_action( 'comment_form', array( $this, 'sub_comment_form_block' ), 1000 ); + add_filter('comment_form_submit_button', array($this, 'sub_comment_form_btn'), 1000, 2); // To save the params passed in + add_action('comment_form', array($this, 'sub_comment_form_block'), 1000); return $defaults; } @@ -894,26 +945,25 @@ public function register_comment_form_actions( $defaults ) { * @since 3.4 * @access public */ - public function sub_comment_form_btn( $unused, $args ) { - if ( empty( $args ) || empty( $this->esi_args ) ) { - Debug2::debug( 'comment form args empty?' ); + public function sub_comment_form_btn($unused, $args) + { + if (empty($args) || empty($this->esi_args)) { + Debug2::debug('comment form args empty?'); return $unused; } $esi_args = array(); // compare current args with default ones - foreach ( $args as $k => $v ) { - if ( ! isset( $this->esi_args[ $k ] ) ) { - $esi_args[ $k ] = $v; - } - elseif ( is_array( $v ) ) { - $diff = array_diff_assoc( $v, $this->esi_args[ $k ] ); - if ( ! empty( $diff ) ) { - $esi_args[ $k ] = $diff; + foreach ($args as $k => $v) { + if (!isset($this->esi_args[$k])) { + $esi_args[$k] = $v; + } elseif (is_array($v)) { + $diff = array_diff_assoc($v, $this->esi_args[$k]); + if (!empty($diff)) { + $esi_args[$k] = $diff; } - } - elseif ( $v !== $this->esi_args[ $k ] ) { - $esi_args[ $k ] = $v; + } elseif ($v !== $this->esi_args[$k]) { + $esi_args[$k] = $v; } } @@ -930,16 +980,17 @@ public function sub_comment_form_btn( $unused, $args ) { * @access public * @since 1.1.3 */ - public function sub_comment_form_block( $post_id ) { + public function sub_comment_form_block($post_id) + { echo GUI::clean_wrapper_end(); $params = array( self::PARAM_ID => $post_id, self::PARAM_ARGS => $this->esi_args, ); - echo $this->sub_esi_block( 'comment-form', 'comment form', $params ); + echo $this->sub_esi_block('comment-form', 'comment form', $params); echo GUI::clean_wrapper_begin(); - add_action( 'comment_form_after', array( $this, 'comment_form_sub_clean' ) ); + add_action('comment_form_after', array($this, 'comment_form_sub_clean')); } /** @@ -949,7 +1000,8 @@ public function sub_comment_form_block( $post_id ) { * @since 1.1.3 * @access public */ - public function comment_form_sub_clean() { + public function comment_form_sub_clean() + { echo GUI::clean_wrapper_end(); } @@ -959,24 +1011,25 @@ public function comment_form_sub_clean() { * @since 2.6 * @access public */ - public function finalize( $buffer ) { + public function finalize($buffer) + { // Prepend combo esi block - if ( self::$_combine_ids ) { - Debug2::debug( '[ESI] 🍔 Enabled combo' ); - $esi_block = $this->sub_esi_block( self::COMBO, '__COMBINE_MAIN__', array(), 'no-cache', true ); + if (self::$_combine_ids) { + Debug2::debug('[ESI] 🍔 Enabled combo'); + $esi_block = $this->sub_esi_block(self::COMBO, '__COMBINE_MAIN__', array(), 'no-cache', true); $buffer = $esi_block . $buffer; } // Bypass if no preserved list to be replaced - if ( ! $this->_esi_preserve_list ) { + if (!$this->_esi_preserve_list) { return $buffer; } - $keys = array_keys( $this->_esi_preserve_list ); + $keys = array_keys($this->_esi_preserve_list); - Debug2::debug( '[ESI] replacing preserved blocks', $keys ); + Debug2::debug('[ESI] replacing preserved blocks', $keys); - $buffer = str_replace( $keys, $this->_esi_preserve_list, $buffer ); + $buffer = str_replace($keys, $this->_esi_preserve_list, $buffer); return $buffer; } @@ -986,17 +1039,17 @@ public function finalize( $buffer ) { * * @since 3.3 */ - public function contain_preserve_esi( $content ) { + public function contain_preserve_esi($content) + { $hit_list = array(); - foreach ( $this->_esi_preserve_list as $k => $v ) { - if ( strpos( $content, '"' . $k . '"' ) !== false ) { + foreach ($this->_esi_preserve_list as $k => $v) { + if (strpos($content, '"' . $k . '"') !== false) { $hit_list[] = '"' . $k . '"'; } - if ( strpos( $content, "'" . $k . "'" ) !== false ) { + if (strpos($content, "'" . $k . "'") !== false) { $hit_list[] = "'" . $k . "'"; } } return $hit_list; } - } diff --git a/src/file.cls.php b/src/file.cls.php index 16b4efd0f..36ea4febf 100644 --- a/src/file.cls.php +++ b/src/file.cls.php @@ -1,15 +1,16 @@ seek($start_line); - if ( $lines === null) { - while ( ! $file->eof() ) { + if ($lines === null) { + while (!$file->eof()) { $res[] = rtrim($file->current(), "\n"); $file->next(); } - } - else{ - for ( $i=0; $i < $lines; $i++ ) { - if ( $file->eof() ) { + } else { + for ($i = 0; $i < $lines; $i++) { + if ($file->eof()) { break; } $res[] = rtrim($file->current(), "\n"); @@ -95,9 +98,9 @@ public static function read($filename, $start_line = null, $lines = null) { return $res; } - $content = file_get_contents( $filename ); + $content = file_get_contents($filename); - $content = self::remove_zero_space( $content ); + $content = self::remove_zero_space($content); return $content; } @@ -112,8 +115,9 @@ public static function read($filename, $start_line = null, $lines = null) { * @param boolean $mkdir * @param boolean $silence Used to avoid WP's functions are used */ - public static function append( $filename, $data, $mkdir = false, $silence = true ) { - return self::save( $filename, $data, $mkdir, true, $silence ); + public static function append($filename, $data, $mkdir = false, $silence = true) + { + return self::save($filename, $data, $mkdir, true, $silence); } /** @@ -126,50 +130,48 @@ public static function append( $filename, $data, $mkdir = false, $silence = true * @param boolean $append If the content needs to be appended * @param boolean $silence Used to avoid WP's functions are used */ - public static function save( $filename, $data, $mkdir = false, $append = false, $silence = true ) { + public static function save($filename, $data, $mkdir = false, $append = false, $silence = true) + { $error = false; - $folder = dirname( $filename ); + $folder = dirname($filename); // mkdir if folder does not exist - if ( ! file_exists( $folder ) ) { - if ( ! $mkdir ) { - return $silence ? false : sprintf( __( 'Folder does not exist: %s', 'litespeed-cache' ), $folder ); + if (!file_exists($folder)) { + if (!$mkdir) { + return $silence ? false : sprintf(__('Folder does not exist: %s', 'litespeed-cache'), $folder); } - set_error_handler( 'litespeed_exception_handler' ); + set_error_handler('litespeed_exception_handler'); try { - mkdir( $folder, 0755, true ); - } - catch ( \ErrorException $ex ) { - return $silence ? false : sprintf( __( 'Can not create folder: %1$s. Error: %2$s', 'litespeed-cache' ), $folder, $ex->getMessage() ); + mkdir($folder, 0755, true); + } catch (\ErrorException $ex) { + return $silence ? false : sprintf(__('Can not create folder: %1$s. Error: %2$s', 'litespeed-cache'), $folder, $ex->getMessage()); } restore_error_handler(); } - if ( ! file_exists( $filename ) ) { - if ( ! is_writable( $folder ) ) { - return $silence ? false : sprintf( __( 'Folder is not writable: %s.', 'litespeed-cache' ), $folder ); + if (!file_exists($filename)) { + if (!is_writable($folder)) { + return $silence ? false : sprintf(__('Folder is not writable: %s.', 'litespeed-cache'), $folder); } - set_error_handler( 'litespeed_exception_handler' ); + set_error_handler('litespeed_exception_handler'); try { - touch( $filename ); - } - catch ( \ErrorException $ex ){ - return $silence ? false : sprintf( __( 'File %s is not writable.', 'litespeed-cache' ), $filename ); + touch($filename); + } catch (\ErrorException $ex) { + return $silence ? false : sprintf(__('File %s is not writable.', 'litespeed-cache'), $filename); } restore_error_handler(); - } - elseif ( ! is_writable( $filename ) ) { - return $silence ? false : sprintf( __( 'File %s is not writable.', 'litespeed-cache' ), $filename ); + } elseif (!is_writable($filename)) { + return $silence ? false : sprintf(__('File %s is not writable.', 'litespeed-cache'), $filename); } - $data = self::remove_zero_space( $data ); + $data = self::remove_zero_space($data); - $ret = file_put_contents( $filename, $data, $append ? FILE_APPEND : LOCK_EX ); - if ( $ret === false ) { - return $silence ? false : sprintf( __( 'Failed to write to %s.', 'litespeed-cache' ), $filename ); + $ret = file_put_contents($filename, $data, $append ? FILE_APPEND : LOCK_EX); + if ($ret === false) { + return $silence ? false : sprintf(__('Failed to write to %s.', 'litespeed-cache'), $filename); } return true; @@ -181,20 +183,21 @@ public static function save( $filename, $data, $mkdir = false, $append = false, * @since 2.1.2 * @since 2.9 changed to public */ - public static function remove_zero_space( $content ) { - if ( is_array( $content ) ) { - $content = array_map( __CLASS__ . '::remove_zero_space', $content ); + public static function remove_zero_space($content) + { + if (is_array($content)) { + $content = array_map(__CLASS__ . '::remove_zero_space', $content); return $content; } // Remove UTF-8 BOM if present - if ( substr( $content, 0, 3 ) === "\xEF\xBB\xBF" ) { - $content = substr( $content, 3 ); + if (substr($content, 0, 3) === "\xEF\xBB\xBF") { + $content = substr($content, 3); } - $content = str_replace( "\xe2\x80\x8b", '', $content ); - $content = str_replace( "\xe2\x80\x8c", '', $content ); - $content = str_replace( "\xe2\x80\x8d", '', $content ); + $content = str_replace("\xe2\x80\x8b", '', $content); + $content = str_replace("\xe2\x80\x8c", '', $content); + $content = str_replace("\xe2\x80\x8d", '', $content); return $content; } @@ -212,16 +215,17 @@ public static function remove_zero_space( $content ) { * @param bool $prepend Prepend insertion if not exist. * @return bool True on write success, false on failure. */ - public static function insert_with_markers($filename, $insertion = false, $marker = false, $prepend = false) { - if ( !$marker ) { + public static function insert_with_markers($filename, $insertion = false, $marker = false, $prepend = false) + { + if (!$marker) { $marker = self::MARKER; } - if ( !$insertion ) { + if (!$insertion) { $insertion = array(); } - return self::_insert_with_markers($filename, $marker, $insertion, $prepend);//todo: capture exceptions + return self::_insert_with_markers($filename, $marker, $insertion, $prepend); //todo: capture exceptions } /** @@ -231,18 +235,15 @@ public static function insert_with_markers($filename, $insertion = false, $marke * @param string $marker * @return string The block data */ - public static function wrap_marker_data($insertion, $marker = false) { - if ( ! $marker ) { + public static function wrap_marker_data($insertion, $marker = false) + { + if (!$marker) { $marker = self::MARKER; } $start_marker = "# BEGIN {$marker}"; - $end_marker = "# END {$marker}"; + $end_marker = "# END {$marker}"; - $new_data = implode( "\n", array_merge( - array( $start_marker ), - $insertion, - array( $end_marker ) - ) ); + $new_data = implode("\n", array_merge(array($start_marker), $insertion, array($end_marker))); return $new_data; } @@ -253,24 +254,21 @@ public static function wrap_marker_data($insertion, $marker = false) { * @param string $marker * @return string The current block data */ - public static function touch_marker_data($filename, $marker = false) { - if( ! $marker ) { + public static function touch_marker_data($filename, $marker = false) + { + if (!$marker) { $marker = self::MARKER; } $result = self::_extract_from_markers($filename, $marker); - if( ! $result ) { + if (!$result) { return false; } $start_marker = "# BEGIN {$marker}"; - $end_marker = "# END {$marker}"; - $new_data = implode( "\n", array_merge( - array( $start_marker ), - $result, - array( $end_marker ) - ) ); + $end_marker = "# END {$marker}"; + $new_data = implode("\n", array_merge(array($start_marker), $result, array($end_marker))); return $new_data; } @@ -281,8 +279,9 @@ public static function touch_marker_data($filename, $marker = false) { * @param string $marker * @return array An array of strings from a file (.htaccess ) from between BEGIN and END markers. */ - public static function extract_from_markers($filename, $marker = false) { - if( ! $marker ) { + public static function extract_from_markers($filename, $marker = false) + { + if (!$marker) { $marker = self::MARKER; } return self::_extract_from_markers($filename, $marker); @@ -295,20 +294,21 @@ public static function extract_from_markers($filename, $marker = false) { * @param string $marker * @return array An array of strings from a file (.htaccess ) from between BEGIN and END markers. */ - private static function _extract_from_markers( $filename, $marker ) { + private static function _extract_from_markers($filename, $marker) + { $result = array(); - if (!file_exists($filename) ) { + if (!file_exists($filename)) { return $result; } - if ( $markerdata = explode( "\n", implode( '', file($filename) ) ) ) { + if ($markerdata = explode("\n", implode('', file($filename)))) { $state = false; - foreach ( $markerdata as $markerline ) { - if ( strpos($markerline, '# END ' . $marker) !== false ) { + foreach ($markerdata as $markerline) { + if (strpos($markerline, '# END ' . $marker) !== false) { $state = false; } - if ( $state ) { + if ($state) { $result[] = $markerline; } if (strpos($markerline, '# BEGIN ' . $marker) !== false) { @@ -331,70 +331,67 @@ private static function _extract_from_markers( $filename, $marker ) { * @since 3.0 Throw errors if failed * @access private */ - private static function _insert_with_markers( $filename, $marker, $insertion, $prepend = false) { - if ( ! file_exists( $filename ) ) { - if ( ! is_writable( dirname( $filename ) ) ) { - Error::t( 'W', dirname( $filename ) ); + private static function _insert_with_markers($filename, $marker, $insertion, $prepend = false) + { + if (!file_exists($filename)) { + if (!is_writable(dirname($filename))) { + Error::t('W', dirname($filename)); } - set_error_handler("litespeed_exception_handler"); + set_error_handler('litespeed_exception_handler'); try { - touch( $filename ); - } catch ( \ErrorException $ex ) { - Error::t( 'W', $filename ); + touch($filename); + } catch (\ErrorException $ex) { + Error::t('W', $filename); } restore_error_handler(); - } - elseif ( ! is_writable( $filename ) ) { - Error::t( 'W', $filename ); + } elseif (!is_writable($filename)) { + Error::t('W', $filename); } - if ( ! is_array( $insertion ) ) { - $insertion = explode( "\n", $insertion ); + if (!is_array($insertion)) { + $insertion = explode("\n", $insertion); } $start_marker = "# BEGIN {$marker}"; - $end_marker = "# END {$marker}"; + $end_marker = "# END {$marker}"; - $fp = fopen( $filename, 'r+' ); - if ( ! $fp ) { - Error::t( 'W', $filename ); + $fp = fopen($filename, 'r+'); + if (!$fp) { + Error::t('W', $filename); } // Attempt to get a lock. If the filesystem supports locking, this will block until the lock is acquired. - flock( $fp, LOCK_EX ); + flock($fp, LOCK_EX); $lines = array(); - while ( ! feof($fp) ) { - $lines[] = rtrim(fgets($fp), "\r\n" ); + while (!feof($fp)) { + $lines[] = rtrim(fgets($fp), "\r\n"); } // Split out the existing file into the preceding lines, and those that appear after the marker $pre_lines = $post_lines = $existing_lines = array(); $found_marker = $found_end_marker = false; - foreach ( $lines as $line ) { - if ( ! $found_marker && false !== strpos($line, $start_marker) ) { + foreach ($lines as $line) { + if (!$found_marker && false !== strpos($line, $start_marker)) { $found_marker = true; continue; - } - elseif ( ! $found_end_marker && false !== strpos($line, $end_marker) ) { + } elseif (!$found_end_marker && false !== strpos($line, $end_marker)) { $found_end_marker = true; continue; } - if ( ! $found_marker ) { + if (!$found_marker) { $pre_lines[] = $line; - } - elseif ( $found_marker && $found_end_marker ) { + } elseif ($found_marker && $found_end_marker) { $post_lines[] = $line; - } - else { + } else { $existing_lines[] = $line; } } // Check to see if there was a change - if ( $existing_lines === $insertion ) { + if ($existing_lines === $insertion) { flock($fp, LOCK_UN); fclose($fp); @@ -402,32 +399,18 @@ private static function _insert_with_markers( $filename, $marker, $insertion, $p } // Check if need to prepend data if not exist - if( $prepend && ! $post_lines ) { + if ($prepend && !$post_lines) { // Generate the new file data - $new_file_data = implode( "\n", array_merge( - array( $start_marker ), - $insertion, - array( $end_marker ), - $pre_lines - ) ); - - } - else { + $new_file_data = implode("\n", array_merge(array($start_marker), $insertion, array($end_marker), $pre_lines)); + } else { // Generate the new file data - $new_file_data = implode( "\n", array_merge( - $pre_lines, - array( $start_marker ), - $insertion, - array( $end_marker ), - $post_lines - ) ); + $new_file_data = implode("\n", array_merge($pre_lines, array($start_marker), $insertion, array($end_marker), $post_lines)); } - // Write to the start of the file, and truncate it to that length fseek($fp, 0); $bytes = fwrite($fp, $new_file_data); - if ( $bytes ) { + if ($bytes) { ftruncate($fp, ftell($fp)); } fflush($fp); @@ -437,5 +420,3 @@ private static function _insert_with_markers( $filename, $marker, $insertion, $p return (bool) $bytes; } } - - diff --git a/src/gui.cls.php b/src/gui.cls.php index 8d13531ce..3317958af 100644 --- a/src/gui.cls.php +++ b/src/gui.cls.php @@ -7,17 +7,18 @@ * @author LiteSpeed Technologies */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class GUI extends Base { +class GUI extends Base +{ private static $_clean_counter = 0; private $_promo_true; // [ file_tag => [ days, litespeed_only ], ... ] private $_promo_list = array( - 'new_version' => array( 7, false ), - 'score' => array( 14, false ), + 'new_version' => array(7, false), + 'score' => array(14, false), // 'slack' => array( 3, false ), ); @@ -40,9 +41,9 @@ class GUI extends Base { * * @since 1.3 */ - public function __construct() { + public function __construct() + { $this->_summary = self::get_summary(); - } /** @@ -50,33 +51,35 @@ public function __construct() { * * @since 3.0 */ - public function init() { - Debug2::debug2( '[GUI] init' ); - if ( is_admin_bar_showing() && current_user_can( 'manage_options' ) ) { - add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue_style' ) ); - add_action( 'admin_bar_menu', array( $this, 'frontend_shortcut' ), 95 ); + public function init() + { + Debug2::debug2('[GUI] init'); + if (is_admin_bar_showing() && current_user_can('manage_options')) { + add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_style')); + add_action('admin_bar_menu', array($this, 'frontend_shortcut'), 95); } /** * Turn on instant click * @since 1.8.2 */ - if ( $this->conf( self::O_UTIL_INSTANT_CLICK ) ) { - add_action( 'wp_enqueue_scripts', array( $this, 'frontend_enqueue_style_public' ) ); + if ($this->conf(self::O_UTIL_INSTANT_CLICK)) { + add_action('wp_enqueue_scripts', array($this, 'frontend_enqueue_style_public')); } // NOTE: this needs to be before optimizer to avoid wrapper being removed - add_filter( 'litespeed_buffer_finalize', array( $this, 'finalize' ), 8 ); + add_filter('litespeed_buffer_finalize', array($this, 'finalize'), 8); } /** - * Print a loading message when redirecting CCSS/UCSS page to aviod whiteboard confusion - */ - public static function print_loading( $counter, $type ) { + * Print a loading message when redirecting CCSS/UCSS page to aviod whiteboard confusion + */ + public static function print_loading($counter, $type) + { echo '
      '; echo " "; - echo sprintf( __( '%1$s %2$s files left in queue', 'litespeed-cache' ), $counter, $type ); - echo '

      ' . __( 'Cancel', 'litespeed-cache' ) . '

      '; + echo sprintf(__('%1$s %2$s files left in queue', 'litespeed-cache'), $counter, $type); + echo '

      ' . __('Cancel', 'litespeed-cache') . '

      '; echo '
      '; } @@ -85,10 +88,11 @@ public static function print_loading( $counter, $type ) { * * @since 1.6.6 */ - public static function pie( $percent, $width = 50, $finished_tick = false, $without_percentage = false, $append_cls = false ) { - $percentage = '' . $percent . ( $without_percentage ? '' : '%' ) . ''; + public static function pie($percent, $width = 50, $finished_tick = false, $without_percentage = false, $append_cls = false) + { + $percentage = '' . $percent . ($without_percentage ? '' : '%') . ''; - if ( $percent == 100 && $finished_tick ) { + if ($percent == 100 && $finished_tick) { $percentage = ''; } @@ -106,10 +110,10 @@ public static function pie( $percent, $width = 50, $finished_tick = false, $with * * @since 3.0 */ - public static function pie_tiny( $percent, $width = 50, $tooltip = '', $tooltip_pos = 'up', $append_cls = false ) { - + public static function pie_tiny($percent, $width = 50, $tooltip = '', $tooltip_pos = 'up', $append_cls = false) + { // formula C = 2πR - $dasharray = 2 * 3.1416 * 9 * ( $percent / 100 ); + $dasharray = 2 * 3.1416 * 9 * ($percent / 100); return "
    '; } @@ -353,20 +402,21 @@ public function media_row_con( $post_id ) { * @since 1.6.2 * @return array $sizes Data for all currently-registered image sizes. */ - public function get_image_sizes() { + public function get_image_sizes() + { global $_wp_additional_image_sizes; $sizes = array(); - foreach ( get_intermediate_image_sizes() as $_size ) { - if ( in_array( $_size, array( 'thumbnail', 'medium', 'medium_large', 'large' ) ) ) { - $sizes[ $_size ][ 'width' ] = get_option( $_size . '_size_w' ); - $sizes[ $_size ][ 'height' ] = get_option( $_size . '_size_h' ); - $sizes[ $_size ][ 'crop' ] = (bool) get_option( $_size . '_crop' ); - } elseif ( isset( $_wp_additional_image_sizes[ $_size ] ) ) { - $sizes[ $_size ] = array( - 'width' => $_wp_additional_image_sizes[ $_size ][ 'width' ], - 'height' => $_wp_additional_image_sizes[ $_size ][ 'height' ], - 'crop' => $_wp_additional_image_sizes[ $_size ][ 'crop' ] + foreach (get_intermediate_image_sizes() as $_size) { + if (in_array($_size, array('thumbnail', 'medium', 'medium_large', 'large'))) { + $sizes[$_size]['width'] = get_option($_size . '_size_w'); + $sizes[$_size]['height'] = get_option($_size . '_size_h'); + $sizes[$_size]['crop'] = (bool) get_option($_size . '_crop'); + } elseif (isset($_wp_additional_image_sizes[$_size])) { + $sizes[$_size] = array( + 'width' => $_wp_additional_image_sizes[$_size]['width'], + 'height' => $_wp_additional_image_sizes[$_size]['height'], + 'crop' => $_wp_additional_image_sizes[$_size]['crop'], ); } } @@ -374,26 +424,29 @@ public function get_image_sizes() { return $sizes; } - /** * Exclude role from optimization filter * * @since 1.6.2 * @access public */ - public function webp_support() { - if ( ! empty( $_SERVER[ 'HTTP_ACCEPT' ] ) && strpos( $_SERVER[ 'HTTP_ACCEPT' ], 'image/webp' ) !== false ) { + public function webp_support() + { + if (!empty($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'image/webp') !== false) { return true; } - if ( ! empty( $_SERVER[ 'HTTP_USER_AGENT' ] ) ) { - if ( strpos( $_SERVER[ 'HTTP_USER_AGENT' ], 'Page Speed' ) !== false ) { - return true; + if (!empty($_SERVER['HTTP_USER_AGENT'])) { + $user_agents = array('chrome-lighthouse', 'googlebot', 'page speed'); + foreach ($user_agents as $user_agent) { + if (stripos($_SERVER['HTTP_USER_AGENT'], $user_agent) !== false) { + return true; + } } - if ( preg_match( "/iPhone OS (\d+)_/i", $_SERVER[ 'HTTP_USER_AGENT' ], $matches ) ) { + if (preg_match('/iPhone OS (\d+)_/i', $_SERVER['HTTP_USER_AGENT'], $matches)) { $lscwp_ios_version = $matches[1]; - if ($lscwp_ios_version >= 14){ + if ($lscwp_ios_version >= 14) { return true; } } @@ -412,23 +465,24 @@ public function webp_support() { * @access public * @return string The buffer */ - public function finalize( $content ) { - if ( defined( 'LITESPEED_NO_LAZY' ) ) { - Debug2::debug2( '[Media] bypass: NO_LAZY const' ); + public function finalize($content) + { + if (defined('LITESPEED_NO_LAZY')) { + Debug2::debug2('[Media] bypass: NO_LAZY const'); return $content; } - if ( ! defined( 'LITESPEED_IS_HTML' ) ) { - Debug2::debug2( '[Media] bypass: Not frontend HTML type' ); + if (!defined('LITESPEED_IS_HTML')) { + Debug2::debug2('[Media] bypass: Not frontend HTML type'); return $content; } - if ( ! Control::is_cacheable() ) { - self::debug( 'bypass: Not cacheable' ); + if (!Control::is_cacheable()) { + self::debug('bypass: Not cacheable'); return $content; } - self::debug( 'finalize' ); + self::debug('finalize'); $this->content = $content; $this->_finalize(); @@ -441,92 +495,89 @@ public function finalize( $content ) { * @since 1.4 * @access private */ - private function _finalize() { + private function _finalize() + { /** * Use webp for optimized images * @since 1.6.2 */ - if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE ) ) && $this->webp_support() ) { - $this->content = $this->_replace_buffer_img_webp( $this->content ); + if ((defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_IMG_OPTM_WEBP)) && $this->webp_support()) { + $this->content = $this->_replace_buffer_img_webp($this->content); } /** * Check if URI is excluded * @since 3.0 */ - $excludes = $this->conf( Base::O_MEDIA_LAZY_URI_EXC ); - if ( ! defined( 'LITESPEED_GUEST_OPTM' ) ) { - $result = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $excludes ); - if ( $result ) { - self::debug( 'bypass lazyload: hit URI Excludes setting: ' . $result ); + $excludes = $this->conf(Base::O_MEDIA_LAZY_URI_EXC); + if (!defined('LITESPEED_GUEST_OPTM')) { + $result = Utility::str_hit_array($_SERVER['REQUEST_URI'], $excludes); + if ($result) { + self::debug('bypass lazyload: hit URI Excludes setting: ' . $result); return; } } - $cfg_lazy = ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_MEDIA_LAZY ) ) && ! $this->cls( 'Metabox' )->setting( 'litespeed_no_image_lazy' ); - $cfg_iframe_lazy = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_MEDIA_IFRAME_LAZY ); - $cfg_js_delay = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_OPTM_JS_DEFER ) == 2; - $cfg_trim_noscript = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_OPTM_NOSCRIPT_RM ); - $cfg_vpi = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_MEDIA_VPI ); + $cfg_lazy = (defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_MEDIA_LAZY)) && !$this->cls('Metabox')->setting('litespeed_no_image_lazy'); + $cfg_iframe_lazy = defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_MEDIA_IFRAME_LAZY); + $cfg_js_delay = defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_OPTM_JS_DEFER) == 2; + $cfg_trim_noscript = defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_OPTM_NOSCRIPT_RM); + $cfg_vpi = defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_MEDIA_VPI); - if ( $cfg_lazy ) { - if ( $cfg_vpi ) { - add_filter( 'litespeed_media_lazy_img_excludes', array( $this->cls( 'Metabox' ), 'lazy_img_excludes' ) ); + if ($cfg_lazy) { + if ($cfg_vpi) { + add_filter('litespeed_media_lazy_img_excludes', array($this->cls('Metabox'), 'lazy_img_excludes')); } - list( $src_list, $html_list, $placeholder_list ) = $this->_parse_img(); + list($src_list, $html_list, $placeholder_list) = $this->_parse_img(); $html_list_ori = $html_list; - } - else { - self::debug( 'lazyload disabled' ); + } else { + self::debug('lazyload disabled'); } // image lazy load - if ( $cfg_lazy ) { - + if ($cfg_lazy) { $__placeholder = Placeholder::cls(); - foreach ( $html_list as $k => $v ) { - $size = $placeholder_list[ $k ]; - $src = $src_list[ $k ]; + foreach ($html_list as $k => $v) { + $size = $placeholder_list[$k]; + $src = $src_list[$k]; - $html_list[ $k ] = $__placeholder->replace( $v, $src, $size ); + $html_list[$k] = $__placeholder->replace($v, $src, $size); } } - if ( $cfg_lazy ) { - $this->content = str_replace( $html_list_ori, $html_list, $this->content ); + if ($cfg_lazy) { + $this->content = str_replace($html_list_ori, $html_list, $this->content); } // iframe lazy load - if ( $cfg_iframe_lazy ) { + if ($cfg_iframe_lazy) { $html_list = $this->_parse_iframe(); $html_list_ori = $html_list; - foreach ( $html_list as $k => $v ) { + foreach ($html_list as $k => $v) { $snippet = $cfg_trim_noscript ? '' : ''; - if ( $cfg_js_delay ) { - $v = str_replace( ' src=', ' data-litespeed-src=', $v ); - } - else { - $v = str_replace( ' src=', ' data-src=', $v ); + if ($cfg_js_delay) { + $v = str_replace(' src=', ' data-litespeed-src=', $v); + } else { + $v = str_replace(' src=', ' data-src=', $v); } - $v = str_replace( '#isU', $content, $matches, PREG_SET_ORDER ); - foreach ( $matches as $match ) { - $attrs = Utility::parse_attr( $match[ 1 ] ); + preg_match_all('##isU', $content, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + $attrs = Utility::parse_attr($match[1]); - if ( empty( $attrs[ 'src' ] ) ) { + if (empty($attrs['src'])) { continue; } - Debug2::debug2( '[Media] found iframe: ' . $attrs[ 'src' ] ); + Debug2::debug2('[Media] found iframe: ' . $attrs['src']); - if ( ! empty( $attrs[ 'data-no-lazy' ] ) || ! empty( $attrs[ 'data-skip-lazy' ] ) || ! empty( $attrs[ 'data-lazyloaded' ] ) || ! empty( $attrs[ 'data-src' ] ) ) { - Debug2::debug2( '[Media] bypassed' ); + if (!empty($attrs['data-no-lazy']) || !empty($attrs['data-skip-lazy']) || !empty($attrs['data-lazyloaded']) || !empty($attrs['data-src'])) { + Debug2::debug2('[Media] bypassed'); continue; } - if ( ! empty( $attrs[ 'class' ] ) && $hit = Utility::str_hit_array( $attrs[ 'class' ], $cls_excludes ) ) { - Debug2::debug2( '[Media] iframe lazyload cls excludes [hit] ' . $hit ); + if (!empty($attrs['class']) && ($hit = Utility::str_hit_array($attrs['class'], $cls_excludes))) { + Debug2::debug2('[Media] iframe lazyload cls excludes [hit] ' . $hit); continue; } - if ( apply_filters( 'litespeed_iframe_lazyload_exc', false, $attrs[ 'src' ] ) ) { - Debug2::debug2( '[Media] bypassed by filter' ); + if (apply_filters('litespeed_iframe_lazyload_exc', false, $attrs['src'])) { + Debug2::debug2('[Media] bypassed by filter'); continue; } // to avoid multiple replacement - if ( in_array( $match[ 0 ], $html_list ) ) { + if (in_array($match[0], $html_list)) { continue; } - $html_list[] = $match[ 0 ]; + $html_list[] = $match[0]; } return $html_list; @@ -748,70 +814,61 @@ private function _parse_iframe() { * @since 1.6.2 * @access private */ - private function _replace_buffer_img_webp( $content ) { + private function _replace_buffer_img_webp($content) + { /** * Added custom element & attribute support * @since 2.2.2 */ - $webp_ele_to_check = $this->conf( Base::O_IMG_OPTM_WEBP_ATTR ); + $webp_ele_to_check = $this->conf(Base::O_IMG_OPTM_WEBP_ATTR); - foreach ( $webp_ele_to_check as $v ) { - if ( ! $v || strpos( $v, '.' ) === false ) { - Debug2::debug2( '[Media] buffer_webp no . attribute ' . $v ); + foreach ($webp_ele_to_check as $v) { + if (!$v || strpos($v, '.') === false) { + Debug2::debug2('[Media] buffer_webp no . attribute ' . $v); continue; } - Debug2::debug2( '[Media] buffer_webp attribute ' . $v ); + Debug2::debug2('[Media] buffer_webp attribute ' . $v); - $v = explode( '.', $v ); - $attr = preg_quote( $v[ 1 ], '#' ); - if ( $v[ 0 ] ) { - $pattern = '#<' . preg_quote( $v[ 0 ], '#' ) . '([^>]+)' . $attr . '=([\'"])(.+)\2#iU'; - } - else { + $v = explode('.', $v); + $attr = preg_quote($v[1], '#'); + if ($v[0]) { + $pattern = '#<' . preg_quote($v[0], '#') . '([^>]+)' . $attr . '=([\'"])(.+)\2#iU'; + } else { $pattern = '# ' . $attr . '=([\'"])(.+)\1#iU'; } - preg_match_all( $pattern, $content, $matches ); + preg_match_all($pattern, $content, $matches); - foreach ( $matches[ $v[ 0 ] ? 3 : 2 ] as $k2 => $url ) { + foreach ($matches[$v[0] ? 3 : 2] as $k2 => $url) { // Check if is a DATA-URI - if ( strpos( $url, 'data:image' ) !== false ) { + if (strpos($url, 'data:image') !== false) { continue; } - if ( ! $url2 = $this->replace_webp( $url ) ) { + if (!($url2 = $this->replace_webp($url))) { continue; } - if ( $v[ 0 ] ) { - $html_snippet = sprintf( - '<' . $v[ 0 ] . '%1$s' . $v[ 1 ] . '=%2$s', - $matches[ 1 ][ $k2 ], - $matches[ 2 ][ $k2 ] . $url2 . $matches[ 2 ][ $k2 ] - ); - } - else { - $html_snippet = sprintf( - ' ' . $v[ 1 ] . '=%1$s', - $matches[ 1 ][ $k2 ] . $url2 . $matches[ 1 ][ $k2 ] - ); + if ($v[0]) { + $html_snippet = sprintf('<' . $v[0] . '%1$s' . $v[1] . '=%2$s', $matches[1][$k2], $matches[2][$k2] . $url2 . $matches[2][$k2]); + } else { + $html_snippet = sprintf(' ' . $v[1] . '=%1$s', $matches[1][$k2] . $url2 . $matches[1][$k2]); } - $content = str_replace( $matches[ 0 ][ $k2 ], $html_snippet, $content ); - + $content = str_replace($matches[0][$k2], $html_snippet, $content); } } // parse srcset // todo: should apply this to cdn too - if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE_SRCSET ) ) && $this->webp_support() ) { - $content = Utility::srcset_replace( $content, array( $this, 'replace_webp' ) ); + if ((defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_IMG_OPTM_WEBP_REPLACE_SRCSET)) && $this->webp_support()) { + $content = Utility::srcset_replace($content, array($this, 'replace_webp')); } // Replace background-image - if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE ) ) && $this->webp_support() ) { - $content = $this->replace_background_webp( $content ); + if ((defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_IMG_OPTM_WEBP)) && $this->webp_support()) { + $content = $this->replace_background_webp($content); } return $content; @@ -822,14 +879,15 @@ private function _replace_buffer_img_webp( $content ) { * * @since 4.0 */ - public function replace_background_webp( $content ) { - Debug2::debug2( '[Media] Start replacing bakcground WebP.' ); + public function replace_background_webp($content) + { + Debug2::debug2('[Media] Start replacing bakcground WebP.'); // preg_match_all( '#background-image:(\s*)url\((.*)\)#iU', $content, $matches ); - preg_match_all( '#url\(([^)]+)\)#iU', $content, $matches ); - foreach ( $matches[ 1 ] as $k => $url ) { + preg_match_all('#url\(([^)]+)\)#iU', $content, $matches); + foreach ($matches[1] as $k => $url) { // Check if is a DATA-URI - if ( strpos( $url, 'data:image' ) !== false ) { + if (strpos($url, 'data:image') !== false) { continue; } @@ -837,15 +895,20 @@ public function replace_background_webp( $content ) { * Support quotes in src `background-image: url('src')` * @since 2.9.3 */ - $url = trim( $url, '\'"' ); + $url = trim($url, '\'"'); + + // Fix Elementors Slideshow unusal background images like style="background-image: url("https://xxxx.png");" + if (strpos($url, '"') === 0 && substr($url, -6) == '"') { + $url = substr($url, 6, -6); + } - if ( ! $url2 = $this->replace_webp( $url ) ) { + if (!($url2 = $this->replace_webp($url))) { continue; } // $html_snippet = sprintf( 'background-image:%1$surl(%2$s)', $matches[ 1 ][ $k ], $url2 ); - $html_snippet = str_replace( $url, $url2, $matches[ 0 ][ $k ] ); - $content = str_replace( $matches[ 0 ][ $k ], $html_snippet, $content ); + $html_snippet = str_replace($url, $url2, $matches[0][$k]); + $content = str_replace($matches[0][$k], $html_snippet, $content); } return $content; @@ -857,11 +920,12 @@ public function replace_background_webp( $content ) { * @since 1.6.2 * @access public */ - public function replace_webp( $url ) { - Debug2::debug2( '[Media] webp replacing: ' . substr( $url, 0, 200 ) ); + public function replace_webp($url) + { + Debug2::debug2('[Media] webp replacing: ' . substr($url, 0, 200)); - if ( substr( $url, -5 ) == '.webp' ) { - Debug2::debug2( '[Media] already webp' ); + if (substr($url, -5) == '.webp') { + Debug2::debug2('[Media] already webp'); return false; } @@ -871,22 +935,20 @@ public function replace_webp( $url ) { * @since 2.9.5 * @see #751737 - API docs for WebP generation */ - if ( apply_filters( 'litespeed_media_check_ori', Utility::is_internal_file( $url ), $url ) ) { + if (apply_filters('litespeed_media_check_ori', Utility::is_internal_file($url), $url)) { // check if has webp file - if ( apply_filters( 'litespeed_media_check_webp', Utility::is_internal_file( $url, 'webp' ), $url ) ) { + if (apply_filters('litespeed_media_check_webp', Utility::is_internal_file($url, 'webp'), $url)) { $url .= '.webp'; - } - else { - Debug2::debug2( '[Media] -no WebP file, bypassed' ); + } else { + Debug2::debug2('[Media] -no WebP file, bypassed'); return false; } - } - else { - Debug2::debug2( '[Media] -no file, bypassed' ); + } else { + Debug2::debug2('[Media] -no file, bypassed'); return false; } - Debug2::debug2( '[Media] - replaced to: ' . $url ); + Debug2::debug2('[Media] - replaced to: ' . $url); return $url; } @@ -899,10 +961,11 @@ public function replace_webp( $url ) { * @param array $img The URL of the attachment image src, the width, the height * @return array */ - public function webp_attach_img_src( $img ) { - Debug2::debug2( '[Media] changing attach src: ' . $img[0] ); - if ( $img && $url = $this->replace_webp( $img[ 0 ] ) ) { - $img[ 0 ] = $url; + public function webp_attach_img_src($img) + { + Debug2::debug2('[Media] changing attach src: ' . $img[0]); + if ($img && ($url = $this->replace_webp($img[0]))) { + $img[0] = $url; } return $img; } @@ -915,8 +978,9 @@ public function webp_attach_img_src( $img ) { * @param string $url * @return string */ - public function webp_url( $url ) { - if ( $url && $url2 = $this->replace_webp( $url ) ) { + public function webp_url($url) + { + if ($url && ($url2 = $this->replace_webp($url))) { $url = $url2; } return $url; @@ -930,16 +994,16 @@ public function webp_url( $url ) { * @param array $srcs * @return array */ - public function webp_srcset( $srcs ) { - if ( $srcs ) { - foreach ( $srcs as $w => $data ) { - if( ! $url = $this->replace_webp( $data[ 'url' ] ) ) { + public function webp_srcset($srcs) + { + if ($srcs) { + foreach ($srcs as $w => $data) { + if (!($url = $this->replace_webp($data['url']))) { continue; } - $srcs[ $w ][ 'url' ] = $url; + $srcs[$w]['url'] = $url; } } return $srcs; } - } diff --git a/src/metabox.cls.php b/src/metabox.cls.php index bf46e814a..7e877e6f9 100644 --- a/src/metabox.cls.php +++ b/src/metabox.cls.php @@ -9,9 +9,10 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Metabox extends Root { +class Metabox extends Root +{ const LOG_TAG = '📦'; const POST_NONCE_ACTION = 'post_nonce_action'; @@ -22,14 +23,15 @@ class Metabox extends Root { * Get the setting list * @since 4.7 */ - public function __construct() { + public function __construct() + { // Append meta box $this->_postmeta_settings = array( - 'litespeed_no_cache' => __( 'Disable Cache', 'litespeed-cache' ), - 'litespeed_no_image_lazy' => __( 'Disable Image Lazyload', 'litespeed-cache' ), - 'litespeed_no_vpi' => __( 'Disable VPI', 'litespeed-cache' ), - 'litespeed_vpi_list' => __( 'Viewport Images', 'litespeed-cache' ), - 'litespeed_vpi_list_mobile' => __( 'Viewport Images', 'litespeed-cache' ) . ' - ' . __( 'Mobile', 'litespeed-cache' ), + 'litespeed_no_cache' => __('Disable Cache', 'litespeed-cache'), + 'litespeed_no_image_lazy' => __('Disable Image Lazyload', 'litespeed-cache'), + 'litespeed_no_vpi' => __('Disable VPI', 'litespeed-cache'), + 'litespeed_vpi_list' => __('Viewport Images', 'litespeed-cache'), + 'litespeed_vpi_list_mobile' => __('Viewport Images', 'litespeed-cache') . ' - ' . __('Mobile', 'litespeed-cache'), ); } @@ -37,27 +39,36 @@ public function __construct() { * Register post edit settings * @since 4.7 */ - public function register_settings() { - add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) ); - add_action( 'save_post', array( $this, 'save_meta_box_settings' ), 15, 2 ); + public function register_settings() + { + add_action('add_meta_boxes', array($this, 'add_meta_boxes')); + add_action('save_post', array($this, 'save_meta_box_settings'), 15, 2); + add_action('attachment_updated', array($this, 'save_meta_box_settings'), 15, 2); } /** * Regsiter meta box * @since 4.7 */ - public function add_meta_boxes( $post_type ) { - if ( apply_filters( 'litespeed_bypass_metabox', false, $post_type ) ) { + public function add_meta_boxes($post_type) + { + if (apply_filters('litespeed_bypass_metabox', false, $post_type)) { return; } - add_meta_box( 'litespeed_meta_boxes', __( 'LiteSpeed Options', 'litespeed-cache' ), array( $this, 'meta_box_options' ), $post_type, 'side', 'core' ); + $post_type_obj = get_post_type_object($post_type); + if (!empty($post_type_obj) && !$post_type_obj->public) { + self::debug('post type public=false, bypass add_meta_boxes'); + return; + } + add_meta_box('litespeed_meta_boxes', __('LiteSpeed Options', 'litespeed-cache'), array($this, 'meta_box_options'), $post_type, 'side', 'core'); } /** * Show meta box content * @since 4.7 */ - public function meta_box_options() { + public function meta_box_options() + { require_once LSCWP_DIR . 'tpl/inc/metabox.php'; } @@ -65,28 +76,29 @@ public function meta_box_options() { * Save settings * @since 4.7 */ - public function save_meta_box_settings( $post_id, $post ) { + public function save_meta_box_settings($post_id, $post) + { global $pagenow; - self::debug( 'Maybe save post2 [post_id] ' . $post_id ); + self::debug('Maybe save post2 [post_id] ' . $post_id); - if ( $pagenow != 'post.php' || ! $post || ! is_object( $post ) ) { + if ($pagenow != 'post.php' || !$post || !is_object($post)) { return; } - if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { + if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } - if ( ! $this->cls( 'Router' )->verify_nonce( self::POST_NONCE_ACTION ) ) { + if (!$this->cls('Router')->verify_nonce(self::POST_NONCE_ACTION)) { return; } - self::debug( 'Saving post [post_id] ' . $post_id ); + self::debug('Saving post [post_id] ' . $post_id); - foreach ( $this->_postmeta_settings as $k => $v ) { - $val = isset( $_POST[ $k ] ) ? $_POST[ $k ] : false; - $this->save( $post_id, $k, $val ); + foreach ($this->_postmeta_settings as $k => $v) { + $val = isset($_POST[$k]) ? $_POST[$k] : false; + $this->save($post_id, $k, $val); } } @@ -94,16 +106,19 @@ public function save_meta_box_settings( $post_id, $post ) { * Load setting per post * @since 4.7 */ - public function setting( $conf, $post_id = false ) { + public function setting($conf, $post_id = false) + { // Check if has metabox non-cacheable setting or not - if ( ! $post_id ) { - if ( is_singular() ) { + if (!$post_id) { + $home_id = get_option('page_for_posts'); + if (is_singular()) { $post_id = get_the_ID(); - + } elseif ($home_id > 0 && is_home()) { + $post_id = $home_id; } } - if ( $post_id && $val = get_post_meta( $post_id, $conf, true ) ) { + if ($post_id && ($val = get_post_meta($post_id, $conf, true))) { return $val; } @@ -114,25 +129,25 @@ public function setting( $conf, $post_id = false ) { * Save a metabox value * @since 4.7 */ - public function save( $post_id, $name, $val, $is_append = false ) { - if( strpos( $name, 'litespeed_vpi_list' ) !== false ) { - $val = Utility::sanitize_lines( $val, 'basename,drop_webp' ); + public function save($post_id, $name, $val, $is_append = false) + { + if (strpos($name, 'litespeed_vpi_list') !== false) { + $val = Utility::sanitize_lines($val, 'basename,drop_webp'); } // Load existing data if has set - if ( $is_append ) { - $existing_data = $this->setting( $name, $post_id ); - if ( $existing_data ) { - $existing_data = Utility::sanitize_lines( $existing_data, 'basename' ); - $val = array_unique( array_merge( $val, $existing_data ) ); + if ($is_append) { + $existing_data = $this->setting($name, $post_id); + if ($existing_data) { + $existing_data = Utility::sanitize_lines($existing_data, 'basename'); + $val = array_unique(array_merge($val, $existing_data)); } } - if ( $val ) { - update_post_meta( $post_id, $name, $val ); - } - else { - delete_post_meta( $post_id, $name ); + if ($val) { + update_post_meta($post_id, $name, $val); + } else { + delete_post_meta($post_id, $name); } } @@ -140,25 +155,25 @@ public function save( $post_id, $name, $val, $is_append = false ) { * Load exclude images per post * @since 4.7 */ - public function lazy_img_excludes( $list ) { + public function lazy_img_excludes($list) + { $is_mobile = $this->_separate_mobile(); - $excludes = $this->setting( $is_mobile ? 'litespeed_vpi_list_mobile' : 'litespeed_vpi_list' ); - if ( $excludes !== null ) { - $excludes = Utility::sanitize_lines( $excludes, 'basename' ); - if ( $excludes ) { + $excludes = $this->setting($is_mobile ? 'litespeed_vpi_list_mobile' : 'litespeed_vpi_list'); + if ($excludes !== null) { + $excludes = Utility::sanitize_lines($excludes, 'basename'); + if ($excludes) { // Check if contains `data:` (invalid result, need to clear existing result) or not - if ( Utility::str_hit_array( 'data:', $excludes ) ) { - $this->cls( 'VPI' )->add_to_queue(); - } - else { - return array_merge( $list, $excludes ); + if (Utility::str_hit_array('data:', $excludes)) { + $this->cls('VPI')->add_to_queue(); + } else { + return array_merge($list, $excludes); } } return $list; } - $this->cls( 'VPI' )->add_to_queue(); + $this->cls('VPI')->add_to_queue(); return $list; } diff --git a/src/object-cache.cls.php b/src/object-cache.cls.php index 04f0f8a2e..3c457e0ef 100644 --- a/src/object-cache.cls.php +++ b/src/object-cache.cls.php @@ -8,22 +8,23 @@ * @author LiteSpeed Technologies */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; - -require_once dirname( __DIR__ ) . '/autoload.php'; - -class Object_Cache extends Root { - const O_OBJECT = 'object'; - const O_OBJECT_KIND = 'object-kind'; - const O_OBJECT_HOST = 'object-host'; - const O_OBJECT_PORT = 'object-port'; - const O_OBJECT_LIFE = 'object-life'; - const O_OBJECT_PERSISTENT = 'object-persistent'; - const O_OBJECT_ADMIN = 'object-admin'; - const O_OBJECT_TRANSIENTS = 'object-transients'; - const O_OBJECT_DB_ID = 'object-db_id'; - const O_OBJECT_USER = 'object-user'; - const O_OBJECT_PSWD = 'object-pswd'; +defined('WPINC') || exit(); + +require_once dirname(__DIR__) . '/autoload.php'; + +class Object_Cache extends Root +{ + const O_OBJECT = 'object'; + const O_OBJECT_KIND = 'object-kind'; + const O_OBJECT_HOST = 'object-host'; + const O_OBJECT_PORT = 'object-port'; + const O_OBJECT_LIFE = 'object-life'; + const O_OBJECT_PERSISTENT = 'object-persistent'; + const O_OBJECT_ADMIN = 'object-admin'; + const O_OBJECT_TRANSIENTS = 'object-transients'; + const O_OBJECT_DB_ID = 'object-db_id'; + const O_OBJECT_USER = 'object-user'; + const O_OBJECT_PSWD = 'object-pswd'; const O_OBJECT_GLOBAL_GROUPS = 'object-global_groups'; const O_OBJECT_NON_PERSISTENT_GROUPS = 'object-non_persistent_groups'; @@ -32,6 +33,7 @@ class Object_Cache extends Root { private $_cfg_method; private $_cfg_host; private $_cfg_port; + private $_cfg_life; private $_cfg_persistent; private $_cfg_admin; private $_cfg_transients; @@ -52,84 +54,82 @@ class Object_Cache extends Root { * * @since 1.8 */ - public function __construct( $cfg = false ) { - defined( 'LSCWP_LOG' ) && Debug2::debug2( '[Object] init' ); + public function __construct($cfg = false) + { + defined('LSCWP_LOG') && Debug2::debug2('[Object] init'); - if ( $cfg ) { - if ( ! is_array( $cfg[ Base::O_OBJECT_GLOBAL_GROUPS ] ) ) { - $cfg[ Base::O_OBJECT_GLOBAL_GROUPS ] = explode( "\n", $cfg[ Base::O_OBJECT_GLOBAL_GROUPS ] ); + if ($cfg) { + if (!is_array($cfg[Base::O_OBJECT_GLOBAL_GROUPS])) { + $cfg[Base::O_OBJECT_GLOBAL_GROUPS] = explode("\n", $cfg[Base::O_OBJECT_GLOBAL_GROUPS]); } - if ( ! is_array( $cfg[ Base::O_OBJECT_NON_PERSISTENT_GROUPS ] ) ) { - $cfg[ Base::O_OBJECT_NON_PERSISTENT_GROUPS ] = explode( "\n", $cfg[ Base::O_OBJECT_NON_PERSISTENT_GROUPS ] ); + if (!is_array($cfg[Base::O_OBJECT_NON_PERSISTENT_GROUPS])) { + $cfg[Base::O_OBJECT_NON_PERSISTENT_GROUPS] = explode("\n", $cfg[Base::O_OBJECT_NON_PERSISTENT_GROUPS]); } - $this->_cfg_method = $cfg[ Base::O_OBJECT_KIND ] ? true : false; - $this->_cfg_host = $cfg[ Base::O_OBJECT_HOST ]; - $this->_cfg_port = $cfg[ Base::O_OBJECT_PORT ]; - $this->_cfg_life = $cfg[ Base::O_OBJECT_LIFE ]; - $this->_cfg_persistent = $cfg[ Base::O_OBJECT_PERSISTENT ]; - $this->_cfg_admin = $cfg[ Base::O_OBJECT_ADMIN ]; - $this->_cfg_transients = $cfg[ Base::O_OBJECT_TRANSIENTS ]; - $this->_cfg_db = $cfg[ Base::O_OBJECT_DB_ID ]; - $this->_cfg_user = $cfg[ Base::O_OBJECT_USER ]; - $this->_cfg_pswd = $cfg[ Base::O_OBJECT_PSWD ]; - $this->_global_groups = $cfg[ Base::O_OBJECT_GLOBAL_GROUPS ]; - $this->_non_persistent_groups = $cfg[ Base::O_OBJECT_NON_PERSISTENT_GROUPS ]; - - if ( $this->_cfg_method ) { + $this->_cfg_method = $cfg[Base::O_OBJECT_KIND] ? true : false; + $this->_cfg_host = $cfg[Base::O_OBJECT_HOST]; + $this->_cfg_port = $cfg[Base::O_OBJECT_PORT]; + $this->_cfg_life = $cfg[Base::O_OBJECT_LIFE]; + $this->_cfg_persistent = $cfg[Base::O_OBJECT_PERSISTENT]; + $this->_cfg_admin = $cfg[Base::O_OBJECT_ADMIN]; + $this->_cfg_transients = $cfg[Base::O_OBJECT_TRANSIENTS]; + $this->_cfg_db = $cfg[Base::O_OBJECT_DB_ID]; + $this->_cfg_user = $cfg[Base::O_OBJECT_USER]; + $this->_cfg_pswd = $cfg[Base::O_OBJECT_PSWD]; + $this->_global_groups = $cfg[Base::O_OBJECT_GLOBAL_GROUPS]; + $this->_non_persistent_groups = $cfg[Base::O_OBJECT_NON_PERSISTENT_GROUPS]; + + if ($this->_cfg_method) { $this->_oc_driver = 'Redis'; } - $this->_cfg_enabled = $cfg[ Base::O_OBJECT ] && class_exists( $this->_oc_driver ) && $this->_cfg_host; + $this->_cfg_enabled = $cfg[Base::O_OBJECT] && class_exists($this->_oc_driver) && $this->_cfg_host; - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] init with cfg result : ', $this->_cfg_enabled ); + defined('LSCWP_LOG') && Debug2::debug('[Object] init with cfg result : ', $this->_cfg_enabled); } // If OC is OFF, will hit here to init OC after conf initialized - elseif ( defined( 'LITESPEED_CONF_LOADED' ) ) { - $this->_cfg_method = $this->conf( Base::O_OBJECT_KIND ) ? true : false; - $this->_cfg_host = $this->conf( Base::O_OBJECT_HOST ); - $this->_cfg_port = $this->conf( Base::O_OBJECT_PORT ); - $this->_cfg_life = $this->conf( Base::O_OBJECT_LIFE ); - $this->_cfg_persistent = $this->conf( Base::O_OBJECT_PERSISTENT ); - $this->_cfg_admin = $this->conf( Base::O_OBJECT_ADMIN ); - $this->_cfg_transients = $this->conf( Base::O_OBJECT_TRANSIENTS ); - $this->_cfg_db = $this->conf( Base::O_OBJECT_DB_ID ); - $this->_cfg_user = $this->conf( Base::O_OBJECT_USER ); - $this->_cfg_pswd = $this->conf( Base::O_OBJECT_PSWD ); - $this->_global_groups = $this->conf( Base::O_OBJECT_GLOBAL_GROUPS ); - $this->_non_persistent_groups = $this->conf( Base::O_OBJECT_NON_PERSISTENT_GROUPS ); - - if ( $this->_cfg_method ) { + elseif (defined('LITESPEED_CONF_LOADED')) { + $this->_cfg_method = $this->conf(Base::O_OBJECT_KIND) ? true : false; + $this->_cfg_host = $this->conf(Base::O_OBJECT_HOST); + $this->_cfg_port = $this->conf(Base::O_OBJECT_PORT); + $this->_cfg_life = $this->conf(Base::O_OBJECT_LIFE); + $this->_cfg_persistent = $this->conf(Base::O_OBJECT_PERSISTENT); + $this->_cfg_admin = $this->conf(Base::O_OBJECT_ADMIN); + $this->_cfg_transients = $this->conf(Base::O_OBJECT_TRANSIENTS); + $this->_cfg_db = $this->conf(Base::O_OBJECT_DB_ID); + $this->_cfg_user = $this->conf(Base::O_OBJECT_USER); + $this->_cfg_pswd = $this->conf(Base::O_OBJECT_PSWD); + $this->_global_groups = $this->conf(Base::O_OBJECT_GLOBAL_GROUPS); + $this->_non_persistent_groups = $this->conf(Base::O_OBJECT_NON_PERSISTENT_GROUPS); + + if ($this->_cfg_method) { $this->_oc_driver = 'Redis'; } - $this->_cfg_enabled = $this->conf( Base::O_OBJECT ) && class_exists( $this->_oc_driver ) && $this->_cfg_host; - } - elseif ( defined( 'self::CONF_FILE' ) && file_exists( WP_CONTENT_DIR . '/' . self::CONF_FILE ) ) { // Get cfg from _data_file + $this->_cfg_enabled = $this->conf(Base::O_OBJECT) && class_exists($this->_oc_driver) && $this->_cfg_host; + } elseif (defined('self::CONF_FILE') && file_exists(WP_CONTENT_DIR . '/' . self::CONF_FILE)) { + // Get cfg from _data_file // Use self::const to avoid loading more classes - $cfg = json_decode( file_get_contents( WP_CONTENT_DIR . '/' . self::CONF_FILE ), true ); - if ( ! empty( $cfg[ self::O_OBJECT_HOST ] ) ) { - $this->_cfg_method = ! empty( $cfg[ self::O_OBJECT_KIND ] ) ? $cfg[ self::O_OBJECT_KIND ] : false; - $this->_cfg_host = $cfg[ self::O_OBJECT_HOST ]; - $this->_cfg_port = $cfg[ self::O_OBJECT_PORT ]; - $this->_cfg_life = ! empty( $cfg[ self::O_OBJECT_LIFE ] ) ? $cfg[ self::O_OBJECT_LIFE ] : $this->_default_life; - $this->_cfg_persistent = ! empty( $cfg[ self::O_OBJECT_PERSISTENT ] ) ? $cfg[ self::O_OBJECT_PERSISTENT ] : false; - $this->_cfg_admin = ! empty( $cfg[ self::O_OBJECT_ADMIN ] ) ? $cfg[ self::O_OBJECT_ADMIN ] : false; - $this->_cfg_transients = ! empty( $cfg[ self::O_OBJECT_TRANSIENTS ] ) ? $cfg[ self::O_OBJECT_TRANSIENTS ] : false; - $this->_cfg_db = ! empty( $cfg[ self::O_OBJECT_DB_ID ] ) ? $cfg[ self::O_OBJECT_DB_ID ] : 0; - $this->_cfg_user = ! empty( $cfg[ self::O_OBJECT_USER ] ) ? $cfg[ self::O_OBJECT_USER ] : ''; - $this->_cfg_pswd = ! empty( $cfg[ self::O_OBJECT_PSWD ] ) ? $cfg[ self::O_OBJECT_PSWD ] : ''; - $this->_global_groups = ! empty( $cfg[ self::O_OBJECT_GLOBAL_GROUPS ] ) ? $cfg[ self::O_OBJECT_GLOBAL_GROUPS ] : array(); - $this->_non_persistent_groups = ! empty( $cfg[ self::O_OBJECT_NON_PERSISTENT_GROUPS ] ) ? $cfg[ self::O_OBJECT_NON_PERSISTENT_GROUPS ] : array(); - - if ( $this->_cfg_method ) { + $cfg = json_decode(file_get_contents(WP_CONTENT_DIR . '/' . self::CONF_FILE), true); + if (!empty($cfg[self::O_OBJECT_HOST])) { + $this->_cfg_method = !empty($cfg[self::O_OBJECT_KIND]) ? $cfg[self::O_OBJECT_KIND] : false; + $this->_cfg_host = $cfg[self::O_OBJECT_HOST]; + $this->_cfg_port = $cfg[self::O_OBJECT_PORT]; + $this->_cfg_life = !empty($cfg[self::O_OBJECT_LIFE]) ? $cfg[self::O_OBJECT_LIFE] : $this->_default_life; + $this->_cfg_persistent = !empty($cfg[self::O_OBJECT_PERSISTENT]) ? $cfg[self::O_OBJECT_PERSISTENT] : false; + $this->_cfg_admin = !empty($cfg[self::O_OBJECT_ADMIN]) ? $cfg[self::O_OBJECT_ADMIN] : false; + $this->_cfg_transients = !empty($cfg[self::O_OBJECT_TRANSIENTS]) ? $cfg[self::O_OBJECT_TRANSIENTS] : false; + $this->_cfg_db = !empty($cfg[self::O_OBJECT_DB_ID]) ? $cfg[self::O_OBJECT_DB_ID] : 0; + $this->_cfg_user = !empty($cfg[self::O_OBJECT_USER]) ? $cfg[self::O_OBJECT_USER] : ''; + $this->_cfg_pswd = !empty($cfg[self::O_OBJECT_PSWD]) ? $cfg[self::O_OBJECT_PSWD] : ''; + $this->_global_groups = !empty($cfg[self::O_OBJECT_GLOBAL_GROUPS]) ? $cfg[self::O_OBJECT_GLOBAL_GROUPS] : array(); + $this->_non_persistent_groups = !empty($cfg[self::O_OBJECT_NON_PERSISTENT_GROUPS]) ? $cfg[self::O_OBJECT_NON_PERSISTENT_GROUPS] : array(); + + if ($this->_cfg_method) { $this->_oc_driver = 'Redis'; } - $this->_cfg_enabled = class_exists( $this->_oc_driver ) && $this->_cfg_host; - } - else { + $this->_cfg_enabled = class_exists($this->_oc_driver) && $this->_cfg_host; + } else { $this->_cfg_enabled = false; } - - } - else { + } else { $this->_cfg_enabled = false; } } @@ -140,8 +140,9 @@ public function __construct( $cfg = false ) { * @since 1.8.3 * @access public */ - public function store_transients( $group ) { - return $this->_cfg_transients && $this->_is_transients_group( $group ); + public function store_transients($group) + { + return $this->_cfg_transients && $this->_is_transients_group($group); } /** @@ -150,8 +151,9 @@ public function store_transients( $group ) { * @since 1.8.3 * @access private */ - private function _is_transients_group( $group ) { - return in_array( $group, array( 'transient', 'site-transient' ) ); + private function _is_transients_group($group) + { + return in_array($group, array('transient', 'site-transient')); } /** @@ -160,7 +162,8 @@ private function _is_transients_group( $group ) { * @since 1.8 * @access public */ - public function update_file( $options ) { + public function update_file($options) + { $changed = false; // NOTE: When included in oc.php, `LSCWP_DIR` will show undefined, so this must be assigned/generated when used @@ -168,9 +171,9 @@ public function update_file( $options ) { $_oc_wp_file = WP_CONTENT_DIR . '/object-cache.php'; // Update cls file - if ( ! file_exists( $_oc_wp_file ) || md5_file( $_oc_wp_file ) !== md5_file( $_oc_ori_file ) ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] copying object-cache.php file to ' . $_oc_wp_file ); - copy( $_oc_ori_file, $_oc_wp_file ); + if (!file_exists($_oc_wp_file) || md5_file($_oc_wp_file) !== md5_file($_oc_ori_file)) { + defined('LSCWP_LOG') && Debug2::debug('[Object] copying object-cache.php file to ' . $_oc_wp_file); + copy($_oc_ori_file, $_oc_wp_file); $changed = true; } @@ -178,8 +181,8 @@ public function update_file( $options ) { /** * Clear object cache */ - if ( $changed ) { - $this->_reconnect( $options ); + if ($changed) { + $this->_reconnect($options); } } @@ -189,14 +192,15 @@ public function update_file( $options ) { * @since 1.8.2 * @access public */ - public function del_file() { + public function del_file() + { // NOTE: When included in oc.php, `LSCWP_DIR` will show undefined, so this must be assigned/generated when used $_oc_ori_file = LSCWP_DIR . 'lib/object-cache.php'; $_oc_wp_file = WP_CONTENT_DIR . '/object-cache.php'; - if ( file_exists( $_oc_wp_file ) && md5_file( $_oc_wp_file ) === md5_file( $_oc_ori_file ) ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] removing ' . $_oc_wp_file ); - unlink( $_oc_wp_file ); + if (file_exists($_oc_wp_file) && md5_file($_oc_wp_file) === md5_file($_oc_ori_file)) { + defined('LSCWP_LOG') && Debug2::debug('[Object] removing ' . $_oc_wp_file); + unlink($_oc_wp_file); } } @@ -206,7 +210,8 @@ public function del_file() { * @since 1.8 * @access public */ - public function test_connection() { + public function test_connection() + { return $this->_connect(); } @@ -216,23 +221,23 @@ public function test_connection() { * @since 1.8 * @access private */ - private function _reconnect( $cfg ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] Reconnecting' ); + private function _reconnect($cfg) + { + defined('LSCWP_LOG') && Debug2::debug('[Object] Reconnecting'); // error_log( 'Object: reconnect !' ); - if ( isset( $this->_conn ) ) { + if (isset($this->_conn)) { // error_log( 'Object: Quiting existing connection!' ); - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] Quiting existing connection' ); + defined('LSCWP_LOG') && Debug2::debug('[Object] Quiting existing connection'); $this->flush(); $this->_conn = null; - $this->cls( false, true ); + $this->cls(false, true); } - $cls = $this->cls( false, false, $cfg ); + $cls = $this->cls(false, false, $cfg); $cls->_connect(); - if ( isset( $cls->_conn ) ) { + if (isset($cls->_conn)) { $cls->flush(); } - } /** @@ -241,21 +246,22 @@ private function _reconnect( $cfg ) { * @since 1.8 * @access private */ - private function _connect() { - if ( isset( $this->_conn ) ) { + private function _connect() + { + if (isset($this->_conn)) { // error_log( 'Object: _connected' ); return true; } - if ( ! class_exists( $this->_oc_driver ) || ! $this->_cfg_host ) { + if (!class_exists($this->_oc_driver) || !$this->_cfg_host) { return null; } - if ( defined( 'LITESPEED_OC_FAILURE' ) ) { + if (defined('LITESPEED_OC_FAILURE')) { return false; } - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] connecting to ' . $this->_cfg_host . ':' . $this->_cfg_port ); + defined('LSCWP_LOG') && Debug2::debug('[Object] connecting to ' . $this->_cfg_host . ':' . $this->_cfg_port); $failed = false; /** @@ -264,108 +270,99 @@ private function _connect() { * @since 1.8.1 * @see https://github.com/phpredis/phpredis/#example-1 */ - if ( $this->_oc_driver == 'Redis' ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] Init ' . $this->_oc_driver . ' connection' ); + if ($this->_oc_driver == 'Redis') { + defined('LSCWP_LOG') && Debug2::debug('[Object] Init ' . $this->_oc_driver . ' connection'); - set_error_handler( 'litespeed_exception_handler' ); + set_error_handler('litespeed_exception_handler'); try { $this->_conn = new \Redis(); - // error_log( 'Object: _connect Redis' ); + // error_log( 'Object: _connect Redis' ); - if ( $this->_cfg_persistent ) { - if ( $this->_cfg_port ) { - $this->_conn->pconnect( $this->_cfg_host, $this->_cfg_port ); + if ($this->_cfg_persistent) { + if ($this->_cfg_port) { + $this->_conn->pconnect($this->_cfg_host, $this->_cfg_port); + } else { + $this->_conn->pconnect($this->_cfg_host); } - else { - $this->_conn->pconnect( $this->_cfg_host ); - } - } - else { - if ( $this->_cfg_port ) { - $this->_conn->connect( $this->_cfg_host, $this->_cfg_port ); - } - else { - $this->_conn->connect( $this->_cfg_host ); + } else { + if ($this->_cfg_port) { + $this->_conn->connect($this->_cfg_host, $this->_cfg_port); + } else { + $this->_conn->connect($this->_cfg_host); } } - if ( $this->_cfg_pswd ) { - $this->_conn->auth( $this->_cfg_pswd ); + if ($this->_cfg_pswd) { + $this->_conn->auth($this->_cfg_pswd); } - if ( $this->_cfg_db ) { - $this->_conn->select( $this->_cfg_db ); + if ($this->_cfg_db) { + $this->_conn->select($this->_cfg_db); } $res = $this->_conn->ping(); - if ( $res != '+PONG' ) { + if ($res != '+PONG') { $failed = true; } - } - catch ( \Exception $e ) { - error_log( $e->getMessage() ); + } catch (\Exception $e) { + error_log($e->getMessage()); $failed = true; - } - catch ( \ErrorException $e ) { - error_log( $e->getMessage() ); + } catch (\ErrorException $e) { + error_log($e->getMessage()); $failed = true; } restore_error_handler(); - - } - /** + } /** * Connect to Memcached - */ - else { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] Init ' . $this->_oc_driver . ' connection' ); - if ( $this->_cfg_persistent ) { - $this->_conn = new \Memcached( $this->_get_mem_id() ); + */ else { + defined('LSCWP_LOG') && Debug2::debug('[Object] Init ' . $this->_oc_driver . ' connection'); + if ($this->_cfg_persistent) { + $this->_conn = new \Memcached($this->_get_mem_id()); // Check memcached persistent connection - if ( $this->_validate_mem_server() ) { + if ($this->_validate_mem_server()) { // error_log( 'Object: _validate_mem_server' ); - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] Got persistent ' . $this->_oc_driver . ' connection' ); + defined('LSCWP_LOG') && Debug2::debug('[Object] Got persistent ' . $this->_oc_driver . ' connection'); return true; } - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] No persistent ' . $this->_oc_driver . ' server list!' ); - } - else { + defined('LSCWP_LOG') && Debug2::debug('[Object] No persistent ' . $this->_oc_driver . ' server list!'); + } else { // error_log( 'Object: new memcached!' ); - $this->_conn = new \Memcached; + $this->_conn = new \Memcached(); } - $this->_conn->addServer( $this->_cfg_host, (int) $this->_cfg_port ); + $this->_conn->addServer($this->_cfg_host, (int) $this->_cfg_port); /** * Add SASL auth * @since 1.8.1 * @since 2.9.6 Fixed SASL connection @see https://www.litespeedtech.com/support/wiki/doku.php/litespeed_wiki:lsmcd:new_sasl */ - if ( $this->_cfg_user && $this->_cfg_pswd && method_exists( $this->_conn, 'setSaslAuthData' ) ) { - $this->_conn->setOption( \Memcached::OPT_BINARY_PROTOCOL, true ); - $this->_conn->setOption( \Memcached::OPT_COMPRESSION, false ); - $this->_conn->setSaslAuthData( $this->_cfg_user, $this->_cfg_pswd ); + if ($this->_cfg_user && $this->_cfg_pswd && method_exists($this->_conn, 'setSaslAuthData')) { + $this->_conn->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); + $this->_conn->setOption(\Memcached::OPT_COMPRESSION, false); + $this->_conn->setSaslAuthData($this->_cfg_user, $this->_cfg_pswd); } // Check connection - if ( ! $this->_validate_mem_server() ) { + if (!$this->_validate_mem_server()) { $failed = true; } } // If failed to connect - if ( $failed ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] Failed to connect ' . $this->_oc_driver . ' server!' ); + if ($failed) { + defined('LSCWP_LOG') && Debug2::debug('[Object] Failed to connect ' . $this->_oc_driver . ' server!'); $this->_conn = null; $this->_cfg_enabled = false; - ! defined( 'LITESPEED_OC_FAILURE' ) && define( 'LITESPEED_OC_FAILURE', true ); + !defined('LITESPEED_OC_FAILURE') && define('LITESPEED_OC_FAILURE', true); // error_log( 'Object: false!' ); return false; } - defined( 'LSCWP_LOG' ) && Debug2::debug2( '[Object] Connected' ); + defined('LSCWP_LOG') && Debug2::debug2('[Object] Connected'); return true; } @@ -376,17 +373,18 @@ private function _connect() { * @since 1.8 * @access private */ - private function _validate_mem_server() { + private function _validate_mem_server() + { $mem_list = $this->_conn->getStats(); - if ( empty( $mem_list ) ) { + if (empty($mem_list)) { return false; } - foreach ( $mem_list as $k => $v ) { - if ( substr( $k, 0, strlen( $this->_cfg_host ) ) != $this->_cfg_host ) { + foreach ($mem_list as $k => $v) { + if (substr($k, 0, strlen($this->_cfg_host)) != $this->_cfg_host) { continue; } - if ( $v[ 'pid' ] > 0 ) { + if (!empty($v['pid']) || !empty($v['curr_connections'])) { return true; } } @@ -400,9 +398,10 @@ private function _validate_mem_server() { * @since 1.8 * @access private */ - private function _get_mem_id() { + private function _get_mem_id() + { $mem_id = 'litespeed'; - if ( is_multisite() ) { + if (is_multisite()) { $mem_id .= '_' . get_current_blog_id(); } @@ -415,22 +414,23 @@ private function _get_mem_id() { * @since 1.8 * @access public */ - public function get( $key ) { - if ( ! $this->_cfg_enabled ) { + public function get($key) + { + if (!$this->_cfg_enabled) { return null; } - if ( ! $this->_can_cache() ) { + if (!$this->_can_cache()) { return null; } - if( ! $this->_connect() ) { + if (!$this->_connect()) { return null; } // defined( 'LSCWP_LOG' ) && Debug2::debug2( '[Object] get ' . $key ); - $res = $this->_conn->get( $key ); + $res = $this->_conn->get($key); return $res; } @@ -441,8 +441,9 @@ public function get( $key ) { * @since 1.8 * @access public */ - public function set( $key, $data, $expire ) { - if ( ! $this->_cfg_enabled ) { + public function set($key, $data, $expire) + { + if (!$this->_cfg_enabled) { return null; } @@ -454,7 +455,7 @@ public function set( $key, $data, $expire ) { // return null; // } - if( ! $this->_connect() ) { + if (!$this->_connect()) { return null; } @@ -464,15 +465,17 @@ public function set( $key, $data, $expire ) { $ttl = $expire ?: $this->_cfg_life; - if ( $this->_oc_driver == 'Redis' ) { + if ($this->_oc_driver == 'Redis') { try { - $res = $this->_conn->setEx( $key, $ttl, $data ); - } catch ( \RedisException $ex ) { - throw new \Exception( $ex->getMessage(), $ex->getCode(), $ex ); + $res = $this->_conn->setEx($key, $ttl, $data); + } catch (\RedisException $ex) { + $res = false; + $msg = sprintf(__('Redis encountered a fatal error: %s (code: %d)', 'litespeed-cache'), $ex->getMessage(), $ex->getCode()); + Debug2::debug('[Object] ' . $msg); + Admin_Display::error($msg); } - } - else { - $res = $this->_conn->set( $key, $data, $ttl ); + } else { + $res = $this->_conn->set($key, $data, $ttl); } return $res; @@ -484,8 +487,9 @@ public function set( $key, $data, $expire ) { * @since 1.8 * @access private */ - private function _can_cache() { - if ( ! $this->_cfg_admin && defined( 'WP_ADMIN' ) ) { + private function _can_cache() + { + if (!$this->_cfg_admin && defined('WP_ADMIN')) { return false; } return true; @@ -497,25 +501,25 @@ private function _can_cache() { * @since 1.8 * @access public */ - public function delete( $key ) { - if ( ! $this->_cfg_enabled ) { + public function delete($key) + { + if (!$this->_cfg_enabled) { return null; } - if( ! $this->_connect() ) { + if (!$this->_connect()) { return null; } // defined( 'LSCWP_LOG' ) && Debug2::debug2( '[Object] delete ' . $key ); - if ( $this->_oc_driver == 'Redis' ) { - $res = $this->_conn->del( $key ); - } - else { - $res = $this->_conn->delete( $key ); + if ($this->_oc_driver == 'Redis') { + $res = $this->_conn->del($key); + } else { + $res = $this->_conn->delete($key); } - return $res; + return (bool) $res; } /** @@ -524,22 +528,22 @@ public function delete( $key ) { * @since 1.8 * @access public */ - public function flush() { - if ( ! $this->_cfg_enabled ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] bypass flushing' ); + public function flush() + { + if (!$this->_cfg_enabled) { + defined('LSCWP_LOG') && Debug2::debug('[Object] bypass flushing'); return null; } - if( ! $this->_connect() ) { + if (!$this->_connect()) { return null; } - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Object] flush!' ); + defined('LSCWP_LOG') && Debug2::debug('[Object] flush!'); - if ( $this->_oc_driver == 'Redis' ) { + if ($this->_oc_driver == 'Redis') { $res = $this->_conn->flushDb(); - } - else { + } else { $res = $this->_conn->flush(); $this->_conn->resetServerList(); } @@ -553,13 +557,14 @@ public function flush() { * @since 1.8 * @access public */ - public function add_global_groups( $groups ) { - if ( ! is_array( $groups ) ) { - $groups = array( $groups ); + public function add_global_groups($groups) + { + if (!is_array($groups)) { + $groups = array($groups); } - $this->_global_groups = array_merge( $this->_global_groups, $groups ); - $this->_global_groups = array_unique( $this->_global_groups ); + $this->_global_groups = array_merge($this->_global_groups, $groups); + $this->_global_groups = array_unique($this->_global_groups); } /** @@ -568,8 +573,9 @@ public function add_global_groups( $groups ) { * @since 1.8 * @access public */ - public function is_global( $group ) { - return in_array( $group, $this->_global_groups ); + public function is_global($group) + { + return in_array($group, $this->_global_groups); } /** @@ -578,13 +584,14 @@ public function is_global( $group ) { * @since 1.8 * @access public */ - public function add_non_persistent_groups( $groups ) { - if ( ! is_array( $groups ) ) { - $groups = array( $groups ); + public function add_non_persistent_groups($groups) + { + if (!is_array($groups)) { + $groups = array($groups); } - $this->_non_persistent_groups = array_merge( $this->_non_persistent_groups, $groups ); - $this->_non_persistent_groups = array_unique( $this->_non_persistent_groups ); + $this->_non_persistent_groups = array_merge($this->_non_persistent_groups, $groups); + $this->_non_persistent_groups = array_unique($this->_non_persistent_groups); } /** @@ -593,8 +600,8 @@ public function add_non_persistent_groups( $groups ) { * @since 1.8 * @access public */ - public function is_non_persistent( $group ) { - return in_array( $group, $this->_non_persistent_groups ); + public function is_non_persistent($group) + { + return in_array($group, $this->_non_persistent_groups); } - -} \ No newline at end of file +} diff --git a/src/object.lib.php b/src/object.lib.php index c178fe695..eba7608d1 100644 --- a/src/object.lib.php +++ b/src/object.lib.php @@ -4,13 +4,14 @@ * * @since 1.8 */ -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); /** * Handle exception */ -if ( ! function_exists( 'litespeed_exception_handler' ) ) { - function litespeed_exception_handler( $errno, $errstr, $errfile, $errline ) { +if (!function_exists('litespeed_exception_handler')) { + function litespeed_exception_handler($errno, $errstr, $errfile, $errline) + { throw new \ErrorException($errstr, 0, $errno, $errfile, $errline); } } @@ -21,151 +22,405 @@ function litespeed_exception_handler( $errno, $errstr, $errfile, $errline ) { * Sets up Object Cache Global and assigns it. * * @since 1.8 + * + * @global WP_Object_Cache $wp_object_cache */ -function wp_cache_init() { +function wp_cache_init() +{ $GLOBALS['wp_object_cache'] = WP_Object_Cache::get_instance(); } /** - * Retrieves the cache contents from the cache by key and group. + * Adds data to the cache, if the cache key doesn't already exist. * * @since 1.8 + * + * @see WP_Object_Cache::add() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The cache key to use for retrieval later. + * @param mixed $data The data to add to the cache. + * @param string $group Optional. The group to add the cache to. Enables the same key + * to be used across groups. Default empty. + * @param int $expire Optional. When the cache data should expire, in seconds. + * Default 0 (no expiration). + * @return bool True on success, false if cache key and group already exist. */ -function wp_cache_get( $key, $group = '', $force = false, &$found = null ) { +function wp_cache_add($key, $data, $group = '', $expire = 0) +{ global $wp_object_cache; - return $wp_object_cache->get( $key, $group, $force, $found ); + return $wp_object_cache->add($key, $data, $group, (int) $expire); } /** - * Saves the data to the cache. + * Adds multiple values to the cache in one call. * - * @since 1.8 + * @since 5.4 + * + * @see WP_Object_Cache::add_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $data Array of keys and values to be set. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool[] Array of return values, grouped by key. Each value is either + * true on success, or false if cache key and group already exist. */ -function wp_cache_set( $key, $data, $group = '', $expire = 0 ) { +function wp_cache_add_multiple(array $data, $group = '', $expire = 0) +{ global $wp_object_cache; - return $wp_object_cache->set( $key, $data, $group, $expire ); + return $wp_object_cache->add_multiple($data, $group, $expire); } /** - * Adds data to the cache, if the cache key doesn't already exist. + * Replaces the contents of the cache with new data. * * @since 1.8 + * + * @see WP_Object_Cache::replace() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The key for the cache data that should be replaced. + * @param mixed $data The new data to store in the cache. + * @param string $group Optional. The group for the cache data that should be replaced. + * Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool True if contents were replaced, false if original value does not exist. */ -function wp_cache_add( $key, $data, $group = '', $expire = 0 ) { +function wp_cache_replace($key, $data, $group = '', $expire = 0) +{ global $wp_object_cache; - return $wp_object_cache->add( $key, $data, $group, $expire ); + return $wp_object_cache->replace($key, $data, $group, (int) $expire); } /** - * Replaces the contents of the cache with new data. + * Saves the data to the cache. + * + * Differs from wp_cache_add() and wp_cache_replace() in that it will always write data. * * @since 1.8 + * + * @see WP_Object_Cache::set() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The cache key to use for retrieval later. + * @param mixed $data The contents to store in the cache. + * @param string $group Optional. Where to group the cache contents. Enables the same key + * to be used across groups. Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool True on success, false on failure. */ -function wp_cache_replace( $key, $data, $group = '', $expire = 0 ) { +function wp_cache_set($key, $data, $group = '', $expire = 0) +{ global $wp_object_cache; - return $wp_object_cache->replace( $key, $data, $group, $expire ); + return $wp_object_cache->set($key, $data, $group, (int) $expire); } /** - * Increment numeric cache item's value + * Sets multiple values to the cache in one call. * - * @since 1.8 + * @since 5.4 + * + * @see WP_Object_Cache::set_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $data Array of keys and values to be set. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool[] Array of return values, grouped by key. Each value is either + * true on success, or false on failure. */ -function wp_cache_incr( $key, $offset = 1, $group = '' ) { +function wp_cache_set_multiple(array $data, $group = '', $expire = 0) +{ global $wp_object_cache; - return $wp_object_cache->incr_desr( $key, $offset, $group ); + return $wp_object_cache->set_multiple($data, $group, $expire); } /** - * Decrements numeric cache item's value. + * Retrieves the cache contents from the cache by key and group. * * @since 1.8 + * + * @see WP_Object_Cache::get() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The key under which the cache contents are stored. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @param bool $force Optional. Whether to force an update of the local cache + * from the persistent cache. Default false. + * @param bool $found Optional. Whether the key was found in the cache (passed by reference). + * Disambiguates a return of false, a storable value. Default null. + * @return mixed|false The cache contents on success, false on failure to retrieve contents. */ -function wp_cache_decr( $key, $offset = 1, $group = '' ) { +function wp_cache_get($key, $group = '', $force = false, &$found = null) +{ global $wp_object_cache; - return $wp_object_cache->incr_desr( $key, $offset, $group, false ); + return $wp_object_cache->get($key, $group, $force, $found); +} + +/** + * Retrieves multiple values from the cache in one call. + * + * @since 5.4 + * + * @see WP_Object_Cache::get_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $keys Array of keys under which the cache contents are stored. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @param bool $force Optional. Whether to force an update of the local cache + * from the persistent cache. Default false. + * @return array Array of return values, grouped by key. Each value is either + * the cache contents on success, or false on failure. + */ +function wp_cache_get_multiple($keys, $group = '', $force = false) +{ + global $wp_object_cache; + + return $wp_object_cache->get_multiple($keys, $group, $force); } /** * Removes the cache contents matching key and group. * * @since 1.8 + * + * @see WP_Object_Cache::delete() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key What the contents in the cache are called. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @return bool True on successful removal, false on failure. */ -function wp_cache_delete( $key, $group = '' ) { +function wp_cache_delete($key, $group = '') +{ global $wp_object_cache; - return $wp_object_cache->delete( $key, $group ); + return $wp_object_cache->delete($key, $group); } /** - * Removes all cache items. + * Deletes multiple values from the cache in one call. + * + * @since 5.4 + * + * @see WP_Object_Cache::delete_multiple() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param array $keys Array of keys under which the cache to deleted. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @return bool[] Array of return values, grouped by key. Each value is either + * true on success, or false if the contents were not deleted. + */ +function wp_cache_delete_multiple(array $keys, $group = '') +{ + global $wp_object_cache; + + return $wp_object_cache->delete_multiple($keys, $group); +} + +/** + * Increments numeric cache item's value. * * @since 1.8 + * + * @see WP_Object_Cache::incr() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The key for the cache contents that should be incremented. + * @param int $offset Optional. The amount by which to increment the item's value. + * Default 1. + * @param string $group Optional. The group the key is in. Default empty. + * @return int|false The item's new value on success, false on failure. */ -function wp_cache_flush() { +function wp_cache_incr($key, $offset = 1, $group = '') +{ global $wp_object_cache; - return $wp_object_cache->flush(); + return $wp_object_cache->incr($key, $offset, $group); } /** - * Adds a group or set of groups to the list of global groups. + * Decrements numeric cache item's value. * * @since 1.8 + * + * @see WP_Object_Cache::decr() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int|string $key The cache key to decrement. + * @param int $offset Optional. The amount by which to decrement the item's value. + * Default 1. + * @param string $group Optional. The group the key is in. Default empty. + * @return int|false The item's new value on success, false on failure. */ -function wp_cache_add_global_groups( $groups ) { +function wp_cache_decr($key, $offset = 1, $group = '') +{ global $wp_object_cache; - $wp_object_cache->add_global_groups( $groups ); + return $wp_object_cache->decr($key, $offset, $group); } /** - * Adds a group or set of groups to the list of non-persistent groups. + * Removes all cache items. * * @since 1.8 + * + * @see WP_Object_Cache::flush() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @return bool True on success, false on failure. */ -function wp_cache_add_non_persistent_groups( $groups ) { +function wp_cache_flush() +{ global $wp_object_cache; - $wp_object_cache->add_non_persistent_groups( $groups ); + return $wp_object_cache->flush(); } /** - * Switches the internal blog ID. + * Removes all cache items from the in-memory runtime cache. * - * This changes the blog id used to create keys in blog specific groups. + * @since 5.4 * - * @since 1.8 + * @see WP_Object_Cache::flush_runtime() * - * @see WP_Object_Cache::switch_to_blog() + * @return bool True on success, false on failure. + */ +function wp_cache_flush_runtime() +{ + global $wp_object_cache; + + return $wp_object_cache->flush_runtime(); +} + +/** + * Removes all cache items in a group, if the object cache implementation supports it. + * + * Before calling this function, always check for group flushing support using the + * `wp_cache_supports( 'flush_group' )` function. + * + * @since 5.4 + * + * @see WP_Object_Cache::flush_group() * @global WP_Object_Cache $wp_object_cache Object cache global instance. * - * @param int $blog_id Site ID. + * @param string $group Name of group to remove from cache. + * @return bool True if group was flushed, false otherwise. */ -function wp_cache_switch_to_blog( $blog_id ) { +function wp_cache_flush_group($group) +{ global $wp_object_cache; - $wp_object_cache->switch_to_blog( $blog_id ); + return $wp_object_cache->flush_group($group); +} + +/** + * Determines whether the object cache implementation supports a particular feature. + * + * @since 5.4 + * + * @param string $feature Name of the feature to check for. Possible values include: + * 'add_multiple', 'set_multiple', 'get_multiple', 'delete_multiple', + * 'flush_runtime', 'flush_group'. + * @return bool True if the feature is supported, false otherwise. + */ +function wp_cache_supports($feature) +{ + switch ($feature) { + case 'add_multiple': + case 'set_multiple': + case 'get_multiple': + case 'delete_multiple': + case 'flush_runtime': + return true; + + case 'flush_group': + default: + return false; + } } /** * Closes the cache. * + * This function has ceased to do anything since WordPress 2.5. The + * functionality was removed along with the rest of the persistent cache. + * + * This does not mean that plugins can't implement this function when they need + * to make sure that the cache is cleaned up after WordPress no longer needs it. + * * @since 1.8 + * + * @return true Always returns true. */ -function wp_cache_close() { +function wp_cache_close() +{ return true; } +/** + * Adds a group or set of groups to the list of global groups. + * + * @since 1.8 + * + * @see WP_Object_Cache::add_global_groups() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param string|string[] $groups A group or an array of groups to add. + */ +function wp_cache_add_global_groups($groups) +{ + global $wp_object_cache; + $wp_object_cache->add_global_groups($groups); +} -class WP_Object_Cache { +/** + * Adds a group or set of groups to the list of non-persistent groups. + * + * @since 1.8 + * + * @param string|string[] $groups A group or an array of groups to add. + */ +function wp_cache_add_non_persistent_groups($groups) +{ + global $wp_object_cache; + + $wp_object_cache->add_non_persistent_groups($groups); +} + +/** + * Switches the internal blog ID. + * + * This changes the blog id used to create keys in blog specific groups. + * + * @since 1.8 + * + * @see WP_Object_Cache::switch_to_blog() + * @global WP_Object_Cache $wp_object_cache Object cache global instance. + * + * @param int $blog_id Site ID. + */ +function wp_cache_switch_to_blog($blog_id) +{ + global $wp_object_cache; + + $wp_object_cache->switch_to_blog($blog_id); +} + +class WP_Object_Cache +{ protected static $_instance; private $_object_cache; @@ -180,14 +435,17 @@ class WP_Object_Cache { private $count_miss = 0; private $count_set = 0; + protected $global_groups = array(); private $blog_prefix; + private $multisite; /** - * Init + * Init. * * @since 1.8 */ - public function __construct() { + public function __construct() + { $this->_object_cache = \LiteSpeed\Object_Cache::cls(); $this->multisite = is_multisite(); @@ -197,264 +455,640 @@ public function __construct() { * Fix multiple instance using same oc issue * @since 1.8.2 */ - ! defined( 'LSOC_PREFIX' ) && define( 'LSOC_PREFIX', substr( md5( __FILE__ ), -5 ) ); + !defined('LSOC_PREFIX') && define('LSOC_PREFIX', substr(md5(__FILE__), -5)); } /** - * Output debug info + * Makes private properties readable for backward compatibility. * - * @since 1.8 + * @since 5.4 + * @access public + * + * @param string $name Property to get. + * @return mixed Property. + */ + public function __get($name) + { + return $this->$name; + } + + /** + * Makes private properties settable for backward compatibility. + * + * @since 5.4 * @access public + * + * @param string $name Property to set. + * @param mixed $value Property value. + * @return mixed Newly-set property. */ - public function debug() { - $log = ' [total] ' . $this->cache_total - . ' [hit_incall] ' . $this->count_hit_incall - . ' [hit] ' . $this->count_hit - . ' [miss_incall] ' . $this->count_miss_incall - . ' [miss] ' . $this->count_miss - . ' [set] ' . $this->count_set; + public function __set($name, $value) + { + return $this->$name = $value; + } - return $log; + /** + * Makes private properties checkable for backward compatibility. + * + * @since 5.4 + * @access public + * + * @param string $name Property to check if set. + * @return bool Whether the property is set. + */ + public function __isset($name) + { + return isset($this->$name); } /** - * Get from cache + * Makes private properties un-settable for backward compatibility. + * + * @since 5.4 + * @access public + * + * @param string $name Property to unset. + */ + public function __unset($name) + { + unset($this->$name); + } + + /** + * Serves as a utility function to determine whether a key is valid. + * + * @since 5.4 + * @access protected + * + * @param int|string $key Cache key to check for validity. + * @return bool Whether the key is valid. + */ + protected function is_valid_key($key) + { + if (is_int($key)) { + return true; + } + + if (is_string($key) && trim($key) !== '') { + return true; + } + + $type = gettype($key); + + if (!function_exists('__')) { + wp_load_translations_early(); + } + + $message = is_string($key) + ? __('Cache key must not be an empty string.') + : /* translators: %s: The type of the given cache key. */ + sprintf(__('Cache key must be integer or non-empty string, %s given.'), $type); + + _doing_it_wrong(sprintf('%s::%s', __CLASS__, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[1]['function']), $message, '6.1.0'); + + return false; + } + + /** + * Get the final key. + * + * @since 1.8 + * @access private + */ + private function _key($key, $group = 'default') + { + if (empty($group)) { + $group = 'default'; + } + + $prefix = $this->_object_cache->is_global($group) ? '' : $this->blog_prefix; + + return LSOC_PREFIX . $prefix . $group . '.' . $key; + } + + /** + * Output debug info. * * @since 1.8 * @access public */ - public function get( $key, $group = 'default', $force = false, &$found = null ) { - $final_key = $this->_key( $key, $group ); -// error_log(''); -// error_log("oc: get \t\t\t[key] " . $final_key . ( $force ? "\t\t\t [forced] " : '' ) ); + public function debug() + { + return ' [total] ' . + $this->cache_total . + ' [hit_incall] ' . + $this->count_hit_incall . + ' [hit] ' . + $this->count_hit . + ' [miss_incall] ' . + $this->count_miss_incall . + ' [miss] ' . + $this->count_miss . + ' [set] ' . + $this->count_set; + } + + /** + * Adds data to the cache if it doesn't already exist. + * + * @since 1.8 + * @access public + * + * @uses WP_Object_Cache::_exists() Checks to see if the cache already has data. + * @uses WP_Object_Cache::set() Sets the data after the checking the cache + * contents existence. + * + * @param int|string $key What to call the contents in the cache. + * @param mixed $data The contents to store in the cache. + * @param string $group Optional. Where to group the cache contents. Default 'default'. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool True on success, false if cache key and group already exist. + */ + public function add($key, $data, $group = 'default', $expire = 0) + { + if (wp_suspend_cache_addition()) { + return false; + } + + if (!$this->is_valid_key($key)) { + return false; + } + + if (empty($group)) { + $group = 'default'; + } + + $id = $this->_key($key, $group); + + if (array_key_exists($id, $this->_cache)) { + return false; + } + + return $this->set($key, $data, $group, (int) $expire); + } + + /** + * Adds multiple values to the cache in one call. + * + * @since 5.4 + * @access public + * + * @param array $data Array of keys and values to be added. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool[] Array of return values, grouped by key. Each value is either + * true on success, or false if cache key and group already exist. + */ + public function add_multiple(array $data, $group = '', $expire = 0) + { + $values = array(); + + foreach ($data as $key => $value) { + $values[$key] = $this->add($key, $value, $group, $expire); + } + + return $values; + } + + /** + * Replaces the contents in the cache, if contents already exist. + * + * @since 1.8 + * @access public + * + * @see WP_Object_Cache::set() + * + * @param int|string $key What to call the contents in the cache. + * @param mixed $data The contents to store in the cache. + * @param string $group Optional. Where to group the cache contents. Default 'default'. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool True if contents were replaced, false if original value does not exist. + */ + public function replace($key, $data, $group = 'default', $expire = 0) + { + if (!$this->is_valid_key($key)) { + return false; + } + + if (empty($group)) { + $group = 'default'; + } + + $id = $this->_key($key, $group); + + if (!array_key_exists($id, $this->_cache)) { + return false; + } + + return $this->set($key, $data, $group, (int) $expire); + } + + /** + * Sets the data contents into the cache. + * + * The cache contents are grouped by the $group parameter followed by the + * $key. This allows for duplicate IDs in unique groups. Therefore, naming of + * the group should be used with care and should follow normal function + * naming guidelines outside of core WordPress usage. + * + * The $expire parameter is not used, because the cache will automatically + * expire for each time a page is accessed and PHP finishes. The method is + * more for cache plugins which use files. + * + * @since 1.8 + * @since 5.4 Returns false if cache key is invalid. + * @access public + * + * @param int|string $key What to call the contents in the cache. + * @param mixed $data The contents to store in the cache. + * @param string $group Optional. Where to group the cache contents. Default 'default'. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool True if contents were set, false if key is invalid. + */ + public function set($key, $data, $group = 'default', $expire = 0) + { + if (!$this->is_valid_key($key)) { + return false; + } + + if (empty($group)) { + $group = 'default'; + } + + $id = $this->_key($key, $group); + + if (is_object($data)) { + $data = clone $data; + } + // error_log("oc: set \t\t\t[key] " . $id ); + $this->_cache[$id] = $data; + + if (array_key_exists($id, $this->_cache_404)) { + // error_log("oc: unset404\t\t\t[key] " . $id ); + unset($this->_cache_404[$id]); + } + + if (!$this->_object_cache->is_non_persistent($group)) { + $this->_object_cache->set($id, serialize(array('data' => $data)), (int) $expire); + $this->count_set++; + } + + if ($this->_object_cache->store_transients($group)) { + $this->_transient_set($key, $data, $group, (int) $expire); + } + + return true; + } + + /** + * Sets multiple values to the cache in one call. + * + * @since 5.4 + * @access public + * + * @param array $data Array of key and value to be set. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @param int $expire Optional. When to expire the cache contents, in seconds. + * Default 0 (no expiration). + * @return bool[] Array of return values, grouped by key. Each value is always true. + */ + public function set_multiple(array $data, $group = '', $expire = 0) + { + $values = array(); + + foreach ($data as $key => $value) { + $values[$key] = $this->set($key, $value, $group, $expire); + } + + return $values; + } + + /** + * Retrieves the cache contents, if it exists. + * + * The contents will be first attempted to be retrieved by searching by the + * key in the cache group. If the cache is hit (success) then the contents + * are returned. + * + * On failure, the number of cache misses will be incremented. + * + * @since 1.8 + * @access public + * + * @param int|string $key The key under which the cache contents are stored. + * @param string $group Optional. Where the cache contents are grouped. Default 'default'. + * @param bool $force Optional. Unused. Whether to force an update of the local cache + * from the persistent cache. Default false. + * @param bool $found Optional. Whether the key was found in the cache (passed by reference). + * Disambiguates a return of false, a storable value. Default null. + * @return mixed|false The cache contents on success, false on failure to retrieve contents. + */ + public function get($key, $group = 'default', $force = false, &$found = null) + { + if (!$this->is_valid_key($key)) { + return false; + } + + if (empty($group)) { + $group = 'default'; + } + + $id = $this->_key($key, $group); + + // error_log(''); + // error_log("oc: get \t\t\t[key] " . $id . ( $force ? "\t\t\t [forced] " : '' ) ); $found = false; $found_in_oc = false; $cache_val = false; - if ( array_key_exists( $final_key, $this->_cache ) && ! $force ) { + if (array_key_exists($id, $this->_cache) && !$force) { $found = true; - $cache_val = $this->_cache[ $final_key ]; - $this->count_hit_incall ++; - } - elseif ( ! array_key_exists( $final_key, $this->_cache_404 ) && ! $this->_object_cache->is_non_persistent( $group ) ) { - $v = $this->_object_cache->get( $final_key ); + $cache_val = $this->_cache[$id]; + $this->count_hit_incall++; + } elseif (!array_key_exists($id, $this->_cache_404) && !$this->_object_cache->is_non_persistent($group)) { + $v = $this->_object_cache->get($id); - if ( $v !== null ) { - $v = @maybe_unserialize( $v ); + if ($v !== null) { + $v = @maybe_unserialize($v); } // To be compatible with false val - if ( is_array( $v ) && array_key_exists( 'data', $v ) ) { - $this->count_hit ++; + if (is_array($v) && array_key_exists('data', $v)) { + $this->count_hit++; $found = true; $found_in_oc = true; - $cache_val = $v[ 'data' ]; - } - else { // Can't find key, cache it to 404 -// error_log("oc: add404\t\t\t[key] " . $final_key ); - $this->_cache_404[ $final_key ] = 1; - $this->count_miss ++; + $cache_val = $v['data']; + } else { + // Can't find key, cache it to 404 + // error_log("oc: add404\t\t\t[key] " . $id ); + $this->_cache_404[$id] = 1; + $this->count_miss++; } - } - else { - $this->count_miss_incall ++; + } else { + $this->count_miss_incall++; } - if ( is_object( $cache_val ) ) { + if (is_object($cache_val)) { $cache_val = clone $cache_val; } // If not found but has `Store Transients` cfg on, still need to follow WP's get_transient() logic - if ( ! $found && $this->_object_cache->store_transients( $group ) ) { - $cache_val = $this->_transient_get( $key, $group ); - if ( $cache_val ) { + if (!$found && $this->_object_cache->store_transients($group)) { + $cache_val = $this->_transient_get($key, $group); + if ($cache_val) { $found = true; // $found not used for now (v1.8.3) } } - if ( $found_in_oc ) { - $this->_cache[ $final_key ] = $cache_val; + if ($found_in_oc) { + $this->_cache[$id] = $cache_val; } - $this->cache_total ++; + $this->cache_total++; return $cache_val; } /** - * Set to cache + * Retrieves multiple values from the cache in one call. * - * @since 1.8 + * @since 5.4 * @access public + * + * @param array $keys Array of keys under which the cache contents are stored. + * @param string $group Optional. Where the cache contents are grouped. Default 'default'. + * @param bool $force Optional. Whether to force an update of the local cache + * from the persistent cache. Default false. + * @return array Array of return values, grouped by key. Each value is either + * the cache contents on success, or false on failure. */ - public function set( $key, $data, $group = 'default', $expire = 0 ) { - $final_key = $this->_key( $key, $group ); - - if ( is_object( $data ) ) { - $data = clone $data; - } -// error_log("oc: set \t\t\t[key] " . $final_key ); - $this->_cache[ $final_key ] = $data; - - if( array_key_exists( $final_key, $this->_cache_404 ) ) { -// error_log("oc: unset404\t\t\t[key] " . $final_key ); - unset( $this->_cache_404[ $final_key ] ); - } - - if ( ! $this->_object_cache->is_non_persistent( $group ) ) { - $this->_object_cache->set( $final_key, serialize( array( 'data' => $data ) ), $expire ); - $this->count_set ++; - } + public function get_multiple($keys, $group = 'default', $force = false) + { + $values = array(); - if ( $this->_object_cache->store_transients( $group ) ) { - $this->_transient_set( $key, $data, $group, $expire ); + foreach ($keys as $key) { + $values[$key] = $this->get($key, $group, $force); } - return true; + return $values; } /** - * Adds data to the cache if it doesn't already exist. + * Removes the contents of the cache key in the group. + * + * If the cache key does not exist in the group, then nothing will happen. * * @since 1.8 * @access public + * + * @param int|string $key What the contents in the cache are called. + * @param string $group Optional. Where the cache contents are grouped. Default 'default'. + * @param bool $deprecated Optional. Unused. Default false. + * @return bool True on success, false if the contents were not deleted. */ - public function add( $key, $data, $group = 'default', $expire = 0 ) { - if ( wp_suspend_cache_addition() ) { + public function delete($key, $group = 'default', $deprecated = false) + { + if (!$this->is_valid_key($key)) { return false; } - $final_key = $this->_key( $key, $group ); + if (empty($group)) { + $group = 'default'; + } + + $id = $this->_key($key, $group); - if ( array_key_exists( $final_key, $this->_cache ) ) { + if ($this->_object_cache->store_transients($group)) { + $this->_transient_del($key, $group); + } + + if (array_key_exists($id, $this->_cache)) { + unset($this->_cache[$id]); + } + // error_log("oc: delete \t\t\t[key] " . $id ); + + if ($this->_object_cache->is_non_persistent($group)) { return false; } - return $this->set( $key, $data, $group, $expire ); + return $this->_object_cache->delete($id); } /** - * Replace cache if the cache key exists. + * Deletes multiple values from the cache in one call. * - * @since 1.8 + * @since 5.4 * @access public + * + * @param array $keys Array of keys to be deleted. + * @param string $group Optional. Where the cache contents are grouped. Default empty. + * @return bool[] Array of return values, grouped by key. Each value is either + * true on success, or false if the contents were not deleted. */ - public function replace( $key, $data, $group = 'default', $expire = 0 ) { - $final_key = $this->_key( $key, $group ); + public function delete_multiple(array $keys, $group = '') + { + $values = array(); - if ( ! array_key_exists( $final_key, $this->_cache ) ) { - return false; + foreach ($keys as $key) { + $values[$key] = $this->delete($key, $group); } - return $this->set( $key, $data, $group, $expire ); + return $values; } /** * Increments numeric cache item's value. * + * @since 5.4 + * + * @param int|string $key The cache key to increment. + * @param int $offset Optional. The amount by which to increment the item's value. + * Default 1. + * @param string $group Optional. The group the key is in. Default 'default'. + * @return int|false The item's new value on success, false on failure. + */ + public function incr($key, $offset = 1, $group = 'default') + { + return $this->incr_desr($key, $offset, $group, true); + } + + /** + * Decrements numeric cache item's value. + * + * @since 5.4 + * + * @param int|string $key The cache key to decrement. + * @param int $offset Optional. The amount by which to decrement the item's value. + * Default 1. + * @param string $group Optional. The group the key is in. Default 'default'. + * @return int|false The item's new value on success, false on failure. + */ + public function decr($key, $offset = 1, $group = 'default') + { + return $this->incr_desr($key, $offset, $group, false); + } + + /** + * Increments or decrements numeric cache item's value. + * * @since 1.8 * @access public */ - public function incr_desr( $key, $offset = 1, $group = 'default', $incr = true ) { - $cache_val = $this->get( $key, $group ); + public function incr_desr($key, $offset = 1, $group = 'default', $incr = true) + { + if (!$this->is_valid_key($key)) { + return false; + } + + if (empty($group)) { + $group = 'default'; + } + + $cache_val = $this->get($key, $group); - if ( $cache_val === false ) { + if (false === $cache_val) { return false; } - if ( ! is_numeric( $cache_val ) ) { + if (!is_numeric($cache_val)) { $cache_val = 0; } $offset = (int) $offset; - if ( $incr ) { + if ($incr) { $cache_val += $offset; - } - else { + } else { $cache_val -= $offset; } - if ( $cache_val < 0 ) { + if ($cache_val < 0) { $cache_val = 0; } - $this->set( $key, $cache_val, $group ); + $this->set($key, $cache_val, $group); return $cache_val; } /** - * Delete cache + * Clears the object cache of all data. * * @since 1.8 * @access public + * + * @return true Always returns true. */ - public function delete( $key, $group = 'default' ) { - - $final_key = $this->_key( $key, $group ); + public function flush() + { + $this->flush_runtime(); - if ( $this->_object_cache->store_transients( $group ) ) { - $this->_transient_del( $key, $group ); - } - - if ( array_key_exists( $final_key, $this->_cache ) ) { - unset( $this->_cache[ $final_key ] ); - } -// error_log("oc: delete \t\t\t[key] " . $final_key ); - - if ( $this->_object_cache->is_non_persistent( $group ) ) { - return false; - } + $this->_object_cache->flush(); - return $this->_object_cache->delete( $final_key ); + return true; } /** - * Clear all cached data + * Removes all cache items from the in-memory runtime cache. * - * @since 1.8 + * @since 5.4 * @access public + * + * @return true Always returns true. */ - public function flush() { + public function flush_runtime() + { $this->_cache = array(); $this->_cache_404 = array(); -// error_log("oc: flush " ); - - $this->_object_cache->flush(); return true; } /** - * Add global groups + * Removes all cache items in a group. * - * @since 1.8 + * @since 5.4 * @access public + * + * @param string $group Name of group to remove from cache. + * @return true Always returns true. */ - public function add_global_groups( $groups ) { - $this->_object_cache->add_global_groups( $groups ); + public function flush_group($group) + { + // unset( $this->cache[ $group ] ); + + return true; } /** - * Add non persistent groups + * Sets the list of global cache groups. * * @since 1.8 * @access public + * + * @param string|string[] $groups List of groups that are global. */ - public function add_non_persistent_groups( $groups ) { - $this->_object_cache->add_non_persistent_groups( $groups ); + public function add_global_groups($groups) + { + $groups = (array) $groups; + + $this->_object_cache->add_global_groups($groups); } /** - * Get the final key + * Sets the list of non-persistent cache groups. * * @since 1.8 - * @access private + * @access public */ - private function _key( $key, $group = 'default' ) { - $prefix = $this->_object_cache->is_global( $group ) ? '' : $this->blog_prefix; + public function add_non_persistent_groups($groups) + { + $groups = (array) $groups; - return LSOC_PREFIX . $prefix . $group . '.' . $key; + $this->_object_cache->add_non_persistent_groups($groups); } /** @@ -463,10 +1097,12 @@ private function _key( $key, $group = 'default' ) { * This changes the blog ID used to create keys in blog specific groups. * * @since 1.8 + * @access public * * @param int $blog_id Blog ID. */ - public function switch_to_blog( $blog_id ) { + public function switch_to_blog($blog_id) + { $blog_id = (int) $blog_id; $this->blog_prefix = $this->multisite ? $blog_id . ':' : ''; } @@ -478,47 +1114,48 @@ public function switch_to_blog( $blog_id ) { * @access private * @see `wp-includes/option.php` function `get_transient`/`set_site_transient` */ - private function _transient_get( $transient, $group ) { - if ( $group == 'transient' ) { + private function _transient_get($transient, $group) + { + if ($group == 'transient') { /**** Ori WP func start ****/ $transient_option = '_transient_' . $transient; - if ( ! wp_installing() ) { + if (!wp_installing()) { // If option is not in alloptions, it is not autoloaded and thus has a timeout $alloptions = wp_load_alloptions(); - if ( !isset( $alloptions[$transient_option] ) ) { + if (!isset($alloptions[$transient_option])) { $transient_timeout = '_transient_timeout_' . $transient; - $timeout = get_option( $transient_timeout ); - if ( false !== $timeout && $timeout < time() ) { - delete_option( $transient_option ); - delete_option( $transient_timeout ); + $timeout = get_option($transient_timeout); + if (false !== $timeout && $timeout < time()) { + delete_option($transient_option); + delete_option($transient_timeout); $value = false; } } } - if ( ! isset( $value ) ) - $value = get_option( $transient_option ); + if (!isset($value)) { + $value = get_option($transient_option); + } /**** Ori WP func end ****/ - } - elseif ( $group == 'site-transient' ) { + } elseif ($group == 'site-transient') { /**** Ori WP func start ****/ $no_timeout = array('update_core', 'update_plugins', 'update_themes'); $transient_option = '_site_transient_' . $transient; - if ( ! in_array( $transient, $no_timeout ) ) { + if (!in_array($transient, $no_timeout)) { $transient_timeout = '_site_transient_timeout_' . $transient; - $timeout = get_site_option( $transient_timeout ); - if ( false !== $timeout && $timeout < time() ) { - delete_site_option( $transient_option ); - delete_site_option( $transient_timeout ); + $timeout = get_site_option($transient_timeout); + if (false !== $timeout && $timeout < time()) { + delete_site_option($transient_option); + delete_site_option($transient_timeout); $value = false; } } - if ( ! isset( $value ) ) - $value = get_site_option( $transient_option ); + if (!isset($value)) { + $value = get_site_option($transient_option); + } /**** Ori WP func end ****/ - } - else { + } else { $value = false; } @@ -532,54 +1169,55 @@ private function _transient_get( $transient, $group ) { * @access private * @see `wp-includes/option.php` function `set_transient`/`set_site_transient` */ - private function _transient_set( $transient, $value, $group, $expiration ) { - if ( $group == 'transient' ) { + private function _transient_set($transient, $value, $group, $expiration) + { + if ($group == 'transient') { /**** Ori WP func start ****/ $transient_timeout = '_transient_timeout_' . $transient; $transient_option = '_transient_' . $transient; - if ( false === get_option( $transient_option ) ) { + if (false === get_option($transient_option)) { $autoload = 'yes'; - if ( $expiration ) { + if ((int) $expiration) { $autoload = 'no'; - add_option( $transient_timeout, time() + $expiration, '', 'no' ); + add_option($transient_timeout, time() + (int) $expiration, '', 'no'); } - $result = add_option( $transient_option, $value, '', $autoload ); + $result = add_option($transient_option, $value, '', $autoload); } else { // If expiration is requested, but the transient has no timeout option, // delete, then re-create transient rather than update. $update = true; - if ( $expiration ) { - if ( false === get_option( $transient_timeout ) ) { - delete_option( $transient_option ); - add_option( $transient_timeout, time() + $expiration, '', 'no' ); - $result = add_option( $transient_option, $value, '', 'no' ); + if ((int) $expiration) { + if (false === get_option($transient_timeout)) { + delete_option($transient_option); + add_option($transient_timeout, time() + (int) $expiration, '', 'no'); + $result = add_option($transient_option, $value, '', 'no'); $update = false; } else { - update_option( $transient_timeout, time() + $expiration ); + update_option($transient_timeout, time() + (int) $expiration); } } - if ( $update ) { - $result = update_option( $transient_option, $value ); + if ($update) { + $result = update_option($transient_option, $value); } } /**** Ori WP func end ****/ - } - elseif ( $group == 'site-transient' ) { + } elseif ($group == 'site-transient') { /**** Ori WP func start ****/ $transient_timeout = '_site_transient_timeout_' . $transient; $option = '_site_transient_' . $transient; - if ( false === get_site_option( $option ) ) { - if ( $expiration ) - add_site_option( $transient_timeout, time() + $expiration ); - $result = add_site_option( $option, $value ); + if (false === get_site_option($option)) { + if ((int) $expiration) { + add_site_option($transient_timeout, time() + (int) $expiration); + } + $result = add_site_option($option, $value); } else { - if ( $expiration ) - update_site_option( $transient_timeout, time() + $expiration ); - $result = update_site_option( $option, $value ); + if ((int) $expiration) { + update_site_option($transient_timeout, time() + (int) $expiration); + } + $result = update_site_option($option, $value); } /**** Ori WP func end ****/ - } - else { + } else { $result = null; } @@ -593,23 +1231,25 @@ private function _transient_set( $transient, $value, $group, $expiration ) { * @access private * @see `wp-includes/option.php` function `delete_transient`/`delete_site_transient` */ - private function _transient_del( $transient, $group ) { - if ( $group == 'transient' ) { + private function _transient_del($transient, $group) + { + if ($group == 'transient') { /**** Ori WP func start ****/ $option_timeout = '_transient_timeout_' . $transient; $option = '_transient_' . $transient; - $result = delete_option( $option ); - if ( $result ) - delete_option( $option_timeout ); + $result = delete_option($option); + if ($result) { + delete_option($option_timeout); + } /**** Ori WP func end ****/ - } - elseif ( $group == 'site-transient' ) { + } elseif ($group == 'site-transient') { /**** Ori WP func start ****/ $option_timeout = '_site_transient_timeout_' . $transient; $option = '_site_transient_' . $transient; - $result = delete_site_option( $option ); - if ( $result ) - delete_site_option( $option_timeout ); + $result = delete_site_option($option); + if ($result) { + delete_site_option($option_timeout); + } /**** Ori WP func end ****/ } } @@ -620,11 +1260,12 @@ private function _transient_del( $transient, $group ) { * @since 1.8 * @access public */ - public static function get_instance() { - if ( ! isset( self::$_instance ) ) { + public static function get_instance() + { + if (!isset(self::$_instance)) { self::$_instance = new self(); } return self::$_instance; } -} \ No newline at end of file +} diff --git a/src/optimize.cls.php b/src/optimize.cls.php index 73e7aa0a2..d680cefad 100644 --- a/src/optimize.cls.php +++ b/src/optimize.cls.php @@ -1,14 +1,17 @@ __optimizer = $this->cls( 'Optimizer' ); + public function __construct() + { + Debug2::debug('[Optm] init'); + $this->__optimizer = $this->cls('Optimizer'); } /** @@ -58,54 +64,61 @@ public function __construct() { * @since 3.0 * @access protected */ - public function init() { - $this->cfg_css_async = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_CSS_ASYNC ); - if ( $this->cfg_css_async ) { - if ( ! $this->conf( self::O_API_KEY ) ) { - Debug2::debug( '[Optm] ❌ CCSS set to OFF due to missing domain key' ); + public function init() + { + $this->cfg_css_async = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_CSS_ASYNC); + if ($this->cfg_css_async) { + if (!$this->conf(self::O_API_KEY)) { + Debug2::debug('[Optm] ❌ CCSS set to OFF due to missing domain key'); $this->cfg_css_async = false; } - if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || ( $this->conf( self::O_OPTM_UCSS ) && $this->conf( self::O_OPTM_CSS_COMB ) ) ) && $this->conf( self::O_OPTM_UCSS_INLINE ) ) { - Debug2::debug( '[Optm] ❌ CCSS set to OFF due to UCSS Inline' ); + if ((defined('LITESPEED_GUEST_OPTM') || ($this->conf(self::O_OPTM_UCSS) && $this->conf(self::O_OPTM_CSS_COMB))) && $this->conf(self::O_OPTM_UCSS_INLINE)) { + Debug2::debug('[Optm] ❌ CCSS set to OFF due to UCSS Inline'); $this->cfg_css_async = false; } } - $this->cfg_js_defer = $this->conf( self::O_OPTM_JS_DEFER ); - if ( defined( 'LITESPEED_GUEST_OPTM' ) ) { + $this->cfg_js_defer = $this->conf(self::O_OPTM_JS_DEFER); + if (defined('LITESPEED_GUEST_OPTM')) { $this->cfg_js_defer = 2; } - if ( $this->cfg_js_defer == 2 ) { - add_filter( 'litespeed_optm_cssjs', function( $con, $file_type ){ - if ( $file_type == 'js' ) { - $con = str_replace( 'DOMContentLoaded', 'DOMContentLiteSpeedLoaded', $con ); - // $con = str_replace( 'addEventListener("load"', 'addEventListener("litespeedLoad"', $con ); - } - return $con; - }, 20, 2 ); + if ($this->cfg_js_defer == 2) { + add_filter( + 'litespeed_optm_cssjs', + function ($con, $file_type) { + if ($file_type == 'js') { + $con = str_replace('DOMContentLoaded', 'DOMContentLiteSpeedLoaded', $con); + // $con = str_replace( 'addEventListener("load"', 'addEventListener("litespeedLoad"', $con ); + } + return $con; + }, + 20, + 2 + ); } // To remove emoji from WP - if ( $this->conf( self::O_OPTM_EMOJI_RM ) ) { + if ($this->conf(self::O_OPTM_EMOJI_RM)) { $this->_emoji_rm(); } - if ( $this->conf( self::O_OPTM_QS_RM ) ) { - add_filter( 'style_loader_src', array( $this, 'remove_query_strings' ), 999 ); - add_filter( 'script_loader_src', array( $this, 'remove_query_strings' ), 999 ); + if ($this->conf(self::O_OPTM_QS_RM)) { + add_filter('style_loader_src', array($this, 'remove_query_strings'), 999); + add_filter('script_loader_src', array($this, 'remove_query_strings'), 999); } // GM JS exclude @since 4.1 - if ( defined( 'LITESPEED_GUEST_OPTM' ) ) { - $this->cfg_js_defer_exc = apply_filters( 'litespeed_optm_gm_js_exc', $this->conf( self::O_OPTM_GM_JS_EXC ) ); - } - else { + if (defined('LITESPEED_GUEST_OPTM')) { + $this->cfg_js_defer_exc = apply_filters('litespeed_optm_gm_js_exc', $this->conf(self::O_OPTM_GM_JS_EXC)); + } else { /** * Exclude js from deferred setting * @since 1.5 */ - if ( $this->cfg_js_defer ) { - add_filter( 'litespeed_optm_js_defer_exc', array( $this->cls( 'Data' ), 'load_js_defer_exc' ) ); - $this->cfg_js_defer_exc = apply_filters( 'litespeed_optm_js_defer_exc', $this->conf( self::O_OPTM_JS_DEFER_EXC ) ); + if ($this->cfg_js_defer) { + add_filter('litespeed_optm_js_defer_exc', array($this->cls('Data'), 'load_js_defer_exc')); + $this->cfg_js_defer_exc = apply_filters('litespeed_optm_js_defer_exc', $this->conf(self::O_OPTM_JS_DEFER_EXC)); + + $this->cfg_js_delay_inc = apply_filters('litespeed_optm_js_delay_inc', $this->conf(self::O_OPTM_JS_DELAY_INC)); } } @@ -113,7 +126,7 @@ public function init() { * Add vary filter for Role Excludes * @since 1.6 */ - add_filter( 'litespeed_vary', array( $this, 'vary_add_role_exclude' ) ); + add_filter('litespeed_vary', array($this, 'vary_add_role_exclude')); /** * Prefetch DNS @@ -121,7 +134,13 @@ public function init() { */ $this->_dns_prefetch_init(); - add_filter( 'litespeed_buffer_finalize', array( $this, 'finalize' ), 20 ); + /** + * Preconnect + * @since 5.6.1 + */ + $this->_dns_preconnect_init(); + + add_filter('litespeed_buffer_finalize', array($this, 'finalize'), 20); } /** @@ -130,9 +149,10 @@ public function init() { * @since 1.6 * @access public */ - public function vary_add_role_exclude( $vary ) { - if ( $this->cls( 'Conf' )->in_optm_exc_roles() ) { - $vary[ 'role_exclude_optm' ] = 1; + public function vary_add_role_exclude($vary) + { + if ($this->cls('Conf')->in_optm_exc_roles()) { + $vary['role_exclude_optm'] = 1; } return $vary; @@ -145,18 +165,19 @@ public function vary_add_role_exclude( $vary ) { * @since 2.9.8 Changed to private * @access private */ - private function _emoji_rm() { - remove_action( 'wp_head' , 'print_emoji_detection_script', 7 ); - remove_action( 'admin_print_scripts' , 'print_emoji_detection_script' ); - remove_filter( 'the_content_feed' , 'wp_staticize_emoji' ); - remove_filter( 'comment_text_rss' , 'wp_staticize_emoji' ); + private function _emoji_rm() + { + remove_action('wp_head', 'print_emoji_detection_script', 7); + remove_action('admin_print_scripts', 'print_emoji_detection_script'); + remove_filter('the_content_feed', 'wp_staticize_emoji'); + remove_filter('comment_text_rss', 'wp_staticize_emoji'); /** * Added for better result * @since 1.6.2.1 */ - remove_action( 'wp_print_styles', 'print_emoji_styles' ); - remove_action( 'admin_print_styles', 'print_emoji_styles' ); - remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); + remove_action('wp_print_styles', 'print_emoji_styles'); + remove_action('admin_print_styles', 'print_emoji_styles'); + remove_filter('wp_mail', 'wp_staticize_emoji_for_email'); } /** @@ -165,15 +186,16 @@ private function _emoji_rm() { * @since 2.1 * @access public */ - public function rm_cache_folder( $subsite_id = false ) { - if ( $subsite_id ) { - file_exists( LITESPEED_STATIC_DIR . '/css/' . $subsite_id ) && File::rrmdir( LITESPEED_STATIC_DIR . '/css/' . $subsite_id ); - file_exists( LITESPEED_STATIC_DIR . '/js/' . $subsite_id ) && File::rrmdir( LITESPEED_STATIC_DIR . '/js/' . $subsite_id ); + public function rm_cache_folder($subsite_id = false) + { + if ($subsite_id) { + file_exists(LITESPEED_STATIC_DIR . '/css/' . $subsite_id) && File::rrmdir(LITESPEED_STATIC_DIR . '/css/' . $subsite_id); + file_exists(LITESPEED_STATIC_DIR . '/js/' . $subsite_id) && File::rrmdir(LITESPEED_STATIC_DIR . '/js/' . $subsite_id); return; } - file_exists( LITESPEED_STATIC_DIR . '/css' ) && File::rrmdir( LITESPEED_STATIC_DIR . '/css' ); - file_exists( LITESPEED_STATIC_DIR . '/js' ) && File::rrmdir( LITESPEED_STATIC_DIR . '/js' ); + file_exists(LITESPEED_STATIC_DIR . '/css') && File::rrmdir(LITESPEED_STATIC_DIR . '/css'); + file_exists(LITESPEED_STATIC_DIR . '/js') && File::rrmdir(LITESPEED_STATIC_DIR . '/js'); } /** @@ -182,17 +204,18 @@ public function rm_cache_folder( $subsite_id = false ) { * @since 1.3 * @access public */ - public function remove_query_strings( $src ) { - if ( strpos( $src, '_litespeed_rm_qs=0' ) || strpos( $src, '/recaptcha' ) ) { + public function remove_query_strings($src) + { + if (strpos($src, '_litespeed_rm_qs=0') || strpos($src, '/recaptcha')) { return $src; } - if ( ! Utility::is_internal_file( $src ) ) { + if (!Utility::is_internal_file($src)) { return $src; } - if ( strpos( $src, '.js?' ) !== false || strpos( $src, '.css?' ) !== false ) { - $src = preg_replace( '/\?.*/', '', $src ); + if (strpos($src, '.js?') !== false || strpos($src, '.css?') !== false) { + $src = preg_replace('/\?.*/', '', $src); } return $src; @@ -206,32 +229,35 @@ public function remove_query_strings( $src ) { * @access public * @return string The content that is after optimization */ - public function finalize( $content ) { - if ( defined( 'LITESPEED_NO_PAGEOPTM' ) ) { - Debug2::debug2( '[Optm] bypass: NO_PAGEOPTM const' ); + public function finalize($content) + { + if (defined('LITESPEED_NO_PAGEOPTM')) { + Debug2::debug2('[Optm] bypass: NO_PAGEOPTM const'); return $content; } - if ( ! defined( 'LITESPEED_IS_HTML' ) ) { - Debug2::debug( '[Optm] bypass: Not frontend HTML type' ); + if (!defined('LITESPEED_IS_HTML')) { + Debug2::debug('[Optm] bypass: Not frontend HTML type'); return $content; } - if ( ! defined( 'LITESPEED_GUEST_OPTM' ) ) { - if ( ! Control::is_cacheable() ) { - Debug2::debug( '[Optm] bypass: Not cacheable' ); + if (!defined('LITESPEED_GUEST_OPTM')) { + if (!Control::is_cacheable()) { + Debug2::debug('[Optm] bypass: Not cacheable'); return $content; } // Check if hit URI excludes - $result = Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], $this->conf( self::O_OPTM_EXC ) ); - if ( $result ) { - Debug2::debug( '[Optm] bypass: hit URI Excludes setting: ' . $result ); + add_filter('litespeed_optm_uri_exc', array($this->cls('Data'), 'load_optm_uri_exc')); + $excludes = apply_filters('litespeed_optm_uri_exc', $this->conf(self::O_OPTM_EXC)); + $result = Utility::str_hit_array($_SERVER['REQUEST_URI'], $excludes); + if ($result) { + Debug2::debug('[Optm] bypass: hit URI Excludes setting: ' . $result); return $content; } } - Debug2::debug( '[Optm] start' ); + Debug2::debug('[Optm] start'); $this->content_ori = $this->content = $content; @@ -245,88 +271,87 @@ public function finalize( $content ) { * @since 1.2.2 * @access private */ - private function _optimize() { + private function _optimize() + { global $wp; - $this->_request_url = home_url( $wp->request ); - - $this->cfg_css_min = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_CSS_MIN ); - $this->cfg_css_comb = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_CSS_COMB ); - $this->cfg_js_min = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_JS_MIN ); - $this->cfg_js_comb = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_JS_COMB ); - $this->cfg_ggfonts_rm = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_GGFONTS_RM ); - $this->cfg_ggfonts_async = ! defined( 'LITESPEED_GUEST_OPTM' ) && $this->conf( self::O_OPTM_GGFONTS_ASYNC ); // forced rm already - $this->_conf_css_font_display = ! defined( 'LITESPEED_GUEST_OPTM' ) && $this->conf( self::O_OPTM_CSS_FONT_DISPLAY ); - - if ( ! $this->cls( 'Router' )->can_optm() ) { - Debug2::debug( '[Optm] bypass: admin/feed/preview' ); + $this->_request_url = home_url($wp->request); + + $this->cfg_css_min = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_CSS_MIN); + $this->cfg_css_comb = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_CSS_COMB); + $this->cfg_js_min = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_JS_MIN); + $this->cfg_js_comb = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_JS_COMB); + $this->cfg_ggfonts_rm = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_GGFONTS_RM); + $this->cfg_ggfonts_async = !defined('LITESPEED_GUEST_OPTM') && $this->conf(self::O_OPTM_GGFONTS_ASYNC); // forced rm already + $this->_conf_css_font_display = !defined('LITESPEED_GUEST_OPTM') && $this->conf(self::O_OPTM_CSS_FONT_DISPLAY); + + if (!$this->cls('Router')->can_optm()) { + Debug2::debug('[Optm] bypass: admin/feed/preview'); return; } - if ( $this->cfg_css_async ) { - $this->_ccss = $this->cls( 'CSS' )->prepare_ccss(); - if ( ! $this->_ccss ) { - Debug2::debug( '[Optm] ❌ CCSS set to OFF due to CCSS not generated yet' ); + if ($this->cfg_css_async) { + $this->_ccss = $this->cls('CSS')->prepare_ccss(); + if (!$this->_ccss) { + Debug2::debug('[Optm] ❌ CCSS set to OFF due to CCSS not generated yet'); $this->cfg_css_async = false; - } - else if ( strpos( $this->_ccss, '' . $this->html_head; } // Check if there is any critical css rules setting - if ( $this->cfg_css_async && $this->_ccss ) { + if ($this->cfg_css_async && $this->_ccss) { $this->html_head = $this->_ccss . $this->html_head; } // Replace html head part - $this->html_head = apply_filters( 'litespeed_optm_html_head', $this->html_head ); - if ( $this->html_head ) { - if ( apply_filters( 'litespeed_optm_html_after_head', false ) ) { - $this->content = str_replace( '', $this->html_head . '', $this->content ); - } - else { + $this->html_head = apply_filters('litespeed_optm_html_head', $this->html_head); + if ($this->html_head) { + if (apply_filters('litespeed_optm_html_after_head', false)) { + $this->content = str_replace('', $this->html_head . '', $this->content); + } else { // Put header content to be after charset - if ( strpos( $this->content, 'content = preg_replace( '#]*)>#isU', '' . $this->html_head , $this->content, 1 ); - } - else { - $this->content = preg_replace( '#]*)>#isU', '' . $this->html_head , $this->content, 1 ); + if (strpos($this->content, 'content = preg_replace('#]*)>#isU', '' . $this->html_head, $this->content, 1); + } else { + $this->content = preg_replace('#]*)>#isU', '' . $this->html_head, $this->content, 1); } } } // Replace html foot part - $this->html_foot = apply_filters( 'litespeed_optm_html_foot', $this->html_foot ); - if ( $this->html_foot ) { - $this->content = str_replace( '', $this->html_foot . '' , $this->content ); + $this->html_foot = apply_filters('litespeed_optm_html_foot', $this->html_foot); + if ($this->html_foot) { + $this->content = str_replace('', $this->html_foot . '', $this->content); } // Drop noscript if enabled - if ( $this->conf( self::O_OPTM_NOSCRIPT_RM ) ) { + if ($this->conf(self::O_OPTM_NOSCRIPT_RM)) { // $this->content = preg_replace( '##isU', '', $this->content ); } // HTML minify - if ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_HTML_MIN ) ) { - $this->content = $this->__optimizer->html_min( $this->content ); + if (defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_HTML_MIN)) { + $this->content = $this->__optimizer->html_min($this->content); } } @@ -484,12 +510,13 @@ private function _optimize() { * * @since 4.0 */ - private function _build_js_tag( $src ) { - if ( $this->cfg_js_defer === 2 ) { + private function _build_js_tag($src) + { + if ($this->cfg_js_defer === 2 || Utility::str_hit_array($src, $this->cfg_js_delay_inc)) { return ''; } - if ( $this->cfg_js_defer ) { + if ($this->cfg_js_defer) { return ''; } @@ -501,10 +528,11 @@ private function _build_js_tag( $src ) { * * @since 4.0 */ - private function _build_js_inline( $script, $minified = false ) { - if ( $this->cfg_js_defer ) { - $deferred = $this->_js_inline_defer( $script, false, $minified ); - if ( $deferred ) { + private function _build_js_inline($script, $minified = false) + { + if ($this->cfg_js_defer) { + $deferred = $this->_js_inline_defer($script, false, $minified); + if ($deferred) { return $deferred; } } @@ -517,12 +545,13 @@ private function _build_js_inline( $script, $minified = false ) { * * @since 4.0 */ - private function _maybe_js_delay() { - if ( $this->cfg_js_defer !== 2 ) { + private function _maybe_js_delay() + { + if ($this->cfg_js_defer !== 2 && !$this->cfg_js_delay_inc) { return; } - $this->html_foot .= ''; + $this->html_foot .= ''; } /** @@ -531,12 +560,13 @@ private function _maybe_js_delay() { * @since 2.7.3 * @access private */ - private function _async_ggfonts() { - if ( ! $this->cfg_ggfonts_async || ! $this->_ggfonts_urls ) { + private function _async_ggfonts() + { + if (!$this->cfg_ggfonts_async || !$this->_ggfonts_urls) { return; } - Debug2::debug2( '[Optm] google fonts async found: ', $this->_ggfonts_urls ); + Debug2::debug2('[Optm] google fonts async found: ', $this->_ggfonts_urls); $html = ''; @@ -550,41 +580,41 @@ private function _async_ggfonts() { * -> family: PT Sans:400,700|PT Sans Narrow:400|Montserrat:600 * */ - $script ='WebFontConfig={google:{families:['; + $script = 'WebFontConfig={google:{families:['; $families = array(); - foreach ( $this->_ggfonts_urls as $v ) { - $qs = wp_specialchars_decode( $v ); - $qs = urldecode( $qs ); - $qs = parse_url( $qs, PHP_URL_QUERY ); - parse_str( $qs, $qs ); - - if ( empty( $qs[ 'family' ] ) ) { - Debug2::debug( '[Optm] ERR ggfonts failed to find family: ' . $v ); + foreach ($this->_ggfonts_urls as $v) { + $qs = wp_specialchars_decode($v); + $qs = urldecode($qs); + $qs = parse_url($qs, PHP_URL_QUERY); + parse_str($qs, $qs); + + if (empty($qs['family'])) { + Debug2::debug('[Optm] ERR ggfonts failed to find family: ' . $v); continue; } - $subset = empty( $qs[ 'subset' ] ) ? '' : ':' . $qs[ 'subset' ]; + $subset = empty($qs['subset']) ? '' : ':' . $qs['subset']; - foreach ( array_filter( explode( '|', $qs[ 'family' ] ) ) as $v2 ) { + foreach (array_filter(explode('|', $qs['family'])) as $v2) { $families[] = $v2 . $subset; } } - $script .= '"' . implode( '","', $families ) . ( $this->_conf_css_font_display ? '&display=swap' : '' ) . '"'; + $script .= '"' . implode('","', $families) . ($this->_conf_css_font_display ? '&display=swap' : '') . '"'; $script .= ']}};'; // if webfontloader lib was loaded before WebFontConfig variable, call WebFont.load $script .= 'if ( typeof WebFont === "object" && typeof WebFont.load === "function" ) { WebFont.load( WebFontConfig ); }'; - $html .= $this->_build_js_inline( $script ); + $html .= $this->_build_js_inline($script); // https://cdnjs.cloudflare.com/ajax/libs/webfont/1.6.28/webfontloader.js $webfont_lib_url = LSWCP_PLUGIN_URL . self::LIB_FILE_WEBFONTLOADER; // default async, if js defer set use defer - $html .= $this->_build_js_tag( $webfont_lib_url ); + $html .= $this->_build_js_tag($webfont_lib_url); // Put this in the very beginning for preconnect $this->html_head = $html . $this->html_head; @@ -596,20 +626,21 @@ private function _async_ggfonts() { * @since 3.0 * @access private */ - private function _font_optm() { - if ( ! $this->_conf_css_font_display || ! $this->_ggfonts_urls ) { + private function _font_optm() + { + if (!$this->_conf_css_font_display || !$this->_ggfonts_urls) { return; } - Debug2::debug2( '[Optm] google fonts optm ', $this->_ggfonts_urls ); + Debug2::debug2('[Optm] google fonts optm ', $this->_ggfonts_urls); - foreach ( $this->_ggfonts_urls as $v ) { - if ( strpos( $v, 'display=' ) ) { + foreach ($this->_ggfonts_urls as $v) { + if (strpos($v, 'display=')) { continue; } - $this->html_head = str_replace( $v, $v . '&display=swap', $this->html_head ); - $this->html_foot = str_replace( $v, $v . '&display=swap', $this->html_foot ); - $this->content = str_replace( $v, $v . '&display=swap', $this->content ); + $this->html_head = str_replace($v, $v . '&display=swap', $this->html_head); + $this->html_foot = str_replace($v, $v . '&display=swap', $this->html_foot); + $this->content = str_replace($v, $v . '&display=swap', $this->content); } } @@ -619,22 +650,35 @@ private function _font_optm() { * @since 1.7.1 * @access private */ - private function _dns_prefetch_init() { + private function _dns_prefetch_init() + { // Widely enable link DNS prefetch - if ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_DNS_PREFETCH_CTRL ) ) { - @header( 'X-DNS-Prefetch-Control: on' ); + if (defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_OPTM_DNS_PREFETCH_CTRL)) { + @header('X-DNS-Prefetch-Control: on'); } - $this->dns_prefetch = $this->conf( self::O_OPTM_DNS_PREFETCH ); - if ( ! $this->dns_prefetch ) { + $this->dns_prefetch = $this->conf(self::O_OPTM_DNS_PREFETCH); + if (!$this->dns_prefetch) { return; } - if ( function_exists( 'wp_resource_hints' ) ) { - add_filter( 'wp_resource_hints', array( $this, 'dns_prefetch_filter' ), 10, 2 ); + if (function_exists('wp_resource_hints')) { + add_filter('wp_resource_hints', array($this, 'dns_prefetch_filter'), 10, 2); + } else { + add_action('litespeed_optm', array($this, 'dns_prefetch_output')); } - else { - add_action( 'litespeed_optm', array( $this, 'dns_prefetch_output' ) ); + } + + /** + * Preconnect init + * + * @since 5.6.1 + */ + private function _dns_preconnect_init() + { + $this->dns_preconnect = $this->conf(self::O_OPTM_DNS_PRECONNECT); + if ($this->dns_preconnect) { + add_action('litespeed_optm', array($this, 'dns_preconnect_output')); } } @@ -644,13 +688,14 @@ private function _dns_prefetch_init() { * @since 1.7.1 * @access public */ - public function dns_prefetch_filter( $urls, $relation_type ) { - if ( $relation_type !== 'dns-prefetch' ) { + public function dns_prefetch_filter($urls, $relation_type) + { + if ($relation_type !== 'dns-prefetch') { return $urls; } - foreach ( $this->dns_prefetch as $v ) { - if ( $v ) { + foreach ($this->dns_prefetch as $v) { + if ($v) { $urls[] = $v; } } @@ -664,92 +709,107 @@ public function dns_prefetch_filter( $urls, $relation_type ) { * @since 1.7.1 * @access public */ - public function dns_prefetch_output() { - foreach ( $this->dns_prefetch as $v ) { - if ( $v ) { + public function dns_prefetch_output() + { + foreach ($this->dns_prefetch as $v) { + if ($v) { $this->html_head .= ''; } } } + /** + * Preconnect + * + * @since 5.6.1 + * @access public + */ + public function dns_preconnect_output() + { + foreach ($this->dns_preconnect as $v) { + if ($v) { + $this->html_head .= ''; + } + } + } + /** * Run minify with src queue list * * @since 1.2.2 * @access private */ - private function _src_queue_handler( $src_list, $html_list, $file_type = 'css' ) { + private function _src_queue_handler($src_list, $html_list, $file_type = 'css') + { $html_list_ori = $html_list; - $can_webp = ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE ) ) && $this->cls( 'Media' )->webp_support(); + $can_webp = (defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_IMG_OPTM_WEBP)) && $this->cls('Media')->webp_support(); $tag = $file_type == 'css' ? 'link' : 'script'; - foreach ( $src_list as $key => $src_info ) { + foreach ($src_list as $key => $src_info) { // Minify inline CSS/JS - if ( ! empty( $src_info[ 'inl' ] ) ) { - if ( $file_type == 'css' ) { - $code = Optimizer::minify_css( $src_info[ 'src' ] ); - $can_webp && $code = $this->cls( 'Media' )->replace_background_webp( $code ); - $snippet = str_replace( $src_info[ 'src' ], $code, $html_list[ $key ] ); - } - else { + if (!empty($src_info['inl'])) { + if ($file_type == 'css') { + $code = Optimizer::minify_css($src_info['src']); + $can_webp && ($code = $this->cls('Media')->replace_background_webp($code)); + $snippet = str_replace($src_info['src'], $code, $html_list[$key]); + } else { // Inline defer JS - if ( $this->cfg_js_defer ) { - $attrs = ! empty( $src_info[ 'attrs' ] ) ? $src_info[ 'attrs' ] : ''; - $snippet = $this->_js_inline_defer( $src_info[ 'src' ], $attrs ) ?: $html_list[ $key ]; - } - else { - $code = Optimizer::minify_js( $src_info[ 'src' ] ); - $snippet = str_replace( $src_info[ 'src' ], $code, $html_list[ $key ] ); + if ($this->cfg_js_defer) { + $attrs = !empty($src_info['attrs']) ? $src_info['attrs'] : ''; + $snippet = $this->_js_inline_defer($src_info['src'], $attrs) ?: $html_list[$key]; + } else { + $code = Optimizer::minify_js($src_info['src']); + $snippet = str_replace($src_info['src'], $code, $html_list[$key]); } } - } // CSS/JS files else { - $url = $this->_build_single_hash_url( $src_info[ 'src' ], $file_type ); - if ( $url ) { - $snippet = str_replace( $src_info[ 'src' ], $url, $html_list[ $key ] ); + $url = $this->_build_single_hash_url($src_info['src'], $file_type); + if ($url) { + $snippet = str_replace($src_info['src'], $url, $html_list[$key]); } // Handle css async load - if ( $file_type == 'css' && $this->cfg_css_async ) { - $snippet = $this->_async_css( $snippet ); + if ($file_type == 'css' && $this->cfg_css_async) { + $snippet = $this->_async_css($snippet); } // Handle js defer - if ( $file_type === 'js' && $this->cfg_js_defer ) { - $snippet = $this->_js_defer( $snippet, $src_info[ 'src' ] ) ?: $snippet; + if ($file_type === 'js' && $this->cfg_js_defer) { + $snippet = $this->_js_defer($snippet, $src_info['src']) ?: $snippet; } } - $snippet = str_replace( "<$tag ", '<' . $tag . ' data-optimized="1" ', $snippet ); - $html_list[ $key ] = $snippet; + $snippet = str_replace("<$tag ", '<' . $tag . ' data-optimized="1" ', $snippet); + $html_list[$key] = $snippet; } - $this->content = str_replace( $html_list_ori, $html_list, $this->content ); + $this->content = str_replace($html_list_ori, $html_list, $this->content); } /** * Build a single URL mapped filename (This will not save in DB) * @since 4.0 */ - private function _build_single_hash_url( $src, $file_type = 'css' ) { - $content = $this->__optimizer->load_file( $src, $file_type ); + private function _build_single_hash_url($src, $file_type = 'css') + { + $content = $this->__optimizer->load_file($src, $file_type); - $is_min = $this->__optimizer->is_min( $src ); + $is_min = $this->__optimizer->is_min($src); - $content = $this->__optimizer->optm_snippet( $content, $file_type, ! $is_min, $src ); + $content = $this->__optimizer->optm_snippet($content, $file_type, !$is_min, $src); - $filepath_prefix = $this->_build_filepath_prefix( $file_type ); + $filepath_prefix = $this->_build_filepath_prefix($file_type); // Save to file - $filename = $filepath_prefix . md5( $this->remove_query_strings( $src ) ) . '.' . $file_type; + $filename = $filepath_prefix . md5($this->remove_query_strings($src)) . '.' . $file_type; $static_file = LITESPEED_STATIC_DIR . $filename; - File::save( $static_file, $content, true ); + File::save($static_file, $content, true); // QS is required as $src may contains version info - $qs_hash = substr( md5( $src ), -5 ); + $qs_hash = substr(md5($src), -5); return LITESPEED_STATIC_URL . "$filename?ver=$qs_hash"; } @@ -759,34 +819,35 @@ private function _build_single_hash_url( $src, $file_type = 'css' ) { * @since 1.2.2 * @access private */ - private function _build_hash_url( $src_list, $file_type = 'css' ) { + private function _build_hash_url($src_list, $file_type = 'css') + { // $url_sensitive = $this->conf( self::O_OPTM_CSS_UNIQUE ) && $file_type == 'css'; // If need to keep unique CSS per URI // Replace preserved ESI (before generating hash) - if ( $file_type == 'js' ) { - foreach ( $src_list as $k => $v ) { - if ( empty( $v[ 'inl' ] ) ) { + if ($file_type == 'js') { + foreach ($src_list as $k => $v) { + if (empty($v['inl'])) { continue; } - $src_list[ $k ][ 'src' ] = $this->_preserve_esi( $v[ 'src' ] ); + $src_list[$k]['src'] = $this->_preserve_esi($v['src']); } } $minify = $file_type === 'css' ? $this->cfg_css_min : $this->cfg_js_min; - $filename_info = $this->__optimizer->serve( $this->_request_url, $file_type, $minify, $src_list ); + $filename_info = $this->__optimizer->serve($this->_request_url, $file_type, $minify, $src_list); - if ( ! $filename_info ) { + if (!$filename_info) { return false; // Failed to generate } - list( $filename, $type ) = $filename_info; + list($filename, $type) = $filename_info; // Add cache tag in case later file deleted to avoid lscache served stale non-existed files @since 4.4.1 - Tag::add( Tag::TYPE_MIN . '.' . $filename ); + Tag::add(Tag::TYPE_MIN . '.' . $filename); - $qs_hash = substr( md5( self::get_option( self::ITEM_TIMESTAMP_PURGE_CSS) ), -5 ); + $qs_hash = substr(md5(self::get_option(self::ITEM_TIMESTAMP_PURGE_CSS)), -5); // As filename is alreay realted to filecon md5, no need QS anymore - $filepath_prefix = $this->_build_filepath_prefix( $type ); + $filepath_prefix = $this->_build_filepath_prefix($type); return LITESPEED_STATIC_URL . $filepath_prefix . $filename . '?ver=' . $qs_hash; } @@ -796,101 +857,106 @@ private function _build_hash_url( $src_list, $file_type = 'css' ) { * @since 1.2.2 * @access private */ - private function _parse_js() { - $excludes = apply_filters( 'litespeed_optimize_js_excludes', $this->conf( self::O_OPTM_JS_EXC ) ); + private function _parse_js() + { + $excludes = apply_filters('litespeed_optimize_js_excludes', $this->conf(self::O_OPTM_JS_EXC)); - $combine_ext_inl = $this->conf( self::O_OPTM_JS_COMB_EXT_INL ); + $combine_ext_inl = $this->conf(self::O_OPTM_JS_COMB_EXT_INL); + if (!apply_filters('litespeed_optm_js_comb_ext_inl', true)) { + Debug2::debug2('[Optm] js_comb_ext_inl bypassed via litespeed_optm_js_comb_ext_inl filter'); + $combine_ext_inl = false; + } $src_list = array(); $html_list = array(); - $content = preg_replace( '##sU', '', $this->content ); - preg_match_all( '#]*)>(.*)#isU', $content, $matches, PREG_SET_ORDER ); - foreach ( $matches as $match ) { - $attrs = empty( $match[ 1 ] ) ? array() : Utility::parse_attr( $match[ 1 ] ); + $content = preg_replace('##sU', '', $this->content); + preg_match_all('#]*)>(.*)#isU', $content, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + $attrs = empty($match[1]) ? array() : Utility::parse_attr($match[1]); - if ( isset( $attrs[ 'data-optimized' ] ) ) { + if (isset($attrs['data-optimized'])) { continue; } - if ( ! empty( $attrs[ 'data-no-optimize' ] ) ) { + if (!empty($attrs['data-no-optimize'])) { continue; } - if ( ! empty( $attrs[ 'data-cfasync' ] ) && $attrs[ 'data-cfasync' ] === 'false' ) { + if (!empty($attrs['data-cfasync']) && $attrs['data-cfasync'] === 'false') { continue; } - if ( ! empty( $attrs[ 'type' ] ) && $attrs[ 'type' ] != 'text/javascript' ) { + if (!empty($attrs['type']) && $attrs['type'] != 'text/javascript') { continue; } // to avoid multiple replacement - if ( in_array( $match[ 0 ], $html_list ) ) { + if (in_array($match[0], $html_list)) { continue; } $this_src_arr = array(); // JS files - if ( ! empty( $attrs[ 'src' ] ) ) { + if (!empty($attrs['src'])) { // Exclude check - $js_excluded = Utility::str_hit_array( $attrs[ 'src' ], $excludes ); - $is_internal = Utility::is_internal_file( $attrs[ 'src' ] ); - $is_file = substr( $attrs[ 'src' ], 0, 5 ) != 'data:'; - $ext_excluded = ! $combine_ext_inl && ! $is_internal; - if ( $js_excluded || $ext_excluded || ! $is_file ) { + $js_excluded = Utility::str_hit_array($attrs['src'], $excludes); + $is_internal = Utility::is_internal_file($attrs['src']); + $is_file = substr($attrs['src'], 0, 5) != 'data:'; + $ext_excluded = !$combine_ext_inl && !$is_internal; + if ($js_excluded || $ext_excluded || !$is_file) { // Maybe defer - if ( $this->cfg_js_defer ) { - $deferred = $this->_js_defer( $match[ 0 ], $attrs[ 'src' ] ); - if ( $deferred ) { - $this->content = str_replace( $match[ 0 ], $deferred, $this->content ); + if ($this->cfg_js_defer) { + $deferred = $this->_js_defer($match[0], $attrs['src']); + if ($deferred) { + $this->content = str_replace($match[0], $deferred, $this->content); } } - Debug2::debug2( '[Optm] _parse_js bypassed due to ' . ( $js_excluded ? 'js files excluded [hit] ' . $js_excluded : 'external js' ) ); + Debug2::debug2('[Optm] _parse_js bypassed due to ' . ($js_excluded ? 'js files excluded [hit] ' . $js_excluded : 'external js')); continue; } - if ( strpos( $attrs[ 'src' ], '/localres/' ) !== false ) { + if (strpos($attrs['src'], '/localres/') !== false) { continue; } - if ( strpos( $attrs[ 'src' ], 'instant_click' ) !== false ) { + if (strpos($attrs['src'], 'instant_click') !== false) { continue; } - $this_src_arr[ 'src' ] = $attrs[ 'src' ]; + $this_src_arr['src'] = $attrs['src']; } // Inline JS - elseif ( ! empty( $match[ 2 ] ) ) { + elseif (!empty($match[2])) { // Debug2::debug( '🌹🌹🌹 ' . $match[2] . '🌹' ); // Exclude check - $js_excluded = Utility::str_hit_array( $match[ 2 ], $excludes ); - if ( $js_excluded || ! $combine_ext_inl ) { + $js_excluded = Utility::str_hit_array($match[2], $excludes); + if ($js_excluded || !$combine_ext_inl) { // Maybe defer - if ( $this->cfg_js_defer ) { - $deferred = $this->_js_inline_defer( $match[ 2 ], $match[ 1 ] ); - if ( $deferred ) { - $this->content = str_replace( $match[ 0 ], $deferred, $this->content ); + if ($this->cfg_js_defer) { + $deferred = $this->_js_inline_defer($match[2], $match[1]); + if ($deferred) { + $this->content = str_replace($match[0], $deferred, $this->content); } } - Debug2::debug2( '[Optm] _parse_js bypassed due to ' . ( $js_excluded ? 'js excluded [hit] ' . $js_excluded : 'inline js' ) ); + Debug2::debug2('[Optm] _parse_js bypassed due to ' . ($js_excluded ? 'js excluded [hit] ' . $js_excluded : 'inline js')); continue; } - $this_src_arr[ 'inl' ] = true; - $this_src_arr[ 'src' ] = $match[ 2 ]; - if ( $match[ 1 ] ) { - $this_src_arr[ 'attrs' ] = $match[ 1 ]; + $this_src_arr['inl'] = true; + $this_src_arr['src'] = $match[2]; + if ($match[1]) { + $this_src_arr['attrs'] = $match[1]; } - } - else { // Compatibility to those who changed src to data-src already - Debug2::debug2( '[Optm] No JS src or inline JS content' ); + } else { + // Compatibility to those who changed src to data-src already + Debug2::debug2('[Optm] No JS src or inline JS content'); continue; } $src_list[] = $this_src_arr; - $html_list[] = $match[ 0 ]; + $html_list[] = $match[0]; } - return array( $src_list, $html_list ); + return array($src_list, $html_list); } /** @@ -899,44 +965,46 @@ private function _parse_js() { * @since 3.0 * @access private */ - private function _js_inline_defer( $con, $attrs = false, $minified = false ) { - if ( strpos( $attrs, 'data-no-defer' ) !== false ) { - Debug2::debug2( '[Optm] bypass: attr api data-no-defer' ); + private function _js_inline_defer($con, $attrs = false, $minified = false) + { + if (strpos($attrs, 'data-no-defer') !== false) { + Debug2::debug2('[Optm] bypass: attr api data-no-defer'); return false; } - $hit = Utility::str_hit_array( $con, $this->cfg_js_defer_exc ); - if ( $hit ) { - Debug2::debug2( '[Optm] inline js defer excluded [setting] ' . $hit ); + $hit = Utility::str_hit_array($con, $this->cfg_js_defer_exc); + if ($hit) { + Debug2::debug2('[Optm] inline js defer excluded [setting] ' . $hit); return false; } - $con = trim( $con ); + $con = trim($con); // Minify JS first - if ( ! $minified ) { // && $this->cfg_js_defer !== 2 - $con = Optimizer::minify_js( $con ); + if (!$minified) { + // && $this->cfg_js_defer !== 2 + $con = Optimizer::minify_js($con); } - if ( ! $con ) { + if (!$con) { return false; } // Check if the content contains ESI nonce or not - $con = $this->_preserve_esi( $con ); + $con = $this->_preserve_esi($con); - if ( $this->cfg_js_defer === 2 ) { + if ($this->cfg_js_defer === 2) { // Drop type attribute from $attrs - if ( strpos( $attrs, ' type=' ) !== false ) { - $attrs = preg_replace( '# type=([\'"])([^\1]+)\1#isU', '', $attrs ); + if (strpos($attrs, ' type=') !== false) { + $attrs = preg_replace('# type=([\'"])([^\1]+)\1#isU', '', $attrs); } // Replace DOMContentLoaded - $con = str_replace( 'DOMContentLoaded', 'DOMContentLiteSpeedLoaded', $con ); + $con = str_replace('DOMContentLoaded', 'DOMContentLiteSpeedLoaded', $con); return '' . $con . ''; // return ''; // return '' . $con . ''; } - return ''; + return ''; } /** @@ -944,15 +1012,16 @@ private function _js_inline_defer( $con, $attrs = false, $minified = false ) { * * @since 3.5.1 */ - private function _preserve_esi( $con ) { - $esi_placeholder_list = $this->cls( 'ESI' )->contain_preserve_esi( $con ); - if ( ! $esi_placeholder_list ) { + private function _preserve_esi($con) + { + $esi_placeholder_list = $this->cls('ESI')->contain_preserve_esi($con); + if (!$esi_placeholder_list) { return $con; } - foreach ( $esi_placeholder_list as $esi_placeholder ) { - $js_var = '__litespeed_var_' . ( self::$_var_i ++ ) . '__'; - $con = str_replace( $esi_placeholder, $js_var, $con ); + foreach ($esi_placeholder_list as $esi_placeholder) { + $js_var = '__litespeed_var_' . self::$_var_i++ . '__'; + $con = str_replace($esi_placeholder, $js_var, $con); $this->_var_preserve_js[] = $js_var . '=' . $esi_placeholder; } @@ -966,12 +1035,18 @@ private function _preserve_esi( $con ) { * @access private * @return array All the src & related raw html list */ - private function _parse_css() { - $excludes = apply_filters( 'litespeed_optimize_css_excludes', $this->conf( self::O_OPTM_CSS_EXC ) ); + private function _parse_css() + { + $excludes = apply_filters('litespeed_optimize_css_excludes', $this->conf(self::O_OPTM_CSS_EXC)); + $ucss_file_exc_inline = apply_filters('litespeed_optimize_ucss_file_exc_inline', $this->conf(self::O_OPTM_UCSS_FILE_EXC_INLINE)); - $combine_ext_inl = $this->conf( self::O_OPTM_CSS_COMB_EXT_INL ); + $combine_ext_inl = $this->conf(self::O_OPTM_CSS_COMB_EXT_INL); + if (!apply_filters('litespeed_optm_css_comb_ext_inl', true)) { + Debug2::debug2('[Optm] css_comb_ext_inl bypassed via litespeed_optm_css_comb_ext_inl filter'); + $combine_ext_inl = false; + } - $css_to_be_removed = apply_filters( 'litespeed_optm_css_to_be_removed', array() ); + $css_to_be_removed = apply_filters('litespeed_optm_css_to_be_removed', array()); $src_list = array(); $html_list = array(); @@ -980,114 +1055,123 @@ private function _parse_css() { // $dom->load( $content );return $val; // $items = $dom->find( 'link' ); - $content = preg_replace( array( '##sU', '#]*)>.*#isU', '#]*)>.*#isU' ), '', $this->content ); - preg_match_all( '#]+)/?>|]*)>([^<]+)#isU', $content, $matches, PREG_SET_ORDER ); + $content = preg_replace(array('##sU', '#]*)>.*#isU', '#]*)>.*#isU'), '', $this->content); + preg_match_all('#]+)/?>|]*)>([^<]+)#isU', $content, $matches, PREG_SET_ORDER); - foreach ( $matches as $match ) { + foreach ($matches as $match) { // to avoid multiple replacement - if ( in_array( $match[ 0 ], $html_list ) ) { + if (in_array($match[0], $html_list)) { continue; } - if ( $exclude = Utility::str_hit_array( $match[ 0 ], $excludes ) ) { - Debug2::debug2( '[Optm] _parse_css bypassed exclude ' . $exclude ); + if ($exclude = Utility::str_hit_array($match[0], $excludes)) { + Debug2::debug2('[Optm] _parse_css bypassed exclude ' . $exclude); continue; } $this_src_arr = array(); - if ( strpos( $match[ 0 ], 'content = str_replace( $match[ 0 ], '', $this->content ); + $this->content = str_replace($match[0], '', $this->content); + + continue; + } + + // Check if need to inline this css file + if (Utility::str_hit_array($attrs['href'], $ucss_file_exc_inline)) { + Debug2::debug('[Optm] ucss_file_exc_inline hit ' . $attrs['href']); + // Replace this css to inline from orig html + $inline_script = ''; + $this->content = str_replace($match[0], $inline_script, $this->content); continue; } // Check Google fonts hit - if ( strpos( $attrs[ 'href' ], 'fonts.googleapis.com' ) !== false ) { + if (strpos($attrs['href'], 'fonts.googleapis.com') !== false) { /** * For async gg fonts, will add webfont into head, hence remove it from buffer and store the matches to use later * @since 2.7.3 * @since 3.0 For font display optm, need to parse google fonts URL too */ - if ( ! in_array( $attrs[ 'href' ], $this->_ggfonts_urls ) ) { - $this->_ggfonts_urls[] = $attrs[ 'href' ]; + if (!in_array($attrs['href'], $this->_ggfonts_urls)) { + $this->_ggfonts_urls[] = $attrs['href']; } - if ( $this->cfg_ggfonts_rm || $this->cfg_ggfonts_async ) { - Debug2::debug( '[Optm] rm css snippet [Google fonts] ' . $attrs[ 'href' ] ); - $this->content = str_replace( $match[ 0 ], '', $this->content ); + if ($this->cfg_ggfonts_rm || $this->cfg_ggfonts_async) { + Debug2::debug('[Optm] rm css snippet [Google fonts] ' . $attrs['href']); + $this->content = str_replace($match[0], '', $this->content); continue; } } - if ( isset( $attrs[ 'data-optimized' ] ) ) { + if (isset($attrs['data-optimized'])) { // $this_src_arr[ 'exc' ] = true; continue; - } - elseif ( ! empty( $attrs[ 'data-no-optimize' ] ) ) { + } elseif (!empty($attrs['data-no-optimize'])) { // $this_src_arr[ 'exc' ] = true; continue; } - $is_internal = Utility::is_internal_file( $attrs[ 'href' ] ); - $ext_excluded = ! $combine_ext_inl && ! $is_internal; - if ( $ext_excluded ) { - Debug2::debug2( '[Optm] Bypassed due to external link' ); + $is_internal = Utility::is_internal_file($attrs['href']); + $ext_excluded = !$combine_ext_inl && !$is_internal; + if ($ext_excluded) { + Debug2::debug2('[Optm] Bypassed due to external link'); // Maybe defer - if ( $this->cfg_css_async ) { - $snippet = $this->_async_css( $match[ 0 ] ); - if ( $snippet != $match[ 0 ] ) { - $this->content = str_replace( $match[ 0 ], $snippet, $this->content ); + if ($this->cfg_css_async) { + $snippet = $this->_async_css($match[0]); + if ($snippet != $match[0]) { + $this->content = str_replace($match[0], $snippet, $this->content); } } continue; } - if ( ! empty( $attrs[ 'media' ] ) && $attrs[ 'media' ] !== 'all' ) { - $this_src_arr[ 'media' ] = $attrs[ 'media' ]; + if (!empty($attrs['media']) && $attrs['media'] !== 'all') { + $this_src_arr['media'] = $attrs['media']; } - $this_src_arr[ 'src' ] = $attrs[ 'href' ]; - } - else { // Inline style - if ( ! $combine_ext_inl ) { - Debug2::debug2( '[Optm] Bypassed due to inline' ); + $this_src_arr['src'] = $attrs['href']; + } else { + // Inline style + if (!$combine_ext_inl) { + Debug2::debug2('[Optm] Bypassed due to inline'); continue; } - $attrs = Utility::parse_attr( $match[ 2 ] ); + $attrs = Utility::parse_attr($match[2]); - if ( ! empty( $attrs[ 'data-no-optimize' ] ) ) { + if (!empty($attrs['data-no-optimize'])) { continue; } - if ( ! empty( $attrs[ 'media' ] ) && $attrs[ 'media' ] !== 'all' ) { - $this_src_arr[ 'media' ] = $attrs[ 'media' ]; + if (!empty($attrs['media']) && $attrs['media'] !== 'all') { + $this_src_arr['media'] = $attrs['media']; } - $this_src_arr[ 'inl' ] = true; - $this_src_arr[ 'src' ] = $match[ 3 ]; + $this_src_arr['inl'] = true; + $this_src_arr['src'] = $match[3]; } $src_list[] = $this_src_arr; - $html_list[] = $match[ 0 ]; + $html_list[] = $match[0]; } - return array( $src_list, $html_list ); + return array($src_list, $html_list); } /** @@ -1096,13 +1180,14 @@ private function _parse_css() { * @since 1.3 * @access private */ - private function _async_css_list( $html_list, $src_list ) { - foreach ( $html_list as $k => $ori ) { - if ( ! empty( $src_list[ $k ][ 'inl' ] ) ) { + private function _async_css_list($html_list, $src_list) + { + foreach ($html_list as $k => $ori) { + if (!empty($src_list[$k]['inl'])) { continue; } - $html_list[ $k ] = $this->_async_css( $ori ); + $html_list[$k] = $this->_async_css($ori); } return $html_list; } @@ -1111,23 +1196,24 @@ private function _async_css_list( $html_list, $src_list ) { * Async CSS snippet * @since 3.5 */ - private function _async_css( $ori ) { - if ( strpos( $ori, 'data-asynced' ) !== false ) { - Debug2::debug2( '[Optm] bypass: attr data-asynced exist' ); + private function _async_css($ori) + { + if (strpos($ori, 'data-asynced') !== false) { + Debug2::debug2('[Optm] bypass: attr data-asynced exist'); return $ori; } - if ( strpos( $ori, 'data-no-async' ) !== false ) { - Debug2::debug2( '[Optm] bypass: attr api data-no-async' ); + if (strpos($ori, 'data-no-async') !== false) { + Debug2::debug2('[Optm] bypass: attr api data-no-async'); return $ori; } // async replacement - $v = str_replace( 'stylesheet', 'preload', $ori ); - $v = str_replace( 'conf( self::O_OPTM_NOSCRIPT_RM ) ) { - $v .= ''; + if (!defined('LITESPEED_GUEST_OPTM') && !$this->conf(self::O_OPTM_NOSCRIPT_RM)) { + $v .= ''; } return $v; @@ -1138,20 +1224,21 @@ private function _async_css( $ori ) { * * @since 3.5 */ - private function _js_defer( $ori, $src ) { - if ( strpos( $ori, ' async' ) !== false ) { - $ori = str_replace( ' async', '', $ori ); + private function _js_defer($ori, $src) + { + if (strpos($ori, ' async') !== false) { + $ori = str_replace(' async', '', $ori); } - if ( strpos( $ori, 'defer' ) !== false ) { + if (strpos($ori, 'defer') !== false) { return false; } - if ( strpos( $ori, 'data-deferred' ) !== false ) { - Debug2::debug2( '[Optm] bypass: attr data-deferred exist' ); + if (strpos($ori, 'data-deferred') !== false) { + Debug2::debug2('[Optm] bypass: attr data-deferred exist'); return false; } - if ( strpos( $ori, 'data-no-defer' ) !== false ) { - Debug2::debug2( '[Optm] bypass: attr api data-no-defer' ); + if (strpos($ori, 'data-no-defer') !== false) { + Debug2::debug2('[Optm] bypass: attr api data-no-defer'); return false; } @@ -1159,19 +1246,51 @@ private function _js_defer( $ori, $src ) { * Exclude JS from setting * @since 1.5 */ - if ( Utility::str_hit_array( $src, $this->cfg_js_defer_exc ) ) { - Debug2::debug( '[Optm] js defer exclude ' . $src ); + if (Utility::str_hit_array($src, $this->cfg_js_defer_exc)) { + Debug2::debug('[Optm] js defer exclude ' . $src); return false; } - if ( $this->cfg_js_defer === 2 ) { - if ( strpos( $ori, ' type=' ) !== false ) { - $ori = preg_replace( '# type=([\'"])([^\1]+)\1#isU', '', $ori ); + if ($this->cfg_js_defer === 2 || Utility::str_hit_array($src, $this->cfg_js_delay_inc)) { + if (strpos($ori, ' type=') !== false) { + $ori = preg_replace('# type=([\'"])([^\1]+)\1#isU', '', $ori); } - return str_replace( ' src=', ' type="litespeed/javascript" data-src=', $ori ); + return str_replace(' src=', ' type="litespeed/javascript" data-src=', $ori); } - return str_replace( '>', ' defer data-deferred="1">', $ori ); + return str_replace('>', ' defer data-deferred="1">', $ori); } + /** + * Delay JS for included setting + * + * @since 5.6 + */ + private function _js_delay($ori, $src) + { + if (strpos($ori, ' async') !== false) { + $ori = str_replace(' async', '', $ori); + } + + if (strpos($ori, 'defer') !== false) { + return false; + } + if (strpos($ori, 'data-deferred') !== false) { + Debug2::debug2('[Optm] bypass: attr data-deferred exist'); + return false; + } + if (strpos($ori, 'data-no-defer') !== false) { + Debug2::debug2('[Optm] bypass: attr api data-no-defer'); + return false; + } + + if (!Utility::str_hit_array($src, $this->cfg_js_delay_inc)) { + return; + } + + if (strpos($ori, ' type=') !== false) { + $ori = preg_replace('# type=([\'"])([^\1]+)\1#isU', '', $ori); + } + return str_replace(' src=', ' type="litespeed/javascript" data-src=', $ori); + } } diff --git a/src/optimizer.cls.php b/src/optimizer.cls.php index 1b410a180..662c6b680 100644 --- a/src/optimizer.cls.php +++ b/src/optimizer.cls.php @@ -9,9 +9,10 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Optimizer extends Root { +class Optimizer extends Root +{ private $_conf_css_font_display; /** @@ -19,8 +20,9 @@ class Optimizer extends Root { * * @since 1.9 */ - public function __construct() { - $this->_conf_css_font_display = $this->conf( Base::O_OPTM_CSS_FONT_DISPLAY ); + public function __construct() + { + $this->_conf_css_font_display = $this->conf(Base::O_OPTM_CSS_FONT_DISPLAY); } /** @@ -29,11 +31,17 @@ public function __construct() { * @since 1.9 * @access public */ - public function html_min( $content, $force_inline_minify = false ) { + public function html_min($content, $force_inline_minify = false) + { + if (!apply_filters('litespeed_html_min', true)) { + Debug2::debug2('[Optmer] html_min bypassed via litespeed_html_min filter'); + return $content; + } + $options = array(); - if ( $force_inline_minify ) { - $options[ 'jsMinifier' ] = __CLASS__ . '::minify_js'; + if ($force_inline_minify) { + $options['jsMinifier'] = __CLASS__ . '::minify_js'; } /** @@ -41,16 +49,15 @@ public function html_min( $content, $force_inline_minify = false ) { * @since 2.2.3 */ try { - $obj = new Lib\HTML_MIN( $content, $options ); + $obj = new Lib\HTML_MIN($content, $options); $content_final = $obj->process(); - if ( ! defined( 'LSCACHE_ESI_SILENCE' ) ) { - $content_final .= "\n" . ''; + if (!defined('LSCACHE_ESI_SILENCE')) { + $content_final .= "\n" . ''; } return $content_final; - - } catch ( \Exception $e ) { - Debug2::debug( '******[Optmer] html_min failed: ' . $e->getMessage() ); - error_log( '****** LiteSpeed Optimizer html_min failed: ' . $e->getMessage() ); + } catch (\Exception $e) { + Debug2::debug('******[Optmer] html_min failed: ' . $e->getMessage()); + error_log('****** LiteSpeed Optimizer html_min failed: ' . $e->getMessage()); return $content; } } @@ -61,28 +68,28 @@ public function html_min( $content, $force_inline_minify = false ) { * @since 1.9 * @access public */ - public function serve( $request_url, $file_type, $minify, $src_list ) { + public function serve($request_url, $file_type, $minify, $src_list) + { // Try Unique CSS - if ( $file_type == 'css' ) { + if ($file_type == 'css') { $content = false; - if ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_OPTM_UCSS ) ) { - $filename = $this->cls( 'UCSS' )->load( $request_url ); + if (defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_OPTM_UCSS)) { + $filename = $this->cls('UCSS')->load($request_url); - if ( $filename ) { - return array( $filename, 'ucss' ); + if ($filename) { + return array($filename, 'ucss'); } } } // Before generated, don't know the contented hash filename yet, so used url hash as tmp filename - $file_path_prefix = $this->_build_filepath_prefix( $file_type ); + $file_path_prefix = $this->_build_filepath_prefix($file_type); $url_tag = $request_url; - $url_tag_for_file = md5( $request_url ); - if ( is_404() ) { + $url_tag_for_file = md5($request_url); + if (is_404()) { $url_tag_for_file = $url_tag = '404'; - } - elseif ( $file_type == 'css' && apply_filters( 'litespeed_ucss_per_pagetype', false ) ) { + } elseif ($file_type == 'css' && apply_filters('litespeed_ucss_per_pagetype', false)) { $url_tag_for_file = $url_tag = Utility::page_type(); } @@ -90,95 +97,94 @@ public function serve( $request_url, $file_type, $minify, $src_list ) { // Create tmp file to avoid conflict $tmp_static_file = $static_file . '.tmp'; - if ( file_exists( $tmp_static_file ) && time() - filemtime( $tmp_static_file ) <= 600 ) { // some other request is generating + if (file_exists($tmp_static_file) && time() - filemtime($tmp_static_file) <= 600) { + // some other request is generating return false; } // File::save( $tmp_static_file, '/* ' . ( is_404() ? '404' : $request_url ) . ' */', true ); // Can't use this bcos this will get filecon md5 changed - File::save( $tmp_static_file, '', true ); + File::save($tmp_static_file, '', true); // Load content $real_files = array(); - foreach ( $src_list as $src_info ) { + foreach ($src_list as $src_info) { $is_min = false; - if ( ! empty( $src_info[ 'inl' ] ) ) { // Load inline - $content = $src_info[ 'src' ]; - } - else { // Load file - $content = $this->load_file( $src_info[ 'src' ], $file_type ); - - if ( ! $content ) { + if (!empty($src_info['inl'])) { + // Load inline + $content = $src_info['src']; + } else { + // Load file + $content = $this->load_file($src_info['src'], $file_type); + + if (!$content) { continue; } - $is_min = $this->is_min( $src_info[ 'src' ] ); + $is_min = $this->is_min($src_info['src']); } - $content = $this->optm_snippet( $content, $file_type, $minify && ! $is_min, $src_info[ 'src' ], ! empty( $src_info[ 'media' ] ) ? $src_info[ 'media' ] : false ); + $content = $this->optm_snippet($content, $file_type, $minify && !$is_min, $src_info['src'], !empty($src_info['media']) ? $src_info['media'] : false); // Write to file - File::save( $tmp_static_file, $content, true, true ); + File::save($tmp_static_file, $content, true, true); } // validate md5 - $filecon_md5 = md5_file( $tmp_static_file ); + $filecon_md5 = md5_file($tmp_static_file); $final_file_path = $file_path_prefix . $filecon_md5 . '.' . $file_type; $realfile = LITESPEED_STATIC_DIR . $final_file_path; - if ( ! file_exists( $realfile ) ) { - rename( $tmp_static_file, $realfile ); - Debug2::debug2( '[Optmer] Saved static file [path] ' . $realfile ); - } - else { - unlink( $tmp_static_file ); + if (!file_exists($realfile)) { + rename($tmp_static_file, $realfile); + Debug2::debug2('[Optmer] Saved static file [path] ' . $realfile); + } else { + unlink($tmp_static_file); } - $vary = $this->cls( 'Vary' )->finalize_full_varies(); - Debug2::debug2( "[Optmer] Save URL to file for [file_type] $file_type [file] $filecon_md5 [vary] $vary " ); - $this->cls( 'Data' )->save_url( $url_tag, $vary, $file_type, $filecon_md5, dirname( $realfile ) ); + $vary = $this->cls('Vary')->finalize_full_varies(); + Debug2::debug2("[Optmer] Save URL to file for [file_type] $file_type [file] $filecon_md5 [vary] $vary "); + $this->cls('Data')->save_url($url_tag, $vary, $file_type, $filecon_md5, dirname($realfile)); - return array( $filecon_md5 . '.' . $file_type, $file_type ); + return array($filecon_md5 . '.' . $file_type, $file_type); } /** * Load a single file * @since 4.0 */ - public function optm_snippet( $content, $file_type, $minify, $src, $media = false ) { + public function optm_snippet($content, $file_type, $minify, $src, $media = false) + { // CSS related features - if ( $file_type == 'css' ) { + if ($file_type == 'css') { // Font optimize - if ( $this->_conf_css_font_display ) { - $content = preg_replace( '#(@font\-face\s*\{)#isU', '${1}font-display:swap;', $content ); + if ($this->_conf_css_font_display) { + $content = preg_replace('#(@font\-face\s*\{)#isU', '${1}font-display:swap;', $content); } - $content = preg_replace( '/@charset[^;]+;\\s*/', '', $content ); + $content = preg_replace('/@charset[^;]+;\\s*/', '', $content); - if ( $media ) { + if ($media) { $content = '@media ' . $media . '{' . $content . "\n}"; } - if ( $minify ) { - $content = self::minify_css( $content ); + if ($minify) { + $content = self::minify_css($content); } - $content = $this->cls( 'CDN' )->finalize( $content ); + $content = $this->cls('CDN')->finalize($content); - if ( ( defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( Base::O_IMG_OPTM_WEBP_REPLACE ) ) && $this->cls( 'Media' )->webp_support() ) { - $content = $this->cls( 'Media' )->replace_background_webp( $content ); + if ((defined('LITESPEED_GUEST_OPTM') || $this->conf(Base::O_IMG_OPTM_WEBP)) && $this->cls('Media')->webp_support()) { + $content = $this->cls('Media')->replace_background_webp($content); } - - } - else { - if ( $minify ) { - $content = self::minify_js( $content ); - } - else { - $content = $this->_null_minifier( $content ); + } else { + if ($minify) { + $content = self::minify_js($content); + } else { + $content = $this->_null_minifier($content); } $content .= "\n;"; } // Add filter - $content = apply_filters( 'litespeed_optm_cssjs', $content, $file_type, $src ); + $content = apply_filters('litespeed_optm_cssjs', $content, $file_type, $src); return $content; } @@ -188,32 +194,35 @@ public function optm_snippet( $content, $file_type, $minify, $src, $media = fals * * @since 4.7 */ - private function load_cached_file( $url, $file_type ) { - $file_path_prefix = $this->_build_filepath_prefix( $file_type ); + private function load_cached_file($url, $file_type) + { + $file_path_prefix = $this->_build_filepath_prefix($file_type); $folder_name = LITESPEED_STATIC_DIR . $file_path_prefix; - $to_be_deleted_folder = $folder_name . date( 'Ymd', strtotime( '-2 days') ); - if ( file_exists( $to_be_deleted_folder ) ) { - Debug2::debug( '[Optimizer] ❌ Clearning folder [name] ' . $to_be_deleted_folder ); - File::rrmdir( $to_be_deleted_folder ); + $to_be_deleted_folder = $folder_name . date('Ymd', strtotime('-2 days')); + if (file_exists($to_be_deleted_folder)) { + Debug2::debug('[Optimizer] ❌ Clearning folder [name] ' . $to_be_deleted_folder); + File::rrmdir($to_be_deleted_folder); } - $today_file = $folder_name . date( 'Ymd' ) . '/' . md5( $url ); - if( file_exists( $today_file ) ) return File::read( $today_file ); + $today_file = $folder_name . date('Ymd') . '/' . md5($url); + if (file_exists($today_file)) { + return File::read($today_file); + } // Write file - $res = wp_remote_get( $url ); - $res_code = wp_remote_retrieve_response_code( $res ); - if ( is_wp_error( $res ) || $res_code != 200 ) { - Debug2::debug2( '[Optimizer] ❌ Load Remote error [code] ' . $res_code ); + $res = wp_remote_get($url); + $res_code = wp_remote_retrieve_response_code($res); + if (is_wp_error($res) || $res_code != 200) { + Debug2::debug2('[Optimizer] ❌ Load Remote error [code] ' . $res_code); return false; } - $con = wp_remote_retrieve_body( $res ); - if ( ! $con ) { + $con = wp_remote_retrieve_body($res); + if (!$con) { return false; } - Debug2::debug( '[Optimizer] ✅ Save remote file to cache [name] ' . $today_file ); - File::save( $today_file, $con, true ); + Debug2::debug('[Optimizer] ✅ Save remote file to cache [name] ' . $today_file); + File::save($today_file, $con, true); return $con; } @@ -223,28 +232,28 @@ private function load_cached_file( $url, $file_type ) { * * @since 3.5 */ - public function load_file( $src, $file_type = 'css' ) { - $real_file = Utility::is_internal_file( $src ); - $postfix = pathinfo( parse_url( $src, PHP_URL_PATH ), PATHINFO_EXTENSION ); - if ( ! $real_file || $postfix != $file_type ) { - Debug2::debug2( '[CSS] Load Remote [' . $file_type . '] ' . $src ); - $this_url = substr( $src, 0, 2 ) == '//' ? set_url_scheme( $src ) : $src; + public function load_file($src, $file_type = 'css') + { + $real_file = Utility::is_internal_file($src); + $postfix = pathinfo(parse_url($src, PHP_URL_PATH), PATHINFO_EXTENSION); + if (!$real_file || $postfix != $file_type) { + Debug2::debug2('[CSS] Load Remote [' . $file_type . '] ' . $src); + $this_url = substr($src, 0, 2) == '//' ? set_url_scheme($src) : $src; $con = $this->load_cached_file($this_url, $file_type); - if ( $file_type == 'css' ) { - $dirname = dirname( $this_url ) . '/'; + if ($file_type == 'css') { + $dirname = dirname($this_url) . '/'; - $con = Lib\CSS_MIN\UriRewriter::prepend( $con, $dirname ); + $con = Lib\CSS_MIN\UriRewriter::prepend($con, $dirname); } - } - else { - Debug2::debug2( '[CSS] Load local [' . $file_type . '] ' . $real_file[ 0 ] ); - $con = File::read( $real_file[ 0 ] ); + } else { + Debug2::debug2('[CSS] Load local [' . $file_type . '] ' . $real_file[0]); + $con = File::read($real_file[0]); - if ( $file_type == 'css' ) { - $dirname = dirname( $real_file[ 0 ] ); + if ($file_type == 'css') { + $dirname = dirname($real_file[0]); - $con = Lib\CSS_MIN\UriRewriter::rewrite( $con, $dirname ); + $con = Lib\CSS_MIN\UriRewriter::rewrite($con, $dirname); } } @@ -257,14 +266,14 @@ public function load_file( $src, $file_type = 'css' ) { * @since 2.2.3 * @access private */ - public static function minify_css( $data ) { + public static function minify_css($data) + { try { $obj = new Lib\CSS_MIN\Minifier(); - return $obj->run( $data ); - - } catch ( \Exception $e ) { - Debug2::debug( '******[Optmer] minify_css failed: ' . $e->getMessage() ); - error_log( '****** LiteSpeed Optimizer minify_css failed: ' . $e->getMessage() ); + return $obj->run($data); + } catch (\Exception $e) { + Debug2::debug('******[Optmer] minify_css failed: ' . $e->getMessage()); + error_log('****** LiteSpeed Optimizer minify_css failed: ' . $e->getMessage()); return $data; } } @@ -277,21 +286,22 @@ public static function minify_css( $data ) { * @since 2.2.3 * @access private */ - public static function minify_js( $data, $js_type = '' ) { + public static function minify_js($data, $js_type = '') + { // For inline JS optimize, need to check if it's js type - if ( $js_type ) { - preg_match( '#type=([\'"])(.+)\g{1}#isU', $js_type, $matches ); - if ( $matches && $matches[ 2 ] != 'text/javascript' ) { - Debug2::debug( '******[Optmer] minify_js bypass due to type: ' . $matches[ 2 ] ); + if ($js_type) { + preg_match('#type=([\'"])(.+)\g{1}#isU', $js_type, $matches); + if ($matches && $matches[2] != 'text/javascript') { + Debug2::debug('******[Optmer] minify_js bypass due to type: ' . $matches[2]); return $data; } } try { - $data = Lib\JSMin::minify( $data ); + $data = Lib\JSMin::minify($data); return $data; - } catch ( \Exception $e ) { - Debug2::debug( '******[Optmer] minify_js failed: ' . $e->getMessage() ); + } catch (\Exception $e) { + Debug2::debug('******[Optmer] minify_js failed: ' . $e->getMessage()); // error_log( '****** LiteSpeed Optimizer minify_js failed: ' . $e->getMessage() ); return $data; } @@ -302,10 +312,11 @@ public static function minify_js( $data, $js_type = '' ) { * * @access private */ - private function _null_minifier( $content ) { - $content = str_replace( "\r\n", "\n", $content ); + private function _null_minifier($content) + { + $content = str_replace("\r\n", "\n", $content); - return trim( $content ); + return trim($content); } /** @@ -313,15 +324,13 @@ private function _null_minifier( $content ) { * * @since 1.9 */ - public function is_min( $filename ) { - $basename = basename( $filename ); - if ( preg_match( '/[-\.]min\.(?:[a-zA-Z]+)$/i', $basename ) ) { + public function is_min($filename) + { + $basename = basename($filename); + if (preg_match('/[-\.]min\.(?:[a-zA-Z]+)$/i', $basename)) { return true; } return false; } - } - - diff --git a/src/placeholder.cls.php b/src/placeholder.cls.php index 94a885f20..48ac70fe4 100644 --- a/src/placeholder.cls.php +++ b/src/placeholder.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Placeholder extends Base { +class Placeholder extends Base +{ const TYPE_GENERATE = 'generate'; const TYPE_CLEAR_Q = 'clear_q'; @@ -23,6 +26,7 @@ class Placeholder extends Base { private $_conf_lqip_min_h; private $_conf_placeholder_resp_color; private $_conf_placeholder_resp_async; + private $_conf_ph_default; private $_placeholder_resp_dict = array(); private $_ph_queue = array(); @@ -33,16 +37,17 @@ class Placeholder extends Base { * * @since 3.0 */ - public function __construct() { - $this->_conf_placeholder_resp = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_MEDIA_PLACEHOLDER_RESP ); - $this->_conf_placeholder_resp_svg = $this->conf( self::O_MEDIA_PLACEHOLDER_RESP_SVG ); - $this->_conf_lqip = ! defined( 'LITESPEED_GUEST_OPTM' ) && $this->conf( self::O_MEDIA_LQIP ); - $this->_conf_lqip_qual = $this->conf( self::O_MEDIA_LQIP_QUAL ); - $this->_conf_lqip_min_w = $this->conf( self::O_MEDIA_LQIP_MIN_W ); - $this->_conf_lqip_min_h = $this->conf( self::O_MEDIA_LQIP_MIN_H ); - $this->_conf_placeholder_resp_async = $this->conf( self::O_MEDIA_PLACEHOLDER_RESP_ASYNC ); - $this->_conf_placeholder_resp_color = $this->conf( self::O_MEDIA_PLACEHOLDER_RESP_COLOR ); - $this->_conf_ph_default = $this->conf( self::O_MEDIA_LAZY_PLACEHOLDER ) ?: LITESPEED_PLACEHOLDER; + public function __construct() + { + $this->_conf_placeholder_resp = defined('LITESPEED_GUEST_OPTM') || $this->conf(self::O_MEDIA_PLACEHOLDER_RESP); + $this->_conf_placeholder_resp_svg = $this->conf(self::O_MEDIA_PLACEHOLDER_RESP_SVG); + $this->_conf_lqip = !defined('LITESPEED_GUEST_OPTM') && $this->conf(self::O_MEDIA_LQIP); + $this->_conf_lqip_qual = $this->conf(self::O_MEDIA_LQIP_QUAL); + $this->_conf_lqip_min_w = $this->conf(self::O_MEDIA_LQIP_MIN_W); + $this->_conf_lqip_min_h = $this->conf(self::O_MEDIA_LQIP_MIN_H); + $this->_conf_placeholder_resp_async = $this->conf(self::O_MEDIA_PLACEHOLDER_RESP_ASYNC); + $this->_conf_placeholder_resp_color = $this->conf(self::O_MEDIA_PLACEHOLDER_RESP_COLOR); + $this->_conf_ph_default = $this->conf(self::O_MEDIA_LAZY_PLACEHOLDER) ?: LITESPEED_PLACEHOLDER; $this->_summary = self::get_summary(); } @@ -50,10 +55,11 @@ public function __construct() { /** * Init Placeholder */ - public function init() { - Debug2::debug2( '[LQIP] init' ); + public function init() + { + Debug2::debug2('[LQIP] init'); - add_action( 'litspeed_after_admin_init', array( $this, 'after_admin_init' ) ); + add_action('litspeed_after_admin_init', array($this, 'after_admin_init')); } /** @@ -62,11 +68,12 @@ public function init() { * @since 3.0 * @access public */ - public function after_admin_init() { - if ( $this->_conf_lqip ) { - add_filter( 'manage_media_columns', array( $this, 'media_row_title' ) ); - add_filter( 'manage_media_custom_column', array( $this, 'media_row_actions' ), 10, 2 ); - add_action( 'litespeed_media_row_lqip', array( $this, 'media_row_con' ) ); + public function after_admin_init() + { + if ($this->_conf_lqip) { + add_filter('manage_media_columns', array($this, 'media_row_title')); + add_filter('manage_media_custom_column', array($this, 'media_row_actions'), 10, 2); + add_action('litespeed_media_row_lqip', array($this, 'media_row_con')); } } @@ -76,8 +83,9 @@ public function after_admin_init() { * @since 3.0 * @access public */ - public function media_row_title( $posts_columns ) { - $posts_columns[ 'lqip' ] = __( 'LQIP', 'litespeed-cache' ); + public function media_row_title($posts_columns) + { + $posts_columns['lqip'] = __('LQIP', 'litespeed-cache'); return $posts_columns; } @@ -88,68 +96,68 @@ public function media_row_title( $posts_columns ) { * @since 3.0 * @access public */ - public function media_row_actions( $column_name, $post_id ) { - if ( $column_name !== 'lqip' ) { + public function media_row_actions($column_name, $post_id) + { + if ($column_name !== 'lqip') { return; } - do_action( 'litespeed_media_row_lqip', $post_id ); - + do_action('litespeed_media_row_lqip', $post_id); } - /** * Display LQIP column * * @since 3.0 * @access public */ - public function media_row_con( $post_id ) { - $meta_value = wp_get_attachment_metadata( $post_id ); + public function media_row_con($post_id) + { + $meta_value = wp_get_attachment_metadata($post_id); - if ( empty( $meta_value[ 'file' ] ) ) { + if (empty($meta_value['file'])) { return; } $total_files = 0; // List all sizes - $all_sizes = array( $meta_value[ 'file' ] ); - $size_path = pathinfo( $meta_value[ 'file' ], PATHINFO_DIRNAME ) . '/'; - foreach ( $meta_value[ 'sizes' ] as $v ) { - $all_sizes[] = $size_path . $v[ 'file' ]; + $all_sizes = array($meta_value['file']); + $size_path = pathinfo($meta_value['file'], PATHINFO_DIRNAME) . '/'; + foreach ($meta_value['sizes'] as $v) { + $all_sizes[] = $size_path . $v['file']; } - foreach ( $all_sizes as $short_path ) { + foreach ($all_sizes as $short_path) { $lqip_folder = LITESPEED_STATIC_DIR . '/lqip/' . $short_path; - if ( is_dir( $lqip_folder ) ) { - Debug2::debug( '[LQIP] Found folder: ' . $short_path ); - - + if (is_dir($lqip_folder)) { + Debug2::debug('[LQIP] Found folder: ' . $short_path); // List all files - foreach ( scandir( $lqip_folder ) as $v ) { - if ( $v == '.' || $v == '..' ) { + foreach (scandir($lqip_folder) as $v) { + if ($v == '.' || $v == '..') { continue; } - if ( $total_files == 0 ) { - echo '
    ' . sprintf( __( 'LQIP image preview for size %s', 'litespeed-cache' ), $v ) .'
    '; + if ($total_files == 0) { + echo '
    ' .
+							sprintf(__('LQIP image preview for size %s', 'litespeed-cache'), $v) .
+							'
    '; } - echo ''; + echo ''; $total_files++; } - } } - if ( $total_files == 0 ) { + if ($total_files == 0) { echo '—'; } - } /** @@ -158,19 +166,20 @@ public function media_row_con( $post_id ) { * @since 3.0 * @access public */ - public function replace( $html, $src, $size ) { + public function replace($html, $src, $size) + { // Check if need to enable responsive placeholder or not - $this_placeholder = $this->_placeholder( $src, $size ) ?: $this->_conf_ph_default; + $this_placeholder = $this->_placeholder($src, $size) ?: $this->_conf_ph_default; $additional_attr = ''; - if ( $this->_conf_lqip && $this_placeholder != $this->_conf_ph_default ) { - Debug2::debug2( '[LQIP] Use resp LQIP [size] ' . $size ); + if ($this->_conf_lqip && $this_placeholder != $this->_conf_ph_default) { + Debug2::debug2('[LQIP] Use resp LQIP [size] ' . $size); $additional_attr = ' data-placeholder-resp="' . $size . '"'; } - $snippet = defined( 'LITESPEED_GUEST_OPTM' ) || $this->conf( self::O_OPTM_NOSCRIPT_RM ) ? '' : ''; - $html = str_replace( array( ' src=', ' srcset=', ' sizes=' ), array( ' data-src=', ' data-srcset=', ' data-sizes=' ), $html ); - $html = str_replace( 'conf(self::O_OPTM_NOSCRIPT_RM) ? '' : ''; + $html = str_replace(array(' src=', ' srcset=', ' sizes='), array(' data-src=', ' data-srcset=', ' data-sizes='), $html); + $html = str_replace('_conf_placeholder_resp ) { + if (!$this->_conf_placeholder_resp) { return false; } // If use local generator - if ( ! $this->_conf_lqip || ! $this->_lqip_size_check( $size ) ) { - return $this->_generate_placeholder_locally( $size ); + if (!$this->_conf_lqip || !$this->_lqip_size_check($size)) { + return $this->_generate_placeholder_locally($size); } - Debug2::debug2( '[LQIP] Resp LQIP process [src] ' . $src . ' [size] ' . $size ); + Debug2::debug2('[LQIP] Resp LQIP process [src] ' . $src . ' [size] ' . $size); $arr_key = $size . ' ' . $src; // Check if its already in dict or not - if ( ! empty( $this->_placeholder_resp_dict[ $arr_key ] ) ) { - Debug2::debug2( '[LQIP] already in dict' ); + if (!empty($this->_placeholder_resp_dict[$arr_key])) { + Debug2::debug2('[LQIP] already in dict'); - return $this->_placeholder_resp_dict[ $arr_key ]; + return $this->_placeholder_resp_dict[$arr_key]; } // Need to generate the responsive placeholder - $placeholder_realpath = $this->_placeholder_realpath( $src, $size ); // todo: give offload API - if ( file_exists( $placeholder_realpath ) ) { - Debug2::debug2( '[LQIP] file exists' ); - $this->_placeholder_resp_dict[ $arr_key ] = File::read( $placeholder_realpath ); + $placeholder_realpath = $this->_placeholder_realpath($src, $size); // todo: give offload API + if (file_exists($placeholder_realpath)) { + Debug2::debug2('[LQIP] file exists'); + $this->_placeholder_resp_dict[$arr_key] = File::read($placeholder_realpath); - return $this->_placeholder_resp_dict[ $arr_key ]; + return $this->_placeholder_resp_dict[$arr_key]; } // Add to cron queue // Prevent repeated requests - if ( in_array( $arr_key, $this->_ph_queue ) ) { - Debug2::debug2( '[LQIP] file bypass generating due to in queue' ); - return $this->_generate_placeholder_locally( $size ); + if (in_array($arr_key, $this->_ph_queue)) { + Debug2::debug2('[LQIP] file bypass generating due to in queue'); + return $this->_generate_placeholder_locally($size); } - if ( $hit = Utility::str_hit_array( $src, $this->conf( self::O_MEDIA_LQIP_EXC ) ) ) { - Debug2::debug2( '[LQIP] file bypass generating due to exclude setting [hit] ' . $hit ); - return $this->_generate_placeholder_locally( $size ); + if ($hit = Utility::str_hit_array($src, $this->conf(self::O_MEDIA_LQIP_EXC))) { + Debug2::debug2('[LQIP] file bypass generating due to exclude setting [hit] ' . $hit); + return $this->_generate_placeholder_locally($size); } $this->_ph_queue[] = $arr_key; // Send request to generate placeholder - if ( ! $this->_conf_placeholder_resp_async ) { + if (!$this->_conf_placeholder_resp_async) { // If requested recently, bypass - if ( $this->_summary && ! empty( $this->_summary[ 'curr_request' ] ) && time() - $this->_summary[ 'curr_request' ] < 300 ) { - Debug2::debug2( '[LQIP] file bypass generating due to interval limit' ); + if ($this->_summary && !empty($this->_summary['curr_request']) && time() - $this->_summary['curr_request'] < 300) { + Debug2::debug2('[LQIP] file bypass generating due to interval limit'); return false; } // Generate immediately - $this->_placeholder_resp_dict[ $arr_key ] = $this->_generate_placeholder( $arr_key ); + $this->_placeholder_resp_dict[$arr_key] = $this->_generate_placeholder($arr_key); - return $this->_placeholder_resp_dict[ $arr_key ]; + return $this->_placeholder_resp_dict[$arr_key]; } // Prepare default svg placeholder as tmp placeholder - $tmp_placeholder = $this->_generate_placeholder_locally( $size ); + $tmp_placeholder = $this->_generate_placeholder_locally($size); // Store it to prepare for cron - $queue = $this->load_queue( 'lqip' ); - if ( in_array( $arr_key, $queue ) ) { - Debug2::debug2( '[LQIP] already in queue' ); + $queue = $this->load_queue('lqip'); + if (in_array($arr_key, $queue)) { + Debug2::debug2('[LQIP] already in queue'); return $tmp_placeholder; } - if ( count( $queue ) > 500 ) { - Debug2::debug2( '[LQIP] queue is full' ); + if (count($queue) > 500) { + Debug2::debug2('[LQIP] queue is full'); return $tmp_placeholder; } $queue[] = $arr_key; - $this->save_queue( 'lqip', $queue ); - Debug2::debug( '[LQIP] Added placeholder queue' ); + $this->save_queue('lqip', $queue); + Debug2::debug('[LQIP] Added placeholder queue'); return $tmp_placeholder; } @@ -276,29 +286,30 @@ private function _placeholder( $src, $size ) { * @since 2.5.1 * @access private */ - private function _placeholder_realpath( $src, $size ) { + private function _placeholder_realpath($src, $size) + { // Use LQIP Cloud generator, each image placeholder will be separately stored // Compatibility with WebP - if ( substr( $src, -5 ) === '.webp' ) { - $src = substr( $src, 0, -5 ); + if (substr($src, -5) === '.webp') { + $src = substr($src, 0, -5); } - $filepath_prefix = $this->_build_filepath_prefix( 'lqip' ); + $filepath_prefix = $this->_build_filepath_prefix('lqip'); // External images will use cache folder directly - $domain = parse_url( $src, PHP_URL_HOST ); - if ( $domain && ! Utility::internal( $domain ) ) { // todo: need to improve `util:internal()` to include `CDN::internal()` - $md5 = md5( $src ); + $domain = parse_url($src, PHP_URL_HOST); + if ($domain && !Utility::internal($domain)) { + // todo: need to improve `util:internal()` to include `CDN::internal()` + $md5 = md5($src); - return LITESPEED_STATIC_DIR . $filepath_prefix . 'remote/' . substr( $md5, 0, 1 ) . '/' . substr( $md5, 1, 1 ) . '/' . $md5 . '.' . $size; + return LITESPEED_STATIC_DIR . $filepath_prefix . 'remote/' . substr($md5, 0, 1) . '/' . substr($md5, 1, 1) . '/' . $md5 . '.' . $size; } // Drop domain - $short_path = Utility::att_short_path( $src ); + $short_path = Utility::att_short_path($src); return LITESPEED_STATIC_DIR . $filepath_prefix . $short_path . '/' . $size; - } /** @@ -307,35 +318,36 @@ private function _placeholder_realpath( $src, $size ) { * @since 2.5.1 * @access public */ - public static function cron( $continue = false ) { + public static function cron($continue = false) + { $_instance = self::cls(); - $queue = $_instance->load_queue( 'lqip' ); + $queue = $_instance->load_queue('lqip'); - if ( empty( $queue ) ) { + if (empty($queue)) { return; } // For cron, need to check request interval too - if ( ! $continue ) { - if ( ! empty( $_instance->_summary[ 'curr_request' ] ) && time() - $_instance->_summary[ 'curr_request' ] < 300 ) { - Debug2::debug( '[LQIP] Last request not done' ); + if (!$continue) { + if (!empty($_instance->_summary['curr_request']) && time() - $_instance->_summary['curr_request'] < 300) { + Debug2::debug('[LQIP] Last request not done'); return; } } - foreach ( $queue as $v ) { - Debug2::debug( '[LQIP] cron job [size] ' . $v ); + foreach ($queue as $v) { + Debug2::debug('[LQIP] cron job [size] ' . $v); - $res = $_instance->_generate_placeholder( $v, true ); + $res = $_instance->_generate_placeholder($v, true); // Exit queue if out of quota - if ( $res === 'out_of_quota' ) { + if ($res === 'out_of_quota') { return; } // only request first one - if ( ! $continue ) { + if (!$continue) { return; } } @@ -347,14 +359,15 @@ public static function cron( $continue = false ) { * @since 3.0 * @access private */ - private function _generate_placeholder_locally( $size ) { - Debug2::debug2( '[LQIP] _generate_placeholder local [size] ' . $size ); + private function _generate_placeholder_locally($size) + { + Debug2::debug2('[LQIP] _generate_placeholder local [size] ' . $size); - $size = explode( 'x', $size ); + $size = explode('x', $size); - $svg = str_replace( array( '{width}', '{height}', '{color}' ), array( $size[ 0 ], $size[ 1 ], $this->_conf_placeholder_resp_color ), $this->_conf_placeholder_resp_svg ); + $svg = str_replace(array('{width}', '{height}', '{color}'), array($size[0], $size[1], $this->_conf_placeholder_resp_color), $this->_conf_placeholder_resp_svg); - return 'data:image/svg+xml;base64,' . base64_encode( $svg ); + return 'data:image/svg+xml;base64,' . base64_encode($svg); } /** @@ -363,90 +376,90 @@ private function _generate_placeholder_locally( $size ) { * @since 2.5.1 * @access private */ - private function _generate_placeholder( $raw_size_and_src, $from_cron = false ) { + private function _generate_placeholder($raw_size_and_src, $from_cron = false) + { // Parse containing size and src info - $size_and_src = explode( ' ', $raw_size_and_src, 2 ); - $size = $size_and_src[ 0 ]; + $size_and_src = explode(' ', $raw_size_and_src, 2); + $size = $size_and_src[0]; - if ( empty( $size_and_src[ 1 ] ) ) { - $this->_popup_and_save( $raw_size_and_src ); - Debug2::debug( '[LQIP] ❌ No src [raw] ' . $raw_size_and_src ); - return $this->_generate_placeholder_locally( $size ); + if (empty($size_and_src[1])) { + $this->_popup_and_save($raw_size_and_src); + Debug2::debug('[LQIP] ❌ No src [raw] ' . $raw_size_and_src); + return $this->_generate_placeholder_locally($size); } - $src = $size_and_src[ 1 ]; + $src = $size_and_src[1]; - $file = $this->_placeholder_realpath( $src, $size ); + $file = $this->_placeholder_realpath($src, $size); // Local generate SVG to serve ( Repeatly doing this here to remove stored cron queue in case the setting _conf_lqip is changed ) - if ( ! $this->_conf_lqip || ! $this->_lqip_size_check( $size ) ) { - $data = $this->_generate_placeholder_locally( $size ); - } - else { + if (!$this->_conf_lqip || !$this->_lqip_size_check($size)) { + $data = $this->_generate_placeholder_locally($size); + } else { $err = false; - $allowance = Cloud::cls()->allowance( Cloud::SVC_LQIP, $err ); - if ( ! $allowance ) { - Debug2::debug( '[LQIP] ❌ No credit: ' . $err ); - $err && Admin_Display::error( Error::msg( $err ) ); + $allowance = Cloud::cls()->allowance(Cloud::SVC_LQIP, $err); + if (!$allowance) { + Debug2::debug('[LQIP] ❌ No credit: ' . $err); + $err && Admin_Display::error(Error::msg($err)); - if ( $from_cron ) { + if ($from_cron) { return 'out_of_quota'; } - return $this->_generate_placeholder_locally( $size ); + return $this->_generate_placeholder_locally($size); } // Generate LQIP - list( $width, $height ) = explode( 'x', $size ); + list($width, $height) = explode('x', $size); $req_data = array( - 'width' => $width, - 'height' => $height, - 'url' => substr( $src, -5 ) === '.webp' ? substr( $src, 0, -5 ) : $src, - 'quality' => $this->_conf_lqip_qual, + 'width' => $width, + 'height' => $height, + 'url' => substr($src, -5) === '.webp' ? substr($src, 0, -5) : $src, + 'quality' => $this->_conf_lqip_qual, ); // CHeck if the image is 404 first - if ( File::is_404( $req_data[ 'url' ] ) ) { - $this->_popup_and_save( $raw_size_and_src, true ); - $this->_append_exc( $src ); - Debug2::debug( '[LQIP] 404 before request [src] ' . $req_data[ 'url' ] ); - return $this->_generate_placeholder_locally( $size ); + if (File::is_404($req_data['url'])) { + $this->_popup_and_save($raw_size_and_src, true); + $this->_append_exc($src); + Debug2::debug('[LQIP] 404 before request [src] ' . $req_data['url']); + return $this->_generate_placeholder_locally($size); } // Update request status - $this->_summary[ 'curr_request' ] = time(); + $this->_summary['curr_request'] = time(); self::save_summary(); - $json = Cloud::post( Cloud::SVC_LQIP, $req_data, 120 ); - if ( ! is_array( $json ) ) { - return $this->_generate_placeholder_locally( $size ); + $json = Cloud::post(Cloud::SVC_LQIP, $req_data, 120); + if (!is_array($json)) { + return $this->_generate_placeholder_locally($size); } - if ( empty( $json[ 'lqip' ] ) || strpos( $json[ 'lqip' ], 'data:image/svg+xml' ) !== 0 ) { + if (empty($json['lqip']) || strpos($json['lqip'], 'data:image/svg+xml') !== 0) { // image error, pop up the current queue - $this->_popup_and_save( $raw_size_and_src, true ); - $this->_append_exc( $src ); - Debug2::debug( '[LQIP] wrong response format', $json ); + $this->_popup_and_save($raw_size_and_src, true); + $this->_append_exc($src); + Debug2::debug('[LQIP] wrong response format', $json); - return $this->_generate_placeholder_locally( $size ); + return $this->_generate_placeholder_locally($size); } - $data = $json[ 'lqip' ]; + $data = $json['lqip']; - Debug2::debug( '[LQIP] _generate_placeholder LQIP' ); + Debug2::debug('[LQIP] _generate_placeholder LQIP'); } // Write to file - File::save( $file, $data, true ); + File::save($file, $data, true); // Save summary data - $this->_summary[ 'last_spent' ] = time() - $this->_summary[ 'curr_request' ]; - $this->_summary[ 'last_request' ] = $this->_summary[ 'curr_request' ]; - $this->_summary[ 'curr_request' ] = 0; + $this->_summary['last_spent'] = time() - $this->_summary['curr_request']; + $this->_summary['last_request'] = $this->_summary['curr_request']; + $this->_summary['curr_request'] = 0; self::save_summary(); - $this->_popup_and_save( $raw_size_and_src ); + $this->_popup_and_save($raw_size_and_src); - Debug2::debug( '[LQIP] saved LQIP ' . $file ); + Debug2::debug('[LQIP] saved LQIP ' . $file); return $data; } @@ -456,13 +469,14 @@ private function _generate_placeholder( $raw_size_and_src, $from_cron = false ) * * @since 3.0 */ - private function _lqip_size_check( $size ) { - $size = explode( 'x', $size ); - if ( $size[ 0 ] >= $this->_conf_lqip_min_w || $size[ 1 ] >= $this->_conf_lqip_min_h ) { + private function _lqip_size_check($size) + { + $size = explode('x', $size); + if ($size[0] >= $this->_conf_lqip_min_w || $size[1] >= $this->_conf_lqip_min_h) { return true; } - Debug2::debug2( '[LQIP] Size too small' ); + Debug2::debug2('[LQIP] Size too small'); return false; } @@ -472,11 +486,12 @@ private function _lqip_size_check( $size ) { * * @since 3.4 */ - private function _append_exc( $src ) { - $val = $this->conf( self::O_MEDIA_LQIP_EXC ); + private function _append_exc($src) + { + $val = $this->conf(self::O_MEDIA_LQIP_EXC); $val[] = $src; - $this->cls( 'Conf' )->update( self::O_MEDIA_LQIP_EXC, $val ); - Debug2::debug( '[LQIP] Appended to LQIP Excludes [URL] ' . $src ); + $this->cls('Conf')->update(self::O_MEDIA_LQIP_EXC, $val); + Debug2::debug('[LQIP] Appended to LQIP Excludes [URL] ' . $src); } /** @@ -484,35 +499,36 @@ private function _append_exc( $src ) { * * @since 3.0 */ - private function _popup_and_save( $raw_size_and_src, $append_to_exc = false ) { - $queue = $this->load_queue( 'lqip' ); - if ( ! empty( $queue ) && in_array( $raw_size_and_src, $queue ) ) { - unset( $queue[ array_search( $raw_size_and_src, $queue ) ] ); + private function _popup_and_save($raw_size_and_src, $append_to_exc = false) + { + $queue = $this->load_queue('lqip'); + if (!empty($queue) && in_array($raw_size_and_src, $queue)) { + unset($queue[array_search($raw_size_and_src, $queue)]); } - if ( $append_to_exc ) { - $size_and_src = explode( ' ', $raw_size_and_src, 2 ); - $this_src = $size_and_src[ 1 ]; + if ($append_to_exc) { + $size_and_src = explode(' ', $raw_size_and_src, 2); + $this_src = $size_and_src[1]; // Append to lqip exc setting first - $this->_append_exc( $this_src ); + $this->_append_exc($this_src); // Check if other queues contain this src or not - if ( $queue ) { - foreach ( $queue as $k => $raw_size_and_src ) { - $size_and_src = explode( ' ', $raw_size_and_src, 2 ); - if ( empty( $size_and_src[ 1 ] ) ) { + if ($queue) { + foreach ($queue as $k => $raw_size_and_src) { + $size_and_src = explode(' ', $raw_size_and_src, 2); + if (empty($size_and_src[1])) { continue; } - if ( $size_and_src[ 1 ] == $this_src ) { - unset( $queue[ $k ] ); + if ($size_and_src[1] == $this_src) { + unset($queue[$k]); } } } } - $this->save_queue( 'lqip', $queue ); + $this->save_queue('lqip', $queue); } /** @@ -521,16 +537,17 @@ private function _popup_and_save( $raw_size_and_src, $append_to_exc = false ) { * @since 2.5.1 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { - case self::TYPE_GENERATE : - self::cron( true ); + switch ($type) { + case self::TYPE_GENERATE: + self::cron(true); break; - case self::TYPE_CLEAR_Q : - $this->clear_q( 'lqip' ); + case self::TYPE_CLEAR_Q: + $this->clear_q('lqip'); break; default: @@ -539,5 +556,4 @@ public function handler() { Admin::redirect(); } - -} \ No newline at end of file +} diff --git a/src/preset.cls.php b/src/preset.cls.php new file mode 100644 index 000000000..e10d676c1 --- /dev/null +++ b/src/preset.cls.php @@ -0,0 +1,279 @@ +dirlist(self::BACKUP_DIR) ?: array() + ); + rsort($backups); + + return $backups; + } + + /** + * Removes extra backup files + * + * @since 5.3.0 + * @access public + */ + public static function prune_backups() + { + $backups = self::get_backups(); + global $wp_filesystem; + + foreach (array_slice($backups, self::MAX_BACKUPS) as $backup) { + $path = self::get_backup($backup); + $wp_filesystem->delete($path); + Debug2::debug('[Preset] Deleted old backup from ' . $backup); + } + } + + /** + * Returns a settings file's extensionless basename given its filesystem path + * + * @since 5.3.0 + * @access public + */ + public static function basename($path) + { + return basename($path, '.data'); + } + + /** + * Returns a standard preset's path given its extensionless basename + * + * @since 5.3.0 + * @access public + */ + public static function get_standard($name) + { + return path_join(self::STANDARD_DIR, $name . '.data'); + } + + /** + * Returns a backup's path given its extensionless basename + * + * @since 5.3.0 + * @access public + */ + public static function get_backup($name) + { + return path_join(self::BACKUP_DIR, $name . '.data'); + } + + /** + * Initializes the global $wp_filesystem object and clears stat cache + * + * @since 5.3.0 + */ + static function init_filesystem() + { + require_once ABSPATH . '/wp-admin/includes/file.php'; + \WP_Filesystem(); + clearstatcache(); + } + + /** + * Init + * + * @since 5.3.0 + */ + public function __construct() + { + Debug2::debug('[Preset] Init'); + $this->_summary = self::get_summary(); + } + + /** + * Applies a standard preset's settings given its extensionless basename + * + * @since 5.3.0 + * @access public + */ + public function apply($preset) + { + $this->make_backup($preset); + + $path = self::get_standard($preset); + $result = $this->import_file($path) ? $preset : 'error'; + + $this->log($result); + } + + /** + * Restores settings from the backup file with the given timestamp, then deletes the file + * + * @since 5.3.0 + * @access public + */ + public function restore($timestamp) + { + $backups = array(); + foreach (self::get_backups() as $backup) { + if (preg_match('/^backup-' . $timestamp . '(-|$)/', $backup) === 1) { + $backups[] = $backup; + } + } + + if (empty($backups)) { + $this->log('error'); + return; + } + + $backup = $backups[0]; + $path = self::get_backup($backup); + + if (!$this->import_file($path)) { + $this->log('error'); + return; + } + + self::init_filesystem(); + global $wp_filesystem; + + $wp_filesystem->delete($path); + Debug2::debug('[Preset] Deleted most recent backup from ' . $backup); + + $this->log('backup'); + } + + /** + * Saves current settings as a backup file, then prunes extra backup files + * + * @since 5.3.0 + * @access public + */ + public function make_backup($preset) + { + $backup = 'backup-' . time() . '-before-' . $preset; + $data = $this->export(true); + + $path = self::get_backup($backup); + File::save($path, $data, true); + Debug2::debug('[Preset] Backup saved to ' . $backup); + + self::prune_backups(); + } + + /** + * Tries to import from a given settings file + * + * @since 5.3.0 + */ + function import_file($path) + { + $debug = function ($result, $name) { + $action = $result ? 'Applied' : 'Failed to apply'; + Debug2::debug('[Preset] ' . $action . ' settings from ' . $name); + return $result; + }; + + $name = self::basename($path); + $contents = file_get_contents($path); + + if (false === $contents) { + Debug2::debug('[Preset] ❌ Failed to get file contents'); + return $debug(false, $name); + } + + $parsed = array(); + try { + // Check if the data is v4+ + if (strpos($contents, '["_version",') === 0) { + $contents = explode("\n", $contents); + foreach ($contents as $line) { + $line = trim($line); + if (empty($line)) { + continue; + } + list($key, $value) = json_decode($line, true); + $parsed[$key] = $value; + } + } else { + $parsed = json_decode(base64_decode($contents), true); + } + } catch (\Exception $ex) { + Debug2::debug('[Preset] ❌ Failed to parse serialized data'); + return $debug(false, $name); + } + + if (empty($parsed)) { + Debug2::debug('[Preset] ❌ Nothing to apply'); + return $debug(false, $name); + } + + $this->cls('Conf')->update_confs($parsed); + + return $debug(true, $name); + } + + /** + * Updates the log + * + * @since 5.3.0 + */ + function log($preset) + { + $this->_summary['preset'] = $preset; + $this->_summary['preset_timestamp'] = time(); + self::save_summary(); + } + + /** + * Handles all request actions from main cls + * + * @since 5.3.0 + * @access public + */ + public function handler() + { + $type = Router::verify_type(); + + switch ($type) { + case self::TYPE_APPLY: + $this->apply(!empty($_GET['preset']) ? $_GET['preset'] : false); + break; + + case self::TYPE_RESTORE: + $this->restore(!empty($_GET['timestamp']) ? $_GET['timestamp'] : false); + break; + + default: + break; + } + + Admin::redirect(); + } +} diff --git a/src/purge.cls.php b/src/purge.cls.php index e08309b5a..32574e4ab 100644 --- a/src/purge.cls.php +++ b/src/purge.cls.php @@ -1,15 +1,18 @@ conf(self::O_OPTM_UCSS)) add_action('edit_post', __NAMESPACE__ . '\Purge::purge_ucss'); + if ($this->conf(self::O_OPTM_UCSS)) { + add_action('edit_post', __NAMESPACE__ . '\Purge::purge_ucss'); + } } /** @@ -75,12 +80,13 @@ public function init() { * @since 3.0 * @access public */ - public function purge_publish( $new_status, $old_status, $post ) { - if ( $new_status != 'publish' && $old_status != 'publish' ) { + public function purge_publish($new_status, $old_status, $post) + { + if ($new_status != 'publish' && $old_status != 'publish') { return; } - $this->purge_post( $post->ID ); + $this->purge_post($post->ID); } /** @@ -89,10 +95,11 @@ public function purge_publish( $new_status, $old_status, $post ) { * @since 1.8 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_PURGE_ALL: $this->_purge_all(); break; @@ -149,8 +156,8 @@ public function handler() { $this->_purge_pages(); break; - case strpos( $type, self::TYPE_PURGE_ERROR ) === 0: - $this->_purge_error( substr( $type, strlen( self::TYPE_PURGE_ERROR ) ) ); + case strpos($type, self::TYPE_PURGE_ERROR) === 0: + $this->_purge_error(substr($type, strlen(self::TYPE_PURGE_ERROR))); break; default: @@ -166,8 +173,9 @@ public function handler() { * @since 1.0.0 * @access public */ - public static function purge_all( $reason = false ) { - self::cls()->_purge_all( $reason ); + public static function purge_all($reason = false) + { + self::cls()->_purge_all($reason); } /** @@ -176,29 +184,37 @@ public static function purge_all( $reason = false ) { * @since 2.2 * @access private */ - private function _purge_all( $reason = false ) { - $this->_purge_all_lscache( true ); - $this->_purge_all_cssjs( true ); - $this->_purge_all_localres( true ); + private function _purge_all($reason = false) + { + // if ( defined( 'LITESPEED_CLI' ) ) { + // // Can't send, already has output, need to save and wait for next run + // self::update_option( self::DB_QUEUE, $curr_built ); + // self::debug( 'CLI request, queue stored: ' . $curr_built ); + // } + // else { + $this->_purge_all_lscache(true); + $this->_purge_all_cssjs(true); + $this->_purge_all_localres(true); // $this->_purge_all_ccss( true ); // $this->_purge_all_lqip( true ); - $this->_purge_all_object( true ); - $this->purge_all_opcache( true ); + $this->_purge_all_object(true); + $this->purge_all_opcache(true); + // } - if ( ! is_string( $reason ) ) { + if (!is_string($reason)) { $reason = false; } - if ( $reason ) { + if ($reason) { $reason = "( $reason )"; } - self::debug( 'Purge all ' . $reason, 3 ); + self::debug('Purge all ' . $reason, 3); - $msg = __( 'Purged all caches successfully.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + $msg = __('Purged all caches successfully.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); - do_action( 'litespeed_purged_all' ); + do_action('litespeed_purged_all'); } /** @@ -210,12 +226,13 @@ private function _purge_all( $reason = false ) { * @since 2.2 * @access public */ - private function _purge_all_lscache( $silence = false ) { - $this->_add( '*' ); + private function _purge_all_lscache($silence = false) + { + $this->_add('*'); - if ( ! $silence ) { - $msg = __( 'Notified LiteSpeed Web Server to purge all LSCache entries.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Notified LiteSpeed Web Server to purge all LSCache entries.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -225,16 +242,17 @@ private function _purge_all_lscache( $silence = false ) { * @since 2.3 * @access private */ - private function _purge_all_ccss( $silence = false ) { - do_action( 'litespeed_purged_all_ccss' ); + private function _purge_all_ccss($silence = false) + { + do_action('litespeed_purged_all_ccss'); - $this->cls( 'CSS' )->rm_cache_folder( 'ccss' ); + $this->cls('CSS')->rm_cache_folder('ccss'); - $this->cls( 'Data' )->url_file_clean( 'ccss' ); + $this->cls('Data')->url_file_clean('ccss'); - if ( ! $silence ) { - $msg = __( 'Cleaned all Critical CSS files.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Cleaned all Critical CSS files.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -244,16 +262,17 @@ private function _purge_all_ccss( $silence = false ) { * @since 2.3 * @access private */ - private function _purge_all_ucss( $silence = false ) { - do_action( 'litespeed_purged_all_ucss' ); + private function _purge_all_ucss($silence = false) + { + do_action('litespeed_purged_all_ucss'); - $this->cls( 'CSS' )->rm_cache_folder( 'ucss' ); + $this->cls('CSS')->rm_cache_folder('ucss'); - $this->cls( 'Data' )->url_file_clean( 'ucss' ); + $this->cls('Data')->url_file_clean('ucss'); - if ( ! $silence ) { - $msg = __( 'Cleaned all Unique CSS files.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Cleaned all Unique CSS files.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -263,18 +282,19 @@ private function _purge_all_ucss( $silence = false ) { * @since 4.5 * @access public */ - public static function purge_ucss( $post_id_or_url ) { - self::debug( 'Purge a single UCSS: ' . $post_id_or_url ); + public static function purge_ucss($post_id_or_url) + { + self::debug('Purge a single UCSS: ' . $post_id_or_url); // If is post_id, generate URL - if ( ! preg_match( '/\D/', $post_id_or_url ) ) { - $post_id_or_url = get_permalink( $post_id_or_url ); + if (!preg_match('/\D/', $post_id_or_url)) { + $post_id_or_url = get_permalink($post_id_or_url); } - $post_id_or_url = untrailingslashit( $post_id_or_url ); + $post_id_or_url = untrailingslashit($post_id_or_url); - $existing_url_files = Data::cls()->mark_as_expired( $post_id_or_url, true ); - if ( $existing_url_files ) { + $existing_url_files = Data::cls()->mark_as_expired($post_id_or_url, true); + if ($existing_url_files) { // Add to UCSS Q - self::cls( 'UCSS' )->add_to_q($existing_url_files); + self::cls('UCSS')->add_to_q($existing_url_files); } } @@ -284,14 +304,15 @@ public static function purge_ucss( $post_id_or_url ) { * @since 3.0 * @access private */ - private function _purge_all_lqip( $silence = false ) { - do_action( 'litespeed_purged_all_lqip' ); + private function _purge_all_lqip($silence = false) + { + do_action('litespeed_purged_all_lqip'); - $this->cls( 'Placeholder' )->rm_cache_folder( 'lqip' ); + $this->cls('Placeholder')->rm_cache_folder('lqip'); - if ( ! $silence ) { - $msg = __( 'Cleaned all LQIP files.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Cleaned all LQIP files.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -301,14 +322,15 @@ private function _purge_all_lqip( $silence = false ) { * @since 3.0 * @access private */ - private function _purge_all_avatar( $silence = false ) { - do_action( 'litespeed_purged_all_avatar' ); + private function _purge_all_avatar($silence = false) + { + do_action('litespeed_purged_all_avatar'); - $this->cls( 'Avatar' )->rm_cache_folder( 'avatar' ); + $this->cls('Avatar')->rm_cache_folder('avatar'); - if ( ! $silence ) { - $msg = __( 'Cleaned all Gravatar files.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Cleaned all Gravatar files.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -318,14 +340,15 @@ private function _purge_all_avatar( $silence = false ) { * @since 3.3 * @access private */ - private function _purge_all_localres( $silence = false ) { - do_action( 'litespeed_purged_all_localres' ); + private function _purge_all_localres($silence = false) + { + do_action('litespeed_purged_all_localres'); - $this->_add( Tag::TYPE_LOCALRES ); + $this->_add(Tag::TYPE_LOCALRES); - if ( ! $silence ) { - $msg = __( 'Cleaned all localized resource entries.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Cleaned all localized resource entries.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -335,31 +358,32 @@ private function _purge_all_localres( $silence = false ) { * @since 1.2.2 * @access private */ - private function _purge_all_cssjs( $silence = false ) { - if ( defined( 'LITESPEED_DID_send_headers' ) ) { - self::debug( "❌ Bypassed cssjs delete as header sent (lscache purge after this point will fail)" ); + private function _purge_all_cssjs($silence = false) + { + if (defined('DOING_CRON') || defined('LITESPEED_DID_send_headers')) { + self::debug('❌ Bypassed cssjs delete as header sent (lscache purge after this point will fail) or doing cron'); return; } - $this->_purge_all_lscache( $silence ); // Purge CSSJS must purge lscache too to avoid 404 + $this->_purge_all_lscache($silence); // Purge CSSJS must purge lscache too to avoid 404 - do_action( 'litespeed_purged_all_cssjs' ); + do_action('litespeed_purged_all_cssjs'); - Optimize::update_option( Optimize::ITEM_TIMESTAMP_PURGE_CSS, time() ); + Optimize::update_option(Optimize::ITEM_TIMESTAMP_PURGE_CSS, time()); - $this->_add( Tag::TYPE_MIN ); + $this->_add(Tag::TYPE_MIN); - $this->cls( 'CSS' )->rm_cache_folder( 'css' ); - $this->cls( 'CSS' )->rm_cache_folder( 'js' ); + $this->cls('CSS')->rm_cache_folder('css'); + $this->cls('CSS')->rm_cache_folder('js'); - $this->cls( 'Data' )->url_file_clean( 'css' ); - $this->cls( 'Data' )->url_file_clean( 'js' ); + $this->cls('Data')->url_file_clean('css'); + $this->cls('Data')->url_file_clean('js'); // Clear UCSS queue as it used combined CSS to generate - $this->clear_q( 'ucss' ); + $this->clear_q('ucss', true); - if ( ! $silence ) { - $msg = __( 'Notified LiteSpeed Web Server to purge CSS/JS entries.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Notified LiteSpeed Web Server to purge CSS/JS entries.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } } @@ -369,13 +393,14 @@ private function _purge_all_cssjs( $silence = false ) { * @since 1.8.2 * @access public */ - public function purge_all_opcache( $silence = false ) { - if ( ! Router::opcache_enabled() ) { - self::debug( 'Failed to reset opcode cache due to opcache not enabled' ); - - if ( ! $silence ) { - $msg = __( 'Opcode cache is not enabled.', 'litespeed-cache' ); - Admin_Display::error( $msg ); + public function purge_all_opcache($silence = false) + { + if (!Router::opcache_enabled()) { + self::debug('Failed to reset opcode cache due to opcache not enabled'); + + if (!$silence) { + $msg = __('Opcode cache is not enabled.', 'litespeed-cache'); + Admin_Display::error($msg); } return false; @@ -383,11 +408,11 @@ public function purge_all_opcache( $silence = false ) { // Purge opcode cache opcache_reset(); - self::debug( 'Reset opcode cache' ); + self::debug('Reset opcode cache'); - if ( ! $silence ) { - $msg = __( 'Reset the entire opcode cache successfully.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Reset the entire opcode cache successfully.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } return true; @@ -399,8 +424,9 @@ public function purge_all_opcache( $silence = false ) { * @since 3.4 * @access public */ - public static function purge_all_object( $silence = true ) { - self::cls()->_purge_all_object( $silence ); + public static function purge_all_object($silence = true) + { + self::cls()->_purge_all_object($silence); } /** @@ -409,26 +435,27 @@ public static function purge_all_object( $silence = true ) { * @since 1.8 * @access private */ - private function _purge_all_object( $silence = false ) { - if ( ! defined( 'LSCWP_OBJECT_CACHE' ) ) { - self::debug( 'Failed to flush object cache due to object cache not enabled' ); - - if ( ! $silence ) { - $msg = __( 'Object cache is not enabled.', 'litespeed-cache' ); - Admin_Display::error( $msg ); + private function _purge_all_object($silence = false) + { + if (!defined('LSCWP_OBJECT_CACHE')) { + self::debug('Failed to flush object cache due to object cache not enabled'); + + if (!$silence) { + $msg = __('Object cache is not enabled.', 'litespeed-cache'); + Admin_Display::error($msg); } return false; } - do_action( 'litespeed_purged_all_object' ); + do_action('litespeed_purged_all_object'); - $this->cls( 'Object_Cache' )->flush(); - self::debug( 'Flushed object cache' ); + $this->cls('Object_Cache')->flush(); + self::debug('Flushed object cache'); - if ( ! $silence ) { - $msg = __( 'Purge all object caches successfully.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + if (!$silence) { + $msg = __('Purge all object caches successfully.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } return true; @@ -441,8 +468,9 @@ private function _purge_all_object( $silence = false ) { * @access public * @param mixed $tags Tags to add to the list. */ - public static function add( $tags, $purge2 = false ) { - self::cls()->_add( $tags, $purge2 ); + public static function add($tags, $purge2 = false) + { + self::cls()->_add($tags, $purge2); } /** @@ -451,43 +479,41 @@ public static function add( $tags, $purge2 = false ) { * @since 2.2 * @access private */ - private function _add( $tags, $purge2 = false ) { - if ( ! is_array( $tags ) ) { - $tags = array( $tags ); + private function _add($tags, $purge2 = false) + { + if (!is_array($tags)) { + $tags = array($tags); } - $tags = $this->_prepend_bid( $tags ); + $tags = $this->_prepend_bid($tags); - if ( ! array_diff( $tags, $purge2 ? $this->_pub_purge2 : $this->_pub_purge ) ) { + if (!array_diff($tags, $purge2 ? $this->_pub_purge2 : $this->_pub_purge)) { return; } - if ( $purge2 ) { - $this->_pub_purge2 = array_merge( $this->_pub_purge2, $tags ); - $this->_pub_purge2 = array_unique( $this->_pub_purge2 ); - } - else { - $this->_pub_purge = array_merge( $this->_pub_purge, $tags ); - $this->_pub_purge = array_unique( $this->_pub_purge ); + if ($purge2) { + $this->_pub_purge2 = array_merge($this->_pub_purge2, $tags); + $this->_pub_purge2 = array_unique($this->_pub_purge2); + } else { + $this->_pub_purge = array_merge($this->_pub_purge, $tags); + $this->_pub_purge = array_unique($this->_pub_purge); } - self::debug( 'added ' . implode( ',', $tags ) . ( $purge2 ? ' [Purge2]' : '' ), 8 ); + self::debug('added ' . implode(',', $tags) . ($purge2 ? ' [Purge2]' : ''), 8); // Send purge header immediately - $curr_built = $this->_build( $purge2 ); - if ( defined( 'LITESPEED_CLI' ) ) { + $curr_built = $this->_build($purge2); + if (defined('LITESPEED_CLI')) { // Can't send, already has output, need to save and wait for next run - self::update_option( $purge2 ? self::DB_QUEUE2 : self::DB_QUEUE, $curr_built ); - self::debug( 'CLI request, queue stored: ' . $curr_built ); - } - else { - @header( $curr_built ); - if ( defined( 'LITESPEED_DID_send_headers' ) && apply_filters( 'litespeed_delay_purge', false ) ) { - self::update_option( $purge2 ? self::DB_QUEUE2 : self::DB_QUEUE, $curr_built ); - self::debug( 'Output existed, queue stored: ' . $curr_built ); + self::update_option($purge2 ? self::DB_QUEUE2 : self::DB_QUEUE, $curr_built); + self::debug('CLI request, queue stored: ' . $curr_built); + } else { + @header($curr_built); + if (defined('DOING_CRON') || defined('LITESPEED_DID_send_headers') || apply_filters('litespeed_delay_purge', false)) { + self::update_option($purge2 ? self::DB_QUEUE2 : self::DB_QUEUE, $curr_built); + self::debug('Output existed, queue stored: ' . $curr_built); } - self::debug( $curr_built ); + self::debug($curr_built); } - } /** @@ -497,8 +523,9 @@ private function _add( $tags, $purge2 = false ) { * @access public * @param mixed $tags Tags to add to the list. */ - public static function add_private( $tags ) { - self::cls()->_add_private( $tags ); + public static function add_private($tags) + { + self::cls()->_add_private($tags); } /** @@ -507,8 +534,9 @@ public static function add_private( $tags ) { * @since 3.0 * @access public */ - public static function add_private_esi( $tag ) { - self::add_private( Tag::TYPE_ESI . $tag ); + public static function add_private_esi($tag) + { + self::add_private(Tag::TYPE_ESI . $tag); } /** @@ -517,8 +545,9 @@ public static function add_private_esi( $tag ) { * @since 3.0 * @access public */ - public static function add_private_all() { - self::add_private( '*' ); + public static function add_private_all() + { + self::add_private('*'); } /** @@ -527,55 +556,56 @@ public static function add_private_all() { * @since 2.2 * @access private */ - private function _add_private( $tags ) { - if ( ! is_array( $tags ) ) { - $tags = array( $tags ); + private function _add_private($tags) + { + if (!is_array($tags)) { + $tags = array($tags); } - $tags = $this->_prepend_bid( $tags ); + $tags = $this->_prepend_bid($tags); - if ( ! array_diff( $tags, $this->_priv_purge ) ) { + if (!array_diff($tags, $this->_priv_purge)) { return; } - self::debug( 'added [private] ' . implode( ',', $tags ), 3 ); + self::debug('added [private] ' . implode(',', $tags), 3); - $this->_priv_purge = array_merge( $this->_priv_purge, $tags ); - $this->_priv_purge = array_unique( $this->_priv_purge ); + $this->_priv_purge = array_merge($this->_priv_purge, $tags); + $this->_priv_purge = array_unique($this->_priv_purge); // Send purge header immediately - @header( $this->_build() ); + @header($this->_build()); } - /** * Incorporate blog_id into purge tags for multisite * * @since 4.0 * @access private * @param mixed $tags Tags to add to the list. - */ - private function _prepend_bid( $tags ){ - if ( in_array('*', $tags ) ){ - return array( '*' ); + */ + private function _prepend_bid($tags) + { + if (in_array('*', $tags)) { + return array('*'); } $curr_bid = is_multisite() ? get_current_blog_id() : ''; - foreach ( $tags as $k => $v ) { - $tags[ $k ] = $curr_bid. '_' .$v; + foreach ($tags as $k => $v) { + $tags[$k] = $curr_bid . '_' . $v; } return $tags; } - /** * Activate `purge related tags` for Admin QS. * * @since 1.1.3 * @access public */ - public static function set_purge_related() { + public static function set_purge_related() + { self::cls()->_purge_related = true; } @@ -585,7 +615,8 @@ public static function set_purge_related() { * @since 1.1.3 * @access public */ - public static function set_purge_single() { + public static function set_purge_single() + { self::cls()->_purge_single = true; } @@ -596,14 +627,16 @@ public static function set_purge_single() { * @since 2.2 Renamed from `frontend_purge`; Access changed from public * @access private */ - private function _purge_front() { - if ( empty( $_SERVER[ 'HTTP_REFERER' ] ) ) { - exit( 'no referer' ); + private function _purge_front() + { + if (empty($_SERVER['HTTP_REFERER'])) { + exit('no referer'); } - $this->purge_url( $_SERVER[ 'HTTP_REFERER' ] ); + $this->purge_url($_SERVER['HTTP_REFERER']); - wp_redirect( $_SERVER[ 'HTTP_REFERER' ] ); + do_action('litespeed_purged_front', $_SERVER['HTTP_REFERER']); + wp_redirect($_SERVER['HTTP_REFERER']); exit(); } @@ -611,19 +644,20 @@ private function _purge_front() { * Purge single UCSS * @since 4.7 */ - private function _purge_ucss() { - if ( empty( $_SERVER[ 'HTTP_REFERER' ] ) ) { - exit( 'no referer' ); + private function _purge_ucss() + { + if (empty($_SERVER['HTTP_REFERER'])) { + exit('no referer'); } - $url_tag = empty( $_GET[ 'url_tag' ] ) ? $_SERVER[ 'HTTP_REFERER' ] : $_GET[ 'url_tag' ]; + $url_tag = empty($_GET['url_tag']) ? $_SERVER['HTTP_REFERER'] : $_GET['url_tag']; - self::debug( 'Purge ucss [url_tag] ' . $url_tag ); + self::debug('Purge ucss [url_tag] ' . $url_tag); - do_action( 'litespeed_purge_ucss', $url_tag ); - $this->purge_url( $_SERVER[ 'HTTP_REFERER' ] ); + do_action('litespeed_purge_ucss', $url_tag); + $this->purge_url($_SERVER['HTTP_REFERER']); - wp_redirect( $_SERVER[ 'HTTP_REFERER' ] ); + wp_redirect($_SERVER['HTTP_REFERER']); exit(); } @@ -634,14 +668,15 @@ private function _purge_ucss() { * @since 2.2 Access changed from public to private, renamed from `_purge_front` * @access private */ - private function _purge_frontpage() { - $this->_add( Tag::TYPE_FRONTPAGE ); - if ( LITESPEED_SERVER_TYPE !== 'LITESPEED_SERVER_OLS' ) { - $this->_add_private( Tag::TYPE_FRONTPAGE ); + private function _purge_frontpage() + { + $this->_add(Tag::TYPE_FRONTPAGE); + if (LITESPEED_SERVER_TYPE !== 'LITESPEED_SERVER_OLS') { + $this->_add_private(Tag::TYPE_FRONTPAGE); } - $msg = __( 'Notified LiteSpeed Web Server to purge the front page.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + $msg = __('Notified LiteSpeed Web Server to purge the front page.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } /** @@ -650,11 +685,12 @@ private function _purge_frontpage() { * @since 1.0.15 * @access private */ - private function _purge_pages() { - $this->_add( Tag::TYPE_PAGES ); + private function _purge_pages() + { + $this->_add(Tag::TYPE_PAGES); - $msg = __( 'Notified LiteSpeed Web Server to purge all pages.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + $msg = __('Notified LiteSpeed Web Server to purge all pages.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } /** @@ -663,17 +699,18 @@ private function _purge_pages() { * @since 1.0.14 * @access private */ - private function _purge_error( $type = false ) { - $this->_add( Tag::TYPE_HTTP ); + private function _purge_error($type = false) + { + $this->_add(Tag::TYPE_HTTP); - if ( ! $type || ! in_array( $type, array( '403', '404', '500' ) ) ) { + if (!$type || !in_array($type, array('403', '404', '500'))) { return; } - $this->_add( Tag::TYPE_HTTP . $type ); + $this->_add(Tag::TYPE_HTTP . $type); - $msg = __( 'Notified LiteSpeed Web Server to purge error pages.', 'litespeed-cache' ); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( $msg ); + $msg = __('Notified LiteSpeed Web Server to purge error pages.', 'litespeed-cache'); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed($msg); } /** @@ -682,51 +719,52 @@ private function _purge_error( $type = false ) { * @since 1.0.7 * @access public */ - public function purge_cat( $value ) { - $val = trim( $value ); - if ( empty( $val ) ) { + public function purge_cat($value) + { + $val = trim($value); + if (empty($val)) { return; } - if ( preg_match( '/^[a-zA-Z0-9-]+$/', $val ) == 0 ) { - self::debug( "$val cat invalid" ); + if (preg_match('/^[a-zA-Z0-9-]+$/', $val) == 0) { + self::debug("$val cat invalid"); return; } - $cat = get_category_by_slug( $val ); - if ( $cat == false ) { - self::debug( "$val cat not existed/published" ); + $cat = get_category_by_slug($val); + if ($cat == false) { + self::debug("$val cat not existed/published"); return; } - self::add( Tag::TYPE_ARCHIVE_TERM . $cat->term_id ); + self::add(Tag::TYPE_ARCHIVE_TERM . $cat->term_id); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( sprintf( __( 'Purge category %s', 'litespeed-cache' ), $val ) ); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed(sprintf(__('Purge category %s', 'litespeed-cache'), $val)); } - /** * Callback to add purge tags if admin selects to purge selected tag pages. * * @since 1.0.7 * @access public */ - public function purge_tag( $val ) { - $val = trim( $val ); - if ( empty( $val ) ) { + public function purge_tag($val) + { + $val = trim($val); + if (empty($val)) { return; } - if ( preg_match( '/^[a-zA-Z0-9-]+$/', $val ) == 0 ) { - self::debug( "$val tag invalid" ); + if (preg_match('/^[a-zA-Z0-9-]+$/', $val) == 0) { + self::debug("$val tag invalid"); return; } - $term = get_term_by( 'slug', $val, 'post_tag' ); - if ( $term == 0 ) { - self::debug( "$val tag not exist" ); + $term = get_term_by('slug', $val, 'post_tag'); + if ($term == 0) { + self::debug("$val tag not exist"); return; } - self::add( Tag::TYPE_ARCHIVE_TERM . $term->term_id ); + self::add(Tag::TYPE_ARCHIVE_TERM . $term->term_id); - ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( sprintf( __( 'Purge tag %s', 'litespeed-cache' ), $val ) ); + !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed(sprintf(__('Purge tag %s', 'litespeed-cache'), $val)); } /** @@ -735,29 +773,30 @@ public function purge_tag( $val ) { * @since 1.0.7 * @access public */ - public function purge_url( $url, $purge2 = false, $quite = false ) { - $val = trim( $url ); - if ( empty( $val ) ) { + public function purge_url($url, $purge2 = false, $quite = false) + { + $val = trim($url); + if (empty($val)) { return; } - if ( strpos( $val, '<' ) !== false ) { - self::debug( "$val url contains <" ); + if (strpos($val, '<') !== false) { + self::debug("$val url contains <"); return; } - $val = Utility::make_relative( $val ); + $val = Utility::make_relative($val); - $hash = Tag::get_uri_tag( $val ); + $hash = Tag::get_uri_tag($val); - if ( $hash === false ) { - self::debug( "$val url invalid" ); + if ($hash === false) { + self::debug("$val url invalid"); return; } - self::add( $hash, $purge2 ); + self::add($hash, $purge2); - ! $quite && ! defined( 'LITESPEED_PURGE_SILENT' ) && Admin_Display::succeed( sprintf( __( 'Purge url %s', 'litespeed-cache' ), $val ) ); + !$quite && !defined('LITESPEED_PURGE_SILENT') && Admin_Display::succeed(sprintf(__('Purge url %s', 'litespeed-cache'), $val)); } /** @@ -766,18 +805,19 @@ public function purge_url( $url, $purge2 = false, $quite = false ) { * @since 1.0.7 * @access public */ - public function purge_list() { - if ( ! isset($_REQUEST[Admin_Display::PURGEBYOPT_SELECT]) || ! isset($_REQUEST[Admin_Display::PURGEBYOPT_LIST]) ) { + public function purge_list() + { + if (!isset($_REQUEST[Admin_Display::PURGEBYOPT_SELECT]) || !isset($_REQUEST[Admin_Display::PURGEBYOPT_LIST])) { return; } $sel = $_REQUEST[Admin_Display::PURGEBYOPT_SELECT]; $list_buf = $_REQUEST[Admin_Display::PURGEBYOPT_LIST]; - if ( empty($list_buf) ) { + if (empty($list_buf)) { return; } - $list_buf = str_replace(",", "\n", $list_buf);// for cli + $list_buf = str_replace(',', "\n", $list_buf); // for cli $list = explode("\n", $list_buf); - switch($sel) { + switch ($sel) { case Admin_Display::PURGEBY_CAT: $cb = 'purge_cat'; break; @@ -794,10 +834,10 @@ public function purge_list() { default: return; } - array_map( array( $this, $cb ), $list ); + array_map(array($this, $cb), $list); // for redirection - $_GET[ Admin_Display::PURGEBYOPT_SELECT ] = $sel; + $_GET[Admin_Display::PURGEBYOPT_SELECT] = $sel; } /** @@ -806,8 +846,9 @@ public function purge_list() { * @since 3.0 * @access public */ - public static function purge_esi( $tag ) { - self::add( Tag::TYPE_ESI . $tag ); + public static function purge_esi($tag) + { + self::add(Tag::TYPE_ESI . $tag); } /** @@ -816,9 +857,10 @@ public static function purge_esi( $tag ) { * @since 3.0 * @access public */ - public static function purge_posttype( $post_type ) { - self::add( Tag::TYPE_ARCHIVE_POSTTYPE . $post_type ); - self::add( $post_type ); + public static function purge_posttype($post_type) + { + self::add(Tag::TYPE_ARCHIVE_POSTTYPE . $post_type); + self::add($post_type); } /** @@ -827,21 +869,22 @@ public static function purge_posttype( $post_type ) { * @since 1.0.0 * @access public */ - public function purge_post( $pid ) { - $pid = intval( $pid ); + public function purge_post($pid) + { + $pid = intval($pid); // ignore the status we don't care - if ( ! $pid || ! in_array( get_post_status( $pid ), array( 'publish', 'trash', 'private', 'draft' ) ) ) { + if (!$pid || !in_array(get_post_status($pid), array('publish', 'trash', 'private', 'draft'))) { return; } - $purge_tags = $this->_get_purge_tags_by_post( $pid ); - if ( ! $purge_tags ) { + $purge_tags = $this->_get_purge_tags_by_post($pid); + if (!$purge_tags) { return; } - self::add( $purge_tags ); - if ( $this->conf( self::O_CACHE_REST ) ) { - self::add( Tag::TYPE_REST ); + self::add($purge_tags); + if ($this->conf(self::O_CACHE_REST)) { + self::add(Tag::TYPE_REST); } // $this->cls( 'Control' )->set_stale(); @@ -855,10 +898,11 @@ public function purge_post( $pid ) { * @since 1.1.3 * @access public */ - public static function purge_widget( $widget_id = null ) { - if ( is_null($widget_id) ) { + public static function purge_widget($widget_id = null) + { + if (is_null($widget_id)) { $widget_id = $_POST['widget-id']; - if ( is_null($widget_id) ) { + if (is_null($widget_id)) { return; } } @@ -874,13 +918,14 @@ public static function purge_widget( $widget_id = null ) { * @since 1.1.3 * @global type $wp_widget_factory */ - public static function purge_comment_widget() { + public static function purge_comment_widget() + { global $wp_widget_factory; - if ( ! isset( $wp_widget_factory->widgets[ 'WP_Widget_Recent_Comments' ] ) ) { + if (!isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) { return; } $recent_comments = $wp_widget_factory->widgets['WP_Widget_Recent_Comments']; - if ( !is_null($recent_comments) ) { + if (!is_null($recent_comments)) { self::add(Tag::TYPE_WIDGET . $recent_comments->id); self::add_private(Tag::TYPE_WIDGET . $recent_comments->id); } @@ -892,9 +937,10 @@ public static function purge_comment_widget() { * @since 1.0.9 * @access public */ - public function purge_feeds() { - if ( $this->conf( self::O_CACHE_TTL_FEED ) > 0 ) { - self::add( Tag::TYPE_FEED ); + public function purge_feeds() + { + if ($this->conf(self::O_CACHE_TTL_FEED) > 0) { + self::add(Tag::TYPE_FEED); } } @@ -904,7 +950,8 @@ public function purge_feeds() { * @access public * @since 1.1.3 */ - public static function purge_on_logout() { + public static function purge_on_logout() + { self::add_private('*'); } @@ -914,37 +961,37 @@ public static function purge_on_logout() { * @access private * @since 1.1.3 */ - private function _finalize() { + private function _finalize() + { // Make sure header output only run once - if ( ! defined( 'LITESPEED_DID_' . __FUNCTION__ ) ) { - define( 'LITESPEED_DID_' . __FUNCTION__, true ); - } - else { + if (!defined('LITESPEED_DID_' . __FUNCTION__)) { + define('LITESPEED_DID_' . __FUNCTION__, true); + } else { return; } do_action('litespeed_purge_finalize'); // Append unique uri purge tags if Admin QS is `PURGESINGLE` - if ( $this->_purge_single ) { + if ($this->_purge_single) { $this->_pub_purge[] = Tag::build_uri_tag(); // TODO: add private tag too } // Append related purge tags if Admin QS is `PURGE` - if ( $this->_purge_related ) { + if ($this->_purge_related) { // Before this, tags need to be finalized $tags_related = Tag::output_tags(); // NOTE: need to remove the empty item `B1_` to avoid purging all $tags_related = array_filter($tags_related); - if ( $tags_related ) { + if ($tags_related) { $this->_pub_purge = array_merge($this->_pub_purge, $tags_related); } } - if ( ! empty($this->_pub_purge) ) { + if (!empty($this->_pub_purge)) { $this->_pub_purge = array_unique($this->_pub_purge); } - if ( ! empty($this->_priv_purge) ) { + if (!empty($this->_priv_purge)) { $this->_priv_purge = array_unique($this->_priv_purge); } } @@ -958,7 +1005,8 @@ private function _finalize() { * @access public * @return string the built purge header */ - public static function output() { + public static function output() + { $instance = self::cls(); $instance->_finalize(); @@ -973,14 +1021,14 @@ public static function output() { * @access private * @return string the built purge header */ - private function _build( $purge2 = false ) { - if ( $purge2 ) { - if ( empty( $this->_pub_purge2 ) ) { + private function _build($purge2 = false) + { + if ($purge2) { + if (empty($this->_pub_purge2)) { return; } - } - else { - if ( empty( $this->_pub_purge ) && empty( $this->_priv_purge ) ) { + } else { + if (empty($this->_pub_purge) && empty($this->_priv_purge)) { return; } } @@ -988,39 +1036,39 @@ private function _build( $purge2 = false ) { $purge_header = ''; // Handle purge2 @since 4.4.1 - if ( $purge2 ) { - $public_tags = $this->_append_prefix( $this->_pub_purge2 ); - if ( empty( $public_tags ) ) { + if ($purge2) { + $public_tags = $this->_append_prefix($this->_pub_purge2); + if (empty($public_tags)) { return; } $purge_header = self::X_HEADER2 . ': public,'; - if ( Control::is_stale() ) { + if (Control::is_stale()) { $purge_header .= 'stale,'; } - $purge_header .= implode( ',', $public_tags ); + $purge_header .= implode(',', $public_tags); return $purge_header; } $private_prefix = self::X_HEADER . ': private,'; - if ( ! empty( $this->_pub_purge ) ) { - $public_tags = $this->_append_prefix( $this->_pub_purge ); - if ( empty( $public_tags ) ) { + if (!empty($this->_pub_purge)) { + $public_tags = $this->_append_prefix($this->_pub_purge); + if (empty($public_tags)) { // If this ends up empty, private will also end up empty return; } $purge_header = self::X_HEADER . ': public,'; - if ( Control::is_stale() ) { + if (Control::is_stale()) { $purge_header .= 'stale,'; } - $purge_header .= implode( ',', $public_tags ); + $purge_header .= implode(',', $public_tags); $private_prefix = ';private,'; } // Handle priv purge tags - if ( ! empty( $this->_priv_purge ) ) { - $private_tags = $this->_append_prefix( $this->_priv_purge, true ); - $purge_header .= $private_prefix . implode( ',', $private_tags ); + if (!empty($this->_priv_purge)) { + $private_tags = $this->_append_prefix($this->_priv_purge, true); + $purge_header .= $private_prefix . implode(',', $private_tags); } return $purge_header; @@ -1032,29 +1080,30 @@ private function _build( $purge2 = false ) { * @since 1.1.0 * @access private */ - private function _append_prefix( $purge_tags, $is_private = false ) { + private function _append_prefix($purge_tags, $is_private = false) + { $curr_bid = is_multisite() ? get_current_blog_id() : ''; - if ( ! in_array( '*', $purge_tags ) ) { + if (!in_array('*', $purge_tags)) { $tags = array(); - foreach ( $purge_tags as $val ) { + foreach ($purge_tags as $val) { $tags[] = LSWCP_TAG_PREFIX . $val; } return $tags; } // Purge All need to check if need to reset crawler or not - if ( ! $is_private && $this->conf( self::O_CRAWLER ) ) { + if (!$is_private && $this->conf(self::O_CRAWLER)) { Crawler::cls()->reset_pos(); } - if ( defined( 'LSWCP_EMPTYCACHE' ) || $is_private ) { - return array( '*' ); + if (defined('LSWCP_EMPTYCACHE') || $is_private) { + return array('*'); } - if ( is_multisite() && ! $this->_is_subsite_purge() ) { + if (is_multisite() && !$this->_is_subsite_purge()) { $blogs = Activation::get_network_ids(); - if ( empty($blogs) ) { + if (empty($blogs)) { self::debug('build_purge_headers: blog list is empty'); return ''; } @@ -1063,8 +1112,7 @@ private function _append_prefix( $purge_tags, $is_private = false ) { $tags[] = LSWCP_TAG_PREFIX . $blog_id . '_'; } return $tags; - } - else { + } else { return array(LSWCP_TAG_PREFIX . $curr_bid . '_'); } } @@ -1074,21 +1122,22 @@ private function _append_prefix( $purge_tags, $is_private = false ) { * * @since 4.0 */ - private function _is_subsite_purge() { - if ( ! is_multisite() ) { + private function _is_subsite_purge() + { + if (!is_multisite()) { return false; } - if ( is_network_admin() ) { + if (is_network_admin()) { return false; } - if ( defined( 'LSWCP_EMPTYCACHE' ) ) { + if (defined('LSWCP_EMPTYCACHE')) { return false; } // Would only use multisite and network admin except is_network_admin is false for ajax calls, which is used by wordpress updates v4.6+ - if ( Router::is_ajax() && ( check_ajax_referer( 'updates', false, false ) || check_ajax_referer( 'litespeed-purgeall-network', false, false ) ) ) { + if (Router::is_ajax() && (check_ajax_referer('updates', false, false) || check_ajax_referer('litespeed-purgeall-network', false, false))) { return false; } @@ -1105,15 +1154,16 @@ private function _is_subsite_purge() { * @since 1.0.0 * @access private */ - private function _get_purge_tags_by_post( $post_id ) { + private function _get_purge_tags_by_post($post_id) + { // If this is a valid post we want to purge the post, the home page and any associated tags & cats // If not, purge everything on the site. $purge_tags = array(); - if ( $this->conf( self::O_PURGE_POST_ALL ) ) { + if ($this->conf(self::O_PURGE_POST_ALL)) { // ignore the rest if purge all - return array( '*' ); + return array('*'); } // now do API hook action for post purge @@ -1122,7 +1172,7 @@ private function _get_purge_tags_by_post( $post_id ) { // post $purge_tags[] = Tag::TYPE_POST . $post_id; $post_status = get_post_status($post_id); - if ( function_exists( 'is_post_status_viewable' ) ) { + if (function_exists('is_post_status_viewable')) { $viewable = is_post_status_viewable($post_status); if ($viewable) { $purge_tags[] = Tag::get_uri_tag(wp_make_link_relative(get_permalink($post_id))); @@ -1136,69 +1186,70 @@ private function _get_purge_tags_by_post( $post_id ) { $post_type = $post->post_type; global $wp_widget_factory; - $recent_posts = $wp_widget_factory->widgets['WP_Widget_Recent_Posts']; - if ( ! is_null($recent_posts) ) { + // recent_posts + $recent_posts = isset($wp_widget_factory->widgets['WP_Widget_Recent_Posts']) ? $wp_widget_factory->widgets['WP_Widget_Recent_Posts'] : null; + if (!is_null($recent_posts)) { $purge_tags[] = Tag::TYPE_WIDGET . $recent_posts->id; } // get adjacent posts id as related post tag - if( $post_type == 'post' ){ + if ($post_type == 'post') { $prev_post = get_previous_post(); $next_post = get_next_post(); - if( ! empty($prev_post->ID) ) { + if (!empty($prev_post->ID)) { $purge_tags[] = Tag::TYPE_POST . $prev_post->ID; - self::debug('--------purge_tags prev is: '.$prev_post->ID); + self::debug('--------purge_tags prev is: ' . $prev_post->ID); } - if( ! empty($next_post->ID) ) { + if (!empty($next_post->ID)) { $purge_tags[] = Tag::TYPE_POST . $next_post->ID; - self::debug('--------purge_tags next is: '.$next_post->ID); + self::debug('--------purge_tags next is: ' . $next_post->ID); } } - if ( $this->conf( self::O_PURGE_POST_TERM ) ) { + if ($this->conf(self::O_PURGE_POST_TERM)) { $taxonomies = get_object_taxonomies($post_type); //self::debug('purge by post, check tax = ' . var_export($taxonomies, true)); - foreach ( $taxonomies as $tax ) { + foreach ($taxonomies as $tax) { $terms = get_the_terms($post_id, $tax); - if ( ! empty($terms) ) { - foreach ( $terms as $term ) { + if (!empty($terms)) { + foreach ($terms as $term) { $purge_tags[] = Tag::TYPE_ARCHIVE_TERM . $term->term_id; } } } } - if ( $this->conf( self::O_CACHE_TTL_FEED ) ) { + if ($this->conf(self::O_CACHE_TTL_FEED)) { $purge_tags[] = Tag::TYPE_FEED; } // author, for author posts and feed list - if ( $this->conf( self::O_PURGE_POST_AUTHOR) ) { + if ($this->conf(self::O_PURGE_POST_AUTHOR)) { $purge_tags[] = Tag::TYPE_AUTHOR . get_post_field('post_author', $post_id); } // archive and feed of post type // todo: check if type contains space - if ( $this->conf( self::O_PURGE_POST_POSTTYPE) ) { - if ( get_post_type_archive_link($post_type) ) { + if ($this->conf(self::O_PURGE_POST_POSTTYPE)) { + if (get_post_type_archive_link($post_type)) { $purge_tags[] = Tag::TYPE_ARCHIVE_POSTTYPE . $post_type; $purge_tags[] = $post_type; } } - if ( $this->conf( self::O_PURGE_POST_FRONTPAGE) ) { + if ($this->conf(self::O_PURGE_POST_FRONTPAGE)) { $purge_tags[] = Tag::TYPE_FRONTPAGE; } - if ( $this->conf( self::O_PURGE_POST_HOMEPAGE) ) { + if ($this->conf(self::O_PURGE_POST_HOMEPAGE)) { $purge_tags[] = Tag::TYPE_HOME; } - if ( $this->conf( self::O_PURGE_POST_PAGES) ) { + if ($this->conf(self::O_PURGE_POST_PAGES)) { $purge_tags[] = Tag::TYPE_PAGES; } - if ( $this->conf( self::O_PURGE_POST_PAGES_WITH_RECENT_POSTS) ) { + if ($this->conf(self::O_PURGE_POST_PAGES_WITH_RECENT_POSTS)) { $purge_tags[] = Tag::TYPE_PAGES_WITH_RECENT_POSTS; } @@ -1206,15 +1257,15 @@ private function _get_purge_tags_by_post( $post_id ) { $date = $post->post_date; $date = strtotime($date); - if ( $this->conf( self::O_PURGE_POST_DATE) ) { + if ($this->conf(self::O_PURGE_POST_DATE)) { $purge_tags[] = Tag::TYPE_ARCHIVE_DATE . date('Ymd', $date); } - if ( $this->conf( self::O_PURGE_POST_MONTH) ) { + if ($this->conf(self::O_PURGE_POST_MONTH)) { $purge_tags[] = Tag::TYPE_ARCHIVE_DATE . date('Ym', $date); } - if ( $this->conf( self::O_PURGE_POST_YEAR) ) { + if ($this->conf(self::O_PURGE_POST_YEAR)) { $purge_tags[] = Tag::TYPE_ARCHIVE_DATE . date('Y', $date); } @@ -1232,7 +1283,8 @@ private function _get_purge_tags_by_post( $post_id ) { * @param string $val The filter value * @return string The filter value */ - public static function filter_with_purge_all( $val ) { + public static function filter_with_purge_all($val) + { self::purge_all(); return $val; } diff --git a/src/report.cls.php b/src/report.cls.php index c0afad614..3983b64b3 100644 --- a/src/report.cls.php +++ b/src/report.cls.php @@ -10,9 +10,10 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Report extends Base { +class Report extends Base +{ const TYPE_SEND_REPORT = 'send_report'; /** @@ -21,10 +22,11 @@ class Report extends Base { * @since 1.6.5 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_SEND_REPORT: $this->post_env(); break; @@ -47,9 +49,9 @@ public function post_env() $report_con = $this->generate_environment_report(); // Generate link - $link = ! empty( $_POST[ 'link' ] ) ? esc_url( $_POST[ 'link' ] ) : ''; + $link = !empty($_POST['link']) ? esc_url($_POST['link']) : ''; - $notes = ! empty( $_POST[ 'notes' ] ) ? esc_html( $_POST[ 'notes' ] ) : ''; + $notes = !empty($_POST['notes']) ? esc_html($_POST['notes']) : ''; $data = array( 'env' => $report_con, @@ -57,18 +59,18 @@ public function post_env() 'notes' => $notes, ); - $json = Cloud::post( Cloud::API_REPORT, $data ); - if ( ! is_array( $json ) ) { + $json = Cloud::post(Cloud::API_REPORT, $data); + if (!is_array($json)) { return; } - $num = ! empty( $json[ 'num' ] ) ? $json[ 'num' ] : '--'; + $num = !empty($json['num']) ? $json['num'] : '--'; $summary = array( - 'num' => $num, - 'dateline' => time(), + 'num' => $num, + 'dateline' => time(), ); - self::save_summary( $summary ); + self::save_summary($summary); return $num; } @@ -80,82 +82,79 @@ public function post_env() * @since 1.0.12 * @access public */ - public function generate_environment_report( $options = null ) { + public function generate_environment_report($options = null) + { global $wp_version, $_SERVER; $frontend_htaccess = Htaccess::get_frontend_htaccess(); $backend_htaccess = Htaccess::get_backend_htaccess(); $paths = array($frontend_htaccess); - if ( $frontend_htaccess != $backend_htaccess ) { + if ($frontend_htaccess != $backend_htaccess) { $paths[] = $backend_htaccess; } - if ( is_multisite() ) { + if (is_multisite()) { $active_plugins = get_site_option('active_sitewide_plugins'); - if ( ! empty($active_plugins) ) { + if (!empty($active_plugins)) { $active_plugins = array_keys($active_plugins); } - } - else { + } else { $active_plugins = get_option('active_plugins'); } - if ( function_exists('wp_get_theme') ) { + if (function_exists('wp_get_theme')) { $theme_obj = wp_get_theme(); $active_theme = $theme_obj->get('Name'); - } - else { + } else { $active_theme = get_current_theme(); } $extras = array( 'wordpress version' => $wp_version, - 'siteurl' => get_option( 'siteurl' ), - 'home' => get_option( 'home' ), + 'siteurl' => get_option('siteurl'), + 'home' => get_option('home'), 'home_url' => home_url(), 'locale' => get_locale(), 'active theme' => $active_theme, ); - $extras[ 'active plugins' ] = $active_plugins; - $extras[ 'cloud' ] = Cloud::get_summary(); + $extras['active plugins'] = $active_plugins; + $extras['cloud'] = Cloud::get_summary(); - if ( is_null($options) ) { - $options = $this->get_options( true ); + if (is_null($options)) { + $options = $this->get_options(true); - if ( is_multisite() ) { + if (is_multisite()) { $options2 = $this->get_options(); - foreach ( $options2 as $k => $v ) { - if ( $options[ $k ] !== $v ) { - $options[ '[Overwritten] ' . $k ] = $v; + foreach ($options2 as $k => $v) { + if ($options[$k] !== $v) { + $options['[Overwritten] ' . $k] = $v; } } } } - if ( ! is_null($options) && is_multisite() ) { + if (!is_null($options) && is_multisite()) { $blogs = Activation::get_network_ids(); - if ( ! empty($blogs) ) { + if (!empty($blogs)) { $i = 0; - foreach ( $blogs as $blog_id ) { - if ( ++$i > 3 ) { // Only log 3 subsites + foreach ($blogs as $blog_id) { + if (++$i > 3) { + // Only log 3 subsites break; } - $opts = $this->cls( 'Conf' )->load_options( $blog_id, true ); - if ( isset($opts[ self::O_CACHE ]) ) { - $options['blog ' . $blog_id . ' radio select'] = $opts[ self::O_CACHE ]; + $opts = $this->cls('Conf')->load_options($blog_id, true); + if (isset($opts[self::O_CACHE])) { + $options['blog ' . $blog_id . ' radio select'] = $opts[self::O_CACHE]; } } } } // Security: Remove cf key in report - $secure_fields = array( - self::O_CDN_CLOUDFLARE_KEY, - self::O_OBJECT_PSWD, - ); - foreach ( $secure_fields as $v ) { - if ( ! empty( $options[ $v ] ) ) { - $options[ $v ] = str_repeat( '*', strlen( $options[ $v ] ) ); + $secure_fields = array(self::O_CDN_CLOUDFLARE_KEY, self::O_OBJECT_PSWD); + foreach ($secure_fields as $v) { + if (!empty($options[$v])) { + $options[$v] = str_repeat('*', strlen($options[$v])); } } @@ -171,15 +170,15 @@ public function generate_environment_report( $options = null ) { private function build_environment_report($server, $options, $extras = array(), $htaccess_paths = array()) { $server_keys = array( - 'DOCUMENT_ROOT'=>'', - 'SERVER_SOFTWARE'=>'', - 'X-LSCACHE'=>'', - 'HTTP_X_LSCACHE'=>'' + 'DOCUMENT_ROOT' => '', + 'SERVER_SOFTWARE' => '', + 'X-LSCACHE' => '', + 'HTTP_X_LSCACHE' => '', ); $server_vars = array_intersect_key($server, $server_keys); - $server_vars[] = "LSWCP_TAG_PREFIX = " . LSWCP_TAG_PREFIX; + $server_vars[] = 'LSWCP_TAG_PREFIX = ' . LSWCP_TAG_PREFIX; - $server_vars = array_merge( $server_vars, $this->cls( 'Base' )->server_vars() ); + $server_vars = array_merge($server_vars, $this->cls('Base')->server_vars()); $buf = $this->_format_report_section('Server Variables', $server_vars); @@ -187,18 +186,18 @@ private function build_environment_report($server, $options, $extras = array(), $buf .= $this->_format_report_section('LSCache Plugin Options', $options); - if ( empty($htaccess_paths) ) { + if (empty($htaccess_paths)) { return $buf; } - foreach ( $htaccess_paths as $path ) { - if ( ! file_exists($path) || ! is_readable($path) ) { + foreach ($htaccess_paths as $path) { + if (!file_exists($path) || !is_readable($path)) { $buf .= $path . " does not exist or is not readable.\n"; continue; } $content = file_get_contents($path); - if ( $content === false ) { + if ($content === false) { $buf .= $path . " returned false for file_get_contents.\n"; continue; } @@ -213,29 +212,28 @@ private function build_environment_report($server, $options, $extras = array(), * @since 1.0.12 * @access private */ - private function _format_report_section( $section_header, $section ) + private function _format_report_section($section_header, $section) { $tab = ' '; // four spaces - if ( empty( $section ) ) { + if (empty($section)) { return 'No matching ' . $section_header . "\n\n"; } $buf = $section_header; - foreach ( $section as $k => $v ) { + foreach ($section as $k => $v) { $buf .= "\n" . $tab; - if ( ! is_numeric( $k ) ) { + if (!is_numeric($k)) { $buf .= $k . ' = '; } - if ( ! is_string( $v ) ) { - $v = var_export( $v, true ); + if (!is_string($v)) { + $v = var_export($v, true); } $buf .= $v; } return $buf . "\n\n"; } - } diff --git a/src/rest.cls.php b/src/rest.cls.php index 0600cad45..cbb65fbf1 100644 --- a/src/rest.cls.php +++ b/src/rest.cls.php @@ -1,14 +1,17 @@ 'POST', - 'callback' => array( $this, 'toggle_crawler_state' ), - 'permission_callback' => '__return_true', - ) ); + 'callback' => array($this, 'toggle_crawler_state'), + 'permission_callback' => function () { + return current_user_can('manage_network_options') || current_user_can('manage_options'); + }, + )); - register_rest_route( 'litespeed/v1', '/tool/check_ip', array( + register_rest_route('litespeed/v1', '/tool/check_ip', array( 'methods' => 'GET', - 'callback' => array( $this, 'check_ip' ), - 'permission_callback' => function() { - return current_user_can( 'manage_network_options' ) || current_user_can( 'manage_options' ); - } - ) ); + 'callback' => array($this, 'check_ip'), + 'permission_callback' => function () { + return current_user_can('manage_network_options') || current_user_can('manage_options'); + }, + )); // IP callback validate - register_rest_route( 'litespeed/v1', '/ip_validate', array( + register_rest_route('litespeed/v1', '/ip_validate', array( 'methods' => 'POST', - 'callback' => array( $this, 'ip_validate' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'ip_validate'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); // Token callback validate - register_rest_route( 'litespeed/v1', '/token', array( + register_rest_route('litespeed/v1', '/token', array( 'methods' => 'POST', - 'callback' => array( $this, 'token' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); - register_rest_route( 'litespeed/v1', '/token', array( + 'callback' => array($this, 'token'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); + register_rest_route('litespeed/v1', '/token', array( 'methods' => 'GET', - 'callback' => array( $this, 'token_get' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); - register_rest_route( 'litespeed/v1', '/ping', array( + 'callback' => array($this, 'token_get'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); + register_rest_route('litespeed/v1', '/ping', array( 'methods' => 'GET', - 'callback' => array( $this, 'ping' ), - 'permission_callback' => '__return_true', - ) ); + 'callback' => array($this, 'ping'), + 'permission_callback' => '__return_true', + )); // API key callback notification - register_rest_route( 'litespeed/v1', '/apikey', array( + register_rest_route('litespeed/v1', '/apikey', array( 'methods' => 'POST', - 'callback' => array( $this, 'apikey' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'apikey'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); // CDN setup callback notification - register_rest_route( 'litespeed/v1', '/cdn_status', array( + register_rest_route('litespeed/v1', '/cdn_status', array( 'methods' => 'POST', - 'callback' => array( $this, 'cdn_status' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'cdn_status'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); // Image optm notify_img // Need validation - register_rest_route( 'litespeed/v1', '/notify_img', array( + register_rest_route('litespeed/v1', '/notify_img', array( 'methods' => 'POST', - 'callback' => array( $this, 'notify_img' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'notify_img'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); - register_rest_route( 'litespeed/v1', '/notify_ucss', array( + register_rest_route('litespeed/v1', '/notify_ucss', array( 'methods' => 'POST', - 'callback' => array( $this, 'notify_ucss' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'notify_ucss'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); - register_rest_route( 'litespeed/v1', '/notify_vpi', array( + register_rest_route('litespeed/v1', '/notify_vpi', array( 'methods' => 'POST', - 'callback' => array( $this, 'notify_vpi' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'notify_vpi'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); - register_rest_route( 'litespeed/v1', '/err_domains', array( + register_rest_route('litespeed/v1', '/err_domains', array( 'methods' => 'POST', - 'callback' => array( $this, 'err_domains' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); + 'callback' => array($this, 'err_domains'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); // Image optm check_img // Need validation - register_rest_route( 'litespeed/v1', '/check_img', array( + register_rest_route('litespeed/v1', '/check_img', array( 'methods' => 'POST', - 'callback' => array( $this, 'check_img' ), - 'permission_callback' => array( $this, 'is_from_cloud' ), - ) ); - + 'callback' => array($this, 'check_img'), + 'permission_callback' => array($this, 'is_from_cloud'), + )); } /** @@ -126,9 +132,10 @@ public function rest_api_init() { * * @since 4.3 */ - public function toggle_crawler_state() { - if( isset( $_POST[ 'crawler_id' ] ) ) { - return $this->cls( 'Crawler' )->toggle_activeness( $_POST[ 'crawler_id' ] ) ? 1 : 0; + public function toggle_crawler_state() + { + if (isset($_POST['crawler_id'])) { + return $this->cls('Crawler')->toggle_activeness($_POST['crawler_id']) ? 1 : 0; } } @@ -138,7 +145,8 @@ public function toggle_crawler_state() { * @since 4.2 * @since 4.4.7 As there is always token/api key validation, ip validation is redundant */ - public function is_from_cloud() { + public function is_from_cloud() + { return true; // return $this->cls( 'Cloud' )->is_from_cloud(); } @@ -148,7 +156,8 @@ public function is_from_cloud() { * * @since 3.0.4 */ - public function token_get() { + public function token_get() + { return Cloud::ok(); } @@ -157,8 +166,9 @@ public function token_get() { * * @since 3.0.4 */ - public function ping() { - return Cloud::ok( array( 'ver' => Core::VER ) ); + public function ping() + { + return Cloud::ok(array('ver' => Core::VER)); } /** @@ -166,7 +176,8 @@ public function ping() { * * @since 3.0 */ - public function check_ip() { + public function check_ip() + { return Tool::cls()->check_ip(); } @@ -175,8 +186,9 @@ public function check_ip() { * * @since 3.0 */ - public function ip_validate() { - return $this->cls( 'Cloud' )->ip_validate(); + public function ip_validate() + { + return $this->cls('Cloud')->ip_validate(); } /** @@ -184,8 +196,9 @@ public function ip_validate() { * * @since 3.0 */ - public function token() { - return $this->cls( 'Cloud' )->token_validate(); + public function token() + { + return $this->cls('Cloud')->token_validate(); } /** @@ -193,8 +206,9 @@ public function token() { * * @since 3.0 */ - public function apikey() { - return $this->cls( 'Cloud' )->save_apikey(); + public function apikey() + { + return $this->cls('Cloud')->save_apikey(); } /** @@ -202,8 +216,9 @@ public function apikey() { * * @since 3.0 */ - public function cdn_status() { - return $this->cls( 'Cdn_Setup' )->update_cdn_status(); + public function cdn_status() + { + return $this->cls('Cdn_Setup')->update_cdn_status(); } /** @@ -211,14 +226,16 @@ public function cdn_status() { * * @since 3.0 */ - public function notify_img() { + public function notify_img() + { return Img_Optm::cls()->notify_img(); } /** * @since 5.2 */ - public function notify_ucss() { + public function notify_ucss() + { self::debug('notify_ucss'); return UCSS::cls()->notify(); } @@ -226,7 +243,8 @@ public function notify_ucss() { /** * @since 4.7 */ - public function notify_vpi() { + public function notify_vpi() + { self::debug('notify_vpi'); return VPI::cls()->notify(); } @@ -234,9 +252,10 @@ public function notify_vpi() { /** * @since 4.7 */ - public function err_domains() { + public function err_domains() + { self::debug('err_domains'); - return $this->cls( 'Cloud' )->rest_err_domains(); + return $this->cls('Cloud')->rest_err_domains(); } /** @@ -244,20 +263,37 @@ public function err_domains() { * * @since 3.0 */ - public function check_img() { + public function check_img() + { + try { + $this->cls('Cloud')->validate_hash(4); + } catch (\Exception $e) { + return self::err($e->getMessage()); + } + return Img_Optm::cls()->check_img(); } + /** + * Return error + * + * @since 5.7.0.1 + */ + public static function err($code) + { + return array('_res' => 'err', '_msg' => $code); + } + /** * Set internal REST tag to ON * * @since 2.9.4 * @access public */ - public function set_internal_rest_on( $not_used = null ) + public function set_internal_rest_on($not_used = null) { $this->_internal_rest_status = true; - Debug2::debug2( '[REST] ✅ Internal REST ON [filter] rest_request_before_callbacks' ); + Debug2::debug2('[REST] ✅ Internal REST ON [filter] rest_request_before_callbacks'); return $not_used; } @@ -268,10 +304,10 @@ public function set_internal_rest_on( $not_used = null ) * @since 2.9.4 * @access public */ - public function set_internal_rest_off( $not_used = null ) + public function set_internal_rest_off($not_used = null) { $this->_internal_rest_status = false; - Debug2::debug2( '[REST] ❎ Internal REST OFF [filter] rest_request_after_callbacks' ); + Debug2::debug2('[REST] ❎ Internal REST OFF [filter] rest_request_after_callbacks'); return $not_used; } @@ -294,35 +330,35 @@ public function is_internal_rest() * @since 2.9.4 Moved here from Utility, dropped static * @access public */ - public function is_rest( $url = false ) + public function is_rest($url = false) { // For WP 4.4.0- compatibility - if ( ! function_exists( 'rest_get_url_prefix' ) ) { - return defined( 'REST_REQUEST' ) && REST_REQUEST; + if (!function_exists('rest_get_url_prefix')) { + return defined('REST_REQUEST') && REST_REQUEST; } $prefix = rest_get_url_prefix(); // Case #1: After WP_REST_Request initialisation - if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { + if (defined('REST_REQUEST') && REST_REQUEST) { return true; } // Case #2: Support "plain" permalink settings - if ( isset( $_GET[ 'rest_route' ] ) && strpos( trim( $_GET[ 'rest_route' ], '\\/' ), $prefix , 0 ) === 0 ) { + if (isset($_GET['rest_route']) && strpos(trim($_GET['rest_route'], '\\/'), $prefix, 0) === 0) { return true; } - if ( ! $url ) { + if (!$url) { return false; } // Case #3: URL Path begins with wp-json/ (REST prefix) Safe for subfolder installation - $rest_url = wp_parse_url( site_url( $prefix ) ); - $current_url = wp_parse_url( $url ); + $rest_url = wp_parse_url(site_url($prefix)); + $current_url = wp_parse_url($url); // Debug2::debug( '[Util] is_rest check [base] ', $rest_url ); // Debug2::debug( '[Util] is_rest check [curr] ', $current_url ); // Debug2::debug( '[Util] is_rest check [curr2] ', wp_parse_url( add_query_arg( array( ) ) ) ); - return strpos( $current_url[ 'path' ], $rest_url[ 'path' ] ) === 0; + return strpos($current_url['path'], $rest_url['path']) === 0; } } diff --git a/src/root.cls.php b/src/root.cls.php index 330d27c10..6a53c23f6 100644 --- a/src/root.cls.php +++ b/src/root.cls.php @@ -1,14 +1,17 @@ conf( Base::O_CACHE_MOBILE ); + protected function _separate_mobile() + { + return (wp_is_mobile() || apply_filters('litespeed_is_mobile', false)) && $this->conf(Base::O_CACHE_MOBILE); } /** @@ -34,16 +38,17 @@ protected function _separate_mobile() { * @since 4.4 * @access public */ - public static function debug( $msg, $backtrace_limit = false ) { - if ( ! defined( 'LSCWP_LOG' ) ) { + public static function debug($msg, $backtrace_limit = false) + { + if (!defined('LSCWP_LOG')) { return; } - if ( defined( 'static::LOG_TAG' )) { + if (defined('static::LOG_TAG')) { $msg = static::LOG_TAG . ' ' . $msg; } - Debug2::debug( $msg, $backtrace_limit ); + Debug2::debug($msg, $backtrace_limit); } /** @@ -52,15 +57,16 @@ public static function debug( $msg, $backtrace_limit = false ) { * @since 4.4 * @access public */ - public static function debug2( $msg, $backtrace_limit = false ) { - if ( ! defined( 'LSCWP_LOG_MORE' ) ) { + public static function debug2($msg, $backtrace_limit = false) + { + if (!defined('LSCWP_LOG_MORE')) { return; } - if ( defined( 'static::LOG_TAG' )) { + if (defined('static::LOG_TAG')) { $msg = static::LOG_TAG . ' ' . $msg; } - Debug2::debug2( $msg, $backtrace_limit ); + Debug2::debug2($msg, $backtrace_limit); } /** @@ -68,10 +74,11 @@ public static function debug2( $msg, $backtrace_limit = false ) { * * @since 3.0 */ - public function has_cache_folder( $type ) { - $subsite_id = is_multisite() && ! is_network_admin() ? get_current_blog_id() : ''; + public function has_cache_folder($type) + { + $subsite_id = is_multisite() && !is_network_admin() ? get_current_blog_id() : ''; - if ( file_exists( LITESPEED_STATIC_DIR . '/' . $type . '/' . $subsite_id ) ) { + if (file_exists(LITESPEED_STATIC_DIR . '/' . $type . '/' . $subsite_id)) { return true; } return false; @@ -82,11 +89,12 @@ public function has_cache_folder( $type ) { * * @since 4.4.2 */ - protected function _maybe_mk_cache_folder( $type ) { - if ( ! $this->has_cache_folder( $type ) ) { - $subsite_id = is_multisite() && ! is_network_admin() ? get_current_blog_id() : ''; + protected function _maybe_mk_cache_folder($type) + { + if (!$this->has_cache_folder($type)) { + $subsite_id = is_multisite() && !is_network_admin() ? get_current_blog_id() : ''; $path = LITESPEED_STATIC_DIR . '/' . $type . '/' . $subsite_id; - mkdir( $path, 0755, true ); + mkdir($path, 0755, true); } } @@ -95,29 +103,27 @@ protected function _maybe_mk_cache_folder( $type ) { * * @since 3.0 */ - public function rm_cache_folder( $type ) { - if ( ! $this->has_cache_folder( $type ) ) { + public function rm_cache_folder($type) + { + if (!$this->has_cache_folder($type)) { return; } - $subsite_id = is_multisite() && ! is_network_admin() ? get_current_blog_id() : ''; + $subsite_id = is_multisite() && !is_network_admin() ? get_current_blog_id() : ''; - File::rrmdir( LITESPEED_STATIC_DIR . '/' . $type . '/' . $subsite_id ); + File::rrmdir(LITESPEED_STATIC_DIR . '/' . $type . '/' . $subsite_id); // Clear All summary data - self::save_summary( false, false, true ); + self::save_summary(false, false, true); - if ( $type == 'ccss' || $type == 'ucss') { - Debug2::debug( '[CSS] Cleared ' . $type . ' queue' ); - } - elseif ( $type == 'avatar' ) { - Debug2::debug( '[Avatar] Cleared ' . $type . ' queue' ); - } - elseif ( $type == 'css' || $type == 'js' ) { + if ($type == 'ccss' || $type == 'ucss') { + Debug2::debug('[CSS] Cleared ' . $type . ' queue'); + } elseif ($type == 'avatar') { + Debug2::debug('[Avatar] Cleared ' . $type . ' queue'); + } elseif ($type == 'css' || $type == 'js') { return; - } - else { - Debug2::debug( '[' . strtoupper( $type ) . '] Cleared ' . $type . ' queue' ); + } else { + Debug2::debug('[' . strtoupper($type) . '] Cleared ' . $type . ' queue'); } } @@ -126,9 +132,10 @@ public function rm_cache_folder( $type ) { * * @since 4.0 */ - protected function _build_filepath_prefix( $type ) { + protected function _build_filepath_prefix($type) + { $filepath_prefix = '/' . $type . '/'; - if ( is_multisite() ) { + if (is_multisite()) { $filepath_prefix .= get_current_blog_id() . '/'; } @@ -141,13 +148,14 @@ protected function _build_filepath_prefix( $type ) { * @since 4.1 * @since 4.3 Elevated to root.cls */ - public function load_queue( $type ) { - $filepath_prefix = $this->_build_filepath_prefix( $type ); + public function load_queue($type) + { + $filepath_prefix = $this->_build_filepath_prefix($type); $static_path = LITESPEED_STATIC_DIR . $filepath_prefix . '.litespeed_conf.dat'; $queue = array(); - if ( file_exists( $static_path ) ) { - $queue = json_decode( file_get_contents( $static_path ), true ) ?: array(); + if (file_exists($static_path)) { + $queue = json_decode(file_get_contents($static_path), true) ?: array(); } return $queue; @@ -159,13 +167,14 @@ public function load_queue( $type ) { * @since 4.1 * @since 4.3 Elevated to root.cls */ - public function save_queue( $type, $list ) { - $filepath_prefix = $this->_build_filepath_prefix( $type ); + public function save_queue($type, $list) + { + $filepath_prefix = $this->_build_filepath_prefix($type); $static_path = LITESPEED_STATIC_DIR . $filepath_prefix . '.litespeed_conf.dat'; - $data = json_encode( $list ); + $data = json_encode($list); - File::save( $static_path, $data, true ); + File::save($static_path, $data, true); } /** @@ -174,91 +183,99 @@ public function save_queue( $type, $list ) { * @since 3.4 * @since 4.3 Elevated to root.cls */ - public function clear_q( $type ) { - $filepath_prefix = $this->_build_filepath_prefix( $type ); + public function clear_q($type, $silent = false) + { + $filepath_prefix = $this->_build_filepath_prefix($type); $static_path = LITESPEED_STATIC_DIR . $filepath_prefix . '.litespeed_conf.dat'; - if ( file_exists( $static_path ) ) { - unlink( $static_path ); + if (file_exists($static_path)) { + $silent = false; + unlink($static_path); } - $msg = __( 'Queue cleared successfully.', 'litespeed-cache' ); - Admin_Display::succeed( $msg ); + if (!$silent) { + $msg = __('All QUIC.cloud service queues have been cleared.', 'litespeed-cache'); + Admin_Display::succeed($msg); + } } /** * Load an instance or create it if not existed * @since 4.0 */ - public static function cls( $cls = false, $unset = false, $data = false ) { - if ( ! $cls ) { + public static function cls($cls = false, $unset = false, $data = false) + { + if (!$cls) { $cls = self::ori_cls(); } $cls = __NAMESPACE__ . '\\' . $cls; - $cls_tag = strtolower( $cls ); + $cls_tag = strtolower($cls); - if ( ! isset( self::$_instances[ $cls_tag ] ) ) { - if ( $unset ) { + if (!isset(self::$_instances[$cls_tag])) { + if ($unset) { return; } - self::$_instances[ $cls_tag ] = new $cls( $data ); - } - else { - if ( $unset ) { - unset( self::$_instances[ $cls_tag ] ); + self::$_instances[$cls_tag] = new $cls($data); + } else { + if ($unset) { + unset(self::$_instances[$cls_tag]); return; } } - return self::$_instances[ $cls_tag ]; + return self::$_instances[$cls_tag]; } /** * Set one conf or confs */ - public function set_conf( $id, $val = null ) { - if ( is_array( $id ) ) { - foreach ( $id as $k => $v ) { - $this->set_conf( $k, $v ); + public function set_conf($id, $val = null) + { + if (is_array($id)) { + foreach ($id as $k => $v) { + $this->set_conf($k, $v); } return; } - self::$_options[ $id ] = $val; + self::$_options[$id] = $val; } /** * Set one primary conf or confs */ - public function set_primary_conf( $id, $val = null ) { - if ( is_array( $id ) ) { - foreach ( $id as $k => $v ) { - $this->set_primary_conf( $k, $v ); + public function set_primary_conf($id, $val = null) + { + if (is_array($id)) { + foreach ($id as $k => $v) { + $this->set_primary_conf($k, $v); } return; } - self::$_primary_options[ $id ] = $val; + self::$_primary_options[$id] = $val; } /** * Set one network conf */ - public function set_network_conf( $id, $val = null ) { - if ( is_array( $id ) ) { - foreach ( $id as $k => $v ) { - $this->set_network_conf( $k, $v ); + public function set_network_conf($id, $val = null) + { + if (is_array($id)) { + foreach ($id as $k => $v) { + $this->set_network_conf($k, $v); } return; } - self::$_network_options[ $id ] = $val; + self::$_network_options[$id] = $val; } /** * Set one const conf */ - public function set_const_conf( $id, $val ) { - self::$_const_options[ $id ] = $val; + public function set_const_conf($id, $val) + { + self::$_const_options[$id] = $val; } /** @@ -266,11 +283,12 @@ public function set_const_conf( $id, $val ) { * * @since 3.0 */ - public function const_overwritten( $id ) { - if ( ! isset( self::$_const_options[ $id ] ) || self::$_const_options[ $id ] == self::$_options[ $id ] ) { + public function const_overwritten($id) + { + if (!isset(self::$_const_options[$id]) || self::$_const_options[$id] == self::$_options[$id]) { return null; } - return self::$_const_options[ $id ]; + return self::$_const_options[$id]; } /** @@ -278,17 +296,18 @@ public function const_overwritten( $id ) { * * @since 3.2.2 */ - public function primary_overwritten( $id ) { - if ( ! isset( self::$_primary_options[ $id ] ) || self::$_primary_options[ $id ] == self::$_options[ $id ] ) { + public function primary_overwritten($id) + { + if (!isset(self::$_primary_options[$id]) || self::$_primary_options[$id] == self::$_options[$id]) { return null; } // Network admin settings is impossible to be overwritten by primary - if ( is_network_admin() ) { + if (is_network_admin()) { return null; } - return self::$_primary_options[ $id ]; + return self::$_primary_options[$id]; } /** @@ -296,9 +315,10 @@ public function primary_overwritten( $id ) { * * @since 1.0 */ - public function get_options( $ori = false ) { - if ( ! $ori ) { - return array_merge( self::$_options, self::$_primary_options, self::$_const_options ); + public function get_options($ori = false) + { + if (!$ori) { + return array_merge(self::$_options, self::$_primary_options, self::$_network_options, self::$_const_options); } return self::$_options; @@ -307,62 +327,65 @@ public function get_options( $ori = false ) { /** * If has a conf or not */ - public function has_conf( $id ) { - return array_key_exists( $id, self::$_options ); + public function has_conf($id) + { + return array_key_exists($id, self::$_options); } /** * If has a primary conf or not */ - public function has_primary_conf( $id ) { - return array_key_exists( $id, self::$_primary_options ); + public function has_primary_conf($id) + { + return array_key_exists($id, self::$_primary_options); } /** * If has a network conf or not */ - public function has_network_conf( $id ) { - return array_key_exists( $id, self::$_network_options ); + public function has_network_conf($id) + { + return array_key_exists($id, self::$_network_options); } /** * Get conf */ - public function conf( $id, $ori = false ) { - if ( isset( self::$_options[ $id ] ) ) { - if ( ! $ori ) { - $val = $this->const_overwritten( $id ); - if ( $val !== null ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Conf] 🏛️ const option ' . $id . '=' . var_export( $val, true ) ); + public function conf($id, $ori = false) + { + if (isset(self::$_options[$id])) { + if (!$ori) { + $val = $this->const_overwritten($id); + if ($val !== null) { + defined('LSCWP_LOG') && Debug2::debug('[Conf] 🏛️ const option ' . $id . '=' . var_export($val, true)); return $val; } - $val = $this->primary_overwritten( $id ); // Network Use primary site settings - if ( $val !== null ) { + $val = $this->primary_overwritten($id); // Network Use primary site settings + if ($val !== null) { return $val; } } // Network orignal value will be in _network_options - if ( ! is_network_admin() || ! $this->has_network_conf( $id ) ) { - return self::$_options[ $id ]; + if (!is_network_admin() || !$this->has_network_conf($id)) { + return self::$_options[$id]; } - } - if ( $this->has_network_conf( $id ) ) { - if ( ! $ori ) { - $val = $this->const_overwritten( $id ); - if ( $val !== null ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Conf] 🏛️ const option ' . $id . '=' . var_export( $val, true ) ); + if ($this->has_network_conf($id)) { + if (!$ori) { + $val = $this->const_overwritten($id); + if ($val !== null) { + defined('LSCWP_LOG') && Debug2::debug('[Conf] 🏛️ const option ' . $id . '=' . var_export($val, true)); return $val; } } - return $this->network_conf( $id ); + return $this->network_conf($id); } - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Conf] Invalid option ID ' . $id ); + defined('LSCWP_LOG') && Debug2::debug('[Conf] Invalid option ID ' . $id); return null; } @@ -370,29 +393,33 @@ public function conf( $id, $ori = false ) { /** * Get primary conf */ - public function primary_conf( $id ) { - return self::$_primary_options[ $id ]; + public function primary_conf($id) + { + return self::$_primary_options[$id]; } /** * Get network conf */ - public function network_conf( $id ) { - if ( ! $this->has_network_conf( $id ) ) { + public function network_conf($id) + { + if (!$this->has_network_conf($id)) { return null; } - return self::$_network_options[ $id ]; + return self::$_network_options[$id]; } /** * Get called class short name */ - public static function ori_cls() { - $cls = new \ReflectionClass( get_called_class() ); + public static function ori_cls() + { + $cls = new \ReflectionClass(get_called_class()); $shortname = $cls->getShortName(); - $namespace = str_replace( __NAMESPACE__ . '\\', '', $cls->getNamespaceName() . '\\' ); - if ( $namespace ) { // the left namespace after dropped LiteSpeed + $namespace = str_replace(__NAMESPACE__ . '\\', '', $cls->getNamespaceName() . '\\'); + if ($namespace) { + // the left namespace after dropped LiteSpeed $shortname = $namespace . $shortname; } @@ -404,9 +431,11 @@ public static function ori_cls() { * * @since 3.0 */ - public static function name( $id ) { - $name = strtolower( self::ori_cls() ); - if ( $name == 'conf2' ) { // For a certain 3.7rc correction, can be dropped after v4 + public static function name($id) + { + $name = strtolower(self::ori_cls()); + if ($name == 'conf2') { + // For a certain 3.7rc correction, can be dropped after v4 $name = 'conf'; } return 'litespeed.' . $name . '.' . $id; @@ -417,12 +446,13 @@ public static function name( $id ) { * * @since 3.0 */ - public static function get_option( $id, $default_v = false ) { - $v = get_option( self::name( $id ), $default_v ); + public static function get_option($id, $default_v = false) + { + $v = get_option(self::name($id), $default_v); // Maybe decode array - if ( is_array( $default_v ) ) { - $v = self::_maybe_decode( $v ); + if (is_array($default_v)) { + $v = self::_maybe_decode($v); } return $v; @@ -433,12 +463,13 @@ public static function get_option( $id, $default_v = false ) { * * @since 3.0 */ - public static function get_site_option( $id, $default_v = false ) { - $v = get_site_option( self::name( $id ), $default_v ); + public static function get_site_option($id, $default_v = false) + { + $v = get_site_option(self::name($id), $default_v); // Maybe decode array - if ( is_array( $default_v ) ) { - $v = self::_maybe_decode( $v ); + if (is_array($default_v)) { + $v = self::_maybe_decode($v); } return $v; @@ -449,12 +480,13 @@ public static function get_site_option( $id, $default_v = false ) { * * @since 3.0 */ - public static function get_blog_option( $blog_id, $id, $default_v = false ) { - $v = get_blog_option( $blog_id, self::name( $id ), $default_v ); + public static function get_blog_option($blog_id, $id, $default_v = false) + { + $v = get_blog_option($blog_id, self::name($id), $default_v); // Maybe decode array - if ( is_array( $default_v ) ) { - $v = self::_maybe_decode( $v ); + if (is_array($default_v)) { + $v = self::_maybe_decode($v); } return $v; @@ -465,8 +497,9 @@ public static function get_blog_option( $blog_id, $id, $default_v = false ) { * * @since 3.0 */ - public static function add_option( $id, $v ) { - add_option( self::name( $id ), self::_maybe_encode( $v ) ); + public static function add_option($id, $v) + { + add_option(self::name($id), self::_maybe_encode($v)); } /** @@ -474,8 +507,9 @@ public static function add_option( $id, $v ) { * * @since 3.0 */ - public static function add_site_option( $id, $v ) { - add_site_option( self::name( $id ), self::_maybe_encode( $v ) ); + public static function add_site_option($id, $v) + { + add_site_option(self::name($id), self::_maybe_encode($v)); } /** @@ -483,8 +517,9 @@ public static function add_site_option( $id, $v ) { * * @since 3.0 */ - public static function update_option( $id, $v ) { - update_option( self::name( $id ), self::_maybe_encode( $v ) ); + public static function update_option($id, $v) + { + update_option(self::name($id), self::_maybe_encode($v)); } /** @@ -492,8 +527,9 @@ public static function update_option( $id, $v ) { * * @since 3.0 */ - public static function update_site_option( $id, $v ) { - update_site_option( self::name( $id ), self::_maybe_encode( $v ) ); + public static function update_site_option($id, $v) + { + update_site_option(self::name($id), self::_maybe_encode($v)); } /** @@ -501,10 +537,11 @@ public static function update_site_option( $id, $v ) { * * @since 4.0 */ - private static function _maybe_decode( $v ) { - if ( ! is_array( $v ) ) { - $v2 = json_decode( $v, true ); - if ( $v2 !== null ) { + private static function _maybe_decode($v) + { + if (!is_array($v)) { + $v2 = json_decode($v, true); + if ($v2 !== null) { $v = $v2; } } @@ -516,9 +553,10 @@ private static function _maybe_decode( $v ) { * * @since 4.0 */ - private static function _maybe_encode( $v ) { - if ( is_array( $v ) ) { - $v = json_encode( $v ) ?: $v; // Non utf-8 encoded value will get failed, then used ori value + private static function _maybe_encode($v) + { + if (is_array($v)) { + $v = json_encode($v) ?: $v; // Non utf-8 encoded value will get failed, then used ori value } return $v; } @@ -528,8 +566,9 @@ private static function _maybe_encode( $v ) { * * @since 3.0 */ - public static function delete_option( $id ) { - delete_option( self::name( $id ) ); + public static function delete_option($id) + { + delete_option(self::name($id)); } /** @@ -537,8 +576,9 @@ public static function delete_option( $id ) { * * @since 3.0 */ - public static function delete_site_option( $id ) { - delete_site_option( self::name( $id ) ); + public static function delete_site_option($id) + { + delete_site_option(self::name($id)); } /** @@ -547,19 +587,20 @@ public static function delete_site_option( $id ) { * @since 3.0 * @access public */ - public static function get_summary( $field = false ) { - $summary = self::get_option( '_summary', array() ); + public static function get_summary($field = false) + { + $summary = self::get_option('_summary', array()); - if ( ! is_array( $summary ) ) { + if (!is_array($summary)) { $summary = array(); } - if ( ! $field ) { + if (!$field) { return $summary; } - if ( array_key_exists( $field, $summary ) ) { - return $summary[ $field ]; + if (array_key_exists($field, $summary)) { + return $summary[$field]; } return null; @@ -571,27 +612,29 @@ public static function get_summary( $field = false ) { * @since 3.0 * @access public */ - public static function save_summary( $data = false, $reload = false, $overwrite = false ) { - if ( $reload || empty( static::cls()->_summary ) ) { + public static function save_summary($data = false, $reload = false, $overwrite = false) + { + if ($reload || empty(static::cls()->_summary)) { self::reload_summary(); } $existing_summary = static::cls()->_summary; - if ( $overwrite || !is_array($existing_summary)) { + if ($overwrite || !is_array($existing_summary)) { $existing_summary = array(); } - $new_summary = array_merge( $existing_summary, $data ?: array() ); -// self::debug2( 'Save after Reloaded summary', $new_summary ); + $new_summary = array_merge($existing_summary, $data ?: array()); + // self::debug2( 'Save after Reloaded summary', $new_summary ); static::cls()->_summary = $new_summary; - self::update_option( '_summary', $new_summary ); + self::update_option('_summary', $new_summary); } /** * Reload summary * @since 5.0 */ - public static function reload_summary() { + public static function reload_summary() + { static::cls()->_summary = self::get_summary(); // self::debug2( 'Reloaded summary', static::cls()->_summary ); } @@ -601,8 +644,8 @@ public static function reload_summary() { * * @since 3.0 */ - public static function get_instance() { + public static function get_instance() + { return static::cls(); } - } diff --git a/src/router.cls.php b/src/router.cls.php index 54e6ed45b..fc72ca38c 100644 --- a/src/router.cls.php +++ b/src/router.cls.php @@ -8,9 +8,10 @@ * @since 1.5 Moved into /inc */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Router extends Base { +class Router extends Base +{ const NONCE = 'LSCWP_NONCE'; const ACTION = 'LSCWP_CTRL'; @@ -30,6 +31,7 @@ class Router extends Base { const ACTION_CSS = 'css'; const ACTION_UCSS = 'ucss'; const ACTION_VPI = 'vpi'; + const ACTION_PRESET = 'preset'; const ACTION_IMPORT = 'import'; const ACTION_REPORT = 'report'; const ACTION_DEBUG2 = 'debug2'; @@ -51,6 +53,7 @@ class Router extends Base { self::ACTION_DEBUG2, self::ACTION_HEALTH, self::ACTION_IMG_OPTM, + self::ACTION_PRESET, self::ACTION_IMPORT, self::ACTION_PLACEHOLDER, self::ACTION_PURGE, @@ -77,20 +80,21 @@ class Router extends Base { * @since 3.0 * @access public */ - public static function self_redirect( $action, $type ) { - if ( defined( 'LITESPEED_CLI' ) || defined( 'DOING_CRON' ) ) { - Admin_Display::succeed( 'To be continued' ); // Show for CLI + public static function self_redirect($action, $type) + { + if (defined('LITESPEED_CLI') || defined('DOING_CRON')) { + Admin_Display::succeed('To be continued'); // Show for CLI return; } // Add i to avoid browser too many redirected warning - $i = ! empty( $_GET[ 'litespeed_i' ] ) ? $_GET[ 'litespeed_i' ] : 0; - $i ++; + $i = !empty($_GET['litespeed_i']) ? $_GET['litespeed_i'] : 0; + $i++; - $link = Utility::build_url( $action, $type, false, null, array( 'litespeed_i' => $i ) ); + $link = Utility::build_url($action, $type, false, null, array('litespeed_i' => $i)); - $url = html_entity_decode( $link ); - exit( "" ); + $url = html_entity_decode($link); + exit(""); } /** @@ -100,34 +104,31 @@ public static function self_redirect( $action, $type ) { * @since 2.3.1 Relocated from cdn.cls * @access public */ - public function can_optm() { + public function can_optm() + { $can = true; - if ( is_user_logged_in() && $this->conf( self::O_OPTM_GUEST_ONLY ) ) { + if (is_user_logged_in() && $this->conf(self::O_OPTM_GUEST_ONLY)) { $can = false; - } - elseif ( is_admin() ) { + } elseif (is_admin()) { $can = false; - } - elseif ( is_feed() ) { + } elseif (is_feed()) { $can = false; - } - elseif ( is_preview() ) { + } elseif (is_preview()) { $can = false; - } - elseif ( self::is_ajax() ) { + } elseif (self::is_ajax()) { $can = false; } - if ( self::_is_login_page() ) { - Debug2::debug( '[Router] Optm bypassed: login/reg page' ); + if (self::_is_login_page()) { + Debug2::debug('[Router] Optm bypassed: login/reg page'); $can = false; } - $can_final = apply_filters( 'litespeed_can_optm', $can ); + $can_final = apply_filters('litespeed_can_optm', $can); - if ( $can_final != $can ) { - Debug2::debug( '[Router] Optm bypassed: filter' ); + if ($can_final != $can) { + Debug2::debug('[Router] Optm bypassed: filter'); } return $can_final; @@ -139,8 +140,9 @@ public function can_optm() { * @since 2.4.2.1 * @access public */ - public static function from_admin() { - return ! empty( $_SERVER[ 'HTTP_REFERER' ] ) && strpos( $_SERVER[ 'HTTP_REFERER' ], get_admin_url() ) === 0; + public static function from_admin() + { + return !empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], get_admin_url()) === 0; } /** @@ -150,24 +152,23 @@ public static function from_admin() { * @since 2.3.1 Relocated from cdn.cls * @access public */ - public static function can_cdn() { + public static function can_cdn() + { $can = true; - if ( is_admin() ) { - if ( ! self::is_ajax() ) { - Debug2::debug2( '[Router] CDN bypassed: is not ajax call' ); + if (is_admin()) { + if (!self::is_ajax()) { + Debug2::debug2('[Router] CDN bypassed: is not ajax call'); $can = false; } - if ( self::from_admin() ) { - Debug2::debug2( '[Router] CDN bypassed: ajax call from admin' ); + if (self::from_admin()) { + Debug2::debug2('[Router] CDN bypassed: ajax call from admin'); $can = false; } - } - elseif ( is_feed() ) { + } elseif (is_feed()) { $can = false; - } - elseif ( is_preview() ) { + } elseif (is_preview()) { $can = false; } @@ -175,7 +176,7 @@ public static function can_cdn() { * Bypass cron to avoid deregister jq notice `Do not deregister the jquery-core script in the administration area.` * @since 2.7.2 */ - if ( defined( 'DOING_CRON' ) ) { + if (defined('DOING_CRON')) { $can = false; } @@ -183,8 +184,8 @@ public static function can_cdn() { * Bypass login/reg page * @since 1.6 */ - if ( self::_is_login_page() ) { - Debug2::debug( '[Router] CDN bypassed: login/reg page' ); + if (self::_is_login_page()) { + Debug2::debug('[Router] CDN bypassed: login/reg page'); $can = false; } @@ -192,20 +193,21 @@ public static function can_cdn() { * Bypass post/page link setting * @since 2.9.8.5 */ - $rest_prefix = function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : apply_filters( 'rest_url_prefix', 'wp-json' ); + $rest_prefix = function_exists('rest_get_url_prefix') ? rest_get_url_prefix() : apply_filters('rest_url_prefix', 'wp-json'); if ( - ! empty( $_SERVER[ 'REQUEST_URI' ] ) && - strpos( $_SERVER[ 'REQUEST_URI' ], $rest_prefix . '/wp/v2/media' ) !== false && - isset( $_SERVER[ 'HTTP_REFERER' ] ) && strpos( $_SERVER[ 'HTTP_REFERER' ], 'wp-admin') !== false + !empty($_SERVER['REQUEST_URI']) && + strpos($_SERVER['REQUEST_URI'], $rest_prefix . '/wp/v2/media') !== false && + isset($_SERVER['HTTP_REFERER']) && + strpos($_SERVER['HTTP_REFERER'], 'wp-admin') !== false ) { - Debug2::debug( '[Router] CDN bypassed: wp-json on admin page' ); + Debug2::debug('[Router] CDN bypassed: wp-json on admin page'); $can = false; } - $can_final = apply_filters( 'litespeed_can_cdn', $can ); + $can_final = apply_filters('litespeed_can_cdn', $can); - if ( $can_final != $can ) { - Debug2::debug( '[Router] CDN bypassed: filter' ); + if ($can_final != $can) { + Debug2::debug('[Router] CDN bypassed: filter'); } return $can_final; @@ -217,8 +219,9 @@ public static function can_cdn() { * @since 2.3.1 * @access protected */ - protected static function _is_login_page() { - if ( in_array( $GLOBALS[ 'pagenow' ], array( 'wp-login.php', 'wp-register.php' ), true ) ) { + protected static function _is_login_page() + { + if (in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'), true)) { return true; } @@ -231,16 +234,17 @@ protected static function _is_login_page() { * @since 1.9.1 * @since 3.3 Renamed from `is_crawler_role_simulation` */ - public function is_role_simulation() { - if( is_admin() ) { + public function is_role_simulation() + { + if (is_admin()) { return; } - if ( empty( $_COOKIE[ 'litespeed_role' ] ) || empty( $_COOKIE[ 'litespeed_hash' ] ) ) { + if (empty($_COOKIE['litespeed_role']) || empty($_COOKIE['litespeed_hash'])) { return; } - Debug2::debug( '[Router] starting role validation' ); + Debug2::debug('[Router] starting role validation'); // Check if is from crawler // if ( empty( $_SERVER[ 'HTTP_USER_AGENT' ] ) || strpos( $_SERVER[ 'HTTP_USER_AGENT' ], Crawler::FAST_USER_AGENT ) !== 0 ) { @@ -249,16 +253,16 @@ public function is_role_simulation() { // } // Hash validation - $hash = self::get_option( self::ITEM_HASH ); - if ( ! $hash || $_COOKIE[ 'litespeed_hash' ] != $hash ) { - Debug2::debug( '[Router] hash not match ' . $_COOKIE[ 'litespeed_hash' ] . ' != ' . $hash ); + $hash = self::get_option(self::ITEM_HASH); + if (!$hash || $_COOKIE['litespeed_hash'] != $hash) { + Debug2::debug('[Router] hash not match ' . $_COOKIE['litespeed_hash'] . ' != ' . $hash); return; } - $role_uid = $_COOKIE[ 'litespeed_role' ]; - Debug2::debug( '[Router] role simulate litespeed_role uid ' . $role_uid ); + $role_uid = $_COOKIE['litespeed_role']; + Debug2::debug('[Router] role simulate litespeed_role uid ' . $role_uid); - wp_set_current_user( $role_uid ); + wp_set_current_user($role_uid); } /** @@ -266,15 +270,16 @@ public function is_role_simulation() { * * @since 3.3 */ - public static function get_hash() { + public static function get_hash() + { // Reuse previous hash if existed - $hash = self::get_option( self::ITEM_HASH ); - if ( $hash ) { + $hash = self::get_option(self::ITEM_HASH); + if ($hash) { return $hash; } - $hash = Str::rrand( 6 ); - self::update_option( self::ITEM_HASH, $hash ); + $hash = Str::rrand(6); + self::update_option(self::ITEM_HASH, $hash); return $hash; } @@ -283,29 +288,30 @@ public static function get_hash() { * * @since 1.6.2 */ - public static function get_role( $uid = null ) { - if ( defined( 'LITESPEED_WP_ROLE' ) ) { + public static function get_role($uid = null) + { + if (defined('LITESPEED_WP_ROLE')) { return LITESPEED_WP_ROLE; } - if ( $uid === null ) { + if ($uid === null) { $uid = get_current_user_id(); } $role = false; - if ( $uid ) { - $user = get_userdata( $uid ); - if ( isset( $user->roles ) && is_array( $user->roles ) ) { - $tmp = array_values( $user->roles ); - $role = array_shift( $tmp ); + if ($uid) { + $user = get_userdata($uid); + if (isset($user->roles) && is_array($user->roles)) { + $tmp = array_values($user->roles); + $role = implode(',', $tmp); // Combine for PHP5.3 const comaptibility } } - Debug2::debug( '[Router] get_role: ' . $role ); + Debug2::debug('[Router] get_role: ' . $role); - if ( ! $role ) { + if (!$role) { return $role; // Guest user - Debug2::debug( '[Router] role: guest' ); + Debug2::debug('[Router] role: guest'); /** * Fix double login issue @@ -313,12 +319,12 @@ public static function get_role( $uid = null ) { * @see https://github.com/litespeedtech/lscache_wp/commit/69e7bc71d0de5cd58961bae953380b581abdc088 * @since 2.9.8 Won't assign const if in login process */ - if ( substr_compare( wp_login_url(), $GLOBALS[ 'pagenow' ], -strlen( $GLOBALS[ 'pagenow' ] ) ) === 0 ) { + if (substr_compare(wp_login_url(), $GLOBALS['pagenow'], -strlen($GLOBALS['pagenow'])) === 0) { return $role; } } - define( 'LITESPEED_WP_ROLE', $role ); + define('LITESPEED_WP_ROLE', $role); return LITESPEED_WP_ROLE; } @@ -330,17 +336,19 @@ public static function get_role( $uid = null ) { * @access public * @return boolean */ - public static function frontend_path() { //todo: move to htaccess.cls ? - if ( ! isset( self::$_frontend_path ) ) { - $frontend = rtrim( ABSPATH, '/' ); // /home/user/public_html/frontend + public static function frontend_path() + { + //todo: move to htaccess.cls ? + if (!isset(self::$_frontend_path)) { + $frontend = rtrim(ABSPATH, '/'); // /home/user/public_html/frontend // get home path failed. Trac ticket #37668 (e.g. frontend:/blog backend:/wordpress) - if ( ! $frontend ) { - Debug2::debug( '[Router] No ABSPATH, generating from home option' ); - $frontend = parse_url( get_option( 'home' ) ); - $frontend = ! empty( $frontend[ 'path' ] ) ? $frontend[ 'path' ] : ''; - $frontend = $_SERVER[ 'DOCUMENT_ROOT' ] . $frontend; + if (!$frontend) { + Debug2::debug('[Router] No ABSPATH, generating from home option'); + $frontend = parse_url(get_option('home')); + $frontend = !empty($frontend['path']) ? $frontend['path'] : ''; + $frontend = $_SERVER['DOCUMENT_ROOT'] . $frontend; } - $frontend = realpath( $frontend ); + $frontend = realpath($frontend); self::$_frontend_path = $frontend; } @@ -354,10 +362,11 @@ public static function frontend_path() { //todo: move to htaccess.cls ? * @access public * @return boolean */ - public function esi_enabled() { - if ( ! isset( self::$_esi_enabled ) ) { - self::$_esi_enabled = defined( 'LITESPEED_ON' ) && $this->conf( self::O_ESI ); - if( ! empty( $_REQUEST[ self::ACTION ] ) ) { + public function esi_enabled() + { + if (!isset(self::$_esi_enabled)) { + self::$_esi_enabled = defined('LITESPEED_ON') && $this->conf(self::O_ESI); + if (!empty($_REQUEST[self::ACTION])) { self::$_esi_enabled = false; } } @@ -370,13 +379,14 @@ public function esi_enabled() { * @since 1.1.1 * @access public */ - public static function can_crawl() { - if ( isset( $_SERVER[ 'X-LSCACHE' ] ) && strpos( $_SERVER[ 'X-LSCACHE' ], 'crawler' ) === false ) { + public static function can_crawl() + { + if (isset($_SERVER['X-LSCACHE']) && strpos($_SERVER['X-LSCACHE'], 'crawler') === false) { return false; } // CLI will bypass this check as crawler library can always do the 428 check - if ( defined( 'LITESPEED_CLI' ) ) { + if (defined('LITESPEED_CLI')) { return true; } @@ -390,14 +400,14 @@ public static function can_crawl() { * @access public * @return string */ - public static function get_action() { - if ( ! isset( self::$_action ) ) { + public static function get_action() + { + if (!isset(self::$_action)) { self::$_action = false; self::cls()->verify_action(); - if ( self::$_action ) { - defined( 'LSCWP_LOG' ) && Debug2::debug( '[Router] LSCWP_CTRL verified: ' . var_export( self::$_action, true ) ); + if (self::$_action) { + defined('LSCWP_LOG') && Debug2::debug('[Router] LSCWP_CTRL verified: ' . var_export(self::$_action, true)); } - } return self::$_action; } @@ -409,8 +419,9 @@ public static function get_action() { * @access public * @return boolean */ - public static function is_logged_in() { - if ( ! isset( self::$_is_logged_in ) ) { + public static function is_logged_in() + { + if (!isset(self::$_is_logged_in)) { self::$_is_logged_in = is_user_logged_in(); } return self::$_is_logged_in; @@ -423,9 +434,10 @@ public static function is_logged_in() { * @access public * @return boolean */ - public static function is_ajax() { - if ( ! isset( self::$_is_ajax ) ) { - self::$_is_ajax = defined( 'DOING_AJAX' ) && DOING_AJAX; + public static function is_ajax() + { + if (!isset(self::$_is_ajax)) { + self::$_is_ajax = defined('DOING_AJAX') && DOING_AJAX; } return self::$_is_ajax; } @@ -437,11 +449,12 @@ public static function is_ajax() { * @access public * @return boolean */ - public function is_admin_ip() { - if ( ! isset( self::$_is_admin_ip ) ) { - $ips = $this->conf( self::O_DEBUG_IPS ); + public function is_admin_ip() + { + if (!isset(self::$_is_admin_ip)) { + $ips = $this->conf(self::O_DEBUG_IPS); - self::$_is_admin_ip = $this->ip_access( $ips ); + self::$_is_admin_ip = $this->ip_access($ips); } return self::$_is_admin_ip; } @@ -452,15 +465,16 @@ public function is_admin_ip() { * @since 1.6 * @access public */ - public static function verify_type() { - if ( empty( $_REQUEST[ self::TYPE ] ) ) { - Debug2::debug( '[Router] no type', 2 ); + public static function verify_type() + { + if (empty($_REQUEST[self::TYPE])) { + Debug2::debug('[Router] no type', 2); return false; } - Debug2::debug( '[Router] parsed type: ' . $_REQUEST[ self::TYPE ], 2 ); + Debug2::debug('[Router] parsed type: ' . $_REQUEST[self::TYPE], 2); - return $_REQUEST[ self::TYPE ]; + return $_REQUEST[self::TYPE]; } /** @@ -469,44 +483,47 @@ public static function verify_type() { * @since 1.1.0 * @access private */ - private function verify_action() { - if ( empty( $_REQUEST[ Router::ACTION ] ) ) { - Debug2::debug2( '[Router] LSCWP_CTRL bypassed empty' ); + private function verify_action() + { + if (empty($_REQUEST[Router::ACTION])) { + Debug2::debug2('[Router] LSCWP_CTRL bypassed empty'); return; } - $action = stripslashes($_REQUEST[ Router::ACTION ]); + $action = stripslashes($_REQUEST[Router::ACTION]); - if ( ! $action ) { - return; + if (!$action) { + return; } $_is_public_action = false; // Each action must have a valid nonce unless its from admin ip and is public action // Validate requests nonce (from admin logged in page or cli) - if ( ! $this->verify_nonce( $action ) ) { + if (!$this->verify_nonce($action)) { // check if it is from admin ip - if ( ! $this->is_admin_ip() ) { - Debug2::debug( '[Router] LSCWP_CTRL query string - did not match admin IP: ' . $action ); + if (!$this->is_admin_ip()) { + Debug2::debug('[Router] LSCWP_CTRL query string - did not match admin IP: ' . $action); return; } // check if it is public action - if ( ! in_array( $action, array( + if ( + !in_array($action, array( Core::ACTION_QS_NOCACHE, Core::ACTION_QS_PURGE, Core::ACTION_QS_PURGE_SINGLE, Core::ACTION_QS_SHOW_HEADERS, Core::ACTION_QS_PURGE_ALL, Core::ACTION_QS_PURGE_EMPTYCACHE, - ) ) ) { - Debug2::debug( '[Router] LSCWP_CTRL query string - did not match admin IP Actions: ' . $action ); + )) + ) { + Debug2::debug('[Router] LSCWP_CTRL query string - did not match admin IP Actions: ' . $action); return; } - if ( apply_filters( 'litespeed_qs_forbidden', false ) ) { - Debug2::debug( '[Router] LSCWP_CTRL forbidden by hook litespeed_qs_forbidden' ); + if (apply_filters('litespeed_qs_forbidden', false)) { + Debug2::debug('[Router] LSCWP_CTRL forbidden by hook litespeed_qs_forbidden'); return; } @@ -514,36 +531,37 @@ private function verify_action() { } /* Now it is a valid action, lets log and check the permission */ - Debug2::debug( '[Router] LSCWP_CTRL: ' . $action ); + Debug2::debug('[Router] LSCWP_CTRL: ' . $action); // OK, as we want to do something magic, lets check if its allowed $_is_multisite = is_multisite(); $_is_network_admin = $_is_multisite && is_network_admin(); - $_can_network_option = $_is_network_admin && current_user_can( 'manage_network_options' ); - $_can_option = current_user_can( 'manage_options' ); + $_can_network_option = $_is_network_admin && current_user_can('manage_network_options'); + $_can_option = current_user_can('manage_options'); - switch ( $action ) { + switch ($action) { // Save network settings case self::ACTION_SAVE_SETTINGS_NETWORK: - if ( $_can_network_option ) { + if ($_can_network_option) { self::$_action = $action; } return; case Core::ACTION_PURGE_BY: - if ( defined( 'LITESPEED_ON' ) && ( $_can_network_option || $_can_option || self::is_ajax() ) ) {//here may need more security + if (defined('LITESPEED_ON') && ($_can_network_option || $_can_option || self::is_ajax())) { + //here may need more security self::$_action = $action; } return; case self::ACTION_DB_OPTM: - if ( $_can_network_option || $_can_option ) { + if ($_can_network_option || $_can_option) { self::$_action = $action; } return; - case Core::ACTION_PURGE_EMPTYCACHE:// todo: moved to purge.cls type action - if ( defined( 'LITESPEED_ON' ) && ( $_can_network_option || ( ! $_is_multisite && $_can_option ) ) ) { + case Core::ACTION_PURGE_EMPTYCACHE: // todo: moved to purge.cls type action + if (defined('LITESPEED_ON') && ($_can_network_option || (!$_is_multisite && $_can_option))) { self::$_action = $action; } return; @@ -554,7 +572,7 @@ private function verify_action() { case Core::ACTION_QS_SHOW_HEADERS: case Core::ACTION_QS_PURGE_ALL: case Core::ACTION_QS_PURGE_EMPTYCACHE: - if ( defined( 'LITESPEED_ON' ) && ( $_is_public_action || self::is_ajax() ) ) { + if (defined('LITESPEED_ON') && ($_is_public_action || self::is_ajax())) { self::$_action = $action; } return; @@ -566,6 +584,7 @@ private function verify_action() { case self::ACTION_CDN_SETUP: case self::ACTION_CDN_CLOUDFLARE: case self::ACTION_CRAWLER: + case self::ACTION_PRESET: case self::ACTION_IMPORT: case self::ACTION_REPORT: case self::ACTION_CSS: @@ -575,14 +594,14 @@ private function verify_action() { case self::ACTION_ACTIVATION: case self::ACTION_HEALTH: case self::ACTION_SAVE_SETTINGS: // Save settings - if ( $_can_option && ! $_is_network_admin ) { + if ($_can_option && !$_is_network_admin) { self::$_action = $action; } return; case self::ACTION_PURGE: case self::ACTION_DEBUG2: - if ( $_can_network_option || $_can_option ) { + if ($_can_network_option || $_can_option) { self::$_action = $action; } return; @@ -598,10 +617,9 @@ private function verify_action() { return; default: - Debug2::debug( '[Router] LSCWP_CTRL match falied: ' . $action ); + Debug2::debug('[Router] LSCWP_CTRL match falied: ' . $action); return; } - } /** @@ -612,11 +630,11 @@ private function verify_action() { * @param string $action * @return bool */ - public function verify_nonce( $action ) { - if ( ! isset( $_REQUEST[ Router::NONCE ] ) || ! wp_verify_nonce( $_REQUEST[ Router::NONCE ], $action ) ) { + public function verify_nonce($action) + { + if (!isset($_REQUEST[Router::NONCE]) || !wp_verify_nonce($_REQUEST[Router::NONCE], $action)) { return false; - } - else{ + } else { return true; } } @@ -627,15 +645,16 @@ public function verify_nonce( $action ) { * @since 1.1.0 * @access public */ - public function ip_access( $ip_list ) { - if ( ! $ip_list ) { + public function ip_access($ip_list) + { + if (!$ip_list) { return false; } - if ( ! isset( self::$_ip ) ) { + if (!isset(self::$_ip)) { self::$_ip = self::get_ip(); } - if ( ! self::$_ip ) { + if (!self::$_ip) { return false; } // $uip = explode('.', $_ip); @@ -645,7 +664,7 @@ public function ip_access( $ip_list ) { // if(count($ip) != 4) continue; // for($i = 0; $i <= 3; $i++) if($ip[$i] == '*') $ip_list[$key][$i] = $uip[$i]; // } - return in_array( self::$_ip, $ip_list ); + return in_array(self::$_ip, $ip_list); } /** @@ -656,7 +675,8 @@ public function ip_access( $ip_list ) { * @access public * @return string */ - public static function get_ip() { + public static function get_ip() + { $_ip = ''; // if ( function_exists( 'apache_request_headers' ) ) { // $apache_headers = apache_request_headers(); @@ -669,8 +689,8 @@ public static function get_ip() { // } - if ( ! $_ip ) { - $_ip = ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : false; + if (!$_ip) { + $_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false; } return $_ip; } @@ -681,8 +701,9 @@ public static function get_ip() { * @since 1.8.2 * @access public */ - public static function opcache_enabled() { - return function_exists( 'opcache_reset' ) && ini_get( 'opcache.enable' ); + public static function opcache_enabled() + { + return function_exists('opcache_reset') && ini_get('opcache.enable'); } /** @@ -690,43 +711,41 @@ public static function opcache_enabled() { * * @since 3.0 */ - public function serve_static() { - if ( ! empty( $_SERVER[ 'SCRIPT_URI' ] ) ) { - if ( strpos( $_SERVER[ 'SCRIPT_URI' ], LITESPEED_STATIC_URL . '/' ) !== 0 ) { + public function serve_static() + { + if (!empty($_SERVER['SCRIPT_URI'])) { + if (strpos($_SERVER['SCRIPT_URI'], LITESPEED_STATIC_URL . '/') !== 0) { return; } - $path = substr( $_SERVER[ 'SCRIPT_URI' ], strlen( LITESPEED_STATIC_URL . '/' ) ); - } - elseif ( ! empty( $_SERVER[ 'REQUEST_URI' ] ) ) { - $static_path = parse_url( LITESPEED_STATIC_URL, PHP_URL_PATH ) . '/'; - if ( strpos( $_SERVER[ 'REQUEST_URI' ], $static_path ) !== 0 ) { + $path = substr($_SERVER['SCRIPT_URI'], strlen(LITESPEED_STATIC_URL . '/')); + } elseif (!empty($_SERVER['REQUEST_URI'])) { + $static_path = parse_url(LITESPEED_STATIC_URL, PHP_URL_PATH) . '/'; + if (strpos($_SERVER['REQUEST_URI'], $static_path) !== 0) { return; } - $path = substr( parse_url( $_SERVER[ 'REQUEST_URI' ], PHP_URL_PATH ), strlen( $static_path ) ); - } - else { + $path = substr(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), strlen($static_path)); + } else { return; } - $path = explode( '/', $path, 2 ); + $path = explode('/', $path, 2); - if ( empty( $path[ 0 ] ) || empty( $path[ 1 ] ) ) { + if (empty($path[0]) || empty($path[1])) { return; } - switch ( $path[ 0 ] ) { + switch ($path[0]) { case 'avatar': - $this->cls( 'Avatar' )->serve_static( $path[ 1 ] ); + $this->cls('Avatar')->serve_static($path[1]); break; case 'localres': - $this->cls( 'Localization' )->serve_static( $path[ 1 ] ); + $this->cls('Localization')->serve_static($path[1]); break; - default : + default: break; } - } /** @@ -737,12 +756,12 @@ public function serve_static() { * @since 3.0 * @access public */ - public function handler( $cls ) { - if ( ! in_array( $cls, self::$_HANDLERS ) ) { + public function handler($cls) + { + if (!in_array($cls, self::$_HANDLERS)) { return; } - return $this->cls( $cls )->handler(); + return $this->cls($cls)->handler(); } - } diff --git a/src/str.cls.php b/src/str.cls.php index 1721ae993..0567150a4 100644 --- a/src/str.cls.php +++ b/src/str.cls.php @@ -1,15 +1,15 @@ conf( Base::O_CACHE_PAGE_LOGIN ) ) { + public function check_login_cacheable() + { + if (!$this->conf(Base::O_CACHE_PAGE_LOGIN)) { return; } - if ( Control::isset_notcacheable() ) { + if (Control::isset_notcacheable()) { return; } - if ( ! empty( $_GET ) ) { - Control::set_nocache( 'has GET request' ); + if (!empty($_GET)) { + Control::set_nocache('has GET request'); return; } - $this->cls( 'Control' )->set_cacheable(); + $this->cls('Control')->set_cacheable(); - self::add( self::TYPE_LOGIN ); + self::add(self::TYPE_LOGIN); // we need to send lsc-cookie manually to make it be sent to all other users when is cacheable $list = headers_list(); - if ( empty( $list ) ) { + if (empty($list)) { return; } - foreach ( $list as $hdr ) { - if ( strncasecmp( $hdr, 'set-cookie:', 11 ) == 0 ) { - $cookie = substr( $hdr, 12 ); - @header( 'lsc-cookie: ' . $cookie, false ); + foreach ($list as $hdr) { + if (strncasecmp($hdr, 'set-cookie:', 11) == 0) { + $cookie = substr($hdr, 12); + @header('lsc-cookie: ' . $cookie, false); } } } @@ -94,8 +98,9 @@ public function check_login_cacheable() { * @access public * @param array $params [wordpress params for widget_posts_args] */ - public function add_widget_recent_posts( $params ) { - self::add( self::TYPE_PAGES_WITH_RECENT_POSTS ); + public function add_widget_recent_posts($params) + { + self::add(self::TYPE_PAGES_WITH_RECENT_POSTS); return $params; } @@ -106,18 +111,19 @@ public function add_widget_recent_posts( $params ) { * @access public * @param mixed $tags A string or array of cache tags to add to the current list. */ - public static function add( $tags ) { - if ( ! is_array( $tags ) ) { - $tags = array( $tags ); + public static function add($tags) + { + if (!is_array($tags)) { + $tags = array($tags); } - Debug2::debug( '💰 [Tag] Add ', $tags ); + Debug2::debug('💰 [Tag] Add ', $tags); - self::$_tags = array_merge( self::$_tags, $tags ); + self::$_tags = array_merge(self::$_tags, $tags); // Send purge header immediately - $tag_header = self::cls()->output( true ); - @header( $tag_header ); + $tag_header = self::cls()->output(true); + @header($tag_header); } /** @@ -126,8 +132,9 @@ public static function add( $tags ) { * @since 3.0 * @access public */ - public static function add_post( $pid ) { - self::add( self::TYPE_POST . $pid ); + public static function add_post($pid) + { + self::add(self::TYPE_POST . $pid); } /** @@ -136,8 +143,9 @@ public static function add_post( $pid ) { * @since 3.0 * @access public */ - public static function add_widget( $id ) { - self::add( self::TYPE_WIDGET . $id ); + public static function add_widget($id) + { + self::add(self::TYPE_WIDGET . $id); } /** @@ -146,8 +154,9 @@ public static function add_widget( $id ) { * @since 3.0 * @access public */ - public static function add_private_esi( $tag ) { - self::add_private( self::TYPE_ESI . $tag ); + public static function add_private_esi($tag) + { + self::add_private(self::TYPE_ESI . $tag); } /** @@ -157,12 +166,13 @@ public static function add_private_esi( $tag ) { * @access public * @param mixed $tags A string or array of cache tags to add to the current list. */ - public static function add_private( $tags ) { - if ( ! is_array( $tags ) ) { - $tags = array( $tags ); + public static function add_private($tags) + { + if (!is_array($tags)) { + $tags = array($tags); } - self::$_tags_priv = array_merge( self::$_tags_priv, $tags ); + self::$_tags_priv = array_merge(self::$_tags_priv, $tags); } /** @@ -171,7 +181,8 @@ public static function add_private( $tags ) { * @since 1.1.3 * @access public */ - public static function output_tags() { + public static function output_tags() + { return self::$_tags; } @@ -184,22 +195,23 @@ public static function output_tags() { * @param boolean $ori Return the original url or not * @return bool|string False on input error, hash otherwise. */ - public static function get_uri_tag( $uri, $ori = false ) { - $no_qs = strtok( $uri, '?' ); - if ( empty( $no_qs ) ) { + public static function get_uri_tag($uri, $ori = false) + { + $no_qs = strtok($uri, '?'); + if (empty($no_qs)) { return false; } - $slashed = trailingslashit( $no_qs ); + $slashed = trailingslashit($no_qs); // If only needs uri tag - if ( $ori ) { + if ($ori) { return $slashed; } - if ( defined( 'LSCWP_LOG' ) ) { + if (defined('LSCWP_LOG')) { return self::TYPE_URL . $slashed; } - return self::TYPE_URL . md5( $slashed ); + return self::TYPE_URL . md5($slashed); } /** @@ -209,8 +221,9 @@ public static function get_uri_tag( $uri, $ori = false ) { * @access public * @param boolean $ori Return the original url or not */ - public static function build_uri_tag( $ori = false ) { - return self::get_uri_tag( urldecode( $_SERVER['REQUEST_URI'] ), $ori ); + public static function build_uri_tag($ori = false) + { + return self::get_uri_tag(urldecode($_SERVER['REQUEST_URI']), $ori); } /** @@ -223,84 +236,77 @@ public static function build_uri_tag( $ori = false ) { * @access private * @return array The list of cache tags to set. */ - private static function _build_type_tags() { + private static function _build_type_tags() + { $tags = array(); $tags[] = Utility::page_type(); $tags[] = self::build_uri_tag(); - if ( is_front_page() ) { + if (is_front_page()) { $tags[] = self::TYPE_FRONTPAGE; - } - elseif ( is_home() ) { + } elseif (is_home()) { $tags[] = self::TYPE_HOME; } - $queried_obj_id = get_queried_object_id(); - if ( is_archive() ) { - //An Archive is a Category, Tag, Author, Date, Custom Post Type or Custom Taxonomy based pages. - if ( is_category() || is_tag() || is_tax() ) { - $tags[] = self::TYPE_ARCHIVE_TERM . $queried_obj_id; - } - elseif ( is_post_type_archive() ) { - global $wp_query; - $post_type = $wp_query->get( 'post_type' ); - $tags[] = self::TYPE_ARCHIVE_POSTTYPE . $post_type; - } - elseif ( is_author() ) { - $tags[] = self::TYPE_AUTHOR . $queried_obj_id; - } - elseif ( is_date() ) { - global $post; - $date = $post->post_date; - $date = strtotime( $date ); - if ( is_day() ) { - $tags[] = self::TYPE_ARCHIVE_DATE . date( 'Ymd', $date ); - } - elseif ( is_month() ) { - $tags[] = self::TYPE_ARCHIVE_DATE . date( 'Ym', $date ); + global $wp_query; + if (isset($wp_query)) { + $queried_obj_id = get_queried_object_id(); + if (is_archive()) { + //An Archive is a Category, Tag, Author, Date, Custom Post Type or Custom Taxonomy based pages. + if (is_category() || is_tag() || is_tax()) { + $tags[] = self::TYPE_ARCHIVE_TERM . $queried_obj_id; + } elseif (is_post_type_archive() && ($post_type = get_post_type())) { + $tags[] = self::TYPE_ARCHIVE_POSTTYPE . $post_type; + } elseif (is_author()) { + $tags[] = self::TYPE_AUTHOR . $queried_obj_id; + } elseif (is_date()) { + global $post; + $date = $post->post_date; + $date = strtotime($date); + if (is_day()) { + $tags[] = self::TYPE_ARCHIVE_DATE . date('Ymd', $date); + } elseif (is_month()) { + $tags[] = self::TYPE_ARCHIVE_DATE . date('Ym', $date); + } elseif (is_year()) { + $tags[] = self::TYPE_ARCHIVE_DATE . date('Y', $date); + } } - elseif ( is_year() ) { - $tags[] = self::TYPE_ARCHIVE_DATE . date( 'Y', $date ); - } - } - } - elseif ( is_singular() ) { - //$this->is_singular = $this->is_single || $this->is_page || $this->is_attachment; - $tags[] = self::TYPE_POST . $queried_obj_id; + } elseif (is_singular()) { + //$this->is_singular = $this->is_single || $this->is_page || $this->is_attachment; + $tags[] = self::TYPE_POST . $queried_obj_id; - if ( is_page() ) { - $tags[] = self::TYPE_PAGES; + if (is_page()) { + $tags[] = self::TYPE_PAGES; + } + } elseif (is_feed()) { + $tags[] = self::TYPE_FEED; } } - elseif ( is_feed() ) { - $tags[] = self::TYPE_FEED; - } // Check REST API - if ( REST::cls()->is_rest() ) { + if (REST::cls()->is_rest()) { $tags[] = self::TYPE_REST; - $path = ! empty( $_SERVER[ 'SCRIPT_URL' ] ) ? $_SERVER[ 'SCRIPT_URL' ] : false; - if ( $path ) { + $path = !empty($_SERVER['SCRIPT_URL']) ? $_SERVER['SCRIPT_URL'] : false; + if ($path) { // posts collections tag - if ( substr( $path, -6 ) == '/posts' ) { - $tags[] = self::TYPE_LIST;// Not used for purge yet + if (substr($path, -6) == '/posts') { + $tags[] = self::TYPE_LIST; // Not used for purge yet } // single post tag global $post; - if ( ! empty( $post->ID ) && substr( $path, - strlen( $post->ID ) - 1 ) === '/' . $post->ID ) { + if (!empty($post->ID) && substr($path, -strlen($post->ID) - 1) === '/' . $post->ID) { $tags[] = self::TYPE_POST . $post->ID; } // pages collections & single page tag - if ( stripos( $path, '/pages' ) !== false ) { + if (stripos($path, '/pages') !== false) { $tags[] = self::TYPE_PAGES; } } - } return $tags; @@ -312,23 +318,24 @@ private static function _build_type_tags() { * @access private * @since 1.1.3 */ - private static function _finalize() { + private static function _finalize() + { // run 3rdparty hooks to tag - do_action( 'litespeed_tag_finalize' ); + do_action('litespeed_tag_finalize'); // generate wp tags - if ( ! defined( 'LSCACHE_IS_ESI' ) ) { + if (!defined('LSCACHE_IS_ESI')) { $type_tags = self::_build_type_tags(); - self::$_tags = array_merge( self::$_tags, $type_tags ); + self::$_tags = array_merge(self::$_tags, $type_tags); } - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST ) { + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { self::$_tags[] = 'guest'; } // append blog main tag self::$_tags[] = ''; // removed duplicates - self::$_tags = array_unique( self::$_tags ); + self::$_tags = array_unique(self::$_tags); } /** @@ -339,12 +346,13 @@ private static function _finalize() { * @access public * @return string empty string if empty, otherwise the cache tags header. */ - public function output( $no_finalize = false ) { - if ( defined( 'LSCACHE_NO_CACHE' ) && LSCACHE_NO_CACHE ) { + public function output($no_finalize = false) + { + if (defined('LSCACHE_NO_CACHE') && LSCACHE_NO_CACHE) { return; } - if ( ! $no_finalize ) { + if (!$no_finalize) { self::_finalize(); } @@ -353,23 +361,22 @@ public function output( $no_finalize = false ) { * Only append blog_id when is multisite * @since 2.9.3 */ - $prefix = LSWCP_TAG_PREFIX . ( is_multisite() ? get_current_blog_id() : '' ) . '_'; + $prefix = LSWCP_TAG_PREFIX . (is_multisite() ? get_current_blog_id() : '') . '_'; // If is_private and has private tags, append them first, then specify prefix to `public` for public tags - if ( Control::is_private() ) { - foreach ( self::$_tags_priv as $priv_tag ) { + if (Control::is_private()) { + foreach (self::$_tags_priv as $priv_tag) { $prefix_tags[] = $prefix . $priv_tag; } $prefix = 'public:' . $prefix; } - foreach ( self::$_tags as $tag ) { + foreach (self::$_tags as $tag) { $prefix_tags[] = $prefix . $tag; } - $hdr = self::X_HEADER . ': ' . implode( ',', $prefix_tags ); + $hdr = self::X_HEADER . ': ' . implode(',', $prefix_tags); return $hdr; } - -} \ No newline at end of file +} diff --git a/src/task.cls.php b/src/task.cls.php index 079178fc3..55d10504f 100644 --- a/src/task.cls.php +++ b/src/task.cls.php @@ -1,31 +1,31 @@ array( 'name' => 'litespeed_task_imgoptm_pull', 'hook' => 'LiteSpeed\Img_Optm::cron_pull' ), // always fetch immediately - Base::O_OPTM_CSS_ASYNC => array( 'name' => 'litespeed_task_ccss', 'hook' => 'LiteSpeed\CSS::cron_ccss' ), - Base::O_OPTM_UCSS => array( 'name' => 'litespeed_task_ucss', 'hook' => 'LiteSpeed\UCSS::cron' ), - Base::O_MEDIA_VPI_CRON => array( 'name' => 'litespeed_task_vpi', 'hook' => 'LiteSpeed\VPI::cron' ), - Base::O_MEDIA_PLACEHOLDER_RESP_ASYNC => array( 'name' => 'litespeed_task_lqip', 'hook' => 'LiteSpeed\Placeholder::cron' ), - Base::O_DISCUSS_AVATAR_CRON => array( 'name' => 'litespeed_task_avatar', 'hook' => 'LiteSpeed\Avatar::cron' ), - Base::O_IMG_OPTM_AUTO => array( 'name' => 'litespeed_task_imgoptm_req', 'hook' => 'LiteSpeed\Img_Optm::cron_auto_request' ), - Base::O_CRAWLER => array( 'name' => 'litespeed_task_crawler', 'hook' => 'LiteSpeed\Crawler::start' ), // Set crawler to last one to use above results + Base::O_IMG_OPTM_CRON => array('name' => 'litespeed_task_imgoptm_pull', 'hook' => 'LiteSpeed\Img_Optm::start_async_cron'), // always fetch immediately + Base::O_OPTM_CSS_ASYNC => array('name' => 'litespeed_task_ccss', 'hook' => 'LiteSpeed\CSS::cron_ccss'), + Base::O_OPTM_UCSS => array('name' => 'litespeed_task_ucss', 'hook' => 'LiteSpeed\UCSS::cron'), + Base::O_MEDIA_VPI_CRON => array('name' => 'litespeed_task_vpi', 'hook' => 'LiteSpeed\VPI::cron'), + Base::O_MEDIA_PLACEHOLDER_RESP_ASYNC => array('name' => 'litespeed_task_lqip', 'hook' => 'LiteSpeed\Placeholder::cron'), + Base::O_DISCUSS_AVATAR_CRON => array('name' => 'litespeed_task_avatar', 'hook' => 'LiteSpeed\Avatar::cron'), + Base::O_IMG_OPTM_AUTO => array('name' => 'litespeed_task_imgoptm_req', 'hook' => 'LiteSpeed\Img_Optm::cron_auto_request'), + Base::O_CRAWLER => array('name' => 'litespeed_task_crawler', 'hook' => 'LiteSpeed\Crawler::start_async_cron'), // Set crawler to last one to use above results ); - private static $_guest_options = array( - Base::O_OPTM_CSS_ASYNC, - Base::O_OPTM_UCSS, - Base::O_MEDIA_VPI, - ); + private static $_guest_options = array(Base::O_OPTM_CSS_ASYNC, Base::O_OPTM_UCSS, Base::O_MEDIA_VPI); const FITLER_CRAWLER = 'litespeed_crawl_filter'; const FITLER = 'litespeed_filter'; @@ -36,38 +36,90 @@ class Task extends Root { * @since 3.0 * @access public */ - public function init() { - Debug2::debug2( '⏰ Task init' ); - - add_filter( 'cron_schedules', array( $this, 'lscache_cron_filter' ) ); + public function init() + { + self::debug2('Init'); + add_filter('cron_schedules', array($this, 'lscache_cron_filter')); - $guest_optm = $this->conf( Base::O_GUEST ) && $this->conf( Base::O_GUEST_OPTM ); + $guest_optm = $this->conf(Base::O_GUEST) && $this->conf(Base::O_GUEST_OPTM); - foreach ( self::$_triggers as $id => $trigger ) { - if ( ! $this->conf( $id ) ) { - if ( ! $guest_optm || ! in_array( $id, self::$_guest_options ) ) { + foreach (self::$_triggers as $id => $trigger) { + if (!$this->conf($id)) { + if (!$guest_optm || !in_array($id, self::$_guest_options)) { continue; } } // Special check for crawler - if ( $id == Base::O_CRAWLER ) { - if ( ! Router::can_crawl() ) { + if ($id == Base::O_CRAWLER) { + if (!Router::can_crawl()) { continue; } - add_filter( 'cron_schedules', array( $this, 'lscache_cron_filter_crawler' ) ); + add_filter('cron_schedules', array($this, 'lscache_cron_filter_crawler')); } - if( ! wp_next_scheduled( $trigger[ 'name' ] ) ) { - Debug2::debug( '⏰ Cron hook register [name] ' . $trigger[ 'name' ] ); + if (!wp_next_scheduled($trigger['name'])) { + self::debug('Cron hook register [name] ' . $trigger['name']); - wp_schedule_event( time(), $id == Base::O_CRAWLER ? self::FITLER_CRAWLER : self::FITLER, $trigger[ 'name' ] ); + wp_schedule_event(time(), $id == Base::O_CRAWLER ? self::FITLER_CRAWLER : self::FITLER, $trigger['name']); } - add_action( $trigger[ 'name' ], $trigger[ 'hook' ] ); + add_action($trigger['name'], $trigger['hook']); } + } + /** + * Handle all async noabort requests + * + * @since 5.5 + */ + public static function async_litespeed_handler() + { + $type = Router::verify_type(); + + self::debug('type=' . $type); + + // Don't lock up other requests while processing + session_write_close(); + switch ($type) { + case 'crawler': + Crawler::async_handler(); + break; + case 'crawler_force': + Crawler::async_handler(true); + break; + case 'imgoptm': + Img_Optm::async_handler(); + break; + case 'imgoptm_force': + Img_Optm::async_handler(true); + break; + default: + } + } + + /** + * Async caller wrapper func + * + * @since 5.5 + */ + public static function async_call($type) + { + $args = array( + 'timeout' => 0.01, + 'blocking' => false, + 'sslverify' => false, + // 'cookies' => $_COOKIE, + ); + $qs = array( + 'action' => 'async_litespeed', + 'nonce' => wp_create_nonce('async_litespeed'), + Router::TYPE => $type, + ); + $url = add_query_arg($qs, admin_url('admin-ajax.php')); + self::debug('async call to ' . $url); + wp_remote_post(esc_url_raw($url), $args); } /** @@ -76,9 +128,10 @@ public function init() { * @since 3.0 * @access public */ - public static function destroy() { + public static function destroy() + { Utility::compatibility(); - array_map( 'wp_clear_scheduled_hook', array_column( self::$_triggers, 'name' ) ); + array_map('wp_clear_scheduled_hook', array_column(self::$_triggers, 'name')); } /** @@ -87,26 +140,27 @@ public static function destroy() { * @since 3.0 * @access public */ - public function try_clean( $id ) { + public function try_clean($id) + { // Clean v2's leftover cron ( will remove in v3.1 ) // foreach ( wp_get_ready_cron_jobs() as $hooks ) { // foreach ( $hooks as $hook => $v ) { // if ( strpos( $hook, 'litespeed_' ) === 0 && ( substr( $hook, -8 ) === '_trigger' || strpos( $hook, 'litespeed_task_' ) !== 0 ) ) { - // Debug2::debug( '⏰ Cron clear legacy [hook] ' . $hook ); + // self::debug( 'Cron clear legacy [hook] ' . $hook ); // wp_clear_scheduled_hook( $hook ); // } // } // } - if ( $id && ! empty( self::$_triggers[ $id ] ) ) { - if ( ! $this->conf( $id ) || ( $id == Base::O_CRAWLER && ! Router::can_crawl() ) ) { - Debug2::debug( '⏰ Cron clear [id] ' . $id . ' [hook] ' . self::$_triggers[ $id ][ 'name' ] ); - wp_clear_scheduled_hook( self::$_triggers[ $id ][ 'name' ] ); + if ($id && !empty(self::$_triggers[$id])) { + if (!$this->conf($id) || ($id == Base::O_CRAWLER && !Router::can_crawl())) { + self::debug('Cron clear [id] ' . $id . ' [hook] ' . self::$_triggers[$id]['name']); + wp_clear_scheduled_hook(self::$_triggers[$id]['name']); } return; } - Debug2::debug( '⏰ ❌ Unknown cron [id] ' . $id ); + self::debug('❌ Unknown cron [id] ' . $id); } /** @@ -115,11 +169,12 @@ public function try_clean( $id ) { * @since 1.6.1 * @access public */ - public function lscache_cron_filter( $schedules ) { - if ( ! array_key_exists( self::FITLER, $schedules ) ) { - $schedules[ self::FITLER ] = array( + public function lscache_cron_filter($schedules) + { + if (!array_key_exists(self::FITLER, $schedules)) { + $schedules[self::FITLER] = array( 'interval' => 60, - 'display' => __( 'Every Minute', 'litespeed-cache' ), + 'display' => __('Every Minute', 'litespeed-cache'), ); } return $schedules; @@ -131,17 +186,17 @@ public function lscache_cron_filter( $schedules ) { * @since 1.1.0 * @access public */ - public function lscache_cron_filter_crawler( $schedules ) { - $interval = $this->conf( Base::O_CRAWLER_RUN_INTERVAL ); + public function lscache_cron_filter_crawler($schedules) + { + $interval = $this->conf(Base::O_CRAWLER_RUN_INTERVAL); // $wp_schedules = wp_get_schedules(); - if ( ! array_key_exists( self::FITLER_CRAWLER, $schedules ) ) { - // Debug2::debug('Crawler cron log: cron filter '.$interval.' added'); - $schedules[ self::FITLER_CRAWLER ] = array( + if (!array_key_exists(self::FITLER_CRAWLER, $schedules)) { + // self::debug('Crawler cron log: cron filter '.$interval.' added'); + $schedules[self::FITLER_CRAWLER] = array( 'interval' => $interval, - 'display' => __( 'LiteSpeed Crawler Cron', 'litespeed-cache' ), + 'display' => __('LiteSpeed Crawler Cron', 'litespeed-cache'), ); } return $schedules; } - -} \ No newline at end of file +} diff --git a/src/tool.cls.php b/src/tool.cls.php index b4e863989..aafb1c94a 100644 --- a/src/tool.cls.php +++ b/src/tool.cls.php @@ -9,27 +9,29 @@ */ namespace LiteSpeed; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Tool extends Root { +class Tool extends Root +{ /** * Get public IP * * @since 3.0 * @access public */ - public function check_ip() { - Debug2::debug( '[Tool] ✅ check_ip' ); + public function check_ip() + { + Debug2::debug('[Tool] ✅ check_ip'); - $response = wp_remote_get( 'https://www.doapi.us/ip' ); + $response = wp_remote_get('https://www.doapi.us/ip'); - if ( is_wp_error( $response ) ) { - return new \WP_Error( 'remote_get_fail', 'Failed to fetch from https://www.doapi.us/ip', array( 'status' => 404 ) ); + if (is_wp_error($response)) { + return new \WP_Error('remote_get_fail', 'Failed to fetch from https://www.doapi.us/ip', array('status' => 404)); } - $data = $response[ 'body' ]; + $data = $response['body']; - Debug2::debug( '[Tool] result [ip] ' . $data ); + Debug2::debug('[Tool] result [ip] ' . $data); return $data; } @@ -42,10 +44,11 @@ public function check_ip() { * @since 3.0 * @access public */ - public function heartbeat() { - add_action( 'wp_enqueue_scripts', array( $this, 'heartbeat_frontend' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'heartbeat_backend' ) ); - add_filter( 'heartbeat_settings', array( $this, 'heartbeat_settings' ) ); + public function heartbeat() + { + add_action('wp_enqueue_scripts', array($this, 'heartbeat_frontend')); + add_action('admin_enqueue_scripts', array($this, 'heartbeat_backend')); + add_filter('heartbeat_settings', array($this, 'heartbeat_settings')); } /** @@ -54,14 +57,15 @@ public function heartbeat() { * @since 3.0 * @access public */ - public function heartbeat_frontend() { - if ( ! $this->conf( Base::O_MISC_HEARTBEAT_FRONT ) ) { + public function heartbeat_frontend() + { + if (!$this->conf(Base::O_MISC_HEARTBEAT_FRONT)) { return; } - if ( ! $this->conf( Base::O_MISC_HEARTBEAT_FRONT_TTL ) ) { - wp_deregister_script( 'heartbeat' ); - Debug2::debug( '[Tool] Deregistered frontend heartbeat' ); + if (!$this->conf(Base::O_MISC_HEARTBEAT_FRONT_TTL)) { + wp_deregister_script('heartbeat'); + Debug2::debug('[Tool] Deregistered frontend heartbeat'); } } @@ -71,28 +75,27 @@ public function heartbeat_frontend() { * @since 3.0 * @access public */ - public function heartbeat_backend() { - if ( $this->_is_editor() ) { - if ( ! $this->conf( Base::O_MISC_HEARTBEAT_EDITOR ) ) { + public function heartbeat_backend() + { + if ($this->_is_editor()) { + if (!$this->conf(Base::O_MISC_HEARTBEAT_EDITOR)) { return; } - if ( ! $this->conf( Base::O_MISC_HEARTBEAT_EDITOR_TTL ) ) { - wp_deregister_script( 'heartbeat' ); - Debug2::debug( '[Tool] Deregistered editor heartbeat' ); + if (!$this->conf(Base::O_MISC_HEARTBEAT_EDITOR_TTL)) { + wp_deregister_script('heartbeat'); + Debug2::debug('[Tool] Deregistered editor heartbeat'); } - } - else { - if ( ! $this->conf( Base::O_MISC_HEARTBEAT_BACK ) ) { + } else { + if (!$this->conf(Base::O_MISC_HEARTBEAT_BACK)) { return; } - if ( ! $this->conf( Base::O_MISC_HEARTBEAT_BACK_TTL ) ) { - wp_deregister_script( 'heartbeat' ); - Debug2::debug( '[Tool] Deregistered backend heartbeat' ); + if (!$this->conf(Base::O_MISC_HEARTBEAT_BACK_TTL)) { + wp_deregister_script('heartbeat'); + Debug2::debug('[Tool] Deregistered backend heartbeat'); } } - } /** @@ -101,24 +104,23 @@ public function heartbeat_backend() { * @since 3.0 * @access public */ - public function heartbeat_settings( $settings ) { + public function heartbeat_settings($settings) + { // Check editor first to make frontend editor valid too - if ( $this->_is_editor() ) { - if ( $this->conf( Base::O_MISC_HEARTBEAT_EDITOR ) ) { - $settings[ 'interval' ] = $this->conf( Base::O_MISC_HEARTBEAT_EDITOR_TTL ); - Debug2::debug( '[Tool] Heartbeat interval set to ' . $this->conf( Base::O_MISC_HEARTBEAT_EDITOR_TTL ) ); + if ($this->_is_editor()) { + if ($this->conf(Base::O_MISC_HEARTBEAT_EDITOR)) { + $settings['interval'] = $this->conf(Base::O_MISC_HEARTBEAT_EDITOR_TTL); + Debug2::debug('[Tool] Heartbeat interval set to ' . $this->conf(Base::O_MISC_HEARTBEAT_EDITOR_TTL)); } - } - elseif ( ! is_admin() ) { - if ( $this->conf( Base::O_MISC_HEARTBEAT_FRONT ) ) { - $settings[ 'interval' ] = $this->conf( Base::O_MISC_HEARTBEAT_FRONT_TTL ); - Debug2::debug( '[Tool] Heartbeat interval set to ' . $this->conf( Base::O_MISC_HEARTBEAT_FRONT_TTL ) ); + } elseif (!is_admin()) { + if ($this->conf(Base::O_MISC_HEARTBEAT_FRONT)) { + $settings['interval'] = $this->conf(Base::O_MISC_HEARTBEAT_FRONT_TTL); + Debug2::debug('[Tool] Heartbeat interval set to ' . $this->conf(Base::O_MISC_HEARTBEAT_FRONT_TTL)); } - } - else { - if ( $this->conf( Base::O_MISC_HEARTBEAT_BACK ) ) { - $settings[ 'interval' ] = $this->conf( Base::O_MISC_HEARTBEAT_BACK_TTL ); - Debug2::debug( '[Tool] Heartbeat interval set to ' . $this->conf( Base::O_MISC_HEARTBEAT_BACK_TTL ) ); + } else { + if ($this->conf(Base::O_MISC_HEARTBEAT_BACK)) { + $settings['interval'] = $this->conf(Base::O_MISC_HEARTBEAT_BACK_TTL); + Debug2::debug('[Tool] Heartbeat interval set to ' . $this->conf(Base::O_MISC_HEARTBEAT_BACK_TTL)); } } return $settings; @@ -130,10 +132,10 @@ public function heartbeat_settings( $settings ) { * @since 3.0 * @access public */ - private function _is_editor() { - $res = is_admin() && Utility::str_hit_array( $_SERVER[ 'REQUEST_URI' ], array( 'post.php', 'post-new.php' ) ); + private function _is_editor() + { + $res = is_admin() && Utility::str_hit_array($_SERVER['REQUEST_URI'], array('post.php', 'post-new.php')); - return apply_filters( 'litespeed_is_editor', $res ); + return apply_filters('litespeed_is_editor', $res); } - -} \ No newline at end of file +} diff --git a/src/ucss.cls.php b/src/ucss.cls.php index 516838932..4118f6a5a 100644 --- a/src/ucss.cls.php +++ b/src/ucss.cls.php @@ -1,13 +1,17 @@ _summary = self::get_summary(); - add_filter( 'litespeed_ucss_whitelist', array( $this->cls( 'Data' ), 'load_ucss_whitelist' ) ); + add_filter('litespeed_ucss_whitelist', array($this->cls('Data'), 'load_ucss_whitelist')); } /** * Uniform url tag for ucss usage * @since 4.7 */ - public static function get_url_tag( $request_url = false ) { + public static function get_url_tag($request_url = false) + { $url_tag = $request_url; - if ( is_404() ) { + if (is_404()) { $url_tag = '404'; - } - elseif ( apply_filters( 'litespeed_ucss_per_pagetype', false ) ) { + } elseif (apply_filters('litespeed_ucss_per_pagetype', false)) { $url_tag = Utility::page_type(); - self::debug( 'litespeed_ucss_per_pagetype filter altered url to ' . $url_tag ); + self::debug('litespeed_ucss_per_pagetype filter altered url to ' . $url_tag); } return $url_tag; @@ -50,67 +55,74 @@ public static function get_url_tag( $request_url = false ) { * * @since 4.0 */ - public function load( $request_url, $dry_run = false ) { + public function load($request_url, $dry_run = false) + { // Check UCSS URI excludes - $ucss_exc = apply_filters( 'litespeed_ucss_exc', $this->conf( self::O_OPTM_UCSS_EXC ) ); - if ( $ucss_exc && $hit = Utility::str_hit_array( $request_url, $ucss_exc ) ) { - self::debug( 'UCSS bypassed due to UCSS URI Exclude setting: ' . $hit ); + $ucss_exc = apply_filters('litespeed_ucss_exc', $this->conf(self::O_OPTM_UCSS_EXC)); + if ($ucss_exc && ($hit = Utility::str_hit_array($request_url, $ucss_exc))) { + self::debug('UCSS bypassed due to UCSS URI Exclude setting: ' . $hit); + Core::comment('QUIC.cloud UCSS bypassed by setting'); return false; } - $filepath_prefix = $this->_build_filepath_prefix( 'ucss' ); + $filepath_prefix = $this->_build_filepath_prefix('ucss'); - $url_tag = self::get_url_tag( $request_url ); + $url_tag = self::get_url_tag($request_url); - $vary = $this->cls( 'Vary' )->finalize_full_varies(); - $filename = $this->cls( 'Data' )->load_url_file( $url_tag, $vary, 'ucss' ); - if ( $filename ) { + $vary = $this->cls('Vary')->finalize_full_varies(); + $filename = $this->cls('Data')->load_url_file($url_tag, $vary, 'ucss'); + if ($filename) { $static_file = LITESPEED_STATIC_DIR . $filepath_prefix . $filename . '.css'; - if ( file_exists( $static_file ) ) { - self::debug2( 'existing ucss ' . $static_file ); + if (file_exists($static_file)) { + self::debug2('existing ucss ' . $static_file); // Check if is error comment inside only - $tmp = File::read( $static_file ); - if ( substr( $tmp, 0, 2 ) == '/*' && substr( $tmp, -2 ) == '*/' ) { - self::debug2( 'existing ucss is error only: ' . $tmp ); + $tmp = File::read($static_file); + if (substr($tmp, 0, 2) == '/*' && substr(trim($tmp), -2) == '*/') { + self::debug2('existing ucss is error only: ' . $tmp); + Core::comment('QUIC.cloud UCSS bypassed due to generation error ❌ ' . $filepath_prefix . $filename . '.css'); return false; } + Core::comment('QUIC.cloud UCSS loaded ✅'); + return $filename . '.css'; } } - if ( $dry_run ) { + if ($dry_run) { return false; } + Core::comment('QUIC.cloud UCSS in queue'); + $uid = get_current_user_id(); $ua = $this->_get_ua(); // Store it for cron - $this->_queue = $this->load_queue( 'ucss' ); + $this->_queue = $this->load_queue('ucss'); - if ( count( $this->_queue ) > 500 ) { - self::debug( 'UCSS Queue is full - 500' ); + if (count($this->_queue) > 500) { + self::debug('UCSS Queue is full - 500'); return false; } - $queue_k = ( strlen( $vary ) > 32 ? md5( $vary ) : $vary ) . ' ' . $url_tag; - $this->_queue[ $queue_k ] = array( - 'url' => apply_filters( 'litespeed_ucss_url', $request_url ), - 'user_agent' => substr( $ua, 0, 200 ), - 'is_mobile' => $this->_separate_mobile(), - 'is_webp' => $this->cls( 'Media' )->webp_support() ? 1 : 0, - 'uid' => $uid, - 'vary' => $vary, - 'url_tag' => $url_tag, + $queue_k = (strlen($vary) > 32 ? md5($vary) : $vary) . ' ' . $url_tag; + $this->_queue[$queue_k] = array( + 'url' => apply_filters('litespeed_ucss_url', $request_url), + 'user_agent' => substr($ua, 0, 200), + 'is_mobile' => $this->_separate_mobile(), + 'is_webp' => $this->cls('Media')->webp_support() ? 1 : 0, + 'uid' => $uid, + 'vary' => $vary, + 'url_tag' => $url_tag, ); // Current UA will be used to request - $this->save_queue( 'ucss', $this->_queue ); - self::debug( 'Added queue_ucss [url_tag] ' . $url_tag . ' [UA] ' . $ua . ' [vary] ' . $vary . ' [uid] ' . $uid ); + $this->save_queue('ucss', $this->_queue); + self::debug('Added queue_ucss [url_tag] ' . $url_tag . ' [UA] ' . $ua . ' [vary] ' . $vary . ' [uid] ' . $uid); // Prepare cache tag for later purge - Tag::add( 'UCSS.' . md5( $queue_k ) ); + Tag::add('UCSS.' . md5($queue_k)); return false; } @@ -120,8 +132,9 @@ public function load( $request_url, $dry_run = false ) { * * @since 5.3 */ - private function _get_ua() { - return ! empty( $_SERVER[ 'HTTP_USER_AGENT' ] ) ? $_SERVER[ 'HTTP_USER_AGENT' ] : ''; + private function _get_ua() + { + return !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; } /** @@ -129,42 +142,39 @@ private function _get_ua() { * * @since 5.3 */ - public function add_to_q($url_files) { - return; // will enable in v5.4 + public function add_to_q($url_files) + { // Store it for cron - $this->_queue = $this->load_queue( 'ucss' ); + $this->_queue = $this->load_queue('ucss'); - if ( count( $this->_queue ) > 500 ) { - self::debug( 'UCSS Queue is full - 500' ); + if (count($this->_queue) > 500) { + self::debug('UCSS Queue is full - 500'); return false; } $ua = $this->_get_ua(); - foreach ( $url_files as $url_file ) { - $vary = $url_file[ 'vary' ]; - $request_url = $url_file[ 'url' ]; - $is_mobile = $url_file[ 'is_mobile' ]; - $is_webp = $url_file[ 'is_webp' ]; - $request_url = $url_file[ 'url' ]; - $url_tag = self::get_url_tag( $request_url ); - - $queue_k = ( strlen( $vary ) > 32 ? md5( $vary ) : $vary ) . ' ' . $url_tag; + foreach ($url_files as $url_file) { + $vary = $url_file['vary']; + $request_url = $url_file['url']; + $is_mobile = $url_file['mobile']; + $is_webp = $url_file['webp']; + $url_tag = self::get_url_tag($request_url); + + $queue_k = (strlen($vary) > 32 ? md5($vary) : $vary) . ' ' . $url_tag; $q = array( - 'url' => apply_filters( 'litespeed_ucss_url', $request_url ), - 'user_agent' => substr( $ua, 0, 200 ), - 'is_mobile' => $is_mobile, - 'is_webp' => $is_webp, - 'uid' => false, - 'vary' => $vary, - 'url_tag' => $url_tag, + 'url' => apply_filters('litespeed_ucss_url', $request_url), + 'user_agent' => substr($ua, 0, 200), + 'is_mobile' => $is_mobile, + 'is_webp' => $is_webp, + 'uid' => false, + 'vary' => $vary, + 'url_tag' => $url_tag, ); // Current UA will be used to request - $this->_queue[ $queue_k ] = $q; + self::debug('Added queue_ucss [url_tag] ' . $url_tag . ' [UA] ' . $ua . ' [vary] ' . $vary . ' [uid] false'); + $this->_queue[$queue_k] = $q; } - $this->save_queue( 'ucss', $this->_queue ); - self::debug( 'Added queue_ucss [url_tag] ' . $url_tag . ' [UA] ' . $ua . ' [vary] ' . $vary . ' [uid] false' ); - - + $this->save_queue('ucss', $this->_queue); } /** @@ -172,9 +182,10 @@ public function add_to_q($url_files) { * * @since 4.0 */ - public static function cron( $continue = false ) { + public static function cron($continue = false) + { $_instance = self::cls(); - return $_instance->_cron_handler( $continue ); + return $_instance->_cron_handler($continue); } /** @@ -182,70 +193,72 @@ public static function cron( $continue = false ) { * * @since 4.2 */ - private function _cron_handler( $continue ) { - $this->_queue = $this->load_queue( 'ucss' ); + private function _cron_handler($continue) + { + $this->_queue = $this->load_queue('ucss'); - if ( empty( $this->_queue ) ) { + if (empty($this->_queue)) { return; } // For cron, need to check request interval too - if ( ! $continue ) { - if ( ! empty( $this->_summary[ 'curr_request' ] ) && time() - $this->_summary[ 'curr_request' ] < 300 && ! $this->conf( self::O_DEBUG ) ) { - self::debug( 'Last request not done' ); + if (!$continue) { + if (!empty($this->_summary['curr_request']) && time() - $this->_summary['curr_request'] < 300 && !$this->conf(self::O_DEBUG)) { + self::debug('Last request not done'); return; } } $i = 0; - foreach ( $this->_queue as $k => $v ) { - if ( ! empty( $v[ '_status' ] ) ) { + foreach ($this->_queue as $k => $v) { + if (!empty($v['_status'])) { continue; } - self::debug( 'cron job [tag] ' . $k . ' [url] ' . $v[ 'url' ] . ( $v[ 'is_mobile' ] ? ' 📱 ' : '' ) . ' [UA] ' . $v[ 'user_agent' ] ); + self::debug('cron job [tag] ' . $k . ' [url] ' . $v['url'] . ($v['is_mobile'] ? ' 📱 ' : '') . ' [UA] ' . $v['user_agent']); - if ( ! isset( $v[ 'is_webp' ] ) ) { - $v[ 'is_webp' ] = false; + if (!isset($v['is_webp'])) { + $v['is_webp'] = false; } - $i ++; - $res = $this->_send_req( $v[ 'url' ], $k, $v[ 'uid' ], $v[ 'user_agent' ], $v[ 'vary' ], $v[ 'url_tag' ], $v[ 'is_mobile' ], $v[ 'is_webp' ] ); - if ( ! $res ) { // Status is wrong, drop this this->_queue - $this->_queue = $this->load_queue( 'ucss' ); - unset( $this->_queue[ $k ] ); - $this->save_queue( 'ucss', $this->_queue ); + $i++; + $res = $this->_send_req($v['url'], $k, $v['uid'], $v['user_agent'], $v['vary'], $v['url_tag'], $v['is_mobile'], $v['is_webp']); + if (!$res) { + // Status is wrong, drop this this->_queue + $this->_queue = $this->load_queue('ucss'); + unset($this->_queue[$k]); + $this->save_queue('ucss', $this->_queue); - if ( ! $continue ) { + if (!$continue) { return; } - if ( $i > 3 ) { - GUI::print_loading( count( $this->_queue ), 'UCSS' ); - return Router::self_redirect( Router::ACTION_UCSS, self::TYPE_GEN ); + if ($i > 3) { + GUI::print_loading(count($this->_queue), 'UCSS'); + return Router::self_redirect(Router::ACTION_UCSS, self::TYPE_GEN); } continue; } // Exit queue if out of quota - if ( $res === 'out_of_quota' ) { + if ($res === 'out_of_quota') { return; } - $this->_queue = $this->load_queue( 'ucss' ); - $this->_queue[ $k ][ '_status' ] = 'requested'; - $this->save_queue( 'ucss', $this->_queue ); - self::debug( 'Saved to queue [k] ' . $k ); + $this->_queue = $this->load_queue('ucss'); + $this->_queue[$k]['_status'] = 'requested'; + $this->save_queue('ucss', $this->_queue); + self::debug('Saved to queue [k] ' . $k); // only request first one - if ( ! $continue ) { + if (!$continue) { return; } - if ( $i > 3 ) { - GUI::print_loading( count( $this->_queue ), 'UCSS' ); - return Router::self_redirect( Router::ACTION_UCSS, self::TYPE_GEN ); + if ($i > 3) { + GUI::print_loading(count($this->_queue), 'UCSS'); + return Router::self_redirect(Router::ACTION_UCSS, self::TYPE_GEN); } } } @@ -256,70 +269,71 @@ private function _cron_handler( $continue ) { * @since 2.3 * @access private */ - private function _send_req( $request_url, $queue_k, $uid, $user_agent, $vary, $url_tag, $is_mobile, $is_webp ) { + private function _send_req($request_url, $queue_k, $uid, $user_agent, $vary, $url_tag, $is_mobile, $is_webp) + { // Check if has credit to push or not $err = false; - $allowance = $this->cls( 'Cloud' )->allowance( Cloud::SVC_UCSS, $err ); - if ( ! $allowance ) { - self::debug( '❌ No credit: ' . $err ); - $err && Admin_Display::error( Error::msg( $err ) ); + $allowance = $this->cls('Cloud')->allowance(Cloud::SVC_UCSS, $err); + if (!$allowance) { + self::debug('❌ No credit: ' . $err); + $err && Admin_Display::error(Error::msg($err)); return 'out_of_quota'; } - set_time_limit( 120 ); + set_time_limit(120); // Update css request status - $this->_summary[ 'curr_request' ] = time(); + $this->_summary['curr_request'] = time(); self::save_summary(); // Gather guest HTML to send - $html = $this->cls('CSS')->prepare_html( $request_url, $user_agent, $uid ); + $html = $this->cls('CSS')->prepare_html($request_url, $user_agent, $uid); - if ( ! $html ) { + if (!$html) { return false; } // Parse HTML to gather all CSS content before requesting $css = false; - list( , $html ) = $this->prepare_css( $html, $is_webp, true ); // Use this to drop CSS from HTML as we don't need those CSS to generate UCSS - $filename = $this->cls( 'Data' )->load_url_file( $url_tag, $vary, 'css' ); - $filepath_prefix = $this->_build_filepath_prefix( 'css' ); + list(, $html) = $this->prepare_css($html, $is_webp, true); // Use this to drop CSS from HTML as we don't need those CSS to generate UCSS + $filename = $this->cls('Data')->load_url_file($url_tag, $vary, 'css'); + $filepath_prefix = $this->_build_filepath_prefix('css'); $static_file = LITESPEED_STATIC_DIR . $filepath_prefix . $filename . '.css'; - self::debug( 'Checking combined file ' . $static_file ); - if ( file_exists( $static_file ) ) { - $css = File::read( $static_file ); + self::debug('Checking combined file ' . $static_file); + if (file_exists($static_file)) { + $css = File::read($static_file); } - if ( ! $css ) { - self::debug( '❌ No combined css' ); + if (!$css) { + self::debug('❌ No combined css'); return false; } $data = array( - 'url' => $request_url, - 'queue_k' => $queue_k, - 'user_agent' => $user_agent, - 'is_mobile' => $is_mobile ? 1 : 0, // todo:compatible w/ tablet - 'is_webp' => $is_webp ? 1 : 0, - 'html' => $html, - 'css' => $css, + 'url' => $request_url, + 'queue_k' => $queue_k, + 'user_agent' => $user_agent, + 'is_mobile' => $is_mobile ? 1 : 0, // todo:compatible w/ tablet + 'is_webp' => $is_webp ? 1 : 0, + 'html' => $html, + 'css' => $css, ); - if ( ! isset( $this->_ucss_whitelist ) ) { + if (!isset($this->_ucss_whitelist)) { $this->_ucss_whitelist = $this->_filter_whitelist(); } - $data[ 'whitelist' ] = $this->_ucss_whitelist; + $data['whitelist'] = $this->_ucss_whitelist; - self::debug( 'Generating: ', $data ); + self::debug('Generating: ', $data); - $json = Cloud::post( Cloud::SVC_UCSS, $data, 30 ); - if ( ! is_array( $json ) ) { + $json = Cloud::post(Cloud::SVC_UCSS, $data, 30); + if (!is_array($json)) { return false; } // Old version compatibility - if ( empty( $json[ 'status' ] ) ) { - if ( ! empty( $json[ 'ucss' ] ) ) { - $this->_save_con( 'ucss', $json[ 'ucss' ], $queue_k, $is_mobile, $is_webp ); + if (empty($json['status'])) { + if (!empty($json['ucss'])) { + $this->_save_con('ucss', $json['ucss'], $queue_k, $is_mobile, $is_webp); } // Delete the row @@ -327,14 +341,14 @@ private function _send_req( $request_url, $queue_k, $uid, $user_agent, $vary, $u } // Unknown status, remove this line - if ( $json[ 'status' ] != 'queued' ) { + if ($json['status'] != 'queued') { return false; } // Save summary data - $this->_summary[ 'last_spent' ] = time() - $this->_summary[ 'curr_request' ]; - $this->_summary[ 'last_request' ] = $this->_summary[ 'curr_request' ]; - $this->_summary[ 'curr_request' ] = 0; + $this->_summary['last_spent'] = time() - $this->_summary['curr_request']; + $this->_summary['last_request'] = $this->_summary['curr_request']; + $this->_summary['curr_request'] = 0; self::save_summary(); return true; @@ -345,31 +359,32 @@ private function _send_req( $request_url, $queue_k, $uid, $user_agent, $vary, $u * * @since 4.2 */ - private function _save_con( $type, $css, $queue_k, $is_mobile, $is_webp ) { + private function _save_con($type, $css, $queue_k, $is_mobile, $is_webp) + { // Add filters - $css = apply_filters( 'litespeed_' . $type, $css, $queue_k ); - self::debug2( 'con: ', $css ); + $css = apply_filters('litespeed_' . $type, $css, $queue_k); + self::debug2('con: ', $css); - if ( substr( $css, 0, 2 ) == '/*' && substr( $css, -2 ) == '*/' ) { - self::debug( '❌ empty ' . $type . ' [content] ' . $css ); + if (substr($css, 0, 2) == '/*' && substr($css, -2) == '*/') { + self::debug('❌ empty ' . $type . ' [content] ' . $css); // continue; // Save the error info too } // Write to file - $filecon_md5 = md5( $css ); + $filecon_md5 = md5($css); - $filepath_prefix = $this->_build_filepath_prefix( $type ); + $filepath_prefix = $this->_build_filepath_prefix($type); $static_file = LITESPEED_STATIC_DIR . $filepath_prefix . $filecon_md5 . '.css'; - File::save( $static_file, $css, true ); + File::save($static_file, $css, true); - $url_tag = $this->_queue[ $queue_k ][ 'url_tag' ]; - $vary = $this->_queue[ $queue_k ][ 'vary' ]; - self::debug2( "Save URL to file [file] $static_file [vary] $vary" ); + $url_tag = $this->_queue[$queue_k]['url_tag']; + $vary = $this->_queue[$queue_k]['vary']; + self::debug2("Save URL to file [file] $static_file [vary] $vary"); - $this->cls( 'Data' )->save_url( $url_tag, $vary, $type, $filecon_md5, dirname( $static_file ), $is_mobile, $is_webp ); + $this->cls('Data')->save_url($url_tag, $vary, $type, $filecon_md5, dirname($static_file), $is_mobile, $is_webp); - Purge::add( strtoupper( $type ) . '.' . md5( $queue_k ) ); + Purge::add(strtoupper($type) . '.' . md5($queue_k)); } /** @@ -378,100 +393,100 @@ private function _save_con( $type, $css, $queue_k, $is_mobile, $is_webp ) { * * @since 3.4.3 */ - public function prepare_css( $html, $is_webp = false, $dryrun = false ) { + public function prepare_css($html, $is_webp = false, $dryrun = false) + { $css = ''; - preg_match_all( '#]+)/?>|]*)>([^<]+)#isU', $html, $matches, PREG_SET_ORDER ); - foreach ( $matches as $match ) { + preg_match_all('#]+)/?>|]*)>([^<]+)#isU', $html, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { $debug_info = ''; - if ( strpos( $match[ 0 ], 'cls( 'Optimizer' )->load_file( $attrs[ 'href' ] ); - if ( ! $con ) { + if (!$dryrun) { + // Dryrun will not load CSS but just drop them + $con = $this->cls('Optimizer')->load_file($attrs['href']); + if (!$con) { continue; } - } - else { + } else { $con = ''; } - } - else { // Inline style - $attrs = Utility::parse_attr( $match[ 2 ] ); + } else { + // Inline style + $attrs = Utility::parse_attr($match[2]); - if ( ! empty( $attrs[ 'media' ] ) && strpos( $attrs[ 'media' ], 'print' ) !== false ) { + if (!empty($attrs['media']) && strpos($attrs['media'], 'print') !== false) { continue; } - Debug2::debug2( '[CSS] Load inline CSS ' . substr( $match[ 3 ], 0, 100 ) . '...', $attrs ); - $con = $match[ 3 ]; + Debug2::debug2('[CSS] Load inline CSS ' . substr($match[3], 0, 100) . '...', $attrs); + $con = $match[3]; $debug_info = '__INLINE__'; } - $con = Optimizer::minify_css( $con ); - if ( $is_webp && $this->cls( 'Media' )->webp_support() ) { - $con = $this->cls( 'Media' )->replace_background_webp( $con ); + $con = Optimizer::minify_css($con); + if ($is_webp && $this->cls('Media')->webp_support()) { + $con = $this->cls('Media')->replace_background_webp($con); } - if ( ! empty( $attrs[ 'media' ] ) && $attrs[ 'media' ] !== 'all' ) { - $con = '@media ' . $attrs[ 'media' ] . '{' . $con . "}\n"; - } - else { + if (!empty($attrs['media']) && $attrs['media'] !== 'all') { + $con = '@media ' . $attrs['media'] . '{' . $con . "}\n"; + } else { $con = $con . "\n"; } $con = '/* ' . $debug_info . ' */' . $con; $css .= $con; - $html = str_replace( $match[ 0 ], '', $html ); + $html = str_replace($match[0], '', $html); } - return array( $css, $html ); + return array($css, $html); } - /** * Filter the comment content, add quotes to selector from whitelist. Return the json * * @since 3.3 */ - private function _filter_whitelist() { + private function _filter_whitelist() + { $whitelist = array(); - $list = apply_filters( 'litespeed_ucss_whitelist', $this->conf( self::O_OPTM_UCSS_WHITELIST ) ); - foreach ( $list as $k => $v ) { - if ( substr( $v, 0, 2 ) === '//' ) { + $list = apply_filters('litespeed_ucss_whitelist', $this->conf(self::O_OPTM_UCSS_SELECTOR_WHITELIST)); + foreach ($list as $k => $v) { + if (substr($v, 0, 2) === '//') { continue; } // Wrap in quotes for selectors - if ( substr( $v, 0, 1 ) !== '/' && strpos( $v, '"' ) === false && strpos( $v, "'" ) === false ) { + if (substr($v, 0, 1) !== '/' && strpos($v, '"') === false && strpos($v, "'") === false) { // $v = "'$v'"; } $whitelist[] = $v; @@ -484,64 +499,65 @@ private function _filter_whitelist() { * Notify finished from server * @since 5.1 */ - public function notify() { + public function notify() + { $post_data = json_decode(file_get_contents('php://input'), true); - if( is_null( $post_data ) ) { + if (is_null($post_data)) { $post_data = $_POST; } - self::debug( 'notify() data', $post_data ); + self::debug('notify() data', $post_data); - $this->_queue = $this->load_queue( 'ucss' ); + $this->_queue = $this->load_queue('ucss'); // Validate key - if ( empty( $post_data[ 'domain_key' ] ) || $post_data[ 'domain_key' ] !== md5( $this->conf( self::O_API_KEY ) ) ) { - self::debug( '❌ notify wrong key' ); - self::save_summary( array( 'notify_ts_err' => time() ) ); - return Cloud::err( 'wrong_key' ); + if (empty($post_data['domain_key']) || $post_data['domain_key'] !== md5($this->conf(self::O_API_KEY))) { + self::debug('❌ notify wrong key'); + self::save_summary(array('notify_ts_err' => time())); + return Cloud::err('wrong_key'); } - list( $post_data ) = $this->cls( 'Cloud' )->extract_msg( $post_data, 'ucss' ); + list($post_data) = $this->cls('Cloud')->extract_msg($post_data, 'ucss'); - $notified_data = $post_data[ 'data' ]; - if ( empty( $notified_data ) || ! is_array( $notified_data ) ) { - self::debug( '❌ notify exit: no notified data' ); - return Cloud::err( 'no notified data' ); + $notified_data = $post_data['data']; + if (empty($notified_data) || !is_array($notified_data)) { + self::debug('❌ notify exit: no notified data'); + return Cloud::err('no notified data'); } // Check if its in queue or not $valid_i = 0; - foreach ( $notified_data as $v ) { - if ( empty( $v[ 'request_url' ] ) ) { - self::debug( '❌ notify bypass: no request_url', $v ); + foreach ($notified_data as $v) { + if (empty($v['request_url'])) { + self::debug('❌ notify bypass: no request_url', $v); continue; } - if ( empty( $v[ 'queue_k' ] ) ) { - self::debug( '❌ notify bypass: no queue_k', $v ); + if (empty($v['queue_k'])) { + self::debug('❌ notify bypass: no queue_k', $v); continue; } - if ( empty( $this->_queue[ $v[ 'queue_k' ] ] ) ) { - self::debug( '❌ notify bypass: no this queue [q_k]' . $v[ 'queue_k' ] ); + if (empty($this->_queue[$v['queue_k']])) { + self::debug('❌ notify bypass: no this queue [q_k]' . $v['queue_k']); continue; } // Save data - if ( ! empty( $v[ 'data_ucss' ] ) ) { - $is_mobile = $this->_queue[ $v[ 'queue_k' ] ][ 'is_mobile' ]; - $is_webp = $this->_queue[ $v[ 'queue_k' ] ][ 'is_webp' ]; - $this->_save_con( 'ucss', $v[ 'data_ucss' ], $v[ 'queue_k' ], $is_mobile, $is_webp ); + if (!empty($v['data_ucss'])) { + $is_mobile = $this->_queue[$v['queue_k']]['is_mobile']; + $is_webp = $this->_queue[$v['queue_k']]['is_webp']; + $this->_save_con('ucss', $v['data_ucss'], $v['queue_k'], $is_mobile, $is_webp); - $valid_i ++; + $valid_i++; } - unset( $this->_queue[ $v[ 'queue_k' ] ] ); - self::debug( 'notify data handled, unset queue [q_k] ' . $v[ 'queue_k' ] ); + unset($this->_queue[$v['queue_k']]); + self::debug('notify data handled, unset queue [q_k] ' . $v['queue_k']); } - $this->save_queue( 'ucss', $this->_queue ); + $this->save_queue('ucss', $this->_queue); - self::debug( 'notified' ); + self::debug('notified'); - return Cloud::ok( array( 'count' => $valid_i ) ); + return Cloud::ok(array('count' => $valid_i)); } /** @@ -550,16 +566,17 @@ public function notify() { * @since 2.3 * @access public */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_GEN: - self::cron( true ); + self::cron(true); break; case self::TYPE_CLEAR_Q: - $this->clear_q( 'ucss' ); + $this->clear_q('ucss'); break; default: @@ -568,5 +585,4 @@ public function handler() { Admin::redirect(); } - } diff --git a/src/utility.cls.php b/src/utility.cls.php index c39bd0fc2..6860b9340 100644 --- a/src/utility.cls.php +++ b/src/utility.cls.php @@ -1,15 +1,18 @@ is_page ) { + if ($wp_query->is_page) { $page_type = is_front_page() ? 'front' : 'page'; - } - elseif ( $wp_query->is_home ) { + } elseif ($wp_query->is_home) { $page_type = 'home'; - } - elseif ( $wp_query->is_single ) { + } elseif ($wp_query->is_single) { // $page_type = $wp_query->is_attachment ? 'attachment' : 'single'; $page_type = get_post_type(); - } - elseif ( $wp_query->is_category ) { + } elseif ($wp_query->is_category) { $page_type = 'category'; - } - elseif ( $wp_query->is_tag ) { + } elseif ($wp_query->is_tag) { $page_type = 'tag'; - } - elseif ( $wp_query->is_tax ) { + } elseif ($wp_query->is_tax) { $page_type = 'tax'; // $page_type = get_queried_object()->taxonomy; - } - elseif ( $wp_query->is_archive ) { - if ( $wp_query->is_day ) { + } elseif ($wp_query->is_archive) { + if ($wp_query->is_day) { $page_type = 'day'; - } - elseif ( $wp_query->is_month ) { + } elseif ($wp_query->is_month) { $page_type = 'month'; - } - elseif ( $wp_query->is_year ) { + } elseif ($wp_query->is_year) { $page_type = 'year'; - } - elseif ( $wp_query->is_author ) { + } elseif ($wp_query->is_author) { $page_type = 'author'; - } - else { + } else { $page_type = 'archive'; } - } - elseif ( $wp_query->is_search ) { + } elseif ($wp_query->is_search) { $page_type = 'search'; - } - elseif ( $wp_query->is_404 ) { + } elseif ($wp_query->is_404) { $page_type = '404'; } @@ -161,23 +157,27 @@ public static function page_type() { * * @since 2.9 */ - public static function ping( $domain ) { - if ( strpos( $domain, ':' ) ) { - $domain = parse_url( $domain, PHP_URL_HOST ); + public static function ping($domain) + { + if (strpos($domain, ':')) { + $domain = parse_url($domain, PHP_URL_HOST); } - $starttime = microtime( true ); - $file = fsockopen( $domain, 443, $errno, $errstr, 10 ); - $stoptime = microtime( true ); - $status = 0; + $starttime = microtime(true); + $file = fsockopen($domain, 443, $errno, $errstr, 10); + $stoptime = microtime(true); + $status = 0; - if ( ! $file ) $status = 99999;// Site is down + if (!$file) { + $status = 99999; + } + // Site is down else { - fclose( $file ); - $status = ( $stoptime - $starttime ) * 1000; - $status = floor( $status ); + fclose($file); + $status = ($stoptime - $starttime) * 1000; + $status = floor($status); } - Debug2::debug( "[Util] ping [Domain] $domain \t[Speed] $status" ); + Debug2::debug("[Util] ping [Domain] $domain \t[Speed] $status"); return $status; } @@ -188,72 +188,71 @@ public static function ping( $domain ) { * @since 1.6.5 * @access public */ - public static function readable_time( $seconds_or_timestamp, $timeout = 3600, $forword = false ) { - - if ( strlen( $seconds_or_timestamp ) == 10 ) { + public static function readable_time($seconds_or_timestamp, $timeout = 3600, $forword = false) + { + if (strlen($seconds_or_timestamp) == 10) { $seconds = time() - $seconds_or_timestamp; - if ( $seconds > $timeout ) { - return date( 'm/d/Y H:i:s', $seconds_or_timestamp + LITESPEED_TIME_OFFSET ); + if ($seconds > $timeout) { + return date('m/d/Y H:i:s', $seconds_or_timestamp + LITESPEED_TIME_OFFSET); } - } - else { + } else { $seconds = $seconds_or_timestamp; } $res = ''; - if ( $seconds > 86400 ) { - $num = floor( $seconds / 86400 ); + if ($seconds > 86400) { + $num = floor($seconds / 86400); $res .= $num . 'd'; $seconds %= 86400; } - if ( $seconds > 3600 ) { - if ( $res ) { + if ($seconds > 3600) { + if ($res) { $res .= ', '; } - $num = floor( $seconds / 3600 ); + $num = floor($seconds / 3600); $res .= $num . 'h'; $seconds %= 3600; } - if ( $seconds > 60 ) { - if ( $res ) { + if ($seconds > 60) { + if ($res) { $res .= ', '; } - $num = floor( $seconds / 60 ); + $num = floor($seconds / 60); $res .= $num . 'm'; $seconds %= 60; } - if ( $seconds > 0 ) { - if ( $res ) { + if ($seconds > 0) { + if ($res) { $res .= ' '; } $res .= $seconds . 's'; } - if ( ! $res ) { - return $forword ? __( 'right now', 'litespeed-cache' ) : __( 'just now', 'litespeed-cache' ); + if (!$res) { + return $forword ? __('right now', 'litespeed-cache') : __('just now', 'litespeed-cache'); } - $res = $forword ? $res : sprintf( __( ' %s ago', 'litespeed-cache' ), $res ); + $res = $forword ? $res : sprintf(__(' %s ago', 'litespeed-cache'), $res); return $res; } - /** * Convert array to string * * @since 1.6 * @access public */ - public static function arr2str( $arr ) { - if ( ! is_array( $arr ) ) { + public static function arr2str($arr) + { + if (!is_array($arr)) { return $arr; } - return base64_encode( json_encode( $arr ) ); + return base64_encode(json_encode($arr)); } /** @@ -262,19 +261,17 @@ public static function arr2str( $arr ) { * @since 1.6 * @access public */ - public static function real_size( $filesize, $is_1000 = false ) { + public static function real_size($filesize, $is_1000 = false) + { $unit = $is_1000 ? 1000 : 1024; - if ( $filesize >= pow( $unit, 3 ) ) { - $filesize = round( $filesize / pow( $unit, 3 ) * 100 ) / 100 . 'G'; - } - elseif ( $filesize >= pow( $unit, 2 ) ) { - $filesize = round( $filesize / pow( $unit, 2 ) * 100 ) / 100 . 'M'; - } - elseif ( $filesize >= $unit ) { - $filesize = round( $filesize / $unit * 100 ) / 100 . 'K'; - } - else { + if ($filesize >= pow($unit, 3)) { + $filesize = round(($filesize / pow($unit, 3)) * 100) / 100 . 'G'; + } elseif ($filesize >= pow($unit, 2)) { + $filesize = round(($filesize / pow($unit, 2)) * 100) / 100 . 'M'; + } elseif ($filesize >= $unit) { + $filesize = round(($filesize / $unit) * 100) / 100 . 'K'; + } else { $filesize = $filesize . 'B'; } return $filesize; @@ -289,11 +286,12 @@ public static function real_size( $filesize, $is_1000 = false ) { * @param string $str * @return array All the attributes */ - public static function parse_attr( $str ) { + public static function parse_attr($str) + { $attrs = array(); - preg_match_all( '#([\w-]+)=(["\'])([^\2]*)\2#isU', $str, $matches, PREG_SET_ORDER ); - foreach ( $matches as $match ) { - $attrs[ $match[ 1 ] ] = trim( $match[ 3 ] ); + preg_match_all('#([\w-]+)=(["\'])([^\2]*)\2#isU', $str, $matches, PREG_SET_ORDER); + foreach ($matches as $match) { + $attrs[$match[1]] = trim($match[3]); } return $attrs; } @@ -309,68 +307,66 @@ public static function parse_attr( $str ) { * @param array $haystack * @return bool|string False if not found, otherwise return the matched string in haystack. */ - public static function str_hit_array( $needle, $haystack, $has_ttl = false ) { - if ( ! $haystack ) { + public static function str_hit_array($needle, $haystack, $has_ttl = false) + { + if (!$haystack) { return false; } /** * Safety check to avoid PHP warning * @see https://github.com/litespeedtech/lscache_wp/pull/131/commits/45fc03af308c7d6b5583d1664fad68f75fb6d017 */ - if ( ! is_array( $haystack ) ) { - Debug2::debug( "[Util] ❌ bad param in str_hit_array()!" ); + if (!is_array($haystack)) { + Debug2::debug('[Util] ❌ bad param in str_hit_array()!'); return false; } $hit = false; $this_ttl = 0; - foreach( $haystack as $item ) { - if ( ! $item ) { + foreach ($haystack as $item) { + if (!$item) { continue; } - if ( $has_ttl ) { + if ($has_ttl) { $this_ttl = 0; - $item = explode( ' ', $item ); - if ( ! empty( $item[ 1 ] ) ) { - $this_ttl = $item[ 1 ]; + $item = explode(' ', $item); + if (!empty($item[1])) { + $this_ttl = $item[1]; } - $item = $item[ 0 ]; + $item = $item[0]; } - if ( substr( $item, 0, 1 ) === '^' && substr( $item, -1 ) === '$' ) { + if (substr($item, 0, 1) === '^' && substr($item, -1) === '$') { // do exact match - if ( substr( $item, 1, -1 ) === $needle ) { + if (substr($item, 1, -1) === $needle) { $hit = $item; break; } - } - elseif ( substr( $item, -1 ) === '$' ) { + } elseif (substr($item, -1) === '$') { // match end - if ( substr( $item, 0, -1 ) === substr($needle, -strlen( $item ) + 1 ) ) { + if (substr($item, 0, -1) === substr($needle, -strlen($item) + 1)) { $hit = $item; break; } - } - elseif ( substr( $item, 0, 1 ) === '^' ) { + } elseif (substr($item, 0, 1) === '^') { // match beginning - if ( substr( $item, 1 ) === substr( $needle, 0, strlen( $item ) - 1 ) ) { + if (substr($item, 1) === substr($needle, 0, strlen($item) - 1)) { $hit = $item; break; } - } - else { - if ( strpos( $needle, $item ) !== false ) { + } else { + if (strpos($needle, $item) !== false) { $hit = $item; break; } } } - if ( $hit ) { - if ( $has_ttl ) { - return array( $hit, $this_ttl ); + if ($hit) { + if ($has_ttl) { + return array($hit, $this_ttl); } return $hit; @@ -385,7 +381,8 @@ public static function str_hit_array( $needle, $haystack, $has_ttl = false ) { * @since 1.2.2 * */ - public static function compatibility() { + public static function compatibility() + { require_once LSCWP_DIR . 'lib/php-compatibility.func.php'; } @@ -397,13 +394,13 @@ public static function compatibility() { * @param string $uri `xx/xx.html` or `/subfolder/xx/xx.html` * @return string http://www.example.com/subfolder/xx/xx.html */ - public static function uri2url( $uri ) { - if ( substr( $uri, 0, 1 ) === '/' ) { + public static function uri2url($uri) + { + if (substr($uri, 0, 1) === '/') { self::domain_const(); $url = LSCWP_DOMAIN . $uri; - } - else { - $url = home_url( '/' ) . $uri; + } else { + $url = home_url('/') . $uri; } return $url; @@ -414,10 +411,11 @@ public static function uri2url( $uri ) { * * @since 4.7 */ - public static function basename( $url ) { - $url = trim( $url ); - $uri = @parse_url( $url, PHP_URL_PATH ); - $basename = pathinfo( $uri, PATHINFO_BASENAME ); + public static function basename($url) + { + $url = trim($url); + $uri = @parse_url($url, PHP_URL_PATH); + $basename = pathinfo($uri, PATHINFO_BASENAME); return $basename; } @@ -427,8 +425,11 @@ public static function basename( $url ) { * * @since 4.7 */ - public static function drop_webp( $filename ) { - if ( substr($filename, -5 ) === '.webp' ) $filename = substr( $filename, 0, -5 ); + public static function drop_webp($filename) + { + if (substr($filename, -5) === '.webp') { + $filename = substr($filename, 0, -5); + } return $filename; } @@ -440,12 +441,13 @@ public static function drop_webp( $filename ) { * @since 1.6.2.1 Added 2nd param keep_qs * @access public */ - public static function url2uri( $url, $keep_qs = false ) { - $url = trim( $url ); - $uri = @parse_url( $url, PHP_URL_PATH ); - $qs = @parse_url( $url, PHP_URL_QUERY ); + public static function url2uri($url, $keep_qs = false) + { + $url = trim($url); + $uri = @parse_url($url, PHP_URL_PATH); + $qs = @parse_url($url, PHP_URL_QUERY); - if ( ! $keep_qs || ! $qs ) { + if (!$keep_qs || !$qs) { return $uri; } @@ -460,18 +462,19 @@ public static function url2uri( $url, $keep_qs = false ) { * @param string `https://aa.com/bbb/wp-content/upload/2018/08/test.jpg` or `/bbb/wp-content/upload/2018/08/test.jpg` * @return string `2018/08/test.jpg` */ - public static function att_short_path( $url ) { - if ( ! defined( 'LITESPEED_UPLOAD_PATH' ) ) { + public static function att_short_path($url) + { + if (!defined('LITESPEED_UPLOAD_PATH')) { $_wp_upload_dir = wp_upload_dir(); - $upload_path = self::url2uri( $_wp_upload_dir[ 'baseurl' ] ); + $upload_path = self::url2uri($_wp_upload_dir['baseurl']); - define( 'LITESPEED_UPLOAD_PATH', $upload_path ); + define('LITESPEED_UPLOAD_PATH', $upload_path); } - $local_file = self::url2uri( $url ); + $local_file = self::url2uri($url); - $short_path = substr( $local_file, strlen( LITESPEED_UPLOAD_PATH ) + 1 ); + $short_path = substr($local_file, strlen(LITESPEED_UPLOAD_PATH) + 1); return $short_path; } @@ -484,13 +487,14 @@ public static function att_short_path( $url ) { * @param string $url * @return string Relative URL, start with / */ - public static function make_relative( $url ) { + public static function make_relative($url) + { // replace home_url if the url is full url self::domain_const(); - if ( strpos( $url, LSCWP_DOMAIN ) === 0 ) { - $url = substr( $url, strlen( LSCWP_DOMAIN ) ); + if (strpos($url, LSCWP_DOMAIN) === 0) { + $url = substr($url, strlen(LSCWP_DOMAIN)); } - return trim( $url ); + return trim($url); } /** @@ -498,17 +502,18 @@ public static function make_relative( $url ) { * * @since 1.7.1 */ - public static function parse_domain( $url ) { - $url = @parse_url( $url ); - if ( empty( $url[ 'host' ] ) ) { + public static function parse_domain($url) + { + $url = @parse_url($url); + if (empty($url['host'])) { return ''; } - if ( ! empty( $url[ 'scheme' ] ) ) { - return $url[ 'scheme' ] . '://' . $url[ 'host' ]; + if (!empty($url['scheme'])) { + return $url['scheme'] . '://' . $url['host']; } - return '//' . $url[ 'host' ]; + return '//' . $url['host']; } /** @@ -516,15 +521,25 @@ public static function parse_domain( $url ) { * * @since 3.3 */ - public static function noprotocol( $url ) { - $tmp = parse_url( trim( $url ) ); - if ( ! empty( $tmp[ 'scheme' ] ) ) { - $url = str_replace( $tmp[ 'scheme' ] . ':', '', $url ); + public static function noprotocol($url) + { + $tmp = parse_url(trim($url)); + if (!empty($tmp['scheme'])) { + $url = str_replace($tmp['scheme'] . ':', '', $url); } return $url; } + /** + * Validate ip v4 + * @since 5.5 + */ + public static function valid_ipv4($ip) + { + return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); + } + /** * Generate domain const * @@ -535,15 +550,16 @@ public static function noprotocol( $url ) { * @since 1.3 * @access public */ - public static function domain_const() { - if ( defined( 'LSCWP_DOMAIN' ) ) { + public static function domain_const() + { + if (defined('LSCWP_DOMAIN')) { return; } self::compatibility(); - $domain = http_build_url( get_home_url(), array(), HTTP_URL_STRIP_ALL ); + $domain = http_build_url(get_home_url(), array(), HTTP_URL_STRIP_ALL); - define( 'LSCWP_DOMAIN', $domain ); + define('LSCWP_DOMAIN', $domain); } /** @@ -553,63 +569,64 @@ public static function domain_const() { * @access public * @param string $content * @param bool $type String handler type - * @return string + * @return string|array */ - public static function sanitize_lines( $arr, $type = null ) { - $types = $type ? explode( ',', $type ) : array(); + public static function sanitize_lines($arr, $type = null) + { + $types = $type ? explode(',', $type) : array(); - if ( ! $arr ) { - if ( $type === 'string' ) { + if (!$arr) { + if ($type === 'string') { return ''; } return array(); } - if ( ! is_array( $arr ) ) { - $arr = explode( "\n", $arr ); + if (!is_array($arr)) { + $arr = explode("\n", $arr); } - $arr = array_map( 'trim', $arr ); + $arr = array_map('trim', $arr); $changed = false; - if ( in_array( 'uri', $types ) ) { - $arr = array_map( __CLASS__ . '::url2uri', $arr ); + if (in_array('uri', $types)) { + $arr = array_map(__CLASS__ . '::url2uri', $arr); $changed = true; } - if ( in_array( 'basename', $types ) ) { - $arr = array_map( __CLASS__ . '::basename', $arr ); + if (in_array('basename', $types)) { + $arr = array_map(__CLASS__ . '::basename', $arr); $changed = true; } - if ( in_array( 'drop_webp', $types ) ) { - $arr = array_map( __CLASS__ . '::drop_webp', $arr ); + if (in_array('drop_webp', $types)) { + $arr = array_map(__CLASS__ . '::drop_webp', $arr); $changed = true; } - if ( in_array( 'relative', $types ) ) { - $arr = array_map( __CLASS__ . '::make_relative', $arr );// Remove domain + if (in_array('relative', $types)) { + $arr = array_map(__CLASS__ . '::make_relative', $arr); // Remove domain $changed = true; } - if ( in_array( 'domain', $types ) ) { - $arr = array_map( __CLASS__ . '::parse_domain', $arr );// Only keep domain + if (in_array('domain', $types)) { + $arr = array_map(__CLASS__ . '::parse_domain', $arr); // Only keep domain $changed = true; } - if ( in_array( 'noprotocol', $types ) ) { - $arr = array_map( __CLASS__ . '::noprotocol', $arr ); // Drop protocol, `https://example.com` -> `//example.com` + if (in_array('noprotocol', $types)) { + $arr = array_map(__CLASS__ . '::noprotocol', $arr); // Drop protocol, `https://example.com` -> `//example.com` $changed = true; } - if ( in_array( 'trailingslash', $types ) ) { - $arr = array_map( 'trailingslashit', $arr ); // Append trailing slach, `https://example.com` -> `https://example.com/` + if (in_array('trailingslash', $types)) { + $arr = array_map('trailingslashit', $arr); // Append trailing slach, `https://example.com` -> `https://example.com/` $changed = true; } - if ( $changed ) { - $arr = array_map( 'trim', $arr ); + if ($changed) { + $arr = array_map('trim', $arr); } - $arr = array_unique( $arr ); - $arr = array_filter( $arr ); + $arr = array_unique($arr); + $arr = array_filter($arr); - if ( in_array( 'string', $types ) ) { - return implode( "\n", $arr ); + if (in_array('string', $types)) { + return implode("\n", $arr); } return $arr; @@ -624,71 +641,68 @@ public static function sanitize_lines( $arr, $type = null ) { * @access public * @return string The built url. */ - public static function build_url( $action, $type = false, $is_ajax = false, $page = null, $append_arr = array() ) { + public static function build_url($action, $type = false, $is_ajax = false, $page = null, $append_arr = array()) + { $prefix = '?'; - if ( $page === '_ori' ) { + if ($page === '_ori') { $page = true; - $append_arr[ '_litespeed_ori' ] = 1; + $append_arr['_litespeed_ori'] = 1; } - if ( ! $is_ajax ) { - if ( $page ) { + if (!$is_ajax) { + if ($page) { // If use admin url - if ( $page === true ) { + if ($page === true) { $page = 'admin.php'; - } - else { - if ( strpos( $page, '?' ) !== false ) { + } else { + if (strpos($page, '?') !== false) { $prefix = '&'; } } $combined = $page . $prefix . Router::ACTION . '=' . $action; - } - else { + } else { // Current page rebuild URL $params = $_GET; - if ( ! empty( $params ) ) { - if ( isset( $params[ Router::ACTION ] ) ) { - unset( $params[ Router::ACTION ] ); + if (!empty($params)) { + if (isset($params[Router::ACTION])) { + unset($params[Router::ACTION]); } - if ( isset( $params[ '_wpnonce' ] ) ) { - unset( $params[ '_wpnonce' ] ); + if (isset($params['_wpnonce'])) { + unset($params['_wpnonce']); } - if ( ! empty( $params ) ) { - $prefix .= http_build_query( $params ) . '&'; + if (!empty($params)) { + $prefix .= http_build_query($params) . '&'; } } global $pagenow; $combined = $pagenow . $prefix . Router::ACTION . '=' . $action; } - } - else { + } else { $combined = 'admin-ajax.php?action=litespeed_ajax&' . Router::ACTION . '=' . $action; } - if ( is_network_admin() ) { - $prenonce = network_admin_url( $combined ); - } - else { - $prenonce = admin_url( $combined ); + if (is_network_admin()) { + $prenonce = network_admin_url($combined); + } else { + $prenonce = admin_url($combined); } - $url = wp_nonce_url( $prenonce, $action, Router::NONCE ); + $url = wp_nonce_url($prenonce, $action, Router::NONCE); - if ( $type ) { + if ($type) { // Remove potential param `type` from url - $url = parse_url( htmlspecialchars_decode( $url ) ); - parse_str( $url[ 'query' ], $query ); + $url = parse_url(htmlspecialchars_decode($url)); + parse_str($url['query'], $query); - $built_arr = array_merge( $query, array( Router::TYPE => $type ) ); - if ( $append_arr ) { - $built_arr = array_merge( $built_arr, $append_arr ); + $built_arr = array_merge($query, array(Router::TYPE => $type)); + if ($append_arr) { + $built_arr = array_merge($built_arr, $append_arr); } - $url[ 'query' ] = http_build_query( $built_arr ); + $url['query'] = http_build_query($built_arr); self::compatibility(); - $url = http_build_url( $url ); - $url = htmlspecialchars( $url, ENT_QUOTES, 'UTF-8' ); + $url = http_build_url($url); + $url = htmlspecialchars($url, ENT_QUOTES, 'UTF-8'); } return $url; @@ -700,18 +714,18 @@ public static function build_url( $action, $type = false, $is_ajax = false, $pag * @since 1.2.3 * */ - public static function internal( $host ) { - if ( ! defined( 'LITESPEED_FRONTEND_HOST' ) ) { - if ( defined( 'WP_HOME' ) ) { - $home_host = WP_HOME;// Also think of `WP_SITEURL` - } - else { - $home_host = get_option( 'home' ); + public static function internal($host) + { + if (!defined('LITESPEED_FRONTEND_HOST')) { + if (defined('WP_HOME')) { + $home_host = WP_HOME; // Also think of `WP_SITEURL` + } else { + $home_host = get_option('home'); } - define( 'LITESPEED_FRONTEND_HOST', parse_url( $home_host, PHP_URL_HOST ) ); + define('LITESPEED_FRONTEND_HOST', parse_url($home_host, PHP_URL_HOST)); } - if ( $host === LITESPEED_FRONTEND_HOST ) { + if ($host === LITESPEED_FRONTEND_HOST) { return true; } @@ -719,12 +733,12 @@ public static function internal( $host ) { * Filter for multiple domains * @since 2.9.4 */ - if ( ! isset( self::$_internal_domains ) ) { - self::$_internal_domains = apply_filters( 'litespeed_internal_domains', array() ); + if (!isset(self::$_internal_domains)) { + self::$_internal_domains = apply_filters('litespeed_internal_domains', array()); } - if ( self::$_internal_domains ) { - return in_array( $host, self::$_internal_domains ); + if (self::$_internal_domains) { + return in_array($host, self::$_internal_domains); } return false; @@ -738,30 +752,31 @@ public static function internal( $host ) { * @access public * @return string|bool The real path of file OR false */ - public static function is_internal_file( $url, $addition_postfix = false ) { - if ( substr( $url, 0, 5 ) == 'data:' ) { - Debug2::debug2( '[Util] data: content not file' ); + public static function is_internal_file($url, $addition_postfix = false) + { + if (substr($url, 0, 5) == 'data:') { + Debug2::debug2('[Util] data: content not file'); return false; } - $url_parsed = parse_url( $url ); - if ( isset( $url_parsed[ 'host' ] ) && ! self::internal( $url_parsed[ 'host' ] ) ) { + $url_parsed = parse_url($url); + if (isset($url_parsed['host']) && !self::internal($url_parsed['host'])) { // Check if is cdn path // Do this to avoid user hardcoded src in tpl - if ( ! CDN::internal( $url_parsed[ 'host' ] ) ) { - Debug2::debug2( '[Util] external' ); + if (!CDN::internal($url_parsed['host'])) { + Debug2::debug2('[Util] external'); return false; } } - if ( empty( $url_parsed[ 'path' ] ) ) { + if (empty($url_parsed['path'])) { return false; } // Need to replace child blog path for assets, ref: .htaccess - if ( is_multisite() && defined( 'PATH_CURRENT_SITE' ) ) { + if (is_multisite() && defined('PATH_CURRENT_SITE')) { $pattern = '#^' . PATH_CURRENT_SITE . '([_0-9a-zA-Z-]+/)(wp-(content|admin|includes))#U'; $replacement = PATH_CURRENT_SITE . '$2'; - $url_parsed[ 'path' ] = preg_replace( $pattern, $replacement, $url_parsed[ 'path' ] ); + $url_parsed['path'] = preg_replace($pattern, $replacement, $url_parsed['path']); // $current_blog = (int) get_current_blog_id(); // $main_blog_id = (int) get_network()->site_id; // if ( $current_blog === $main_blog_id ) { @@ -781,23 +796,21 @@ public static function is_internal_file( $url, $addition_postfix = false ) { * @internal #611001 - Combine & Minify not working? * @since 1.6.3 */ - if ( substr( $url_parsed[ 'path' ], 0, 1 ) === '/' ) { - if ( defined( 'LITESPEED_WP_REALPATH' ) ) { - $file_path_ori = $_SERVER[ 'DOCUMENT_ROOT' ] . LITESPEED_WP_REALPATH . $url_parsed[ 'path' ]; - } - else { - $file_path_ori = $_SERVER[ 'DOCUMENT_ROOT' ] . $url_parsed[ 'path' ]; + if (substr($url_parsed['path'], 0, 1) === '/') { + if (defined('LITESPEED_WP_REALPATH')) { + $file_path_ori = $_SERVER['DOCUMENT_ROOT'] . LITESPEED_WP_REALPATH . $url_parsed['path']; + } else { + $file_path_ori = $_SERVER['DOCUMENT_ROOT'] . $url_parsed['path']; } - } - else { - $file_path_ori = Router::frontend_path() . '/' . $url_parsed[ 'path' ]; + } else { + $file_path_ori = Router::frontend_path() . '/' . $url_parsed['path']; } /** * Added new file postfix to be check if passed in * @since 2.2.4 */ - if ( $addition_postfix ) { + if ($addition_postfix) { $file_path_ori .= '.' . $addition_postfix; } @@ -806,15 +819,15 @@ public static function is_internal_file( $url, $addition_postfix = false ) { * @see #101091 plugin `Hide My WordPress` * @since 2.2.3 */ - $file_path_ori = apply_filters( 'litespeed_realpath', $file_path_ori ); + $file_path_ori = apply_filters('litespeed_realpath', $file_path_ori); - $file_path = realpath( $file_path_ori ); - if ( ! is_file( $file_path ) ) { - Debug2::debug2( '[Util] file not exist: ' . $file_path_ori ); + $file_path = realpath($file_path_ori); + if (!is_file($file_path)) { + Debug2::debug2('[Util] file not exist: ' . $file_path_ori); return false; } - return array( $file_path, filesize( $file_path ) ); + return array($file_path, filesize($file_path)); } /** @@ -822,12 +835,13 @@ public static function is_internal_file( $url, $addition_postfix = false ) { * * @since 3.4.3 */ - public static function parse_url_safe( $url, $component = -1 ) { - if ( substr( $url, 0, 2 ) == '//' ) { + public static function parse_url_safe($url, $component = -1) + { + if (substr($url, 0, 2) == '//') { $url = 'https:' . $url; } - return parse_url( $url, $component ); + return parse_url($url, $component); } /** @@ -835,48 +849,47 @@ public static function parse_url_safe( $url, $component = -1 ) { * * @since 2.2.3 */ - public static function srcset_replace( $content, $callback ) { - preg_match_all( '# srcset=([\'"])(.+)\g{1}#iU', $content, $matches ); + public static function srcset_replace($content, $callback) + { + preg_match_all('# srcset=([\'"])(.+)\g{1}#iU', $content, $matches); $srcset_ori = array(); $srcset_final = array(); - foreach ( $matches[ 2 ] as $k => $urls_ori ) { - - $urls_final = explode( ',', $urls_ori ); + foreach ($matches[2] as $k => $urls_ori) { + $urls_final = explode(',', $urls_ori); $changed = false; - foreach ( $urls_final as $k2 => $url_info ) { - $url_info_arr = explode( ' ', trim( $url_info ) ); + foreach ($urls_final as $k2 => $url_info) { + $url_info_arr = explode(' ', trim($url_info)); - if ( ! $url2 = call_user_func( $callback, $url_info_arr[ 0 ] ) ) { + if (!($url2 = call_user_func($callback, $url_info_arr[0]))) { continue; } $changed = true; - $urls_final[ $k2 ] = str_replace( $url_info_arr[ 0 ], $url2, $url_info ); + $urls_final[$k2] = str_replace($url_info_arr[0], $url2, $url_info); - Debug2::debug2( '[Util] - srcset replaced to ' . $url2 . ( ! empty( $url_info_arr[ 1 ] ) ? ' ' . $url_info_arr[ 1 ] : '' ) ); + Debug2::debug2('[Util] - srcset replaced to ' . $url2 . (!empty($url_info_arr[1]) ? ' ' . $url_info_arr[1] : '')); } - if ( ! $changed ) { + if (!$changed) { continue; } - $urls_final = implode( ',', $urls_final ); + $urls_final = implode(',', $urls_final); - $srcset_ori[] = $matches[ 0 ][ $k ]; + $srcset_ori[] = $matches[0][$k]; - $srcset_final[] = str_replace( $urls_ori, $urls_final, $matches[ 0 ][ $k ] ); + $srcset_final[] = str_replace($urls_ori, $urls_final, $matches[0][$k]); } - if ( $srcset_ori ) { - $content = str_replace( $srcset_ori, $srcset_final, $content ); - Debug2::debug2( '[Util] - srcset replaced' ); + if ($srcset_ori) { + $content = str_replace($srcset_ori, $srcset_final, $content); + Debug2::debug2('[Util] - srcset replaced'); } return $content; - } /** @@ -885,32 +898,33 @@ public static function srcset_replace( $content, $callback ) { * @since 3.0 * @access public */ - public static function pagination( $total, $limit, $return_offset = false ) { - $pagenum = isset( $_GET[ 'pagenum' ] ) ? absint( $_GET[ 'pagenum' ] ) : 1; + public static function pagination($total, $limit, $return_offset = false) + { + $pagenum = isset($_GET['pagenum']) ? absint($_GET['pagenum']) : 1; - $offset = ( $pagenum - 1 ) * $limit; - $num_of_pages = ceil( $total / $limit ); + $offset = ($pagenum - 1) * $limit; + $num_of_pages = ceil($total / $limit); - if ( $offset > $total ) { + if ($offset > $total) { $offset = $total - $limit; } - if ( $offset < 0 ) { + if ($offset < 0) { $offset = 0; } - if ( $return_offset ) { + if ($return_offset) { return $offset; } - $page_links = paginate_links( array( - 'base' => add_query_arg( 'pagenum', '%#%' ), + $page_links = paginate_links(array( + 'base' => add_query_arg('pagenum', '%#%'), 'format' => '', 'prev_text' => '«', 'next_text' => '»', 'total' => $num_of_pages, 'current' => $pagenum, - ) ); + )); return '
    ' . $page_links . '
    '; } @@ -921,15 +935,17 @@ public static function pagination( $total, $limit, $return_offset = false ) { * @since 2.0 * @access public */ - public static function chunk_placeholder( $data, $fields ) { - $division = substr_count( $fields, ',' ) + 1; + public static function chunk_placeholder($data, $fields) + { + $division = substr_count($fields, ',') + 1; - $q = implode( ',', array_map( - function( $el ) { return '(' . implode( ',', $el ) . ')'; }, - array_chunk( array_fill( 0, count( $data ), '%s' ), $division ) - ) ); + $q = implode( + ',', + array_map(function ($el) { + return '(' . implode(',', $el) . ')'; + }, array_chunk(array_fill(0, count($data), '%s'), $division)) + ); return $q; } - } diff --git a/src/vary.cls.php b/src/vary.cls.php index 96afe699b..ed0526c18 100644 --- a/src/vary.cls.php +++ b/src/vary.cls.php @@ -1,13 +1,17 @@ _update_vary_name(); } @@ -29,39 +34,39 @@ public function init() { * * @since 4.0 */ - private function _update_vary_name() { - $db_cookie = $this->conf( Base::O_CACHE_LOGIN_COOKIE ); // [3.0] todo: check if works in network's sites + private function _update_vary_name() + { + $db_cookie = $this->conf(Base::O_CACHE_LOGIN_COOKIE); // [3.0] todo: check if works in network's sites // If no vary set in rewrite rule - if ( ! isset( $_SERVER[ 'LSCACHE_VARY_COOKIE' ] ) ) { - if ( $db_cookie ) { + if (!isset($_SERVER['LSCACHE_VARY_COOKIE'])) { + if ($db_cookie) { // Display cookie error msg to admin - if ( is_multisite() ? is_network_admin() : is_admin() ) { + if (is_multisite() ? is_network_admin() : is_admin()) { Admin_Display::show_error_cookie(); } - Control::set_nocache( 'vary cookie setting error' ); + Control::set_nocache('vary cookie setting error'); return; } return; } // If db setting does not exist, skip checking db value - if ( ! $db_cookie ) { + if (!$db_cookie) { return; } // beyond this point, need to make sure db vary setting is in $_SERVER env. - $vary_arr = explode( ',', $_SERVER[ 'LSCACHE_VARY_COOKIE' ] ); + $vary_arr = explode(',', $_SERVER['LSCACHE_VARY_COOKIE']); - if ( in_array( $db_cookie, $vary_arr ) ) { + if (in_array($db_cookie, $vary_arr)) { self::$_vary_name = $db_cookie; return; } - if ( is_multisite() ? is_network_admin() : is_admin() ) { + if (is_multisite() ? is_network_admin() : is_admin()) { Admin_Display::show_error_cookie(); } Control::set_nocache('vary cookie setting lost error'); - } /** @@ -69,65 +74,65 @@ private function _update_vary_name() { * * @since 4.0 */ - public function after_user_init() { + public function after_user_init() + { // logged in user - if ( Router::is_logged_in() ) { + if (Router::is_logged_in()) { // If not esi, check cache logged-in user setting - if ( ! $this->cls( 'Router' )->esi_enabled() ) { + if (!$this->cls('Router')->esi_enabled()) { // If cache logged-in, then init cacheable to private - if ( $this->conf( Base::O_CACHE_PRIV ) ) { - add_action( 'wp_logout', __NAMESPACE__ . '\Purge::purge_on_logout' ); + if ($this->conf(Base::O_CACHE_PRIV)) { + add_action('wp_logout', __NAMESPACE__ . '\Purge::purge_on_logout'); - $this->cls( 'Control' )->init_cacheable(); - Control::set_private( 'logged in user' ); + $this->cls('Control')->init_cacheable(); + Control::set_private('logged in user'); } // No cache for logged-in user else { - Control::set_nocache( 'logged in user' ); + Control::set_nocache('logged in user'); } } // ESI is on, can be public cache else { // Need to make sure vary is using group id - $this->cls( 'Control' )->init_cacheable(); + $this->cls('Control')->init_cacheable(); } // register logout hook to clear login status - add_action( 'clear_auth_cookie', array( $this, 'remove_logged_in' ) ); - - } - else { + add_action('clear_auth_cookie', array($this, 'remove_logged_in')); + } else { // Only after vary init, can detect if is Guest mode or not $this->_maybe_guest_mode(); // Set vary cookie for logging in user, otherwise the user will hit public with vary=0 (guest version) - add_action( 'set_logged_in_cookie', array( $this, 'add_logged_in' ), 10, 4 ); - add_action( 'wp_login', __NAMESPACE__ . '\Purge::purge_on_logout' ); + add_action('set_logged_in_cookie', array($this, 'add_logged_in'), 10, 4); + add_action('wp_login', __NAMESPACE__ . '\Purge::purge_on_logout'); - $this->cls( 'Control' )->init_cacheable(); + $this->cls('Control')->init_cacheable(); // Check `login page` cacheable setting because they don't go through main WP logic - add_action( 'login_init', array( $this->cls( 'Tag' ), 'check_login_cacheable' ), 5 ); + add_action('login_init', array($this->cls('Tag'), 'check_login_cacheable'), 5); - if ( ! empty( $_GET[ 'litespeed_guest' ] ) ) { - add_action( 'wp_loaded', array( $this, 'update_guest_vary' ), 20 ); + if (!empty($_GET['litespeed_guest'])) { + add_action('wp_loaded', array($this, 'update_guest_vary'), 20); } } // Add comment list ESI - add_filter( 'comments_array', array( $this, 'check_commenter' ) ); + add_filter('comments_array', array($this, 'check_commenter')); // Set vary cookie for commenter. - add_action( 'set_comment_cookies', array( $this, 'append_commenter' ) ); + add_action('set_comment_cookies', array($this, 'append_commenter')); /** * Don't change for REST call because they don't carry on user info usually * @since 1.6.7 */ - add_action( 'rest_api_init', function(){ // this hook is fired in `init` hook - Debug2::debug( '[Vary] Rest API init disabled vary change' ); - add_filter( 'litespeed_can_change_vary', '__return_false' ); - } ); + add_action('rest_api_init', function () { + // this hook is fired in `init` hook + Debug2::debug('[Vary] Rest API init disabled vary change'); + add_filter('litespeed_can_change_vary', '__return_false'); + }); } /** @@ -135,52 +140,53 @@ public function after_user_init() { * * @since 4.0 */ - private function _maybe_guest_mode() { - if ( defined( 'LITESPEED_GUEST' ) ) { - Debug2::debug( '[Vary] 👒👒 Guest mode ' . ( LITESPEED_GUEST ? 'predefined' : 'turned off' ) ); + private function _maybe_guest_mode() + { + if (defined('LITESPEED_GUEST')) { + Debug2::debug('[Vary] 👒👒 Guest mode ' . (LITESPEED_GUEST ? 'predefined' : 'turned off')); return; } - if ( ! $this->conf( Base::O_GUEST ) ) { + if (!$this->conf(Base::O_GUEST)) { return; } // If vary is set, then not a guest - if ( self::has_vary() ) { + if (self::has_vary()) { return; } // If has admin QS, then no guest - if ( ! empty( $_GET[ Router::ACTION ] ) ) { + if (!empty($_GET[Router::ACTION])) { return; } - if ( defined( 'DOING_AJAX' ) ) { + if (defined('DOING_AJAX')) { return; } - if ( defined( 'DOING_CRON' ) ) { + if (defined('DOING_CRON')) { return; } // If is the request to update vary, then no guest // Don't need anymore as it is always ajax call // Still keep it in case some WP blocked the lightweigh guest vary update script, WP can still update the vary - if ( ! empty( $_GET[ 'litespeed_guest' ] ) ) { + if (!empty($_GET['litespeed_guest'])) { return; } /* @ref https://wordpress.org/support/topic/checkout-add-to-cart-executed-twice/ */ - if ( ! empty( $_GET[ 'litespeed_guest_off' ] ) ) { + if (!empty($_GET['litespeed_guest_off'])) { return; } - Debug2::debug( '[Vary] 👒👒 Guest mode' ); + Debug2::debug('[Vary] 👒👒 Guest mode'); - ! defined( 'LITESPEED_GUEST' ) && define( 'LITESPEED_GUEST', true ); + !defined('LITESPEED_GUEST') && define('LITESPEED_GUEST', true); - if ( $this->conf( Base::O_GUEST_OPTM ) ) { - ! defined( 'LITESPEED_GUEST_OPTM' ) && define( 'LITESPEED_GUEST_OPTM', true ); + if ($this->conf(Base::O_GUEST_OPTM)) { + !defined('LITESPEED_GUEST_OPTM') && define('LITESPEED_GUEST_OPTM', true); } } @@ -190,23 +196,25 @@ private function _maybe_guest_mode() { * @since 4.0 * @deprecated 4.1 Use independent lightweight guest.vary.php as a replacement */ - public function update_guest_vary() { + public function update_guest_vary() + { // This process must not be cached - ! defined( 'LSCACHE_NO_CACHE' ) && define( 'LSCACHE_NO_CACHE', true ); + !defined('LSCACHE_NO_CACHE') && define('LSCACHE_NO_CACHE', true); $_guest = new Lib\Guest(); - if ( $_guest->always_guest() || self::has_vary() ) { // If contains vary already, don't reload to avoid infinite loop when parent page having browser cache - ! defined( 'LITESPEED_GUEST' ) && define( 'LITESPEED_GUEST', true ); // Reuse this const to bypass set vary in vary finalize - Debug2::debug( '[Vary] 🤠🤠 Guest' ); + if ($_guest->always_guest() || self::has_vary()) { + // If contains vary already, don't reload to avoid infinite loop when parent page having browser cache + !defined('LITESPEED_GUEST') && define('LITESPEED_GUEST', true); // Reuse this const to bypass set vary in vary finalize + Debug2::debug('[Vary] 🤠🤠 Guest'); echo '[]'; - exit; + exit(); } - Debug2::debug( "[Vary] Will update guest vary in finalize" ); + Debug2::debug('[Vary] Will update guest vary in finalize'); // return json - echo json_encode( array( 'reload' => 'yes' ) ); - exit; + echo json_encode(array('reload' => 'yes')); + exit(); } /** @@ -224,29 +232,31 @@ public function update_guest_vary() { * @param array $comments The current comments to output * @return array The comments to output. */ - public function check_commenter( $comments ) { + public function check_commenter($comments) + { /** * Hook to bypass pending comment check for comment related plugins compatibility * @since 2.9.5 */ - if ( apply_filters( 'litespeed_vary_check_commenter_pending', true ) ) { + if (apply_filters('litespeed_vary_check_commenter_pending', true)) { $pending = false; - foreach ( $comments as $comment ) { - if ( ! $comment->comment_approved ) { // current user has pending comment + foreach ($comments as $comment) { + if (!$comment->comment_approved) { + // current user has pending comment $pending = true; break; } } // No pending comments, don't need to add private cache - if ( ! $pending ) { - Debug2::debug( '[Vary] No pending comment' ); + if (!$pending) { + Debug2::debug('[Vary] No pending comment'); $this->remove_commenter(); // Remove commenter prefilled info if exists, for public cache - foreach( $_COOKIE as $cookie_name => $cookie_value ) { - if ( strlen( $cookie_name ) >= 15 && strpos( $cookie_name, 'comment_author_' ) === 0 ) { - unset( $_COOKIE[ $cookie_name ] ); + foreach ($_COOKIE as $cookie_name => $cookie_value) { + if (strlen($cookie_name) >= 15 && strpos($cookie_name, 'comment_author_') === 0) { + unset($_COOKIE[$cookie_name]); } } @@ -258,11 +268,10 @@ public function check_commenter( $comments ) { // set vary=2 for next time vary lookup $this->add_commenter(); - if ( $this->conf( Base::O_CACHE_COMMENTER ) ) { - Control::set_private( 'existing commenter' ); - } - else { - Control::set_nocache( 'existing commenter' ); + if ($this->conf(Base::O_CACHE_COMMENTER)) { + Control::set_private('existing commenter'); + } else { + Control::set_nocache('existing commenter'); } return $comments; @@ -274,11 +283,12 @@ public function check_commenter( $comments ) { * @since 1.1.3 * @access public */ - public static function has_vary() { - if ( empty( $_COOKIE[ self::$_vary_name ] ) ) { + public static function has_vary() + { + if (empty($_COOKIE[self::$_vary_name])) { return false; } - return $_COOKIE[ self::$_vary_name ]; + return $_COOKIE[self::$_vary_name]; } /** @@ -288,8 +298,9 @@ public static function has_vary() { * @since 1.6.2 Removed static referral * @access public */ - public function add_logged_in( $logged_in_cookie = false, $expire = false, $expiration = false, $uid = false ) { - Debug2::debug( '[Vary] add_logged_in' ); + public function add_logged_in($logged_in_cookie = false, $expire = false, $expiration = false, $uid = false) + { + Debug2::debug('[Vary] add_logged_in'); /** * NOTE: Run before `$this->_update_default_vary()` to make vary changeable @@ -298,7 +309,7 @@ public function add_logged_in( $logged_in_cookie = false, $expire = false, $expi self::can_ajax_vary(); // If the cookie is lost somehow, set it - $this->_update_default_vary( $uid, $expire ); + $this->_update_default_vary($uid, $expire); } /** @@ -308,8 +319,9 @@ public function add_logged_in( $logged_in_cookie = false, $expire = false, $expi * @since 1.6.2 Removed static referral * @access public */ - public function remove_logged_in() { - Debug2::debug( '[Vary] remove_logged_in' ); + public function remove_logged_in() + { + Debug2::debug('[Vary] remove_logged_in'); /** * NOTE: Run before `$this->_update_default_vary()` to make vary changeable @@ -318,7 +330,7 @@ public function remove_logged_in() { self::can_ajax_vary(); // Force update vary to remove login status - $this->_update_default_vary( -1 ); + $this->_update_default_vary(-1); } /** @@ -328,8 +340,9 @@ public function remove_logged_in() { * @since 2.6 Changed to static * @access public */ - public static function can_ajax_vary() { - Debug2::debug( '[Vary] _can_change_vary -> true' ); + public static function can_ajax_vary() + { + Debug2::debug('[Vary] _can_change_vary -> true'); self::$_can_change_vary = true; } @@ -339,11 +352,12 @@ public static function can_ajax_vary() { * @since 1.6.2 * @access private */ - private function can_change_vary() { + private function can_change_vary() + { // Don't change for ajax due to ajax not sending webp header - if ( Router::is_ajax() ) { - if ( ! self::$_can_change_vary ) { - Debug2::debug( '[Vary] can_change_vary bypassed due to ajax call' ); + if (Router::is_ajax()) { + if (!self::$_can_change_vary) { + Debug2::debug('[Vary] can_change_vary bypassed due to ajax call'); return false; } } @@ -352,8 +366,8 @@ private function can_change_vary() { * POST request can set vary to fix #820789 login "loop" guest cache issue * @since 1.6.5 */ - if ( isset( $_SERVER["REQUEST_METHOD"] ) && $_SERVER["REQUEST_METHOD"] !== 'GET' && $_SERVER["REQUEST_METHOD"] !== 'POST' ) { - Debug2::debug( '[Vary] can_change_vary bypassed due to method not get/post' ); + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST') { + Debug2::debug('[Vary] can_change_vary bypassed due to method not get/post'); return false; } @@ -361,13 +375,13 @@ private function can_change_vary() { * Disable vary change if is from crawler * @since 2.9.8 To enable woocommerce cart not empty warm up (@Taba) */ - if ( ! empty( $_SERVER[ 'HTTP_USER_AGENT' ] ) && strpos( $_SERVER[ 'HTTP_USER_AGENT' ], Crawler::FAST_USER_AGENT ) === 0 ) { - Debug2::debug( '[Vary] can_change_vary bypassed due to crawler' ); + if (!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], Crawler::FAST_USER_AGENT) === 0) { + Debug2::debug('[Vary] can_change_vary bypassed due to crawler'); return false; } - if ( ! apply_filters( 'litespeed_can_change_vary', true ) ) { - Debug2::debug( '[Vary] can_change_vary bypassed due to litespeed_can_change_vary hook' ); + if (!apply_filters('litespeed_can_change_vary', true)) { + Debug2::debug('[Vary] can_change_vary bypassed due to litespeed_can_change_vary hook'); return false; } @@ -381,28 +395,28 @@ private function can_change_vary() { * @since 1.6.6.1 Add ran check to make it only run once ( No run multiple times due to login process doesn't have valid uid ) * @access private */ - private function _update_default_vary( $uid = false, $expire = false ) { + private function _update_default_vary($uid = false, $expire = false) + { // Make sure header output only run once - if ( ! defined( 'LITESPEED_DID_' . __FUNCTION__ ) ) { - define( 'LITESPEED_DID_' . __FUNCTION__, true ); - } - else { - Debug2::debug2( "[Vary] _update_default_vary bypassed due to run already" ); + if (!defined('LITESPEED_DID_' . __FUNCTION__)) { + define('LITESPEED_DID_' . __FUNCTION__, true); + } else { + Debug2::debug2('[Vary] _update_default_vary bypassed due to run already'); return; } // If the cookie is lost somehow, set it - $vary = $this->finalize_default_vary( $uid ); + $vary = $this->finalize_default_vary($uid); $current_vary = self::has_vary(); - if ( $current_vary !== $vary && $current_vary !== 'commenter' && $this->can_change_vary() ) { + if ($current_vary !== $vary && $current_vary !== 'commenter' && $this->can_change_vary()) { // $_COOKIE[ self::$_vary_name ] = $vary; // not needed // save it - if ( ! $expire ) { + if (!$expire) { $expire = time() + 2 * DAY_IN_SECONDS; } - $this->_cookie( $vary, $expire ); - Debug2::debug( "[Vary] set_cookie ---> $vary" ); + $this->_cookie($vary, $expire); + Debug2::debug("[Vary] set_cookie ---> $vary"); // Control::set_nocache( 'changing default vary' . " $current_vary => $vary" ); } } @@ -413,7 +427,8 @@ private function _update_default_vary( $uid = false, $expire = false ) { * @since 1.9.1 * @access public */ - public function get_vary_name() { + public function get_vary_name() + { return self::$_vary_name; } @@ -426,18 +441,24 @@ public function get_vary_name() { * @param string $role The user role * @return int The set value if already set */ - public function in_vary_group( $role ) { + public function in_vary_group($role) + { $group = 0; - $vary_groups = $this->conf( Base::O_CACHE_VARY_GROUP ); - if ( array_key_exists( $role, $vary_groups ) ) { - $group = $vary_groups[ $role ]; - } - elseif ( $role === 'administrator' ) { + $vary_groups = $this->conf(Base::O_CACHE_VARY_GROUP); + + $roles = explode(',', $role); + if ($found = array_intersect($roles, array_keys($vary_groups))) { + $groups = array(); + foreach ($found as $curr_role) { + $groups[] = $vary_groups[$curr_role]; + } + $group = implode(',', array_unique($groups)); + } elseif (in_array('administrator', $roles)) { $group = 99; } - if ( $group ) { - Debug2::debug2( '[Vary] role in vary_group [group] ' . $group ); + if ($group) { + Debug2::debug2('[Vary] role in vary_group [group] ' . $group); } return $group; @@ -453,53 +474,50 @@ public function in_vary_group( $role ) { * @since 1.6.2 * @access public */ - public function finalize_default_vary( $uid = false ) { + public function finalize_default_vary($uid = false) + { // Must check this to bypass vary generation for guests // Must check this to avoid Guest page's CSS/JS/CCSS/UCSS get non-guest vary filename - if ( defined( 'LITESPEED_GUEST' ) && LITESPEED_GUEST ) { + if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) { return false; } $vary = array(); - if ( $this->conf( Base::O_GUEST ) ) { - $vary[ 'guest_mode' ] = 1; + if ($this->conf(Base::O_GUEST)) { + $vary['guest_mode'] = 1; } - if ( ! $uid ) { + if (!$uid) { $uid = get_current_user_id(); - } - else { - Debug2::debug( '[Vary] uid: ' . $uid ); + } else { + Debug2::debug('[Vary] uid: ' . $uid); } // get user's group id - $role = Router::get_role( $uid ); + $role = Router::get_role($uid); - if ( $uid > 0 && $role ) { - $vary[ 'logged-in' ] = 1; + if ($uid > 0 && $role) { + $vary['logged-in'] = 1; // parse role group from settings - if ( $role_group = $this->in_vary_group( $role ) ) { - $vary[ 'role' ] = $role_group; + if ($role_group = $this->in_vary_group($role)) { + $vary['role'] = $role_group; } // Get admin bar set // see @_get_admin_bar_pref() - $pref = get_user_option( 'show_admin_bar_front', $uid ); - Debug2::debug2( '[Vary] show_admin_bar_front: ' . $pref ); + $pref = get_user_option('show_admin_bar_front', $uid); + Debug2::debug2('[Vary] show_admin_bar_front: ' . $pref); $admin_bar = $pref === false || $pref === 'true'; - if ( $admin_bar ) { - $vary[ 'admin_bar' ] = 1; - Debug2::debug2( '[Vary] admin bar : true' ); + if ($admin_bar) { + $vary['admin_bar'] = 1; + Debug2::debug2('[Vary] admin bar : true'); } - - } - else { + } else { // Guest user - Debug2::debug( '[Vary] role id: failed, guest' ); - + Debug2::debug('[Vary] role id: failed, guest'); } /** @@ -508,24 +526,24 @@ public function finalize_default_vary( $uid = false ) { * @since 1.6.2 Hooked to webp (checked in v4, no webp anymore) * @since 3.0 Used by 3rd hooks too */ - $vary = apply_filters( 'litespeed_vary', $vary ); + $vary = apply_filters('litespeed_vary', $vary); - if ( ! $vary ) { + if (!$vary) { return false; } - ksort( $vary ); + ksort($vary); $res = array(); - foreach ( $vary as $key => $val ) { + foreach ($vary as $key => $val) { $res[] = $key . ':' . $val; } - $res = implode( ';', $res ); - if ( defined( 'LSCWP_LOG' ) ) { + $res = implode(';', $res); + if (defined('LSCWP_LOG')) { return $res; } // Encrypt in production - return md5( $this->conf( Base::HASH ) . $res ); + return md5($this->conf(Base::HASH) . $res); } /** @@ -533,9 +551,10 @@ public function finalize_default_vary( $uid = false ) { * * @since 4.0 */ - public function finalize_full_varies() { - $vary = $this->_finalize_curr_vary_cookies( true ); - $vary .= $this->finalize_default_vary( get_current_user_id() ); + public function finalize_full_varies() + { + $vary = $this->_finalize_curr_vary_cookies(true); + $vary .= $this->finalize_default_vary(get_current_user_id()); $vary .= $this->get_env_vary(); return $vary; } @@ -545,10 +564,11 @@ public function finalize_full_varies() { * * @since 4.0 */ - public function get_env_vary() { - $env_vary = isset( $_SERVER[ 'LSCACHE_VARY_VALUE' ] ) ? $_SERVER[ 'LSCACHE_VARY_VALUE' ] : false; - if ( ! $env_vary ) { - $env_vary = isset( $_SERVER[ 'HTTP_X_LSCACHE_VARY_VALUE' ] ) ? $_SERVER[ 'HTTP_X_LSCACHE_VARY_VALUE' ] : false; + public function get_env_vary() + { + $env_vary = isset($_SERVER['LSCACHE_VARY_VALUE']) ? $_SERVER['LSCACHE_VARY_VALUE'] : false; + if (!$env_vary) { + $env_vary = isset($_SERVER['HTTP_X_LSCACHE_VARY_VALUE']) ? $_SERVER['HTTP_X_LSCACHE_VARY_VALUE'] : false; } return $env_vary; } @@ -561,8 +581,9 @@ public function get_env_vary() { * @since 1.1.6 * @access public */ - public function append_commenter() { - $this->add_commenter( true ); + public function append_commenter() + { + $this->add_commenter(true); } /** @@ -572,15 +593,16 @@ public function append_commenter() { * @access private * @param boolean $from_redirect If the request is from redirect page or not */ - private function add_commenter( $from_redirect = false ) { + private function add_commenter($from_redirect = false) + { // If the cookie is lost somehow, set it - if ( self::has_vary() !== 'commenter' ) { - Debug2::debug( '[Vary] Add commenter' ); + if (self::has_vary() !== 'commenter') { + Debug2::debug('[Vary] Add commenter'); // $_COOKIE[ self::$_vary_name ] = 'commenter'; // not needed // save it // only set commenter status for current domain path - $this->_cookie( 'commenter', time() + apply_filters( 'comment_cookie_lifetime', 30000000 ), self::_relative_path( $from_redirect ) ); + $this->_cookie('commenter', time() + apply_filters('comment_cookie_lifetime', 30000000), self::_relative_path($from_redirect)); // Control::set_nocache( 'adding commenter status' ); } } @@ -591,14 +613,15 @@ private function add_commenter( $from_redirect = false ) { * @since 1.1.3 * @access private */ - private function remove_commenter() { - if ( self::has_vary() === 'commenter' ) { - Debug2::debug( '[Vary] Remove commenter' ); + private function remove_commenter() + { + if (self::has_vary() === 'commenter') { + Debug2::debug('[Vary] Remove commenter'); // remove logged in status from global var // unset( $_COOKIE[ self::$_vary_name ] ); // not needed // save it - $this->_cookie( false, false, self::_relative_path() ); + $this->_cookie(false, false, self::_relative_path()); // Control::set_nocache( 'removing commenter status' ); } } @@ -610,13 +633,14 @@ private function remove_commenter() { * @access private * @param boolean $from_redirect If the request is from redirect page or not */ - private static function _relative_path( $from_redirect = false ) { + private static function _relative_path($from_redirect = false) + { $path = false; $tag = $from_redirect ? 'HTTP_REFERER' : 'SCRIPT_URL'; - if ( ! empty( $_SERVER[ $tag ] ) ) { - $path = parse_url( $_SERVER[ $tag ] ); - $path = ! empty( $path[ 'path' ] ) ? $path[ 'path' ] : false; - Debug2::debug( '[Vary] Cookie Vary path: ' . $path ); + if (!empty($_SERVER[$tag])) { + $path = parse_url($_SERVER[$tag]); + $path = !empty($path['path']) ? $path['path'] : false; + Debug2::debug('[Vary] Cookie Vary path: ' . $path); } return $path; } @@ -633,20 +657,21 @@ private static function _relative_path( $from_redirect = false ) { * @global $post * @return mixed false if the user has the postpass cookie. Empty string if the post is not password protected. Vary header otherwise. */ - public function finalize() { + public function finalize() + { // Finalize default vary - if ( ! defined( 'LITESPEED_GUEST' ) || ! LITESPEED_GUEST ) { + if (!defined('LITESPEED_GUEST') || !LITESPEED_GUEST) { $this->_update_default_vary(); } $tp_cookies = $this->_finalize_curr_vary_cookies(); - if ( ! $tp_cookies ) { - Debug2::debug2( '[Vary] no custimzed vary' ); + if (!$tp_cookies) { + Debug2::debug2('[Vary] no custimzed vary'); return; } - return self::X_HEADER . ': ' . implode( ',', $tp_cookies ); + return self::X_HEADER . ': ' . implode(',', $tp_cookies); } /** @@ -656,39 +681,40 @@ public function finalize() { * @access private * @return array List of all vary cookies currently added. */ - private function _finalize_curr_vary_cookies( $values_json = false ) { + private function _finalize_curr_vary_cookies($values_json = false) + { global $post; $cookies = array(); // No need to append default vary cookie name - if ( ! empty( $post->post_password ) ) { + if (!empty($post->post_password)) { $postpass_key = 'wp-postpass_' . COOKIEHASH; - if ( $this->_get_cookie_val( $postpass_key ) ) { - Debug2::debug( '[Vary] finalize bypassed due to password protected vary ' ); + if ($this->_get_cookie_val($postpass_key)) { + Debug2::debug('[Vary] finalize bypassed due to password protected vary '); // If user has password cookie, do not cache & ignore existing vary cookies - Control::set_nocache( 'password protected vary' ); + Control::set_nocache('password protected vary'); return false; } - $cookies[] = $values_json ? $this->_get_cookie_val( $postpass_key ) : $postpass_key; + $cookies[] = $values_json ? $this->_get_cookie_val($postpass_key) : $postpass_key; } - $cookies = apply_filters( 'litespeed_vary_curr_cookies', $cookies ); - if ( $cookies ) { - $cookies = array_filter( array_unique( $cookies ) ); - Debug2::debug( '[Vary] vary cookies changed by filter litespeed_vary_curr_cookies', $cookies ); + $cookies = apply_filters('litespeed_vary_curr_cookies', $cookies); + if ($cookies) { + $cookies = array_filter(array_unique($cookies)); + Debug2::debug('[Vary] vary cookies changed by filter litespeed_vary_curr_cookies', $cookies); } - if ( ! $cookies ) { + if (!$cookies) { return false; } // Format cookie name data or value data - sort( $cookies ); // This is to maintain the cookie val orders for $values_json=true case. - foreach ( $cookies as $k => $v ) { - $cookies[ $k ] = $values_json ? $this->_get_cookie_val( $v ) : 'cookie=' . $v; + sort($cookies); // This is to maintain the cookie val orders for $values_json=true case. + foreach ($cookies as $k => $v) { + $cookies[$k] = $values_json ? $this->_get_cookie_val($v) : 'cookie=' . $v; } - return $values_json ? json_encode( $cookies ) : $cookies; + return $values_json ? json_encode($cookies) : $cookies; } /** @@ -696,9 +722,10 @@ private function _finalize_curr_vary_cookies( $values_json = false ) { * * @since 4.0 */ - private function _get_cookie_val( $key ) { - if ( ! empty( $_COOKIE[ $key ] ) ) { - return $_COOKIE[ $key ]; + private function _get_cookie_val($key) + { + if (!empty($_COOKIE[$key])) { + return $_COOKIE[$key]; } return false; @@ -715,8 +742,9 @@ private function _get_cookie_val( $key ) { * @param integer $expire Expire time. * @param boolean $path False if use wp root path as cookie path */ - private function _cookie($val = false, $expire = false, $path = false) { - if ( ! $val ) { + private function _cookie($val = false, $expire = false, $path = false) + { + if (!$val) { $expire = 1; } @@ -724,9 +752,8 @@ private function _cookie($val = false, $expire = false, $path = false) { * Add HTTPS bypass in case clients use both HTTP and HTTPS version of site * @since 1.7 */ - $is_ssl = $this->conf( Base::O_UTIL_NO_HTTPS_VARY ) ? false : is_ssl(); + $is_ssl = $this->conf(Base::O_UTIL_NO_HTTPS_VARY) ? false : is_ssl(); - setcookie( self::$_vary_name, $val, $expire, $path?: COOKIEPATH, COOKIE_DOMAIN, $is_ssl, true ); + setcookie(self::$_vary_name, $val, $expire, $path ?: COOKIEPATH, COOKIE_DOMAIN, $is_ssl, true); } - } diff --git a/src/vpi.cls.php b/src/vpi.cls.php index 37650e88e..c1656169e 100644 --- a/src/vpi.cls.php +++ b/src/vpi.cls.php @@ -1,24 +1,32 @@ _summary = self::get_summary(); } @@ -27,46 +35,49 @@ public function __construct() { * * @since 4.7 */ - public function add_to_queue() { + public function add_to_queue() + { $is_mobile = $this->_separate_mobile(); global $wp; - $request_url = home_url( $wp->request ); + $request_url = home_url($wp->request); - $ua = ! empty( $_SERVER[ 'HTTP_USER_AGENT' ] ) ? $_SERVER[ 'HTTP_USER_AGENT' ] : ''; + $ua = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; // Store it to prepare for cron - $this->_queue = $this->load_queue( 'vpi' ); + $this->_queue = $this->load_queue('vpi'); - if ( count( $this->_queue ) > 500 ) { - self::debug( 'Queue is full - 500' ); + if (count($this->_queue) > 500) { + self::debug('Queue is full - 500'); return; } - if ( ! is_singular() ) { - self::debug( 'not single post ID' ); + $home_id = get_option('page_for_posts'); + + if (!is_singular() && !($home_id > 0 && is_home())) { + self::debug('not single post ID'); return; } - $post_id = get_the_ID(); + $post_id = is_home() ? $home_id : get_the_ID(); - $queue_k = ( $is_mobile ? 'mobile' : '' ) . ' ' . $request_url; - if ( ! empty( $this->_queue[ $queue_k ] ) ) { - self::debug( 'queue k existed ' . $queue_k ); + $queue_k = ($is_mobile ? 'mobile' : '') . ' ' . $request_url; + if (!empty($this->_queue[$queue_k])) { + self::debug('queue k existed ' . $queue_k); return; } - $this->_queue[ $queue_k ] = array( - 'url' => apply_filters( 'litespeed_vpi_url', $request_url ), - 'post_id' => $post_id, - 'user_agent' => substr( $ua, 0, 200 ), - 'is_mobile' => $this->_separate_mobile(), + $this->_queue[$queue_k] = array( + 'url' => apply_filters('litespeed_vpi_url', $request_url), + 'post_id' => $post_id, + 'user_agent' => substr($ua, 0, 200), + 'is_mobile' => $this->_separate_mobile(), ); // Current UA will be used to request - $this->save_queue( 'vpi', $this->_queue ); - self::debug( 'Added queue_vpi [url] ' . $queue_k . ' [UA] ' . $ua ); + $this->save_queue('vpi', $this->_queue); + self::debug('Added queue_vpi [url] ' . $queue_k . ' [UA] ' . $ua); // Prepare cache tag for later purge - Tag::add( 'VPI.' . md5( $queue_k ) ); + Tag::add('VPI.' . md5($queue_k)); return null; } @@ -75,66 +86,69 @@ public function add_to_queue() { * Notify finished from server * @since 4.7 */ - public function notify() { + public function notify() + { $post_data = json_decode(file_get_contents('php://input'), true); - if( is_null( $post_data ) ) { + if (is_null($post_data)) { $post_data = $_POST; } - self::debug( 'notify() data', $post_data ); + self::debug('notify() data', $post_data); - $this->_queue = $this->load_queue( 'vpi' ); + $this->_queue = $this->load_queue('vpi'); // Validate key - if ( empty( $post_data[ 'domain_key' ] ) || $post_data[ 'domain_key' ] !== md5( $this->conf( self::O_API_KEY ) ) ) { - self::debug( '❌ notify wrong key' ); - self::save_summary( array( 'notify_ts_err' => time() ) ); - return Cloud::err( 'wrong_key' ); + if (empty($post_data['domain_key']) || $post_data['domain_key'] !== md5($this->conf(self::O_API_KEY))) { + self::debug('❌ notify wrong key'); + self::save_summary(array('notify_ts_err' => time())); + return Cloud::err('wrong_key'); } - list( $post_data ) = $this->cls( 'Cloud' )->extract_msg( $post_data, 'vpi' ); + list($post_data) = $this->cls('Cloud')->extract_msg($post_data, 'vpi'); - $notified_data = $post_data[ 'data' ]; - if ( empty( $notified_data ) || ! is_array( $notified_data ) ) { - self::debug( '❌ notify exit: no notified data' ); - return Cloud::err( 'no notified data' ); + $notified_data = $post_data['data']; + if (empty($notified_data) || !is_array($notified_data)) { + self::debug('❌ notify exit: no notified data'); + return Cloud::err('no notified data'); } // Check if its in queue or not $valid_i = 0; - foreach ( $notified_data as $v ) { - if ( empty( $v[ 'request_url' ] ) ) { - self::debug( '❌ notify bypass: no request_url', $v ); + foreach ($notified_data as $v) { + if (empty($v['request_url'])) { + self::debug('❌ notify bypass: no request_url', $v); continue; } - if ( empty( $v[ 'queue_k' ] ) ) { - self::debug( '❌ notify bypass: no queue_k', $v ); + if (empty($v['queue_k'])) { + self::debug('❌ notify bypass: no queue_k', $v); continue; } // $queue_k = ( $is_mobile ? 'mobile' : '' ) . ' ' . $v[ 'request_url' ]; - $queue_k = $v[ 'queue_k' ]; + $queue_k = $v['queue_k']; - if ( empty( $this->_queue[ $queue_k ] ) ) { - self::debug( '❌ notify bypass: no this queue [q_k]' . $queue_k ); + if (empty($this->_queue[$queue_k])) { + self::debug('❌ notify bypass: no this queue [q_k]' . $queue_k); continue; } // Save data - if ( ! empty( $v[ 'data_vpi' ] ) ) { - $post_id = $this->_queue[ $queue_k ][ 'post_id' ]; - $name = !empty( $v[ 'is_mobile' ] ) ? 'litespeed_vpi_list_mobile' : 'litespeed_vpi_list'; - $this->cls( 'Metabox' )->save( $post_id, $name, $v[ 'data_vpi' ] ); - - $valid_i ++; + if (!empty($v['data_vpi'])) { + $post_id = $this->_queue[$queue_k]['post_id']; + $name = !empty($v['is_mobile']) ? 'litespeed_vpi_list_mobile' : 'litespeed_vpi_list'; + $urldecode = is_array($v['data_vpi']) ? array_map('urldecode', $v['data_vpi']) : urldecode($v['data_vpi']); + self::debug('save data_vpi', $urldecode); + $this->cls('Metabox')->save($post_id, $name, $urldecode); + + $valid_i++; } - unset( $this->_queue[ $queue_k ] ); - self::debug( 'notify data handled, unset queue [q_k] ' . $queue_k ); + unset($this->_queue[$queue_k]); + self::debug('notify data handled, unset queue [q_k] ' . $queue_k); } - $this->save_queue( 'vpi', $this->_queue ); + $this->save_queue('vpi', $this->_queue); - self::debug( 'notified' ); + self::debug('notified'); - return Cloud::ok( array( 'count' => $valid_i ) ); + return Cloud::ok(array('count' => $valid_i)); } /** @@ -142,9 +156,10 @@ public function notify() { * * @since 4.7 */ - public static function cron( $continue = false ) { + public static function cron($continue = false) + { $_instance = self::cls(); - return $_instance->_cron_handler( $continue ); + return $_instance->_cron_handler($continue); } /** @@ -152,67 +167,69 @@ public static function cron( $continue = false ) { * * @since 4.7 */ - private function _cron_handler( $continue = false ) { - self::debug( 'cron start' ); - $this->_queue = $this->load_queue( 'vpi' ); + private function _cron_handler($continue = false) + { + self::debug('cron start'); + $this->_queue = $this->load_queue('vpi'); - if ( empty( $this->_queue ) ) { + if (empty($this->_queue)) { return; } // For cron, need to check request interval too - if ( ! $continue ) { - if ( ! empty( $this->_summary[ 'curr_request_vpi' ] ) && time() - $this->_summary[ 'curr_request_vpi' ] < 300 && ! $this->conf( self::O_DEBUG ) ) { - self::debug( 'Last request not done' ); + if (!$continue) { + if (!empty($this->_summary['curr_request_vpi']) && time() - $this->_summary['curr_request_vpi'] < 300 && !$this->conf(self::O_DEBUG)) { + self::debug('Last request not done'); return; } } $i = 0; - foreach ( $this->_queue as $k => $v ) { - if ( ! empty( $v[ '_status' ] ) ) { + foreach ($this->_queue as $k => $v) { + if (!empty($v['_status'])) { continue; } - self::debug( 'cron job [tag] ' . $k . ' [url] ' . $v[ 'url' ] . ( $v[ 'is_mobile' ] ? ' 📱 ' : '' ) . ' [UA] ' . $v[ 'user_agent' ] ); + self::debug('cron job [tag] ' . $k . ' [url] ' . $v['url'] . ($v['is_mobile'] ? ' 📱 ' : '') . ' [UA] ' . $v['user_agent']); - $i ++; - $res = $this->_send_req( $v[ 'url' ], $k, $v[ 'user_agent' ], $v[ 'is_mobile' ] ); - if ( ! $res ) { // Status is wrong, drop this this->_queue - $this->_queue = $this->load_queue( 'vpi' ); - unset( $this->_queue[ $k ] ); - $this->save_queue( 'vpi', $this->_queue ); + $i++; + $res = $this->_send_req($v['url'], $k, $v['user_agent'], $v['is_mobile']); + if (!$res) { + // Status is wrong, drop this this->_queue + $this->_queue = $this->load_queue('vpi'); + unset($this->_queue[$k]); + $this->save_queue('vpi', $this->_queue); - if ( ! $continue ) { + if (!$continue) { return; } // if ( $i > 3 ) { - GUI::print_loading( count( $this->_queue ), 'VPI' ); - return Router::self_redirect( Router::ACTION_VPI, self::TYPE_GEN ); + GUI::print_loading(count($this->_queue), 'VPI'); + return Router::self_redirect(Router::ACTION_VPI, self::TYPE_GEN); // } continue; } // Exit queue if out of quota - if ( $res === 'out_of_quota' ) { + if ($res === 'out_of_quota') { return; } - $this->_queue = $this->load_queue( 'vpi' ); - $this->_queue[ $k ][ '_status' ] = 'requested'; - $this->save_queue( 'vpi', $this->_queue ); - self::debug( 'Saved to queue [k] ' . $k ); + $this->_queue = $this->load_queue('vpi'); + $this->_queue[$k]['_status'] = 'requested'; + $this->save_queue('vpi', $this->_queue); + self::debug('Saved to queue [k] ' . $k); // only request first one - if ( ! $continue ) { + if (!$continue) { return; } // if ( $i > 3 ) { - GUI::print_loading( count( $this->_queue ), 'VPI' ); - return Router::self_redirect( Router::ACTION_VPI, self::TYPE_GEN ); + GUI::print_loading(count($this->_queue), 'VPI'); + return Router::self_redirect(Router::ACTION_VPI, self::TYPE_GEN); // } } } @@ -223,63 +240,64 @@ private function _cron_handler( $continue = false ) { * @since 4.7 * @access private */ - private function _send_req( $request_url, $queue_k, $user_agent, $is_mobile ) { + private function _send_req($request_url, $queue_k, $user_agent, $is_mobile) + { $svc = Cloud::SVC_VPI; // Check if has credit to push or not $err = false; - $allowance = $this->cls( 'Cloud' )->allowance( $svc, $err ); - if ( ! $allowance ) { - self::debug( '❌ No credit: ' . $err ); - $err && Admin_Display::error( Error::msg( $err ) ); + $allowance = $this->cls('Cloud')->allowance($svc, $err); + if (!$allowance) { + self::debug('❌ No credit: ' . $err); + $err && Admin_Display::error(Error::msg($err)); return 'out_of_quota'; } - set_time_limit( 120 ); + set_time_limit(120); // Update css request status - self::save_summary( array( 'curr_request_vpi' => time() ), true ); + self::save_summary(array('curr_request_vpi' => time()), true); // Gather guest HTML to send - $html = $this->cls('CSS')->prepare_html( $request_url, $user_agent ); + $html = $this->cls('CSS')->prepare_html($request_url, $user_agent); - if ( ! $html ) { + if (!$html) { return false; } // Parse HTML to gather all CSS content before requesting $css = false; - list( $css, $html ) = $this->cls( 'CSS' )->prepare_css( $html ); + list($css, $html) = $this->cls('CSS')->prepare_css($html); - if ( ! $css ) { - self::debug( '❌ No css' ); + if (!$css) { + self::debug('❌ No css'); return false; } $data = array( - 'url' => $request_url, - 'queue_k' => $queue_k, - 'user_agent' => $user_agent, - 'is_mobile' => $is_mobile ? 1 : 0, // todo:compatible w/ tablet - 'html' => $html, - 'css' => $css, + 'url' => $request_url, + 'queue_k' => $queue_k, + 'user_agent' => $user_agent, + 'is_mobile' => $is_mobile ? 1 : 0, // todo:compatible w/ tablet + 'html' => $html, + 'css' => $css, ); - self::debug( 'Generating: ', $data ); + self::debug('Generating: ', $data); - $json = Cloud::post( $svc, $data, 30 ); - if ( ! is_array( $json ) ) { + $json = Cloud::post($svc, $data, 30); + if (!is_array($json)) { return false; } // Unknown status, remove this line - if ( $json[ 'status' ] != 'queued' ) { + if ($json['status'] != 'queued') { return false; } // Save summary data self::reload_summary(); - $this->_summary[ 'last_spent_vpi' ] = time() - $this->_summary[ 'curr_request_vpi' ]; - $this->_summary[ 'last_request_vpi' ] = $this->_summary[ 'curr_request_vpi' ]; - $this->_summary[ 'curr_request_vpi' ] = 0; + $this->_summary['last_spent_vpi'] = time() - $this->_summary['curr_request_vpi']; + $this->_summary['last_request_vpi'] = $this->_summary['curr_request_vpi']; + $this->_summary['curr_request_vpi'] = 0; self::save_summary(); return true; @@ -290,16 +308,17 @@ private function _send_req( $request_url, $queue_k, $user_agent, $is_mobile ) { * * @since 4.7 */ - public function handler() { + public function handler() + { $type = Router::verify_type(); - switch ( $type ) { + switch ($type) { case self::TYPE_GEN: - self::cron( true ); + self::cron(true); break; case self::TYPE_CLEAR_Q: - $this->clear_q( 'vpi' ); + $this->clear_q('vpi'); break; default: @@ -308,5 +327,4 @@ public function handler() { Admin::redirect(); } - } diff --git a/thirdparty/aelia-currencyswitcher.cls.php b/thirdparty/aelia-currencyswitcher.cls.php index 26d8b840c..bde8402bf 100644 --- a/thirdparty/aelia-currencyswitcher.cls.php +++ b/thirdparty/aelia-currencyswitcher.cls.php @@ -10,17 +10,13 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -use \LiteSpeed\API; +use LiteSpeed\API; -class Aelia_CurrencySwitcher { - private static $_cookies = array( - 'aelia_cs_selected_currency', - 'aelia_customer_country', - 'aelia_customer_state', - 'aelia_tax_exempt', - ); +class Aelia_CurrencySwitcher +{ + private static $_cookies = array('aelia_cs_selected_currency', 'aelia_customer_country', 'aelia_customer_state', 'aelia_tax_exempt'); /** * Detects if WooCommerce is installed. @@ -28,17 +24,19 @@ class Aelia_CurrencySwitcher { * @since 1.0.13 * @access public */ - public static function detect() { - if ( defined('WOOCOMMERCE_VERSION') && isset($GLOBALS['woocommerce-aelia-currencyswitcher']) && is_object($GLOBALS['woocommerce-aelia-currencyswitcher']) ) { + public static function detect() + { + if (defined('WOOCOMMERCE_VERSION') && isset($GLOBALS['woocommerce-aelia-currencyswitcher']) && is_object($GLOBALS['woocommerce-aelia-currencyswitcher'])) { // Not all pages need to add vary, so need to use this API to set conditions - self::$_cookies = apply_filters( 'litespeed_3rd_aelia_cookies', self::$_cookies ); - add_filter( 'litespeed_vary_curr_cookies', __CLASS__ . '::check_cookies' ); // this is for vary response headers, only add when needed - add_filter( 'litespeed_vary_cookies', __CLASS__ . '::register_cookies' ); // this is for rewrite rules, so always add + self::$_cookies = apply_filters('litespeed_3rd_aelia_cookies', self::$_cookies); + add_filter('litespeed_vary_curr_cookies', __CLASS__ . '::check_cookies'); // this is for vary response headers, only add when needed + add_filter('litespeed_vary_cookies', __CLASS__ . '::register_cookies'); // this is for rewrite rules, so always add } } - public static function register_cookies( $list ) { - return array_merge( $list, self::$_cookies ); + public static function register_cookies($list) + { + return array_merge($list, self::$_cookies); } /** @@ -48,12 +46,13 @@ public static function register_cookies( $list ) { * @since 1.0.13 * @access public */ - public static function check_cookies( $list ) { + public static function check_cookies($list) + { // NOTE: is_cart and is_checkout should also be checked, but will be checked by woocommerce anyway. - if ( ! is_woocommerce() ) { + if (!is_woocommerce()) { return $list; } - return array_merge( $list, self::$_cookies ); + return array_merge($list, self::$_cookies); } } diff --git a/thirdparty/amp.cls.php b/thirdparty/amp.cls.php index 8d6f9e921..b905e46e5 100644 --- a/thirdparty/amp.cls.php +++ b/thirdparty/amp.cls.php @@ -7,29 +7,31 @@ * @subpackage LiteSpeed_Cache/thirdparty * @author LiteSpeed Technologies */ -namespace LiteSpeed\Thirdparty ; +namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit ; +defined('WPINC') || exit(); -use \LiteSpeed\API ; +use LiteSpeed\API; -class AMP { +class AMP +{ /** * @since 4.2 */ - private static function _maybe_amp( $amp_function ) { - if ( is_admin() ) { + private static function _maybe_amp($amp_function) + { + if (is_admin()) { return; } - if ( ! isset( $_GET[ 'amp' ] ) && ( ! function_exists( $amp_function ) || ! $amp_function() ) ) { + if (!isset($_GET['amp']) && (!function_exists($amp_function) || !$amp_function())) { return; } - do_action( 'litespeed_debug', '[3rd] ❌ AMP disabled page optm/lazy' ); + do_action('litespeed_debug', '[3rd] ❌ AMP disabled page optm/lazy'); - ! defined( 'LITESPEED_NO_PAGEOPTM' ) && define( 'LITESPEED_NO_PAGEOPTM', true ); - ! defined( 'LITESPEED_NO_LAZY' ) && define( 'LITESPEED_NO_LAZY', true ); - ! defined( 'LITESPEED_NO_OPTM' ) && define( 'LITESPEED_NO_OPTM', true ); + !defined('LITESPEED_NO_PAGEOPTM') && define('LITESPEED_NO_PAGEOPTM', true); + !defined('LITESPEED_NO_LAZY') && define('LITESPEED_NO_LAZY', true); + !defined('LITESPEED_NO_OPTM') && define('LITESPEED_NO_OPTM', true); // ! defined( 'LITESPEED_GUEST' ) && define( 'LITESPEED_GUEST', false ); } @@ -38,8 +40,9 @@ private static function _maybe_amp( $amp_function ) { * * @since 4.2 */ - public static function maybe_acc_mob_pages() { - self::_maybe_amp( 'ampforwp_is_amp_endpoint' ); + public static function maybe_acc_mob_pages() + { + self::_maybe_amp('ampforwp_is_amp_endpoint'); } /** @@ -47,8 +50,9 @@ public static function maybe_acc_mob_pages() { * * @since 4.2.0.1 */ - public static function maybe_google_amp() { - self::_maybe_amp( 'amp_is_request' ); + public static function maybe_google_amp() + { + self::_maybe_amp('amp_is_request'); } /** @@ -59,9 +63,10 @@ public static function maybe_google_amp() { * @since 2.9.8.6 * @access public */ - public static function preload() { - add_action( 'wp', __CLASS__ . '::maybe_acc_mob_pages' ); - add_action( 'wp', __CLASS__ . '::maybe_google_amp' ); + public static function preload() + { + add_action('wp', __CLASS__ . '::maybe_acc_mob_pages'); + add_action('wp', __CLASS__ . '::maybe_google_amp'); // amp_is_request() from AMP // self::maybe_amp( 'amp_is_request' ); diff --git a/thirdparty/autoptimize.cls.php b/thirdparty/autoptimize.cls.php index 9306c5c93..46498cf9c 100644 --- a/thirdparty/autoptimize.cls.php +++ b/thirdparty/autoptimize.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Autoptimize { @@ -18,8 +18,8 @@ class Autoptimize */ public static function detect() { - if ( defined( 'AUTOPTIMIZE_PLUGIN_DIR' ) ) { - add_action( 'litespeed_purge_finalize', __CLASS__ . '::purge' ); + if (defined('AUTOPTIMIZE_PLUGIN_DIR')) { + add_action('litespeed_purge_finalize', __CLASS__ . '::purge'); } } @@ -31,8 +31,8 @@ public static function detect() */ public static function purge() { - if ( defined( 'AUTOPTIMIZE_PURGE' ) || has_action( 'shutdown', 'autoptimize_do_cachepurged_action', 11 ) ) { - do_action( 'litespeed_purge_all', '3rd Autoptimize' ); + if (defined('AUTOPTIMIZE_PURGE') || has_action('shutdown', 'autoptimize_do_cachepurged_action', 11)) { + do_action('litespeed_purge_all', '3rd Autoptimize'); } } } diff --git a/thirdparty/avada.cls.php b/thirdparty/avada.cls.php index 815d94f05..54b0b9a1c 100644 --- a/thirdparty/avada.cls.php +++ b/thirdparty/avada.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Avada { @@ -18,12 +18,12 @@ class Avada */ public static function detect() { - if ( ! defined( 'AVADA_VERSION' ) ) { + if (!defined('AVADA_VERSION')) { return; } - add_action( 'update_option_avada_dynamic_css_posts', __CLASS__ . '::flush' ); - add_action( 'update_option_fusion_options', __CLASS__ . '::flush' ); + add_action('update_option_avada_dynamic_css_posts', __CLASS__ . '::flush'); + add_action('update_option_fusion_options', __CLASS__ . '::flush'); } /** @@ -34,8 +34,6 @@ public static function detect() */ public static function flush() { - do_action( 'litespeed_purge_all', '3rd avada' ); + do_action('litespeed_purge_all', '3rd avada'); } - } - diff --git a/thirdparty/bbpress.cls.php b/thirdparty/bbpress.cls.php index d67e1df63..84d6d21a5 100644 --- a/thirdparty/bbpress.cls.php +++ b/thirdparty/bbpress.cls.php @@ -6,9 +6,9 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -use \LiteSpeed\Router; +use LiteSpeed\Router; class BBPress { @@ -20,10 +20,11 @@ class BBPress */ public static function detect() { - if ( function_exists( 'is_bbpress' ) ) { - add_action('litespeed_api_purge_post', __CLASS__ . '::on_purge' );//todo - if ( apply_filters( 'litespeed_esi_status', false ) ) {// don't consider private cache yet (will do if any feedback) - add_action( 'litespeed_control_finalize', __CLASS__ . '::set_control' ); + if (function_exists('is_bbpress')) { + add_action('litespeed_api_purge_post', __CLASS__ . '::on_purge'); //todo + if (apply_filters('litespeed_esi_status', false)) { + // don't consider private cache yet (will do if any feedback) + add_action('litespeed_control_finalize', __CLASS__ . '::set_control'); } } } @@ -36,13 +37,13 @@ public static function detect() */ public static function set_control() { - if ( ! apply_filters( 'litespeed_control_cacheable', false ) ) { + if (!apply_filters('litespeed_control_cacheable', false)) { return; } // set non ESI public - if ( is_bbpress() && Router::is_logged_in() ) { - do_action( 'litespeed_control_set_nocache', 'bbpress nocache due to loggedin' ); + if (is_bbpress() && Router::is_logged_in()) { + do_action('litespeed_control_set_nocache', 'bbpress nocache due to loggedin'); } } @@ -56,33 +57,32 @@ public static function set_control() */ public static function on_purge($post_id) { - if ( ! is_bbpress() ) { - if ( ! function_exists( 'bbp_is_forum' ) || ! function_exists( 'bbp_is_topic' ) || ! function_exists( 'bbp_is_reply' ) ) { + if (!is_bbpress()) { + if (!function_exists('bbp_is_forum') || !function_exists('bbp_is_topic') || !function_exists('bbp_is_reply')) { return; } - if ( ! bbp_is_forum( $post_id ) && ! bbp_is_topic( $post_id ) && ! bbp_is_reply( $post_id ) ) { + if (!bbp_is_forum($post_id) && !bbp_is_topic($post_id) && !bbp_is_reply($post_id)) { return; } } // Need to purge base forums page, bbPress page was updated. - do_action( 'litespeed_purge_posttype', bbp_get_forum_post_type() ); - $ancestors = get_post_ancestors( $post_id ); + do_action('litespeed_purge_posttype', bbp_get_forum_post_type()); + $ancestors = get_post_ancestors($post_id); // If there are ancestors, need to purge them as well. - if ( ! empty( $ancestors ) ) { - foreach ( $ancestors as $ancestor ) { - do_action( 'litespeed_purge_post', $ancestor ); + if (!empty($ancestors)) { + foreach ($ancestors as $ancestor) { + do_action('litespeed_purge_post', $ancestor); } } global $wp_widget_factory; - if ( bbp_is_reply( $post_id ) && ! is_null( $wp_widget_factory->widgets[ 'BBP_Replies_Widget' ] ) ) { - do_action( 'litespeed_purge_widget', $wp_widget_factory->widgets[ 'BBP_Replies_Widget' ]->id ); + if (bbp_is_reply($post_id) && !is_null($wp_widget_factory->widgets['BBP_Replies_Widget'])) { + do_action('litespeed_purge_widget', $wp_widget_factory->widgets['BBP_Replies_Widget']->id); } - if ( bbp_is_topic( $post_id ) && ! is_null( $wp_widget_factory->widgets[ 'BBP_Topics_Widget' ] ) ) { - do_action( 'litespeed_purge_widget', $wp_widget_factory->widgets[ 'BBP_Topics_Widget' ]->id ); + if (bbp_is_topic($post_id) && !is_null($wp_widget_factory->widgets['BBP_Topics_Widget'])) { + do_action('litespeed_purge_widget', $wp_widget_factory->widgets['BBP_Topics_Widget']->id); } } } - diff --git a/thirdparty/beaver-builder.cls.php b/thirdparty/beaver-builder.cls.php index f2b2bc4ee..6fb581979 100644 --- a/thirdparty/beaver-builder.cls.php +++ b/thirdparty/beaver-builder.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Beaver_Builder { @@ -18,7 +18,7 @@ class Beaver_Builder */ public static function detect() { - if ( ! defined( 'FL_BUILDER_VERSION' ) ) { + if (!defined('FL_BUILDER_VERSION')) { return; } @@ -26,15 +26,10 @@ public static function detect() * Purge All hooks * @see beaver-builder/extensions/fi-builder-cache-helper/classes/class-fi-builder-cache-helper.php */ - $actions = array( - 'fl_builder_cache_cleared', - 'fl_builder_after_save_layout', - 'fl_builder_after_save_user_template', - 'upgrader_process_complete', - ); + $actions = array('fl_builder_cache_cleared', 'fl_builder_after_save_layout', 'fl_builder_after_save_user_template', 'upgrader_process_complete'); - foreach ( $actions as $val ) { - add_action( $val, __CLASS__ . '::purge' ); + foreach ($actions as $val) { + add_action($val, __CLASS__ . '::purge'); } } @@ -46,6 +41,6 @@ public static function detect() */ public static function purge() { - do_action( 'litespeed_purge_all', '3rd Beaver_Builder' ); + do_action('litespeed_purge_all', '3rd Beaver_Builder'); } } diff --git a/thirdparty/caldera-forms.cls.php b/thirdparty/caldera-forms.cls.php index 164a1b89f..ef2929964 100644 --- a/thirdparty/caldera-forms.cls.php +++ b/thirdparty/caldera-forms.cls.php @@ -6,13 +6,17 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Caldera_Forms { - public static function detect() { - if ( ! defined( 'CFCORE_VER' ) ) return; +class Caldera_Forms +{ + public static function detect() + { + if (!defined('CFCORE_VER')) { + return; + } // plugins/caldera-forms/classes/render/nonce.php -> class Caldera_Forms_Render_Nonce - do_action( 'litespeed_nonce', 'caldera_forms_front_*' ); + do_action('litespeed_nonce', 'caldera_forms_front_*'); } -} \ No newline at end of file +} diff --git a/thirdparty/divi-theme-builder.cls.php b/thirdparty/divi-theme-builder.cls.php index 3ca71a5bb..63f248f8f 100644 --- a/thirdparty/divi-theme-builder.cls.php +++ b/thirdparty/divi-theme-builder.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Divi_Theme_Builder { @@ -20,31 +20,35 @@ class Divi_Theme_Builder */ public static function preload() { - if ( ! function_exists( 'et_setup_theme' ) ) return; - if ( ! empty( $_GET[ 'et_fb' ] ) || ! empty( $_GET[ 'et_pb_preview' ] ) ) { - do_action( 'litespeed_disable_all', 'divi edit mode' ); + if (!function_exists('et_setup_theme')) { + return; + } + if (!empty($_GET['et_fb']) || !empty($_GET['et_pb_preview']) || (!empty($_GET['p']) && !empty($_GET['preview']) && $_GET['preview'] === 'true')) { + do_action('litespeed_disable_all', 'divi edit mode'); } } public static function detect() { - if ( ! defined( 'ET_CORE' ) ) return; + if (!defined('ET_CORE')) { + return; + } // As DIVI will set page to non-cacheable for the 1st visit to generate CCSS, will need to ignore that no-cache for crawler - defined( 'LITESPEED_CRAWLER_IGNORE_NONCACHEABLE' ) || define( 'LITESPEED_CRAWLER_IGNORE_NONCACHEABLE', true ); + defined('LITESPEED_CRAWLER_IGNORE_NONCACHEABLE') || define('LITESPEED_CRAWLER_IGNORE_NONCACHEABLE', true); /** * Add contact form to nonce * @since 2.9.7.1 #475461 */ - do_action( 'litespeed_nonce', 'et-pb-contact-form-submit' ); + do_action('litespeed_nonce', 'et-pb-contact-form-submit'); /** * Subscribe module and A/B logging * @since 3.0 @Robert Staddon */ - do_action( 'litespeed_nonce', 'et_frontend_nonce' ); - do_action( 'litespeed_nonce', 'et_ab_log_nonce' ); + do_action('litespeed_nonce', 'et_frontend_nonce'); + do_action('litespeed_nonce', 'et_ab_log_nonce'); /* // the comment box fix is for user using theme builder, ESI will load the wrong json string diff --git a/thirdparty/elementor.cls.php b/thirdparty/elementor.cls.php index 9b36a85d1..0bd003135 100644 --- a/thirdparty/elementor.cls.php +++ b/thirdparty/elementor.cls.php @@ -5,40 +5,45 @@ * @since 2.9.8.8 */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -use \LiteSpeed\Debug2; +use LiteSpeed\Debug2; class Elementor { public static function preload() { - if ( ! defined( 'ELEMENTOR_VERSION' ) ) { + if (!defined('ELEMENTOR_VERSION')) { return; } - if ( ! is_admin() ) { -// add_action( 'init', __CLASS__ . '::disable_litespeed_esi', 4 ); // temporarily comment out this line for backward compatibility + if (!is_admin()) { + // add_action( 'init', __CLASS__ . '::disable_litespeed_esi', 4 ); // temporarily comment out this line for backward compatibility } - if ( isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] === 'elementor' ) { - do_action( 'litespeed_disable_all', 'elementor edit mode' ); + if (isset($_GET['action']) && $_GET['action'] === 'elementor') { + do_action('litespeed_disable_all', 'elementor edit mode'); } - if ( ! empty( $_SERVER[ 'HTTP_REFERER' ] ) && strpos( $_SERVER[ 'HTTP_REFERER' ], 'action=elementor' ) ) { - if ( ! empty( $_REQUEST['actions'] ) ) { - $json = json_decode( stripslashes( $_REQUEST['actions'] ), true ); + if (!empty($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'action=elementor')) { + if (!empty($_REQUEST['actions'])) { + $json = json_decode(stripslashes($_REQUEST['actions']), true); // Debug2::debug( '3rd Elementor', $json ); - if ( ! empty( $json[ 'save_builder' ][ 'action' ] ) && $json[ 'save_builder' ][ 'action' ] == 'save_builder' && ! empty( $json[ 'save_builder' ][ 'data' ][ 'status' ] ) && $json[ 'save_builder' ][ 'data' ][ 'status' ] == 'publish' ) { + if ( + !empty($json['save_builder']['action']) && + $json['save_builder']['action'] == 'save_builder' && + !empty($json['save_builder']['data']['status']) && + $json['save_builder']['data']['status'] == 'publish' + ) { return; // Save post, don't disable all in case we will allow fire crawler right away after purged } } - do_action( 'litespeed_disable_all', 'elementor edit mode in HTTP_REFERER' ); + do_action('litespeed_disable_all', 'elementor edit mode in HTTP_REFERER'); } } public static function disable_litespeed_esi() { - define( 'LITESPEED_ESI_OFF', true ); + define('LITESPEED_ESI_OFF', true); } } diff --git a/thirdparty/entry.inc.php b/thirdparty/entry.inc.php index 86379d283..5a8b6827c 100644 --- a/thirdparty/entry.inc.php +++ b/thirdparty/entry.inc.php @@ -10,9 +10,9 @@ * a common place for plugin authors to append their file to. * */ -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -use \LiteSpeed\API; +use LiteSpeed\API; $third_cls = array( 'Aelia_CurrencySwitcher', @@ -39,15 +39,15 @@ 'Yith_Wishlist', ); -foreach ( $third_cls as $cls ) { - add_action( 'litespeed_load_thirdparty', 'LiteSpeed\Thirdparty\\' . $cls . '::detect' ) ; +foreach ($third_cls as $cls) { + add_action('litespeed_load_thirdparty', 'LiteSpeed\Thirdparty\\' . $cls . '::detect'); } // Preload needed for certain thirdparty -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\Divi_Theme_Builder::preload' ); -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\WooCommerce::preload' ); -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\NextGenGallery::preload' ); -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\AMP::preload' ); -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\Elementor::preload' ); -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\Gravity_Forms::preload' ); -add_action( 'litespeed_init', 'LiteSpeed\Thirdparty\Perfmatters::preload' ); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\Divi_Theme_Builder::preload'); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\WooCommerce::preload'); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\NextGenGallery::preload'); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\AMP::preload'); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\Elementor::preload'); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\Gravity_Forms::preload'); +add_action('litespeed_init', 'LiteSpeed\Thirdparty\Perfmatters::preload'); diff --git a/thirdparty/facetwp.cls.php b/thirdparty/facetwp.cls.php index 88c026906..23261b0a3 100644 --- a/thirdparty/facetwp.cls.php +++ b/thirdparty/facetwp.cls.php @@ -6,30 +6,27 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Facetwp { public static function detect() { - if ( ! defined( 'FACETWP_VERSION' ) ) return; - /** + if (!defined('FACETWP_VERSION')) { + return; + } + /** * For Facetwp, if the template is "wp", return the buffered HTML * So marked as rest call to put is_json to ESI */ - if ( - ! empty( $_POST['action'] ) - && ! empty( $_POST['data'] ) - && ! empty( $_POST['data']['template'] ) - && $_POST['data']['template'] === 'wp' - ) { - add_filter( 'litespeed_esi_params', __CLASS__ . '::set_is_json' ); + if (!empty($_POST['action']) && !empty($_POST['data']) && !empty($_POST['data']['template']) && $_POST['data']['template'] === 'wp') { + add_filter('litespeed_esi_params', __CLASS__ . '::set_is_json'); } } - public static function set_is_json( $params ) + public static function set_is_json($params) { - $params[ 'is_json' ] = 1; + $params['is_json'] = 1; return $params; } -} \ No newline at end of file +} diff --git a/thirdparty/gravity-forms.cls.php b/thirdparty/gravity-forms.cls.php index dca390f1e..b99eee6b9 100644 --- a/thirdparty/gravity-forms.cls.php +++ b/thirdparty/gravity-forms.cls.php @@ -6,21 +6,21 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Gravity_Forms { - /** - * Check if GF is enabled and disable LSCWP on gf-download and gf-signature URI - * - * @since 4.1.0 #900899 #827184 - */ - public static function preload() - { - if ( class_exists( 'GFCommon' ) ) { - if ( isset( $_GET['gf-download'] ) || isset( $_GET['gf-signature'] ) ) { - do_action( 'litespeed_disable_all', 'Stopped for Gravity Form' ); - } - } - } + /** + * Check if GF is enabled and disable LSCWP on gf-download and gf-signature URI + * + * @since 4.1.0 #900899 #827184 + */ + public static function preload() + { + if (class_exists('GFCommon')) { + if (isset($_GET['gf-download']) || isset($_GET['gf-signature'])) { + do_action('litespeed_disable_all', 'Stopped for Gravity Form'); + } + } + } } diff --git a/thirdparty/litespeed-check.cls.php b/thirdparty/litespeed-check.cls.php index a3a2f05b8..2994e1512 100644 --- a/thirdparty/litespeed-check.cls.php +++ b/thirdparty/litespeed-check.cls.php @@ -1,4 +1,5 @@ ' . + esc_html__('Please consider disabling the following detected plugins, as they may conflict with LiteSpeed Cache:', 'litespeed-cache') . + '

    ' . + 'PageSpeed Ninja' . + '

    ' . + '
', + false, + true + ); + } } - public static function activated_plugin( $plugin, $network_wide ) { - self::incompatible_plugin_notice( $plugin, $network_wide, 'activated' ); + public static function activated_plugin($plugin, $network_wide) + { + self::incompatible_plugin_notice($plugin, $network_wide, 'activated'); } - public static function deactivated_plugin( $plugin, $network_wide ) { - self::incompatible_plugin_notice( $plugin, $network_wide, 'deactivated' ); + public static function deactivated_plugin($plugin, $network_wide) + { + self::incompatible_plugin_notice($plugin, $network_wide, 'deactivated'); } /** * Detect any incompatible plugins that are currently `active` and `valid`. * Show a notification if there are any. */ - public static function incompatible_plugin_notice( $plugin, $_network_wide, $action ) { + public static function incompatible_plugin_notice($plugin, $_network_wide, $action) + { self::update_messages(); /** @@ -85,37 +105,30 @@ public static function incompatible_plugin_notice( $plugin, $_network_wide, $act * `wp_get_active_and_valid_plugins` can see the change, so we'll need to * remove `$plugin` from the list. */ - $deactivated = 'deactivated' === $action ? array( $plugin ) : array(); + $deactivated = 'deactivated' === $action ? array($plugin) : array(); - $incompatible_plugins = - array_map( - function( $plugin ) { return WP_PLUGIN_DIR . '/' . $plugin; }, - array_diff( self::$_incompatible_plugins, $deactivated ) - ); + $incompatible_plugins = array_map(function ($plugin) { + return WP_PLUGIN_DIR . '/' . $plugin; + }, array_diff(self::$_incompatible_plugins, $deactivated)); - $active_incompatible_plugins = - array_map( - function( $plugin ) { - $plugin = get_plugin_data( $plugin, false, true ); - return $plugin['Name']; - }, - array_intersect( $incompatible_plugins, wp_get_active_and_valid_plugins() ) - ); + $active_incompatible_plugins = array_map(function ($plugin) { + $plugin = get_plugin_data($plugin, false, true); + return $plugin['Name']; + }, array_intersect($incompatible_plugins, wp_get_active_and_valid_plugins())); - if ( empty( $active_incompatible_plugins ) ) { + if (empty($active_incompatible_plugins)) { return; } \LiteSpeed\Admin_Display::error( - '
' - . esc_html__( - 'Please consider disabling the following detected plugins, as they may conflict with LiteSpeed Cache:', - 'litespeed-cache' - ) - . '

' - . implode( ', ', $active_incompatible_plugins ) - . '

' - . '
', + '
' . + esc_html__('Please consider disabling the following detected plugins, as they may conflict with LiteSpeed Cache:', 'litespeed-cache') . + '

' . + implode(', ', $active_incompatible_plugins) . + '

' . + '
', false, true ); @@ -126,23 +139,17 @@ function( $plugin ) { * a number of incompatible plugins in succession without dismissing the * notice(s). */ - private static function update_messages() { - $messages = - \LiteSpeed\Admin_Display::get_option( - \LiteSpeed\Admin_Display::DB_MSG_PIN, - array() - ); - if ( is_array( $messages ) ) { - foreach ( $messages as $index => $message ) { - if ( strpos( $message, self::$_msg_id ) !== false ) { - unset( $messages[ $index ] ); - if ( ! $messages ) { + private static function update_messages() + { + $messages = \LiteSpeed\Admin_Display::get_option(\LiteSpeed\Admin_Display::DB_MSG_PIN, array()); + if (is_array($messages)) { + foreach ($messages as $index => $message) { + if (strpos($message, self::$_msg_id) !== false) { + unset($messages[$index]); + if (!$messages) { $messages = -1; } - \LiteSpeed\Admin_Display::update_option( - \LiteSpeed\Admin_Display::DB_MSG_PIN, - $messages - ); + \LiteSpeed\Admin_Display::update_option(\LiteSpeed\Admin_Display::DB_MSG_PIN, $messages); break; } } diff --git a/thirdparty/nextgengallery.cls.php b/thirdparty/nextgengallery.cls.php index a264372c2..fcbd7a0a8 100644 --- a/thirdparty/nextgengallery.cls.php +++ b/thirdparty/nextgengallery.cls.php @@ -4,9 +4,9 @@ * * @since 1.0.5 */ -namespace LiteSpeed\Thirdparty ; +namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit ; +defined('WPINC') || exit(); // Try preload instead // todo: need test @@ -14,9 +14,9 @@ class NextGenGallery { - const CACHETAG_ALBUMS = 'NGG_A.' ; - const CACHETAG_GALLERIES = 'NGG_G.' ; - const CACHETAG_TAGS = 'NGG_T.' ; + const CACHETAG_ALBUMS = 'NGG_A.'; + const CACHETAG_GALLERIES = 'NGG_G.'; + const CACHETAG_TAGS = 'NGG_T.'; /** * Detect is triggered at the load_nextgen_gallery_modules action. @@ -28,21 +28,21 @@ class NextGenGallery */ public static function preload() { - add_action( 'ngg_added_new_image', __CLASS__ . '::add_image' ) ; - add_action( 'ngg_ajax_image_save', __CLASS__ . '::update_image' ) ; - add_action( 'ngg_delete_picture', __CLASS__ . '::delete_image' ) ; - add_action( 'ngg_moved_images', __CLASS__ . '::move_image', 10, 3 ) ; - add_action( 'ngg_copied_images', __CLASS__ . '::copy_image', 10, 3 ) ; - add_action( 'ngg_generated_image', __CLASS__ . '::gen_image' ) ; - add_action( 'ngg_recovered_image', __CLASS__ . '::gen_image' ) ; + add_action('ngg_added_new_image', __CLASS__ . '::add_image'); + add_action('ngg_ajax_image_save', __CLASS__ . '::update_image'); + add_action('ngg_delete_picture', __CLASS__ . '::delete_image'); + add_action('ngg_moved_images', __CLASS__ . '::move_image', 10, 3); + add_action('ngg_copied_images', __CLASS__ . '::copy_image', 10, 3); + add_action('ngg_generated_image', __CLASS__ . '::gen_image'); + add_action('ngg_recovered_image', __CLASS__ . '::gen_image'); - add_action( 'ngg_gallery_sort', __CLASS__ . '::update_gallery' ) ; - add_action( 'ngg_delete_gallery', __CLASS__ . '::update_gallery' ) ; + add_action('ngg_gallery_sort', __CLASS__ . '::update_gallery'); + add_action('ngg_delete_gallery', __CLASS__ . '::update_gallery'); - add_action( 'ngg_update_album', __CLASS__ . '::update_album' ) ; - add_action( 'ngg_delete_album', __CLASS__ . '::update_album' ) ; + add_action('ngg_update_album', __CLASS__ . '::update_album'); + add_action('ngg_delete_album', __CLASS__ . '::update_album'); - add_filter( 'ngg_displayed_gallery_cache_params', __CLASS__ . '::add_container' ) ; + add_filter('ngg_displayed_gallery_cache_params', __CLASS__ . '::add_container'); } /** @@ -54,12 +54,12 @@ public static function preload() */ public static function add_image($image) { - if ( ! $image || ! method_exists( $image, 'get_gallery' ) ) { - return ; + if (!$image || !method_exists($image, 'get_gallery')) { + return; } - $gallery = $image->get_gallery() ; - if ( $gallery && $gallery->pageid ) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $gallery->pageid ) ; + $gallery = $image->get_gallery(); + if ($gallery && $gallery->pageid) { + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $gallery->pageid); } } @@ -71,37 +71,34 @@ public static function add_image($image) */ public static function update_image() { - if ( isset( $_REQUEST[ 'gallery_id' ] ) ) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . sanitize_key( $_REQUEST[ 'gallery_id' ] ) ); - return ; + if (isset($_REQUEST['gallery_id'])) { + do_action('litespeed_purge', self::CACHETAG_GALLERIES . sanitize_key($_REQUEST['gallery_id'])); + return; } - if ( isset( $_POST[ 'task_list' ] ) ) { - $task_list = str_replace( '\\', '', $_POST[ 'task_list' ] ) ; - $task_list = json_decode( $task_list, true ) ; + if (isset($_POST['task_list'])) { + $task_list = str_replace('\\', '', $_POST['task_list']); + $task_list = json_decode($task_list, true); - if ( ! empty( $task_list[ 0 ][ 'query' ][ 'id' ] ) ) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . sanitize_key( $task_list[ 0 ][ 'query' ][ 'id' ] ) ); - return ; + if (!empty($task_list[0]['query']['id'])) { + do_action('litespeed_purge', self::CACHETAG_GALLERIES . sanitize_key($task_list[0]['query']['id'])); + return; } } - if ( isset($_POST['id']) ) { - $id = (int)$_POST['id'] ; + if (isset($_POST['id'])) { + $id = (int) $_POST['id']; + } elseif (isset($_POST['image'])) { + $id = (int) $_POST['image']; + } elseif (isset($_GET['pid'])) { + $id = (int) $_GET['pid']; + } else { + error_log('LiteSpeed_Cache hit ngg_ajax_image_save with no post image id.'); + return; } - elseif ( isset($_POST['image']) ) { - $id = (int)$_POST['image'] ; - } - elseif ( isset($_GET['pid']) ) { - $id = (int)$_GET['pid'] ; - } - else { - error_log('LiteSpeed_Cache hit ngg_ajax_image_save with no post image id.') ; - return ; - } - $image = \C_Image_Mapper::get_instance()->find($id) ; - if ( $image ) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $image->galleryid ); + $image = \C_Image_Mapper::get_instance()->find($id); + if ($image) { + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $image->galleryid); } } @@ -113,8 +110,8 @@ public static function update_image() */ public static function delete_image() { - if ( isset($_GET['gid']) ) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . sanitize_key( $_GET['gid'] ) ); + if (isset($_GET['gid'])) { + do_action('litespeed_purge', self::CACHETAG_GALLERIES . sanitize_key($_GET['gid'])); } } @@ -130,9 +127,9 @@ public static function delete_image() public static function move_image($images, $old_gallery_ids, $new_gallery_id) { foreach ($old_gallery_ids as $gid) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $gid ); + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $gid); } - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $new_gallery_id ); + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $new_gallery_id); } /** @@ -144,7 +141,7 @@ public static function move_image($images, $old_gallery_ids, $new_gallery_id) */ public static function copy_image($image_pid_map, $old_gallery_ids, $new_gallery_id) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $new_gallery_id ); + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $new_gallery_id); } /** @@ -155,7 +152,7 @@ public static function copy_image($image_pid_map, $old_gallery_ids, $new_gallery */ public static function gen_image($image) { - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $image->galleryid ); + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $image->galleryid); } /** @@ -168,11 +165,11 @@ public static function gen_image($image) public static function update_gallery($gid) { // New version input will be an object with gid value - if ( is_object( $gid ) && ! empty( $gid->gid ) ) { - $gid = $gid->gid ; + if (is_object($gid) && !empty($gid->gid)) { + $gid = $gid->gid; } - do_action( 'litespeed_purge', self::CACHETAG_GALLERIES . $gid ); + do_action('litespeed_purge', self::CACHETAG_GALLERIES . $gid); } /** @@ -184,7 +181,7 @@ public static function update_gallery($gid) */ public static function update_album($aid) { - do_action( 'litespeed_purge', self::CACHETAG_ALBUMS . $aid ); + do_action('litespeed_purge', self::CACHETAG_ALBUMS . $aid); } /** @@ -199,31 +196,30 @@ public static function update_album($aid) public static function add_container($render_parms) { // Check if null. If it is null, can't continue. - if ( is_null($render_parms) ) { - return null ; + if (is_null($render_parms)) { + return null; } - $src = $render_parms[0]->source ; - $container_ids = $render_parms[0]->container_ids ; + $src = $render_parms[0]->source; + $container_ids = $render_parms[0]->container_ids; // Can switch on first char if we end up with more sources. switch ($src) { case 'albums': - $tag = self::CACHETAG_ALBUMS ; - break ; + $tag = self::CACHETAG_ALBUMS; + break; case 'galleries': - $tag = self::CACHETAG_GALLERIES ; - break ; + $tag = self::CACHETAG_GALLERIES; + break; case 'tags': - $tag = self::CACHETAG_TAGS ; - break ; + $tag = self::CACHETAG_TAGS; + break; default: - return $render_parms ; + return $render_parms; } foreach ($container_ids as $id) { - do_action( 'litespeed_tag_add', $tag . $id ); + do_action('litespeed_tag_add', $tag . $id); } - return $render_parms ; + return $render_parms; } } - diff --git a/thirdparty/perfmatters.cls.php b/thirdparty/perfmatters.cls.php index a60b7feb7..84a283f03 100644 --- a/thirdparty/perfmatters.cls.php +++ b/thirdparty/perfmatters.cls.php @@ -5,20 +5,27 @@ * @since 4.4.5 */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class Perfmatters { - public static function preload() { - if ( ! defined( 'PERFMATTERS_VERSION' ) ) return; +class Perfmatters +{ + public static function preload() + { + if (!defined('PERFMATTERS_VERSION')) { + return; + } - if ( is_admin() ) return; + if (is_admin()) { + return; + } - if ( has_action( 'shutdown','perfmatters_script_manager' ) !== false ) { - add_action( 'init', __CLASS__ . '::disable_litespeed_esi', 4 ); + if (has_action('shutdown', 'perfmatters_script_manager') !== false) { + add_action('init', __CLASS__ . '::disable_litespeed_esi', 4); } } - public static function disable_litespeed_esi() { - defined( 'LITESPEED_ESI_OFF' ) || define( 'LITESPEED_ESI_OFF', true ); + public static function disable_litespeed_esi() + { + defined('LITESPEED_ESI_OFF') || define('LITESPEED_ESI_OFF', true); } } diff --git a/thirdparty/theme-my-login.cls.php b/thirdparty/theme-my-login.cls.php index 71ee7d4db..2fd6134eb 100644 --- a/thirdparty/theme-my-login.cls.php +++ b/thirdparty/theme-my-login.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Theme_My_Login { @@ -19,8 +19,8 @@ class Theme_My_Login */ public static function detect() { - if ( defined( 'THEME_MY_LOGIN_PATH' ) ) { - add_action( 'litespeed_control_finalize', __CLASS__ . '::set_control' ); + if (defined('THEME_MY_LOGIN_PATH')) { + add_action('litespeed_control_finalize', __CLASS__ . '::set_control'); } } @@ -32,14 +32,13 @@ public static function detect() */ public static function set_control() { - if ( ! apply_filters( 'litespeed_control_cacheable', false ) ) { + if (!apply_filters('litespeed_control_cacheable', false)) { return; } // check if this page is TML page or not - if ( class_exists( 'Theme_My_Login' ) && \Theme_My_Login::is_tml_page() ) { - do_action( 'litespeed_control_set_nocache', 'Theme My Login' ); + if (class_exists('Theme_My_Login') && \Theme_My_Login::is_tml_page()) { + do_action('litespeed_control_set_nocache', 'Theme My Login'); } } - -} \ No newline at end of file +} diff --git a/thirdparty/user-switching.cls.php b/thirdparty/user-switching.cls.php index 8b192b630..dd56114ce 100644 --- a/thirdparty/user-switching.cls.php +++ b/thirdparty/user-switching.cls.php @@ -6,20 +6,22 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class User_Switching { public static function detect() { - if ( ! defined( 'user_switching' ) ) return; + if (!defined('user_switching')) { + return; + } /** * Register switch back URL nonce * @since 3.0 @Robert Staddon */ - if ( function_exists( 'current_user_switched' ) && $old_user = current_user_switched() ) { - do_action( 'litespeed_nonce', 'switch_to_olduser_' . $old_user->ID ); + if (function_exists('current_user_switched') && ($old_user = current_user_switched())) { + do_action('litespeed_nonce', 'switch_to_olduser_' . $old_user->ID); } } } diff --git a/thirdparty/wc-pdf-product-vouchers.cls.php b/thirdparty/wc-pdf-product-vouchers.cls.php index 91cb5d9a7..5d0c4b0f1 100644 --- a/thirdparty/wc-pdf-product-vouchers.cls.php +++ b/thirdparty/wc-pdf-product-vouchers.cls.php @@ -6,28 +6,26 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class WC_PDF_Product_Vouchers { +class WC_PDF_Product_Vouchers +{ /** * Do not cache generated vouchers * * @since 5.1.0 */ - public static function detect() { - if ( ! class_exists( '\WC_PDF_Product_Vouchers_Loader' ) ) { + public static function detect() + { + if (!class_exists('\WC_PDF_Product_Vouchers_Loader')) { return; } - $is_voucher = - ! empty( $_GET['post_type'] ) - && 'wc_voucher' === $_GET['post_type']; - $has_key = - ! empty( $_GET['voucher_key'] ) - || ! empty( $_GET['key'] ); + $is_voucher = !empty($_GET['post_type']) && 'wc_voucher' === $_GET['post_type']; + $has_key = !empty($_GET['voucher_key']) || !empty($_GET['key']); - if ( $is_voucher && $has_key ) { - do_action( 'litespeed_control_set_nocache', '3rd WC PDF Product Voucher' ); + if ($is_voucher && $has_key) { + do_action('litespeed_control_set_nocache', '3rd WC PDF Product Voucher'); } } } diff --git a/thirdparty/wcml.cls.php b/thirdparty/wcml.cls.php index 63690cb74..394f67a3a 100644 --- a/thirdparty/wcml.cls.php +++ b/thirdparty/wcml.cls.php @@ -6,36 +6,42 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -class WCML { +class WCML +{ private static $_currency = ''; public static function detect() { - if ( ! defined( 'WCML_VERSION' ) ) return; + if (!defined('WCML_VERSION')) { + return; + } - add_filter( 'wcml_client_currency', __CLASS__ . '::apply_client_currency' ); - add_action( 'wcml_set_client_currency', __CLASS__ . '::set_client_currency' ); + add_filter('wcml_client_currency', __CLASS__ . '::apply_client_currency'); + add_action('wcml_set_client_currency', __CLASS__ . '::set_client_currency'); } - public static function set_client_currency( $currency ) { - self::apply_client_currency( $currency ); + public static function set_client_currency($currency) + { + self::apply_client_currency($currency); - do_action( 'litespeed_vary_ajax_force' ); + do_action('litespeed_vary_ajax_force'); } - public static function apply_client_currency( $currency ) { - if ( $currency !== wcml_get_woocommerce_currency_option() ) { + public static function apply_client_currency($currency) + { + if ($currency !== wcml_get_woocommerce_currency_option()) { self::$_currency = $currency; - add_filter( 'litespeed_vary', __CLASS__ . '::apply_vary' ); + add_filter('litespeed_vary', __CLASS__ . '::apply_vary'); } return $currency; } - public static function apply_vary( $list ) { - $list[ 'wcml_currency' ] = self::$_currency; + public static function apply_vary($list) + { + $list['wcml_currency'] = self::$_currency; return $list; } -} \ No newline at end of file +} diff --git a/thirdparty/woo-paypal.cls.php b/thirdparty/woo-paypal.cls.php index fa2e28847..c64f66843 100644 --- a/thirdparty/woo-paypal.cls.php +++ b/thirdparty/woo-paypal.cls.php @@ -6,16 +6,18 @@ * @since 3.0 */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class Woo_Paypal { public static function detect() { - if ( ! defined( 'WC_GATEWAY_PPEC_VERSION' ) ) return; + if (!defined('WC_GATEWAY_PPEC_VERSION')) { + return; + } - do_action( 'litespeed_nonce', '_wc_ppec_update_shipping_costs_nonce private' ); - do_action( 'litespeed_nonce', '_wc_ppec_start_checkout_nonce private' ); - do_action( 'litespeed_nonce', '_wc_ppec_generate_cart_nonce private' ); + do_action('litespeed_nonce', '_wc_ppec_update_shipping_costs_nonce private'); + do_action('litespeed_nonce', '_wc_ppec_start_checkout_nonce private'); + do_action('litespeed_nonce', '_wc_ppec_generate_cart_nonce private'); } } diff --git a/thirdparty/woocommerce.cls.php b/thirdparty/woocommerce.cls.php index 9b8008bfd..2c7dc7dd8 100644 --- a/thirdparty/woocommerce.cls.php +++ b/thirdparty/woocommerce.cls.php @@ -1,4 +1,5 @@ */ + namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -use \LiteSpeed\API; -use \LiteSpeed\Base; +use LiteSpeed\API; +use LiteSpeed\Base; -class WooCommerce extends Base { +class WooCommerce extends Base +{ const O_CACHE_TTL_FRONTPAGE = Base::O_CACHE_TTL_FRONTPAGE; - const CACHETAG_SHOP = 'WC_S' ; - const CACHETAG_TERM = 'WC_T.' ; - const O_ESI_CACHE_CART = 'wc_esi_cache_cart'; - const O_UPDATE_INTERVAL = 'wc_update_interval' ; - const O_SHOP_FRONT_TTL = 'wc_shop_use_front_ttl' ; - const O_WOO_CACHE_CART = 'woo_cache_cart' ; - const O_PQS_CS = 0 ; // flush product on quantity + stock change, categories on stock change - const O_PS_CS = 1 ; // flush product and categories on stock change - const O_PS_CN = 2 ; // flush product on stock change, categories no flush - const O_PQS_CQS = 3 ; // flush product and categories on quantity + stock change - - const ESI_PARAM_ARGS = 'wc_args' ; - const ESI_PARAM_POSTID = 'wc_post_id' ; - const ESI_PARAM_NAME = 'wc_name' ; - const ESI_PARAM_PATH = 'wc_path' ; - const ESI_PARAM_LOCATED = 'wc_located' ; - - private $cache_cart ; - private $esi_enabled ; + const CACHETAG_SHOP = 'WC_S'; + const CACHETAG_TERM = 'WC_T.'; + const O_UPDATE_INTERVAL = 'wc_update_interval'; + const O_CART_VARY = 'wc_cart_vary'; + const O_PQS_CS = 0; // flush product on quantity + stock change, categories on stock change + const O_PS_CS = 1; // flush product and categories on stock change + const O_PS_CN = 2; // flush product on stock change, categories no flush + const O_PQS_CQS = 3; // flush product and categories on quantity + stock change + + const ESI_PARAM_ARGS = 'wc_args'; + const ESI_PARAM_POSTID = 'wc_post_id'; + const ESI_PARAM_NAME = 'wc_name'; + const ESI_PARAM_PATH = 'wc_path'; + const ESI_PARAM_LOCATED = 'wc_located'; + + private $esi_enabled; /** * Detects if WooCommerce is installed. @@ -46,12 +46,11 @@ class WooCommerce extends Base { */ public static function detect() { - if ( ! defined( 'WOOCOMMERCE_VERSION' ) ) { - return ; + if (!defined('WOOCOMMERCE_VERSION')) { + return; } - self::cls()->add_hooks() ; - + self::cls()->add_hooks(); } /** @@ -62,74 +61,48 @@ public static function detect() */ public function add_hooks() { - $this->_option_append() ; + $this->_option_append(); - $this->cache_cart = apply_filters( 'litespeed_conf', self::O_WOO_CACHE_CART ) ; - $this->esi_enabled = apply_filters( 'litespeed_esi_status', false ); + $this->esi_enabled = apply_filters('litespeed_esi_status', false); - add_action( 'litespeed_control_finalize', array( $this, 'set_control' ) ); - add_action( 'litespeed_tag_finalize', array( $this, 'set_tag' ) ); + add_action('litespeed_control_finalize', array($this, 'set_control')); + add_action('litespeed_tag_finalize', array($this, 'set_tag')); // Purging a product on stock change should only occur during product purchase. This function will add the purging callback when an order is complete. - add_action( 'woocommerce_product_set_stock', array( $this, 'purge_product' ) ) ; - add_action( 'woocommerce_variation_set_stock', array( $this, 'purge_product' ) ) ; // #984479 Update variations stock + add_action('woocommerce_product_set_stock', array($this, 'purge_product')); + add_action('woocommerce_variation_set_stock', array($this, 'purge_product')); // #984479 Update variations stock - add_action( 'comment_post', array( $this, 'add_review' ), 10, 3 ) ; + add_action('comment_post', array($this, 'add_review'), 10, 3); - if ( $this->esi_enabled ) { - if ( function_exists( 'is_shop' ) && ! is_shop() ) { - add_action( 'litespeed_tpl_normal', array( $this, 'set_block_template' ) ); + if ($this->esi_enabled) { + if (function_exists('is_shop') && !is_shop()) { + add_action('litespeed_tpl_normal', array($this, 'set_block_template')); // No need for add-to-cart button // add_action( 'litespeed_esi_load-wc-add-to-cart-form', array( $this, 'load_add_to_cart_form_block' ) ) ; - add_action( 'litespeed_esi_load-storefront-cart-header', array( $this, 'load_cart_header' ) ); - add_action( 'litespeed_esi_load-widget', array( $this, 'register_post_view' ) ); - } - - if ( function_exists( 'is_product' ) && is_product() ) { - add_filter( 'litespeed_esi_params', array( $this, 'add_post_id' ), 10, 2 ); + add_action('litespeed_esi_load-storefront-cart-header', array($this, 'load_cart_header')); + add_action('litespeed_esi_load-widget', array($this, 'register_post_view')); } - /** - * Only when cart is not empty, give it an ESI with private cache - * Call when template_include to make sure woo cart is initialized - * @since 1.7.2 - */ - if ( apply_filters( 'litespeed_conf', self::O_ESI_CACHE_CART ) ) { - add_action( 'template_include', array( $this, 'check_if_need_esi' ) ); - add_filter( 'litespeed_vary', array( $this, 'vary_maintain' ) ); + if (function_exists('is_product') && is_product()) { + add_filter('litespeed_esi_params', array($this, 'add_post_id'), 10, 2); } - } - if ( is_admin() ) { - add_action('litespeed_api_purge_post', array( $this, 'backend_purge' ) ) ;//todo - add_action( 'delete_term_relationships', array( $this, 'delete_rel' ), 10, 2 ) ; - add_action( 'litespeed_settings_tab', array( $this, 'settings_add_tab' ) ); - add_action( 'litespeed_settings_content', array( $this, 'settings_add_content' ) ); - add_filter( 'litespeed_widget_default_options', array( $this, 'wc_widget_default' ), 10, 2 ); - } - - // Purge cart if is ESI / Purge private if not enabled ESI - if ( $this->cache_cart ) { - $hooks_to_purge = array( - 'woocommerce_add_to_cart', 'woocommerce_ajax_added_to_cart', - 'woocommerce_remove_cart_item', - 'woocommerce_restore_cart_item', - 'woocommerce_after_cart_item_quantity_update', - 'woocommerce_applied_coupon', 'woocommerce_removed_coupon', - 'woocommerce_checkout_order_processed', - ) ; - foreach ( $hooks_to_purge as $v ) { - if ( $this->esi_enabled ) { - add_action( $v, array( $this, 'purge_esi' ) ) ; - } - else { - add_action( $v, array( $this, 'purge_private_all' ) ) ; - } - } + if (is_admin()) { + add_action('litespeed_api_purge_post', array($this, 'backend_purge')); //todo + add_action('delete_term_relationships', array($this, 'delete_rel'), 10, 2); + add_action('litespeed_settings_tab', array($this, 'settings_add_tab')); + add_action('litespeed_settings_content', array($this, 'settings_add_content')); + add_filter('litespeed_widget_default_options', array($this, 'wc_widget_default'), 10, 2); } + if (apply_filters('litespeed_conf', self::O_CART_VARY)) { + add_filter('litespeed_vary_cookies', function ($list) { + $list[] = 'woocommerce_cart_hash'; + return array_unique($list); + }); + } } /** @@ -140,9 +113,8 @@ public function add_hooks() */ public function purge_esi() { - do_action( 'litespeed_debug', '3rd woo purge ESI in action: ' . current_filter() ) ; - do_action( 'litespeed_purge_private_esi', 'storefront-cart-header' ); - + do_action('litespeed_debug', '3rd woo purge ESI in action: ' . current_filter()); + do_action('litespeed_purge_private_esi', 'storefront-cart-header'); } /** @@ -153,7 +125,7 @@ public function purge_esi() */ public function purge_private_all() { - do_action( 'litespeed_purge_private_all' ); + do_action('litespeed_purge_private_all'); } /** @@ -162,15 +134,14 @@ public function purge_private_all() * @since 1.7.2 * @access public */ - public function check_if_need_esi( $template ) + public function check_if_need_esi($template) { - if ( $this->vary_needed() ) { - do_action( 'litespeed_debug', 'API: 3rd woo added ESI' ); - add_action( 'litespeed_tpl_normal', array( $this, 'set_swap_header_cart' ) ); + if ($this->vary_needed()) { + do_action('litespeed_debug', 'API: 3rd woo added ESI'); + add_action('litespeed_tpl_normal', array($this, 'set_swap_header_cart')); } return $template; - } /** @@ -179,10 +150,11 @@ public function check_if_need_esi( $template ) * @since 1.7.2 * @access public */ - public function vary_maintain( $vary ) { - if ( $this->vary_needed() ) { - do_action( 'litespeed_debug', 'API: 3rd woo added vary due to cart not empty' ); - $vary[ 'woo_cart' ] = 1; + public function vary_maintain($vary) + { + if ($this->vary_needed()) { + do_action('litespeed_debug', 'API: 3rd woo added vary due to cart not empty'); + $vary['woo_cart'] = 1; } return $vary; @@ -196,19 +168,19 @@ public function vary_maintain( $vary ) { */ private function vary_needed() { - if ( ! function_exists( 'WC' ) ) { - return false ; + if (!function_exists('WC')) { + return false; } - $woocom = WC() ; - if ( ! $woocom ) { - return false ; + $woocom = WC(); + if (!$woocom) { + return false; } - if ( is_null( $woocom->cart ) ) { - return false ; + if (is_null($woocom->cart)) { + return false; } - return $woocom->cart->get_cart_contents_count() > 0 ; + return $woocom->cart->get_cart_contents_count() > 0; } /** @@ -220,7 +192,7 @@ private function vary_needed() */ public function set_block_template() { - add_action('woocommerce_before_template_part', array( $this, 'block_template' ), 999, 4) ; + add_action('woocommerce_before_template_part', array($this, 'block_template'), 999, 4); } /** @@ -236,10 +208,10 @@ public function set_block_template() */ public function set_swap_header_cart() { - $priority = has_action('storefront_header', 'storefront_header_cart') ; - if ( $priority !== false ) { - remove_action('storefront_header', 'storefront_header_cart', $priority) ; - add_action('storefront_header', array( $this, 'esi_cart_header' ), $priority) ; + $priority = has_action('storefront_header', 'storefront_header_cart'); + if ($priority !== false) { + remove_action('storefront_header', 'storefront_header_cart', $priority); + add_action('storefront_header', array($this, 'esi_cart_header'), $priority); } } @@ -254,33 +226,30 @@ public function set_swap_header_cart() */ public function block_template($template_name, $template_path, $located, $args) { - if ( strpos($template_name, 'add-to-cart') === false ) { - if ( strpos($template_name, 'related.php') !== false ) { - remove_action('woocommerce_before_template_part', array( $this, 'block_template' ), 999) ; - add_filter('woocommerce_related_products_args', array( $this, 'add_related_tags' ) ) ; - add_action('woocommerce_after_template_part', array( $this, 'end_template' ), 999) ; + if (strpos($template_name, 'add-to-cart') === false) { + if (strpos($template_name, 'related.php') !== false) { + remove_action('woocommerce_before_template_part', array($this, 'block_template'), 999); + add_filter('woocommerce_related_products_args', array($this, 'add_related_tags')); + add_action('woocommerce_after_template_part', array($this, 'end_template'), 999); } - return ; + return; } - return ; - - + return; + // todo: wny not use? - // todo: wny not use? - - global $post ; + global $post; $params = array( self::ESI_PARAM_ARGS => $args, self::ESI_PARAM_NAME => $template_name, self::ESI_PARAM_POSTID => $post->ID, self::ESI_PARAM_PATH => $template_path, - self::ESI_PARAM_LOCATED => $located - ) ; - add_action('woocommerce_after_add_to_cart_form', array( $this, 'end_form' ) ) ; - add_action('woocommerce_after_template_part', array( $this, 'end_form' ), 999) ; - echo apply_filters( 'litespeed_esi_url', 'wc-add-to-cart-form', 'WC_CART_FORM', $params ); - echo apply_filters( 'litespeed_clean_wrapper_begin', '' ); + self::ESI_PARAM_LOCATED => $located, + ); + add_action('woocommerce_after_add_to_cart_form', array($this, 'end_form')); + add_action('woocommerce_after_template_part', array($this, 'end_form'), 999); + echo apply_filters('litespeed_esi_url', 'wc-add-to-cart-form', 'WC_CART_FORM', $params); + echo apply_filters('litespeed_clean_wrapper_begin', ''); } /** @@ -294,12 +263,12 @@ public function block_template($template_name, $template_path, $located, $args) */ public function end_form($template_name = '') { - if ( ! empty($template_name) && strpos($template_name, 'add-to-cart') === false ) { - return ; + if (!empty($template_name) && strpos($template_name, 'add-to-cart') === false) { + return; } - echo apply_filters( 'litespeed_clean_wrapper_end', '' ); - remove_action('woocommerce_after_add_to_cart_form', array( $this, 'end_form' ) ) ; - remove_action('woocommerce_after_template_part', array( $this, 'end_form' ), 999) ; + echo apply_filters('litespeed_clean_wrapper_end', ''); + remove_action('woocommerce_after_add_to_cart_form', array($this, 'end_form')); + remove_action('woocommerce_after_template_part', array($this, 'end_form'), 999); } /** @@ -315,14 +284,14 @@ public function end_form($template_name = '') */ public function add_related_tags($args) { - if ( empty($args) || ! isset($args['post__in']) ) { - return $args ; + if (empty($args) || !isset($args['post__in'])) { + return $args; } - $related_posts = $args['post__in'] ; - foreach ( $related_posts as $related ) { - do_action( 'litespeed_tag_add_post', $related ); + $related_posts = $args['post__in']; + foreach ($related_posts as $related) { + do_action('litespeed_tag_add_post', $related); } - return $args ; + return $args; } /** @@ -336,9 +305,9 @@ public function add_related_tags($args) */ public function end_template($template_name) { - if ( strpos($template_name, 'related.php') !== false ) { - remove_action('woocommerce_after_template_part', array( $this, 'end_template' ), 999) ; - $this->set_block_template() ; + if (strpos($template_name, 'related.php') !== false) { + remove_action('woocommerce_after_template_part', array($this, 'end_template'), 999); + $this->set_block_template(); } } @@ -352,7 +321,7 @@ public function end_template($template_name) */ public function esi_cart_header() { - echo apply_filters( 'litespeed_esi_url', 'storefront-cart-header', 'STOREFRONT_CART_HEADER' ); + echo apply_filters('litespeed_esi_url', 'storefront-cart-header', 'STOREFRONT_CART_HEADER'); } /** @@ -382,10 +351,10 @@ public function load_cart_header() */ public function load_add_to_cart_form_block($params) { - global $post, $wp_query ; - $post = get_post($params[self::ESI_PARAM_POSTID]) ; - $wp_query->setup_postdata($post) ; - function_exists( 'wc_get_template' ) && wc_get_template($params[self::ESI_PARAM_NAME], $params[self::ESI_PARAM_ARGS], $params[self::ESI_PARAM_PATH]) ; + global $post, $wp_query; + $post = get_post($params[self::ESI_PARAM_POSTID]); + $wp_query->setup_postdata($post); + function_exists('wc_get_template') && wc_get_template($params[self::ESI_PARAM_NAME], $params[self::ESI_PARAM_ARGS], $params[self::ESI_PARAM_PATH]); } /** @@ -401,23 +370,23 @@ function_exists( 'wc_get_template' ) && wc_get_template($params[self::ESI_PARAM_ */ public function register_post_view($params) { - if ( $params[API::PARAM_NAME] !== 'WC_Widget_Recently_Viewed' ) { - return ; + if ($params[API::PARAM_NAME] !== 'WC_Widget_Recently_Viewed') { + return; } - if ( ! isset($params[self::ESI_PARAM_POSTID]) ) { - return ; + if (!isset($params[self::ESI_PARAM_POSTID])) { + return; } - $id = $params[self::ESI_PARAM_POSTID] ; - $esi_post = get_post($id) ; - $product = function_exists( 'wc_get_product' ) ? wc_get_product($esi_post) : false ; + $id = $params[self::ESI_PARAM_POSTID]; + $esi_post = get_post($id); + $product = function_exists('wc_get_product') ? wc_get_product($esi_post) : false; - if ( empty($product) ) { - return ; + if (empty($product)) { + return; } - global $post ; - $post = $esi_post ; - function_exists( 'wc_track_product_view' ) && wc_track_product_view() ; + global $post; + $post = $esi_post; + function_exists('wc_track_product_view') && wc_track_product_view(); } /** @@ -428,11 +397,11 @@ function_exists( 'wc_track_product_view' ) && wc_track_product_view() ; * @since 1.1.0 * @access public */ - public function add_post_id( $params, $block_id ) + public function add_post_id($params, $block_id) { - if ( $block_id == 'widget' ) { - if ( $params[ API::PARAM_NAME ] == 'WC_Widget_Recently_Viewed' ) { - $params[ self::ESI_PARAM_POSTID ] = get_the_ID(); + if ($block_id == 'widget') { + if ($params[API::PARAM_NAME] == 'WC_Widget_Recently_Viewed') { + $params[self::ESI_PARAM_POSTID] = get_the_ID(); } } @@ -448,19 +417,18 @@ public function add_post_id( $params, $block_id ) * @since 1.1.0 * @access public */ - public function wc_widget_default( $options, $widget ) + public function wc_widget_default($options, $widget) { - if ( ! is_array( $options ) ) { + if (!is_array($options)) { return $options; } - $widget_name = get_class( $widget ) ; - if ( $widget_name === 'WC_Widget_Recently_Viewed' ) { - $options[ API::WIDGET_O_ESIENABLE ] = API::VAL_ON2; - $options[ API::WIDGET_O_TTL ] = 0; - } - elseif ( $widget_name === 'WC_Widget_Recent_Reviews' ) { - $options[ API::WIDGET_O_ESIENABLE ] = API::VAL_ON; - $options[ API::WIDGET_O_TTL ] = 86400; + $widget_name = get_class($widget); + if ($widget_name === 'WC_Widget_Recently_Viewed') { + $options[API::WIDGET_O_ESIENABLE] = API::VAL_ON2; + $options[API::WIDGET_O_TTL] = 0; + } elseif ($widget_name === 'WC_Widget_Recent_Reviews') { + $options[API::WIDGET_O_ESIENABLE] = API::VAL_ON; + $options[API::WIDGET_O_TTL] = 86400; } return $options; } @@ -474,51 +442,49 @@ public function wc_widget_default( $options, $widget ) */ public function set_tag() { - $id = get_the_ID() ; - if ( $id === false ) { - return ; + $id = get_the_ID(); + if ($id === false) { + return; } // Check if product has a cache ttl limit or not - $sale_from = get_post_meta( $id, '_sale_price_dates_from', true ) ; - $sale_to = get_post_meta( $id, '_sale_price_dates_to', true ) ; - $now = current_time( 'timestamp' ) ; - $ttl = false ; - if ( $sale_from && $now < $sale_from ) { - $ttl = $sale_from - $now ; - } - elseif ( $sale_to && $now < $sale_to ) { - $ttl = $sale_to - $now ; + $sale_from = (int) get_post_meta($id, '_sale_price_dates_from', true); + $sale_to = (int) get_post_meta($id, '_sale_price_dates_to', true); + $now = current_time('timestamp'); + $ttl = false; + if ($sale_from && $now < $sale_from) { + $ttl = $sale_from - $now; + } elseif ($sale_to && $now < $sale_to) { + $ttl = $sale_to - $now; } - if ( $ttl && $ttl < apply_filters( 'litespeed_control_ttl', 0 ) ) { - do_action( 'litespeed_control_set_ttl', $ttl, "WooCommerce set scheduled TTL to $ttl" ) ; + if ($ttl && $ttl < apply_filters('litespeed_control_ttl', 0)) { + do_action('litespeed_control_set_ttl', $ttl, "WooCommerce set scheduled TTL to $ttl"); } - if ( function_exists( 'is_shop' ) && is_shop() ) { - do_action( 'litespeed_tag_add', self::CACHETAG_SHOP ); - } - if ( function_exists( 'is_product_taxonomy' ) && ! is_product_taxonomy() ) { - return ; - } - if ( isset($GLOBALS['product_cat']) && is_string( $GLOBALS['product_cat'] ) ) { // todo: need to check previous woo version to find if its from old woo versions or not! - $term = get_term_by('slug', $GLOBALS['product_cat'], 'product_cat') ; + if (function_exists('is_shop') && is_shop()) { + do_action('litespeed_tag_add', self::CACHETAG_SHOP); } - elseif ( isset($GLOBALS['product_tag']) && is_string( $GLOBALS['product_tag'] ) ) { - $term = get_term_by('slug', $GLOBALS['product_tag'], 'product_tag') ; + if (function_exists('is_product_taxonomy') && !is_product_taxonomy()) { + return; } - else { - $term = false ; + if (isset($GLOBALS['product_cat']) && is_string($GLOBALS['product_cat'])) { + // todo: need to check previous woo version to find if its from old woo versions or not! + $term = get_term_by('slug', $GLOBALS['product_cat'], 'product_cat'); + } elseif (isset($GLOBALS['product_tag']) && is_string($GLOBALS['product_tag'])) { + $term = get_term_by('slug', $GLOBALS['product_tag'], 'product_tag'); + } else { + $term = false; } - if ( $term === false ) { - return ; + if ($term === false) { + return; } - while ( isset($term) ) { - do_action( 'litespeed_tag_add', self::CACHETAG_TERM . $term->term_id ); - if ( $term->parent == 0 ) { - break ; + while (isset($term)) { + do_action('litespeed_tag_add', self::CACHETAG_TERM . $term->term_id); + if ($term->parent == 0) { + break; } - $term = get_term($term->parent) ; + $term = get_term($term->parent); } } @@ -528,12 +494,12 @@ public function set_tag() * @since 1.0.5 * @since 1.6.3 Removed static * @access public - * @param string $esi_id The ESI block id if a request is an ESI request. + * @param string $esi_id The ESI block id if a request is an ESI request. * @return boolean True if cacheable, false if not. */ public function set_control($esi_id) { - if ( ! apply_filters( 'litespeed_control_cacheable', false ) ) { + if (!apply_filters('litespeed_control_cacheable', false)) { return; } @@ -541,98 +507,63 @@ public function set_control($esi_id) * Avoid possible 500 issue * @since 1.6.2.1 */ - if ( ! function_exists( 'WC' ) ) { - return ; - } - - $woocom = WC() ; - if ( ! isset($woocom) ) { - return ; + if (!function_exists('WC')) { + return; } - // Set TTL - if ( function_exists( 'is_shop' ) && is_shop() ) { - if ( apply_filters( 'litespeed_conf', self::O_SHOP_FRONT_TTL ) ) { - do_action( 'litespeed_control_set_ttl', apply_filters( 'litespeed_conf', self::O_CACHE_TTL_FRONTPAGE ) ); - } + $woocom = WC(); + if (!$woocom || empty($woocom->session)) { + return; } // For later versions, DONOTCACHEPAGE should be set. // No need to check uri/qs. - if ( version_compare($woocom->version, '1.4.2', '>=') ) { - if ( version_compare( $woocom->version, '3.2.0', '<' ) && defined('DONOTCACHEPAGE') && DONOTCACHEPAGE ) { - do_action( 'litespeed_control_set_nocache', '3rd party woocommerce not cache by constant' ); - return ; - } - elseif ( version_compare($woocom->version, '2.1.0', '>=') ) { - $err = false ; - - if ( ! function_exists( 'wc_get_page_id' ) ) { - return ; + if (version_compare($woocom->version, '1.4.2', '>=')) { + if (version_compare($woocom->version, '3.2.0', '<') && defined('DONOTCACHEPAGE') && DONOTCACHEPAGE) { + do_action('litespeed_control_set_nocache', '3rd party woocommerce not cache by constant'); + return; + } elseif (version_compare($woocom->version, '2.1.0', '>=')) { + $err = false; + + if (!function_exists('wc_get_page_id')) { + return; } /** * From woo/inc/class-wc-cache-helper.php:prevent_caching() * @since 1.4 */ - $page_ids = array_filter( array( wc_get_page_id( 'cart' ), wc_get_page_id( 'checkout' ), wc_get_page_id( 'myaccount' ) ) ); - if ( isset( $_GET['download_file'] ) || isset( $_GET['add-to-cart'] ) || is_page( $page_ids ) ) { - $err = 'woo non cacheable pages' ; - } - elseif ( is_null($woocom->cart) ) { - $err = 'null cart' ; - } - elseif ( ! $this->esi_enabled && $woocom->cart->get_cart_contents_count() !== 0 ) { - if ( $this->cache_cart ) { - do_action( 'litespeed_control_set_private', 'cache cart' ); - /** - * no rewrite rule to set no vary, so can't set no_vary otherwise it will always miss as can't match vary - * @since 1.6.6.1 - */ - // do_action( 'litespeed_vary_no' ); - do_action( 'litespeed_tag_add_private_esi', 'storefront-cart-header' ); - } - else { - $err = 'cart is not empty' ; - } - } - elseif ( $esi_id === 'storefront-cart-header' ) { - if ( $this->cache_cart ) { - do_action( 'litespeed_control_set_private', 'cache cart' ); - do_action( 'litespeed_vary_no' ); - do_action( 'litespeed_tag_add_private_esi', 'storefront-cart-header' ); - } - else { - $err = 'ESI cart should be nocache' ; - } - } - elseif ( function_exists( 'wc_notice_count' ) && wc_notice_count() > 0 ) { - $err = 'has wc notice' ; + $page_ids = array_filter(array(wc_get_page_id('cart'), wc_get_page_id('checkout'), wc_get_page_id('myaccount'))); + if (isset($_GET['download_file']) || isset($_GET['add-to-cart']) || is_page($page_ids)) { + $err = 'woo non cacheable pages'; + } elseif (function_exists('wc_notice_count') && wc_notice_count() > 0) { + $err = 'has wc notice'; } - if ( $err ) { - do_action( 'litespeed_control_set_nocache', '3rd party woocommerce not cache due to ' . $err ); - return ; + if ($err) { + do_action('litespeed_control_set_nocache', '3rd party woocommerce not cache due to ' . $err); + return; } } - return ; + return; } - $uri = esc_url($_SERVER["REQUEST_URI"]) ; - $uri_len = strlen($uri) ; - if ( $uri_len < 5 ) { - return ; + $uri = esc_url($_SERVER['REQUEST_URI']); + $uri_len = strlen($uri); + if ($uri_len < 5) { + return; } - if ( in_array($uri, array('cart/', 'checkout/', 'my-account/', 'addons/', 'logout/', 'lost-password/', 'product/')) ) { // why contains `product`? - do_action( 'litespeed_control_set_nocache', 'uri in cart/account/user pages' ); - return ; + if (in_array($uri, array('cart/', 'checkout/', 'my-account/', 'addons/', 'logout/', 'lost-password/', 'product/'))) { + // why contains `product`? + do_action('litespeed_control_set_nocache', 'uri in cart/account/user pages'); + return; } - $qs = sanitize_text_field($_SERVER["QUERY_STRING"]) ; - $qs_len = strlen($qs) ; - if ( ! empty($qs) && $qs_len >= 12 && strpos( $qs, 'add-to-cart=' ) === 0 ) { - do_action( 'litespeed_control_set_nocache', 'qs contains add-to-cart' ); - return ; + $qs = sanitize_text_field($_SERVER['QUERY_STRING']); + $qs_len = strlen($qs); + if (!empty($qs) && $qs_len >= 12 && strpos($qs, 'add-to-cart=') === 0) { + do_action('litespeed_control_set_nocache', 'qs contains add-to-cart'); + return; } } @@ -644,30 +575,74 @@ public function set_control($esi_id) * @access public * @param WC_Product $product */ - public function purge_product($product) { - do_action( 'litespeed_debug', '[3rd] Woo Purge [pid]' . $product->get_id() ); + public function purge_product($product) + { + do_action('litespeed_debug', '[3rd] Woo Purge [pid] ' . $product->get_id()); - $config = apply_filters( 'litespeed_conf', self::O_UPDATE_INTERVAL ) ; - if ( is_null($config) ) { - $config = self::O_PQS_CS ; - } + $do_purge = function ($action, $debug = '') use ($product) { + $config = apply_filters('litespeed_conf', self::O_UPDATE_INTERVAL); + if (is_null($config)) { + $config = self::O_PQS_CS; + } - if ( $config === self::O_PQS_CQS ) { - $this->backend_purge($product->get_id()) ; - } - elseif ( $config !== self::O_PQS_CS && $product->is_in_stock() ) { - do_action( 'litespeed_debug', '[3rd] Woo No purge needed [option] ' . $config ); - return ; - } - elseif ( $config !== self::O_PS_CN && ! $product->is_in_stock() ) { - $this->backend_purge($product->get_id()) ; + if ($config === self::O_PQS_CQS) { + $action(); + if ($debug) { + do_action('litespeed_debug', $debug); + } + } elseif ($config !== self::O_PQS_CS && $product->is_in_stock()) { + do_action('litespeed_debug', '[3rd] Woo No purge needed [option] ' . $config); + return false; + } elseif ($config !== self::O_PS_CN && !$product->is_in_stock()) { + $action(); + if ($debug) { + do_action('litespeed_debug', $debug); + } + } + return true; + }; + + if ( + !$do_purge(function () use ($product) { + $this->backend_purge($product->get_id()); + }) + ) { + return; } - do_action( 'litespeed_purge_post', $product->get_id() ); + do_action('litespeed_purge_post', $product->get_id()); // Check if is variation, purge stock too #984479 - if ( $product->is_type( 'variation' ) ) { - do_action( 'litespeed_purge_post', $product->get_parent_id() ); + if ($product->is_type('variation')) { + do_action('litespeed_purge_post', $product->get_parent_id()); + } + + // Check if WPML is enabled ##972971 + if (defined('WPML_PLUGIN_BASENAME')) { + // Check if it is a variable product and get post/parent ID + $wpml_purge_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id(); + $type = apply_filters('wpml_element_type', get_post_type($wpml_purge_id)); + $trid = apply_filters('wpml_element_trid', false, $wpml_purge_id, $type); + $translations = apply_filters('wpml_get_element_translations', array(), $trid, $type); + foreach ($translations as $lang => $translation) { + do_action('litespeed_debug', '[3rd] Woo WPML purge language: ' . $translation->language_code . ' , post ID: ' . $translation->element_id); + do_action('litespeed_purge_post', $translation->element_id); + // use the $translation->element_id as it is post ID of other languages + } + + // Check other languages category and purge if configured. + // wp_get_post_terms() only returns default language category ID + $default_cats = wp_get_post_terms($wpml_purge_id, 'product_cat'); + $languages = apply_filters('wpml_active_languages', null); + + foreach ($default_cats as $default_cat) { + foreach ($languages as $language) { + $tr_cat_id = icl_object_id($default_cat->term_id, 'product_cat', false, $language['code']); + $do_purge(function () use ($tr_cat_id) { + do_action('litespeed_purge', self::CACHETAG_TERM . $tr_cat_id); + }, '[3rd] Woo Purge WPML category [language] ' . $language['code'] . ' [cat] ' . $tr_cat_id); + } + } } } @@ -684,15 +659,15 @@ public function purge_product($product) { */ public function delete_rel($post_id, $term_ids) { - if ( ! function_exists( 'wc_get_product' ) ) { - return ; + if (!function_exists('wc_get_product')) { + return; } - if ( empty($term_ids) || wc_get_product($post_id) === false ) { - return ; + if (empty($term_ids) || wc_get_product($post_id) === false) { + return; } - foreach ( $term_ids as $term_id ) { - do_action( 'litespeed_purge', self::CACHETAG_TERM . $term_id ); + foreach ($term_ids as $term_id) { + do_action('litespeed_purge', self::CACHETAG_TERM . $term_id); } } @@ -706,29 +681,29 @@ public function delete_rel($post_id, $term_ids) */ public function backend_purge($post_id) { - if ( ! function_exists( 'wc_get_product' ) ) { - return ; + if (!function_exists('wc_get_product')) { + return; } - if ( ! isset($post_id) || wc_get_product($post_id) === false ) { - return ; + if (!isset($post_id) || wc_get_product($post_id) === false) { + return; } - $cats = $this->get_cats($post_id) ; - if ( ! empty($cats) ) { - foreach ( $cats as $cat ) { - do_action( 'litespeed_purge', self::CACHETAG_TERM . $cat ); + $cats = $this->get_cats($post_id); + if (!empty($cats)) { + foreach ($cats as $cat) { + do_action('litespeed_purge', self::CACHETAG_TERM . $cat); } } - if ( ! function_exists( 'wc_get_product_terms' ) ) { - return ; + if (!function_exists('wc_get_product_terms')) { + return; } - $tags = wc_get_product_terms($post_id, 'product_tag', array('fields' => 'ids')) ; - if ( ! empty($tags) ) { - foreach ( $tags as $tag ) { - do_action( 'litespeed_purge', self::CACHETAG_TERM . $tag ); + $tags = wc_get_product_terms($post_id, 'product_tag', array('fields' => 'ids')); + if (!empty($tags)) { + foreach ($tags as $tag) { + do_action('litespeed_purge', self::CACHETAG_TERM . $tag); } } } @@ -745,18 +720,18 @@ public function backend_purge($post_id) */ public function add_review($unused, $comment_approved, $commentdata) { - if ( ! function_exists( 'wc_get_product' ) ) { - return ; + if (!function_exists('wc_get_product')) { + return; } - $post_id = $commentdata['comment_post_ID'] ; - if ( $comment_approved !== 1 || ! isset($post_id) || wc_get_product($post_id) === false ) { - return ; + $post_id = $commentdata['comment_post_ID']; + if ($comment_approved !== 1 || !isset($post_id) || wc_get_product($post_id) === false) { + return; } - global $wp_widget_factory ; - $recent_reviews = $wp_widget_factory->widgets[ 'WC_Widget_Recent_Reviews' ] ; - if ( ! is_null( $recent_reviews ) ) { - do_action( 'litespeed_tag_add_widget', $recent_reviews->id ); + global $wp_widget_factory; + $recent_reviews = $wp_widget_factory->widgets['WC_Widget_Recent_Reviews']; + if (!is_null($recent_reviews)) { + do_action('litespeed_tag_add_widget', $recent_reviews->id); } } @@ -766,14 +741,13 @@ public function add_review($unused, $comment_approved, $commentdata) * @since 1.6.3 Removed static * @since 3.0 new API */ - private function _option_append() { + private function _option_append() + { // Append option save value filter - do_action( 'litespeed_conf_multi_switch', self::O_UPDATE_INTERVAL, 3 ); // This need to be before conf_append + do_action('litespeed_conf_multi_switch', self::O_UPDATE_INTERVAL, 3); // This need to be before conf_append - do_action( 'litespeed_conf_append', self::O_ESI_CACHE_CART, true ); - do_action( 'litespeed_conf_append', self::O_UPDATE_INTERVAL, false ); - do_action( 'litespeed_conf_append', self::O_SHOP_FRONT_TTL, true ); - do_action( 'litespeed_conf_append', self::O_WOO_CACHE_CART, true ); + do_action('litespeed_conf_append', self::O_UPDATE_INTERVAL, false); + do_action('litespeed_conf_append', self::O_CART_VARY, false); } /** @@ -782,13 +756,13 @@ private function _option_append() { * * @since 1.6.3 Removed static */ - public function settings_add_tab( $setting_page ) + public function settings_add_tab($setting_page) { - if ( $setting_page != 'cache' ) { - return ; + if ($setting_page != 'cache') { + return; } - require 'woocommerce.tab.tpl.php' ; + require 'woocommerce.tab.tpl.php'; } /** @@ -796,13 +770,13 @@ public function settings_add_tab( $setting_page ) * * @since 3.0 */ - public function settings_add_content( $setting_page ) + public function settings_add_content($setting_page) { - if ( $setting_page != 'cache' ) { - return ; + if ($setting_page != 'cache') { + return; } - require 'woocommerce.content.tpl.php' ; + require 'woocommerce.content.tpl.php'; } /** @@ -817,20 +791,20 @@ public function settings_add_content( $setting_page ) */ private function get_cats($product_id) { - if ( ! function_exists( 'WC' ) ) { - return ; + if (!function_exists('WC')) { + return; } - $woocom = WC() ; - if ( isset($woocom) && version_compare($woocom->version, '2.5.0', '>=') && function_exists( 'wc_get_product_cat_ids' ) ) { - return wc_get_product_cat_ids($product_id) ; + $woocom = WC(); + if (isset($woocom) && version_compare($woocom->version, '2.5.0', '>=') && function_exists('wc_get_product_cat_ids')) { + return wc_get_product_cat_ids($product_id); } - $product_cats = wp_get_post_terms($product_id, 'product_cat', array("fields" => "ids")) ; - foreach ( $product_cats as $product_cat ) { - $product_cats = array_merge($product_cats, get_ancestors($product_cat, 'product_cat')) ; + $product_cats = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids')); + foreach ($product_cats as $product_cat) { + $product_cats = array_merge($product_cats, get_ancestors($product_cat, 'product_cat')); } - return $product_cats ; + return $product_cats; } /** @@ -844,7 +818,7 @@ public static function preload() * Auto puge for WooCommerce Advanced Bulk Edit plugin, * Bulk edit hook need to add to preload as it will die before detect. */ - add_action( 'wp_ajax_wpmelon_adv_bulk_edit', __CLASS__ . '::bulk_edit_purge', 1 ) ; + add_action('wp_ajax_wpmelon_adv_bulk_edit', __CLASS__ . '::bulk_edit_purge', 1); } /** @@ -854,40 +828,41 @@ public static function preload() */ public static function bulk_edit_purge() { - if ( empty( $_POST[ 'type' ] ) || $_POST[ 'type' ] != 'saveproducts' || empty( $_POST[ 'data' ] ) ) return ; + if (empty($_POST['type']) || $_POST['type'] != 'saveproducts' || empty($_POST['data'])) { + return; + } /* - * admin-ajax form-data structure - * array( - * "type" => "saveproducts", - * "data" => array( - * "column1" => "464$###0$###2#^#463$###0$###4#^#462$###0$###6#^#", - * "column2" => "464$###0$###2#^#463$###0$###4#^#462$###0$###6#^#" - * ) - * ) - */ - $stock_string_arr = array() ; - foreach ( $_POST[ 'data' ] as $stock_value ) { - $stock_string_arr = array_merge( $stock_string_arr, explode( '#^#', $stock_value ) ) ; + * admin-ajax form-data structure + * array( + * "type" => "saveproducts", + * "data" => array( + * "column1" => "464$###0$###2#^#463$###0$###4#^#462$###0$###6#^#", + * "column2" => "464$###0$###2#^#463$###0$###4#^#462$###0$###6#^#" + * ) + * ) + */ + $stock_string_arr = array(); + foreach ($_POST['data'] as $stock_value) { + $stock_string_arr = array_merge($stock_string_arr, explode('#^#', $stock_value)); } - $lscwp_3rd_woocommerce = new self() ; + $lscwp_3rd_woocommerce = new self(); - if ( count( $stock_string_arr ) < 1 ) { - return ; + if (count($stock_string_arr) < 1) { + return; } - foreach ( $stock_string_arr as $edited_stock ) { - $product_id = strtok( $edited_stock, '$' ); - $product = wc_get_product( $product_id ) ; + foreach ($stock_string_arr as $edited_stock) { + $product_id = strtok($edited_stock, '$'); + $product = wc_get_product($product_id); - if ( empty( $product ) ) { - do_action( 'litespeed_debug', '3rd woo purge: ' . $product_id . ' not found.' ) ; - continue ; + if (empty($product)) { + do_action('litespeed_debug', '3rd woo purge: ' . $product_id . ' not found.'); + continue; } - $lscwp_3rd_woocommerce->purge_product( $product ); + $lscwp_3rd_woocommerce->purge_product($product); } } } - diff --git a/thirdparty/woocommerce.content.tpl.php b/thirdparty/woocommerce.content.tpl.php index d5f3157a0..f0c848550 100644 --- a/thirdparty/woocommerce.content.tpl.php +++ b/thirdparty/woocommerce.content.tpl.php @@ -1,7 +1,8 @@ -

- - -

- -
-

-

-

FAQ.', 'litespeed-cache' ), 'href="https://docs.litespeedtech.com/lscache/lscwp/installation/#non-cacheable-pages" target="_blank"' ); ?>

-

-
- - - - - - - - - - +

+ + +

- - - - +
+

+

+

FAQ.', 'litespeed-cache'), 'href="https://docs.litespeedtech.com/lscache/lscwp/installation/#non-cacheable-pages" target="_blank"'); ?>

+

+
- - - - +
- - - - -
- ' . Lang::title( Base::O_ESI ) . '' ); ?> -
-
- - - - __( 'Purge product on changes to the quantity or stock status.', 'litespeed-cache' ) . ' ' . __( 'Purge categories only when stock status changes.', 'litespeed-cache' ), - self::O_PS_CS => __( 'Purge product and categories only when the stock status changes.', 'litespeed-cache' ), - self::O_PS_CN => __( 'Purge product only when the stock status changes.', 'litespeed-cache' ) . ' ' . __( 'Do not purge categories on changes to the quantity or stock status.', 'litespeed-cache' ), - self::O_PQS_CQS => __( 'Always purge both product and categories on changes to the quantity or stock status.', 'litespeed-cache' ), - ); - $conf = (int) apply_filters( 'litespeed_conf', $id ); - foreach ( $options as $k => $v ) : - $checked = (int) $k === $conf ? ' checked ' : ''; - ?> - -
- /> - -
- -
- -
-
- - - - -
- - -
-
- - - - -
- -
-
+ + + + + -
+ + + + __('Purge product on changes to the quantity or stock status.', 'litespeed-cache') . ' ' . __('Purge categories only when stock status changes.', 'litespeed-cache'), + self::O_PS_CS => __('Purge product and categories only when the stock status changes.', 'litespeed-cache'), + self::O_PS_CN => __('Purge product only when the stock status changes.', 'litespeed-cache') . ' ' . __('Do not purge categories on changes to the quantity or stock status.', 'litespeed-cache'), + self::O_PQS_CQS => __('Always purge both product and categories on changes to the quantity or stock status.', 'litespeed-cache'), + ); + $conf = (int) apply_filters('litespeed_conf', $id); + foreach ($options as $k => $v) : + $checked = (int) $k === $conf ? ' checked ' : ''; + ?> + +
+ /> + +
+ +
+ +
+
+ + + + + + + cls('Admin_Display')->build_switch($id); ?> +
+ + +
+
+ + + +
\ No newline at end of file diff --git a/thirdparty/wp-polls.cls.php b/thirdparty/wp-polls.cls.php index 1c3dc02c7..619cdf559 100644 --- a/thirdparty/wp-polls.cls.php +++ b/thirdparty/wp-polls.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); // todo: need test @@ -14,13 +14,12 @@ class Wp_Polls { public static function detect() { - add_filter( 'wp_polls_display_pollvote', __CLASS__ . '::set_control' ); - add_filter( 'wp_polls_display_pollresult', __CLASS__ . '::set_control' ); + add_filter('wp_polls_display_pollvote', __CLASS__ . '::set_control'); + add_filter('wp_polls_display_pollresult', __CLASS__ . '::set_control'); } public static function set_control() { - do_action( 'litespeed_control_set_nocache', 'wp polls' ); + do_action('litespeed_control_set_nocache', 'wp polls'); } } - diff --git a/thirdparty/wp-postratings.cls.php b/thirdparty/wp-postratings.cls.php index 6ec9fecd6..731dd8e2b 100644 --- a/thirdparty/wp-postratings.cls.php +++ b/thirdparty/wp-postratings.cls.php @@ -6,11 +6,10 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class WP_PostRatings { - /** * Detects if plugin is installed. * @@ -19,8 +18,8 @@ class WP_PostRatings */ public static function detect() { - if ( defined( 'WP_POSTRATINGS_VERSION' ) ) { - add_action( 'rate_post', __CLASS__ . '::flush', 10, 3 ); + if (defined('WP_POSTRATINGS_VERSION')) { + add_action('rate_post', __CLASS__ . '::flush', 10, 3); } } @@ -30,9 +29,8 @@ public static function detect() * @since 1.1.1 * @access public */ - public static function flush( $uid, $post_id, $post_ratings_score ) + public static function flush($uid, $post_id, $post_ratings_score) { - do_action( 'litespeed_purge_post', $post_id ); + do_action('litespeed_purge_post', $post_id); } - } diff --git a/thirdparty/wpdiscuz.cls.php b/thirdparty/wpdiscuz.cls.php index d0047c9f5..13ecd3e8b 100644 --- a/thirdparty/wpdiscuz.cls.php +++ b/thirdparty/wpdiscuz.cls.php @@ -7,34 +7,35 @@ * @subpackage LiteSpeed_Cache/thirdparty * @author LiteSpeed Technologies */ -namespace LiteSpeed\Thirdparty ; +namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit ; +defined('WPINC') || exit(); -use \LiteSpeed\API ; +use LiteSpeed\API; class Wpdiscuz { public static function detect() { - if ( ! defined( 'WPDISCUZ_DS' ) ) return ; - - self::check_commenter() ; - add_action( 'wpdiscuz_add_comment', __CLASS__ . '::add_comment' ) ; + if (!defined('WPDISCUZ_DS')) { + return; + } + self::check_commenter(); + add_action('wpdiscuz_add_comment', __CLASS__ . '::add_comment'); } public static function add_comment() { - API::vary_append_commenter() ; + API::vary_append_commenter(); } public static function check_commenter() { - $commentor = wp_get_current_commenter() ; + $commentor = wp_get_current_commenter(); - if ( strlen( $commentor[ 'comment_author' ] ) > 0 ) { - add_filter( 'litespeed_vary_check_commenter_pending', '__return_false' ) ; + if (strlen($commentor['comment_author']) > 0) { + add_filter('litespeed_vary_check_commenter_pending', '__return_false'); } } } diff --git a/thirdparty/wplister.cls.php b/thirdparty/wplister.cls.php index 8fa9f7d1a..a017050b1 100644 --- a/thirdparty/wplister.cls.php +++ b/thirdparty/wplister.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class WPLister { @@ -18,12 +18,11 @@ class WPLister */ public static function detect() { - if ( defined( 'WOOCOMMERCE_VERSION' ) && defined( 'WPLISTER_VERSION' ) ) { + if (defined('WOOCOMMERCE_VERSION') && defined('WPLISTER_VERSION')) { // User reported this will sync correctly. - add_action( 'wplister_revise_inventory_status', array( WooCommerce::cls(), 'backend_purge' ) ); + add_action('wplister_revise_inventory_status', array(WooCommerce::cls(), 'backend_purge')); // Added as a safety measure for WPLister Pro only. - add_action( 'wplister_inventory_status_changed', array( WooCommerce::cls(), 'backend_purge' ) ); + add_action('wplister_inventory_status_changed', array(WooCommerce::cls(), 'backend_purge')); } } - } diff --git a/thirdparty/wpml.cls.php b/thirdparty/wpml.cls.php index 49bb3c549..b3326f53c 100644 --- a/thirdparty/wpml.cls.php +++ b/thirdparty/wpml.cls.php @@ -6,29 +6,29 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class WPML { - public static function detect() { - if ( ! defined( 'WPML_PLUGIN_BASENAME' ) ) return; + if (!defined('WPML_PLUGIN_BASENAME')) { + return; + } - add_filter( 'litespeed_internal_domains', __CLASS__ . '::append_domains' ); + add_filter('litespeed_internal_domains', __CLASS__ . '::append_domains'); } /** * Take language domains as internal domains */ - public static function append_domains( $domains ) + public static function append_domains($domains) { - $wpml_domains = apply_filters( 'wpml_setting', false, 'language_domains' ); - if ( $wpml_domains ) { - $domains = array_merge( $domains, array_values( $wpml_domains ) ); + $wpml_domains = apply_filters('wpml_setting', false, 'language_domains'); + if ($wpml_domains) { + $domains = array_merge($domains, array_values($wpml_domains)); } return $domains; } - -} \ No newline at end of file +} diff --git a/thirdparty/wptouch.cls.php b/thirdparty/wptouch.cls.php index 48b959734..cc74017a9 100644 --- a/thirdparty/wptouch.cls.php +++ b/thirdparty/wptouch.cls.php @@ -6,7 +6,7 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); class WpTouch { @@ -19,8 +19,8 @@ class WpTouch public static function detect() { global $wptouch_pro; - if ( isset( $wptouch_pro ) ) { - add_action( 'litespeed_control_finalize', __CLASS__ . '::set_control' ); + if (isset($wptouch_pro)) { + add_action('litespeed_control_finalize', __CLASS__ . '::set_control'); } } @@ -33,10 +33,8 @@ public static function detect() public static function set_control() { global $wptouch_pro; - if ( $wptouch_pro->is_mobile_device ) { - add_filter( 'litespeed_is_mobile', '__return_true' ); + if ($wptouch_pro->is_mobile_device) { + add_filter('litespeed_is_mobile', '__return_true'); } } - } - diff --git a/thirdparty/yith-wishlist.cls.php b/thirdparty/yith-wishlist.cls.php index 66bc40ee4..f99ce4a0b 100644 --- a/thirdparty/yith-wishlist.cls.php +++ b/thirdparty/yith-wishlist.cls.php @@ -6,35 +6,36 @@ */ namespace LiteSpeed\Thirdparty; -defined( 'WPINC' ) || exit; +defined('WPINC') || exit(); -use \LiteSpeed\Tag; -use \LiteSpeed\Conf; -use \LiteSpeed\Base; +use LiteSpeed\Tag; +use LiteSpeed\Conf; +use LiteSpeed\Base; -class Yith_Wishlist { +class Yith_Wishlist +{ const ESI_PARAM_POSTID = 'yith_pid'; private static $_post_id; - /** * Detects if YITH WooCommerce Wishlist and WooCommerce are installed. * * @since 1.1.0 * @access public */ - public static function detect() { - if ( ! defined( 'WOOCOMMERCE_VERSION' ) || ! defined( 'YITH_WCWL' ) ) { + public static function detect() + { + if (!defined('WOOCOMMERCE_VERSION') || !defined('YITH_WCWL')) { return; } - if ( apply_filters( 'litespeed_esi_status', false ) ) { - add_action( 'litespeed_tpl_normal', __CLASS__ . '::is_not_esi' ); - add_action( 'litespeed_esi_load-yith_wcwl_add', __CLASS__ . '::load_add_to_wishlist' ); - add_filter( 'litespeed_esi_inline-yith_wcwl_add', __CLASS__ . '::inline_add_to_wishlist', 20, 2 ); + if (apply_filters('litespeed_esi_status', false)) { + add_action('litespeed_tpl_normal', __CLASS__ . '::is_not_esi'); + add_action('litespeed_esi_load-yith_wcwl_add', __CLASS__ . '::load_add_to_wishlist'); + add_filter('litespeed_esi_inline-yith_wcwl_add', __CLASS__ . '::inline_add_to_wishlist', 20, 2); // hook to add/delete wishlist - add_action( 'yith_wcwl_added_to_wishlist', __CLASS__ . '::purge' ); - add_action( 'yith_wcwl_removed_from_wishlist', __CLASS__ . '::purge' ); + add_action('yith_wcwl_added_to_wishlist', __CLASS__ . '::purge'); + add_action('yith_wcwl_removed_from_wishlist', __CLASS__ . '::purge'); } } @@ -44,8 +45,9 @@ public static function detect() { * @since 1.2.0 * @access public */ - public static function purge() { - do_action( 'litespeed_purge_esi', 'yith_wcwl_add' ); + public static function purge() + { + do_action('litespeed_purge_esi', 'yith_wcwl_add'); } /** @@ -57,10 +59,11 @@ public static function purge() { * @since 1.1.0 * @access public */ - public static function is_not_esi() { - add_filter( 'yith_wcwl_add_to_wishlist_params', __CLASS__ . '::add_to_wishlist_params', 999, 2 ); + public static function is_not_esi() + { + add_filter('yith_wcwl_add_to_wishlist_params', __CLASS__ . '::add_to_wishlist_params', 999, 2); - add_filter( 'yith_wcwl_add_to_wishlisth_button_html', __CLASS__ . '::sub_add_to_wishlist', 999 ); + add_filter('yith_wcwl_add_to_wishlisth_button_html', __CLASS__ . '::sub_add_to_wishlist', 999); } /** @@ -68,8 +71,9 @@ public static function is_not_esi() { * * @since 3.4.1 */ - public static function add_to_wishlist_params( $defaults, $atts ) { - self::$_post_id = ! empty( $atts[ 'product_id' ] ) ? $atts[ 'product_id' ] : $defaults[ 'product_id' ]; + public static function add_to_wishlist_params($defaults, $atts) + { + self::$_post_id = !empty($atts['product_id']) ? $atts['product_id'] : $defaults['product_id']; return $defaults; } @@ -83,28 +87,30 @@ public static function add_to_wishlist_params( $defaults, $atts ) { * @since 1.1.0 * @access public */ - public static function sub_add_to_wishlist( $template ) { + public static function sub_add_to_wishlist($template) + { $params = array( self::ESI_PARAM_POSTID => self::$_post_id, ); - $inline_tags = array( - '', - rtrim( Tag::TYPE_ESI, '.' ), - Tag::TYPE_ESI . 'yith_wcwl_add', + $inline_tags = array('', rtrim(Tag::TYPE_ESI, '.'), Tag::TYPE_ESI . 'yith_wcwl_add'); + $inline_tags = implode( + ',', + array_map(function ($val) { + return 'public:' . LSWCP_TAG_PREFIX . '_' . $val; + }, $inline_tags) ); - $inline_tags = implode( ',', array_map( function($val){ return 'public:' . LSWCP_TAG_PREFIX . '_' . $val; }, $inline_tags ) ); $inline_tags .= ',' . LSWCP_TAG_PREFIX . '_tag_priv'; - do_action( 'litespeed_esi_combine', 'yith_wcwl_add' ); + do_action('litespeed_esi_combine', 'yith_wcwl_add'); $inline_params = array( - 'val' => $template, - 'tag' => $inline_tags, - 'control' => 'private,no-vary,max-age=' . Conf::cls()->conf( Base::O_CACHE_TTL_PRIV ), + 'val' => $template, + 'tag' => $inline_tags, + 'control' => 'private,no-vary,max-age=' . Conf::cls()->conf(Base::O_CACHE_TTL_PRIV), ); - return apply_filters( 'litespeed_esi_url', 'yith_wcwl_add', 'YITH ADD TO WISHLIST', $params, 'private,no-vary', false, false, false, $inline_params ); + return apply_filters('litespeed_esi_url', 'yith_wcwl_add', 'YITH ADD TO WISHLIST', $params, 'private,no-vary', false, false, false, $inline_params); } /** @@ -115,13 +121,14 @@ public static function sub_add_to_wishlist( $template ) { * @since 1.1.0 * @access public */ - public static function load_add_to_wishlist( $params ) { + public static function load_add_to_wishlist($params) + { // global $post, $wp_query; // $post = get_post( $params[ self::ESI_PARAM_POSTID ] ); // $wp_query->setup_postdata( $post ); - echo \YITH_WCWL_Shortcode::add_to_wishlist( array( 'product_id' => $params[ self::ESI_PARAM_POSTID ] ) ); - do_action( 'litespeed_control_set_private', 'yith wishlist' ); - do_action( 'litespeed_vary_no' ); + echo \YITH_WCWL_Shortcode::add_to_wishlist(array('product_id' => $params[self::ESI_PARAM_POSTID])); + do_action('litespeed_control_set_private', 'yith wishlist'); + do_action('litespeed_vary_no'); } /** @@ -129,28 +136,29 @@ public static function load_add_to_wishlist( $params ) { * * @since 3.4.2 */ - public static function inline_add_to_wishlist( $res, $params ) { - if ( ! is_array( $res ) ) { + public static function inline_add_to_wishlist($res, $params) + { + if (!is_array($res)) { $res = array(); } - $pid = $params[ self::ESI_PARAM_POSTID ]; + $pid = $params[self::ESI_PARAM_POSTID]; - $res[ 'val' ] = \YITH_WCWL_Shortcode::add_to_wishlist( array( 'product_id' => $pid ) ); + $res['val'] = \YITH_WCWL_Shortcode::add_to_wishlist(array('product_id' => $pid)); - $res[ 'control' ] = 'private,no-vary,max-age=' . Conf::cls()->conf( Base::O_CACHE_TTL_PRIV ); + $res['control'] = 'private,no-vary,max-age=' . Conf::cls()->conf(Base::O_CACHE_TTL_PRIV); - $inline_tags = array( - '', - rtrim( Tag::TYPE_ESI, '.' ), - Tag::TYPE_ESI . 'yith_wcwl_add', + $inline_tags = array('', rtrim(Tag::TYPE_ESI, '.'), Tag::TYPE_ESI . 'yith_wcwl_add'); + $inline_tags = implode( + ',', + array_map(function ($val) { + return 'public:' . LSWCP_TAG_PREFIX . '_' . $val; + }, $inline_tags) ); - $inline_tags = implode( ',', array_map( function( $val ) { return 'public:' . LSWCP_TAG_PREFIX . '_' . $val; }, $inline_tags ) ); $inline_tags .= ',' . LSWCP_TAG_PREFIX . '_tag_priv'; - $res[ 'tag' ] = $inline_tags; + $res['tag'] = $inline_tags; return $res; } - } diff --git a/tpl/cache/network_settings-browser.tpl.php b/tpl/cache/network_settings-browser.tpl.php index dd5c06c22..14306d0dc 100644 --- a/tpl/cache/network_settings-browser.tpl.php +++ b/tpl/cache/network_settings-browser.tpl.php @@ -1,5 +1,5 @@ - - - - title( $id ) ; ?> - - + + + + title($id); ?> + + build_input( $id ) ; - - $this->_validate_syntax( $id ) ; + $this->build_input($id); - echo '

' . __('SYNTAX: alphanumeric and "_".', 'litespeed-cache') - . ' ' . __('No spaces and case sensitive.', 'litespeed-cache') - . ' ' . __('MUST BE UNIQUE FROM OTHER WEB APPLICATIONS.', 'litespeed-cache') - . '

' - . '

' - . sprintf(__('The default login cookie is %s.', 'litespeed-cache'), '_lscache_vary') - . ' ' . __('The server will determine if the user is logged in based on the existence of this cookie.', 'litespeed-cache') - . ' ' . __('This setting is useful for those that have multiple web applications for the same domain.', 'litespeed-cache') - . ' ' . __('If every web application uses the same cookie, the server may confuse whether a user is logged in or not.', 'litespeed-cache') - . ' ' . __('The cookie set here will be used for this WordPress installation.', 'litespeed-cache') - . '

' - . '

' - . __('Example use case:', 'litespeed-cache') - . '
' - . sprintf(__('There is a WordPress installed for %s.', 'litespeed-cache'), 'www.example.com') - . '
' - . sprintf(__('Then another WordPress is installed (NOT MULTISITE) at %s', 'litespeed-cache'), 'www.example.com/blog/') - . ' ' . __('The cache needs to distinguish who is logged into which WordPress site in order to cache correctly.', 'litespeed-cache') - . '
' - ; ?> - ' ; ?> - _validate_syntax($id); - if ( preg_match( '#[^\w\-]#', $this->conf( $id ) ) ) { - echo '

❌ ' . __( 'Invalid login cookie. Invalid characters found.', 'litespeed-cache' ) . '

' ; - } + echo '

' . __('SYNTAX: alphanumeric and "_".', 'litespeed-cache') + . ' ' . __('No spaces and case sensitive.', 'litespeed-cache') + . ' ' . __('MUST BE UNIQUE FROM OTHER WEB APPLICATIONS.', 'litespeed-cache') + . '

' + . '

' + . sprintf(__('The default login cookie is %s.', 'litespeed-cache'), '_lscache_vary') + . ' ' . __('The server will determine if the user is logged in based on the existence of this cookie.', 'litespeed-cache') + . ' ' . __('This setting is useful for those that have multiple web applications for the same domain.', 'litespeed-cache') + . ' ' . __('If every web application uses the same cookie, the server may confuse whether a user is logged in or not.', 'litespeed-cache') + . ' ' . __('The cookie set here will be used for this WordPress installation.', 'litespeed-cache') + . '

' + . '

' + . __('Example use case:', 'litespeed-cache') + . '
' + . sprintf(__('There is a WordPress installed for %s.', 'litespeed-cache'), 'www.example.com') + . '
' + . sprintf(__('Then another WordPress is installed (NOT MULTISITE) at %s', 'litespeed-cache'), 'www.example.com/blog/') + . ' ' . __('The cache needs to distinguish who is logged into which WordPress site in order to cache correctly.', 'litespeed-cache') + . '
'; ?> + '; ?> + conf( $id ) ) { - $cookie_rule = ''; - try { - $cookie_rule = Htaccess::cls()->current_login_cookie() ; - } catch ( \Exception $e ) { - echo '

' . $e->getMessage() . '

' ; - } + if (preg_match('#[^\w\-]#', $this->conf($id))) { + echo '

❌ ' . __('Invalid login cookie. Invalid characters found.', 'litespeed-cache') . '

'; + } - $cookie_arr = explode( ',', $cookie_rule ) ; - if ( ! in_array( $this->conf( $id ), $cookie_arr ) ) { - echo '

' - . __( 'WARNING: The .htaccess login cookie and Database login cookie do not match.', 'litespeed-cache' ) - . '

' - ; - } + if (defined('LITESPEED_ON') && $this->conf($id)) { + $cookie_rule = ''; + try { + $cookie_rule = Htaccess::cls()->current_login_cookie(); + } catch (\Exception $e) { + echo '

' . $e->getMessage() . '

'; + } + $cookie_arr = explode(',', $cookie_rule); + if (!in_array($this->conf($id), $cookie_arr)) { + echo '

' + . __('WARNING: The .htaccess login cookie and Database login cookie do not match.', 'litespeed-cache') + . '

'; } + } ?> - - + + + + + + + title($id); ?> + + + build_textarea($id, 50); + + $this->_validate_syntax($id); + echo '

' . __('SYNTAX: alphanumeric and "_".', 'litespeed-cache') + . ' ' . __('No spaces and case sensitive.', 'litespeed-cache') + . '

' + . '

' + . ' ' . __('You can list the 3rd party vary cookies here.', 'litespeed-cache') + . '

' + . '

'; ?> + '; ?> + + \ No newline at end of file diff --git a/tpl/cache/settings_inc.object.tpl.php b/tpl/cache/settings_inc.object.tpl.php index dcd767c0e..09f8eb972 100644 --- a/tpl/cache/settings_inc.object.tpl.php +++ b/tpl/cache/settings_inc.object.tpl.php @@ -17,7 +17,8 @@ $mem_conn_desc = '' . __( 'Passed', 'litespeed-cache' ) . '' ; } else { - $mem_conn_desc = '' . __( 'Failed', 'litespeed-cache' ) . '' ; + $severity = $this->conf( Base::O_OBJECT, true ) ? "danger" : "warning"; + $mem_conn_desc = '' . __( 'Failed', 'litespeed-cache' ) . '' ; } ?> @@ -76,6 +77,7 @@ build_input( $id ); ?>

LSMCD/Redis' ) ; ?> +
/path/to/memcached.sock' ); ?>
@@ -90,6 +92,7 @@
11211' ) ; ?> 6379' ) ; ?> +
0' ); ?>
diff --git a/tpl/cdn/auto_setup.tpl.php b/tpl/cdn/auto_setup.tpl.php index 9e670dfd8..d14a662dc 100644 --- a/tpl/cdn/auto_setup.tpl.php +++ b/tpl/cdn/auto_setup.tpl.php @@ -1,260 +1,270 @@ maybe_extract_token(); -$cloud_linked = Cloud::get_summary( 'is_linked' ); +$cloud_linked = Cloud::get_summary('is_linked'); $setup_summary = Cdn_Setup::get_summary(); $cdn_setup_done_ts = 0; -if ( ! empty( $setup_summary[ 'cdn_setup_done_ts' ] ) ) { - $cdn_setup_done_ts = $setup_summary[ 'cdn_setup_done_ts' ]; +if (!empty($setup_summary['cdn_setup_done_ts'])) { + $cdn_setup_done_ts = $setup_summary['cdn_setup_done_ts']; } $has_setup_token = $__cdnsetup->has_cdn_setup_token(); -if ( ! empty( $setup_summary[ 'cdn_setup_ts' ] ) ) { - $cdn_setup_ts = $setup_summary[ 'cdn_setup_ts' ]; +if (!empty($setup_summary['cdn_setup_ts'])) { + $cdn_setup_ts = $setup_summary['cdn_setup_ts']; - if ( !empty( $setup_summary[ 'cdn_setup_err' ] ) ) { - $cdn_setup_err = $setup_summary[ 'cdn_setup_err' ]; + if (!empty($setup_summary['cdn_setup_err'])) { + $cdn_setup_err = $setup_summary['cdn_setup_err']; } - if ($this->conf( Base::O_QC_NAMESERVERS )) { - $nameservers = explode(',', $this->conf( Base::O_QC_NAMESERVERS )); + if ($this->conf(Base::O_QC_NAMESERVERS)) { + $nameservers = explode(',', $this->conf(Base::O_QC_NAMESERVERS)); } } else { $cdn_setup_ts = 0; } $curr_status = '' . __('Not running', 'litespeed-cache') . ''; -$apply_btn_txt = __( 'Run CDN Setup', 'litespeed-cache' ); +$apply_btn_txt = __('Run CDN Setup', 'litespeed-cache'); $apply_btn_type = Cdn_Setup::TYPE_RUN; $disabled = ''; $dom = parse_url(home_url(), PHP_URL_HOST); if ($cdn_setup_done_ts) { $curr_status = ' ' - . __('Done', 'litespeed-cache') - . ' ' - . sprintf( __('Completed at %s', 'litespeed-cache'), wp_date(get_option( 'date_format' ) . ' ' . get_option( 'time_format'), $cdn_setup_done_ts) ) - . ''; + . __('Done', 'litespeed-cache') + . ' ' + . sprintf(__('Completed at %s', 'litespeed-cache'), wp_date(get_option('date_format') . ' ' . get_option('time_format'), $cdn_setup_done_ts)) + . ''; $disabled = 'disabled'; } else if (!$has_setup_token) { $disabled = 'disabled'; -} else if ( ! empty( $cdn_setup_err ) ) { +} else if (!empty($cdn_setup_err)) { $curr_status = ' ' . __('Paused', 'litespeed-cache'); $curr_status_subline = '

' . $cdn_setup_err . '

'; -} else if ( $cdn_setup_ts > 0 ) { - if ( isset($nameservers) ) { +} else if ($cdn_setup_ts > 0) { + if (isset($nameservers)) { $curr_status = ' ' . __('Verifying, waiting for nameservers to be updated.', 'litespeed-cache') . ' ' . __('Click the refresh button below to refresh status.', 'litespeed-cache'); - if ( isset( $setup_summary[ 'cdn_verify_msg' ])) { - $curr_status_subline = '

' . __( 'Last Verification Result', 'litespeed-cache' ) . ': ' . $setup_summary[ 'cdn_verify_msg' ] . '

'; + if (isset($setup_summary['cdn_verify_msg'])) { + $curr_status_subline = '

' . __('Last Verification Result', 'litespeed-cache') . ': ' . $setup_summary['cdn_verify_msg'] . '

'; } } else { $curr_status = ' ' . __('In Progress', 'litespeed-cache'); - $curr_status_subline = '

' . __( 'You will receive an email upon status update.', 'litespeed-cache' ) . ' ' . __( 'This process may take several minutes.', 'litespeed-cache' ) . '

'; + $curr_status_subline = '

' . __('You will receive an email upon status update.', 'litespeed-cache') . ' ' . __('This process may take several minutes.', 'litespeed-cache') . '

'; } - $apply_btn_txt = __( 'Refresh CDN Setup Status', 'litespeed-cache' ); + $apply_btn_txt = __('Refresh CDN Setup Status', 'litespeed-cache'); $apply_btn_type = Cdn_Setup::TYPE_STATUS; } ?>

- +

- +

    -
  1. -
  2. -
  3. +
  4. +
  5. +
  6. - - - + + +

- +

- +

  • - - + +
  • - - set up the CDN manually at QUIC.cloud.', 'litespeed-cache' ), - 'href="https://quic.cloud/docs/onboarding/" target="_blank" class="litespeed-learn-more"'); ?> + + set up the CDN manually at QUIC.cloud.', 'litespeed-cache'), + 'href="https://quic.cloud/docs/onboarding/" target="_blank" class="litespeed-learn-more"' + ); ?>
  • - - - + + +

- +

- +

- ' . __( 'Account is linked!', 'litespeed-cache' ) . ''; ?> -

- ', - false, - 'litespeed-link-with-icon' ); ?> - ', - false, - 'litespeed-link-with-icon' ); ?> -

+ ' . __('Account is linked!', 'litespeed-cache') . ''; ?> +

+ ', + false, + 'litespeed-link-with-icon' + ); ?> + ', + false, + 'litespeed-link-with-icon' + ); ?> +

- - ' . __( 'Ready to run CDN setup.', 'litespeed-cache' ) . ''; ?> - -

-
- -
+ + ' . __('Ready to run CDN setup.', 'litespeed-cache') . ''; ?> + +

+
+ +

- +

- + - - + +

- +

- $cnt ) { - echo ''; + $cnt) { + echo ''; } ?>
- + - +
' . $type . '' . $cnt . '
' . wp_kses_post($type) . '' . wp_kses_post($cnt) . '

- +

- - ', - false, - 'litespeed-link-with-icon' ); ?> + + ', + false, + 'litespeed-link-with-icon' + ); ?>

- +

- +
- +

- +

- +

- +

    ' . $nameserver . ''; } ?>

- - - + + +

- +

- - + +

- +

- + \ No newline at end of file diff --git a/tpl/cdn/manage.tpl.php b/tpl/cdn/manage.tpl.php index 8ad8ac0e9..880ec23dd 100644 --- a/tpl/cdn/manage.tpl.php +++ b/tpl/cdn/manage.tpl.php @@ -1,79 +1,80 @@ conf( Base::O_CDN_CLOUDFLARE ) ; -$cf_domain = $this->conf( Base::O_CDN_CLOUDFLARE_NAME ) ?: '-' ; -$cf_zone = $this->conf( Base::O_CDN_CLOUDFLARE_ZONE ) ?: '-' ; +namespace LiteSpeed; -$curr_status = CDN\Cloudflare::get_option( CDN\Cloudflare::ITEM_STATUS, array() ) ; +defined('WPINC') || exit; + +$cf_on = $this->conf(Base::O_CDN_CLOUDFLARE); +$cf_domain = $this->conf(Base::O_CDN_CLOUDFLARE_NAME) ?: '-'; +$cf_zone = $this->conf(Base::O_CDN_CLOUDFLARE_ZONE) ?: '-'; + +$curr_status = CDN\Cloudflare::get_option(CDN\Cloudflare::ITEM_STATUS, array()); ?>

-

:

+

: qc_link(); ?>

- -
-

-

- -

-
- + +
+

+

+ +

+
+ -

:

-

:

+

:

+

:

- : - - + : + + - - + + - - + + - - - = $curr_status[ 'devmode_expired' ] ) { - $expired_at = date( 'm/d/Y H:i:s', $curr_status[ 'devmode_expired' ] + LITESPEED_TIME_OFFSET ) ; - $curr_status[ 'devmode' ] = 'OFF' ; - echo sprintf( __( 'Current status is %1$s since %2$s.', 'litespeed-cache' ), '' . strtoupper( $curr_status[ 'devmode' ] ) . '', '' . $expired_at . '' ) ; - } - else { - $expired_at = $curr_status[ 'devmode_expired' ] - time() ; - $expired_at = Utility::readable_time( $expired_at, 3600 * 3, true ); - ?> - ' . strtoupper( $curr_status[ 'devmode' ] ) . '' ) ; ?> - ' . $expired_at . '' ) ; ?> + + + = $curr_status['devmode_expired']) { + $expired_at = date('m/d/Y H:i:s', $curr_status['devmode_expired'] + LITESPEED_TIME_OFFSET); + $curr_status['devmode'] = 'OFF'; + echo sprintf(__('Current status is %1$s since %2$s.', 'litespeed-cache'), '' . strtoupper($curr_status['devmode']) . '', '' . $expired_at . ''); + } else { + $expired_at = $curr_status['devmode_expired'] - time(); + $expired_at = Utility::readable_time($expired_at, 3600 * 3, true); + ?> + ' . strtoupper($curr_status['devmode']) . ''); ?> + ' . $expired_at . ''); ?> - - + } + ?> + + -

- - - -

+

+ + + +

- : - + : + - - - - - + + + + +

\ No newline at end of file diff --git a/tpl/crawler/map.tpl.php b/tpl/crawler/map.tpl.php index e41d113db..c8ce5a7ba 100644 --- a/tpl/crawler/map.tpl.php +++ b/tpl/crawler/map.tpl.php @@ -1,71 +1,86 @@ list_map( 30 ); +$list = $__map->list_map(30); $count = $__map->count_map(); -$pagination = Utility::pagination( $count, 30 ); +$pagination = Utility::pagination($count, 30); ?>

- - - + + + - - - + + +

- - + +

- + + +
+
+
+ +
+
+ +
+ +
+
- - - - - - - - - $v ) : ?> + - - - - + + + + + + + $v) : ?> + + + + + +
#
- - - display_status( $v[ 'res' ], $v[ 'reason' ] ); ?> - - - #
+ + + display_status($v['res'], $v['reason']); ?> + + +

- =
- =
- =
- =
-

+ =
+ =
+ =
+ =
+

\ No newline at end of file diff --git a/tpl/crawler/settings-general.tpl.php b/tpl/crawler/settings-general.tpl.php index aef8e2fc9..49d2ece76 100644 --- a/tpl/crawler/settings-general.tpl.php +++ b/tpl/crawler/settings-general.tpl.php @@ -1,159 +1,164 @@ form_action(); ?>

- +

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
- - title( $id ); ?> - - build_input($id); ?> -
- - - - - : - : - - - recommended( $id ); ?> - - - _validate_ttl( $id, false, 30000 ); ?> - -
- _api_env_var( Base::ENV_CRAWLER_USLEEP ); ?> -
-
- - title( $id ); ?> - - build_input($id); ?> -
- - recommended($id); ?> -
-
- - title( $id ); ?> - - build_input($id); ?> -
- - recommended( $id ); ?> - _validate_ttl( $id, 60 ); ?> -
-
- - title( $id ); ?> - - build_input($id); ?> -
- - recommended($id); ?> -
-
- - title( $id ); ?> - - build_input( $id, 'litespeed-input-short' ); ?> -
- - recommended( $id ); ?> - _validate_ttl( $id, 1, 16 ); ?> -
-
- - title( $id ); ?> - - build_input( $id, 'litespeed-input-short' ); ?> -
- - recommended( $id ); ?> - _validate_ttl( $id, 10, 300 ); ?> -
-
- - title( $id ); ?> - - build_input($id); ?> -
- - - - - : - : - - - - : - : - - - -
- _api_env_var( Base::ENV_CRAWLER_LOAD_LIMIT, Base::ENV_CRAWLER_LOAD_LIMIT_ENFORCE ); ?> -
-
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
+
+ + title($id); ?> + + build_input($id); ?> +
+ + + + + : + : + + + recommended($id); ?> + + + _validate_ttl($id, false, 30000); ?> + +
+ _api_env_var(Base::ENV_CRAWLER_USLEEP); ?> +
+
+ + title($id); ?> + + build_input($id); ?> +
+ + recommended($id); ?> +
+
+ + title($id); ?> + + build_input($id); ?> +
+ + recommended($id); ?> + _validate_ttl($id, 60); ?> +
+
+ + title($id); ?> + + build_input($id); ?> +
+ + recommended($id); ?> +
+
+ + title($id); ?> + + build_input($id, 'litespeed-input-short'); ?> +
+ + recommended($id); ?> + _validate_ttl($id, 1, 16); ?> +
+
+ + title($id); ?> + + build_input($id, 'litespeed-input-short'); ?> +
+ + recommended($id); ?> + _validate_ttl($id, 10, 300); ?> +
+
+ + title($id); ?> + + build_input($id); ?> +
+ + + + + : + : + + + + : + : + + + +
+ _api_env_var(Base::ENV_CRAWLER_LOAD_LIMIT, Base::ENV_CRAWLER_LOAD_LIMIT_ENFORCE); ?> +
+
form_end(); diff --git a/tpl/crawler/settings-sitemap.tpl.php b/tpl/crawler/settings-sitemap.tpl.php index 8013dfbd5..05cdc2992 100644 --- a/tpl/crawler/settings-sitemap.tpl.php +++ b/tpl/crawler/settings-sitemap.tpl.php @@ -14,12 +14,13 @@ - title( $id ); ?> + title($id); ?> - build_input( $id, 'litespeed-input-long' ); ?> + build_textarea($id); ?>
+
diff --git a/tpl/crawler/summary.tpl.php b/tpl/crawler/summary.tpl.php index d6a8e20d7..812bf0728 100644 --- a/tpl/crawler/summary.tpl.php +++ b/tpl/crawler/summary.tpl.php @@ -1,49 +1,49 @@ list_crawlers(); $summary = Crawler::get_summary(); -if ( $summary[ 'curr_crawler' ] >= count( $crawler_list ) ) { - $summary[ 'curr_crawler' ] = 0; +if ($summary['curr_crawler'] >= count($crawler_list)) { + $summary['curr_crawler'] = 0; } -$is_running = time() - $summary[ 'is_running' ] <= $this->conf( Base::O_CRAWLER_RUN_DURATION ); +$is_running = time() - $summary['is_running'] <= $this->conf(Base::O_CRAWLER_RUN_DURATION); $disabled = Router::can_crawl() ? '' : 'disabled'; -$seconds = $this->conf( Base::O_CRAWLER_RUN_INTERVAL ); -if($seconds > 0): +$seconds = $this->conf(Base::O_CRAWLER_RUN_INTERVAL); +if ($seconds > 0) : $recurrence = ''; $hours = (int)floor($seconds / 3600); - if ( $hours ) { - if ( $hours > 1) { + if ($hours) { + if ($hours > 1) { $recurrence .= sprintf(__('%d hours', 'litespeed-cache'), $hours); - } - else { + } else { $recurrence .= sprintf(__('%d hour', 'litespeed-cache'), $hours); } } - $minutes = (int)floor( ($seconds % 3600 ) / 60 ); - if ( $minutes ) { + $minutes = (int)floor(($seconds % 3600) / 60); + if ($minutes) { $recurrence .= ' '; - if ( $minutes > 1) { + if ($minutes > 1) { $recurrence .= sprintf(__('%d minutes', 'litespeed-cache'), $minutes); - } - else { + } else { $recurrence .= sprintf(__('%d minute', 'litespeed-cache'), $minutes); } } - ?> +?>

- +

- +

@@ -52,172 +52,178 @@ - -

- : - -

+ +

+ : + +

+ + +

+ : + conf(Base::O_CRAWLER_CRAWL_INTERVAL)); ?> + +

- -

- : - conf( Base::O_CRAWLER_CRAWL_INTERVAL )); ?> -

+ +

+ : + +

+ - - -

- : - -

- + +

+ : + +

+ - -

- : - -

- + +

+ : + +

+ - -

- : - -

- +

+ : + get_server_load(); ?> +

- -

- : - -

- + +

+ : + +

+ - -

- : - -

- + +

+ : + +

+ - -

- Last crawled: %s item(s)', 'litespeed-cache'), $summary[ 'last_crawled' ] ); ?> -

- + +

+ Last crawled: %s item(s)', 'litespeed-cache'), $summary['last_crawled']); ?> +

+ -

- " . __('Reset position', 'litespeed-cache') . ""; - - $href = Router::can_crawl() ? Utility::build_url( Router::ACTION_CRAWLER, Crawler::TYPE_START ) : 'javascript:;'; - echo " " . __('Manually run', 'litespeed-cache') . ""; - ?> -

- - - - - - - - - - - - - $v ) : - $hit = ! empty( $summary[ 'crawler_stats' ][ $i ][ 'H' ] ) ? $summary[ 'crawler_stats' ][ $i ][ 'H' ] : 0; - $miss = ! empty( $summary[ 'crawler_stats' ][ $i ][ 'M' ] ) ? $summary[ 'crawler_stats' ][ $i ][ 'M' ] : 0; - - $blacklisted = ! empty( $summary[ 'crawler_stats' ][ $i ][ 'B' ] ) ? $summary[ 'crawler_stats' ][ $i ][ 'B' ] : 0; - $blacklisted += ! empty( $summary[ 'crawler_stats' ][ $i ][ 'N' ] ) ? $summary[ 'crawler_stats' ][ $i ][ 'N' ] : 0; - - if ( isset( $summary[ 'crawler_stats' ][ $i ][ 'W' ] ) ) { - $waiting = $summary[ 'crawler_stats' ][ $i ][ 'W' ] ?: 0; - } - else { - $waiting = $summary[ 'list_size' ] - $hit - $miss - $blacklisted; - } +

+ " . __('Reset position', 'litespeed-cache') . ""; + + $href = Router::can_crawl() ? Utility::build_url(Router::ACTION_CRAWLER, Crawler::TYPE_START) : 'javascript:;'; + echo " " . __('Manually run', 'litespeed-cache') . ""; ?> -

- - - - - - + + + + + + + + + +
#
- "; - } - ?> - - - - ' . ( $waiting ?: '-' ) . ' '; ?> - ' . ( $hit ?: '-' ) . ' '; ?> - ' . ( $miss ?: '-' ) . ' '; ?> - ' . ( $blacklisted ?: '-' ) . ' '; ?> - - build_toggle( 'litespeed-crawler-'.$i , $__crawler->is_active( $i ) ); ?> - - " . __( 'running', 'litespeed-cache' ) . ""; - } +

+ + + + + + + + + + + + + + + $v) : + $hit = !empty($summary['crawler_stats'][$i]['H']) ? $summary['crawler_stats'][$i]['H'] : 0; + $miss = !empty($summary['crawler_stats'][$i]['M']) ? $summary['crawler_stats'][$i]['M'] : 0; + + $blacklisted = !empty($summary['crawler_stats'][$i]['B']) ? $summary['crawler_stats'][$i]['B'] : 0; + $blacklisted += !empty($summary['crawler_stats'][$i]['N']) ? $summary['crawler_stats'][$i]['N'] : 0; + + if (isset($summary['crawler_stats'][$i]['W'])) { + $waiting = $summary['crawler_stats'][$i]['W'] ?: 0; + } else { + $waiting = $summary['list_size'] - $hit - $miss - $blacklisted; } ?> - - - - -
#
- -

- =
- =
- =
- =
-

- -
-
-
-
Hooking WP-Cron Into the System Task Scheduler to learn how to create the system cron task.','litespeed-cache'), ' href="https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/" target="_blank" '); ?>
-
- +
+ "; + } + ?> + + + + ' . ($waiting ?: '-') . ' '; ?> + ' . ($hit ?: '-') . ' '; ?> + ' . ($miss ?: '-') . ' '; ?> + ' . ($blacklisted ?: '-') . ' '; ?> + + build_toggle('litespeed-crawler-' . $i, $__crawler->is_active($i)); ?> + + " . __('running', 'litespeed-cache') . ""; + } + } + ?> +
+ +

+ =
+ =
+ =
+ =
+

+ +
+
+
+
Hooking WP-Cron Into the System Task Scheduler to learn how to create the system cron task.', 'litespeed-cache'), ' href="https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/" target="_blank" '); ?>
+
+

json_path(); - if ( $ajaxUrl ): + $ajaxUrl = $__crawler->json_path(); + if ($ajaxUrl) : ?> - + -
-
-
-
-
- +
+
+
+
+
+ +
+
    +
  • Start watching...
  • +
  • +
-
    -
  • Start watching...
  • -
  • -
-
- - -

- -

- + + +

+ +

+ \ No newline at end of file diff --git a/tpl/dash/dashboard.tpl.php b/tpl/dash/dashboard.tpl.php index 1901f9083..ccae5d50d 100644 --- a/tpl/dash/dashboard.tpl.php +++ b/tpl/dash/dashboard.tpl.php @@ -1,27 +1,23 @@ scores(); $crawler_summary = Crawler::get_summary(); // Image related info -$optm_summary = Img_Optm::get_summary(); +$img_optm_summary = Img_Optm::get_summary(); $img_count = Img_Optm::cls()->img_count(); -if ( ! empty( $img_count[ 'groups_all' ] ) ) { - $img_gathered_percentage = 100 - floor( $img_count[ 'groups_not_gathered' ] * 100 / $img_count[ 'groups_all' ] ); -} -else { - $img_gathered_percentage = 0; +$img_finished_percentage = 0; +if ($img_count['groups_all']) $img_finished_percentage = 100 - floor($img_count['groups_new'] * 100 / $img_count['groups_all']); +if ($img_finished_percentage == 100 && $img_count['groups_new']) { + $img_finished_percentage = 99; } -if ( ! empty( $img_count[ 'imgs_gathered' ] ) ) { - $img_finished_percentage = 100 - floor( $img_count[ 'img.' . Img_Optm::STATUS_RAW ] * 100 / $img_count[ 'imgs_gathered' ] ); -} -else { - $img_finished_percentage = 0; -} +$__cloud = Cloud::cls(); $cloud_summary = Cloud::get_summary(); $css_summary = CSS::get_summary(); @@ -29,10 +25,10 @@ $placeholder_summary = Placeholder::get_summary(); $vpi_summary = VPI::get_summary(); -$ccss_count = count( $this->load_queue( 'ccss' ) ); -$ucss_count = count( $this->load_queue( 'ucss' ) ); -$placeholder_queue_count = count( $this->load_queue( 'lqip' ) ); -$vpi_queue_count = count( $this->load_queue( 'vpi' ) ); +$ccss_count = count($this->load_queue('ccss')); +$ucss_count = count($this->load_queue('ucss')); +$placeholder_queue_count = count($this->load_queue('lqip')); +$vpi_queue_count = count($this->load_queue('vpi')); ?>
@@ -40,26 +36,26 @@
__( 'Image Optimization', 'litespeed-cache' ), - 'page_optm' => __( 'Page Optimization', 'litespeed-cache' ), - 'cdn' => __( 'CDN Bandwidth', 'litespeed-cache' ), - 'lqip' => __( 'Low Quality Image Placeholder', 'litespeed-cache' ), + 'img_optm' => __('Image Optimization', 'litespeed-cache'), + 'page_optm' => __('Page Optimization', 'litespeed-cache'), + 'cdn' => __('CDN Bandwidth', 'litespeed-cache'), + 'lqip' => __('Low Quality Image Placeholder', 'litespeed-cache'), ); - foreach ( $cat_list as $svc => $title ) : + foreach ($cat_list as $svc => $title) : $finished_percentage = 0; $total_used = $used = $quota = $pag_used = $pag_total = '-'; $pag_width = 0; @@ -67,34 +63,35 @@ $pag_txt_color = ''; $usage = false; - if ( ! empty( $cloud_summary[ 'usage.' . $svc ] ) ) { - $usage = $cloud_summary[ 'usage.' . $svc ]; - $finished_percentage = floor( $usage[ 'used' ] * 100 / $usage[ 'quota' ] ); - $used = (int)$usage[ 'used' ]; - $quota = (int)$usage[ 'quota' ]; - $pag_used = ! empty( $usage[ 'pag_used' ] ) ? (int)$usage[ 'pag_used' ] : 0; - $pag_bal = ! empty( $usage[ 'pag_bal' ] ) ? (int)$usage[ 'pag_bal' ] : 0; + if (!empty($cloud_summary['usage.' . $svc])) { + $usage = $cloud_summary['usage.' . $svc]; + $finished_percentage = floor($usage['used'] * 100 / $usage['quota']); + $used = (int)$usage['used']; + $quota = (int)$usage['quota']; + $pag_used = !empty($usage['pag_used']) ? (int)$usage['pag_used'] : 0; + $pag_bal = !empty($usage['pag_bal']) ? (int)$usage['pag_bal'] : 0; $pag_total = $pag_used + $pag_bal; - if ( ! empty( $usage[ 'total_used' ] ) ) { - $total_used = (int)$usage[ 'total_used' ]; + if (!empty($usage['total_used'])) { + $total_used = (int)$usage['total_used']; } - if ( $pag_total ) { - $pag_width = round( $pag_used / $pag_total * 100 ) . '%'; + if ($pag_total) { + // $finished_percentage = floor( ($pag_used+$usage[ 'used' ]) * 100 / ($usage[ 'quota' ]+$pag_total) ); + $pag_width = round($pag_used / $pag_total * 100) . '%'; } - if ( $finished_percentage > 85 ) { + if ($finished_percentage > 85) { $percentage_bg = 'warning'; - if ( $finished_percentage > 95 ) { + if ($finished_percentage > 95) { $percentage_bg = 'danger'; - if ( $pag_bal ) { // is using PAG quota + if ($pag_bal) { // is using PAG quota $percentage_bg = 'warning'; $pag_txt_color = 'litespeed-success'; } } } - if ( $svc == 'cdn' ) { + if ($svc == 'cdn') { // $used = Utility::real_size( $used * 1000000 * 100, true ); // $quota = Utility::real_size( $quota * 1000000 * 100, true ); // $pag_used = Utility::real_size( $pag_used * 1000000 * 100, true ); @@ -108,15 +105,15 @@

-
- +
+
-

+

- + of

@@ -124,40 +121,41 @@
- 0 ) { ?> + 0) { ?>

- : -

- - + +

- $sub_usage ) : ?> - : - + $sub_usage) : ?> + : +

- +

- : / ∞ -

- = 0 && isset( $usage[ 'daily_quota' ] ) && $usage[ 'daily_quota' ] >= 0 ) { ?> + = 0 && isset($usage['daily_quota']) && $usage['daily_quota'] >= 0) { ?>

- : / + : /

@@ -166,32 +164,40 @@ -
-
-

-
- - - - <?php echo $cloud_summary['partner']['name']; ?> - - <?php echo $cloud_summary['partner']['name']; ?> - - - - - - +
+
+

+
+ + + + <?php echo $cloud_summary['partner']['name']; ?> + + <?php echo $cloud_summary['partner']['name']; ?> + + + + + + + - +
-
- +

@@ -200,9 +206,10 @@

- - + + +

@@ -210,30 +217,30 @@
- +

- +

- s + s

- +

- s + s

- +

- % + %
@@ -243,13 +250,13 @@
@@ -257,17 +264,18 @@

- - + + + - - conf( $id ) ) : ?> + + conf($id)) : ?> ON - + OFF @@ -278,32 +286,32 @@
- -
-

- -

-
- get_cls_of_pagescore( $health_scores[ 'score_before' ] ) ); ?> + +
+

+ +

+
+ get_cls_of_pagescore($health_scores['score_before'])); ?> +
-
-
-

- -

-
- get_cls_of_pagescore( $health_scores[ 'score_after' ] ) ); ?> +
+

+ +

+
+ get_cls_of_pagescore($health_scores['score_after'])); ?> +
-
-
-

- -

-
- % +
+

+ +

+
+ % +
-
- +
@@ -311,9 +319,9 @@
- +
@@ -321,84 +329,75 @@

- - + +

+

+ : +

+

+ : +

+ -
-
- -
-
-
-

-

- - of -

-
-
-
- -

- : - - - () - -

+ +

+ : + + + () + +

- +

: - - () + + ()

- : + :

- : + :

Lang::title( Base::O_IMG_OPTM_AUTO ), - Base::O_IMG_OPTM_CRON => Lang::title( Base::O_IMG_OPTM_CRON ), + Base::O_IMG_OPTM_AUTO => Lang::title(Base::O_IMG_OPTM_AUTO), + Base::O_IMG_OPTM_CRON => Lang::title(Base::O_IMG_OPTM_CRON), ); - foreach ( $cache_list as $id => $title ) : + foreach ($cache_list as $id => $title) : ?>

- conf( $id ) ) : ?> + conf($id)) : ?> ON - + OFF - +

@@ -410,26 +409,26 @@

- - + +

- __( 'Public Cache', 'litespeed-cache' ), - Base::O_CACHE_PRIV => __( 'Private Cache', 'litespeed-cache' ), - Base::O_OBJECT => __( 'Object Cache', 'litespeed-cache' ), - Base::O_CACHE_BROWSER => __( 'Browser Cache', 'litespeed-cache' ), + Base::O_CACHE => __('Public Cache', 'litespeed-cache'), + Base::O_CACHE_PRIV => __('Private Cache', 'litespeed-cache'), + Base::O_OBJECT => __('Object Cache', 'litespeed-cache'), + Base::O_CACHE_BROWSER => __('Browser Cache', 'litespeed-cache'), ); - foreach ( $cache_list as $id => $title ) : - ?> + foreach ($cache_list as $id => $title) : + ?>

- conf( $id ) ) : ?> + conf($id)) : ?> ON - + OFF - +

@@ -438,32 +437,31 @@

- - + +

- +

- ' . Utility::readable_time( $css_summary[ 'last_request_ccss' ] ) . ''; ?> + ' . Utility::readable_time($css_summary['last_request_ccss']) . ''; ?>

- ' . esc_html( $css_summary[ 'last_spent_ccss' ] ) . 's'; ?> + ' . esc_html($css_summary['last_spent_ccss']) . 's'; ?>

- : - - + : + +

- +
@@ -471,32 +469,31 @@ class="button button-secondary button-small

- - + +

- +

- ' . Utility::readable_time( $ucss_summary[ 'last_request' ] ) . ''; ?> + ' . Utility::readable_time($ucss_summary['last_request']) . ''; ?>

- ' . esc_html( $ucss_summary[ 'last_spent' ] ) . 's'; ?> + ' . esc_html($ucss_summary['last_spent']) . 's'; ?>

- : - - + : + +

- +
@@ -504,31 +501,31 @@ class="button button-secondary button-small

- - + +

- +

- ' . Utility::readable_time( $placeholder_summary[ 'last_request' ] ) . ''; ?> + ' . Utility::readable_time($placeholder_summary['last_request']) . ''; ?>

- ' . esc_html( $placeholder_summary[ 'last_spent' ] ) . 's'; ?> + ' . esc_html($placeholder_summary['last_spent']) . 's'; ?>

- : - - + : + +

- +
@@ -536,31 +533,31 @@ class="button button-secondary button-small

- (VPI) - + (VPI) +

- +

- ' . Utility::readable_time( $vpi_summary[ 'last_request' ] ) . ''; ?> + ' . Utility::readable_time($vpi_summary['last_request']) . ''; ?>

- ' . esc_html( $vpi_summary[ 'last_spent' ] ) . 's'; ?> + ' . esc_html($vpi_summary['last_spent']) . 's'; ?>

- : - - + : + +

- +
@@ -568,50 +565,70 @@ class="button button-secondary button-small

- - + +

- list_crawlers() );?> + list_crawlers()); ?>

- : + :

- -

- : - -

+ +

+ : + +

- -

- : - -

+ +

+ : + +

- -

- : - -

+ +

+ : + +

- -

- Last crawled: %d item(s)', 'litespeed-cache'), $crawler_summary[ 'last_crawled' ] ); ?> -

+ +

+ Last crawled: %d item(s)', 'litespeed-cache'), $crawler_summary['last_crawled']); ?> +

+
+
+

+ QUIC.cloud + +

+

+ +

+

+ +

+

+ more!', 'litespeed-cache'), ' href="https://www.quic.cloud/quic-cloud-services-and-features/litespeed-cache-service/" target="_blank"'); ?> +

+
+ QUIC.cloud +
+
+
+

- -
+
\ No newline at end of file diff --git a/tpl/db_optm/manage.tpl.php b/tpl/db_optm/manage.tpl.php index 5fc44f734..8a61b4025 100644 --- a/tpl/db_optm/manage.tpl.php +++ b/tpl/db_optm/manage.tpl.php @@ -1,68 +1,74 @@ array( - 'title' => __( 'Clean All', 'litespeed-cache' ), + 'title' => __('Clean All', 'litespeed-cache'), 'desc' => '', ), 'revision' => array( - 'title' => __( 'Post Revisions', 'litespeed-cache' ), - 'desc' => __( 'Clean all post revisions', 'litespeed-cache' ), + 'title' => __('Post Revisions', 'litespeed-cache'), + 'desc' => __('Clean all post revisions', 'litespeed-cache'), + ), + 'orphaned_post_meta' => array( + 'title' => __('Orphaned Post Meta', 'litespeed-cache'), + 'desc' => __('Clean all orphaned post meta records', 'litespeed-cache'), ), 'auto_draft' => array( - 'title' => __( 'Auto Drafts', 'litespeed-cache' ), - 'desc' => __( 'Clean all auto saved drafts', 'litespeed-cache' ), + 'title' => __('Auto Drafts', 'litespeed-cache'), + 'desc' => __('Clean all auto saved drafts', 'litespeed-cache'), ), 'trash_post' => array( - 'title' => __( 'Trashed Posts', 'litespeed-cache' ), - 'desc' => __( 'Clean all trashed posts and pages', 'litespeed-cache' ), + 'title' => __('Trashed Posts', 'litespeed-cache'), + 'desc' => __('Clean all trashed posts and pages', 'litespeed-cache'), ), 'spam_comment' => array( - 'title' => __( 'Spam Comments', 'litespeed-cache' ), - 'desc' => __( 'Clean all spam comments', 'litespeed-cache' ), + 'title' => __('Spam Comments', 'litespeed-cache'), + 'desc' => __('Clean all spam comments', 'litespeed-cache'), ), 'trash_comment' => array( - 'title' => __( 'Trashed Comments', 'litespeed-cache' ), - 'desc' => __( 'Clean all trashed comments', 'litespeed-cache' ), + 'title' => __('Trashed Comments', 'litespeed-cache'), + 'desc' => __('Clean all trashed comments', 'litespeed-cache'), ), 'trackback-pingback' => array( - 'title' => __( 'Trackbacks/Pingbacks', 'litespeed-cache' ), - 'desc' => __( 'Clean all trackbacks and pingbacks', 'litespeed-cache' ), + 'title' => __('Trackbacks/Pingbacks', 'litespeed-cache'), + 'desc' => __('Clean all trackbacks and pingbacks', 'litespeed-cache'), ), 'expired_transient' => array( - 'title' => __( 'Expired Transients', 'litespeed-cache' ), - 'desc' => __( 'Clean expired transient options', 'litespeed-cache' ), + 'title' => __('Expired Transients', 'litespeed-cache'), + 'desc' => __('Clean expired transient options', 'litespeed-cache'), ), 'all_transients' => array( - 'title' => __( 'All Transients', 'litespeed-cache' ), - 'desc' => __( 'Clean all transient options', 'litespeed-cache' ), + 'title' => __('All Transients', 'litespeed-cache'), + 'desc' => __('Clean all transient options', 'litespeed-cache'), ), 'optimize_tables' => array( - 'title' => __( 'Optimize Tables', 'litespeed-cache' ), - 'desc' => __( 'Optimize all tables in your database', 'litespeed-cache' ), + 'title' => __('Optimize Tables', 'litespeed-cache'), + 'desc' => __('Optimize all tables in your database', 'litespeed-cache'), ), ); -$rev_max = $this->conf( Base::O_DB_OPTM_REVISIONS_MAX ); -$rev_age = $this->conf( Base::O_DB_OPTM_REVISIONS_AGE ); -if ( $rev_max || $rev_age ) { - $_panels[ 'revision' ][ 'desc' ] = sprintf( __( 'Clean revisions older than %1$s day(s), excluding %2$s latest revisions', 'litespeed-cache' ), '' . $rev_age . '' , '' . $rev_max . '' ); +$rev_max = $this->conf(Base::O_DB_OPTM_REVISIONS_MAX); +$rev_age = $this->conf(Base::O_DB_OPTM_REVISIONS_AGE); +if ($rev_max || $rev_age) { + $_panels['revision']['desc'] = sprintf(__('Clean revisions older than %1$s day(s), excluding %2$s latest revisions', 'litespeed-cache'), '' . $rev_age . '', '' . $rev_max . ''); } $total = 0; -foreach ( $_panels as $tag => $v ) { - if ( $tag != 'all' ) { - $_panels[ $tag ][ 'count' ] = $this->cls( 'DB_Optm' )->db_count( $tag ); - if ( ! in_array( $tag, array( 'optimize_tables' ) ) ) { - $total += $_panels[ $tag ][ 'count' ]; +foreach ($_panels as $tag => $v) { + if ($tag != 'all') { + $_panels[$tag]['count'] = $this->cls('DB_Optm')->db_count($tag); + if (!in_array($tag, array('optimize_tables'))) { + $total += $_panels[$tag]['count']; } } - $_panels[ $tag ][ 'link' ] = Utility::build_url( Router::ACTION_DB_OPTM, $tag ); + $_panels[$tag]['link'] = Utility::build_url(Router::ACTION_DB_OPTM, $tag); } -$_panels[ 'all' ][ 'count' ] = $total; +$_panels['all']['count'] = $total; $autoload_summary = DB_Optm::cls()->autoload_summary(); @@ -70,67 +76,69 @@

- +

-

+

- - - - - - + + + + + + + + - list_myisam(); - if ( $list ) : - foreach ( $list as $k => $v ) : - ?> + if ($list) : + foreach ($list as $k => $v) : + ?> + + + + + + + + - - - - - - - - - - +
#
#
TABLE_NAME; ?>ENGINE; ?> + + + +
TABLE_NAME; ?>ENGINE; ?> - - - + +
- -
@@ -143,45 +151,42 @@ margin-left: 20px; margin-right: 20px; } - .litespeed-body .field-col:first-child{ - margin-left:0; + + .litespeed-body .field-col:first-child { + margin-left: 0; } -

+

- Autoload size: autoload_size ); ?>

+ Autoload size: autoload_size); ?>

Autoload entries: autload_entries; ?>

-

Autoload top list:

+

Autoload top list:

- - - - - - - autoload_toplist as $k => $v ) : ?> + - - - + + + + + + autoload_toplist as $k => $v) : ?> + + + + +
#
option_name; ?>option_value_length; ?>#
option_name; ?>option_value_length; ?>
-
- - - - - - +
\ No newline at end of file diff --git a/tpl/general/entry.tpl.php b/tpl/general/entry.tpl.php index 8377bf5f9..62fb35a3e 100644 --- a/tpl/general/entry.tpl.php +++ b/tpl/general/entry.tpl.php @@ -39,7 +39,6 @@
form_action(); // include all tpl for faster UE foreach ($menu_list as $tab => $val) { @@ -48,7 +47,6 @@ echo "
"; } - $this->form_end(); ?>
diff --git a/tpl/general/network_settings.tpl.php b/tpl/general/network_settings.tpl.php index e32c3bb0c..fddcc6bce 100644 --- a/tpl/general/network_settings.tpl.php +++ b/tpl/general/network_settings.tpl.php @@ -2,6 +2,7 @@ namespace LiteSpeed; defined( 'WPINC' ) || exit; +$this->form_action(); ?>

diff --git a/tpl/general/settings.tpl.php b/tpl/general/settings.tpl.php index 96557c3c3..49c64ff5f 100644 --- a/tpl/general/settings.tpl.php +++ b/tpl/general/settings.tpl.php @@ -1,6 +1,8 @@ can_token(); -$is_requesting = ! empty( $cloud_summary[ 'token_ts' ] ) && ( empty( $cloud_summary[ 'apikey_ts' ] ) || $cloud_summary[ 'token_ts' ] > $cloud_summary[ 'apikey_ts' ] ); +$is_requesting = !empty($cloud_summary['token_ts']) && (empty($cloud_summary['apikey_ts']) || $cloud_summary['token_ts'] > $cloud_summary['apikey_ts']); -$apply_btn_txt = __( 'Request Domain Key', 'litespeed-cache' ); -if ( $this->conf( Base::O_API_KEY ) ) { - $apply_btn_txt = __( 'Refresh Domain Key', 'litespeed-cache' ); - if ( $is_requesting ) { - $apply_btn_txt = __( 'Waiting for Refresh', 'litespeed-cache' ); +$apply_btn_txt = __('Request Domain Key', 'litespeed-cache'); +if ($this->conf(Base::O_API_KEY)) { + $apply_btn_txt = __('Refresh Domain Key', 'litespeed-cache'); + if ($is_requesting) { + $apply_btn_txt = __('Waiting for Refresh', 'litespeed-cache'); } -} -elseif ( $is_requesting ) { - $apply_btn_txt = __( 'Waiting for Approval', 'litespeed-cache' ); +} elseif ($is_requesting) { + $apply_btn_txt = __('Waiting for Approval', 'litespeed-cache'); } $apply_ts_txt = ''; -if ( ! empty( $cloud_summary[ 'token_ts' ] ) ) { - $apply_ts_txt .= ' ' . __( 'Requested', 'litespeed-cache' ) . ': ' . Utility::readable_time( $cloud_summary[ 'token_ts' ] ) . ''; +if (!empty($cloud_summary['token_ts'])) { + $apply_ts_txt .= ' ' . __('Requested', 'litespeed-cache') . ': ' . Utility::readable_time($cloud_summary['token_ts']) . ''; } -if ( ! empty( $cloud_summary[ 'apikey_ts' ] ) ) { - $apply_ts_txt .= ' ' . __( 'Approved', 'litespeed-cache' ) . ': ' . Utility::readable_time( $cloud_summary[ 'apikey_ts' ] ) . ''; +if (!empty($cloud_summary['apikey_ts'])) { + $apply_ts_txt .= ' ' . __('Approved', 'litespeed-cache') . ': ' . Utility::readable_time($cloud_summary['apikey_ts']) . ''; } -if ( ! $can_token ) { - $next_available_req = $cloud_summary[ 'token_ts' ] + Cloud::EXPIRATION_TOKEN - time(); - $apply_ts_txt .= ' ' . sprintf( __( 'Next available request time: After %s', 'litespeed-cache' ), Utility::readable_time( $next_available_req, 0, true ) ); +if (!$can_token) { + $next_available_req = $cloud_summary['token_ts'] + Cloud::EXPIRATION_TOKEN - time(); + $apply_ts_txt .= ' ' . sprintf(__('Next available request time: After %s', 'litespeed-cache'), Utility::readable_time($next_available_req, 0, true)); } +$this->form_action(); ?>

- - + +

- - _is_multisite ) : ?> - - - - - - - - - - - - - - - - - - -
- - title( $id ); ?> - - - build_input( $id ); ?> - - build_input( $id, null, null, 'text', true ); ?> - - - - - - - - - - - - - - can_link_qc() ) : ?> - - - - - - -
-

:

-

' . $apply_btn_txt . '' ); ?>

-

:

-

1) ' . home_url() . '/' . ( function_exists( 'rest_get_url_prefix' ) ? rest_get_url_prefix() : apply_filters( 'rest_url_prefix', 'wp-json' ) ) . '/litespeed/v1/token' ); ?>

-

2)

-

:

-
- + + + _is_multisite) : ?> + + + + + + - - - _is_multisite ) : ?> - - - - - - + + _is_multisite) : ?> + + + + + + + + + + + + + + + + + - conf( Base::O_IMG_OPTM_WEBP ) ) : ?> -
- ⚠️ : ' . Lang::title( Base::O_IMG_OPTM_WEBP ) . '' ); ?> - - + +
+ + title($id); ?> + + + build_input($id); ?> + + build_input($id, null, null, 'text', true); ?> + - -
-

:

-

-
- + + + + + + + + - conf( Base::O_API_KEY ) ) : ?> -
-

:

-

' . Lang::title( Base::O_API_KEY ) . '' ) . ' See Terms.'; ?>

-
- -
-

:

-

' . __( 'Link to QUIC.cloud', 'litespeed-cache' ) . '' ); ?>

-

-
- - -
- - -
- - : - - - ⚠️ - + + qc_link(), __('Visit My Dashboard on QUIC.cloud', 'litespeed-cache'), false, 'button litespeed-btn-success litespeed-right'); ?> + can_link_qc()) : ?> + + + + + + +
+

:

+

' . $apply_btn_txt . ''); ?>

+

:

+

1) ' . home_url() . '/' . (function_exists('rest_get_url_prefix') ? rest_get_url_prefix() : apply_filters('rest_url_prefix', 'wp-json')) . '/litespeed/v1/token'); ?>

+

2)

+

:

+
+ + + +
+

:

+

+
+ + + conf(Base::O_API_KEY)) : ?> +
+

:

+

' . Lang::title(Base::O_API_KEY) . '') . ' See Terms.'; ?>

+
+ +
+

:

+

' . __('Link to QUIC.cloud', 'litespeed-cache') . ''); ?>

+

+
-
- -
-

- ' data-litespeed-cfm=""> -

-

- Service: ' . $svc . ' Node: ' . $cloud_summary[ 'server.' . $svc ] . ' Connected Date: ' . Utility::readable_time( $cloud_summary[ 'server_date.' . $svc ] ) . '

'; +
+ + +
+ + : + + + ⚠️ + + + +
+ +
+

+ ' data-litespeed-cfm=""> +

+

+ Service: ' . $svc . ' Node: ' . $cloud_summary['server.' . $svc] . ' Connected Date: ' . Utility::readable_time($cloud_summary['server_date.' . $svc]) . '

'; + } + } + if (!$has_service) { + echo __('No cloud services currently in use', 'litespeed-cache'); } - } - if ( ! $has_service ) { - echo __( 'No cloud services currently in use', 'litespeed-cache' ); - } - ?> -

+ ?> +

+
-
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - - - +
+ + title($id); ?> + + build_switch($id); ?> +
+ + 🚨 + + + + + conf( Base::O_GUEST ) && ! $this->conf( Base::O_OPTM_UCSS ) ) { + if ($this->conf(Base::O_GUEST) && !$this->conf(Base::O_OPTM_UCSS)) { $typeList[] = 'UCSS'; } - if ( $this->conf( Base::O_GUEST ) && ! $this->conf( Base::O_OPTM_CSS_ASYNC ) ) { + if ($this->conf(Base::O_GUEST) && !$this->conf(Base::O_OPTM_CSS_ASYNC)) { $typeList[] = 'CCSS'; } - if ( ! empty( $typeList ) ) { - $theType = implode( '/', $typeList ); + if (!empty($typeList)) { + $theType = implode('/', $typeList); echo '
'; echo ''; - echo '⚠️ ' . sprintf( __( 'Your %1s quota on %2s will still be in use.', 'litespeed-cache' ), $theType, 'QUIC.cloud' ); + echo '⚠️ ' . sprintf(__('Your %1s quota on %2s will still be in use.', 'litespeed-cache'), $theType, 'QUIC.cloud'); echo ''; } - ?> - - conf( Base::O_GUEST ) ) : ?> -
- ⚠️ : ' . Lang::title( Base::O_GUEST ) . '' ); ?> - - - - conf( Base::O_CACHE_MOBILE ) ) : ?> -
- ⚠️ : ' . Lang::title( Base::O_CACHE_MOBILE ) . '' ); ?> - - + ?> + + conf(Base::O_GUEST)) : ?> +
+ + ⚠️ : ' . Lang::title(Base::O_GUEST) . ''); ?> + + + + conf(Base::O_CACHE_MOBILE)) : ?> +
+ + ⚠️ : ' . Lang::title(Base::O_CACHE_MOBILE) . ''); ?> + + + + conf(Base::O_IMG_OPTM_WEBP)) : ?> +
+ + ⚠️ : ' . Lang::title(Base::O_IMG_OPTM_WEBP) . ''); ?> + + +
+
+ + title($id); ?> + + build_input($id); ?> +
+ +
: - DoAPI.us + ⚠️ : +
+ + _validate_ip($id); ?> +
+
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
- conf( Base::O_IMG_OPTM_WEBP_REPLACE ) ) : ?> -
- ⚠️ : ' . Lang::title( Base::O_IMG_OPTM_WEBP_REPLACE ) . '' ); ?> - - - -
- - title( $id ); ?> - - build_input($id); ?> -
- -
: - DoAPI.us - ⚠️ : -
- - _validate_ip( $id ); ?> -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
+form_end(); ?> \ No newline at end of file diff --git a/tpl/general/settings_tuning.tpl.php b/tpl/general/settings_tuning.tpl.php index 9eaf42994..02c5d7a20 100644 --- a/tpl/general/settings_tuning.tpl.php +++ b/tpl/general/settings_tuning.tpl.php @@ -2,6 +2,7 @@ namespace LiteSpeed; defined( 'WPINC' ) || exit; +$this->form_action(); ?>

@@ -53,3 +54,5 @@ + +form_end(); ?> diff --git a/tpl/img_optm/settings.media_webp.tpl.php b/tpl/img_optm/settings.media_webp.tpl.php index a4d988e9e..07e243a60 100644 --- a/tpl/img_optm/settings.media_webp.tpl.php +++ b/tpl/img_optm/settings.media_webp.tpl.php @@ -1,19 +1,23 @@ - - - - title( $id ); ?> - - - build_switch( $id ); ?> -
- -
-
-
- - + + + + title($id); ?> + + + build_switch($id); ?> + +
+ + +
+
+
+ + \ No newline at end of file diff --git a/tpl/img_optm/settings.tpl.php b/tpl/img_optm/settings.tpl.php index fc7a80997..426568c01 100644 --- a/tpl/img_optm/settings.tpl.php +++ b/tpl/img_optm/settings.tpl.php @@ -98,19 +98,6 @@ - - - - title( $id ); ?> - - - build_switch( $id ); ?> -
- -
- - - allowance( Cloud::SVC_IMG_OPTM ); +defined('WPINC') || exit; + +$closest_server = Cloud::get_summary('server.' . Cloud::SVC_IMG_OPTM); +$usage_cloud = Cloud::get_summary('usage.' . Cloud::SVC_IMG_OPTM); +$allowance = Cloud::cls()->allowance(Cloud::SVC_IMG_OPTM); $__img_optm = Img_Optm::cls(); $wet_limit = $__img_optm->wet_limit(); $img_count = $__img_optm->img_count(); -$need_gather = $__img_optm->need_gather(); $optm_summary = Img_Optm::get_summary(); -list( $last_run, $is_running ) = $__img_optm->cron_running( false ); - -if ( ! empty( $img_count[ 'groups_all' ] ) ) { - $gathered_percentage = 100 - floor( $img_count[ 'groups_not_gathered' ] * 100 / $img_count[ 'groups_all' ] ); - if ( $gathered_percentage == 100 && $img_count[ 'groups_not_gathered' ] ) { - $gathered_percentage = 99; - } -} -else { - $gathered_percentage = 0; -} - -if ( ! empty( $img_count[ 'imgs_gathered' ] ) ) { - $finished_percentage = 100 - floor( $img_count[ 'img.' . Img_Optm::STATUS_RAW ] * 100 / $img_count[ 'imgs_gathered' ] ); - if ( $finished_percentage == 100 && $img_count[ 'img.' . Img_Optm::STATUS_RAW ] ) { - $finished_percentage = 99; - } -} -else { - $finished_percentage = 0; +list($last_run, $is_running) = $__img_optm->cron_running(false); +$finished_percentage = 0; +if ($img_count['groups_all']) $finished_percentage = 100 - floor($img_count['groups_new'] * 100 / $img_count['groups_all']); +if ($finished_percentage == 100 && $img_count['groups_new']) { + $finished_percentage = 99; } $unfinished_num = 0; -if ( ! empty( $img_count[ 'img.' . Img_Optm::STATUS_REQUESTED ] ) ) { - $unfinished_num += $img_count[ 'img.' . Img_Optm::STATUS_REQUESTED ]; +if (!empty($img_count['img.' . Img_Optm::STATUS_REQUESTED])) { + $unfinished_num += $img_count['img.' . Img_Optm::STATUS_REQUESTED]; } -if ( ! empty( $img_count[ 'img.' . Img_Optm::STATUS_NOTIFIED ] ) ) { - $unfinished_num += $img_count[ 'img.' . Img_Optm::STATUS_NOTIFIED ]; +if (!empty($img_count['img.' . Img_Optm::STATUS_NOTIFIED])) { + $unfinished_num += $img_count['img.' . Img_Optm::STATUS_NOTIFIED]; } -if ( ! empty( $img_count[ 'img.' . Img_Optm::STATUS_ERR_FETCH ] ) ) { - $unfinished_num += $img_count[ 'img.' . Img_Optm::STATUS_ERR_FETCH ]; +if (!empty($img_count['img.' . Img_Optm::STATUS_ERR_FETCH])) { + $unfinished_num += $img_count['img.' . Img_Optm::STATUS_ERR_FETCH]; } ?> @@ -53,151 +39,131 @@

- - + + - + - +

- ' . intval( $allowance ) . '' ); ?> + ' . intval($allowance) . ''); ?>

- -

- - ' . $wet_limit . ''; ?> -

+ +

+ + ' . $wet_limit . ''; ?> +

- - - - +

- +

- : + : - - () + + +

+ + + +

+ : + + + () + +

+ + + +

+ : + + + ()

- - + +

- +

- : + : - - () + + ()

- +

- ' . Utility::readable_time( $last_run ) . '' ); ?> + ' . Utility::readable_time($last_run) . ''); ?>

- +

- : + : - - () + + ()

-
- - - -

- : - - - () - -

- -
-

 %4$s', - ($unfinished_num ? Utility::build_url( Router::ACTION_IMG_OPTM, Img_Optm::TYPE_CLEAN ) : 'javascript:;'), - __( 'Remove all previous unfinished image optimization requests.', 'litespeed-cache' ), + ($unfinished_num ? Utility::build_url(Router::ACTION_IMG_OPTM, Img_Optm::TYPE_CLEAN) : 'javascript:;'), + __('Remove all previous unfinished image optimization requests.', 'litespeed-cache'), ($unfinished_num ? '' : ' disabled'), - __( 'Clean Up Unfinished Data', 'litespeed-cache' ) . ( $unfinished_num ? ': ' . Admin_Display::print_plural( $unfinished_num, 'image' ) : '') + __('Clean Up Unfinished Data', 'litespeed-cache') . ($unfinished_num ? ': ' . Admin_Display::print_plural($unfinished_num, 'image') : '') ); - ?>

+ ?>

- +

- +

- +

- ' . Utility::readable_time( $optm_summary[ 'bk_summary' ][ 'date' ] ) . ''; ?> + ' . Utility::readable_time($optm_summary['bk_summary']['date']) . ''; ?>

- +

- ' . intval( $optm_summary[ 'bk_summary' ][ 'count' ] ) . ''; ?> + ' . intval($optm_summary['bk_summary']['count']) . ''; ?>

- ' . Utility::real_size( $optm_summary[ 'bk_summary' ][ 'sum' ] ) . ''; ?> + ' . Utility::real_size($optm_summary['bk_summary']['sum']) . ''; ?>

@@ -205,24 +171,18 @@
-

+

- get_image_sizes() as $title => $size ) { - echo "
$title ( " . ( $size[ 'width' ] ? $size[ 'width' ] . 'px' : '*' ) . ' x ' . ( $size[ 'height' ] ? $size[ 'height' ] . 'px' : '*' ) . ' )
'; + get_image_sizes() as $title => $size) { + echo "
$title ( " . ($size['width'] ? $size['width'] . 'px' : '*') . ' x ' . ($size['height'] ? $size['height'] . 'px' : '*') . ' )
'; }; ?>
@@ -230,31 +190,31 @@
-

+

- 🚨  - + 🚨  +

- +
-

- ' . Utility::readable_time( $optm_summary[ 'rmbk_summary' ][ 'date' ] ) . ''; ?> -

-

- ' . $optm_summary[ 'rmbk_summary' ][ 'count' ] . ''; ?> -

-

- ' . Utility::real_size( $optm_summary[ 'rmbk_summary' ][ 'sum' ] ) . ''; ?> -

+

+ ' . Utility::readable_time($optm_summary['rmbk_summary']['date']) . ''; ?> +

+

+ ' . $optm_summary['rmbk_summary']['count'] . ''; ?> +

+

+ ' . Utility::real_size($optm_summary['rmbk_summary']['sum']) . ''; ?> +

- +
@@ -264,65 +224,38 @@

- +

- +

- : + : - - - - - - -

-

- - : - + + - + -

-
-
- -
-
- -
-
-

- : - - - - + - +

- - : - - - - + :
+ :

- @@ -330,20 +263,24 @@

- +

- : + : +

+

+ :

- : + :

- : + : +

@@ -352,17 +289,17 @@

- +

@@ -370,15 +307,14 @@
-
- +
\ No newline at end of file diff --git a/tpl/inc/admin_footer.php b/tpl/inc/admin_footer.php index 1597be08d..5b7898b89 100644 --- a/tpl/inc/admin_footer.php +++ b/tpl/inc/admin_footer.php @@ -1,23 +1,24 @@ '; -$rate_us = '' - . sprintf( __( 'Rate %s on %s', 'litespeed-cache' ), '' . __( 'LiteSpeed Cache', 'litespeed-cache' ) . $stars . '', 'WordPress.org' ) - . '' ; +$stars = + ''; +$rate_us = + '' . + sprintf(__('Rate %s on %s', 'litespeed-cache'), '' . __('LiteSpeed Cache', 'litespeed-cache') . $stars . '', 'WordPress.org') . + ''; -$wiki = '' . __( 'Read LiteSpeed Documentation', 'litespeed-cache' ) . '' ; +$wiki = '' . __('Read LiteSpeed Documentation', 'litespeed-cache') . ''; -$forum = '' . __( 'Visit LSCWP support forum', 'litespeed-cache' ) . '' ; +$forum = '' . __('Visit LSCWP support forum', 'litespeed-cache') . ''; -$community = '' . __( 'Join LiteSpeed Slack community', 'litespeed-cache' ) . '' ; +$community = '' . __('Join LiteSpeed Slack community', 'litespeed-cache') . ''; // Change the footer text -if ( ! is_multisite() || is_network_admin() ) { - $footer_text = $rate_us . ' | ' . $wiki . ' | ' . $forum . ' | ' . $community ; +if (!is_multisite() || is_network_admin()) { + $footer_text = $rate_us . ' | ' . $wiki . ' | ' . $forum . ' | ' . $community; +} else { + $footer_text = $wiki . ' | ' . $forum . ' | ' . $community; } -else { - $footer_text = $wiki . ' | ' . $forum . ' | ' . $community ; -} \ No newline at end of file diff --git a/tpl/inc/disabled_all.php b/tpl/inc/disabled_all.php index 0ae2536b1..9299abfa9 100644 --- a/tpl/inc/disabled_all.php +++ b/tpl/inc/disabled_all.php @@ -1,9 +1,8 @@ _postmeta_settings as $k => $v ) { - $existing_val = get_post_meta( $post_id, $k, true ); +foreach ($this->_postmeta_settings as $k => $v) { + $existing_val = get_post_meta($post_id, $k, true); - - if ( in_array( $k, array( 'litespeed_vpi_list', 'litespeed_vpi_list_mobile' ) ) ) { - if ( is_array( $existing_val ) ) $existing_val = implode( PHP_EOL, $existing_val ); + if (in_array($k, array('litespeed_vpi_list', 'litespeed_vpi_list_mobile'))) { + if (is_array($existing_val)) { + $existing_val = implode(PHP_EOL, $existing_val); + } echo '
'; echo ''; echo '
'; - } - else { + } else { echo '
'; - echo ''; + echo ''; echo '
'; } } echo '
'; -Doc::learn_more( 'https://docs.litespeedtech.com/lscache/lscwp/metabox/' ); -echo '
'; \ No newline at end of file +Doc::learn_more('https://docs.litespeedtech.com/lscache/lscwp/metabox/'); +echo '
'; diff --git a/tpl/inc/show_display_installed.php b/tpl/inc/show_display_installed.php index 3ac4ce2c6..bbf1d6ee0 100644 --- a/tpl/inc/show_display_installed.php +++ b/tpl/inc/show_display_installed.php @@ -1,21 +1,34 @@ '. __('LiteSpeed Cache plugin is installed!', 'litespeed-cache'). '' . ' ' - . __('This message indicates that the plugin was installed by the server admin.', 'litespeed-cache') . ' ' - . __('The LiteSpeed Cache plugin is used to cache pages - a simple way to improve the performance of the site.', 'litespeed-cache') . ' ' - . __('However, there is no way of knowing all the possible customizations that were implemented.', 'litespeed-cache') . ' ' - . __('For that reason, please test the site to make sure everything still functions properly.', 'litespeed-cache') - . '

' - . __('Examples of test cases include:', 'litespeed-cache') - . '
    ' - . '
  • ' . __('Visit the site while logged out.', 'litespeed-cache') . '
  • ' - . '
  • ' . __('Create a post, make sure the front page is accurate.', 'litespeed-cache') . '
  • ' - . '
' - . sprintf(__('If there are any questions, the team is always happy to answer any questions on the support forum.', 'litespeed-cache'), - 'href="https://wordpress.org/support/plugin/litespeed-cache" rel="noopener noreferrer" target="_blank"') - . '
' - . __('If you would rather not move at litespeed, you can deactivate this plugin.', 'litespeed-cache'); +$buf = + '

' . + __('LiteSpeed Cache plugin is installed!', 'litespeed-cache') . + '

' . + ' ' . + __('This message indicates that the plugin was installed by the server admin.', 'litespeed-cache') . + ' ' . + __('The LiteSpeed Cache plugin is used to cache pages - a simple way to improve the performance of the site.', 'litespeed-cache') . + ' ' . + __('However, there is no way of knowing all the possible customizations that were implemented.', 'litespeed-cache') . + ' ' . + __('For that reason, please test the site to make sure everything still functions properly.', 'litespeed-cache') . + '

' . + __('Examples of test cases include:', 'litespeed-cache') . + '
    ' . + '
  • ' . + __('Visit the site while logged out.', 'litespeed-cache') . + '
  • ' . + '
  • ' . + __('Create a post, make sure the front page is accurate.', 'litespeed-cache') . + '
  • ' . + '
' . + sprintf( + __('If there are any questions, the team is always happy to answer any questions on the support forum.', 'litespeed-cache'), + 'href="https://wordpress.org/support/plugin/litespeed-cache" rel="noopener noreferrer" target="_blank"' + ) . + '
' . + __('If you would rather not move at litespeed, you can deactivate this plugin.', 'litespeed-cache'); self::add_notice(self::NOTICE_BLUE . ' lscwp-whm-notice', $buf); diff --git a/tpl/inc/show_error_cookie.php b/tpl/inc/show_error_cookie.php index 99ef50afc..6423472b4 100644 --- a/tpl/inc/show_error_cookie.php +++ b/tpl/inc/show_error_cookie.php @@ -1,11 +1,13 @@ Advanced tab.', 'litespeed-cache'), - admin_url('admin.php?page=litespeed-cache#advanced')); +$err = + __('NOTICE: Database login cookie did not match your login cookie.', 'litespeed-cache') . + ' ' . + __('If the login cookie was recently changed in the settings, please log out and back in.', 'litespeed-cache') . + ' ' . + sprintf(__('If not, please verify the setting in the Advanced tab.', 'litespeed-cache'), admin_url('admin.php?page=litespeed-cache#advanced')); if (LITESPEED_SERVER_TYPE === 'LITESPEED_SERVER_OLS') { $err .= ' ' . __('If using OpenLiteSpeed, the server must be restarted once for the changes to take effect.', 'litespeed-cache'); diff --git a/tpl/inc/show_rule_conflict.php b/tpl/inc/show_rule_conflict.php index 8e558641f..0c6c34ae0 100644 --- a/tpl/inc/show_rule_conflict.php +++ b/tpl/inc/show_rule_conflict.php @@ -1,14 +1,16 @@ Learn More)', 'litespeed-cache' ), - '.htaccess', - '`ExpiresDefault`', - 'href="https://docs.litespeedtech.com/lscache/lscwp/troubleshoot/#browser-displays-stale-content" target="_blank"' +$err = sprintf( + __( + 'Unexpected cache rule %2$s found in %1$s file. This rule may cause visitors to see old versions of pages due to the browser caching HTML pages. If you are sure that HTML pages are not being browser cached, this message can be dismissed. (Learn More)', + 'litespeed-cache' + ), + '.htaccess', + '`ExpiresDefault`', + 'href="https://docs.litespeedtech.com/lscache/lscwp/troubleshoot/#browser-displays-stale-content" target="_blank"' ); // other plugin left cache expired rules in .htaccess which will cause conflicts -echo self::build_notice( self::NOTICE_YELLOW . ' lscwp-notice-ruleconflict', $err ) ; - +echo self::build_notice(self::NOTICE_YELLOW . ' lscwp-notice-ruleconflict', $err); diff --git a/tpl/page_optm/entry.tpl.php b/tpl/page_optm/entry.tpl.php index ebfc939f7..f51928a47 100644 --- a/tpl/page_optm/entry.tpl.php +++ b/tpl/page_optm/entry.tpl.php @@ -11,6 +11,7 @@ 'settings_media_exc' => __( 'Media Excludes', 'litespeed-cache' ), 'settings_localization' => __( 'Localization', 'litespeed-cache' ), 'settings_tuning' => __( 'Tuning', 'litespeed-cache' ), + 'settings_tuning_css' => __( 'Tuning', 'litespeed-cache' ) . ' - CSS', ); ?> diff --git a/tpl/page_optm/settings_css.tpl.php b/tpl/page_optm/settings_css.tpl.php index e1788ad43..cb401112e 100644 --- a/tpl/page_optm/settings_css.tpl.php +++ b/tpl/page_optm/settings_css.tpl.php @@ -1,277 +1,295 @@ test_url( '' ); // exit; $css_summary = CSS::get_summary(); $ucss_summary = UCSS::get_summary(); -$closest_server_ucss = Cloud::get_summary( 'server.' . Cloud::SVC_UCSS ); -$closest_server = Cloud::get_summary( 'server.' . Cloud::SVC_CCSS ); +$closest_server_ucss = Cloud::get_summary('server.' . Cloud::SVC_UCSS); +$closest_server = Cloud::get_summary('server.' . Cloud::SVC_CCSS); -$ccss_queue = $this->load_queue( 'ccss' ); -$ucss_queue = $this->load_queue( 'ucss' ); +$ccss_queue = $this->load_queue('ccss'); +$ucss_queue = $this->load_queue('ucss'); ?>

- - + +

- - - - - - +
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
+ - - - - - - - - + + + - - - -
-
API: add_filter( 'litespeed_ucss_per_pagetype', '__return_true' );" ); ?> + + + + - conf( Base::O_OPTM_UCSS ) && ! $this->conf( Base::O_OPTM_CSS_COMB ) ) : ?> -
- ' . Lang::title( Base::O_OPTM_CSS_COMB ) . '', '' . __( 'OFF', 'litespeed-cache' ) . '' ); ?> - - + + + - + + ' data-litespeed-cfm=""> + - - - - + +
+

+ ( ) + Clear +

+

+ $v) : ?> + 20) : ?> + + + + + + + + + 📱'; ?> + +
+ +

+
+ + + + + + - - - - + + - - - + + + - conf( Base::O_OPTM_CSS_ASYNC ) && $this->conf( Base::O_OPTM_CSS_COMB ) && $this->conf( Base::O_OPTM_UCSS ) && $this->conf( Base::O_OPTM_UCSS_INLINE ) ) : ?> -
- ' . Lang::title( Base::O_OPTM_UCSS_INLINE ) . '' ); ?> - - + + + + - + + + - +
+ + +

+ ' . Utility::readable_time($css_summary['last_request_ccss']) . ''; ?> +

+

+ ' . $css_summary['last_spent_ccss'] . 's'; ?> +

+ + -
- - - + + ' data-litespeed-cfm=""> + - - - - + +
+

+ ( ) + Clear +

+

+ $v) : ?> + 20) : ?> + + + + + + + + + 📱'; ?> + +
+ +

+
+ + + + + + + + - - - - + + + + + + + + + + + + + + -
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- conf( Base::O_API_KEY ) ) : ?> -
-

- +
+ + title($id); ?> + + build_switch($id); ?> + +
+
- +
+ + title($id); ?> + + build_switch($id); ?> + +
+ + +
+
+ + title($id); ?> + + build_switch($id); ?> + +
+ conf(Base::O_API_KEY)) : ?> +
+

+ +
+ -
+ + + +
+
+ API: add_filter( 'litespeed_ucss_per_pagetype', '__return_true' );"); ?> -
- - -

- ' . Utility::readable_time( $ucss_summary[ 'last_request' ] ) . ''; ?> -

-

- ' . $ucss_summary[ 'last_spent' ] . 's'; ?> -

+ conf(Base::O_OPTM_UCSS) && !$this->conf(Base::O_OPTM_CSS_COMB)) : ?> +
+ + ' . Lang::title(Base::O_OPTM_CSS_COMB) . '', '' . __('OFF', 'litespeed-cache') . ''); ?> + - - - ' data-litespeed-cfm=""> - +
- -
-

- ( ) - Clear -

-

- $v ) : ?> - 20 ) : ?> - - - - - - - - - 📱'; ?> - -
- -

-
- - - - - +
+ + +

+ ' . Utility::readable_time($ucss_summary['last_request']) . ''; ?> +

+

+ ' . $ucss_summary['last_spent'] . 's'; ?> +

+ + -
- - title( $id ); ?> - - build_switch( $id ); ?> -
- ' . Lang::title( Base::O_GUEST ) . '' ); ?> -
- ' . Lang::title( Base::O_OPTM_CSS_ASYNC ) . '' ); ?> - -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- ' . Lang::title( Base::O_OPTM_CSS_COMB ) . '' ); ?> -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- conf( Base::O_API_KEY ) ) : ?> -
-

- +
+ + title($id); ?> + + build_switch($id); ?> + +
+ ' . Lang::title(Base::O_GUEST) . ''); ?> +
+ + ' . Lang::title(Base::O_OPTM_CSS_ASYNC) . ''); ?> +
- - -
- -
-
- ' . __( 'ON', 'litespeed-cache' ) . '' ); ?> -
- : - data-no-async="1"' ); ?> - +
+ + title($id); ?> + + build_switch($id); ?> +
+ ' . Lang::title(Base::O_OPTM_CSS_COMB) . ''); ?> +
+
+ + title($id); ?> + + build_switch($id); ?> + +
+ conf(Base::O_API_KEY)) : ?> +
+

+ +
+ + +
+ +
+
+ ' . __('ON', 'litespeed-cache') . ''); ?> +
+ + : + data-no-async="1"'); ?> + -
- - -

- ' . Utility::readable_time( $css_summary[ 'last_request_ccss' ] ) . ''; ?> -

-

- ' . $css_summary[ 'last_spent_ccss' ] . 's'; ?> -

+ conf(Base::O_OPTM_CSS_ASYNC) && $this->conf(Base::O_OPTM_CSS_COMB) && $this->conf(Base::O_OPTM_UCSS) && $this->conf(Base::O_OPTM_UCSS_INLINE)) : ?> +
+ + ' . Lang::title(Base::O_OPTM_UCSS_INLINE) . ''); ?> + - - - ' data-litespeed-cfm=""> - +
- -
-

- ( ) - Clear -

-

- $v ) : ?> - 20 ) : ?> - - - - - - - - - 📱'; ?> - -
- -

-
- - - - -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
- - title( $id ); ?> - - build_switch( $id, array( __( 'Default', 'litespeed-cache' ), 'Swap' ) ); ?> -
- font-display', '@font-face' ); ?> -
' . __( 'Swap', 'litespeed-cache' ) . '' ); ?> -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
+ + title($id); ?> + + build_switch($id, array(__('Default', 'litespeed-cache'), 'Swap')); ?> +
+ font-display', '@font-face'); ?> +
' . __('Swap', 'litespeed-cache') . ''); ?> +
+
+ + \ No newline at end of file diff --git a/tpl/page_optm/settings_html.tpl.php b/tpl/page_optm/settings_html.tpl.php index f1b2c0769..75374dbed 100644 --- a/tpl/page_optm/settings_html.tpl.php +++ b/tpl/page_optm/settings_html.tpl.php @@ -1,148 +1,170 @@

- - + +

- - - - - +
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
+ + + + + + + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + -
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
+ + title($id); ?> + + build_textarea($id); ?> +
+ + : //www.example.com + + +
+
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - : //www.example.com - - -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ + + +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - - -
-
+ + title($id); ?> + + build_textarea($id); ?> +
+ + : https://example.com + + +
+
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - - -
-
+ + title($id); ?> + + build_textarea($id); ?> +
+ + + +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
- ⚠️ - - -
- : - &_litespeed_rm_qs=0' ); ?> - -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+ + ⚠️ + + +
+ + : + &_litespeed_rm_qs=0'); ?> + +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - - -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ + + +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ + +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- <noscript>' ); ?> - -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ <noscript>'); ?> + +
+
\ No newline at end of file + + \ No newline at end of file diff --git a/tpl/page_optm/settings_js.tpl.php b/tpl/page_optm/settings_js.tpl.php index afd838933..2c3c603ff 100644 --- a/tpl/page_optm/settings_js.tpl.php +++ b/tpl/page_optm/settings_js.tpl.php @@ -1,76 +1,84 @@

- - + +

- +
+ - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + -
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
+ + title($id); ?> + + build_switch($id); ?> + +
+ +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - -
- 🚨 - - -
-
+ + title($id); ?> + + build_switch($id); ?> + +
+ + +
+ + 🚨 + + +
+
- - title( $id ); ?> - - build_switch( $id ); ?> -
- ' . Lang::title( Base::O_OPTM_JS_COMB ) . '' ); ?> -
-
+ + title($id); ?> + + build_switch($id); ?> +
+ ' . Lang::title(Base::O_OPTM_JS_COMB) . ''); ?> +
+
- - title( $id ); ?> - - build_switch( $id, array( __( 'OFF', 'litespeed-cache' ), __( 'Deferred', 'litespeed-cache' ), __( 'Delayed', 'litespeed-cache' ) ) ); ?> -
- -
- - -
- 🚨 - -
-
+ + title($id); ?> + + build_switch($id, array(__('OFF', 'litespeed-cache'), __('Deferred', 'litespeed-cache'), __('Delayed', 'litespeed-cache'))); ?> +
+ +
+ + +
+ + 🚨 + +
+
+ + \ No newline at end of file diff --git a/tpl/page_optm/settings_media.tpl.php b/tpl/page_optm/settings_media.tpl.php index f5f00022c..0aa44be1b 100644 --- a/tpl/page_optm/settings_media.tpl.php +++ b/tpl/page_optm/settings_media.tpl.php @@ -1,242 +1,267 @@ load_queue( 'lqip' ); +$lqip_queue = $this->load_queue('lqip'); ?>

- - + +

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + +
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - -
- 💡 - - -
-
- - title( $id ); ?> - - build_input( $id, 'litespeed-input-long' ); ?> -
- -
LITESPEED_PLACEHOLDER', 'wp-config.php' ); ?> -
data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs=' ); ?> -
data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' ); ?> -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - -
-
- - title( $id ); ?> - - build_input( $id, 'litespeed-input-long' ); ?> -
- - -
{width} {height}' ); ?> -
{color}' ); ?> -
recommended( $id ); ?> -
-
- - title( $id ); ?> - - build_input( $id, null, null, 'color' ); ?> -
- - recommended( $id ); ?> -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
- -
-
- - title( $id ); ?> - - build_input( $id, 'litespeed-input-short' ); ?> -
- -
- recommended( $id ); ?> - _validate_ttl( $id, 1, 20 ); ?> -
💡 ' . __( 'Purge All', 'litespeed-cache' ) . ' - ' . __( 'LQIP Cache', 'litespeed-cache' ) . ''); ?> -
-
- - title( $id ); ?> - - build_input( $id, 'litespeed-input-short' ); ?> x - build_input( Base::O_MEDIA_LQIP_MIN_H, 'litespeed-input-short' ); ?> - -
- - recommended( $id ); ?> - _validate_ttl( $id, 10, 800 ); ?> - _validate_ttl( Base::O_MEDIA_LQIP_MIN_H, 10, 800 ); ?> -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - ' . __('ON', 'litespeed-cache') . '', - '' . Lang::title( Base::O_MEDIA_PLACEHOLDER_RESP_SVG ) . '' - ); ?> - ' . __('OFF', 'litespeed-cache') . '' ); ?> - -
- -
- - -

- ' . Utility::readable_time( $placeholder_summary[ 'last_request' ] ) . ''; ?> -

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - -
+ + title($id); ?> + + build_switch($id); ?> +
+ + +
+
+ + title($id); ?> + + build_switch($id); ?> +
+ + +
+ + 💡 + + +
+
+ + title($id); ?> + + build_input($id, 'litespeed-input-long'); ?> +
+ +
LITESPEED_PLACEHOLDER', 'wp-config.php'); ?> +
data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs='); ?> +
data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'); ?> +
+
+ + title($id); ?> + + build_switch($id); ?> + +
+ + +
+
+ + title($id); ?> + + build_input($id, 'litespeed-input-long'); ?> +
+ + +
{width} {height}'); ?> +
{color}'); ?> +
recommended($id); ?> +
+
+ + title($id); ?> + + build_input($id, null, null, 'color'); ?> +
+ + recommended($id); ?> +
+
+ + title($id); ?> + + build_switch($id); ?> + +
+ +
+ +
+
+ + title($id); ?> + + build_input($id, 'litespeed-input-short'); ?> +
+ +
+ recommended($id); ?> + _validate_ttl($id, 1, 20); ?> +
💡 ' . __('Purge All', 'litespeed-cache') . ' - ' . __('LQIP Cache', 'litespeed-cache') . ''); ?> +
+
+ + title($id); ?> + + build_input($id, 'litespeed-input-short'); ?> x + build_input(Base::O_MEDIA_LQIP_MIN_H, 'litespeed-input-short'); ?> + +
+ + recommended($id); ?> + _validate_ttl($id, 10, 800); ?> + _validate_ttl(Base::O_MEDIA_LQIP_MIN_H, 10, 800); ?> +
+
+ + title($id); ?> + + build_switch($id); ?> +
+ + ' . __('ON', 'litespeed-cache') . '', + '' . Lang::title(Base::O_MEDIA_PLACEHOLDER_RESP_SVG) . '' + ); ?> + ' . __('OFF', 'litespeed-cache') . ''); ?> + +
+ +
+ + +

+ ' . Utility::readable_time($placeholder_summary['last_request']) . ''; ?> +

+ + + + + ' data-litespeed-cfm=""> + + + +
+

+ ( ) + Clear +

+

+ $v) : ?> + 20) : ?> + + + + + +
+ +

+
+ + + + - - - - ' data-litespeed-cfm=""> - - - -
-

- ( ) - Clear -

-

- $v ) : ?> - 20 ) : ?> - - - - - -
- -

-
- - - - -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- - - -
- ⚠️ : ' . Lang::title( Base::O_MEDIA_LAZY ) . '' ); ?> - - -
- : - add_filter( "litespeed_media_ignore_remote_missing_sizes", "__return_true" );', '' . Lang::title( Base::O_MEDIA_ADD_MISSING_SIZES ) . '' ); ?> - -
-
+
+
+ + title($id); ?> + + build_switch($id); ?> +
+ + +
+
+ + title($id); ?> + + build_switch($id); ?> +
+ + + +
+ + ⚠️ : ' . Lang::title(Base::O_MEDIA_LAZY) . ''); ?> + + +
+ + : + add_filter( "litespeed_media_ignore_remote_missing_sizes", "__return_true" );', '' . Lang::title(Base::O_MEDIA_ADD_MISSING_SIZES) . ''); ?> + +
+
\ No newline at end of file diff --git a/tpl/page_optm/settings_tuning.tpl.php b/tpl/page_optm/settings_tuning.tpl.php index 8573c508c..ba200b108 100644 --- a/tpl/page_optm/settings_tuning.tpl.php +++ b/tpl/page_optm/settings_tuning.tpl.php @@ -1,239 +1,159 @@ roles as $k => $v ) { - $roles[ $k ] = $v[ 'name' ]; +foreach ($wp_roles->roles as $k => $v) { + $roles[$k] = $v['name']; } -ksort( $roles ); +ksort($roles); ?>

- - + +

- - - - - - - - - - - - - - +
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - - -
- : - litespeed_optimize_css_excludes' ); ?> - data-no-optimize="1"' ); ?> -
: https://github.com/litespeedtech/lscache_wp/blob/dev/data/css_excludes.txt -
-
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - - -
- : - litespeed_optimize_js_excludes' ); ?> - data-no-optimize="1"' ); ?> -
: https://github.com/litespeedtech/lscache_wp/blob/dev/data/js_excludes.txt -
-
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - -
*' ); ?> -
-

-

- -

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + -
+ + title($id); ?> + + build_textarea($id); ?> +
+ + + +
+ + : + litespeed_optm_js_delay_inc'); ?> + +
+
+ + title($id); ?> + + build_textarea($id); ?> +
+ + + +
+ + : + litespeed_optimize_js_excludes'); ?> + data-no-optimize="1"'); ?> +
: https://github.com/litespeedtech/lscache_wp/blob/dev/data/js_excludes.txt +
+
+
+ + title($id); ?> + + build_textarea($id); ?> +
+ + + +
+ : + litespeed_optm_js_defer_exc'); ?> + data-no-defer="1"'); ?> +
: https://github.com/litespeedtech/lscache_wp/blob/dev/data/js_defer_excludes.txt +
+
+
+ + title($id); ?> + + build_textarea($id); ?> +
+ ' . Lang::title(Base::O_GUEST) . ''); ?> + + +
+ : + litespeed_optm_gm_js_exc'); ?> + data-no-defer="1"'); ?> + +
+
+ + title($id); ?> + + build_textarea($id); ?> +
+ + _uri_usage_example(); ?> +
+ : + litespeed_optm_uri_exc'); ?> + +
+
+ + title($id); ?> + + build_switch($id); ?> +
+ +
+
+ + title($id); ?> + +
+ +
+
+ $title) : ?> + build_checkbox($id . '[]', $title, $this->cls('Conf')->in_optm_exc_roles($role), $role); ?> +
- - : https://github.com/litespeedtech/lscache_wp/blob/dev/data/ucss_whitelist.txt - - -
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - - -
- : - litespeed_ucss_exc' ); ?> - -
API: add_filter( 'litespeed_ucss_per_pagetype', function(){return get_post_type() == 'page';} );", 'page' ); ?> -
API: add_action( 'litespeed_optm', function(){get_post_type() == 'page' && do_action( 'litespeed_conf_force', 'optm-ucss', false );});", 'page' ); ?> - -
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - page' ); ?> - -
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - _uri_usage_example(); ?> -
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- -
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - - -
- : - litespeed_optm_js_defer_exc' ); ?> - data-no-defer="1"' ); ?> -
: https://github.com/litespeedtech/lscache_wp/blob/dev/data/js_defer_excludes.txt -
-
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- ' . Lang::title( Base::O_GUEST ) . '' ); ?> - - -
- : - litespeed_optm_gm_js_exc' ); ?> - data-no-defer="1"' ); ?> - -
-
- - title( $id ); ?> - - build_textarea( $id ); ?> -
- - _uri_usage_example(); ?> -
-
- - title( $id ); ?> - - build_switch( $id ); ?> -
- -
-
- - title( $id ); ?> - -
- -
-
- $title ): ?> - build_checkbox( $id . '[]', $title, $this->cls( 'Conf' )->in_optm_exc_roles( $role ), $role ); ?> - -
-
+
\ No newline at end of file diff --git a/tpl/page_optm/settings_tuning_css.tpl.php b/tpl/page_optm/settings_tuning_css.tpl.php new file mode 100644 index 000000000..a3e3a2909 --- /dev/null +++ b/tpl/page_optm/settings_tuning_css.tpl.php @@ -0,0 +1,136 @@ + +

+ - CSS + +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + title( $id ); ?> + + build_textarea( $id ); ?> +
+ + + +
+ : + litespeed_optimize_css_excludes' ); ?> + data-no-optimize="1"' ); ?> +
: https://github.com/litespeedtech/lscache_wp/blob/dev/data/css_excludes.txt +
+
+
+ + title( $id ); ?> + + build_textarea( $id ); ?> +
+ + + +
+
+ + title( $id ); ?> + + build_textarea( $id ); ?> + +
+ + title( $id ); ?> + + build_textarea( $id ); ?> +
+ + + +
+ : + litespeed_ucss_exc' ); ?> + +
API: add_filter( 'litespeed_ucss_per_pagetype', function(){return get_post_type() == 'page';} );", 'page' ); ?> +
API: add_action( 'litespeed_optm', function(){get_post_type() == 'page' && do_action( 'litespeed_conf_force', 'optm-ucss', false );});", 'page' ); ?> + +
+
+ + title( $id ); ?> + + build_textarea( $id ); ?> +
+ + page' ); ?> + +
+
+ + title( $id ); ?> + + build_textarea( $id ); ?> +
+ + _uri_usage_example(); ?> +
+
+ + title( $id ); ?> + + build_textarea( $id ); ?> +
+ +
+
diff --git a/tpl/page_optm/settings_vpi.tpl.php b/tpl/page_optm/settings_vpi.tpl.php index 9504acd10..2c9f75848 100644 --- a/tpl/page_optm/settings_vpi.tpl.php +++ b/tpl/page_optm/settings_vpi.tpl.php @@ -45,7 +45,7 @@ - ' data-litespeed-cfm=""> + ' data-litespeed-cfm=""> @@ -73,6 +73,7 @@ +
diff --git a/tpl/presets/entry.tpl.php b/tpl/presets/entry.tpl.php new file mode 100644 index 000000000..fc061b429 --- /dev/null +++ b/tpl/presets/entry.tpl.php @@ -0,0 +1,51 @@ + __( 'Standard Presets', 'litespeed-cache' ), + 'import_export' => __( 'Import / Export', 'litespeed-cache' ), +); + +?> + +
+

+ +

+ + v + +
+
+ +
+ + +
+ $val) { + echo "
"; + if ('import_export' === $tab) { + require LSCWP_DIR . "tpl/toolbox/$tab.tpl.php"; + } else { + require LSCWP_DIR . "tpl/presets/$tab.tpl.php"; + } + echo "
"; + } + + ?> +
+ +
diff --git a/tpl/presets/standard.tpl.php b/tpl/presets/standard.tpl.php new file mode 100644 index 000000000..9885c522f --- /dev/null +++ b/tpl/presets/standard.tpl.php @@ -0,0 +1,194 @@ + __( 'Essentials', 'litespeed-cache' ), + 'body' => array( + __( 'Default Cache', 'litespeed-cache' ), + __( 'Higher TTL', 'litespeed-cache' ), + __( 'Browser Cache', 'litespeed-cache' ) + ), + 'footer' => array( + __( 'This no-risk preset is appropriate for all websites. Good for new users, simple websites, or cache-oriented development.', 'litespeed-cache' ), + __( 'A Domain Key is not required to use this preset. Only basic caching features are enabled.', 'litespeed-cache' ) + ) +); + +$presets['basic'] = array( + 'title' => __( 'Basic', 'litespeed-cache' ), + 'body' => array( + __( 'Everything in Essentials, Plus', 'litespeed-cache' ), + __( 'Image Optimization', 'litespeed-cache' ), + __( 'Mobile Cache', 'litespeed-cache' ) + ), + 'footer' => array( + __( 'This low-risk preset introduces basic optimizations for speed and user experience. Appropriate for enthusiastic beginners.', 'litespeed-cache' ), + __( 'A Domain Key is required to use this preset. Includes optimizations known to improve site score in page speed measurement tools.', 'litespeed-cache' ) + ) +); + +$presets['advanced'] = array( + 'title' => __( 'Advanced (Recommended)', 'litespeed-cache' ), + 'body' => array( + __( 'Everything in Basic, Plus', 'litespeed-cache' ), + __( 'Guest Mode and Guest Optimization', 'litespeed-cache' ), + __( 'CSS, JS and HTML Minification', 'litespeed-cache' ), + __( 'Font Display Optimization', 'litespeed-cache' ), + __( 'JS Defer for both external and inline JS', 'litespeed-cache' ), + __( 'DNS Prefetch for static files', 'litespeed-cache' ), + __( 'Gravatar Cache', 'litespeed-cache' ), + __( 'Remove Query Strings from Static Files', 'litespeed-cache' ), + __( 'Remove WordPress Emoji', 'litespeed-cache' ), + __( 'Remove Noscript Tags', 'litespeed-cache' ) + ), + 'footer' => array( + __( 'This preset is good for most websites, and is unlikely to cause conflicts. Any CSS or JS conflicts may be resolved with Page Optimization > Tuning tools.', 'litespeed-cache' ), + __( 'A Domain Key is required to use this preset. Includes many optimizations known to improve page speed scores.', 'litespeed-cache' ) + ) +); + +$presets['aggressive'] = array( + 'title' => __( 'Aggressive', 'litespeed-cache' ), + 'body' => array( + __( 'Everything in Advanced, Plus', 'litespeed-cache' ), + __( 'CSS & JS Combine', 'litespeed-cache' ), + __( 'Asynchronous CSS Loading with Critical CSS', 'litespeed-cache' ), + __( 'Removed Unused CSS for Users', 'litespeed-cache' ), + __( 'Lazy Load for Iframes', 'litespeed-cache' ) + ), + 'footer' => array( + __( 'This preset might work out of the box for some websites, but be sure to test! Some CSS or JS exclusions may be necessary in Page Optimization > Tuning.', 'litespeed-cache' ), + __( 'A Domain Key is required to use this preset. Includes many optimizations known to improve page speed scores.', 'litespeed-cache' ) + ) +); + +$presets['extreme'] = array( + 'title' => __( 'Extreme', 'litespeed-cache' ), + 'body' => array( + __( 'Everything in Aggressive, Plus', 'litespeed-cache' ), + __( 'Lazy Load for Images', 'litespeed-cache' ), + __( 'Viewport Image Generation', 'litespeed-cache' ), + __( 'JS Delayed', 'litespeed-cache' ), + __( 'Inline JS added to Combine', 'litespeed-cache' ), + __( 'Inline CSS added to Combine', 'litespeed-cache' ) + ), + 'footer' => array( + __( 'This preset almost certainly will require testing and exclusions for some CSS, JS and Lazy Loaded images. Pay special attention to logos, or HTML-based slider images.', 'litespeed-cache' ), + __( 'A Domain Key is required to use this preset. Enables the maximum level of optimizations for improved page speed scores.', 'litespeed-cache' ) + ) +); + +?> + +

+ + +

+ +

+ +
+ +
+
+
+

+ +

+
+
+
    + +
  • + +
+
+ +
+
+ + + +
+
+ +
+ + $timestamp, + 'time' => $time, + 'title' => $title + ); +} + +if ( ! empty( $summary['preset'] ) || ! empty( $backups ) ) : +?> +

+ +

+ + + +

+ ' . esc_html( $presets[ $name ]['title'] ) . '', + $time + ); + } + ?> +

+ + + +

+ + + + +

+ -form_action( Router::ACTION_DEBUG2, Debug2::TYPE_BETA_TEST ); ?> +form_action(Router::ACTION_DEBUG2, Debug2::TYPE_BETA_TEST); ?> -

- - -

+

+ + +

-
-
: https://github.com/litespeedtech/lscache_wp/commit/e9cb446dfb66d133264d3ebec0535aaed5c932c0
+
+
: https://github.com/litespeedtech/lscache_wp/commit/example_comment_hash_d3ebec0535aaed5c932c0
- + -

dev

+

dev

-

master

+

master

-

latest

+

latest

-

- +

+ - 3.6.4 - - 🚨 - -

+ 3.6.4 + + 🚨 + +

-
' . __( 'Use latest GitHub Dev/Master commit', 'litespeed-cache' ) . '' ); ?>
-
' . __( 'Use latest WordPress release version', 'litespeed-cache' ) . '' ); ?>
+
' . __('Use latest GitHub Dev/Master commit', 'litespeed-cache') . ''); ?>
+
' . __('Use latest WordPress release version', 'litespeed-cache') . ''); ?>
-

- 🚨 v3.6.4', 'dev/master/v4+' ); ?> -

+

+ 🚨 v3.6.4', 'dev/master/v4+'); ?> +

- - + + \ No newline at end of file