HEX
Server: LiteSpeed
System: Linux atali.colombiahosting.com.co 5.14.0-570.12.1.el9_6.x86_64 #1 SMP PREEMPT_DYNAMIC Tue May 13 06:11:55 EDT 2025 x86_64
User: coopserp (1713)
PHP: 8.2.29
Disabled: dl,exec,passthru,proc_open,proc_close,shell_exec,memory_limit,system,popen,curl_multi_exec,show_source,symlink,link,leak,listen,diskfreespace,tmpfile,ignore_user_abord,highlight_file,source,show_source,fpaththru,virtual,posix_ctermid,posix_getcwd,posix_getegid,posix_geteuid,posix_getgid,posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid,posix,posix_getppid,posix_getpwnam,posix_getpwuid,posix_getrlimit,posix_getsid,posix_getuid,posix_isatty,posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid,posix_setpgid,posix_setsid,posix_setid,posix_times,posix_ttyname,posix_uname,proc_get_status,proc_nice,proc_terminate
Upload Files
File: /home/coopserp/public_html/speedycache-pro.tar
assets/css/admin.css000064400000003112151526423640010445 0ustar00/*Donut Chart*/

.speedycache-test-notice {
border-left: none;
background-color:white;
color: #0F172A;
border-radius: 8px;
padding: 0px 15px;
box-shadow: 0 0 #0000, 0 0 #0000, 0 1px 3px 0 #0000001a, 0 1px 2px -1px #0000001a;
}

.speedycache-test-notice p{
margin:0px;
padding:0px;    
}

.speedycache-test-chart-wrap {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
}

.speedycache-notice-title {
text-align: center;
font-weight: 600;
font-size: 20px;
}

.speedycache-test-donut-text {
font-family: Arial, Helvetica, sans-serif;
fill: #FF6200;
}

.speedycache-donut-wrap {
width: 100%;
max-width: 170px;
font-size: 16px;
animation: donutfade 1s;
text-align: center;
}

.speedycache-donut-segment {
transform-origin: center;
}

.speedycache-donut-percent {
font-size: 0.85em;
line-height: 0.8;
transform: translateY(0.5em);
font-weight: bold;
}

.speedycache-donut-label {
font-size: 1em;
font-weight: 700;
line-height: 1;
transform: translateY(0.25em);
}

.speedycache-test-action{
margin:10px auto;
text-align:center;
font-weight:400;
line-height:2;
font-size:14px;
}

.speedycache-enable-btn{
background-color: #3d5afe;
border: none;
color: #FFF;
outline: none;
border-radius: 4px;
box-shadow: 1px 0 5px 0 #ccc;
padding: 8px 14px;
font-weight: bold;
font-size: 0.9rem;
cursor: pointer;
transition: background-color 0.4s, transform 0.3s;
}

.speedycache-enable-btn:hover{
background-color:#0529f7;
transform: translateY(-1px);
transition: background-color 0.6s, transform 0.4s;
color:#FFF;
}assets/js/instantpage.js000064400000005641151526423640011353 0ustar00!(function(){let t,e,n,o,i,a=null,s=65,c=new Set;const r=1111;function d(t){o=performance.now();const e=t.target.closest("a");m(e)&&p(e.href,"high")}function u(t){if(performance.now()-o<r)return;if(!("closest"in t.target))return;const e=t.target.closest("a");m(e)&&(e.addEventListener("mouseout",f,{passive:!0}),i=setTimeout(()=>{p(e.href,"high"),i=void 0},s))}function l(t){const e=t.target.closest("a");m(e)&&p(e.href,"high")}function f(t){t.relatedTarget&&t.target.closest("a")==t.relatedTarget.closest("a")||i&&(clearTimeout(i),i=void 0)}function h(t){if(performance.now()-o<r)return;const e=t.target.closest("a");if(t.which>1||t.metaKey||t.ctrlKey)return;if(!e)return;e.addEventListener("click",function(t){1337!=t.detail&&t.preventDefault()},{capture:!0,passive:!1,once:!0});const n=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1,detail:1337});e.dispatchEvent(n)}function m(o){if(o&&o.href&&(!n||"instant"in o.dataset)){if(o.origin!=location.origin){if(!(e||"instant"in o.dataset)||!a)return}if(["http:","https:"].includes(o.protocol)&&("http:"!=o.protocol||"https:"!=location.protocol)&&(t||!o.search||"instant"in o.dataset)&&!(o.hash&&o.pathname+o.search==location.pathname+location.search||"noInstant"in o.dataset))return!0}}function p(t,e="auto"){if(c.has(t))return;const n=document.createElement("link");n.rel="prefetch",n.href=t,n.fetchPriority=e,n.as="document",document.head.appendChild(n),c.add(t)}!function(){if(!document.createElement("link").relList.supports("prefetch"))return;const o="instantVaryAccept"in document.body.dataset||"Shopify"in window,i=navigator.userAgent.indexOf("Chrome/");i>-1&&(a=parseInt(navigator.userAgent.substring(i+"Chrome/".length)));if(o&&a&&a<110)return;const c="instantMousedownShortcut"in document.body.dataset;t="instantAllowQueryString"in document.body.dataset,e="instantAllowExternalLinks"in document.body.dataset,n="instantWhitelist"in document.body.dataset;const r={capture:!0,passive:!0};let f=!1,v=!1,g=!1;if("instantIntensity"in document.body.dataset){const t=document.body.dataset.instantIntensity;if(t.startsWith("mousedown"))f=!0,"mousedown-only"==t&&(v=!0);else if(t.startsWith("viewport")){const e=navigator.connection&&navigator.connection.saveData,n=navigator.connection&&navigator.connection.effectiveType&&navigator.connection.effectiveType.includes("2g");e||n||("viewport"==t?document.documentElement.clientWidth*document.documentElement.clientHeight<45e4&&(g=!0):"viewport-all"==t&&(g=!0))}else{const e=parseInt(t);isNaN(e)||(s=e)}}v||document.addEventListener("touchstart",d,r);f?c||document.addEventListener("mousedown",l,r):document.addEventListener("mouseover",u,r);c&&document.addEventListener("mousedown",h,r);if(g){let t=window.requestIdleCallback;t||(t=(t=>{t()})),t(function(){const t=new IntersectionObserver(e=>{e.forEach(e=>{if(e.isIntersecting){const n=e.target;t.unobserve(n),p(n.href)}})});document.querySelectorAll("a").forEach(e=>{m(e)&&t.observe(e)})},{timeout:1500})}}();})();assets/js/delayjs.min.js000064400000001265151526423640011251 0ustar00!function(){let t=["mouseover","click","keydown","wheel","touchmove","touchstart"],e=setTimeout(r,1e4);function r(){t.forEach(t=>{window.removeEventListener(t,r,{passive:!0})}),document.querySelectorAll('script[type="speedycache/javascript"]').forEach(async t=>{await new Promise(e=>{var r,a;let c;return r=t,a=e,c=document.createElement("script"),void(r.getAttributeNames().forEach(t=>{"type"!==t&&c.setAttribute("data-src"==t?"src":t,r.getAttribute(t))}),c.setAttribute("type","text/javascript"),r.hasAttribute("data-src")||(c.text=r.text),c.addEventListener("load",a),r.after(c),r.remove())})}),null!=e&&(clearTimeout(e),e=null)}t.forEach(t=>{window.addEventListener(t,r,{passive:!0})})}();assets/js/index.html000064400000000133151526423640010464 0ustar00<h1>Powered By SpeedyCache</h1>
Go to <a href="https://speedycache.com">SpeedyCache.Com</a>assets/js/metabox.js000064400000001403151526423640010465 0ustar00jQuery(document).ready(function() {
	
	jQuery('#speedycache-generate-specific-cache').on('click', function(){
		let ccss_disabled = jQuery('#speedycache-disable-critical-css:checked');
		
		if(ccss_disabled.length){
			alert('Critical CSS is disabled for this post');
			return;
		}

		jQuery.ajax({
			'method': 'POST',
			'url': speedycache_metabox.url,
			'data': {
				'post_id': speedycache_metabox.post_id,
				'security': speedycache_metabox.nonce,
				'action': 'speedycache_generate_single_ccss',
			},
			success: function(res){
				if(!res.success){
					alert(res.data.message ? res.data.message : 'Something went wrong ! Unable to intitiate Critical CSS!');
					return;
				}
				
				alert(res.data.message);
			}
		});
	});
});assets/js/lazy-load.js000064400000011764151526423640010735 0ustar00var speedycache_lazy_load = {
	sources: [],
	osl: 0,
	scroll: false,
	init: function(){
		speedycache_lazy_load.set_source();

		window.addEventListener('load', function(){
			let observer = new MutationObserver((mutations) => {
				speedycache_lazy_load.osl = speedycache_lazy_load.sources.length;
				speedycache_lazy_load.set_source();
		
				if(speedycache_lazy_load.sources.length > speedycache_lazy_load.osl){
					speedycache_lazy_load.load_sources(false);
				}
			});

			observer.observe(document.getElementsByTagName('html')[0], {childList: true, attributes: true, subtree: true, attributeFilter: ["src"], attributeOldValue: false, characterDataOldValue: false});
			
			speedycache_lazy_load.load_sources(true);
		});
		
		let js_events = ['scroll', 'resize', 'click'];
		
		js_events.forEach((event) => {
			window.addEventListener(event, function(){
				speedycache_lazy_load.scroll=true;
				speedycache_lazy_load.load_sources(false);
			});
		});
	},
	c: function(e, pageload){
		var winH = document.documentElement.clientHeight || body.clientHeight;
		var number = 0;

		if(pageload){
			number = 0;
		}else{
			number = (winH > 800) ? 800 : 200;
			number = speedycache_lazy_load.scroll ? 800 : number;
		}

		var elemRect = e.getBoundingClientRect();
		var top = 0;
		var parentOfE = e.parentNode ? e.parentNode : false;

		if(typeof parentOfE.getBoundingClientRect == 'undefined'){
			var parentRect = false;
		}else{
			var parentRect = parentOfE.getBoundingClientRect();
		}

		if(elemRect.x == 0 && elemRect.y == 0){
			for(var i = 0; i < 10; i++){
				if(parentOfE){
					if(parentRect.x == 0 && parentRect.y == 0){
						if(parentOfE.parentNode){
							parentOfE = parentOfE.parentNode;
						}

						if(typeof parentOfE.getBoundingClientRect == 'undefined'){
							parentRect = false;
						}else{
							parentRect = parentOfE.getBoundingClientRect();
						}
					}else{
						top = parentRect.top;
						break;
					}
				}
			};
		}else{
			top = elemRect.top;
		}

		if(winH - top + number > 0){
			return true;
		}

		return false;
	},
	r: function(e, pageload){
		var self = this;
		var originalsrc,originalsrcset;

		try{
			
			originalsrc = e.getAttribute('data-speedycache-original-src');
			originalsrcset = e.getAttribute('data-speedycache-original-srcset');
			originalsizes = e.getAttribute('data-speedycache-original-sizes');
			
			if(self.c(e, pageload)){
				if(originalsrc || originalsrcset){
					if(e.tagName == 'DIV' || e.tagName == 'A' || e.tagName == 'SPAN'){
						e.style.backgroundImage = 'url(' + originalsrc + ')';
						e.removeAttribute('data-speedycache-original-src');
						e.removeAttribute('data-speedycache-original-srcset');
						e.removeAttribute('onload');
						
					}else{
						if(originalsrc){
							e.setAttribute('src', originalsrc);
						}

						if(originalsrcset){
							e.setAttribute('srcset', originalsrcset);
						}

						if(originalsizes){
							e.setAttribute('sizes', originalsizes);
						}

						if(e.getAttribute('alt') && e.getAttribute('alt') == 'blank'){
							e.removeAttribute('alt');
						}

						e.removeAttribute('data-speedycache-original-src');
						e.removeAttribute('data-speedycache-original-srcset');
						e.removeAttribute('data-speedycache-original-sizes');
						e.removeAttribute('onload');

						if(e.tagName == 'IFRAME'){
							var y = "https://www.youtube.com/embed/";

							if(navigator.userAgent.match(/\sEdge?\/\d/i)){
								e.setAttribute('src',e.getAttribute('src').replace(/.+\/main\/youtube\.html\#/, y));
							}
							
							e.onload = function(){
								if(typeof window.jQuery != 'undefined'){if(jQuery.fn.fitVids){jQuery(e).parent().fitVids({ customSelector: 'iframe[src]'});}}

								var s = e.getAttribute('src').match(/main\/youtube\.html\#(.+)/);
								if(s){
									try{
										var i = e.contentDocument || e.contentWindow;
										if(i.location.href == 'about:blank'){
											e.setAttribute('src',y+s[1]);
										}
									}catch(err){
										e.setAttribute('src',y+s[1]);
									}
								}
							}
						}
					}
				}else{
					if(e.tagName == 'NOSCRIPT'){
						if(e.getAttribute('data-type') == 'speedycache'){
							e.removeAttribute('data-type');
							e.insertAdjacentHTML('afterend', e.innerHTML);
						}
					}
				}
			}

		}catch(error){
			console.log(error);
			console.log('==>', e);
		}
	},
	set_source: function(){
		var i = [].slice.call(document.getElementsByTagName('img'));
		var f = [].slice.call(document.getElementsByTagName('iframe'));
		var d = [].slice.call(document.getElementsByTagName('div'));
		var a = [].slice.call(document.getElementsByTagName('a'));
		var s = [].slice.call(document.getElementsByTagName('span'));
		var n = [].slice.call(document.getElementsByTagName('noscript'));

		this.sources = i.concat(f).concat(d).concat(a).concat(s).concat(n);
	},
	load_sources: function(pageload){
		var self = this;

		[].forEach.call(self.sources, function(e, index) {
			self.r(e, pageload);
		});
	}
};

document.addEventListener('DOMContentLoaded',function(){
	speedycache_lazy_load.init();
});assets/js/delayjs.js000064400000002412151526423640010462 0ustar00(function(){
let speedycache_js_events = ['mouseover','click','keydown','wheel','touchmove','touchstart'],
speedycache_djs_timeout = setTimeout(speedycache_delay_event, 10000);

speedycache_js_events.forEach((event) => {
	window.addEventListener(event, speedycache_delay_event, {passive: true});
});

function speedycache_delay_event(){
	
	speedycache_js_events.forEach((event) => {
		window.removeEventListener(event, speedycache_delay_event, {passive: true});
	});
	
	document.querySelectorAll('script[type="speedycache/javascript"]').forEach(async e => {
		await new Promise(resolve => speedycache_load_js(e, resolve));
	});
	
	if(speedycache_djs_timeout != null){
		clearTimeout(speedycache_djs_timeout);
		speedycache_djs_timeout = null;
	}
}

function speedycache_load_js(js, resolve){
	let async_js = document.createElement('script');
	
	let attr = js.getAttributeNames();
	attr.forEach(name => {
		if(name === 'type'){
			return;
		}

		async_js.setAttribute(name == 'data-src' ? 'src' : name, js.getAttribute(name));
	});

	async_js.setAttribute('type', 'text/javascript');
	
	if(!js.hasAttribute('data-src')){
		async_js.text = js.text;
	}

	async_js.addEventListener('load', resolve);

	js.after(async_js);
	js.remove();

}
})();
assets/js/admin.js000064400000001512151526423640010117 0ustar00jQuery(document).ready(function($) {
	$('.speedycache-test-notice .speedycache-custom-dismiss').click(function(e) {
		e.preventDefault();
		$('.speedycache-test-notice').slideUp();
			$.ajax({
				url: speedycache_pro_ajax.url,
				type: 'POST',
				data: {
					action: 'speedycache_dismiss_test_notice',
					security: speedycache_pro_ajax.nonce
				}
			});
		});	

	$('.speedycache-copy-test-settings').click(function(e){
		e.preventDefault();
		$.ajax({
			method : 'GET',
			url : speedycache_pro_ajax.url + '?action=speedycache_copy_test_settings&security='+speedycache_pro_ajax.nonce,
			success: function(res){
				if(res.success){
					alert('The settings has been successfully saved!');
					location.reload(true);
					return;
				}
				if(res.data){
					alert(res.data);
				}
			}
		});
	});
})
assets/js/heartbeat.js000064400000000000151526423640010755 0ustar00assets/images/no-image.png000064400000003441151526423640011527 0ustar00�PNG


IHDR<PE�S	pHYs���\�rtEXtSoftwarewww.inkscape.org��<�IDATx��_H��?3�I��f������n*��K�R��胘E�B\��do�r7��@Ԡ�"{�|�$1��0
��uIt�5u�?s�5����[�o��ۜ3����3s��V�����$I׀q(�y����h���}h69�_M�%I�7ʗ�H����v���o�'��������w�
+UX��JGV:���Q���*�tTa��
+UX��JGhoo���������ݻ�P���Vjjj�����בe��XQ��v�u�VZ[[岩�)����������`0p��I222����_�B�-�^�jy}�G���<�>}��f�9���r�����"UUU�}�3gΐ��MOO� p��9�<y��� !!��ׯc0hoo�ѣG��� �".\ ;;�;w���Յ^�G��QTTDqq1sss�l6<^���‰'�'�{��������r�͆�b!//��A]]---DGG�)<99INNUUUttt��ֆ�j%99��ʳg�(**���:u
Q���dgg���iiiA����܌���֭[r��1���8�<999��ǯO�l6���?.���~FGG��� %%�m۶�p8ؽ{��¢(�
���Jbb"���r���9ikk�n��e���A�����t���ȱ���	tww��p:����C����={��z�$Ik�?� �G�$jkk9{�,UUU���s��Ű���B����e��,!!!�5���{��s�Nz{{�j��ڵK�u�����,)))��\�P(���f��F�۷o���L������`dd$l���ʢ�����D������>�/,��=�V�����˹t�QQQ�������{������C�kn޼��n������X�fsX닢6$u:� EYY������r��!���G�211Acc#&�	��$vuu5MMMTVV�����իa9	n�����_,//��A�Q�~?� ���_$I"��j	�B\�r���`�$�P($w��D�nǯ��F��eee�F0����"_F�JD�ÛE ���b����R8���CD�pOO���ae���E��jLMMa�ٸv�چ��Hx``����z���A���7|}�o��۷��������E>|(/7-Z����Q�n7999���h4ddd��ݍ^��իW�\.


��˓�ݿ�Á�d�(߈����a:;;���װV�Q)//���`�����a+�7o�ȷ�˗/inn&--���Bnܸ!�����	�����cǎ�򍸇?~�ȇ�����Y��ƨ��G*++9}�4~��X%%%�����c&&&XZZ��ra�Z��@GGdž�X�ȑ#�����v����xyc��j��������d�t:B�n��Ѹ�Fc#��ii�����̰�����,~�����z����/V�d2�r��oD���#�刺6���)))����Ç���MEE�(r����hjjbzz����S\\�j<��Dff&�/_&55��i�G�h��t:��t+>9߽{��8��餦��哓�

���NLL� �����8qqq�ull�Ʉ�` ��ׇ$I<x�����7����T:���Q���*�tTa��
+UX��JGV:���Q���*�t�Ha�g)����,~�$�	n��Ѝ���F���z���-�I���5�}��;��"�	IEND�B`�assets/images/image-palceholder.png000064400000000221151526423640013366 0ustar00�PNG


IHDR+F],sRGB��,	pHYs��PLTE���������8�;�tRNSn�p2��IDATx�c`�a0�����FIEND�B`�functions.php000064400000024614151526423640007304 0ustar00<?php

// Are we being accessed directly ?
if(!defined('ABSPATH')) {
	exit('Hacking Attempt !');
}

// Is called when the ADMIN enables the plugin
function speedycache_pro_activate(){
	global $speedycache;
	
	if(empty($speedycache)){
		$speedycache = new \SpeedyCache();
	}

	$speedycache->options = get_option('speedycache_options', []);
	$speedycache->options['minify_html'] = true;
	$speedycache->options['minify_js'] = true;
	$speedycache->options['render_blocking'] = true;

	update_option('speedycache_options', $speedycache->options);
	update_option('speedycache_pro_version', SPEEDYCACHE_PRO_VERSION);
}

// Load license data
function speedycache_pro_load_license($parent = 0){
	global $speedycache, $lic_resp;
	
	$license_field = 'speedycache_license';
	$license_api_url = SPEEDYCACHE_API;
	
	// Save license
	if(!empty($parent) && is_string($parent) && strlen($parent) > 5){		
		$lic['license'] = $parent;
	
	// Load license of Soft Pro
	}elseif(!empty($parent)){
		$license_field = 'softaculous_pro_license';
		$lic = get_option('softaculous_pro_license', []);
	
	// My license
	}else{
		$lic = get_option($license_field, []);
	}
	
	// Loaded license is a Soft Pro
	if(!empty($lic['license']) && preg_match('/^softwp/is', $lic['license'])){
		$license_field = 'softaculous_pro_license';
		$license_api_url = 'https://a.softaculous.com/softwp/';
		$prods = apply_filters('softaculous_pro_products', []);
	}else{
		$prods = [];
	}

	if(empty($lic['last_update'])){
		$lic['last_update'] = time() - 86600;
	}
	
	// Update license details as well
	if(!empty($lic) && !empty($lic['license']) && (time() - @$lic['last_update']) >= 86400){
		
		$url = $license_api_url.'/license.php?license='.$lic['license'].'&prods='.implode(',', $prods).'&url='.rawurlencode(site_url());
		$resp = wp_remote_get($url);
		$lic_resp = $resp;

		//Did we get a response ?
		if(is_array($resp)){
			
			$tosave = json_decode($resp['body'], true);
			
			//Is it the license ?
			if(!empty($tosave['license'])){
				$tosave['last_update'] = time();
				update_option($license_field, $tosave);
				$lic = $tosave;
			}
		}
	}
	
	// If the license is Free or Expired check for Softaculous Pro license
	if(empty($lic) || empty($lic['active'])){
		
		if(function_exists('softaculous_pro_load_license')){
			$softaculous_license = softaculous_pro_load_license();
			if(!empty($softaculous_license['license']) && 
				(!empty($softaculous_license['active']) || empty($lic['license']))
			){
				$lic = $softaculous_license;
			}
		}elseif(empty($parent)){
			$soft_lic = get_option('softaculous_pro_license', []);
			
			if(!empty($soft_lic)){
				return speedycache_pro_load_license(1);
			}
		}
	}
	
	if(!empty($lic['license'])){
		$speedycache->license = $lic;
	}

}

add_filter('softaculous_pro_products', 'speedycache_softaculous_pro_products', 10, 1);
function speedycache_softaculous_pro_products($r = []){
	$r['speedycache'] = 'speedycache';
	return $r;
}

// Add our license key if ANY
function speedycache_pro_updater_filter_args($queryArgs) {
	
	global $speedycache;

	if ( !empty($speedycache->license['license']) ) {
		$queryArgs['license'] = $speedycache->license['license'];
	}

	$queryArgs['url'] = rawurlencode(site_url());

	return $queryArgs;
}

// Handle the Check for update link and ask to install license key
function speedycache_pro_updater_check_link($final_link){
	
	global $speedycache;
	
	if(empty($speedycache->license['license'])){
		return '<a href="'.admin_url('admin.php?page=speedycache_license').'">Install SpeedyCache Pro License Key</a>';
	}
	
	return $final_link;
}

function speedycache_pro_is_network_active($pluign){
	$is_network_wide = false;
	
	// Handling network site
	if(!is_multisite()){
		return $is_network_wide;
	}
	
	$_tmp_plugins = get_site_option('active_sitewide_plugins');

	if(!empty($_tmp_plugins) && preg_grep('/.*\/'.$pluign.'\.php$/', array_keys($_tmp_plugins))){
		$is_network_wide = true;
	}
	
	return $is_network_wide;
}

// Prevent update of SpeedyCache free
function speedycache_pro_get_free_version_num(){
		
	if(defined('SPEEDYCACHE_VERSION')){
		return SPEEDYCACHE_VERSION;
	}
	
	// In case of SpeedyCache deactive
	return speedycache_pro_file_get_version_num('speedycache/speedycache.php');
}

// Prevent update of SpeedyCache free
function speedycache_pro_file_get_version_num($plugin){
	
	// In case of SpeedyCache deactive
	include_once(ABSPATH . 'wp-admin/includes/plugin.php');
	$plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/'.$plugin);

	if(empty($plugin_data)){
		return false;
	}

	return $plugin_data['Version'];

}

// Prevent update of SpeedyCache free
function speedycache_pro_disable_manual_update_for_plugin($transient){
	$plugin = 'speedycache/speedycache.php';
	
	// Is update available?
	if(!isset($transient->response) || !isset($transient->response[$plugin])){
		return $transient;
	}
	
	$free_version = speedycache_pro_get_free_version_num();
	$pro_version = SPEEDYCACHE_PRO_VERSION;
	
	if(!empty($GLOBALS['speedycache_pro_is_upgraded'])){
		$pro_version = speedycache_pro_file_get_version_num('speedycache-pro/speedycache-pro.php');
	}

	// Update the SpeedyCache version to the equivalent of Pro version
	if(!empty($pro_version) && version_compare($free_version, $pro_version, '<')){
		$transient->response[$plugin]->new_version = $pro_version;
		$transient->response[$plugin]->package = 'https://downloads.wordpress.org/plugin/speedycache.'.$pro_version.'.zip';
	}else{
		unset($transient->response[$plugin]);
	}

	return $transient;
}

// Auto update free version after update pro version
function speedycache_pro_update_free_after_pro($upgrader_object, $options){
	
	// Check if the action is an update for the plugins
	if($options['action'] != 'update' || $options['type'] != 'plugin'){
		return;
	}
		
	// Define the slugs for the free and pro plugins
	$free_slug = 'speedycache/speedycache.php'; 
	$pro_slug = 'speedycache-pro/speedycache-pro.php';

	// Check if the pro plugin is in the list of updated plugins
	if( 
		(isset($options['plugins']) && in_array($pro_slug, $options['plugins']) && !in_array($free_slug, $options['plugins'])) ||
		(isset($options['plugin']) && $pro_slug == $options['plugin'])
	){
	
		// Trigger the update for the free plugin
		$current_version = speedycache_pro_get_free_version_num();
		
		if(empty($current_version)){
			return;
		}
		
		$GLOBALS['speedycache_pro_is_upgraded'] = true;
		
		// This will set the 'update_plugins' transient again
		wp_update_plugins();

		// Check for updates for the free plugin
		$update_plugins = get_site_transient('update_plugins');
		
		if(empty($update_plugins) || !isset($update_plugins->response[$free_slug]) || version_compare($update_plugins->response[$free_slug]->new_version, $current_version, '<=')){
			return;
		}
		
		require_once(ABSPATH . 'wp-admin/includes/plugin.php');
		require_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
		
		$skin = wp_doing_ajax()? new WP_Ajax_Upgrader_Skin() : null;
		
		$upgrader = new Plugin_Upgrader($skin);
		$upgraded = $upgrader->upgrade($free_slug);
		
		if(!is_wp_error($upgraded) && $upgraded){
			// Re-active free plugins
			if( file_exists( WP_PLUGIN_DIR . '/'.  $free_slug ) && is_plugin_inactive($free_slug) ){
				activate_plugin($free_slug); // TODO for network
			}
			
			// Re-active pro plugins
			if( file_exists( WP_PLUGIN_DIR . '/'.  $pro_slug ) && is_plugin_inactive($pro_slug) ){
				activate_plugin($pro_slug); // TODO for network
			}
		}
	}
}

// Looks if SpeedyCache just got updated
function speedycache_pro_update_check(){
	$sql = array();
	$current_version = get_option('speedycache_pro_version');
	$version = (int) str_replace('.', '', $current_version);

	// No update required
	if($current_version == SPEEDYCACHE_PRO_VERSION){
		return true;
	}

	// If the user was using SpeedyCache Pro before seperation
	// then we need to clear the cache as we have updated the location of assets of the Pro version.
	if(empty($current_version) || (!empty($current_version) && version_compare($current_version, '1.2.0', '<'))){
		$free_version = get_option('speedycache_version');

		if(!empty($free_version)){
			$desk_cache = glob(WP_CONTENT_DIR . '/cache/speedycache/'. sanitize_text_field($_SERVER['HTTP_HOST']) .'/all/*', GLOB_ONLYDIR);
			$mobile_cache = glob(WP_CONTENT_DIR . '/cache/speedycache/'. sanitize_text_field($_SERVER['HTTP_HOST']) .'/mobile-cache/*', GLOB_ONLYDIR);
			$deletable_dir = [];
			
			if(!empty($desk_cache)){
				$deletable_dir = $desk_cache;
			}

			if(!empty($mobile_cache)){
				$deletable_dir = array_merge($mobile_cache, $deletable_dir);
			}

			if(!empty($deletable_dir)){
				global $wp_filesystem;
				
				include_once(ABSPATH . 'wp-admin/includes/file.php');
				WP_Filesystem();
				
				foreach($deletable_dir as $dir){
					if(method_exists($wp_filesystem, 'delete')){
						$wp_filesystem->delete($dir, true);
					}
				}
			}
		}

		speedycache_pro_activate();
	}
	
	$is_network_wide = speedycache_pro_is_network_active('speedycache-pro');
	
	if($is_network_wide){
		$free_ins = get_site_option('speedycache_free_installed');
	}else{
		$free_ins = get_option('speedycache_free_installed');
	}
		
	// If plugin runing reached here it means SpeedyCache free installed 
	if(empty($free_ins)){
		if($is_network_wide){
			update_site_option('speedycache_free_installed', time());
		}else{
			update_option('speedycache_free_installed', time());
		}
	}
	
	// Re-init NAG dismiss expire time
	update_option('speedycache_pro_older_pro_version_nag', time());
	update_option('speedycache_pro_older_free_version_nag', time());

	// Save the new Version
	update_option('speedycache_pro_version', SPEEDYCACHE_PRO_VERSION);
}
	
function speedycache_pro_api_url($main_server = 0, $suffix = 'speedycache'){
	
	global $speedycache;
	
	$r = array(
		'https://s0.softaculous.com/a/softwp/',
		'https://s1.softaculous.com/a/softwp/',
		'https://s2.softaculous.com/a/softwp/',
		'https://s3.softaculous.com/a/softwp/',
		'https://s4.softaculous.com/a/softwp/',
		'https://s5.softaculous.com/a/softwp/',
		'https://s7.softaculous.com/a/softwp/',
		'https://s8.softaculous.com/a/softwp/'
	);
	
	$mirror = $r[array_rand($r)];
	
	// If the license is newly issued, we need to fetch from API only
	// This is to give time to the mirror server to replicate the data.
	if(!empty($main_server) || empty($speedycache->license['last_edit']) || 
		(!empty($speedycache->license['last_edit']) && (time() - 3600) < $speedycache->license['last_edit'])
	){
		$mirror = SPEEDYCACHE_API;
	}
	
	if(!empty($suffix)){
		$mirror = str_replace('/softwp', '/'.$suffix, $mirror);
	}
	
	return $mirror;
	
}init.php000064400000020522151526423640006231 0ustar00<?php

if(!defined('ABSPATH')){
	die('Hacking Attempt!');
}

if(!class_exists('SpeedyCache')){
#[\AllowDynamicProperties]
class SpeedyCache{
	public $options = array();
	public $brand_name = 'SpeedyCache';
	public $logs;
	public $settings;
	public $license;
	public $image;
	public $mobile_cache;
	public $columnjs;
	public $js;
	public $css_util;
	public $render_blocking;
	public $enhanced;
	public $object;
	public $bloat;
}
}

// Prevent update of speedycache free
// This also work for auto update
add_filter('site_transient_update_plugins', 'speedycache_pro_disable_manual_update_for_plugin');
add_filter('pre_site_transient_update_plugins', 'speedycache_pro_disable_manual_update_for_plugin');

// Auto update free version after update pro version
add_action('upgrader_process_complete', 'speedycache_pro_update_free_after_pro', 10, 2);

add_action('plugins_loaded', 'speedycache_pro_load_plugin');

register_activation_hook( __FILE__, 'speedycache_pro_activate');

function speedycache_pro_load_plugin(){
	global $speedycache;
	
	if(empty($speedycache)){
		$speedycache = new \SpeedyCache();
	}
	
	speedycache_pro_load_license();

	// Actions to handle WP Cron schedules
	add_action('speedycache_auto_optm', '\SpeedyCache\Image::auto_optimize', 10, 1);
	add_action('speedycache_img_delete', '\SpeedyCache\Image::scheduled_delete', 10, 1);
	add_action('speedycache_generate_ccss', '\SpeedyCache\CriticalCss::generate', 10, 1);
	add_action('speedycache_unused_css', '\SpeedyCache\UnusedCss::generate', 10, 1);
	
	speedycache_pro_update_check();
	
	add_action('speedycache_test_event', 'speedycache_pro_run_test');
	
	// Check for updates
	include_once(SPEEDYCACHE_PRO_DIR . '/main/plugin-update-checker.php');
	$speedycache_updater = SpeedyCache_PucFactory::buildUpdateChecker(speedycache_pro_api_url().'/updates.php?version='.SPEEDYCACHE_PRO_VERSION, SPEEDYCACHE_PRO_FILE);

	// Add the license key to query arguments
	$speedycache_updater->addQueryArgFilter('speedycache_pro_updater_filter_args');
		
	// Show the text to install the license key
	add_filter('puc_manual_final_check_link-speedycache-pro', 'speedycache_pro_updater_check_link', 10, 1);	
	
	if(!is_admin() && !current_user_can('activate_plugins')){
		return;
	}

	include_once SPEEDYCACHE_PRO_DIR . '/main/admin.php';
	add_action('admin_notices', 'speedycachepro_free_version_nag');
}
	
// Nag when plugins dont have same version.
function speedycachepro_free_version_nag(){
	
	if(!defined('SPEEDYCACHE_VERSION')){
		return;
	}

	$dismissed_free = (int) get_option('speedycache_version_free_nag');
	$dismissed_pro = (int) get_option('speedycache_version_pro_nag');

	// Checking if time has passed since the dismiss.
	if(!empty($dismissed_free) && time() < $dismissed_pro && !empty($dismissed_pro) && time() < $dismissed_pro){
		return;
	}

	$showing_error = false;
	if(version_compare(SPEEDYCACHE_VERSION, SPEEDYCACHE_PRO_VERSION) > 0 && (empty($dismissed_pro) || time() > $dismissed_pro)){
		$showing_error = true;

		echo '<div class="notice notice-warning is-dismissible" id="speedycache-pro-version-notice" onclick="speedycache_pro_dismiss_notice(event)" data-type="pro">
		<p style="font-size:16px;">'.esc_html__('You are using an older version of SpeedyCache Pro. We recommend updating to the latest version to ensure seamless and uninterrupted use of the application.', 'speedycache').'</p>
	</div>';
	}elseif(version_compare(SPEEDYCACHE_VERSION, SPEEDYCACHE_PRO_VERSION) < 0 && (empty($dismissed_free) || time() > $dismissed_free)){
		$showing_error = true;

		echo '<div class="notice notice-warning is-dismissible" id="speedycache-pro-version-notice" onclick="speedycache_pro_dismiss_notice(event)" data-type="free">
		<p style="font-size:16px;">'.esc_html__('You are using an older version of SpeedyCache. We recommend updating to the latest free version to ensure smooth and uninterrupted use of the application.', 'speedycache').'</p>
	</div>';
	}
	
	if(!empty($showing_error)){
		wp_register_script('speedycache-pro-version-notice', '', array('jquery'), SPEEDYCACHE_PRO_VERSION, true );
		wp_enqueue_script('speedycache-pro-version-notice');
		wp_add_inline_script('speedycache-pro-version-notice', '
	function speedycache_pro_dismiss_notice(e){
		e.preventDefault();
		let target = jQuery(e.target);

		if(!target.hasClass("notice-dismiss")){
			return;
		}

		let jEle = target.closest("#speedycache-pro-version-notice"),
		type = jEle.data("type");

		jEle.slideUp();
		
		jQuery.post("'.admin_url('admin-ajax.php').'", {
			security : "'.wp_create_nonce('speedycache_version_notice').'",
			action: "speedycache_pro_version_notice",
			type: type
		}, function(res){
			if(!res["success"]){
				alert(res["data"]);
			}
		}).fail(function(data){
			alert("There seems to be some issue dismissing this alert");
		});
	}');
	}
}

// Version nag ajax
function speedycache_pro_version_notice(){
	check_admin_referer('speedycache_version_notice', 'security');

	if(!current_user_can('activate_plugins')){
		wp_send_json_error(__('You do not have required access to do this action', 'speedycache-pro'));
	}
	
	$type = '';
	if(!empty($_REQUEST['type'])){
		$type = sanitize_text_field(wp_unslash($_REQUEST['type']));
	}

	if(empty($type)){
		wp_send_json_error(__('Unknown version difference type', 'speedycache-pro'));
	}
	
	update_option('speedycache_version_'. $type .'_nag', time() + WEEK_IN_SECONDS);
	wp_send_json_success();
}
add_action('wp_ajax_speedycache_pro_version_notice', 'speedycache_pro_version_notice');

function speedycache_pro_run_test() {

	update_option('speedycache_test_executed', 1);

	$speedycache_options = get_option('speedycache_options', []);
 	$should_test_optimization = (empty($speedycache_options['delay_js']) || empty($speedycache_options['render_blocking']));

	if (!$should_test_optimization){
		return;
	}

	$url = site_url();

	$old_score_arr = speedycache_pro_test_score($url);
	$new_score_arr = speedycache_pro_test_score($url . '?test_speedycache=1');

	$old_score = intval($old_score_arr['score']);
	$new_score = intval($new_score_arr['score']);

	if($new_score <= $old_score){
		return;
	} 

	$test_results = [
		'old_score' => $old_score,
		'new_score' => $new_score,
	];
	
	// Deleting the test file
	$test_dir = \SpeedyCache\Util::cache_path('test');

	if(file_exists($test_dir) && file_exists($test_dir .'/index.html')){
		unlink($test_dir .'/index.html');
	}
	
	update_option('speedycache_test_results', $test_results);
}

function speedycache_pro_test_score($url) {

	$parsed_url = parse_url($url);
	parse_str($parsed_url['query'] ?? '', $query_params);

	$is_test_mode = isset($query_params['test_speedycache']) && $query_params['test_speedycache'] === '1';

	if($is_test_mode){
		global $speedycache;

		$speedycache_test_options = ['minify_html' => true, 'delay_js' => true, 'render_blocking' => true, 'minify_js' => true, 'critical_images' => true, 'lazy_load' => true, 'delay_js_mode' => 'selected', 'delay_js_scripts' => ['fbevents.js', 'google-analytics.com', 'adsbygoogle.js', 'googletagmanager.com', 'fbq(', "ga( '", "ga('", '/gtm.js', '/gtag/js', 'gtag(', '/gtm-', '/gtm.']];

		$speedycache->options = array_merge($speedycache->options, $speedycache_test_options);
		$test_folder = \SpeedyCache\Util::cache_path('test');

		if(!file_exists($test_folder)){
			mkdir($test_folder, 0755, true);
		}
		
		$cache_content = speedycache_pro_generate_test_cache($url);
		if($cache_content){
			file_put_contents($test_folder . '/index.html', $cache_content);
		}
	}

	$api_url = SPEEDYCACHE_API . 'pagespeed.php?url=' . $url;

	$res = wp_remote_post($api_url, [
		'sslverify' => false,
		'timeout' => 30
	]);

	if(is_wp_error($res) || empty($res['body'])){
		return 0;
	}

	$body = json_decode($res['body'], true);

	return !empty($body['success']) && !empty($body['results']) ? $body['results'] : 0;
}

function speedycache_pro_generate_test_cache($url) {
	$response = wp_safe_remote_get($url);
	if(is_wp_error($response) || empty($response['body'])){
		return false;
	}
	return $response['body'];
}


//register_deactivation_hook( __FILE__, '\SpeedyCache\Install::deactivate');

// Load WP CLI command(s) on demand.
if(defined('WP_CLI') && !empty(WP_CLI) && defined('SPEEDYCACHE_PRO')){
	include_once SPEEDYCACHE_PRO_DIR.'/main/cli.php';
}main/license.php000064400000010167151526423640007640 0ustar00<?php

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT!');
}

include_once SPEEDYCACHE_DIR . '/main/settings.php';

function speedycache_license_page(){
	global $speedycache;
	
	if(isset($_REQUEST['save_speedycache_license'])){
		speedycache_license();
	}
	
	speedycache_add_javascript();
	settings_errors('speedycache-notice');
	
	?>
	
	<div class="speedycache-setting-content">
		<div class="speedycache-tab-group" style="width:78%">
			<table class="wp-list-table fixed striped users speedycache-license-table" cellspacing="1" border="0" width="78%" cellpadding="10" align="center">
				<tbody>
					<tr>				
						<th align="left" width="25%"><?php esc_html_e('SpeedyCache Version', 'speedycache'); ?></th>
						<td><?php
							echo SPEEDYCACHE_PRO_VERSION.(defined('SPEEDYCACHE_PRO') ? ' (Pro Version)' : '');
						?>
						</td>
					</tr>
					<tr>			
						<th align="left" valign="top"><?php esc_html_e('SpeedyCache License', 'speedycache'); ?></th>
						<td align="left">
							<form method="post" action="">
								<span style="color:var(--speedycache-red)">
									<?php echo (defined('SPEEDYCACHE_PRO') && empty($speedycache->license) ? '<span style="color:var(--speedycache-red)">Unlicensed</span> &nbsp; &nbsp;' : '')?>
								</span>
								<input type="hidden" name="speedycache_license_nonce" value="<?php echo wp_create_nonce('speedycache_license');?>"/>
								<input type="text" name="speedycache_license" value="<?php echo (empty($speedycache->license) ? empty($_POST['speedycache_license']) ? '' : speedycache_optpost('speedycache_license') : $speedycache->license['license'])?>" size="30" placeholder="e.g. SPDFY-11111-22222-33333-44444" style="width:300px;"> &nbsp; 
								<input name="save_speedycache_license" class="speedycache-btn speedycache-btn-primary" value="Update License" type="submit">
							</form>
							<?php if(!empty($speedycache->license)){
								
								$expires = $speedycache->license['expires'];
								$expires = substr($expires, 0, 4).'/'.substr($expires, 4, 2).'/'.substr($expires, 6);
								
								echo '<div style="margin-top:10px;">License Status : '.(empty($speedycache->license['status_txt']) ? 'N.A.' : wp_kses_post($speedycache->license['status_txt'])).' &nbsp; &nbsp; &nbsp; 
								'.($speedycache->license['expires'] <= date('Ymd') ? 'License Expires : <span style="color:var(--speedycache-red)">'.esc_attr($expires).'</span>' : (empty($speedycache->license['has_plid']) ? 'License Expires : ' . esc_html($expires) : '')).'
								</div>';
								
							}?>
						</td>
					</tr>
					<tr>
						<th align="left">URL</th>
						<td><?php echo get_site_url(); ?></td>
					</tr>
					<tr>				
						<th align="left">Path</th>
						<td><?php echo ABSPATH; ?></td>
					</tr>
					<tr>				
						<th align="left">Server's IP Address</th>
						<td><?php echo esc_html($_SERVER['SERVER_ADDR']); ?></td>
					</tr>
					<tr>				
						<th align="left">.htaccess is writable</th>
						<td><?php echo (is_writable(ABSPATH.'/.htaccess') ? '<span style="color:var(--speedycache-red)">Yes</span>' : '<span style="color:green">No</span>');?></td>
					</tr>		
				</tbody>
			</table>
		</div>
	<?php speedycache_promotion_tmpl(); ?>
	</div>
<?php
	speedycache_page_footer(true);
}

function speedycache_license(){
	global $speedycache, $lic_resp;

	if(!wp_verify_nonce($_POST['speedycache_license_nonce'], 'speedycache_license')){
		speedycache_notify(array(__('Security Check Failed', 'speedycache'),'error'));
		return;
	}

	$license = sanitize_key($_POST['speedycache_license']);
	
	if(empty($license)){
		speedycache_notify(array(__('The license key was not submitted', 'speedycache'),'error'));
		return;
	}
	
	speedycache_pro_load_license($license);
	
	if(!is_array($lic_resp)){
		speedycache_notify(array(__('The response was malformed<br>'.var_export($lic_resp, true), 'speedycache'), 'error'));
		return;
	}

	$json = json_decode($lic_resp['body'], true);
	
	// Save the License
	if(empty($json['license'])){
		speedycache_notify(array(__('The license key is invalid', 'speedycache'), 'error'));
		return;
		
	}
	
}
main/bloat.php000064400000024224151526423640007316 0ustar00<?php

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT!');
}

class Bloat{

	static function actions(){
		global $speedycache;
		
		// Add the filters / actions
		if(!empty($speedycache->bloat['disable_xmlrpc'])){
			add_filter('xmlrpc_enabled', '__return_null');
			add_filter('bloginfo_url', '\SpeedyCache\Bloat::xmlrpc_remove_pingback_url', 10000, 2);
			add_action('wp_loaded', '\SpeedyCache\Bloat::xmlrpc_disable');
		}
		
		// Disable DashIcons
		if(!empty($speedycache->bloat['disable_dashicons'])){
			add_action('wp_print_styles', '\SpeedyCache\Bloat::disable_dashicons');
		}
		
		if(!is_admin()){
			// Remove jQuery migrate
			if(!empty($speedycache->bloat['disable_jmigrate'])){
				add_action('wp_default_scripts', '\SpeedyCache\Bloat::remove_jquery_migrate');
			}
			
			// Remove Block CSS
			if(!empty($speedycache->bloat['disable_block_css'])){
				add_action('wp_enqueue_scripts', '\SpeedyCache\Bloat::disable_block_editor_css');
			}

			// Disable Cart Fragment
			if(!empty($speedycache->bloat['disable_cart_fragment'])){
				add_action('wp_enqueue_scripts', '\SpeedyCache\Bloat::disable_cart_fragment', 11);
			}
			
			// Disable WooCommerce Assets
			if(!empty($speedycache->bloat['disable_woo_assets'])){
				add_action('wp_enqueue_scripts', '\SpeedyCache\Bloat::disable_woocommerce_assets', 99);
			}
			
			// Disale RSS Feeds
			if(!empty($speedycache->bloat['disable_rss'])){
				add_action('do_feed_rdf', '\SpeedyCache\Bloat::disable_wp_feeds', 1);
				add_action('do_feed_rss', '\SpeedyCache\Bloat::disable_wp_feeds', 1);
				add_action('do_feed_rss2', '\SpeedyCache\Bloat::disable_wp_feeds', 1);
				add_action('do_feed_atom', '\SpeedyCache\Bloat::disable_wp_feeds', 1);
				add_action('do_feed_rss2_comments', '\SpeedyCache\Bloat::disable_wp_feeds', 1);
				add_action('do_feed_atom_comments', '\SpeedyCache\Bloat::disable_wp_feeds', 1);
				
				// Remove links
				remove_action( 'wp_head', 'feed_links_extra', 3 );
				remove_action( 'wp_head', 'feed_links', 2 );
			}
		}

		// Disable OEmbeds
		if(!empty($speedycache->bloat['disable_oembeds'])){
			add_action('init', '\SpeedyCache\Bloat::disable_oembeds');
		}
		
		if(!empty($speedycache->bloat['disable_gutenberg'])){
			add_filter('use_block_editor_for_post_type', '__return_false', 100);
			add_filter('after_setup_theme', '\SpeedyCache\Bloat::disable_gutenberg_hooks');
		}
		
		// Limit Post revisions
		if(!empty($speedycache->bloat['limit_post_revision'])){
			add_filter('wp_revisions_to_keep', '\SpeedyCache\Bloat::limit_post_revisions');
		}

		// Update Heartbeat
		if(!empty($speedycache->bloat['update_heartbeat'])){
			add_action('init', '\SpeedyCache\Bloat::disable_heartbeat');
			add_action('wp_enqueue_scripts', '\SpeedyCache\Bloat::disable_heartbeat');
			add_action('admin_enqueue_scripts', '\SpeedyCache\Bloat::disable_heartbeat');
			add_filter('heartbeat_settings', '\SpeedyCache\Bloat::change_heartbeat_interval', 100);
		}
	}

	// Disbale XML request
	static function xmlrpc_disable(){
		global $pagenow;

		// Is it xmlrpc.php ?
		if ($pagenow === 'xmlrpc.php'){	
			echo 'XML-RPC is disabled';
			exit();
		}	
	}
	
	// Disables the XML-RPC functionality
	static function xmlrpc_remove_pingback_url($output, $show) {

		if($show == 'pingback_url'){
			$output = '';
		}

		return $output;
	}
	
	// Disable Dashicons
	static function disable_dashicons(){
		if(!is_admin_bar_showing() && !is_customize_preview()){
			wp_dequeue_style('dashicons');
			wp_deregister_style('dashicons');
		}
	}
	
	// Remove jQuery Migrate
	static function remove_jquery_migrate($scripts){
		
		if(!is_admin() && isset($scripts->registered['jquery'])){
			$script = $scripts->registered['jquery'];

			if($script->deps){
				$script->deps = array_diff($script->deps, array('jquery-migrate'));
			}
		}
	}
	
	// Disable OEmbeds
	static function disable_oembeds(){
		// Remove oEmbed REST API endpoint
		remove_action('rest_api_init', 'wp_oembed_register_route');

		// Disable oEmbed auto-discovery links
		remove_action('wp_head', 'wp_oembed_add_discovery_links');

		// Disable oEmbed-specific JavaScript from the front-end and back-end
		remove_action('wp_head', 'wp_oembed_add_host_js');

		// Remove oEmbed provider fetch URL rewriting
		remove_filter('oembed_fetch_url', 'wp_oembed_rewrite_url');

		// Disable oEmbed in TinyMCE editor
		add_filter('tiny_mce_plugins', '\SpeedyCache\Bloat::disable_tiny_mce_oembed');
	}

	static function disable_tiny_mce_oembed($plugins){
		return array_diff($plugins, array('wpembed'));
	}

	// Remove Block Editor CSS
	static function disable_block_editor_css(){
		wp_dequeue_style('wp-block-library');
		wp_dequeue_style('wp-block-library-theme');
		wp_dequeue_style('wp-block-style');
	}
	
	// Updates the count of number of post revesions.
	static function limit_post_revisions($num){
		global $speedycache;
		
		if(!empty($speedycache->bloat['post_revision_count']) && $speedycache->bloat['post_revision_count'] === 'disable'){
			$num = 0;
		} elseif(!empty($speedycache->bloat['post_revision_count']) && is_numeric($speedycache->bloat['post_revision_count'])){
			$num = intval($speedycache->bloat['post_revision_count']);
		}

		return $num;
	}
	
	// Updating the Heartbeat interval.
	static function change_heartbeat_interval($settings){
		global $speedycache;

		if(!empty($speedycache->bloat['heartbeat_frequency'])){
			$settings['interval'] = $speedycache->bloat['heartbeat_frequency'];
			$settings['minimalInterval'] = $speedycache->bloat['heartbeat_frequency'];
		}

		return $settings;
	}
	
	static function disable_cart_fragment(){
		if(function_exists('is_woocommerce')){
			if(!is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page() && !is_product() && !is_product_category() && !is_shop()){
				wp_dequeue_script('wc-cart-fragments');
			}
		}
	}
	
	static function disable_woocommerce_assets(){
		if(!class_exists('WooCommerce')){
			return;
		}
		
		if(!is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page() && !is_product() && !is_product_category() && !is_shop()){
			// Disable WooCommerce stylesheets
			wp_dequeue_style('woocommerce-general');
			wp_dequeue_style('woocommerce-layout');
			wp_dequeue_style('woocommerce-smallscreen');
			wp_dequeue_style('woocommerce_frontend_styles');
			wp_dequeue_style('woocommerce_fancybox_styles');
			wp_dequeue_style('woocommerce_chosen_styles');
			wp_dequeue_style('woocommerce_prettyPhoto_css');

			// Disable WooCommerce scripts
			wp_dequeue_script('wc_price_slider');
			wp_dequeue_script('wc-single-product');
			wp_dequeue_script('wc-add-to-cart');
			wp_dequeue_script('wc-checkout');
			wp_dequeue_script('wc-add-to-cart-variation');
			wp_dequeue_script('wc-single-product');
			wp_dequeue_script('wc-cart');
			wp_dequeue_script('wc-chosen');
			wp_dequeue_script('woocommerce');
			wp_dequeue_script('prettyPhoto');
			wp_dequeue_script('prettyPhoto-init');
			wp_dequeue_script('jquery-blockui');
			wp_dequeue_script('jquery-placeholder');
			wp_dequeue_script('fancybox');
			wp_dequeue_script('jqueryui');
		}
	}
	
	static function disable_wp_feeds(){
		 wp_die(sprintf(esc_html__('No feed available, please visit our %1$shomepage%2$s!'),
            ' <a href="' . esc_url( home_url( '/' ) ) . '">',
            '</a>'));
	}
	
	static function disable_heartbeat(){
		global $speedycache, $pagenow;

		if(empty($speedycache->bloat['disable_heartbeat'])) {
			return;
		}

		$remove_heartbeat = false;

		switch($speedycache->bloat['disable_heartbeat']){
			case 'disable':
				$remove_heartbeat = true;
				break;
				
			case 'editor':
				if($pagenow != 'post.php' && $pagenow != 'post-new.php'){
					$remove_heartbeat = true;
				}
		}
		
		if(!empty($remove_heartbeat)){
			wp_deregister_script('heartbeat');
		
			//We have replaced heartbeat with an empty heartbeat to prevent any errors
			wp_enqueue_script('heartbeat', SPEEDYCACHE_PRO_URL . '/assets/js/heartbeat.js', null, SPEEDYCACHE_PRO_VERSION, true);
		}
	}

	// Disable Gutenberg
	static function disable_gutenberg_hooks(){
		remove_action('admin_menu', 'gutenberg_menu');
		remove_action('admin_init', 'gutenberg_redirect_demo');

		remove_filter('wp_refresh_nonces', 'gutenberg_add_rest_nonce_to_heartbeat_response_headers');
		remove_filter('get_edit_post_link', 'gutenberg_revisions_link_to_editor');
		remove_filter('wp_prepare_revision_for_js', 'gutenberg_revisions_restore');

		remove_action('rest_api_init', 'gutenberg_register_rest_routes');
		remove_action('rest_api_init', 'gutenberg_add_taxonomy_visibility_field');
		remove_filter('rest_request_after_callbacks', 'gutenberg_filter_oembed_result');
		remove_filter('registered_post_type', 'gutenberg_register_post_prepare_functions');

		remove_action('do_meta_boxes', 'gutenberg_meta_box_save', 1000);
		remove_action('submitpost_box', 'gutenberg_intercept_meta_box_render');
		remove_action('submitpage_box', 'gutenberg_intercept_meta_box_render');
		remove_action('edit_page_form', 'gutenberg_intercept_meta_box_render');
		remove_action('edit_form_advanced', 'gutenberg_intercept_meta_box_render');
		remove_filter('redirect_post_location', 'gutenberg_meta_box_save_redirect');
		remove_filter('filter_gutenberg_meta_boxes', 'gutenberg_filter_meta_boxes');

		remove_action('admin_notices', 'gutenberg_build_files_notice');
		remove_filter('body_class', 'gutenberg_add_responsive_body_class');
		remove_filter('admin_url', 'gutenberg_modify_add_new_button_url'); // old
		remove_action('admin_enqueue_scripts', 'gutenberg_check_if_classic_needs_warning_about_blocks');
		remove_filter('register_post_type_args', 'gutenberg_filter_post_type_labels');

		remove_action('admin_init', 'gutenberg_add_edit_link_filters');
		remove_action('admin_print_scripts-edit.php', 'gutenberg_replace_default_add_new_button');
		remove_filter('redirect_post_location', 'gutenberg_redirect_to_classic_editor_when_saving_posts');
		remove_filter('display_post_states', 'gutenberg_add_gutenberg_post_state');
		remove_action('edit_form_top', 'gutenberg_remember_classic_editor_when_saving_posts');
	}
}
main/googlefonts.php000064400000013112151526423640010535 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('Hacking Attempt');
}

class GoogleFonts{

	// Plucks out the google font urls from the content
	static function get($content){

		preg_match_all('/<link.*href=(["\'])(.*fonts\.googleapis\.com\/css.*?)\1/m', $content, $font_rels);

		//We just need the index 2
		if(empty($font_rels[2])){
			return $content;
		}
		
		$fonts = array();
		
		for($i = 0; $i < count($font_rels[2]); $i++){
			if(empty($font_rels[2][$i])){
				continue;
			}
		
			$fonts[md5($font_rels[2][$i])] = $font_rels[2][$i];
		}
		
		if(empty($fonts)){
			return;
		}

		self::fetch($fonts);
	}

	// Reads the font css and saves it to /speedycache/fonts/font-name/
	static function fetch($fonts){
		
		$html = '<!DOCTYPE html>
<html>
<body>
<a href="https://speedycache.com">SpeedyCache</a>
</body>
</html>';
		

		foreach($fonts as $font_name => $url){
			$url = esc_url($url);

			if(substr($url, 0, 2) === '//'){
				$url = 'https:' . $url;
			}

			$response = wp_remote_get($url, array('user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'));
			
			if(is_wp_error($response) || !is_array($response)){
				continue;
			}
			
			$css = wp_remote_retrieve_body($response);
			
			if(is_wp_error($css) || empty($css)){
				continue;
			}
			
			if(!file_exists(speedycache_cache_path('fonts'))){
				@mkdir(speedycache_cache_path('fonts'));
			}
			
			if(!file_exists(speedycache_cache_path('fonts/index.html'))){
				file_put_contents(speedycache_cache_path('fonts/index.html'), $html);
			}

			if(!file_exists(speedycache_cache_path('fonts/').$font_name)){
				@mkdir(speedycache_cache_path('fonts/').$font_name);
			}
			
			if(!file_exists(speedycache_cache_path('fonts/').$font_name . '/index.html')){
				file_put_contents(speedycache_cache_path('fonts/').$font_name . '/index.html', $html);
			}

			preg_match_all('/url\((.*?)\)/m', $response['body'], $urls); // Get URL from the CSS we got

			if(empty($urls) || empty($urls[1])){
				continue;
			}
			
			foreach($urls[1] as $url){
				$file_name = basename($url);
				
				if(file_exists(speedycache_cache_path('fonts/') . $font_name . '/' . $file_name)){
					continue;
				}

				if(strpos($url, 'display=swap') === FALSE){
					$url_to_hit = add_query_arg(array('display' => 'swap'), $url);
				}

				$response = wp_remote_get($url_to_hit);

				if(is_wp_error($response) || !is_array($response)){
					continue;
				}
				
				$font = wp_remote_retrieve_body($response);

				if(is_wp_error($font) || empty($font)){
					continue;
				}

				file_put_contents(speedycache_cache_path('fonts/').$font_name.'/'.$file_name, $font); // Creating the font file
				$css = str_replace($url, SPEEDYCACHE_CACHE_URL .'/'. SPEEDYCACHE_SERVER_HOST . '/fonts/'. $font_name .'/'. $file_name, $css);
			}

			if(file_exists(speedycache_cache_path('fonts/').$font_name.'/'.$font_name . '.css')){
				return;
			}

			//If we need to add swap then either we failed to add display=swap to the url or it didnt return what we expected.
			if(strpos($css, 'swap') === FALSE){
				$css = preg_replace('/(^@font-face\s{)/m', "$1\n  font-display: swap;", $css);
			}
			
			file_put_contents(speedycache_cache_path('fonts/').$font_name.'/'.$font_name . '.css', $css);
		}
	}

	// Replaces font url to the local font url
	static function replace($content){
		
		$cache_dir = speedycache_cache_path();
		
		if(!is_dir($cache_dir . '/fonts')){
			@mkdir($cache_dir . '/fonts', 0755, true);
		}

		$fonts = array_diff(@scandir($cache_dir . 'fonts'), array('..', '.'));
		
		if(empty($fonts)){
			return $content;
		}

		// To remove any preload or dns-fetch or preconnect for google fonts
		preg_match_all('/<link(?:[^>]+)?href=(["\'])([^>]*?fonts\.(gstatic|googleapis)\.com.*?)\1.*?>/i', $content, $google_links, PREG_SET_ORDER);
			
		if(!empty($google_links)){
			foreach($google_links as $google_link){

				preg_match('/rel=(["\'])(.*?(preload|preconnect|dns-fetch).*?)\1/i', $google_link[2], $removeable_link);

				if(!empty($removeable_link)){
					$content = str_replace($google, '', $html);
				}
			}
		}
		
		/**
		  * Our Font css name is in md5(created from the font URL) and we dont have URL in this function to get
		  * all the google fonts url to replace the fonts .
		*/
		preg_match_all('/<link.*href=(["\'])(.*fonts\.googleapis\.com\/css.*?)\1/m', $content, $font_rels);
		
		if(empty($font_rels[2])){
			return $content;
		}
		
		foreach($font_rels[2] as $url){
			foreach($fonts as $font){

				if(in_array($font, array('.', '..'))){
					continue;
				}
				
				if(!file_exists($cache_dir . 'fonts/' . $font . '/' . $font . '.css')){
					continue;
				}
				
				$css_url = SPEEDYCACHE_CACHE_URL .'/'. SPEEDYCACHE_SERVER_HOST . '/fonts/' . $font . '/' . $font . '.css';
				
				if(md5($url) === $font){
					$content = preg_replace('/<link(.*)href=(["\'])(.*fonts\.googleapis\.com\/css.*?)\2/m', '<link$1 href="'.$css_url .'" ', $content);
				}
			}
		}
		
		return $content;
	}
	
	static function add_swap($content){	
		$content = str_replace('&#038;display=swap', '', $content);
		$content = str_replace('&display=swap', '', $content);

		// Add font-display=swap as a querty parameter to Google fonts
		$content = str_replace('googleapis.com/css?family', 'googleapis.com/css?display=swap&family', $content);
		
		return $content;
	}

}
main/commoncss.php000064400000007154151526423640010221 0ustar00<?php 

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('Hacking Attempt!');
}

class CommonCss{
	
	static function get_endpoint($is_unusedcss = false){
		global $speedycache;

		$endpoints = get_transient('speedycache_ccss_endpoint');

		$target_file = empty($is_unusedcss) ? 'index.php' : 'ucss.php';

		$mirror = 'https://s4.softaculous.com/a/speedycache/critical-css/' . $target_file;		
		$license = strpos($speedycache->license['license'], 'SPDFY') !== 0 ? '' : $speedycache->license['license'];

		if(empty($endpoints)){
			$res = wp_remote_get(SPEEDYCACHE_API.'license.php?license='.$license.'&url='.rawurlencode(site_url()));

			// Did we get a response ?
			if(!is_array($res)){
				return $mirror;
			}
			
			if(empty($res['body'])){
				return $mirror;
			}

			$body = json_decode($res['body'], true);

			if(empty($body['fast_mirrors'])){
				return $mirror;
			}
			
			$endpoints = $body['fast_mirrors'];
			
			if(empty($endpoints) || !is_array($endpoints)){
				return $mirror;
			}
		}
		
		$index = floor(rand(0, count($endpoints) - 1));

		if(empty($endpoints[$index])){
			return $mirror;
		}

		set_transient('speedycache_ccss_endpoint', $endpoints, 180);

		$mirror = str_replace('a/softaculous', 'a/speedycache/critical-css/'.$target_file, $endpoints[$index]);
		
		return $mirror;
		
	}
	
	static function schedule($schedule_name, $urls){

		$scheduled = self::get_schedule(array($schedule_name));
		$time = time();
		
		if(!empty($scheduled) && isset(end($scheduled)['time'])){
			// getting the last index to get the last scheduled event
			$time = end($scheduled)['time'] + 10;
		}
		
		$final_schd_time = $time;
	
		if(!wp_next_scheduled($schedule_name, array('urls' => $urls))){
			wp_schedule_single_event($final_schd_time, $schedule_name, array('urls' => $urls));
		}
	}
	
	// Returns an array of cron event "speedycache_unused_css"
	static function get_schedule($event_name){
		$cron = _get_cron_array();
		
		if(empty($cron)){
			return false;
		}
		
		$scheduled = array();
		
		foreach($cron as $key => $crn){
			foreach($crn as $e_key => $event){
				if(!in_array($e_key, $event_name)){
					continue;
				}

				$args = [];

				foreach($event as $evt){
					if(!empty($evt['args'][0])){
						$args = $evt['args'][0];
					}
				}
				
				array_push($scheduled, array('name' => get_the_title($args), 'time' => $key));
			}
		}
		
		return $scheduled;
	}
	
	// Adds the Critical CSS to the cache file
	static function update_cached($file, $css){
		global $speedycache;

		if(!file_exists($file)){
			return;
		}

		$content = file_get_contents($file);
		
		if(empty($content)){
			return;
		}
		
		$content = static::update_content($content, $css);

		// Updates the .html.gz file
		if(!empty($speedycache->options['gzip'])){
			self::update_gzip($file, $content);
		}
		
		// Updates the .html file
		file_put_contents($file, $content);
	}

	static function update_gzip($file, $content){
		
		$gz_file = str_replace('.html', '.html.gz', $file);
		
		if(file_exists($gz_file)){
			unlink($gz_file);
		}
		
		$content = gzencode($content, 6);
		
		if(!empty($content)){
			file_put_contents($gz_file, $content);
		}
	}
	
	static function log($log_name, $message, $url = '-'){
		$ccss_logs = get_option($log_name, []);
		
		if(count($ccss_logs) > 10){
			array_shift($ccss_logs);
		}
		
		$ccss_logs[$url] = array('time' => date('h:i:s'), 'message' => $message);
		update_option($log_name, $ccss_logs);
	}
	
	
}main/youtube.html000064400000004451151526423640010066 0ustar00<html>
<head>
	<style type="text/css">
body{background-color:#000;color:#fff;font:12px Roboto,Arial,sans-serif;height:100%;margin:0;overflow:hidden;padding:0;position:absolute;width:100%}
.y{background-position:center center;background-repeat:no-repeat;background-size:cover;height:100%;position:absolute;width:100%}
.yb{position:absolute;cursor:pointer;width:90px;height:60px;background-color:#333;box-shadow:0 0 30px rgba(0,0,0,0.6);z-index:1;opacity:.8;border-radius:6px}
.yb:before{content:"";border-style:solid;border-width:15px 0 15px 26px;border-color:transparent transparent transparent #fff}
.yb, .yb:before{position:absolute;top:50%;left:50%;transform:translate3d(-50%,-50%,0)}
.yb:hover{background-color:#ff0000;}
iframe{position:absolute;height:100%;width:100%;top:0;left:0;}
	</style>
	<script type="text/javascript">
var i=location.hash.match(/\#([^\?]+)/);
function img(){
	var q = window.innerWidth < 321 ? "mqdefault" : (window.innerWidth > 320 && window.innerWidth < 481 ? "hqdefault" : (window.innerWidth > 480 && window.innerWidth < 750 ? "sddefault" : "maxresdefault"));
	var img = document.createElement("IMG");
	img.setAttribute( "src", 'https://i.ytimg.com/vi/' + i[1] + '/' + q + '.webp');
	img.addEventListener('load', function(e){
		if(e.target.width == 120 && e.target.height == 90 && window.innerWidth > 320){
			e.target.setAttribute( 'src', 'https://i.ytimg.com/vi/' + i[1] + '/' + "hqdefault" + '.jpg');
		}
		document.getElementById("d").style['background-image'] = 'url(' + e.target.src + ')';
	});
	
	
	document.getElementById('d').addEventListener('click', function(){
		var start = window.location.hash.match(/[^a-zA-Z\d\s:](start\=\d+)/i);
		var hash = ["rel=0", "showinfo=0", "autoplay=1"];
		var ifrm = document.createElement("iframe");
		if(start){hash.push(start[1]);}
		ifrm.setAttribute("frameborder", "0");
		ifrm.setAttribute("allowfullscreen", "");
		ifrm.setAttribute("allow", "autoplay");
		ifrm.setAttribute( "src", "https://www.youtube.com/embed/"+ i[1] +"?" + hash.join("&"));
		this.innerHTML = "";
		this.appendChild(ifrm);
	});
};

window.addEventListener('resize', function(){img();});
window.addEventListener('load', function(){img();});


	</script>
</head>
<body>
	<div id="d" class="y">
		<div class="yb"></div>
	</div>
</body>
</html>main/cli.php000064400000003202151526423640006755 0ustar00<?php
/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

if(!defined('ABSPATH')){
    exit;
}

if(!defined('WP_CLI')){
    return;
}

class speedycache_cli extends \WP_CLI_Command{


	/**
	  * Purges/Cleares cache or minified files
	  * ## OPTIONS
	  * <type>
	  * : Purges cache or minified
	  * ---
	  * options:
	  *  - cache
	  *  - and minified
	  *
	  * ## EXAMPLES
	  * # Purge Cache
	  * $ wp speedycache purge cache
	  *
	  * # Purge cache and minfied
	  * $ wp speedycache purge cache and minified
	*/
	public function purge($args, $args_assoc){
		global $speedycache;

		if(!isset($speedycache)){
			WP_CLI::error('speedycache has not been defined!');
		}

		if(!function_exists('speedycache_delete_cache')){
			WP_CLI::error('speedycache_delete_cache() does not exist!');
		}

		if(empty($args[0]) || $args[0] !== 'cache'){
			self::wrong_usage();
		}
		
		if(empty($args[1]) || empty($args[2])){
			$this->delete_cache();
			return;
		}
		
		if($args[1] == 'and' && $args[2] == 'minified'){
			$this->delete_cache(true);
			return;
		}
	
		self::wrong_usage();
	}
	
	private function delete_cache($minified_too = false){
		if(function_exists('speedycache_delete_cache')){
			WP_CLI::error('Somethinng Went Wrong: Unable to delete cache');
		}

		WP_CLI::line('Clearing the ALL cache...');
		
		if(defined('SPEEDYCACHE_VERSION') && version_compare(SPEEDYCACHE_VERSION, '1.2.0', '>=')){
			$delete['minified'] = $minified_too;
			\SpeedyCache\Delete::run($delete);
		} else {
			speedycache_delete_cache($minified_too);
		}

		WP_CLI::success('The cache has been cleared!');
	}
}

WP_CLI::add_command('speedycache', 'speedycache_cli');main/admin.php000064400000045724151526423640007315 0ustar00<?php

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT!');
}

// Show menu with error if speedy cache is installed but is older than 1.1.0
// as after that we dont short circuit the free version
if(!defined('SPEEDYCACHE_VERSION') || version_compare(SPEEDYCACHE_VERSION, '1.1.1') < 0){
	add_action('admin_menu', 'speedycachepro_add_menu');
	return; // Return else going forward will break things.
}

add_action('speedycache_license_tmpl', '\SpeedyCache\SettingsPage::license_tab');
add_action('speedycache_db_tmpl', '\SpeedyCache\SettingsPage::db_tab');
add_action('speedycache_pro_logs_tmpl', '\SpeedyCache\SettingsPage::logs');
add_action('speedycache_pro_stats_tmpl', '\SpeedyCache\SettingsPage::stats');
add_action('speedycache_image_optm_tmpl', '\SpeedyCache\SettingsPage::image_optm');
add_action('speedycache_bloat_tmpl', '\SpeedyCache\SettingsPage::bloat_tab');
add_action('speedycache_object_cache_tmpl', '\SpeedyCache\SettingsPage::object_tab');

include_once SPEEDYCACHE_PRO_DIR . '/main/premium.php';

if(defined('SPEEDYCACHE_PRO') && file_exists(SPEEDYCACHE_PRO_DIR . '/main/image.php')){
	\SpeedyCache\Image::init();
	add_action('wp_ajax_speedycache_download_cwebp', '\SpeedyCache\Image::download_cwebp');
	add_action('add_meta_boxes_attachment', 'speedycache_pro_media_metabox');
}

add_action('admin_init', 'speedycache_pro_schedule_test_event');
add_action('admin_notices', 'speedycache_pro_notices');
add_filter('softaculous_expired_licenses', 'speedycache_pro_plugins_expired');
add_action('admin_enqueue_scripts', 'speedycache_pro_enqueue_admin_scripts');

// ----- AJAX ACTIONS ----- //
add_action('wp_ajax_speedycache_statics_ajax_request', 'speedycache_pro_img_stats');
add_action('wp_ajax_speedycache_optimize_image_ajax_request', 'speedycache_pro_optimize_image');
add_action('wp_ajax_speedycache_update_image_settings', 'speedycache_pro_save_img_settings');
add_action('wp_ajax_speedycache_update_image_list_ajax_request', 'speedycache_pro_list_imgs');
add_action('wp_ajax_speedycache_revert_image_ajax_request', 'speedycache_pro_revert_img');
add_action('wp_ajax_speedycache_img_revert_all', 'speedycache_pro_revert_all_imgs');
add_action('wp_ajax_speedycache_verify_license', 'speedycache_pro_verify_license');
add_action('wp_ajax_speedycache_copy_test_settings', 'speedycache_pro_copy_test_settings');
add_action('wp_ajax_speedycache_dismiss_test_notice','speedycache_pro_dismiss_test_notice');
add_action('wp_ajax_speedycache_pro_dismiss_expired_licenses', 'speedycache_pro_dismiss_expired_licenses');

function speedycachepro_add_menu(){
	add_menu_page('SpeedyCache Settings', 'SpeedyCache', 'activate_plugins', 'speedycache', 'speedycachepro_menu_page');
}

function speedycachepro_menu_page(){
	echo '<div style="color: #333;padding: 50px;text-align: center;">
		<h1 style="font-size: 2em;margin-bottom: 10px;">Update Speedycache to Latest Version!</h>
		<p style=" font-size: 16px;margin-bottom: 20px; font-weight:400;">SpeedyCache Pro depends on the free version of SpeedyCache, so you need to update the free version to use SpeedyCache without any issue.</p>
		<a href="'.admin_url('plugin-install.php?s=speedycache&tab=search').'" style="text-decoration: none;font-size:16px;">Install Now</a>
	</div>';
}

function speedycache_pro_img_stats(){
	check_ajax_referer('speedycache_ajax_nonce', 'security');

	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}
	
	if(!class_exists('\SpeedyCache\Image')){
		wp_send_json_error(__('The file required to Process Image optimization is not present', 'speedycache'));
	}

	$res = \SpeedyCache\Image::statics_data();
	wp_send_json($res);
}

function speedycache_pro_optimize_image(){
	check_ajax_referer('speedycache_ajax_nonce', 'security');

	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}
	
	if(!class_exists('\SpeedyCache\Image')){
		wp_send_json_error(__('The file required to Process Image optimization is not present', 'speedycache'));
	}
	
	$id = null;
	if(!empty($_POST['img_id'])){
		$id = (int) sanitize_text_field(wp_unslash($_POST['img_id']));
		
		if(empty($id)){
			wp_send_json_error('Empty Image ID');
		}
	}
	

	$res = \SpeedyCache\Image::optimize_single($id);
	$res[1] = isset($res[1]) ? $res[1] : '';
	$res[2] = isset($res[2]) ? $res[2] : '';
	$res[3] = isset($res[3]) ? $res[3] : '';
	
	$response = array(
		'message' => $res[0],
		'success' => $res[1],
		'id' => $res[2],
		'percentage' => $res[3],
	);
	
	wp_send_json($response);
}

function speedycache_pro_save_img_settings(){
	check_ajax_referer('speedycache_ajax_nonce', 'security');
	
	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}
	
	global $speedycache;

	$settings = speedycache_optpost('settings');
	
	foreach($settings as $key => $setting){		
		$new_key = str_replace('img_', '', $key);
		
		$settings[$new_key] = $setting;
		unset($settings[$key]);
	}

	$speedycache->image['settings'] = $settings;
	
	if(update_option('speedycache_img', $speedycache->image['settings'])){
		wp_send_json_success();
	}
	
	wp_send_json_error();
}

function speedycache_pro_list_imgs(){
	check_ajax_referer('speedycache_ajax_nonce', 'security');
	
	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}
	
	$query_images_args = array();
	$query_images_args['offset'] = intval(speedycache_optget('page')) * intval(speedycache_optget('per_page'));
	$query_images_args['order'] = 'DESC';
	$query_images_args['orderby'] = 'ID';
	$query_images_args['post_type'] = 'attachment';
	$query_images_args['post_mime_type'] = array('image/jpeg', 'image/png', 'image/gif');
	$query_images_args['post_status'] = 'inherit';
	$query_images_args['posts_per_page'] = speedycache_optget('per_page');
	$query_images_args['meta_query'] = array(
								array(
									'key' => 'speedycache_optimisation',
									'compare' => 'EXISTS'
									)
								);

	$query_images_args['s'] = speedycache_optget('search');

	if(!empty($_GET['filter'])){
		if(speedycache_optget('filter') == 'error_code'){
			
			$filter = array(
				'key' => 'speedycache_optimisation',
				'value' => base64_encode('"error_code"'),
				'compare' => 'LIKE'
			);

			$filter_second = array(
				'key' => 'speedycache_optimisation',
				'compare' => 'NOT LIKE'
			);

			array_push($query_images_args['meta_query'], $filter);
			array_push($query_images_args['meta_query'], $filter_second);
		}
	}

	$result = array(
		'content' => \SpeedyCache\Image::list_content($query_images_args),
		'result_count' => \SpeedyCache\Image::count_query($query_images_args)
	);

	wp_send_json($result);
}

function speedycache_pro_revert_img(){
	check_ajax_referer('speedycache_ajax_nonce', 'security');

	if(!current_user_can('manage_options')){
		wp_die('Must Be admin');
	}

	global $speedycache;

	if(!empty($_GET['id'])){
		$speedycache->image['id'] = (int) speedycache_optget('id');
	}

	wp_send_json(\SpeedyCache\Image::revert());
}

function speedycache_pro_revert_all_imgs(){
	check_ajax_referer('speedycache_ajax_nonce', 'security');

	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}
	
	\SpeedyCache\Image::revert_all();
}


function speedycache_pro_verify_license(){

	if(!wp_verify_nonce($_GET['security'], 'speedycache_license')){
		wp_send_json_error(__('Security Check Failed', 'speedycache'));
	}
	
	if(!current_user_can('manage_options')){
		wp_send_json_error(__('You do not have required permission.', 'speedycache'));
	}
	
	global $speedycache;

	$license = sanitize_key($_GET['license']);
	
	if(empty($license)){
		wp_send_json_error(__('The license key was not submitted', 'speedycache'));
	}
	
	$resp = wp_remote_get(SPEEDYCACHE_API.'license.php?license='.$license.'&url='.rawurlencode(site_url()), array('timeout' => 30));
	
	if(!is_array($resp)){
		wp_send_json_error(__('The response was malformed<br>'.var_export($resp, true), 'speedycache'));
	}

	$json = json_decode($resp['body'], true);

	// Save the License
	if(empty($json['license'])){
		wp_send_json_error(__('The license key is invalid', 'speedycache'));
	}
	
	$speedycache->license = $json;
	update_option('speedycache_license', $json, false);
	
	wp_send_json_success();
}

function speedycache_pro_enqueue_admin_scripts(){
	wp_enqueue_style('speedycache-admin-pro', SPEEDYCACHE_PRO_URL . '/assets/css/admin.css', [], SPEEDYCACHE_PRO_VERSION);
	wp_enqueue_script('speedycache-admin-pro', SPEEDYCACHE_PRO_URL . '/assets/js/admin.js', [], SPEEDYCACHE_PRO_VERSION);
	wp_localize_script('speedycache-admin-pro', 'speedycache_pro_ajax', [
		'url' => admin_url('admin-ajax.php'),
		'nonce' => wp_create_nonce('speedycache_pro_ajax_nonce'),
		'premium' => defined('SPEEDYCACHE_PRO'),
	]);
}

// Sets speedycache settings to our predefined defaults.
function speedycache_pro_copy_test_settings(){
	check_ajax_referer('speedycache_pro_ajax_nonce', 'security');

	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}

	global $speedycache;

	$test_settings = ['minify_html' => true, 'delay_js' => true, 'render_blocking' => true, 'minify_js' => true, 'critical_images' => true, 'lazy_load' => true, 'delay_js_mode' => 'selected', 'delay_js_scripts' => ['fbevents.js', 'google-analytics.com', 'adsbygoogle.js', 'googletagmanager.com', 'fbq(', "ga( '", "ga('", '/gtm.js', '/gtag/js', 'gtag(', '/gtm-', '/gtm.']];
	
	$speedycache->options = array_merge($speedycache->options, $test_settings);
	
	update_option('speedycache_options', $speedycache->options);
	delete_option('speedycache_test_results');
	
	wp_send_json_success(__('Settings applied successfully.', 'speedycache-pro'));
}	

function speedycache_pro_dismiss_test_notice(){
	check_ajax_referer('speedycache_pro_ajax_nonce', 'security');

	if(!current_user_can('manage_options')){
		wp_die('Must be admin');
	}
	
	delete_option('speedycache_test_results');
}

function speedycache_pro_schedule_test_event() {
	$install_time = get_option('speedycache_free_installed', 0);
	$event_executed = get_option('speedycache_test_executed', 0);
	if($install_time && !$event_executed){
		if(($install_time + WEEK_IN_SECONDS) < time()){
			$event_time = time() + DAY_IN_SECONDS;
		} else {
			$event_time = $install_time + WEEK_IN_SECONDS;
		}

		if(!wp_next_scheduled('speedycache_test_event')){
			wp_schedule_single_event($event_time, 'speedycache_test_event');
		}
	}
}

function speedycache_pro_test_results_notice() {
	
	if(!current_user_can('manage_options')){
		return;
	}

	$current_screen = get_current_screen();
	if(!isset($current_screen->id) || strpos($current_screen->id, 'speedycache') === false){
		return;
	}

	$test_results = get_option('speedycache_test_results');

	if(empty($test_results)){
		return;
	}
	
	$old_score = $test_results['old_score'];
	$new_score = $test_results['new_score'];

	$stroke_old = !empty($old_score) ? 100 - $old_score : 0;
	$stroke_new = !empty($new_score) ? 100 - $new_score : 0;

	$old_color = speedycache_pro_get_score_color($old_score);
	$new_color = speedycache_pro_get_score_color($new_score);

	echo '<div class="notice notice-success is-dismissible speedycache-test-notice">
	<p class="speedycache-notice-title"><strong>'.esc_html__('Speed Test Results:', 'speedycache-pro').'</strong></p>

	<div class="speedycache-test-chart-wrap">
		<!-- Before Optimization -->
		<div class="speedycache-donut-wrap speedycache-before-optimization">
			<svg width="150" height="150" viewBox="0 0 40 40" class="speedycache-donut">
				<circle class="donut-hole" cx="20" cy="20" r="15.91549430918954" fill="'.esc_attr($old_color[1]).'"></circle>
				<circle class="speedycache-donut-segment" cx="20" cy="20" r="15.91549430918954" fill="transparent" stroke-width="3" stroke-linecap="round" stroke-dasharray="'.esc_attr($old_score).' '.esc_attr($stroke_old).'" stroke-dashoffset="25" style="stroke:'.esc_attr($old_color[0]).';"></circle>
				<g class="speedycache-test-donut-text">
					<text y="55%" transform="translate(0, 2)">
						<tspan x="50%" text-anchor="middle" class="speedycache-donut-percent" style="fill:'.esc_attr($old_color[2]).';">'.esc_attr($old_score).'</tspan>
					</text>
				</g>
			</svg>
			<p class="speedycache-donut-label">'.esc_html__('Before Optimization', 'speedycache-pro').'</p>
		</div>

		<!-- After Optimization -->
		<div class="speedycache-donut-wrap speedycache-after-optimization">
			<svg width="150" height="150" viewBox="0 0 40 40" class="speedycache-donut">
				<circle class="donut-hole" cx="20" cy="20" r="15.91549430918954" fill="'.esc_attr($new_color[1]).'"></circle>
				<circle class="speedycache-donut-segment" cx="20" cy="20" r="15.91549430918954" fill="transparent" stroke-width="3" stroke-linecap="round" stroke-dasharray="'.esc_attr($new_score).' '.esc_attr($stroke_new).'" stroke-dashoffset="25" style="stroke:'.esc_attr($new_color[0]).';"></circle>
				<g class="speedycache-test-donut-text">
					<text y="55%" transform="translate(0, 2)">
						<tspan x="50%" text-anchor="middle" class="speedycache-donut-percent" style="fill:'.esc_attr($new_color[2]).';">'.esc_attr($new_score).'</tspan>
					</text>
				</g>
			</svg>
			<p class="speedycache-donut-label">'.esc_html__('After Optimization', 'speedycache-pro').'</p>
		</div>
	</div>

	<div class="speedycache-test-action">
		'.esc_html__('Want to enable the SpeedyCache settings used for this test?', 'speedycache-pro').' 
		<button class="speedycache-enable-btn speedycache-copy-test-settings">'.esc_html__('Enable Now', 'speedycache-pro').'</button>
	</div>

	<button type="button" class="notice-dismiss speedycache-custom-dismiss">
		<span class="screen-reader-text">'.esc_html__('Dismiss this notice.', 'speedycache-pro').'</span>
	</button>
	</div>';
}

function speedycache_pro_plugins_expired($plugins){
	global $speedycache;
	
	if(!empty($speedycache->license) && empty($speedycache->license['active'])){
		$plugins[] = 'SpeedyCache';
	}

	return $plugins;
}

function speedycache_pro_notices(){
	global $speedycache;
	
	if(!current_user_can('activate_plugins')){
		return;
	}

	$current_screen = get_current_screen();
	
	// Test result notice
	if(isset($current_screen->id) && strpos($current_screen->id, 'speedycache') !== false){
		speedycache_pro_test_results_notice();
	}
	
	// If the license is active then we do not need to show any notice.
	if(!empty($speedycache->license) && empty($speedycache->license['active'])){
		speedycache_pro_expiry_notice();
	}
	
}

function speedycache_pro_expiry_notice(){
	global $speedycache;

	// The combined notice for all Softaculous plugin to show that the license has expired
	$dismissed_at = get_option('softaculous_expired_licenses', 0);
	$expired_plugins = apply_filters('softaculous_expired_licenses', []);
	if(
		!empty($expired_plugins) && 
		is_array($expired_plugins) && 
		!defined('SOFTACULOUS_EXPIRY_LICENSES') && 
		(empty($dismissed_at) || ($dismissed_at + WEEK_IN_SECONDS) < time())
	){

		define('SOFTACULOUS_EXPIRY_LICENSES', true); // To make sure other plugins don't return a Notice
		echo '<div class="notice notice-error is-dismissible" id="speedycache-pro-expiry-notice">
				<p>'.sprintf(__('Your %1$s plugin license has %2$sExpired%3$s. Please renew your license for uninterrupted updates and support.', 'speedycache-pro'), 
				esc_html(implode(', ', $expired_plugins)),
				'<font style="color:red;"><b>',
				'</b></font>'
				). '</p>
			</div>';

		wp_register_script('speedycache-pro-expiry-notice', '', array('jquery'), SPEEDYCACHE_PRO_VERSION, true );
		wp_enqueue_script('speedycache-pro-expiry-notice');
		wp_add_inline_script('speedycache-pro-expiry-notice', '
		jQuery(document).ready(function(){
			jQuery("#speedycache-pro-expiry-notice").on("click", ".notice-dismiss", function(e){
				e.preventDefault();
				let target = jQuery(e.target);

				let jEle = target.closest("#speedycache-pro-expiry-notice");
				jEle.slideUp();

				jQuery.post("'.admin_url('admin-ajax.php').'", {
					security : "'.wp_create_nonce('speedycache_expiry_notice').'",
					action: "speedycache_pro_dismiss_expired_licenses",
				}, function(res){
					if(!res["success"]){
						alert(res["data"]);
					}
				}).fail(function(data){
					alert("There seems to be some issue dismissing this alert");
				});
			});
		})');
	}
}

function speedycache_pro_get_score_color($score) {

	$score_color_map = [
		0   => ['#c00', '#c003', '#c00'], // Red
		50  => ['#fa3', '#ffa50036', '#fa3'], // Orange
		90  => ['#0c6', '#00cc663b', '#080'], // Green
	];

	if ($score >= 0 && $score < 50) {
		return $score_color_map[0];
	} elseif ($score >= 50 && $score < 90) {
		return $score_color_map[50];
	} else {
		return $score_color_map[90];
	}
}

function speedycache_pro_media_metabox($post){
	
	if(empty($post)){
		return;
	}
	
	$allowed_img_types = [
		'image/png',
		'image/jpg',
		'image/jpeg',
	];
	
	if(!in_array($post->post_mime_type, $allowed_img_types)){
		return;
	}

	add_meta_box( 
		'speedycache-optm-img',
		__('SpeedyCache Image Optimization', 'speedycache-pro'),
		'speedycache_pro_img_optm_metabox',
		'attachment',
		'side',
		'default'
		);
}

function speedycache_pro_img_optm_metabox($post){
	
	if(empty($post)){
		echo 'No Post data';
		return;
	}
	
	$optimized_data = get_post_meta($post->ID, 'speedycache_optimisation', true);
	
	if(!empty($optimized_data)){
		$optimized_data = base64_decode($optimized_data);
		$optimized_data = json_decode($optimized_data, true);
		
		if(!empty($optimized_data) && !empty($optimized_data[0]) && !empty($optimized_data[0]['file']) && file_exists($optimized_data[0]['file'])){
			esc_html_e('Image has already been optimized', 'speedycache-pro');
			return;
		}
	}

	echo '<button class="button" id="speedycache-optm-attachment" data-id="'.esc_attr($post->ID).'">'.esc_html__('Optimize this Image', 'speedycache-pro').'</button>';
	
	wp_register_script('speedycache-img-optm-meta-box', '', array('jquery'), '', true);
	wp_enqueue_script('speedycache-img-optm-meta-box');
	wp_add_inline_script('speedycache-img-optm-meta-box', 'jQuery(document).ready(function(){
		jQuery("#speedycache-optm-attachment").on("click", function(e){
			e.preventDefault();
			
			let attachment_id = jQuery(e.target).data("id"),
			nonce = "'.wp_create_nonce('speedycache_ajax_nonce').'";
			
			jQuery.ajax({
				url : "'.esc_url(admin_url('admin-ajax.php')).'",
				method : "POST",
				data : {
					"action":"speedycache_optimize_image_ajax_request",
					"security": nonce,
					"img_id": attachment_id,
				},
				success: function(res){
					if(res.success){
						window.location.reload();
					}
				}
			});
			
		})
	})');
}

function speedycache_pro_dismiss_expired_licenses(){
	check_admin_referer('speedycache_expiry_notice', 'security');

	if(!current_user_can('activate_plugins')){
		wp_send_json_error(__('You do not have required access to do this action', 'speedycache-pro'));
	}

	update_option('softaculous_expired_licenses', time());
	wp_send_json_success();
}main/metaboxpro.php000064400000003743151526423640010400 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('Hacking Attempt');
}

class MetaboxPro{

	static function html($content, $post_id){
		global $speedycache;
		
		if(empty($speedycache->options['critical_css'])){
			return '';
		}

		$post_meta = get_post_meta($post_id, 'speedycache_post_meta', true);

		$html = '<div class="speedycache-option-wrap">
	<div class="speedycache-option-info">
		<span class="speedycache-option-name">'.esc_html__('Disable CriticalCSS', 'speedycache').'</span>
	</div>
	<label for="speedycache-disable-critical-css" class="speedycache-custom-checkbox">
		<input type="checkbox" id="speedycache-disable-critical-css" name="speedycache_disable_critical_css" '. (!empty($post_meta['disable_critical_css']) ? ' checked' : ''). '/>
		<div class="speedycache-input-slider"></div>
	</label>
</div>

<h3>Critical CSS</h3>
<p>Create Crtical CSS for this page</p>
<button class="button" id="speedycache-generate-specific-cache">Generate CriticalCSS</button>
';

		return $html;

	}

	static function enqueue_scripts(){
		global $speedycache, $post;

		if(empty($speedycache->options['critical_css'])){
			return;
		}

		wp_enqueue_script('speedycache_metabox', SPEEDYCACHE_PRO_URL . '/assets/js/metabox.js', array('jquery'), SPEEDYCACHE_PRO_VERSION, true);
		
		wp_localize_script('speedycache_metabox', 'speedycache_metabox', array(
			'nonce' => wp_create_nonce('speedycache_nonce'),
			'post_id' => !empty($post->ID) ? $post->ID : '',
			'url' => admin_url('admin-ajax.php')
		));
	}
	
	// Filter to sets options to be saved for post meta
	static function options($options){
		global $speedycache;
		
		if(empty($options)){
			$options = [];
		}
		
		if(!is_array($options)){
			$options = [$options]; 
		}
		
		if(!empty($speedycache->options['critical_css'])){
			$options[] = 'disable_critical_css';
		}
		
		return $options;
	}
}
main/db.php000064400000003766151526423640006612 0ustar00<?php
/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class DB{

	static function clean($type){
		global $wpdb;

		if($type === 'transient_options'){
			$wpdb->query("DELETE FROM `$wpdb->options` WHERE option_name LIKE '%\_transient\_%' ;");
			wp_send_json(array('success' => true));
		}
		
		if($type === 'expired_transient'){
			$wpdb->query("DELETE FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time());
			
			wp_send_json(array('success' => true));
		}
		
		if($type === 'trackback_pingback'){
			$wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback' ;");
			wp_send_json(array('success' => true));
		}
		
		if($type === 'trashed_spam_comments'){
			$wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_approved = 'spam' OR comment_approved = 'trash' ;");
			wp_send_json(array('success' => true));
		}
		
		if($type === 'trashed_contents'){
			$wpdb->query("DELETE FROM `$wpdb->posts` WHERE post_status = 'trash';");
			wp_send_json(array('success' => true));
		}
		
		if($type === 'post_revisions'){
			$wpdb->query("DELETE FROM `$wpdb->posts` WHERE post_type = 'revision';");
			wp_send_json(array('success' => true));
		}
		
		if($type === 'all_warnings'){
			$wpdb->query("DELETE FROM `$wpdb->posts` WHERE post_type = 'revision';");
			$wpdb->query("DELETE FROM `$wpdb->posts` WHERE post_status = 'trash';");
			$wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_approved = 'spam' OR comment_approved = 'trash' ;");
			$wpdb->query("DELETE FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback' ;");
			$wpdb->query("DELETE FROM `$wpdb->options` WHERE option_name LIKE '%\_transient\_%' ;");
			$wpdb->query("DELETE FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time());

			wp_send_json(array('success' => true));
		}
	}

}

main/renderblocking.php000064400000111221151526423640011177 0ustar00<?php

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class RenderBlocking {

	static function init($html){
		global $speedycache;
		
		$speedycache->render_blocking = array();
		$speedycache->render_blocking['except'] = '';
		$speedycache->render_blocking['tags'] = array();
		$speedycache->render_blocking['header_start_index'] = 0;
		$speedycache->render_blocking['js_tags_text'] = '';
		$speedycache->render_blocking['html'] = $html;
		
		self::set_header_start_index();
		self::set_tags();
		
		$speedycache->render_blocking['tags'] = self::reorder_tags($speedycache->render_blocking['tags']);
	}

	static function set_tags(){
		self::set_comments();
		self::set_js();
		self::set_css();
	}

	static function set_comments(){
		global $speedycache;
		
		$comment_tags = self::find_tags('<!--', '-->');

		self::set_except($comment_tags);

		foreach($comment_tags as $key => $value){
			if(preg_match("/\<\!--\s*\[if/i", $value['text'])){
				if(preg_match("/data-speedycache-render\=[\"\']false[\"\']/i", $value['text'])){
					continue;
				}

				array_push($speedycache->render_blocking['tags'], $value);
			}
		}
	}

	static function set_css(){
		global $speedycache;
		
		$style_tags = self::find_tags('<style', '</style>');

		foreach($style_tags as $key => $value){
			// <script>var xxx ={"id":"4", "html":"<style>\n\t\t\t.container{color:#CCCCCC;}\n\t\t<\/style>"};</script>
			if(!preg_match("/<\/script>/i", $value['text'])){
				array_push($speedycache->render_blocking['tags'], $value);
			}
		}

		$link_tags = self::find_tags('<link', '>');

		foreach($link_tags as $key => $value){
			if(preg_match("/href\s*\=/i", $value['text'])){
				if(preg_match("/rel\s*\=\s*[\'\"]\s*stylesheet\s*[\'\"]/i", $value['text'])){
					array_push($speedycache->render_blocking['tags'], $value);
				}
			}
		}
	}

	static function set_js(){
		global $speedycache;
		
		// Creating regex to exclude js from RenderBlocking
		if(!empty($speedycache->options['render_blocking_excludes'])){
			$exclude_script_list = array_map('preg_quote', $speedycache->options['render_blocking_excludes'], array_fill(0, count($speedycache->options['render_blocking_excludes']), '/'));
			$exclude_user_script = '/\b(?:' . implode('|', $exclude_script_list) . ')\b/';
		}
		
		$script_tag = self::find_tags('<script', '</script>');
		
		foreach($script_tag as $key => $value){
			
			if(self::exclude_scripts($value['text'])){
				continue;
			}
			
			// Excludes the user specified scripts
			if(!empty($exclude_user_script) && preg_match($exclude_user_script, $value['text'])){
				continue;
			}
			
			// Import map should always load at the same place as it is meant to be loaded before other scripts.
			if(preg_match("/importmap/i", $value['text'])){
			    continue;
			}

			//<script type='text/javascript' src='http://partner.googleadservices.com/gampad/google_service.js'></script>
			if(preg_match("/partner\.googleadservices\.com\/gampad\/google_service\.js/i", $value['text'])){
				continue;
			}

			// <script type='text/javascript'>
			// GS_googleAddAdSenseService("ca-pub-1059380037");
			// GS_googleEnableAllServices();
			// </script>
			if(preg_match("/<script[^\>]*>\s*GS_googleAddAdSenseService\([\"\'][^\"\']+[\"\']\)\;\s*GS_googleEnableAllServices\(\)\;\s*<\/script>/i", $value['text'])){
				continue;
			}

			// <script type='text/javascript'>
			// GA_googleAddSlot("ca-pub-1059380037", "viajablog-300-250");
			// </script>
			if(preg_match("/<script[^\>]*>\s*GA_googleAddSlot\([^\)]+\)\;\s*<\/script>/i", $value['text'])){
				continue;
			}

			// <script type='text/javascript'>
			// GA_googleFetchAds();
			// </script>
			if(preg_match("/<script[^\>]*>\s*GA_googleFetchAds\(\)\;\s*<\/script>/i", $value['text'])){
				continue;
			}

			// <script>
			//   (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
			//   (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
			//   m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
			//   })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

			//   ga('create', 'UA-9999-9', 'auto');
			//   ga('send', 'pageview');
			// </script>
			if(preg_match("/<script[^\>]*>\s*\(function\(i,s,o,g,r,a,m\)\{i\[\'GoogleAnalyticsObject\'\]/i", $value['text'])){
				if(preg_match("/ga\(\'send\',\s*\'pageview\'\)\;\s*<\/script>/i", $value['text'])){
					continue;
				}
			}

			// <script async src="https://www.googletagmanager.com/gtag/js?id=AW-123456789"></script>
			// <script>window.dataLayer=window.dataLayer||[];
			// function gtag(){
			// dataLayer.push(arguments);
			// }
			// gtag('js', new Date());
			// gtag('config', 'AW-123456789');</script>
			// <script type="text/javascript">
			// gtag('event', 'page_view', {
			// 'send_to': 'AW-123456789',
			// 'ecomm_pagetype': 'home'
			// });
			//</script>
			if(preg_match("/<script[^\>]+googletagmanager\.com\/gtag\/js[^\>]+>/i", $value['text'])){
				continue;
			}
			
			if(preg_match("/^<script>\s*window\.dataLayer\s*=\s*window\.dataLayer/i", $value['text']) && 
				preg_match("/gtag\([^\)]+\)\s*\;\s*<\/script>$/i", $value['text'])){
				continue;
			}

			/*
			<script id="bx24_form_inline" data-skip-moving="true">
				(function(w,d,u,b){w['Bitrix24FormObject']=b;w[b] = w[b] || function(){arguments[0].ref=u;
						(w[b].forms=w[b].forms||[]).push(arguments[0])};
						if(w[b]['forms']) return;
						var s=d.createElement('script');s.async=1;s.src=u+'?'+(1*new Date());
						var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);
				})(window,document,'https://speedycache.bitrix24.com/bitrix/js/crm/form_loader.js','b24form');

				b24form({"id":"1","lang":"en","sec":"yesxbh","type":"inline"});
			</script>
			*/
			if(preg_match("/data-skip-moving\=[\"\']true[\"\']/i", $value['text'])){
				continue;
			}

			if(preg_match('/amzn_assoc_placement/i', $value['text'])){
				// <script>amzn_assoc_placement="adunit0";
				// amzn_assoc_search_bar="false";
				// amzn_assoc_tracking_id="3d0f1f-20";
				// amzn_assoc_ad_mode="search";
				// amzn_assoc_ad_type="smart";
				// amzn_assoc_marketplace="amazon";
				// amzn_assoc_region="US";
				// amzn_assoc_title="";
				// amzn_assoc_default_search_phrase="Spray Paint ";
				// amzn_assoc_default_category="All";
				// amzn_assoc_linkid="949bfb847147d654e679d4876a8e2b77";</script>
				continue;
			}
			
			//<script type="text/javascript">document.write("<div data-role=\"amazonjs\" data-asin=\"1234567890\" data-locale=\"JP\" data-tmpl=\"\" data-img-size=\"\" class=\"asin_1234567890_JP_ amazonjs_item\"><div class=\"amazonjs_indicator\"><span class=\"amazonjs_indicator_img\"></span><a class=\"amazonjs_indicator_title\" href=\"https://www.amazon.co.jp/%E5%B8%8%E5%AF%BF/dp/1234567890?SubscriptionId=AKIAIQGSXT2U7QVCQGHA&tag=hiyokoweb06-22&linkCode=xm2&camp=2025&creative=165953&creativeASIN=4335787\">希望難民ご一行様 ピースボートと「承認の共同体」幻想 (光文社新書)</a><span class=\"amazonjs_indicator_footer\"></span></div></div>")</script>
			if(preg_match("/^<script[^\>]*>\s*document.write\([\"\']\s*<div/i", $value['text'])){
				if(preg_match("/\s*<\/div>[\"\']\)\s*<\/script>$/i", $value['text'])){
					if(preg_match("/amazonjs/i", $value['text'])){
						continue;
					}
				}
			}

			if(preg_match('/reklamstore/i', $value['text'])){
				if(preg_match("/reklamstore_region_id/i", $value['text'])){
					continue;
				}else if(preg_match("/reklamstore\.com\/reklamstore\.js/i", $value['text'])){
					continue;
				}
			}

			//<script>document.write ('<iframe id="g2324_1" src="http://site.com/index.php?display_gallery_iframe&amp;gal_id=2324_1&amp;gal_type=2&amp;gal_cap=OFF&amp;gal_page=false"></iframe>');</script>
			if(preg_match("/document\.write\s*\(/i", $value['text'])){
				if(preg_match("/<iframe/i", $value['text'])){
					continue;
				}
			}

			//Yandex.Metrika counter
			if(preg_match("/mc\.yandex\.ru\/metrika\/watch\.js/i", $value['text'])){
				if(preg_match("/yandex_metrika_callbacks/i", $value['text'])){
					continue;
				}
			}

			//<script type="text/javascript" src="https://seal.thawte.com/getthawteseal?host_name=www.site.co.za&amp;size=S&amp;lang=en"></script>
			if(preg_match("/seal\.thawte\.com/i", $value['text'])){
				continue;
			}
			
			//<script type= "text/javascript">var RecaptchaOptions = {custom_translations : { instructions_visual : "This is my text:" }};</script>
			if(preg_match("/var\s+RecaptchaOptions\s*=\s*\{/i", $value['text'])){
				continue;
			}

			/*
			<script src='https://www.google.com/recaptcha/api.js?render=12356o4hLx1PTv7yszALlb5F_M&#038;ver=3.0'></script>
			<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=88a7E&amp;hl=en"></script>
			*/
			if(preg_match("/google\.com\/recaptcha\/api/i", $value['text'])){
				continue;
			}

			// <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
			// new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
			// j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
			// 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
			// })(window,document,'script','dataLayer','GTM-5NRFSPW');</script>
			if(preg_match("/googletagmanager\.com\/gtm\.js/i", $value['text']) && preg_match("/parentNode\.insertBefore/i", $value['text'])){
				continue;
			}

			//<script src="https://gist.github.com/name/89964fb23055f8d45f12345befd4d024.js"></script>
			if(preg_match("/gist\.github\.com\//i", $value['text'])){
				continue;
			}

			//<script async="asnyc" type="text/javascript" src="https://a-ssl.ligatus.com/?ids=11111&t=js&s=1"></script>
			if(preg_match("/a-ssl\.ligatus\.com/i", $value['text'])){
				continue;
			}

			//<script type="text/javascript" src="https://sealserver.trustwave.com/seal.js?style=invert&code=89999"></script>
			if(preg_match("/sealserver\.trustwave\.com\/seal\.js/i", $value['text'])){
				continue;
			}

			//<script language="javascript" src="//inviocare.us13.list-manage.com/generate-js/?u=f3707cdf398370b05&fid=4301&show=10" type="text/javascript"></script>
			if(preg_match("/inviocare\.us13\.list\-manage\.com\/generate\-js/i", $value['text'])){
				continue;
			}

			//<script type="text/javascript" src="https://form.jotform.co/jsform/60138856"></script>
			if(preg_match("/jotform[^\/]+\/jsform\/\d+/i", $value['text'])){
				continue;
			}

			//<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/shell.js"></script>
			//<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
			if(preg_match("/js\.hsforms\.net\/forms\//i", $value['text'])){
				continue;
			}

			/*
			<script>hbspt.forms.create({
			portalId: 5102205,
			formId: "c11016e5-6a9a-4361-a358-a2ac92b8399e",
			shortcode: "wp"
			});</script>
			*/
			if(preg_match("/<script>\s*hbspt\.forms\.create\([^\)]+\)\;\s*<\/script>/i", $value['text'])){
				continue;
			}

			//<script type="application/json" class="wp-playlist-script">
			if(preg_match("/<script[^\>]+application\/json[^\>]+/i", $value['text'])){
				// if(preg_match("/<script[^\>]+wp-playlist-script[^\>]+/i", $value['text'])){
				// 	continue;
				// }

				continue;
			}

			//<script type='application/ld+json' class='yoast-schema-graph yoast-schema-graph--main'></script>
			if(preg_match("/<script[^\>]+application\/ld\+json[^\>]+>/i", $value['text'])){
				continue;
			}

			//<script id='tmpl-nf-field-input' type='text/template'>
			//<script type='text/html' class='av-video-tmpl'>
			if(preg_match("/<script[^\>]+text\/(template|html)[^\>]+/i", $value['text'])){
				continue;
			}

			//<script type="text/css" id="tmpl-tribe_customizer_css">
			if(preg_match("/<script[^\>]+text\/css[^\>]+/i", $value['text'])){
				continue;
			}

			// <script src='https://snapppt.com/widgets/widget_loader/979939cd-504c-4b59-9dcc-9e9f39dc1d09/grid.js' class='snapppt-widget'></script>
			if(preg_match("/snapppt\.com\/widgets\/widget_loader/i", $value['text'])){
				continue;
			}

			// <script src="/plugins/smart-cookie-kit/res/empty.js" data-blocked="http://maps.googleapis.com/maps/api/js" data-sck_type="2" data-sck_unlock="profiling" data-sck_ref="Google Maps" data-sck_index="1" class="BlockedBySmartCookieKit"></script>
			if(preg_match("/class\s*\=\s*[\'\"]BlockedBySmartCookieKit[\'\"]/i", $value['text'])){
				continue;
			}

			/*
			<script src="//platform.linkedin.com/in.js" type="text/javascript">lang: en_US</script>
			<script type="IN/Share" data-counter="top" data-onSuccess="share" data-url="https://helenstock.com/product/romantic-fashion/"></script>
			*/
			if(preg_match("/platform\.linkedin\.com\/in\.js/i", $value['text']) || preg_match("/type=[\"\']IN\/Share[\"\']/i", $value['text'])){
				continue;
			}

			/*
			<script id="mNCC" language="javascript">
			medianet_width="336";
			medianet_height="280";
			medianet_crid="656555462";
			medianet_versionId="3111299";
			</script>
			<script src="//contextual.media.net/nmedianet.js?cid=8CU33LCO0"></script>
			*/
			if((preg_match('/medianet_width/i', $value['text']) && preg_match('/medianet_height/i', $value['text'])) || preg_match("/contextual\.media\.net\/nmedianet\.js/i", $value['text'])){
				continue;
			}

			/*
			<script class="cmplz-stats">(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||fu);</script>
			<script class="cmplz-native">function complianz_enable_cookies(){console.log("enabling cookies");}</script>
			https://wordpress.org/plugins/complianz-gdpr/
			*/
			if(preg_match("/class\s*\=\s*[\"\']cmplz-(stats|native)\s*[\"\']/i", $value['text'])){
				continue;
			}

			/*
			Advanced noCaptcha & invisible Captcha
			var anr_onloadCallback=function(){
			};
			*/
			if(preg_match('/anr_onloadCallback/i', $value['text'])){
				continue;
			}

			$speedycache->render_blocking['js_tags_text'] = $speedycache->render_blocking['js_tags_text'].$value['text'];

			array_push($speedycache->render_blocking['tags'], $value);
		}
	}

	static function set_header_start_index(){
		global $speedycache;
		
		$head_tag = self::find_tags('<head', '>');
		
		$speedycache->render_blocking['header_start_index'] = 0;
		if(!empty($head_tag[0]) && !empty($head_tag[0]['start'])){
			$speedycache->render_blocking['header_start_index'] = $head_tag[0]['start'];
		}

	}

	static function reorder_tags($tags){
		// <script>jQuery('head').append('<style>' + arr_splits[i] + '</style>');</script>
		// <script>document.getElementById("id").innerHTML='<div> <span> <!--[if !IE]>--> xxx <!--<![endif]--> </span></div>';</script>
		$list = array();
		
		for ($i=0; $i < count($tags); $i++){
			for ($j=0; $j < count($tags); $j++){ 
				if($tags[$i]['start'] > $tags[$j]['start']){
					if($tags[$i]['end'] < $tags[$j]['end']){
						array_push($list, $i);
					}
				}
			}
		}

		foreach($list as $key => $value){
			unset($tags[$value]);
		}

		$sorter = array();
		$ret = array();

		foreach($tags as $ii => $va){
			$sorter[$ii] = $va['start'];
		}

		asort($sorter);

		foreach($sorter as $ii => $va){
			$ret[$ii] = $tags[$ii];
		}

		$tags = $ret;

		return $tags;
	}

	static function exclude_scripts($text){

		$excludeables = array(
			'/google_ad_client/',
			'/googlesyndication\.com/',
			'/app\.getresponse\.com/i',
			'/adsbygoogle/i',
			'/^<script[^\>]*>\s*gtag\([^\)]+\)\s*\;\s*<\/script>$/i',
			'/smarticon\.geotrust\.com\/si\.js/i',
			'/veedi\.com\/player\/embed\/veediEmbed\.js/i',
			'/cdn\.ampproject\.org/i',
			'/data-speedycache-render\=[\"\']false[\"\']/i',
			'/adserver\.adtechjp\.com/i',
			'/ib\.3lift\.com/i',
			'/adtradradservices\.com/i',
			'/static.clickpapa.com\/c\.js/i',
			'/clickpapa_ad_client/i',
			'/cts\.tradepub\.com/i',
			'/_areklam_target|ad\.arklm\.com/i',
			'/admatic\.com\.tr/i',
			'/ca\.cubecdn\.net/i',
			'/amazon-adsystem\.com\/widgets\/onejs/i',
			'/cdn\.playwire\.com\/bolt\/js\/zeus\/embed\.js/i',
			'/static\.mailerlite\.com/i',
		);
		
		$is_excludeable = false;

		foreach($excludeables as $excludeable){
			if(preg_match($excludeable, $text)){
				$is_excludeable = true;
				break;
			}
		}

		
		return $is_excludeable;
	}

	static function set_except($tags){
		global $speedycache;
		
		foreach($tags as $key => $value){
			$speedycache->render_blocking['except'] = $value['text'].$speedycache->render_blocking['except'];
		}
	}

	static function find_tags($start_string, $end_string, $html = false){
		global $speedycache;
		
		$data = $speedycache->render_blocking['html'];
		if(!empty($html)){
			$data = $html;
		}

		$list = array();
		$start_index = false;
		$end_index = false;

		for($i = 0; $i < strlen($data); $i++){
			if(substr($data, $i, strlen($start_string)) == $start_string){
				if(!$start_index && !$end_index){
					$start_index = $i;
				}
			}

			if(empty($start_index) || $i < $start_index){
				continue;
			}

			if(substr($data, $i, strlen($end_string)) !== $end_string){
				continue;
			}
			
			$end_index = $i + strlen($end_string) - 1;
			$text = substr($data, $start_index, ($end_index - $start_index + 1));

			if($html === false){
				$tag = self::get_tags($start_index, $text, $end_index);

				if($tag !== FALSE){
					array_push($list, $tag);
				}
			}else{
				array_push($list, array('start' => $start_index, 'end' => $end_index, 'text' => $text));
			}

			$start_index = false;
			$end_index = false;
		}

		return $list;
	}

	static function get_tags($start_index, $text, $end_index){
		global $speedycache;
		
		if($start_index <= $speedycache->render_blocking['header_start_index']){
			return false;
		}
		
		if($speedycache->render_blocking['except']){
			if(strpos($speedycache->render_blocking['except'], $text) === false){
				return array('start' => $start_index, 'end' => $end_index, 'text' => $text);
			}
			
			return false;
		}
		
		return array('start' => $start_index, 'end' => $end_index, 'text' => $text);
	}

	static function split_html_condition($tag){
		if(substr_count($tag, '<!--') !== substr_count($tag, '-->')){
			return false;
		}

		if(!preg_match("/\<\!--\s*\[if[^\>]+>/i", $tag, $start_cond)){
			return false;
		}

		if(!preg_match("/<\!\[endif\]-->/i", $tag, $end_cond)){
			return false;
		}
				
		$all = array();

		$script_tag = self::find_tags('<script', '</script>', $tag);
		$style_tags = self::find_tags('<style', '</style>', $tag);
		$link_tags = self::find_tags('<link', '>', $tag);

		$all = array_merge($script_tag, $style_tags, $link_tags);

		$all = self::reorder_tags($all);

		foreach($all as $key => &$value){
			$value['text'] = $start_cond[0].$value['text'].$end_cond[0];
		}

		return $all;
	}

	static function add_defer_attr($tags){
		$external_start = false;

		foreach($tags as $key => &$value){

			if(preg_match("/^<script/i", $value['text'])){
				if(preg_match("/var\s+[^\=\;\s\"\']+\s*\=\s*new\s+[^\(\)]+\(/i", $value['text'])){
					//var block_td_uid_2_58aab3b5b4eb1=new tdBlock()
					break;
				}else if(preg_match("/jQuery\(\s*window\s*\)\.load\(/i", $value['text']) || preg_match("/\\$\(\s*window\s*\)\.load\(/i", $value['text'])){
					//jQuery(window).load(function(){
					//$(window).load(function(){
					break;
				}else if(preg_match("/^<script[^\>]*>\s*jQuery\([^\)\(]+\)\.[a-z]+\(/i", $value['text']) && strpos($value['text'], "\n") === FALSE){
					//<script>jQuery("div").append("");</script>

					$value['text'] = self::defer_load_inline_js($value['text']);
				}else if(preg_match("/^<script[^\>]*>\s*\(function\(\\$\)\{[^\}\n]+\}\)\(jQuery\)\;\s*<\/script>/", $value['text'])){
					//<script>(function($){"use strict";$("html").removeClass("ut-no-js").addClass("ut-js js");})(jQuery);</script>

					$value['text'] = self::defer_load_inline_js($value['text']);
				}else if(preg_match("/^<script[^\>]+src=[\'\"][^\>]+>/i", $value['text'])){
					if(preg_match("/data-cfasync\=/i", $value['text'])){
						break;
					}

					if(preg_match("/googletagmanager\.com/i", $value['text'])){
						continue;
					}

					if(!preg_match("/\s+defer\s+/i", $value['text'])){
						$value['text'] = preg_replace("/<script\s+/", '<script defer ', $value['text']);
					}

					$external_start = true;
				}else{
					//inline js

					if(preg_match("/connect\.facebook\.net/i", $value['text']) && preg_match("/parentNode\.insertBefore/i", $value['text'])){
						// <script>(function(d, s, id){
						// var js, fjs=d.getElementsByTagName(s)[0];
						// if(d.getElementById(id)) return;
						// js=d.createElement(s); js.id=id;
						// js.async=true;
						// js.src="//connect.facebook.net/nl_NL/sdk.js#xfbml=1&version=v2.8&appId=1126044540802926";
						// fjs.parentNode.insertBefore(js, fjs);
						// }(document, 'script', 'facebook-jssdk'));</script>

						continue;
					}else if(preg_match("/<script[^\>]*>\s*_stq\s*\=\s*window\._stq/i", $value['text']) && preg_match("/_stq\.push\s*\([^\)]+\)\s*\;\s*<\/script>/i", $value['text'])){
						// <script type='text/javascript'>
						// _stq = window._stq || [];
						// _stq.push([ 'view', {v:'ext',j:'1:5.5',blog:'121052134',post:'88',tz:'3',srv:'www.bibersa.com'} ]);
						// _stq.push([ 'clickTrackerInit', '121052134', '88' ]);
						// </script>

						continue;
					}else{
						if($external_start){
							break;
						}else{
							if(preg_match("/var\s+wpforms(_settings|RecaptchaLoad|RecaptchaCallback)\s*\=/i", $value['text'])){
								// WPForms Lite
								// var wpforms_settings = {variable}
								// var wpformsRecaptchaLoad=function(){
								// var wpformsRecaptchaCallback=function
								continue;
							}

							if(preg_match("/window\.TL_Const/i", $value['text']) && preg_match("/var\s+TL_Const/i", $value['text'])){
								// Thrive Leads
								// if(!window.TL_Const){var TL_Const=
								continue;
							}

							if(preg_match("/<script[^\>]+application\/ld\+json[^\>]+>/i", $value['text'])){
								// <script type="application/ld+json">
								// {
								// "@context": "http://schema.org/",
								// "@type": "Product",
								// "name": "Product Name",
								// "image": "/default.png",
								// "aggregateRating": {
								// "@type": "AggregateRating",
								// "ratingValue": "5",
								// "reviewCount": "81"
								// }
								// }
								// </script>
								continue;
							}

							if(preg_match("/_translator_revolution_dropdown/i", $value['text'])){
								// <script>var _translator_revolution_dropdown=_translator_revolution_dropdown||{languages: ["en","fr","de"],excludeSelector: "code, #wpadminbar",locationWidget: false};</script>

								continue;
							}

							$value['text'] = self::defer_load_inline_js($value['text']);
						}
					}
				}
			}else if(preg_match("/^<(link|style)/i", $value['text'])){
				continue;
			}else if(preg_match("/<\!--\s*\[if/i", $value['text'])){
				preg_match_all("/<script[^\>]+src=[\'\"][^\>]+>/i", $value['text'], $src_number);
				preg_match_all("/<script[^\>]*/i", $value['text'], $script_tag_number);

				if(count($script_tag_number[0]) != count($src_number[0])){
					break;
				}

				if(preg_match("/<link|<style/i", $value['text'])){
					break;
				}

				if(!preg_match("/<script[^\>]+src=[\'\"][^\>]+>/i", $value['text'])){
					break;
				}

				if(preg_match("/data-cfasync\=/i", $value['text'])){
					break;
				}

				if(!preg_match("/<script[^\>]+defer[^\>]+>/i", $value['text'])){
					$value['text'] = preg_replace("/<script\s+/", '<script defer ', $value['text']);
				}
			}else{
				break;
			}
		}

		return $tags;
	}

	static function action($render_blocking_css = false, $make_defer = false){
		global $speedycache;
		
		$wpemojiSettings = '';
		$google_fonts = '';
		$bootstrapcdn = '';
		$inline_js = '';
		$document_ready_js = '';
		$third_part_js = '';
		$script = '';
		$style = '';
		
		//to remove tags
		$speedycache->render_blocking['tags'] = array_reverse($speedycache->render_blocking['tags']);
		
		foreach($speedycache->render_blocking['tags'] as $key => &$value){
			if(preg_match("/\<\!--\s*\[if[^\>]+>/i", $value['text'])){
				if($arr = self::split_html_condition($value['text'])){
					$style = '';
					$script = '';

					foreach($arr as $arr_key => $arr_value){
						if(preg_match("/\<\!--\s*\[if[^\>]+>(<link|<style)/i", $arr_value['text'])){
							$style = $style."\n".$arr_value['text'];
						}else if(preg_match("/\<\!--\s*\[if[^\>]+><script/i", $arr_value['text'])){
							$script = $script."\n".$arr_value['text'];
						}
					}
				}

				$value['text'] = $script;
				$speedycache->render_blocking['html'] = substr_replace($speedycache->render_blocking['html'], $style, $value['start'], ($value['end'] - $value['start'] + 1));
			}else if(preg_match("/^<script/i", $value['text'])){
				$speedycache->render_blocking['html'] = substr_replace($speedycache->render_blocking['html'], '', $value['start'], ($value['end'] - $value['start'] + 1));
			}else if(preg_match("/^<link[^\>]+(fonts|ajax)\.googleapis\.com[^\>]+>/", $value['text'])){
				if(!empty($speedycache->options['google_fonts'])){
					$speedycache->render_blocking['html'] = substr_replace($speedycache->render_blocking['html'], '', $value['start'], ($value['end'] - $value['start'] + 1));

					$google_fonts = $value['text']."\n".$google_fonts;
				}
			}else if(preg_match("/^<link[^\>]+(maxcdn)\.bootstrapcdn\.com[^\>]+>/", $value['text'])){
				$speedycache->render_blocking['html'] = substr_replace($speedycache->render_blocking['html'], '', $value['start'], ($value['end'] - $value['start'] + 1));

				$bootstrapcdn = $value['text']."\n".$bootstrapcdn;
			}
		}
		
		foreach($speedycache->render_blocking['tags'] as $key => &$value){
			
			if($value['text'] && preg_match("/^<script/i", $value['text'])){
				if(preg_match("/gravatar\.com\/js\/gprofiles\.js/i", $value['text']) || 
					preg_match("/use\.fontawesome\.com/i", $value['text']) || 
					preg_match("/s0\.wp\.com\/".SPEEDYCACHE_WP_CONTENT_DIR."\/js\/devicepx-jetpack\.js/i", $value['text'])){
					//<script type='text/javascript' src='http://s.gravatar.com/js/gprofiles.js?ver=2023Janaa'></script>
					//<script type='text/javascript' src='http://s0.wp.com/site-data/js/devicepx-jetpack.js?ver=201701'></script>
					//<script defer src="https://use.fontawesome.com/123456789.js"></script>

					if(!preg_match("/\sdefer\s/i", $value['text'])){
						$value['text'] = preg_replace("/<script\s+/", '<script defer ', $value['text']);
					}

					if(!preg_match("/\sasync\s/i", $value['text'])){
						$value['text'] = preg_replace("/<script\s+/", '<script async ', $value['text']);
					}

					unset($speedycache->render_blocking['tags'][$key]);
					$third_part_js = $value['text']."\n".$third_part_js;
				}else if(preg_match("/document\.addEventListener\(\s*[\"\']\s*DOMContentLoaded\s*[\"\']\s*,\s*function\s*\([^\)]*\)\s*\{/i", $value['text'])){
					//to remove jQuery(document) which contains window.attachEvent
					unset($speedycache->render_blocking['tags'][$key]);
					$document_ready_js = $value['text']."\n".$document_ready_js;
				}else if(preg_match("/^<script[^\>]*>\s*jQuery\(\s*document\s*\)\.ready\(/i", $value['text'])){
					// <script>
					// 	jQuery(document).ready(function($){
					// 	});
					// </script>

					if(preg_match("/jQuery\(\s*window\s*\)\.load\(/i", $value['text'])){
						//jQuery(window).load(function(){
						continue;
					}

					if(preg_match("/\\$\(\s*window\s*\)\.load\(/i", $value['text'])){
						//$(window).load(function(){
						continue;
					}

					if(preg_match("/var owl\s*=\s*\\$\([\'\"]\.products-carousels-/i", $value['text'])){
						//to exclude carousel of Master Slider
						//https://codecanyon.net/item/master-slider-wordpress-responsive-touch-slider
						//var owl=$('.products-carousels-99056136 #products');
						continue;
					}
					
					if(preg_match("/\}\s*\)\s*\;\s*<\/script>$/i", $value['text'])){
						$jqIsReady_func_name = 'jqIsReady_'.rand(100,999);
						$value['text'] = preg_replace("/(<script[^\>]*>)/i", "$1"."(function ".$jqIsReady_func_name."(){if(typeof jQuery === \"undefined\"){".$jqIsReady_func_name."();}else{", $value['text']);
						$value['text'] = preg_replace("/\s*(<\/script>)/i", "}})();"."$1", $value['text']);

						unset($speedycache->render_blocking['tags'][$key]);
						$document_ready_js = $value['text']."\n".$document_ready_js;
					}
				}else if(preg_match("/^<script[^\>]*>\s*window\.\_wpemojiSettings/", $value['text'])){
					//to remove window._wpemojiSettings from tags
					unset($speedycache->render_blocking['tags'][$key]);
					$wpemojiSettings = $wpemojiSettings."\n".$value['text'];
				}else if(!preg_match("/^<script[^\>]+src=[\'\"][^\>]+>/", $value['text'])){
					//to remove inline js which do not contain any function
					//<script>var _wpcf7={"loaderUrl":"sample"};</script>
					$tmp = $value['text'];

					// <script>/*<![CDATA[*/var THO_Front = THO_Front || {}; THO_Front.data = {"end_of_content_id":"tho-end","const":{"_e_click":1,"_engagement":2}}/*]]> */</script>
					$tmp = preg_replace("/<script[^\>]+>\s*\/\*\s*<\!\[CDATA\[\s*\*\//", "", $tmp);
					$tmp = preg_replace("/\/\*\s*\]\]>\s*\*\/\s*<\/script>/", "", $tmp);

					// to remove multi-line comments but it removes everything. it does not work properly
					$tmp = preg_replace("/\s*\/\*(.+)\*\/\s*/", '', $tmp);

					//var themifyScript causes "fixed header" issue on thepurplepumpkinblog.co.uk
					if(preg_match("/var\sthemifyScript/i", $tmp)){
						continue;
					}

					//<script data-cfasync="false" type="text/javascript">var lsjQuery = jQuery;</script>
					if(preg_match("/data-cfasync\=[\"\']false[\"\']/i", $tmp)){
						continue;
					}

					if(preg_match("/(function|jQuery|if)\s*\([^\)\(]+\)/i", $tmp)){
						if(!preg_match("/<script[^\>]*>\s*function heateorSssLoadEvent/i", $tmp)){
							//https://plugins.trac.wordpress.org/browser/sassy-social-share/trunk/includes/class-sassy-social-share-widgets.php#L72
							//https://plugins.trac.wordpress.org/browser/sassy-social-share/trunk/public/class-sassy-social-share-public.php#L104

							continue;
						}
					}

					//var block_td_uid_2_58aab3b5b4eb1=new tdBlock()
					if(preg_match("/var\s+[^\=\;\s\"\']+\s*\=\s*new\s+[^\(\)]+\(/i", $tmp)){
						continue;
					}

					//<script>var lsjQuery = jQuery;</script>
					if(preg_match("/var\s+[^\=\s]+\s*\=\s*jQuery\s*\;/i", $value['text'])){
						continue;
					}

					//<script>Abtf.css();</script>
					//<script>dtGlobals.logoEnabled=1;</script>
					//if var does not exist
					if(!preg_match("/var\s*[a-z0-9_]+\s*\=\s*[^\;]+\s*\;/i", $tmp)){
						continue;
					}

					//$=jQuery.noConflict()
					//var joblistin_caned_msgs=jQuery.parseJSON('[{\"title\":\"jobs description 1\",
					if(preg_match("/\=\s*jQuery\.(noConflict|parseJSON)\(/i", $tmp)){
						continue;
					}

					//$(".menu-item-has-children a")
					if(preg_match("/\\\$\s*\(\s*[\"\']/", $tmp)){
						continue;
					}

					/*
					<script>
					jQ_nxs(document).on('nxs_event_resizeend.menu_mini_expand', function(){
						//something
					});
					</script>
					*/
					if(preg_match("/\([^\)]+\)\.on\(\s*[\'\"][^\'\"]+[\'\"]\s*\,\s*function\(\)\{/", $tmp)){
						continue;
					}

					/*
					<script>
					videojs("vid1").videoJsResolutionSwitcher();
					var my_video_id = videojs("vid1");
					my_video_id.watermark({ file: "/site-data/uploads/2019/05/logo.png", xpos: 0, ypos: 0, xrepeat: 0, opacity: 1,clickable: true,url: "https://www.site.net"  });
					</script>
					*/
					if(preg_match("/videojs\([^\)\(]+\)\.videoJsResolutionSwitcher/", $tmp)){
						continue;
					}

					unset($speedycache->render_blocking['tags'][$key]);
					$inline_js = $value['text']."\n".$inline_js;

				}
			}
		}

		//to add Google Fonts at the end of page before js sources
		if(!empty($google_fonts)){
			//$google_fonts = self::combine_google_fonts($google_fonts);

			if(!empty($speedycache->options['google_fonts'])){
				
				if(preg_match('/speedycache-google-fonts/', $speedycache->render_blocking['html'])){
					$speedycache->render_blocking['html'] = str_replace('<noscript id="speedycache-google-fonts">', '<noscript id="speedycache-google-fonts">'.$google_fonts, $speedycache->render_blocking['html']);
				}else{
					$google_fonts = self::async_google_fonts($google_fonts);
					$speedycache->render_blocking['html'] = str_replace('</body>', $google_fonts."\n".'</body>', $speedycache->render_blocking['html']);
				}

			}
		}
		
		//to add BootstrapCDN at the end of page before js sources
		if(!empty($bootstrapcdn)){
			$speedycache->render_blocking['html'] = str_replace('</body>', $bootstrapcdn."\n".'</body>', $speedycache->render_blocking['html']);
		}

		//to add Inline Js before at the end of page before js sources
		if(!empty($inline_js)){
			$speedycache->render_blocking['html'] = str_replace('</body>', $inline_js."\n".'</body>', $speedycache->render_blocking['html']);
		}

		//to add third_part_js at the end of page
		if(!empty($third_part_js)){
			$speedycache->render_blocking['html'] = str_replace('</body>', $third_part_js."\n".'</body>', $speedycache->render_blocking['html']);
		}

		//to add defer and async attribute
		if(!empty($make_defer) || empty($speedycache->options['combine_js_enhanced'])){
			$speedycache->render_blocking['tags'] = self::add_defer_attr($speedycache->render_blocking['tags']);
		}

		//to add tags into footer
		$speedycache->render_blocking['tags'] = array_reverse($speedycache->render_blocking['tags']);
		foreach($speedycache->render_blocking['tags'] as $key => $value){
			if(preg_match("/^<script/i", $value['text'])){
				$speedycache->render_blocking['html'] = str_replace('</body>', $value['text']."\n".'</body>', $speedycache->render_blocking['html']);
			}else if(preg_match("/\<\!--\s*\[if[^\>]+>/i", $value['text'])){
				$speedycache->render_blocking['html'] = str_replace('</body>', $value['text']."\n".'</body>', $speedycache->render_blocking['html']);
			}
		}

		//to add document_ready_js at the end of page
		if(!empty($document_ready_js)){
			$speedycache->render_blocking['html'] = str_replace('</body>', $document_ready_js."\n".'</body>', $speedycache->render_blocking['html']);
		}

		//to add wpemojiSettings at the end of page
		if(!empty($wpemojiSettings)){
			$speedycache->render_blocking['html'] = str_replace('</body>', $wpemojiSettings."\n".'</body>', $speedycache->render_blocking['html']);
		}
		
		return preg_replace("/^\s+/m", '', $speedycache->render_blocking['html']);
	}

	static function async_google_fonts($fonts){
		if(preg_match("/\shref\=/", $fonts)){
			$fonts = '<noscript id="speedycache-google-fonts">'.$fonts.'</noscript>';
			$onload = "<script>document.addEventListener('DOMContentLoaded',function(){function speedycachegl(){var wgh=document.querySelector('noscript#speedycache-google-fonts').innerText, wgha=wgh.match(/<link[^\>]+>/gi);var i=0;for(i=0;i<wgha.length;i++){var wrpr=document.createElement('div');wrpr.innerHTML=wgha[i];document.body.appendChild(wrpr.firstChild);}}speedycachegl();});</script>";
			
			return $fonts."\n".$onload;
		}
		
		return $fonts;
	}

	static function combine_google_fonts($fonts){
		$family = '';
		$subset = '';

		preg_match_all("/fonts\.googleapis\.com\/css\?family\=([^\'\"]+)/si", $fonts, $arr);

		if(empty($arr[0])){
			return $fonts;
		}

		foreach($arr[0] as $key => $value){
			//to remove special chars
			$value = htmlspecialchars_decode($value);

			$parts = parse_url($value);
			parse_str($parts['query'], $query);

			$family = $query['family'];
			if(!empty($family)){
				$family = $family.'|'.$query['family'];
			}

			if(isset($query['subset']) && $query['subset']){
				
				$subset = $query['subset'];
				if(!empty($subset)){
					$subset = $subset.','.$query['subset'];
				}
			}
		}

		$family = str_replace(' ', '+', $family);
		if(!empty($subset)){
			$family.'&subset='.$subset;
		}

		return "<!--\n".$fonts."\n-->\n"."<link rel='stylesheet' id='speedycache-google-combined' href='http://fonts.googleapis.com/css?family=".$family."' type='text/css' media='all'/>";
	}

	static function defer_load_inline_js($script){
		if(preg_match("/<script[^\>]*>\s*\/\/\<\!\[CDATA\[\s*/", $script) && preg_match("/\/\/\]\]\>\s*<\/script>/", $script)){
			$script = preg_replace("/(<script[^\>]*>)\s*\/\/\<\!\[CDATA\[\s*/", "$1\n", $script);
			$script = preg_replace("/\/\/\]\]\>\s*(<\/script>)/", "\n$1", $script);
		}

		if(preg_match("/var\s+wpforms_conditional_logic/i", $script)){
			// to exclude the conditions of wpforms
			// <script type='text/javascript'>
			// /* <![CDATA[ */
			// var wpforms_conditional_logic = {"5616":{"17"}]],"action":"show"}}}
			// /* ]]> */
			// </script>
			return $script;
		}

		if(preg_match("/var\s+recaptchaWidgets/i", $script)){
			if(preg_match("/var\s+recaptchaCallback/i", $script)){
				// to exclude
				// https://github.com/IQComputing/wpcf7-recaptcha/blob/master/recaptcha-v2.php#L94
				return $script;
			}
		}

		if(preg_match('/function jqIsReady/i', $script)){
			return $script;
		}

		if(preg_match("/^<script[^\>]+>\s*<\/script>/i", $script)){
			// to exclude empty inline source
			// <script type="text/javascript" id="speedycachep-script-frontend"></script>
			return $script;
		}

		$script = preg_replace("/^(<script[^\>]*>)/i", "$1"."document.addEventListener('DOMContentLoaded',function(){", $script);
		$script = preg_replace("/\s*(<\/script>)/i", "});"."$1", $script);

		return $script;
	}
}main/statistics.php000064400000010433151526423640010404 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class Statistics{

	static function init($extension = false, $size = false){
		global $speedycache;
		$speedycache->settings['static_extension'] = $extension ? $extension : false;
		$speedycache->settings['static_size'] = $size ? $size : false;
	}

	static function get(){
		
		$desktop_files = get_option('speedycache_html');
		$desktop_size = round(get_option('speedycache_html_size')/1000, 2);
		$mobile_files = get_option('speedycache_mobile');
		$mobile_size = round(get_option('speedycache_mobile_size')/1000, 2);
		$js_files = get_option('speedycache_js');
		$js_size = round(get_option('speedycache_js_size')/1000, 2);
		$css_files = get_option('speedycache_css');
		$css_size = round(get_option('speedycache_css_size')/1000, 2);
		
		$stats = array();
		$stats['desktop'] = array('size' => $desktop_size, 'file' => $desktop_files);
		$stats['mobile'] = array('size' => $mobile_size, 'file' => $mobile_files);
		$stats['js'] = array('size' => $js_size, 'file' => $js_files);
		$stats['css'] = array('size' => $css_size, 'file' => $css_files);

		return $stats;
	}

	static function update_db(){
		global $speedycache;
		
		// We do not need stats if its a test
		if(!empty($_GET['test_speedycache'])){
			return;
		}

		$option_name = 'speedycache_' . $speedycache->settings['static_extension'];
		$option_name_for_size = $option_name . '_size';
		
		$current_opt = get_option($option_name);
		
		if(!empty($current_opt)){
			$current_opt = $current_opt + 1;
			update_option($option_name, $current_opt);
		}else{
			update_option($option_name, 1, null, 'yes');
		}

		$size_current_opt = get_option($option_name_for_size);

		if(!empty($size_current_opt)){
			$size_current_opt = $size_current_opt + $speedycache->settings['static_size'];
			update_option($option_name_for_size, $size_current_opt);
			return;
		}
		
		update_option($option_name_for_size, $speedycache->settings['static_size'], null, 'yes');

	}

	static function statics(){
		?>
		<div class="speedycache-block">
			<div class="speedycache-block-title">
				<h2 id="cache-statics-h2"><?php _e('Cache Statistics', 'speedycache'); ?></h2>
			</div>
			<div id="speedycache-cache-statics">
				<div id="speedycache-cache-statics-desktop" class="speedycache-card">
					<div class="speedycache-card-body">
						<div class="speedycache-stats-info">
							<span>Desktop Cache</span>
							<p id="speedycache-cache-statics-desktop-data">
								<span class="speedycache-size">0Kb</span><br/>
								<span class="speedycache-files">of 0 Items</span>
							</p>
						</div>
						<div class="speedycache-stat-icon">
							<i class="fas fa-desktop"></i>
							<!--<span class="dashicons dashicons-desktop"></span>-->
						</div>
					</div>
				</div>
				<div id="speedycache-cache-statics-mobile" class="speedycache-card">
					<div class="speedycache-card-body">
						<div class="speedycache-stats-info">
							<span>Mobile Cache</span>
							<p id="speedycache-cache-statics-mobile-data">
								<span class="speedycache-size">0Kb</span><br/>
								<span class="speedycache-files">of 0 Items</span></p>
						</div>
						<div class="speedycache-stat-icon">
							<i class="fas fa-mobile"></i>
						</div>
					</div>
				</div>
				<div id="speedycache-cache-statics-css" class="speedycache-card">
					<div class="speedycache-card-body">
						<div class="speedycache-stats-info">
							<span>Minified CSS</span>
							<p id="speedycache-cache-statics-css-data">
								<span class="speedycache-size">0Kb</span><br/>
								<span class="speedycache-files">of 0 Items</span>
							</p>
						</div>
						<div class="speedycache-stat-icon"><i class="fab fa-css3-alt"></i></div>
					</div>
				</div>
				<div id="speedycache-cache-statics-js" class="speedycache-card">
					<div class="speedycache-card-body">	
						<div class="speedycache-stats-info">
							<span>Minified JS</span>
							<p id="speedycache-cache-statics-js-data">
								<span class="speedycache-size">0Kb</span><br/>
								<span class="speedycache-files">of 0 Items</span>
							</p>
						</div>
						<div class="speedycache-stat-icon"><i class="fab fa-js-square"></i></div>
					</div>
				</div>
			</div>
		</div>
	<?php }

}

main/prooptimizations.php000064400000004144151526423640011646 0ustar00<?php

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT');
}

class ProOptimizations{
	static $content = '';

	// function init(&$content){
		// self::$content = $content;
	// }
	
	static function defer_js(&$content){
		global $speedycache;

		\SpeedyCache\Enhanced::init();
		$content = \SpeedyCache\Enhanced::render_blocking($content);
	}
	
	static function delay_js(&$content){
		global $speedycache;

		\SpeedyCache\Enhanced::init();
		if(empty($speedycache->enhanced)){
			$speedycache->enhanced['html'] = $content;
		}

		$content = \SpeedyCache\Enhanced::delay_js($content);
	}
	
	static function unused_css(){
		$url = esc_url(speedycache_optserver('HTTP_HOST'). speedycache_optserver('REQUEST_URI'));

		if(strpos($url, '?test_speedycache') !== FALSE){
			\SpeedyCache\UnusedCss::generate(array($url));
		} else {
			\SpeedyCache\UnusedCss::schedule('speedycache_unused_css', array($url));
		}
	}
	
	static function critical_css(){
		$url = esc_url(speedycache_optserver('HTTP_HOST'). speedycache_optserver('REQUEST_URI'));

		if(strpos($url, '?test_speedycache') !== FALSE){
			\SpeedyCache\CriticalCss::generate(array($url));
		} else {
			\SpeedyCache\CriticalCss::schedule('speedycache_generate_ccss', array($url));
		}
	}
	
	static function img_lazy_load(&$content){

		// to disable for Ajax Load More on the pages
		if(speedycache_is_plugin_active('ajax-load-more/ajax-load-more.php') && !empty($_SERVER['REQUEST_URI']) && preg_match("/\/page\/\d+\//", sanitize_url(wp_unslash($_SERVER['REQUEST_URI'])))){
			return;
		}

		$content = \SpeedyCache\Enhanced::lazy_load($content);
		$lazy_load_js = '';
		
		if(file_exists(SPEEDYCACHE_PRO_DIR . '/main/lazyload.php')){
			$lazy_load_js = \SpeedyCache\LazyLoad::get_js_source();
		}

		$content = preg_replace("/\s*<\/head\s*>/i", $lazy_load_js.'</head>', $content, 1);
	}
	
	static function remove_gfonts(&$content){
		if(!empty($speedycache->bloat['remove_gfonts'])){
			$content = preg_replace('/<link[^<>]*\/\/fonts\.(googleapis|google|gstatic)\.com[^<>]*>/i', '', $content);
		}
	}
}main/mobile.php000064400000003106151526423640007460 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class Mobile{

	static function cache(){
		global $speedycache;
		
		$speedycache->mobile_cache = array();
		$speedycache->mobile_cache['folder_name'] = 'mobile-cache';
		$speedycache->mobile_cache['wptouch'] = false;
	}

	static function update_htaccess($data){
		global $speedycache;
		
		preg_match("/RewriteEngine\sOn(.+)/is", $data, $out);
		$htaccess = "\n##### Start: Mobile Cache Rules #####\n";
		$htaccess .= $out[0];

		// Updates the moble cache htaccess rule according to wptouch
		if($speedycache->mobile_cache['wptouch']){
			$wptouch_rule = "RewriteCond %{HTTP:Cookie} !wptouch-pro-view=desktop";
			$htaccess = str_replace("RewriteCond %{HTTP:Profile}", $wptouch_rule."\n"."RewriteCond %{HTTP:Profile}", $htaccess);
		}

		/**
		* Structure of this array is
		*	searchable => replacer
		*/
		$rules = array(
			'RewriteCond %{HTTP:Cookie} !safirmobilswitcher=mobil' => 'RewriteCond %{HTTP:Cookie} !safirmobilswitcher=masaustu',
			'RewriteCond %{HTTP_USER_AGENT} !^.*' => 'RewriteCond %{HTTP_USER_AGENT} ^.*',
		);
		
		foreach($rules as $search => $replacement){
			$htaccess = str_replace($search, $replacement, $htaccess);
		}

		$htaccess = preg_replace('/\/speedycache\/'.preg_quote(SPEEDYCACHE_SERVER_HOST).'\/all\//', '/speedycache/'.SPEEDYCACHE_SERVER_HOST .'/'. $speedycache->mobile_cache['folder_name']."/", $htaccess);
		$htaccess .= "\n##### End: Mobile Cache Rules #####\n";

		return $htaccess;
	}

}
main/image.php000064400000214160151526423640007277 0ustar00<?php
/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

class Image{

	static function init(){
		global $speedycache, $speedycache_optm_method;
		
		$speedycache->image = array();
		$speedycache->image['upload_dir'] = wp_upload_dir();
		$speedycache->image['id'] = false;
		$speedycache->image['metadata'] = array();
		$speedycache->image['name'] = '';
		$speedycache->image['path'] = '';
		$speedycache->image['url'] = '';
		$speedycache->image['images'] = array();
		$speedycache->image['images_clone'] = array();
		$speedycache->image['disabled_method'] = 0;
		
		// Default settings for img optimization
		$speedycache->image['settings'] = array(
			'on_upload' => false,
			'automatic_optm' => false,
			'url_rewrite' => false,
			'compression_method' => 'gd',
			'compression_quality' => '70'
		);
		
		$speedycache_optm_method = array(
			'gd' => array(
				'title' => 'GD',
				'desc' => 'Compress using PHP\'s native Extension for compression and conversion.'
			),
			'imagick' => array(
				'title' => 'Imagick',
				'desc' => 'Imagick outputs better image quality after compression at the cost of a little bigger file size compared to GD.'
			),
			'cwebp' => array(
				'title' => 'cWebP',
				'desc' => 'cwebp is a utility which can be downloaded on your server and its fast and light on you server.'
			)
		);
		
		// Binaries for cwebp
		$speedycache->image['binaries'] = array(
			'WINNT' => ['cwebp-122-windows-x64.exe', 'gif2webp-122-windows-x64.exe'],
			'Linux' => ['cwebp-122-linux-x86-64', 'gif2webp-122-linux-x86-64']
		);
		
		if(array_key_exists(PHP_OS, $speedycache->image['binaries'])){
			$speedycache->image['cwebp_binary'] = $speedycache->image['binaries'][PHP_OS][0];
			$speedycache->image['cwebp_gif'] = $speedycache->image['binaries'][PHP_OS][1];
		}

		if($img_settings = get_option('speedycache_img')){
			$speedycache->image['settings'] = array_merge($speedycache->image['settings'], $img_settings);
			self::compression_method_checks();

			return;
		}
		
		self::compression_method_checks();
		update_option('speedycache_img', $speedycache->image['settings']);

	}

	static function total_reduction(){
		global $wpdb;
		
		$query = "SELECT sum(`meta_value`) as total FROM `".$wpdb->prefix."postmeta` WHERE `meta_key`= 'speedycache_optimisation_reduction'";
		$result = $wpdb->get_row( $query );
		
		if(!empty($result->total)){
			$reduced = ($result->total && $result->total > 0) ? $result->total : 0;
			
			return $reduced > 10000 ? $reduced/1000 : $reduced;	
		}
		
		return 0;
	}

	static function optimized_file_count(){
		global $wpdb;
		
		$query = "SELECT count(`meta_value`) as optimized FROM `".$wpdb->prefix."postmeta` WHERE `meta_key`= 'speedycache_optimisation'";
		$result = $wpdb->get_row($query);
		
		if($result->optimized && $result->optimized > 0){
			return $result->optimized;
		}
		
		return 0;
	}

	static function optm_img_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'EXISTS'
				),
				array(
					'key' => 'speedycache_optimisation',
					'value' => base64_encode('"destination_path"'),
					'compare' => 'LIKE'
				)
			)
		));
	}

	static function error_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'EXISTS'
				),
				array(
					'key' => 'speedycache_optimisation',
					'value' => base64_encode('"error_code"'),
					'compare' => 'LIKE'
				)
			)
		));
	}

	static function null_posts_groupby(){
		return '';
	}

	static function count_posts_fields(){
		return 'COUNT(*) as post_count_speedycache';
	}

	static function count_query($query_images_args){
		add_filter('posts_fields', '\SpeedyCache\Image::count_posts_fields');
		add_filter('posts_groupby', '\SpeedyCache\Image::null_posts_groupby');

		unset($query_images_args['offset']);
		unset($query_images_args['order']);
		unset($query_images_args['orderby']);

		$query_images_args['posts_per_page'] = -1;

		$query_image = new \WP_Query( $query_images_args );

		return $query_image->posts[0]->post_count_speedycache;
	}

	static function image_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => '_wp_attachment_metadata',
					'compare' => 'EXISTS'
				)
			)
		));
	}

	static function uncompressed_count(){

		return self::count_query(array(
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'NOT EXISTS'
				)
			)
		));
	}

	static function unoptimized(){
		global $speedycache;
		
		$tmp_image = array();

		$optimization_data = get_post_meta($speedycache->image['id'], 'speedycache_optimisation', true);
		$optm_json = base64_decode($optimization_data);
		
		if(empty($optm_json)){
			$percentage = 100 / count($speedycache->image['images']);
			
			return array('meta_optimized' => array(), 'images' => $speedycache->image['images'], 'total_reduction' => 0, 'percentage' => $percentage);
		}

		$optm_json = json_decode($optm_json, true);
		$meta_optimized = self::object_to_array($optm_json);
		$percentage = count($meta_optimized) * 100/count($speedycache->image['images']);
		
		foreach($speedycache->image['images'] as $key => $value){
			$exist = false;

			foreach($meta_optimized as $meta_key => $meta_value){
				if($value['file'] == $meta_value['file']){
					$exist = true;
					//break;
				}
			}

			if(empty($exist)){
				array_push($tmp_image, $value);
			}
		}

		//START: total reduction
		$total_reduction = 0;
		
		foreach($meta_optimized as $m_key => $m_value){
			$m_value['reduction'] = isset($m_value['reduction']) ? $m_value['reduction'] : 0;
			
			if($m_key == 0){
				$reduction = $m_value['reduction'];
			}
			
			$total_reduction += $m_value['reduction'];
		}
		//END: total reduction

		if(count($tmp_image) <= 0){
			return array('meta_optimized' => array(), 'images' => array(), 'total_reduction' => 0);
		}

		$last = speedycache_optget('last');
		if(!empty($last)){
			if(preg_match('/last-(\d+)/', $last, $last_number)){
				if(count($tmp_image) > 5){
					$tmp_image = array_slice($tmp_image, $last_number[1]*-1, 1);
				}
			}
		}

		return array('meta_optimized' => $meta_optimized, 'images' => array_slice($tmp_image, 0, 1), 'total_reduction' => $total_reduction, 'percentage' => $percentage);
	}

	static function object_to_array($obj){
		if(is_object($obj)){
			$obj = (array) $obj;
		}
		
		if(!is_array($obj)){
			$new = $obj;
			return $new;
		}
		
		$new = array();
		foreach($obj as $key => $val){
			$new[$key] = self::object_to_array($val);
		}
		return $new;
	}

	static function reorder_by_dimensions(){
		global $speedycache;
		
		$tmp = $speedycache->image['images'];

		foreach($tmp as $key => $value){
			$width_list[$key] = $value['width'];
		}

		array_multisort($width_list, SORT_DESC, $tmp);
		
		return $tmp;
	}

	static function optimize_single($id = null){
		global $speedycache;

		if(!empty($id)){
			self::init();
		}

		self::set_id($id);
		self::set_meta_data();

		if(wp_next_scheduled('speedycache_auto_optm', array($speedycache->image['id']))){
			wp_clear_scheduled_hook('speedycache_auto_optm' , array($speedycache->image['id']));
		}

		if(empty($speedycache->image['id'])){
			return array('finish', 'success'); 
		}

		if(!isset($speedycache->image['metadata']['file']) && !empty($speedycache->image['id'])){
			$meta_optimized = array();
			$meta_optimized[0]['time'] = time();
			$meta_optimized[0]['id'] = $speedycache->image['id'];
			$meta_optimized[0]['error_code'] = 17;

			update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', 0);
			update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_optimized)));

			return array('Image has been optimized', 'success', $speedycache->image['id'], 100);
		}

		self::set_name();
		self::set_path();
		self::set_url();
		self::set_images();

		if(!empty($speedycache->image['id']) && count($speedycache->image['images']) == 0){
			$meta_optimized = array();
			$meta_optimized[0]['time'] = time();
			$meta_optimized[0]['id'] = $speedycache->image['id'];
			$meta_optimized[0]['error_code'] = 18;

			update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', 0);
			update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_optimized)));

			return array('Image has been optimized', 'success', $speedycache->image['id'], 100);
		}

		$error_exist = false;
		$meta_optimized = array();
		$total_reduction = 0;
		
		$speedycache->image['images'] = self::unique_array($speedycache->image['images']);
		$speedycache->image['images'] = self::reorder_by_dimensions();

		$speedycache->image['images_clone'] = $speedycache->image['images'];

		$unoptimized = self::unoptimized();
		$speedycache->image['images'] = $unoptimized['images'];
		$meta_optimized = $unoptimized['meta_optimized'];
		$total_reduction = $unoptimized['total_reduction'];
		$percentage = isset($unoptimized['percentage']) && $unoptimized['percentage'] ? $unoptimized['percentage'] : 0;

		if(count($speedycache->image['images']) == 0){
			return array('Image has been optimized', 'success', '', 100);
		}

		foreach($speedycache->image['images'] as $key => $value){
		
			$res = self::compress($value);
			
			if(!empty($res['success'])){
				$value['destination_path'] = $res['destination_path'];
				$value['reduction'] = $res['reduction'];

				$total_reduction += $value['reduction'];

				$value['time'] = time();
				$value['id'] = $speedycache->image['id'];
				
				array_push($meta_optimized, $value);
			}else{
				if(!isset($res['error_code']) && isset($res['error_message'])){
					return array($res['error_message'], 'error');
					break;
				}

				if(in_array($res['error_code'] , array(2, 6, 7, 11, 19, 20, 22, 23))){
					return array($res['error_message'], 'error');
					break;
				}

				$value['error_code'] = $res['error_code'];
				$error_exist = true;
			}

			$value['time'] = time();
			$value['id'] = $speedycache->image['id'];

			if(!empty($value['error_code'])){
				if($value['error_code'] != 8 || ($value['error_code'] == 8 && $key === 0)){
					array_push($meta_optimized, $value);
				}
			}
		}
		
		$percentage = self::update_meta($total_reduction, $meta_optimized);

		return array('Image has been optimized', 'success', $speedycache->image['id'], $percentage, $total_reduction);
	}

	static function update_meta($total_reduction, $meta_optimized){
		global $speedycache;
		
		if(isset($meta_optimized[0]) && isset($meta_optimized[0]['error_code']) && $meta_optimized[0]['error_code']){

			update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_optimized)));
			update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', 0);

			return 100;
		}

		$percentage = 0;
		$meta_temp = array();
		
		foreach($speedycache->image['images_clone'] as $key => $value){
			$backup_file = $value['file'];
			
			$value['file'] = preg_replace('/.(jpg|jpeg|png|gif)$/', '.webp', $value['file']);
			
			if(!file_exists($value['file']) || !file_exists($backup_file)){
				continue;
			}

			$diff = filesize($backup_file) - filesize($value['file']);
			$diff = $diff > 0 ? $diff : 0;

			$value['destination_path'] = $backup_file;
			$value['reduction'] = $diff;
			$value['time'] = time();
			$value['id'] = $speedycache->image['id'];

			array_push($meta_temp, $value);
		}

		foreach($meta_optimized as $m_key => $m_value){
			if(empty($m_value['error_code'])){
				continue;
			}

			$exist = false;

			for($i=0; $i < count($meta_temp); $i++){
				if($meta_temp['file'] == $m_value['file']){
					$exist = true;
				}
			}

			if(empty($exist)){
				$m_value['destination_path'] = '';
				$m_value['reduction'] = 0;
				$m_value['time'] = time();
				$m_value['id'] = $speedycache->image['id'];

				array_push($meta_temp, $m_value);
			}
		}
		
		if(count($meta_temp) > 0){
			$percentage = count($meta_temp)*100/count($speedycache->image['images_clone']);
		}else{
			$percentage = 0;
		}

		update_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction', $total_reduction);
		update_post_meta($speedycache->image['id'], 'speedycache_optimisation', base64_encode(json_encode($meta_temp)));

		return $percentage;
	}

	static function compress($source_image){
		global $speedycache;

		/*
			Error Codes
			2 = in backup folder parent folder not writable
			3 = no need to optimize
			4 = source is not writable
			5 = destination is not writable
			6 = ImageMagick library is not avaliable
			7 = Error via api
			8 = Source file does not exist
			9 = Image size exceed 5mb limit while processing
		   11 = Empty Name
		   12 = Forbidden
		   13 = CloudFlare to restrict access
		   14 = No Extension
		   15 = Image size is 0Kb
		   16 = Corrupted Image
		   17 = Empty Metadata
		   18 = No Image
		   19 = webp is not saved
		   20 = file size of destination_move_source_path is zero
		   21 = Unacceptable file type
		   22 = Unable to Convert Image using cwebp.
		   23 = The URL of the image has webp extension.
		*/

		// if the url starts with /wp-content
		if(preg_match('/^\/' . SPEEDYCACHE_WP_CONTENT_DIR . '/i', $source_image['url'])){
			$source_image['url'] = home_url().$source_image['url'];
		}

		$source_path = $source_image['file'];
		$res_backup = array('success' => true, 'error_message' => '');
		$webp_path = preg_replace('/.(jpe?g|png|gif)$/', '.webp', $source_path);

		if(strlen($speedycache->image['name']) === 0){
			return array('success' => false, 'error_code' => 11);
		}

		if(!file_exists($source_path)){
			return array('success' => false, 'error_code' => 8);
		}

		if(!pathinfo($source_image['url'], PATHINFO_EXTENSION)){
			return array('success' => false, 'error_code' => 14);
		}

		// If the URL of the image is a webp
		if(pathinfo($source_image['url'], PATHINFO_EXTENSION) == 'webp' && file_exists($webp_path)){
			return array('success' => false, 'error_code' => 23);
		}

		if(@filesize($source_path) > 5000000){
			return array("success" => false, 'error_code' => 9);
		}

		if(!self::allowed_mime($source_path)){
			return array('success' => false, 'error_code' => 21);
		}

		if(!self::path_is_image($source_path)){
			return array('success' => false, 'error_code' => 16);
		}

		if(filesize($source_path) == 0){
			return array('success' => false, 'error_code' => 15);
		}

		if(@rename($source_path, $source_path.'_writabletest')){
			rename($source_path.'_writabletest', $source_path);
		}else{
			return array('success' => false, 'error_message' => $source_path . ' is not writable', 'error_code' => 4);
		}

		$optm_result = self::start_optimization($source_path); // here we need to plugin compression static function
		
		if(empty($optm_result['success'])){
			//NOTE:Place some error Message here.
			return $optm_result;
		}

		if(!file_exists($webp_path)){
			return array('success' => false, 'error_code' => 19, 'error_message' => $webp_path . ' destination_path is not saved');
		}
		
		if(filesize($webp_path) <= 0){
			return array('success' => false, 'error_code' => 20, 'error_message' => $webp_path . ' file size of destination_path is zero');
		}

		$diff = self::compare_sizes($source_path, $webp_path);
		return array('success' => true, 'destination_path' => $webp_path, 'reduction' => $diff);
	}


	static function start_optimization($img){
		global $speedycache;

		switch($speedycache->image['settings']['compression_method']){
			case 'gd': 
				return self::gd_webp($img);
				
			case 'imagick':
				return self::imagick_webp($img);
				
			case 'cwebp':
				if(defined('SPEEDYCACHE_PRO')){					
					return \SpeedyCache\Image::cwebp_convert($img);
				}
				
				return array('success' => false, 'error_message' => 'SpeedyCache cwebp is a Pro feature');
				
			default:
				return array('success' => false,  'error_message' => 'The provided conversion method is not valid');
		}
	}

	static function path_is_image($source_path){
		$size = getimagesize($source_path);

		if(empty($size)){
			return false;
		}

		return true;
	}

	static function get_quality($img){
		$dimensions = $img->getImageGeometry();
		
		if($dimensions['width'] < 200 && $dimensions['height'] < 200){
			return 85;
		}

		return 90;
	}

	static function compare_sizes($source_path, $destination_path){
		$diff = filesize($source_path) - filesize($destination_path);

		return ($diff > 0) ? $diff : 1;
	}


	//TODO:: Will need it when we will add non webp compression
	static function create_backup_folder($destination_path){
		global $speedycache;
		
		$destination_path = str_replace($speedycache->image['upload_dir']['basedir'], '', $destination_path);
		$path_arr = explode('/', $destination_path);

		$path = $speedycache->image['upload_dir']['basedir'];

		for ($i=1; $i < count($path_arr) - 1; $i++){
			$parent_path = $path;
			$path = $path.'/'.$path_arr[$i];

			if(is_dir($path)){
				continue;
			}
			
			if(@mkdir($path, 0755, true)){
				//
			}else{
				//warning
				if($path_arr[$i] == 'speedycache-backup'){
					//toDO: to stop cron job and warn the user
				}

				return array('success' => false, 'error_message' => $parent_path.' is not writable', 'error_code' => 2);
			}
		}

		return array('success' => true, 'error_message' => '');
	}

	static function set_id($id = null){
		global $speedycache;
		
		$get_id = speedycache_optget('id');
		
		if(!empty($get_id)){
			$speedycache->image['id'] = intval($get_id);
		}elseif(!empty($id)){
			$speedycache->image['id'] = intval($id);
		}else{
			$speedycache->image['id'] = self::get_first_id();
		}
	}

	static function set_images(){
		global $speedycache;
		
		if(empty($speedycache->image['metadata']['file'])){
			return;
		}

		$arr = array(
			'file' => $speedycache->image['upload_dir']['basedir'].'/'.$speedycache->image['metadata']['file'],
			'url' => $speedycache->image['upload_dir']['baseurl'].'/'.$speedycache->image['metadata']['file'],
			'width' => $speedycache->image['metadata']['width'],
			'height' => $speedycache->image['metadata']['height'],
			'mime_type' => ''
		);
		
		array_push($speedycache->image['images'], $arr);

		$i = 0;
		$image_error = false;

		if(!is_array($speedycache->image['metadata']['sizes'])){
			if(empty($image_error)){
				self::not_in_metadata();
			}
		}

		foreach((array)$speedycache->image['metadata']['sizes'] as $key => $value){
			$value['url'] = $speedycache->image['url'].$value['file'];
			$value['file'] = $speedycache->image['path'].$value['file'];
			$value['mime_type'] = isset($value['mime-type']) ? $value['mime-type'] : '';

			unset($value['mime-type']);

			if($i == 0){
				if(self::not_found(self::get_correct_url($speedycache->image['upload_dir']['baseurl'].'/'.$speedycache->image['metadata']['file']))){
					$image_error = true;
					break;
				}
			}

			if(!self::not_found(self::get_correct_url($value['url'])) && self::allowed_mime($value['file'])){
				array_push($speedycache->image['images'], $value);
			}

			$i++;
		}

		if(empty($image_error)){
			self::not_in_metadata();
		}
	}

	static function get_correct_url($path){
		if(preg_match('/^\/'.SPEEDYCACHE_WP_CONTENT_DIR.'/i', $path)){
			
			// content_url() must return HTTP but it return /wp-content so we need to check
			if(content_url() == '/'.SPEEDYCACHE_WP_CONTENT_DIR && home_url() == site_url()){
				$path = home_url().$path;
			}
		}

		return $path;
	}

	static function not_in_metadata(){
		global $speedycache;
		
		$paths = array();

		foreach($speedycache->image['images'] as $key => $value){
			array_push($paths, $value['file']);
		}
		
		$files = glob($speedycache->image['path'].$speedycache->image['name'].'-'.'*');

		foreach((array)$files as $file){
			if(@filesize($file) > 1000000){
				continue;
			}

			if(!preg_match('/\.(jpg|jpeg|jpe|png|gif)$/i', $file)){
				continue;
			}

			$exp_dos = explode('/',$file);
			$basename = end($exp_dos);

			if(in_array($file, $paths)){
				continue;
			}
			
			if(!preg_match('/'.preg_quote($speedycache->image['name'], '/').'-(\d+)x(\d+)\..+/', $basename, $dimensions)){
				continue;
			}
			
			$value = array(
				'url' => $speedycache->image['url'].$basename,
				'file' => $file,
				'width' => $dimensions[1],
				'height' => $dimensions[2],
			);

			if(!self::not_found($value['url'])){
				array_push($speedycache->image['images'], $value);
			}
		}
	}

	static function set_path(){
		global $speedycache;
		
		$speedycache->image['path'] = $speedycache->image['upload_dir']['basedir'].'/'.preg_replace('/'.preg_quote($speedycache->image['name'], '/').'.+/', '', $speedycache->image['metadata']['file']);
	}

	static function set_url(){
		global $speedycache;
		
		$speedycache->image['url'] = $speedycache->image['upload_dir']['baseurl'].'/'.preg_replace('/'.preg_quote($speedycache->image['name'], '/').'.+/', '', $speedycache->image['metadata']['file']);
	}

	static function set_name(){
		global $speedycache;
		
		if(empty($speedycache->image['metadata'])){
			return;
		}

		if(isset($speedycache->image['metadata']['sizes']) && count($speedycache->image['metadata']['sizes']) > 0){
			$array_values = array_values($speedycache->image['metadata']['sizes']);
			$speedycache->image['name'] = preg_replace('/-'.$array_values[0]['width'].'x'.$array_values[0]['height'].'.+/', '', $array_values[0]['file']);

			if(!$speedycache->image['name']){
				$speedycache->image['name'] = substr($speedycache->image['metadata']['file'], strrpos($speedycache->image['metadata']['file'], '/') + 1);
			}
			
			return;
		}

		$info = pathinfo($speedycache->image['metadata']['file']);
		$speedycache->image['name'] =  basename($speedycache->image['metadata']['file'],'.'.$info['extension']);

		//$this->name = substr($this->metadata['file'], strrpos($this->metadata['file'], '/') + 1);
	}

	static function set_meta_data(){
		global $speedycache;
		
		$speedycache->image['metadata'] = wp_get_attachment_metadata($speedycache->image['id']);
	}

	//to get last image which is not optimized
	static function get_first_id(){

		$query_image = new \WP_Query(array(
			'order' => 'DESC',
			'orderby' => 'ID',
			'post_type' => 'attachment', 
			'post_mime_type' => 'image/jpeg, image/png, image/gif', 
			'post_status' => 'inherit',
			'posts_per_page' => 1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'NOT EXISTS'
				),
				array(
					'key' => '_wp_attachment_metadata',
					'compare' => 'EXISTS'
				)
			)
		));

		return count($query_image->posts) == 1 ? $query_image->posts[0]->ID : false;
	}

	static function statics_data(){
		$res = array(
			'total_image_number' => self::image_count(),
			'error' => self::error_count(),
			'optimized' => self::optimized_file_count(),
			'uncompressed' => self::uncompressed_count(),
			'reduction' => self::total_reduction(),
			'percent' => 0,
		);

		if($res['optimized'] > 0){
			$res['percent'] = ($res['optimized'] - $res['error']) * 100/$res['optimized'];
		}else{
			$res['percent'] = 0;
		}
		
		$res['percent'] = number_format($res['percent'], 2);
		$res['reduction'] = $res['reduction'];
		
		return $res;
	}

	static function revert_all(){
		global $speedycache;
		
		if(!current_user_can('manage_options')){
			wp_die('Must Be admin');
		}

		$images = new \WP_Query(array(
			'order' => 'DESC',
			'orderby' => 'ID',
			'post_type' => 'attachment',
			'post_mime_type' => array('image/jpeg', 'image/png', 'image/gif'),
			'post_status' => 'inherit',
			'posts_per_page' => -1,
			'meta_query' => array(
				array(
					'key' => 'speedycache_optimisation',
					'compare' => 'EXISTS'
				)
			)
		));

		$failed = true;
		
		if(count($images->posts) <= 100){
			
			if($images->posts && count($images->posts) > 0){
				foreach($images->posts as $key => $post){
					$speedycache->image['id'] = $post->ID;
					$result = self::revert();
					
					if($result['success'] === true){
						$failed = false;
					}
				}
			}
			
			if(!empty($failed)){
				wp_send_json(array('success' => false, 'message' => __('Files can\'t be reverted', 'speedycache'))); 
			}
			
			wp_send_json(array('success' => true));
		}

		$schedule_posts = [];
		foreach($images->posts as $key => $post){
			
			if(100 === count($schedule_posts) || !empty($erase)){
				$schedule_posts = [];
			}

			$erase = false; // Flag to unset the $scheduled_posts
			
			$schedule_posts[] = $post->ID;

			// Check if we have reached 99 and make sure its not the last index
			if(count($schedule_posts) <= 99 && $key !== (count($images->posts) - 1)){
				continue;
			}
			
			// Skip if alredy on schedule list.
			if(wp_next_scheduled('speedycache_img_delete', array($schedule_posts))){
				$erase = true;
				continue;
			}
		
			$scheduled = self::get_optimization_schedule(array('speedycache_img_delete'));
			$time = time();
		
			if(!empty($scheduled) && isset(end($scheduled)['time'])){
				// getting the last index to get the last scheduled event
				$time = end($scheduled)['time'];
			}
			
			$final_schd_time = $time + 10;
		
			if(!wp_next_scheduled('speedycache_img_delete', array($schedule_posts))){
				wp_schedule_single_event($final_schd_time, 'speedycache_img_delete', array($schedule_posts));
				
				continue;
			}
		}

		wp_send_json(array('success' => true));
	}

	// Schedule deletion of image to reduce load on the server at a single time.
	static function scheduled_delete($img_id){
		global $speedycache;
		
		if(empty($img_id)){
			return;
		}

		if(is_scalar($img_id)){
			$speedycache->image['id'] = $img_id;
			self::revert();
			return;
		}
		
		foreach($img_id as $id){
			$speedycache->image['id'] = $id;
			self::revert();
		}
	}

	// Reverts a single image
	static function revert(){
		global $speedycache;
		
		if(empty($speedycache->image['id'])){
			return array('success' => false);
		}
		
		$optimization_data = get_post_meta($speedycache->image['id'], 'speedycache_optimisation', true);

		// optm = optimization
		$optm_json = base64_decode($optimization_data);
		$optm_json = json_decode($optm_json, true);
		
		if(empty($optm_json)){
			return array('success' => false);
		}

		if(!empty($optm_json) && is_array($optm_json) && count($optm_json) == 1 && !empty($optm_json[0])){
			if(!empty($optm_json[0]['error_code']) && $optm_json[0]['error_code'] == 18){
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');

				return array('success' => true);
			}
		}

		$result = false;

		$optm_json = array_reverse($optm_json);
		$error_numbers = 0;
		
		foreach($optm_json as $key => $image){

			if(@!is_writable($image['file'])){
				if(isset($speedycache->image['metadata']['file']) && preg_match('/'.preg_quote($speedycache->image['metadata']['file'], '/').'/', $image['url'])){
					if(file_exists($image['file'])){
						$result = array('success' => true, 'message' => $image['file'].' is not writable');
						break;
					}
					
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
				}
			}

			if(
				!empty($image['url']) && 
				!preg_match('/\.webp$/', $image['url']) && 
				isset($image['destination_path']) && 
				file_exists($image['destination_path']) &&
				(pathinfo($image['destination_path'], PATHINFO_EXTENSION) == 'webp')
			){
				@unlink($image['file']);

				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
				$result = array('success' => true);
				
				continue;
			}

			if(!empty($image['error_code'])){
				if(isset($speedycache->image['metadata']['file']) && preg_match('/'.preg_quote($speedycache->image['metadata']['file'], '/').'/', $image['url'])){
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
					delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
					$result = array('success' => true);
				}else{
					$error_numbers++;

					if($error_numbers == count($optm_json)){
						delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
						delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
						$result = array('success' => true);
					}
				}
				
				continue;
			}

			if(preg_match('/'.preg_quote($speedycache->image['metadata']['file'], '/').'/', $image['url'])){
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation');
				delete_post_meta($speedycache->image['id'], 'speedycache_optimisation_reduction');
				$result = array('success' => true);
			}

		}
		
		return $result;
	}

	static function revert_on_delete($id){
		global $speedycache;
		
		if(!wp_attachment_is_image($id)){
			return;
		}
		
		$speedycache->image['id'] = $id;
		
		self::revert();
	}

	static function get_error_text($id){
		
		//Error Codes
		$errors = array(
			2 => __('In backup folder parent folder not writable', 'speedycache'),
			3 => __('No need to optimize', 'speedycache'),
			4 => __('Source is not writable', 'speedycache'),
			5 => __('Destination is not writable', 'speedycache'),
			6 => __('ImageMagick library is not avaliable', 'speedycache'),
			7 => __('Error via api', 'speedycache'),
			8 => __('Source file does not exist', 'speedycache'),
			9 => __('Image size exceed 20mb limit while processing', 'speedycache'),
		   11 => __('Empty Name', 'speedycache'),
		   12 => __('Forbidden', 'speedycache'),
		   13 => __('CloudFlare to restrict access', 'speedycache'),
		   14 => __('No Extension', 'speedycache'),
		   15 => __('Image size is 0Kb', 'speedycache'),
		   16 => __('Corrupted Image', 'speedycache'),
		   17 => __('Empty metadata', 'speedycache'),
		   18 => __('No Image', 'speedycache'),
		   19 => __('destination_move_source_path is not saved', 'speedycache'),
		   20 => __('file size of destination_move_source_path is zero', 'speedycache'),
		   21 => __('Unacceptable file type', 'speedycache'),
		   23 => __('WEBP create by other tool', 'speedycache'),
		);

		return isset($errors[$id]) ? $errors[$id] : 'Unkown error code';
	}

	// TODO:: Will use it when we will do non-webp compression
	static function backup_folder_exist(){
		global $speedycache;
		
		$backup_folder_path = $speedycache->image['upload_dir']['basedir'].'/speedycache-backup';

		if(is_dir($backup_folder_path)){
			return true;
		}

		if(@mkdir($backup_folder_path, 0755, true)){
			return true;
		}
		return false;

	}

	static function push_main_image($arr){
		if(!isset($arr[0]) || isset($arr[0]->error_code)){
			return $arr;
		}

		$main = clone $arr[0];
		$total_reduction = 0;

		foreach($arr as $std_key => $std_value){
			if(!isset($std_value->error_code)){
				if(isset($std_value->reduction) && $std_value->reduction){
					$total_reduction = $total_reduction + $std_value->reduction;
				}
			}
		}

		$main->reduction = $total_reduction;

		array_unshift($arr, $main);

		return $arr;
	}

	static function list_content($query_images_args = array()){
		global $speedycache;
		
		remove_filter('posts_fields', '\SpeedyCache\Image::count_posts_fields'); //was causing bug
		
		$query_image = new \WP_Query( $query_images_args );
		$return_output = '';
		
		if(empty($query_image->posts) || count($query_image->posts) <= 0){
			return self::get_empty_row();
		}
		
		$count = 0;
		foreach($query_image->posts as $key => $post){
			$count++;
			$value_json = get_post_meta($post->ID, 'speedycache_optimisation', true);
			$tmpvalue_json = base64_decode($value_json);
			
			$std = json_decode($tmpvalue_json);

			$revert = true;

			$std = self::push_main_image($std);
			
			foreach($std as $std_key => $std_value){
				
				$content = ($std_key === 0) ? self::get_row() : self::get_child_row();

				if(empty($content)){
					continue;
				}

				$std_value->destination_path = isset($std_value->destination_path) ? $std_value->destination_path : '';
				$std_value->reduction = isset($std_value->reduction) ? $std_value->reduction : 0;
				
				if($std_key === 0 && $revert){
					$revert_button = '';
				}else{
					$revert_button = 'display:none;';
				}

				if(isset($std_value->error_code) && $std_value->error_code == 8){
					$revert_button = 'display:none;';
				}

				if(file_exists($std_value->destination_path)){
					$backup_url = $std_value->url.'?v='.time();
					$backup_title = 'Original Image';
					$backup_error_style = '';
				}else{
					if(isset($std_value->error_code) && $std_value->error_code){
						$backup_url = get_edit_post_link($std_value->id);
						$backup_title = self::get_error_text($std_value->error_code);
						$backup_error_style = 'color: #FF0000;cursor:pointer;font-weight:bold;';
					}else{
						$backup_url = '#';
						$backup_title = '';
						$backup_error_style = '';
					}
				}
				
				$std_value->file = preg_replace('/.(jpg|jpeg|png|gif)$/','.webp', $std_value->file);
				
				if(file_exists($std_value->file)){
					$std_value->url = preg_replace('/.(jpg|jpeg|png|gif)$/','.webp', $std_value->url).'?v='.time();
				}else{
					$std_value->url = SPEEDYCACHE_PRO_URL.'/assets/images/no-image.png';
				}

				$short_code = array(
					'{{post_id}}',
					'{{attachment}}',
					'{{post_title}}',
					'{{url}}',
					'{{width}}',
					'{{height}}',
					'{{reduction}}',
					'{{date}}',
					'{{revert_button}}',
					'{{backup_url}}',
					'{{backup_title}}',
					'{{backup_error_style}}'
				);
				
				$datas = array(
					$std_value->id,
					$std_value->url,
					$post->post_title,
					$std_value->url,
					$std_value->width,
					$std_value->height,
					$std_value->reduction/1000,
					date('d-m-Y <br> H:i:s', $std_value->time),
					$revert_button,
					$backup_url,
					$backup_title,
					$backup_error_style
				);
			
				$return_output .= str_replace($short_code, $datas, $content);
			}
		}
		return $return_output;
	}

	static function allowed_mime($filename){
		global $speedycache;
		
		$mimetype = false;

		if(!file_exists($filename)){
			return false;
		}

		if(function_exists('finfo_open')){
		   $finfo = finfo_open(FILEINFO_MIME_TYPE);
		   $mimetype = finfo_file($finfo, $filename);
		   finfo_close($finfo);
		}else if(function_exists('getimagesize')){
		   $img = getimagesize($filename);
		   $mimetype = $img['mime'];
		}else{
			echo 'not found mime_content_type';
			exit;
		}
		
		if($speedycache->image['settings']['compression_method'] === 'cwebp' && self::gif2webp_exists()){
			if(preg_match('/(jpg|jpeg|jpe|png|gif)/i', $mimetype)){
				return true;
			}
			
			return false;
		}

		if(preg_match('/(jpg|jpeg|jpe|png)/i', $mimetype)){
			return true;
		}
		
		return false;
	}

	// Check if the image is available, the response code should be 200
	static function not_found($url){
		return false;
		
		$res = wp_remote_head($url, array('timeout' => 3 ));

		if(is_wp_error($res)){
			$url_header = @get_headers($url);

			if(preg_match('/200\s+OK/i', $url_header[0])){
				return false;
			}
			
			return true;
		}
		
		if($res['response']['code'] == 200){
			return false;
		}

		return true;
	}

	//Checks if the image is Unique
	static function unique_array($images){
		if(count($images) <= 1){
			return $images;
		}

		$arr = array();
		$images_tmp = array();

		foreach($images as $key => $value){
			if(!in_array($value['file'], $arr)){
				array_push($arr, $value['file']);
				array_push($images_tmp, $value);
			}
		}
		
		return $images_tmp;
	}
	//Template static functions Starts Here

	//Table row for the converted Image
	static function get_row(){
		return '<tr class="alternate author-self status-inherit" post-id="{{post_id}}">
			<td class="column-icon media-icon image-icon">
				<img width="39" height="60" src="{{attachment}}" class="attachment-80x60">
			</td>
			<td class="title column-title">
				<p style="margin-bottom: 0;"><a href="{{url}}" target="_blank">{{post_title}}</a></p>
				<p style="margin-bottom: 0;">
					<a style="{{backup_error_style}}" href="{{backup_url}}" target="_blank"><strong>{{backup_title}}</strong></a>
				</p>
			</td>
			<td class="author column-author speedycache-open-image-details" style="text-align: center;cursor: pointer;">{{reduction}}KB<span class="dashicons dashicons-arrow-down-alt2"></span></td>
			<td class="date column-date" style="text-align: center;">{{date}}</td>
			<td class="date column-date" style="text-align: center;">
			<div class="speedycache-revert" style="{{revert_button}}">
				<input type="hidden" value="{{post_id}}">
			</div>
			</td>
		</tr>';
	}

	//table row for different sizes of image.
	static function get_child_row(){
		
		return '<tr class="alternate author-self status-inherit" post-id="{{post_id}}" post-type="detail" style="display: none; padding-left: 20px;">
			<td class="column-icon media-icon" style="font-size:3.5em; color:#ccc;"><i class="fas fa-image"></i></td>
			<td class="title column-title">
				<p style="margin-bottom: 0;"><a href="{{url}}" target="_blank">{{post_title}}</a></p>
				<p style="margin-bottom: 0;">
					<a style="{{backup_error_style}}" href="{{backup_url}}" target="_blank"><strong>{{backup_title}}</strong></a>
				</p>
				<p style="margin-bottom: 0;">{{width}}x{{height}}</p>
			</td>
			<td class="author column-author" style="text-align: center;">{{reduction}}KB</td>
			<td class="date column-date" style="text-align: center;">{{date}}</td>
			<td class="date column-date" style="text-align: center;">
			</td>
		</tr>';
	}

	//No Image optimized
	static function get_empty_row(){
		return '<tr class="author-self status-inherit">
			<td colspan="4">No image has been optimized yet</td>
		</tr>';

	}

	//Paging for the converted Images Table
	static function paging(){ ?>
		<div class="tablenav bottom" style="padding:5px 16px 5px 19px">
			<div style="float:left;">
				<span class="deleteicon">
					<input type="text" style="height:28px;" placeholder="Search" id="speedycache-image-search-input" class="deletable" value="">
					<span class="cleared"></span>
				</span>
				<input type="submit" class="button action" value="Search" id="speedycache-image-search-button" name="filter_action">
			</div>
			<div style="float:left;padding-left:5px;">
				<select id="speedycache-image-list-filter" class="bulk-action-selector-top">
					<option value="" selected="selected">All</option>
					<option value='error_code'>Errors</option>
				</select>
			</div>
			<div style="float:left;padding-left:5px;">
				<select id="speedycache-image-per-page" class="bulk-action-selector-top">
					<option value="5" selected="selected">5</option>
					<option value="10">10</option>
					<option value="25">25</option>
				</select>
			</div>
			<div class="tablenav-pages">
				<span class="pagination-links">
					<a class="tablenav-pages-navspan button first-page disabled speedycache-image-list-first-page" aria-hidden="true" data-page-action="first-page">«</a>
					<a class="tablenav-pages-navspan button prev-page speedycache-image-list-prev-page" aria-hidden="true" data-page-action="prev-page">‹</a>
					<a class="paging-input"><label class="speedycache-current-page">1</label> / <span class="total-pages speedycache-total-pages">1</span></a>
					<a class="next-page button speedycache-image-list-next-page" data-page-action="next-page">›</a>
					<a class="last-page button speedycache-image-list-last-page" data-page-action="last-page">»</a>
				</span>
			</div>
			<br class="clear">
		</div>
	<?php
	}

	//Settings for Image Optimization
	static function settings(){
		global $speedycache, $speedycache_optm_method; 

		?>
		<div class="speedycache-block">
			<div class="speedycache-block-title"><h2><?php _e('Settings', 'speedycache'); ?></h2></div>
			<form class="speedycache-img-opt-settings">
				<div class="speedycache-option-wrap">
					<label for="speedycache_img_automatic_optm" class="speedycache-custom-checkbox">
						<input type="checkbox" id="speedycache_img_automatic_optm" name="img_automatic_optm" <?php echo (isset($speedycache->image['settings']['automatic_optm']) && $speedycache->image['settings']['automatic_optm']) ? ' checked="true"' : '';?>/>
						<div class="speedycache-input-slider"></div>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Automatic optimization', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Whenever user visits the website and there are images that haven\'t been converted to webp then that image(s) gets converted.', 'speedycache'); ?></span>
					</div>
				</div>
				<div class="speedycache-option-wrap">
					<label for="speedycache_img_on_upload" class="speedycache-custom-checkbox">
						<input type="checkbox" id="speedycache_img_on_upload" name="img_on_upload" <?php echo (isset($speedycache->image['settings']['on_upload']) && $speedycache->image['settings']['on_upload']) ? ' checked="true"' : '';?>/>
						<div class="speedycache-input-slider"></div>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Optimize on Image Upload', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Images will be added to a queue and will optimized after a certain interval to reduce load on the server.', 'speedycache'); ?></span>
					</div>
				</div>
				
				<div class="speedycache-option-wrap">
					<label for="speedycache_img_url_rewrite" class="speedycache-custom-checkbox">
						<input type="checkbox" id="speedycache_img_url_rewrite" name="img_url_rewrite" <?php echo (isset($speedycache->image['settings']['url_rewrite']) && $speedycache->image['settings']['url_rewrite']) ? ' checked="true"' : '';?>/>
						<div class="speedycache-input-slider"></div>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Rewrite Image URL\'s', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Rewrites the url of the image on the page to the webp version if webp version is avaliable.', 'speedycache'); ?></span>
					</div>
				</div>

				<div class="speedycache-option-wrap">
					<label for="speedycache_img_quality">
						<input type="number" id="speedycache_img_quality" name="img_compression_quality" value="<?php echo esc_attr($speedycache->image['settings']['compression_quality']);?>" min="50" step="5" max="90"/>
					</label>
					<div class="speedycache-option-info">
						<span class="speedycache-option-name"><?php esc_html_e('Compression Quality', 'speedycache'); ?></span>
						<span class="speedycache-option-desc"><?php esc_html_e('Higher the number higher will be the converted image quality in webp', 'speedycache'); ?></span>
					</div>
				</div>
				
				<div class="speedycache-block-title" style="flex-direction:column">
					<h4><?php esc_html_e('Conversion Methods', 'speedycache'); ?></h4>
					<p style="display:block; font-family: monospace; background-color: #f2f2f2; border-radius:6px; padding:10px;"><span style="color:var(--speedycache-red); font-weight:bold;"><i class="fas fa-exclamation"></i> Note:</span><?php esc_html_e('Only cwebp supports gif conversions to webp. But when you upload an image to WordPress whether it be a jpg, png, or gif format, WordPress creates different sizes of that image on upload so, in the process of resizing some resized version of gifs may lose their animation.', 'speedycache'); ?>
				</div>
				<?php foreach($speedycache_optm_method as $m_key => $method){ ?>
					<div class="speedycache-option-wrap <?php echo !$method['status'] ? ' speedycache-disabled-methods' : '' ?>">
						<label for="speedycache-img-<?php echo esc_attr($m_key);?>">
							<input type="radio" value="<?php echo esc_attr($m_key);?>" name="img_compression_method" id="speedycache-img-<?php echo esc_attr($m_key);?>" <?php echo (isset($speedycache->image['settings']['compression_method']) && $speedycache->image['settings']['compression_method'] == $m_key ? ' checked="true"' : '');?> <?php echo !$method['status'] ? ' disabled' : '' ?>/>
						</label>
						<div class="speedycache-option-info">
							<span class="speedycache-option-name"><?php echo esc_html($method['title']); ?></span>
							<span class="speedycache-option-desc"><?php echo esc_html($method['desc']); ?></span>
						</div>
						<?php 
						// TODO:: Need to fix this _e as it is a dynamic value we will need to use sprintf
						if(!$speedycache_optm_method[$m_key]['status']){ ?>
							<div class="speedycache-more-info" data-info="<?php echo esc_html($speedycache_optm_method[$m_key]['message']);?>" >
								<i class="fas fa-question-circle"></i>
							</div>
						<?php } ?>
							<div class="speedycache-img-method-actions">
						<?php 
						
						if($m_key == 'cwebp'){
							if(defined('SPEEDYCACHE_PRO') && !file_exists(wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_binary'])){
								echo '<button style="margin-right:5px;" class="speedycache-button speedycache-btn-black speedycache-webp-download">Download Binary</button>';
							}
							
							if(defined('SPEEDYCACHE_PRO') && !self::gif2webp_exists()){
								echo '<button class="speedycache-button speedycache-btn-black speedycache-webp-download" style="margin-top:2px;" data-type="gif">Download Binary for GIF</button>';
							}
						}
						?>
						</div>
					</div>	
				<?php } ?>
			</form>
		</div>
	<?php 
	}


	//Image Optimization Stats
	static function statics(){
		$res = self::statics_data();
		$ring_success = 100 - (int)$res['percent'];
		
		$scheduled = self::get_optimization_schedule(array('speedycache_auto_optm', 'speedycache_img_delete'));
		$scheduled_count = count($scheduled);
		
		//the css below is written in one line to make regex replace easy in js update.
	?>
		<style>
			@keyframes donut1 {
			0%{stroke-dasharray: 0, 100;}
			100%{stroke-dasharray: <?php echo esc_attr($res['percent'] .', ' . $ring_success);?>;}
		}
		</style>
		<div class="speedycache-block">
			<div class="speedycache-img-stats speedycache-admin-row">
				<div class="speedycache-is-block speedycache-img-graph">
					<div class="speedycache-card-body">
						<div class="speedycache-img-start-optm">
							<div class="speedycache-img-stat-info">
								<div class="speedycache-img-main-stat">
									<?php esc_html_e('Success', 'speedycache'); ?>
									<span class="speedycache-img-success-per"><?php echo esc_html($res['percent']);?>%</span>
								</div>
								<div class="speedycache-img-main-stat">
									<?php esc_html_e('Error', 'speedycache');?>
									<span class="speedycache-img-error-count" <?php echo $res['error'] > 0 ? 'style="color:#dc3545"' : '' ?>><?php echo esc_html($res['error']);?></span>
								</div>
								<div class="speedycache-img-main-stat">
									<?php esc_html_e('Scheduled', 'speedycache');?>
									<span class="speedycache-scheduled-count <?php echo $scheduled_count > 0 ? 'speedycache-scheduled-count-indicator' : '';?>" setting-id="speedycache-img-scheduled-modal"><?php echo esc_html($scheduled_count);?></span>
								</div>
							</div>
							<div class="speedycache-img-remain-optm">
								<span class="speedycache_img_optm_status" style="background-color:<?php echo $res['uncompressed'] > 0 ? '#EED202' : '#90ee90'?>"></span>
								<span>
								<?php 
									if($res['uncompressed'] > 0){
										echo esc_html($res['uncompressed']) . ' ';
										esc_html_e('Files needed to be optimized', 'speedycache');
									} else {
										esc_html_e('All images are optimized', 'speedycache');
									}	
								?></span>
									
							</div>
							<div class="speedycache-img-optimize-all" style="margin-left:auto;">
								<button class="speedycache-button speedycache-btn-black speedycache-img-optm-btn" setting-id="speedycache-modal-optimize-all"><?php esc_html_e('Optimize All', 'speedycache'); ?></button>
								<button class="speedycache-img-delete-all-conv speedycache-button speedycache-btn-transparent"><?php esc_html_e('Delete all conversions', 'speedycache'); ?></button>
							</div>
						</div>
					</div>
				</div>
		
				<div class="speedycache-is-block speedycache-img-count">
					<div>
						<div class="speedycache-img-opt-stat">
							<div class="speedycache-img-optm-count"><?php echo esc_html($res['optimized'] . '/' . $res['total_image_number']); ?></div>
							<div class="speedycache-img-optm-count-text"><?php echo esc_html_e('Image(s) optimized', 'speedycache'); ?>
							<?php echo esc_html_e('with total reduction of', 'speedycache'); ?> <span class="speedycache-img-reduced-size"><?php echo esc_html($res['reduction'] > 10000 ? round($res['reduction']/1000, 2).'MB' : $res['reduction'].'KB');?></span></div>
						</div>
					</div>
				</div>
			</div>
		</div>
		
		<div modal-id="speedycache-img-scheduled-modal" class="speedycache-modal">
			<div class="speedycache-modal-wrap">
				<div class="speedycache-modal-header">
					<div><?php esc_html_e('Scheduled Tasks', 'speedycache'); ?></div>
					<div title="Close Modal" class="speedycache-close-modal">
						<span class="dashicons dashicons-no"></span>
					</div>
				</div>
				<div class="speedycache-modal-content speedycache-info-modal">
					<?php if($scheduled_count < 1){ ?>
						<span><?php esc_html_e('No Image Scheduled', 'speedycache'); ?></span>
					<?php } else { ?>
					<!--<p style="text-align:center;"><?php //_e('Time Interval of the Schedule is 1 minute', 'speedycache');?></p>-->
					<table style="margin:auto; width: 100%;">
						<thead>
							<tr>
								<th class="speedycache-table-hitem" scope="col"><?php esc_html_e('Image', 'speedycache'); ?></th>
								<th class="speedycache-table-hitem" scope="col"><?php esc_html_e('Time', 'speedycache'); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php
							foreach($scheduled as $key => $schedule){

								$time = $schedule['time'] - time();

								$time_str = 'in '.$time. ' seconds';
								
								if($time > 59){
									$time_str = 'in '. round($time/60, 1) . ' minute(s)';
								} else if($time <= 0){
									$time_str = 'now';
								}
								?>
							<tr>
								<td class="speedycache-table-item"><?php echo esc_html('Batch ' . ($key + 1)); ?></td>
								<td class="speedycache-table-item" style="text-align:right;"><?php echo esc_html($time_str);?> <i class="fas fa-stopwatch"></i></td>
							</tr>
							<?php } ?>
							
						</tbody>
					</table>
					<?php } ?>
				</div>
			</div>
		</div>
		
		<div modal-id="speedycache-modal-all-img-revert" class="speedycache-modal">
			<div class="speedycache-modal-wrap">
				<div class="speedycache-modal-content">
					<i class="fas fa-info-circle"></i>
					<h1><?php esc_html_e('Revert All Images!', 'speedycache'); ?></h1>
					<p><?php esc_html_e('Once deleted the changes won\'t be reversible.', 'speedycache'); ?></p>
					<div class="speedycache-modal-db-actions">
						<button class="speedycache-btn speedycache-db-confirm-yes"><?php esc_html_e('Yes', 'speedycache'); ?></button>
						<button class="speedycache-btn speedycache-db-confirm-no"><?php esc_html_e('No', 'speedycache'); ?></button>
					</div>
				</div>
			</div>
		</div>
	<?php
	}
	//Templates Ends here

	//Need to create logs for Automatic Optimization
	static function log(){
		
	}

	static function compression_method_checks(){
		global $speedycache, $speedycache_optm_method;
		
		$gd = self::gd_check();
		$speedycache_optm_method['gd'] = array_merge($speedycache_optm_method['gd'], $gd);
		
		if(!$speedycache_optm_method['gd']['status']){
			$speedycache->image['disabled_method']++;
			self::change_method_if_not_available('gd');
		}
		
		$imagick = self::imagick_check();
		$speedycache_optm_method['imagick'] = array_merge($speedycache_optm_method['imagick'], $imagick);
		
		if(!$speedycache_optm_method['imagick']['status']){
			$speedycache->image['disabled_method']++;
			self::change_method_if_not_available('imagick');
		}
		
		$cwebp = self::cwebp_check();
		$speedycache_optm_method['cwebp'] = array_merge($speedycache_optm_method['cwebp'], $cwebp);
		
		if(!$speedycache_optm_method['cwebp']['status']){
			$speedycache->image['disabled_method']++;
			self::change_method_if_not_available('cwebp');
		}
	}

	// GD static function Starts here
	static function gd_check(){
		if(!extension_loaded('gd')){
			return array('status' => false, 'message' => 'You dont have GD PHP extension');
		}

		if(isset(gd_info()['WebP Support']) && !gd_info()['WebP Support']){
			return array('status' => false, 'message' => 'GD extension on your server dosen\'t support WEBP');
		}
		
		if(isset(gd_info()['WebP Support']) && gd_info()['WebP Support']){
			return array('status' => true, 'message' => 'Operational');
		}
	}

	static function gd_webp($file){
		global $speedycache, $speedycache_optm_method;

		if(isset($speedycache_optm_method['gd']['status']) && !$speedycache_optm_method['gd']['status']){
			return array('success' => false, 'error_message' => $speedycache_optm_method['gd']['message']);
		}
		
		$image_size = getimagesize($file);
		$width = $image_size[0];
		$height = $image_size[1];
		
		switch($image_size['mime']){
			case 'image/jpg':
			case 'image/jpeg':
				$source = imagecreatefromjpeg($file);
				break;
			
			case 'image/png':
				$source = imagecreatefrompng($file);
				break;
				
			case 'image/webp': 
				return array('success' => false, 'error_message' => 'File is alredy a WEBP file');
				
			default:
				return array('success' => false, 'error_message' => 'File has unsupported mime'.$image_size['mime']);
		}
		
		if(empty($source)){
			return false;
		}
		
		$dst = imagecreatetruecolor($width, $height);
		
		if(imagealphablending($dst, false) !== false){
			//change the RGB values if you need, but leave alpha at 127
			$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);

			if($transparent !== false){
				//simpler than flood fill
				if(imagefilledrectangle($dst, 0, 0, $width, $height, $transparent) !== false){
					//restore default blending
					if(imagealphablending($dst, true) !== false){
						if(imagecopy($dst, $source, 0, 0, 0, 0, $width, $height) !== false){
							$success = true;
						}
					};
				}
			}
		}
		
		if(!$success){
			return array('success' => false, 'error_message' => 'Couldn\'t convert the given image.');
		}
		
		$webp_path = preg_replace('/.(jpe?g|png)$/', '.webp', $file);
		
		imagedestroy($source);
		imagewebp($dst, $webp_path, $speedycache->image['settings']['compression_quality']);
		imagedestroy($dst);
		
		if(!file_exists($webp_path)){
			return array('url' => $webp_path, 'success' => true, 'error_message' => 19);
		}

		return array(
			'url' => $webp_path,
			'success' => true,
			'error_message' => ''
		);
	}
	//GD Ends Here

	//Imagick static functions
	static function imagick_check(){
		
		if(!extension_loaded('imagick')){
			return array('status' => false, 'message' => 'Imagick extension isn\'t installed');
		}
		
		$image = new \Imagick();
		
		if(!in_array('WEBP', $image->queryFormats('WEBP'))){
			$image->clear();
			$image->destroy();
		
			return array('status' => false, 'message' => 'Imagick installed on your system is without WEBP support');
		}
		
		return array('status' => true, 'message' => 'Operational');
	}

	static function change_method_if_not_available($m_name){
		global $speedycache, $speedycache_optm_method;
		
		if($speedycache->image['settings']['compression_method'] != $m_name){
			return;
		}
		
		$valid_method = '';
		
		foreach($speedycache_optm_method as $key => $method){
			if($key == $m_name){
				continue;
			}
			
			if(!empty($method['status'])){
				$speedycache->image['settings']['compression_method'] = $key;
				return;
			}
		}

		$speedycache->image['settings']['compression_method'] = $valid_method;
	}

	//Conversion of image to webp
	static function imagick_webp($file){
		global $speedycache, $speedycache_optm_method;
		
		if(isset($speedycache_optm_method['imagick']['status']) && !$speedycache_optm_method['imagick']['status']){
			return array('success' => false, 'error_message' => $speedycache_optm_method['imagick']['message']);
		}
		
		$dest = preg_replace('/.(png|jpe?g)$/', '.webp', $file);
		
		$image = new \Imagick();
		$image->readImage($file);
		$image->setImageCompressionQuality($speedycache->image['settings']['compression_quality']);
		$image->setImageFormat('WEBP');
		
		if($image->writeImage($dest)){
			$image->clear();
			$image->destroy();
			
			return array('success' => true, 'error_message' => '');
		}
		
		$image->clear();
		$image->destroy();
		
		return array('success' => false, 'error_message' => 'File didn\'t got saved');
	}

	//cwebp static functions
	static function cwebp_check(){
		global $speedycache;
		
		if(!defined('SPEEDYCACHE_PRO')){
			return array('status' => false, 'message' => 'cwebp is a SPEEDYCACHE PRO feature.');
		}
		
		if(!function_exists('exec')){
			return array('status' => false, 'message' => 'You dont have access to exec static function hence you cant use cWebP for Image optimizations');
		}
		
		if(isset($speedycache->image['cwebp_binary'])){
			
			if(!file_exists(wp_upload_dir()['basedir'].'/speedycache-binary/'.$speedycache->image['cwebp_binary'])){
				return array('status' => false, 'message' => 'You don\'t have the cwebp Binary on your server.', 'downloaded' => false);
			} 
		}
		
		return array('status' => true, 'message' => 'Operational');
	}

	static function rewrite_url_to_webp($content){
		if(strpos(speedycache_optserver('HTTP_ACCEPT'), 'image/webp') < 0){
			return $content;
		}
		
		if( ! preg_match_all( '/<img\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ){
			return $content;
		}
		
		foreach($matches as $match){
			///(?i)(https?:\/\/|www.|\w+\.(png|jpe?g)$)[^\s]+/
			preg_match_all('/https?:\/(\/[^\/]+)+\.(?:jpe?g|png|gif)/', $match[0], $urls, PREG_SET_ORDER); 
			
			foreach($urls as $url){
				$file_url = preg_replace('/.(jpe?g|png|gif)$/', '.webp', $url[0]);
				
				$file_path = explode(SPEEDYCACHE_WP_CONTENT_DIR.'/uploads', $file_url);

				if(!isset($file_path[1]) || !file_exists(wp_upload_dir()['basedir'].$file_path[1])){
					continue;
				}
				
				$content = str_replace($url[0], $file_url, $content);
			}
		
		}
		
		return $content;
	}

	//Adding wp event for automatic optm on image upload
	static function convert_on_upload($id){
		global $speedycache;

		if(!$speedycache->image['settings']['on_upload']){
			return;
		}
		
		if(!wp_attachment_is_image($id)){
			return;
		}
		
		$scheduled = self::get_optimization_schedule(array('speedycache_auto_optm'));
		$time = time();
		
		if(!empty($scheduled) && isset(end($scheduled)['time'])){
			$time = end($scheduled)['time'];
		}
		
		// Convert after 5 minutes of upload
		if(!wp_next_scheduled('speedycache_auto_optm', array($id))){
			wp_schedule_single_event($time + 300, 'speedycache_auto_optm', array($id));
			return;
		}
	}

	//Optimizing image on Upload
	static function auto_optimize($img_id){
		self::optimize_single($img_id);
	}

	//Whenever user visits a page and there are images that dont have a webp versions then those images are set to be converted.
	static function optimize_on_fly($content){
		global $wpdb, $speedycache;

		//Sitepad dosen't have this static function.
		if(function_exists('wp_filter_content_tags')){
			$content = wp_filter_content_tags($content);
		}

		if(!preg_match_all('/<img\s[^>]+>|background:\s*url\(["\']?(.*?)["\']?\)/i', $content, $matches, PREG_SET_ORDER)){
			return $content;
		}

		foreach($matches as $match){
			// pl-image{post-id} will work only after Pagelayer 1.9.0
			if(!preg_match('/(?:wp|pl)-image-([\d]+)/i', $match[0], $post_id)){
				/*
				* This is for compatibility with other editors and for inline css background url
				* what we do here is look for either img src url or background:url()
				* Then we attempt to get id from the URL.
				*/
				//<img(?:[^>]|[^\/>]).*src[\s*]?=[\s*]?"(.+?)" just in case the one used causes bugs
				if(strpos($match[0], 'background:url') === FALSE && !preg_match('/<img.*?src="(.*?)"/', $match[0], $url)){
					continue;
				}
				
				if(strpos($match[0], 'background:url') !== FALSE){
					$image_url = sanitize_url($match[1]);
				} else {
					$image_url = sanitize_url($url[1]);
				}

				$post_id = (int) attachment_url_to_postid($image_url);
				
				if(empty($post_id)){
					$file = basename($image_url);
					$like = '%'.$wpdb->esc_like($file) .'%';
					$query = $wpdb->prepare("SELECT `post_id` FROM `".$wpdb->prefix."postmeta` WHERE `meta_value` LIKE %s", $like);
					$post_id = (int) $wpdb->get_var($query);
				}

				if(empty($post_id)){
					continue;
				}
			}
		
			if(empty($post_id)){
				continue;
			}
			
			// If we captured post id through wp-image|pl-image
			if(is_array($post_id) && isset($post_id[1])){
				$post_id = intval($post_id[1]);
			}

			// If the image is already scheduled for optimization then just skip it.
			if(wp_next_scheduled('speedycache_auto_optm', array($post_id))){
				continue;
			}
			
			if(!get_post($post_id)){
				continue;
			}

			$optimized = (int) $wpdb->get_var($wpdb->prepare("SELECT count(`meta_key`) as optimized FROM `".$wpdb->prefix."postmeta` WHERE `meta_key`= 'speedycache_optimisation' AND `post_id`=%d", $post_id));
			
			if($optimized > 0){
				continue;
			}
			
			$scheduled = self::get_optimization_schedule(array('speedycache_auto_optm'));
			$time = time();
		
			if(!empty($scheduled) && isset(end($scheduled)['time'])){
				// getting the last index to get the last scheduled event
				$time = end($scheduled)['time'];
			}
			
			$final_schd_time = $time + 60;
		
			if(!wp_next_scheduled('speedycache_auto_optm', array($post_id))){
				wp_schedule_single_event($final_schd_time, 'speedycache_auto_optm', array($post_id));
				
				continue;
			}
		}

		return $content;
	}

	// Returns an array of cron event "speedycache_auto_optm"
	static function get_optimization_schedule($event_name){
		$cron = _get_cron_array();
		
		if(empty($cron)){
			return false;
		}
		
		$scheduled = array();
		
		foreach($cron as $key => $crn){
			foreach($crn as $e_key => $event){
				if(!in_array($e_key, $event_name)){
					continue;
				}

				foreach($event as $evt){
					$args = $evt['args'][0];
				}
				
				array_push($scheduled, array('name' => get_the_title($args), 'time' => $key));
			}
		}
		
		return $scheduled;
	}

	static function gif2webp_exists(){
		global $speedycache;
		
		if(file_exists(wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_gif'])){
			return true;
		}
		
		return false;
	}
	
	static function download_cwebp(){
		global $speedycache;

		check_ajax_referer('speedycache_ajax_nonce', 'security');
		
		$binary_name = $speedycache->image['cwebp_binary'];
		
		$type = speedycache_optget('type');
		
		switch($type){
			case 'gif':
				$binary_name = $speedycache->image['cwebp_gif'];
				break;
				
			case 'cwebp':
				$binary_name = $speedycache->image['cwebp_binary'];
				break;
				
			default:
				return;
		}
		
		$binary_path = wp_upload_dir()['basedir'].'/speedycache-binary';
		
		if(!file_exists($binary_path)){
			@mkdir($binary_path);
		}
		
		//If The binary alredy exists on the server
		if(file_exists($binary_path.'/'.$binary_name)){
			wp_send_json(array('success' => false, 'error_message' => 'Binary Exists already.'));
		}
		
		$resp = wp_remote_get(SPEEDYCACHE_API.'/files/cwebp/'.$binary_name);
		$json = wp_remote_get(SPEEDYCACHE_API.'/files/hash.json');
		
		$hash = json_decode($json['body'], true);
		$file = $resp['body'];
		
		if(!$hash){
			wp_send_json(array('success' => false, 'error_message' => 'Unable to verify the downloaded binary.'));
		}
		
		if(!$file){
			wp_send_json(array('success' => false, 'error_message' => 'Could not download the file please try again later.'));
		}
		
		$binary_file = $binary_path.'/'.$binary_name;
		
		file_put_contents($binary_file, $file);
		
		if(!file_exists($binary_file)){
			wp_send_json(array('success' => false, 'error_message' => 'There was issue downloading the binary.'));
		}
		
		if(hash_file('md5', $binary_file) != $hash[$binary_name]){
			@unlink($binary_path.'/'.$binary_name);
			wp_send_json(array('success' => false, 'error_message' => 'Hash of the file downloaded didn\'t match'));
		}
			
		@chmod($binary_file, 0755);
		
		$output = null;
		$res = null;
		
		if(!function_exists('exec')){
			wp_send_json(array('success' => false, 'error_message' => 'Your server dosen\'t supports exec'));
		}
		
		$exec_name = $type === 'gif' ? 'gf2webp' : 'cwebp';
		
		/*
		* To check if the binary is supported by the server.
		*/
		exec('"'.$binary_file.'"  '.$exec_name.' -version 2>&1', $output, $res);
		
		if($res != 0){
			wp_send_json(array('success' => false, 'error_messsage' => 'The binary for cwebp isn\'t supported by your server'));
		}
		
		if($type = 'gif'){
			$speedycache->image['cwebp_gif'] = $binary_name;
		} else {
			$speedycache->image['cwebp_binary'] = $binary_name;
		}
		
		wp_send_json(array('success' => true));
	}

	static function cwebp_convert($file){
		global $speedycache, $speedycache_optm_method;
		
		if(isset($speedycache_optm_method['cwebp']['status']) && !$speedycache_optm_method['cwebp']['status']){
			return array('success' => false, 'error_message' => $speedycache_optm_method['cwebp']['message']);
		}
			
		$mime = mime_content_type($file);
		
		if($mime == 'image/gif'){
			$binary_path = wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_gif'];
			$binary_name = 'gif2webp';
		} else {
			$binary_path = wp_upload_dir()['basedir']. '/speedycache-binary/'.$speedycache->image['cwebp_binary'];
			$binary_name = 'cwebp';
		}
		
		$output_file = preg_replace('/.(jpe?g|png|gif)$/', '.webp', $file);
		

		$res = null;
		$output = null;
		
		if(!file_exists($binary_path)){
			return array('success' => false, 'error_message' => 'The binary to use cwebp not found');
		}
		
		/*
		*	-- Use "" around the paths in exec, as without "" can cause a bug on some servers installs. 
		*	-- The Structure of the command below is :- 
		*	"path_of_binary" cwebp -q [quality_in_int] "original_file_path" -o "output_file.webp"
		*	-- 2>&1 is used to redirect stderr to same place as stdout
		*	https://www.brianstorti.com/understanding-shell-script-idiom-redirect/
		*/
		exec('"'.$binary_path.'" '.$binary_name.' -q '.$speedycache->image['settings']['compression_quality'].' "'.$file. '" -o "'. $output_file. '" 2>&1', $output, $res);
		
		if($res != 0){
			return array('success' => false, 'error_message' => 'Couldn\'t convert the given image using cwebp.', 'error_code' => 22);
		}
		
		return array('success' => true, 'error_message' => '', 'dest' => $output_file);
	}
	
	static function list_image_html(){
	?>
	<div id="speedycache-image-list">
		<?php \SpeedyCache\Image::paging(); ?>
		<div style="width:100%; overflow-x:auto;">
			<table class="wp-list-table widefat fixed media" style="width: 95%; margin-left: 20px;">
				<thead>
					<tr style="height: 35px;">
						<th scope="col" id="icon" class="manage-column column-icon" style=""></th>
						<th scope="col" id="title" class="manage-column column-title sortable desc" style="width: 323px;">
							<span style="padding-left: 8px;"><?php esc_html_e('File Name', 'speedycache'); ?></span>
						</th>
						<th scope="col" id="author" class="manage-column column-author sortable desc" style="width: 120px;text-align: center;">
							<span><?php esc_html_e('Reduction', 'speedycache'); ?></span>
						</th>
						<th scope="col" id="date" class="manage-column column-date sortable asc" style="width: 91px;text-align: center;">
							<span><?php esc_html_e('Date', 'speedycache'); ?></span>
						</th>
						<th scope="col" id="date" class="manage-column column-date sortable asc" style="width: 60px;text-align: center;">
							<span><?php esc_html_e('Revert', 'speedycache'); ?></span>
						</th>	
					</tr>
				</thead>
				<tbody id="the-list">
					<?php 
						$query_images_args = array();

						$query_images_args['order'] = 'DESC';
						$query_images_args['orderby'] = 'ID';
						$query_images_args['post_type'] = 'attachment';
						$query_images_args['post_mime_type'] = array('image/jpeg', 'image/png', 'image/gif');
						$query_images_args['post_status'] = 'inherit';
						$query_images_args['posts_per_page'] = 5;
						$query_images_args['meta_query'] = array(
							array(
								'key' => 'speedycache_optimisation',
								'compare' => 'EXISTS'
							)
						);

						echo \SpeedyCache\Image::list_content($query_images_args);
					?>
				</tbody>
			</table>
		</div>
	</div>
	<?php 
	}

}

main/index.html000064400000000133151526423640007472 0ustar00<h1>Powered By SpeedyCache</h1>
Go to <a href="https://speedycache.com">SpeedyCache.Com</a>main/criticalcss.php000064400000022373151526423640010523 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('Hacking Attempt');
}

class CriticalCss extends CommonCss{

	static function generate($urls){
		global $speedycache;

		$time = time() + 50;
		set_time_limit(60);
		
		$api = self::get_endpoint();
		
		if(empty($urls)){
			self::log('speedycache_ccss_logs', 'URL not found');
			return false;
		}

		if(empty($speedycache->license['license'])){
			self::log('speedycache_ccss_logs', 'License Not found, please link your License');
			return false;
		}

		$path = speedycache_cache_path('critical-css/');
		$error = ''; // To hold errors when single Critical CSS is generated
		$attempted_url = []; // Keeping track of URL that have been proccessed to generate CriticalCSS to handle in case of Timeout

		if(!is_dir($path)){
			mkdir($path);
			touch($path . 'index.html');
		}

		foreach($urls as $url){
			// Handeling php timeout here
			if($time < time()){
				$urls = array_diff($urls, $attempted_url);
				self::schedule($urls);
				return;
			}

			$url = trim($url, '/');
			$license = strpos($speedycache->license['license'], 'SPDFY') !== 0 ? '' : $speedycache->license['license'];
			$attempted_url[] = $url;

			$basename = md5($url);
			$file_name = $path . $basename . '.css';

			$response = wp_remote_post($api, array(
				'timeout' => 30,
				'body' => array(
					'url' => $url,
					'license' => $license,
				),
				'sslverify' => false,
			));

			if(is_wp_error($response)){
				$error = $response->get_error_message();
				self::log('speedycache_ccss_logs', $response->get_error_message(), $url);
				continue;
			}

			$body = json_decode(wp_remote_retrieve_body($response), true);
			
			if(empty($body)){
				$error = __('The response recieved is empty.', 'speedycache');
				self::log('speedycache_ccss_logs', __('The response recieved is empty.', 'speedycache'), $url);
				continue;
			}

			if(empty($body['success'])){
				$error = !empty($body['message']) ? wp_strip_all_tags($body['message']) : __('Unable to extract CriticalCss', 'speedycache');
				self::log('speedycache_ccss_logs', !empty($body['message']) ? wp_strip_all_tags($body['message']) : __('Unable to extract CriticalCss', 'speedycache'), $url);
				continue;
			}

			if(empty($body['css']) || strlen($body['css']) < 20){
				$error = __('Was unable to generate Critical CSS', 'speedycache');
				self::log('speedycache_ccss_logs', __('Was unable to generate Critical CSS', 'speedycache'), $url);
				continue;
			}
			
			if(!is_dir($path)){
				mkdir($path);
			}
			
			file_put_contents($file_name, $body['css']);

			self::update_css($url, $body['css']);
			
			self::log('speedycache_ccss_logs', 'success', $url); //Updates the log on success
			
			if(!empty($error)){
				return $error;
			}

			return true;
		}
	}
	
	// Builds up the list to schedule URLs
	static function get_url_list(){
		global $blog_id;
		
		$pages = get_pages(array('child_of' => 0, 'number' => 9));
		
		if(empty($pages)){
			return false;
		}

		$page_to_crawl = [];

		$url = get_home_url(!empty($blog_id) ? $blog_id : null);
		
		if(!empty($url)){
			$page_to_crawl['home'] = $url;
		}

		foreach($pages as $p){
			$page_to_crawl[$p->ID] = get_page_link($p->ID);
		}

		return $page_to_crawl;
	}
	
	// Adds the generated css and asynchronyses the css includes
	static function update_css($url, $css){
		global $speedycache;
		
		if(empty($url)){
			return false;
		}
		
		if(empty($css) && file_exists(speedycache_cache_path('critical-css/') . md5($url) . '.css')){
			$css = file_get_contents(speedycache_cache_path('critical-css/') . md5($url) . '.css');
		}
		
		if(empty($css)){
			return false;
		}

		$css = '<style id="speedycache-generated-criticalcss">'. "\n". wp_strip_all_tags($css) . '</style>';

		$url = parse_url($url);
		$uri = !empty($url['path']) ?  $url['path'] : '';
		$cache_loc = $uri . '/index.html';

		if(empty($cache_loc)){
			return;
		}
		
		if(!empty($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] === 'SpeedyCacheTest'){
			$cache_path = speedycache_cache_path('test' . $cache_loc);
		} else {
			$cache_path = speedycache_cache_path('all' . $cache_loc);
		}

		$cache_path = rtrim($cache_path, '/');
		
		// For Desktop
		\SpeedyCache\CriticalCss::update_cached($cache_path, $css);

		if(!empty($speedycache->options['mobile_theme']) && $_SERVER['HTTP_USER_AGENT'] !== 'SpeedyCacheTest'){
			$cache_mobile = speedycache_cache_path('mobile-cache' . $cache_loc);
			
			// For Mobile Cache
			if(file_exists($cache_mobile)){
				\SpeedyCache\CriticalCss::update_cached($cache_mobile, $css);
			}	
		}

	}
	
	// Updates the content of the cached file
	static function update_content($content, $css){
		
		if(strpos($content, 'speedycache-generated-criticalcss') !== FALSE){
			$content = preg_replace('/<style id="speedycache-generated-criticalcss">(.*)<\/style>/sU', $css, $content);
		} else{
			$content = preg_replace('#</title>#iU', "</title>\n". $css, $content);
		}

		$content = \SpeedyCache\CriticalCss::make_css_defer($content);
		
		return $content;
	}
	
	/**
	 * This extracts the stylesheet links and convertes them to preload to make them async,
	 * and add the stylesheet links in noscript if js is disabled in some browsers
	 */
	static function make_css_defer($content){
		
		$css_links = '/(?=<link[^>]*\s(rel\s*=\s*[\'"]stylesheet["\']))<link[^>]*\shref\s*=\s*[\'"]([^\'"]+)[\'"](.*)>/iU';
		
		preg_match_all($css_links, $content, $matches, PREG_SET_ORDER, 0);

		if(empty($matches)){
			return $content;
		}
		
		$noscript_wrap = '<noscript>';

		foreach($matches as $tag){
			$preload = str_replace('stylesheet', 'preload', $tag[1]);
			$onload = preg_replace('~' . preg_quote($tag[3], '~') . '~iU', ' as="style" onload="" ' . $tag[3] . '>', $tag[3]);

			$new_tag = str_replace($tag[3] . '>', $onload, $tag[0]);
			$new_tag = str_replace($tag[1], $preload, $new_tag);
			$new_tag = str_replace('onload=""', 'onload="this.onload=null;this.rel=\'stylesheet\'"', $new_tag);
			$new_tag = preg_replace('/(id\s*=\s*[\"\'](?:[^\"\']*)*[\"\'])/i', '', $new_tag);

			$content = str_replace($tag[0], $new_tag, $content);
			
			$noscript_wrap .= $tag[0];
		}
		
		$noscript_wrap .= '</noscript>';
		
		$content = str_replace($noscript_wrap, '', $content);
		
		return str_replace('</body>', $noscript_wrap . '</body>', $content);

	}
	
	static function status_modal(){
		$html = '<!--SpeedyCache Critical CSS Logs Modal Starts Here-->
	<div modal-id="speedycache_critical_css" class="speedycache-modal">
		<div class="speedycache-modal-wrap">
			<div class="speedycache-modal-header">
				<div>'.esc_html__('Critical Cache Logs', 'speedycache').'</div>
				<div title="Close Modal" class="speedycache-close-modal">
					<span class="dashicons dashicons-no"></span>
				</div>
			</div>
			<div class="speedycache-modal-content" style="min-height:50vh;">
				<div class="speedycache-critical-css-status">';
			
			$generate_ccss = get_option('speedycache_ccss_logs', []);
			
			$scheduled = self::get_schedule(array('speedycache_generate_ccss'));
		
			if(!empty($scheduled)){
				$time = 'now';
				if(!empty($scheduled[0]['time']) && ($scheduled[0]['time'] - time()) > 0){
					$time = 'in ' . ($scheduled[0]['time'] - time()) . 's';
				}

				$html .= '<p style="color:rgb(1, 67, 97); background-color: rgb(229, 246, 253); padding: 10px; border-radius: 6px; font-family: monospace;">'. esc_html__('A process has been scheduled and will be executed', 'speedycache'). ' <strong>' . esc_html($time).'</strong></p>';
			}

			if(count($generate_ccss) < 1){
				$html .= '<span>'.esc_html__('No Logs found for CriticalCss', 'speedycache').'</span>';
			} else {
				$html .='<table style="margin:auto; width: 100%;">
					<thead>
						<tr>
							<th class="speedycache-table-hitem" scope="col">'.esc_html__('Time', 'speedycache').'</th>
							<th class="speedycache-table-hitem" scope="col">'. esc_html__('URLs', 'speedycache').'</th>
							<th class="speedycache-table-hitem" scope="col">'. esc_html__('Status', 'speedycache').'</th>
						</tr>
					</thead>
					<tbody>';
					
					$generate_ccss = array_reverse($generate_ccss);
					
					foreach($generate_ccss as $url => $status){
						$parsed_url = wp_parse_url($url);
						$path = !empty($parsed_url['path']) ? $parsed_url['path'] : '/';
						
						if($status['message'] == 'success'){
							$status_html = '<span class="dashicons dashicons-yes-alt" style="color:	#198754;" title="Success"></span>';
						} else {
							$status_html = '<div class="speedycache-tt"><span class="dashicons dashicons-info" style="color:#DC3545;"></span><span class="speedycache-tt-text">'.esc_html($status['message']).'</span></div>';
						}
						
						$html .= '<tr><td class="speedycache-table-item">'.esc_html($status['time']).'</td>
						<td class="speedycache-table-item">'.esc_html($path).'</td>
						<td class="speedycache-table-item" style="text-align:right;">'.wp_kses_post($status_html).'</td></tr>';
					}

				$html .= '</tbody>
				</table>';
			}
			
			$html .= '</div>
		</div>
	</div>
</div>';

		return $html;
	}

}
main/premium.php000064400000000606151526423640007671 0ustar00<?php

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT');
}

global $pagenow;
if(in_array($pagenow, ['post-new.php', 'post.php'], true)){
	add_action('admin_enqueue_scripts', '\SpeedyCache\MetaboxPro::enqueue_scripts');
	add_filter('speedycache_pro_metabox', '\SpeedyCache\MetaboxPro::html', 10, 2);
	add_filter('speedycache_metabox_fields', '\SpeedyCache\MetaboxPro::options');
}main/object-cache-lib.php000064400000025556151526423640011301 0ustar00<?php

if(!defined( 'WPINC' )){
	die();
}

/**
 * Object Cache API
 *
 * @link https://developer.wordpress.org/reference/classes/wp_object_cache/
 *
 * @package WordPress
 * @subpackage Cache
 */

/** WP_Object_Cache class */
require_once $plugin_dir . '/main/objectcache.php';


function wp_cache_init() {
	$GLOBALS['wp_object_cache'] = WP_Object_Cache::get_instance();
}

function wp_cache_add( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->add( $key, $data, $group, (int) $expire );
}

function wp_cache_add_multiple( array $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->add_multiple( $data, $group, $expire );
}

function wp_cache_replace( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->replace( $key, $data, $group, (int) $expire );
}

function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->set( $key, $data, $group, (int) $expire );
}

function wp_cache_set_multiple( array $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->set_multiple( $data, $group, $expire );
}

function wp_cache_get( $key, $group = '', $force = false, &$found = null ) {
	global $wp_object_cache;

	return $wp_object_cache->get( $key, $group, $force, $found );
}

function wp_cache_get_multiple( $keys, $group = '', $force = false ) {
	global $wp_object_cache;

	return $wp_object_cache->get_multiple( $keys, $group, $force );
}

function wp_cache_delete( $key, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->delete( $key, $group );
}

function wp_cache_delete_multiple( array $keys, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->delete_multiple( $keys, $group );
}

function wp_cache_incr( $key, $offset = 1, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->incr( $key, $offset, $group );
}

function wp_cache_decr( $key, $offset = 1, $group = '' ) {
	global $wp_object_cache;

	return $wp_object_cache->decr( $key, $offset, $group );
}


function wp_cache_flush() {
	global $wp_object_cache;

	return $wp_object_cache->flush();
}

function wp_cache_flush_runtime() {
	return wp_cache_flush();
}

function wp_cache_flush_group( $group ) {
	global $wp_object_cache;

	return $wp_object_cache->flush_group( $group );
}

function wp_cache_supports( $feature ) {
	switch ( $feature ) {
		case 'add_multiple':
		case 'set_multiple':
		case 'get_multiple':
		case 'delete_multiple':
		case 'flush_runtime':
		case 'flush_group':
			return true;

		default:
			return false;
	}
}


function wp_cache_close() {
	return true;
}


function wp_cache_add_global_groups( $groups ) {
	global $wp_object_cache;

	$wp_object_cache->add_global_groups( $groups );
}


function wp_cache_add_non_persistent_groups( $groups ) {
	// Default cache doesn't persist so nothing to do here.
}

function wp_cache_switch_to_blog( $blog_id ) {
	global $wp_object_cache;

	$wp_object_cache->switch_to_blog( $blog_id );
}

function wp_cache_reset() {
	_deprecated_function( __FUNCTION__, '3.5.0', 'wp_cache_switch_to_blog()' );

	global $wp_object_cache;

	$wp_object_cache->reset();
}


#[AllowDynamicProperties]
class WP_Object_Cache {

	private $cache = array();
	public $cache_hits = 0;
	public $cache_misses = 0;
	protected $global_groups = array();
	private $blog_prefix;
	private $multisite;
	public $object_cache;
	static $instance;

	public function __construct() {
		$this->object_cache = \SpeedyCache\ObjectCache::get_instance();

		$this->multisite = is_multisite();
		$this->blog_prefix = $this->multisite ? get_current_blog_id() . ':' : '';
	}
	
	static function get_instance(){
		if(self::$instance){
			return self::$instance;
		}
		
		self::$instance = new self;
		
		return self::$instance;
	}

	public function __get( $name ) {
		return $this->$name;
	}

	public function __set( $name, $value ) {
		return $this->$name = $value;
	}

	public function __isset( $name ) {
		return isset( $this->$name );
	}

	public function __unset( $name ) {
		unset( $this->$name );
	}

	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;
	}

	protected function _exists( $key, $group ) {
		if(!$id = $this->id($key, $group)){
			return false;
		}
		
		return isset($this->cache[$group][$id]);
	}

	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($this->_exists($key, $group)){
			return false;
		}

		return $this->set($key, $data, $group, (int) $expire);
	}

	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;
	}

	public function replace( $key, $data, $group = 'default', $expire = 0 ) {
		if ( ! $this->is_valid_key( $key ) ) {
			return false;
		}
		
		if(!$id = $this->id($key, $group)){
			return false;
		}

		if (!$this->_exists($key, $group)){
			if(!$this->object_cache::exists($id)){
				return false;
			}
		}

		return $this->set( $key, $data, $group, (int) $expire );
	}

	public function set( $key, $data, $group = 'default', $expire = 0 ) {
		if(! $this->is_valid_key($key)){
			return false;
		}

		if(is_object($data)){
			$data = clone $data;
		}

		if(!$id = $this->id($key, $group)){
			return false;
		}

		if(!in_array($group, $this->object_cache::$non_cache_group)){
			$this->object_cache::set($id, $data, (int) $expire);
		}

		$this->cache[$group][$id] = $data;

		return 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;
	}

	public function get( $key, $group = 'default', $force = false, &$found = null ) {
		if ( ! $this->is_valid_key( $key ) ) {
			return false;
		}
		
		if(!$id = $this->id($key, $group)){
			$found = false;
			$this->cache_misses += 1;
			return false;
		}
		
		// In memory cache
		if($this->_exists($key, $group)){
			$found = true;
			$this->cache_hits += 1;
			return $this->cache[$group][$id];
		}

		// Non Cache Group check.
		if(empty($this->object_cache) || in_array($group, $this->object_cache::$non_cache_group)){
			$found = false;
			$this->cache_misses += 1;
			return false;
		}
		
		// Fetch cache from redis.
		if($cache = $this->object_cache::get($id)){
			$found = true;
			$this->cache_hits += 1;
			
			if(is_serialized($cache)){
				$cache = maybe_unserialize($cache);
			}

			$this->cache[$group][$id] = $cache;
			return $this->cache[$group][$id];
		}

		$found = false;
		$this->cache_misses += 1;
		return false;
	}

	public function get_multiple($keys, $group = 'default', $force = false) {
		$values = array();

		foreach($keys as $key){
			$values[$key] = $this->get($key, $group, $force);
		}

		return $values;
	}

	public function delete($key, $group = 'default', $deprecated = false) {
		if (! $this->is_valid_key($key)){
			return false;
		}

		if(!$id = $this->id($key, $group)){
			return false;
		}

		if(empty($this->cache[$group]) && empty($this->cache[$group][$id]) && !$this->object_cache::exists($id)) {
			return false;
		}

		unset($this->cache[$group][$id]);
		$this->object_cache::delete($id);
		return true;
	}

	public function delete_multiple(array $keys, $group = ''){
		$values = array();

		foreach($keys as $key){
			$values[$key] = $this->delete($key, $group);
		}

		return $values;
	}

	public function incr($key, $offset = 1, $group = 'default'){
		return $this->incr_desr($key, $offset = 1, $group, true);
	}

	public function decr($key, $offset = 1, $group = 'default'){
		return $this->incr_desr($key, $offset = 1, $group, false);
	}
	
	public function incr_desr($key, $offset = 1, $group = 'default', $incr = true){
		if (! $this->is_valid_key($key)){
			return false;
		}

		$cache_val = $this->get($key, $group);

		if(false === $cache_val){
			return false;
		}

		if(! is_numeric( $cache_val)){
			$cache_val = 0;
		}

		$offset = (int) $offset;

		if($incr){
			$cache_val += $offset;
		}
		else {
			$cache_val -= $offset;
		}

		if ( $cache_val < 0 ) {
			$cache_val = 0;
		}

		$this->set($key, $cache_val, $group);

		return $cache_val;
	}

	public function flush() {
		$this->cache = array();

		if(!empty($this->object_cache)){
			$this->object_cache::flush_db();
		}

		return true;
	}

	public function flush_group($group) {
		unset($this->cache[$group]);

		return true;
	}

	public function add_global_groups($groups){
		$groups = (array) $groups;

		$groups = array_fill_keys($groups, true);
		$this->global_groups = array_merge($this->global_groups, $groups);
	}
	
	public function is_global($group){
		return in_array($group, $this->global_groups);
	}

	public function switch_to_blog($blog_id){
		$blog_id = (int) $blog_id;
		$this->blog_prefix = $this->multisite ? $blog_id . ':' : '';
	}

	public function reset(){
		_deprecated_function(__FUNCTION__, '3.5.0', 'WP_Object_Cache::switch_to_blog()');

		// Clear out non-global caches since the blog ID has changed.
		foreach(array_keys($this->cache) as $group){
			if(! isset( $this->global_groups[$group])){
				unset($this->cache[$group]);
			}
		}
	}

	public function stats() {
		echo '<p>';
		echo "<strong>Cache Hits:</strong> {$this->cache_hits}<br />";
		echo "<strong>Cache Misses:</strong> {$this->cache_misses}<br />";
		echo '</p>';
		echo '<ul>';
		foreach($this->cache as $group => $cache){
			echo '<li><strong>Group:</strong> ' . esc_html($group) . ' - ( ' . number_format(strlen(serialize($cache)) / KB_IN_BYTES, 2 ) . 'k )</li>';
		}
		echo '</ul>';
	}
	
	public function id($key, $group){
		$prefix = $this->is_global($group) ? '' : $this->blog_prefix;
		
		if(empty($group)){
			$group = 'default';
		}

		return  $prefix . $group . '.' . $key;
	}
}main/logs.php000064400000016656151526423640007173 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class Logs{

	static function log($type){
		global $speedycache;
		
		$speedycache->logs = array();
		$speedycache->logs['type'] = $type;
		$speedycache->logs['name'] = '';
		$speedycache->logs['limit'] = 0;
		$speedycache->logs['logs'] = array();
		
		if($speedycache->logs['type'] == 'delete'){
			$speedycache->logs['name'] = 'speedycache_delete_cache_logs';
			$speedycache->logs['limit'] = 25;
		}
		
		self::set_logs();
	}

	static function update_db(){
		global $speedycache;
		
		if(get_option($speedycache->logs['name'])){
			update_option($speedycache->logs['name'], $speedycache->logs['logs'], false);
		}else{
			update_option($speedycache->logs['name'], $speedycache->logs['logs'], false);
		}
	}

	static function set_logs(){
		global $speedycache;

		if($log = get_option($speedycache->logs['name'])){
			$speedycache->logs['logs'] = $log;
		}
	}

	// To detect which static function called delete_cache()
	static function decode_via($data){

		$return_res = '';
		
		switch($data['function']){
			case 'all_cache':
				$return_res = '- All cache files deleted from Manage Cache';
				break;

			case 'delete_single':
				$return_res = '- Cache of a page got deleted';
				break;
				
			case 'gravatar':
				$return_res = '- Gravatar cache deleted';
				break;
				
			case 'minified':
				$return_res = '- Minified and combined assets deleted';
				break;

			case 'cache':
			
				if(empty($data['args'][0])){
					$return_res = '- Cache of a page got deleted';
					break;
				}
			
				$return_res = '- Cache of a page #ID:'.$data['args'][0].' got deleted';
				break;
				
			case 'purge_varnish':
				$return_res = '- Varnish Cache got Purged Successfully';
				break;
			
			case 'on_status_transitions':
			case 'on_status_change':
				if(empty($data['args'])){
					$return_res = '- Cache of one page has been purged on page status transition';
					break;
				}

				$type = $data['args'][2]->post_type;
			
				if($data['args'][0] == 'publish' && $data['args'][1] == 'publish'){
					$return_res = '- The '.$type.' has been updated- #ID:'.$data['args'][2]->ID.' - One cached file has been removed';
				}else if($data['args'][0] == 'publish' && $data['args'][1] != 'publish'){
					$return_res = '- New '.$type.' has been published - '.$type.' ID:'.$data['args'][2]->ID;
				}else {
					$return_res = '- The '.$type.' status has been changed. - '.$data['args'][1].' > '.$data['args'][0].' #ID:'.$data['args'][2]->ID;
				}
				
				break;
			
			case 'wp_set_comment_status':
			case 'on_comment_status':
				if(empty($data['args'])){
					$return_res = '- Post cache deleted becuase of comment status change';
					break;
				}
			
					
				if(isset($data['args'][2]->comment_ID)){
					$return_res = '- Comment(ID: '.$data['args'][2]->comment_ID.') has been marked as '.$data['args'][1].' - One cached file has been removed';
				}else{
					$return_res = '- Comment has been marked as '.$data['args'][1].' - Comment ID: '.$data['args'][0].' - One cached file has been removed';
				}
				
				break;
		}
		
		if(!empty($return_res)){
			return $return_res;
		}

		return $data['function'];
	}

	static function get_via(){
		$arr = array();
		$via = debug_backtrace();
		
		// TODO: Need to remove unwanted code from this
		if(isset($via[8]) && ($via[8]['function'] == 'wp_set_comment_status') && ($via[2]['function'] == 'home_page_cache') && ($via[3]['function'] == 'speedycache_single_delete_cache')){
			return false;
		}
		
		if($via[3]['function'] == 'speedycache_delete_home_page_cache'){
			return false;
		}

		if($via[4]['function'] == 'clear_cache_after_woocommerce_checkout_order_processed'){
			$arr['args'] = array();
			$arr['function'] = $via[4]['function'];

			$order = wc_get_order($via[4]['args'][0]);

			if($order){
				foreach($order->get_items() as $item_key => $item_values ){
					array_push($arr['args'], $item_values->get_product_id());
				}
			}
		}elseif($via[4]['function'] === 'speedycache_set_schedule'){
			$arr['function'] = $via[4]['function'];
			$arr['args'] = $via[4]['args'];
		}elseif($via[2]['function'] == 'varnish'){
			$arr['function'] = $via[2]['function'];
		}else if($via[3]['function'] == 'on_status_transitions' || $via[3]['function'] == 'speedycache_single_delete_cache'){
			$arr['args'] = $via[3]['args'];
			$arr['function'] = $via[3]['function'];
		}
		else if($via[3]['function'] == 'on_comment_status' || $via[3]['function'] == 'on_status_change'){
			$arr['args'] = $via[3]['args'];
			$arr['function'] = $via[3]['function'];
		}else if($via[4]['function'] == 'speedycache_delete_css_and_js_cache_toolbar' || $via[4]['function'] == 'speedycache_delete_cache_toolbar'){
			$arr['function'] = $via[4]['function'];
		}else if(isset($via[7]) && ($via[7]['function'] == 'wp_set_comment_status')){
			$arr['args'] = $via[7]['args'];
			$arr['function'] = $via[7]['function'];
		}else if(isset($via[6]) && ($via[3]['function'] == 'apply_filters' && $via[6]['function'] == 'speedycache_clear_all_cache')){
			$arr['file'] = $via[6]['file'];
			$arr['function'] = $via[6]['function'];
		}else if(in_array($via[2]['function'], ['all_cache', 'gravatar', 'minified', 'purge_varnish'])){
			$arr['function'] = $via[2]['function'];
		}else if($via[2]['function'] == 'cache'){
			$arr['function'] = $via[2]['function'];
			$arr['args'] = $via[2]['args'];
		}else{
			$arr['function'] = $via[3]['function'];

			if(isset($via[3]['file']) && $via[3]['file']){
				if(preg_match("/\/plugins\/([^\/]+)\//", $via[3]['file'], $plugin_name)){
					$arr['function'] = $arr['function'].' ('.$plugin_name[1].')';
				}
			}
		}

		return $arr;
	}

	static function action($from = ''){
		global $speedycache;
		
		if($speedycache->logs['type'] == 'delete'){
			$log = [];
			$log['date'] = date('d-m-Y @ H:i:s', current_time('timestamp'));
			
			if($from && $from['prefix'] != 'all'){
				$log['via'] = [];
				$log['via']['function'] = '- Cache Timeout / '.$from['prefix'].' '.$from['content'];
			}else{
				$log['via'] = self::get_via();
			}
		}
		
		if($log && $log['via'] !== false){
			
			if(!in_array($log, $speedycache->logs['logs'])){
				array_unshift($speedycache->logs['logs'], $log);

				if($speedycache->logs['limit'] < count($speedycache->logs['logs'])){
					array_pop($speedycache->logs['logs']);
				}

				self::update_db();
			}
		}
	}

	static function print_logs(){
		global $speedycache;

		?>
		<div id="speedycache-delete-logs">
			<div class="speedycache-block">
				<div class="speedycache-block-title">
					<h2>Delete Cache Logs</h2>
				</div>

				<table class="speedycache-log-table">
					<thead>
						<tr>
							<th scope="col">Date</th>
							<th scope="col">Via</th>
						</tr>
					</thead>
					<tbody>
						<?php if($speedycache->logs['logs'] && count($speedycache->logs['logs']) > 0){ ?>
							<?php foreach($speedycache->logs['logs'] as $key => $log){ ?>
								<tr>
									<td scope="row"><?php echo isset($log['date']) ? esc_html($log['date']) : '';?></td>
									<td style="border-right:1px solid #DEDBD1;"><?php echo isset($log['via']) ? esc_html(self::decode_via($log['via'])) : ''; ?></td>
								</tr>
							<?php } ?>
						<?php }else{ ?>
								<tr>
									<td style="border-left:1px solid #DEDBD1;" scope="row"><label>No Log</label></td>
									<td style="border-right:1px solid #DEDBD1;"></td>
								</tr>
						<?php } ?>
					</tbody>
				</table>
			</div>
		</div>
		<?php
	}

}

main/settingspage.php000064400000103156151526423640010714 0ustar00<?php

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT!');
}

class SettingsPage{
	
	static function license_tab(){
		global $speedycache;
		
		echo '<div class="speedycache-tab" id="speedycache-license">
			<h2><img src="'.SPEEDYCACHE_URL.'/assets/images/icons/license.svg" height="32" width="32"/> License</h2>
			<table class="wp-list-table fixed striped users speedycache-license-table" cellspacing="1" border="0" width="78%" cellpadding="10" align="center">
				<tbody>
					<tr>				
						<th align="left" width="25%">'.esc_html__('SpeedyCache Version', 'speedycache').'</th>
						<td>'.SPEEDYCACHE_PRO_VERSION.(defined('SPEEDYCACHE_PRO') ? ' (Pro Version)' : '').'</td>
					</tr>
					<tr>			
						<th align="left" valign="top">'.esc_html__('SpeedyCache License', 'speedycache').'</th>
						<td align="left">
							<form method="post" action="">
								<span style="color:var(--speedycache-red)">
									'.(defined('SPEEDYCACHE_PRO') && empty($speedycache->license) ? '<span style="color:var(--speedycache-red)">Unlicensed</span> &nbsp; &nbsp;' : '').'
								</span>
								<input type="hidden" name="security" value="'.wp_create_nonce('speedycache_license').'"/>
								<input type="hidden" name="action" value="speedycache_verify_license"/>
								<input type="text" name="license" value="'.(empty($speedycache->license) ? empty($_POST['license']) ? '' : \SpeedyCache\Util::sanitize_post('speedycache_license') : $speedycache->license['license']).'" size="30" placeholder="e.g. SPDFY-11111-22222-33333-44444" style="width:300px;">
								<button class="speedycache-button speedycache-btn-black" id="speedycache-license-btn" type="submit">Update License<span class="speedycache-spinner"><span></button>
							</form>';
							if(!empty($speedycache->license)){
								$expires = $speedycache->license['expires'];
								$expires = substr($expires, 0, 4).'/'.substr($expires, 4, 2).'/'.substr($expires, 6);
								
								echo '<div style="margin-top:10px;">License Status : '.(empty($speedycache->license['status_txt']) ? 'N.A.' : wp_kses_post($speedycache->license['status_txt'])).' &nbsp; &nbsp; &nbsp;';
								
								if(empty($speedycache->license['has_plid']) || $speedycache->license['expires'] <= date('Ymd')){
									echo 'License Expires : '.($speedycache->license['expires'] <= date('Ymd') ? '<span style="color:var(--speedycache-red)">'.esc_attr($expires).'</span>' : esc_attr($expires));
								}
								echo '</div>';
							}
						echo '</td>
					</tr>
					<tr>
						<th align="left">URL</th>
						<td>'.get_site_url().'</td>
					</tr>
					<tr>				
						<th align="left">Path</th>
						<td>'.ABSPATH.'</td>
					</tr>
					<tr>				
						<th align="left">Server\'s IP Address</th>
						<td>'.esc_html($_SERVER['SERVER_ADDR']).'</td>
					</tr>
					<tr>				
						<th align="left">.htaccess is writable</th>
						<td>'.(is_writable(ABSPATH.'/.htaccess') ? '<span style="color:var(--speedycache-red)">Yes</span>' : '<span style="color:green">No</span>').'</td>
					</tr>		
				</tbody>
			</table>
		</div>';
	}
	
	// Earlier we use to just log deletion, but now we will log other stuff too.
	static function logs(){
		global $speedycache;
		
		$speedycache->logs['logs'] = get_option('speedycache_delete_cache_logs', []);

		echo '<div class="speedycache-logs">
			<div class="speedycache-logs-header">SpeedyCache Logs</div>
			<div class="speedycache-logs-content">';
			if(!empty($speedycache->logs['logs']) && count($speedycache->logs['logs']) > 0){
				foreach($speedycache->logs['logs'] as $key => $log){
					echo '<div class="speedycache-logs-row">'.(isset($log['date']) ? esc_html($log['date']) : '') . (isset($log['via']) ? esc_html(\SpeedyCache\Logs::decode_via($log['via'])) : '').'</div>';
				}
			}else{
				echo '<div class="speedycache-logs-row">'. esc_html__('No logs found', 'speedycache'). '</div>';
			}

			echo '</div>
		</div>';
	}
	
	static function stats(){
		global $speedycache;
		
		if(!class_exists('\SpeedyCache\Util')){
			return;
		}

		// CACHE SIZE
		$cache_stats = get_option('speedycache_html_size', 0);

		if(empty($cache_stats)){
			$desktop_cache = \SpeedyCache\Util::cache_path('all');
			$cache_stats = 0;

			if(file_exists($desktop_cache)){
				$cache_stats = \SpeedyCache\Util::dir_size($desktop_cache);
			}
			
			$mobile_cache = \SpeedyCache\Util::cache_path('mobile-cache');

			if(file_exists($mobile_cache)){
				$cache_stats += \SpeedyCache\Util::dir_size($mobile_cache);
			}
			
			update_option('speedycache_html_size', $cache_stats);
		}
		
		// MINIFIED SIZE
		$assets_stats = get_option('speedycache_assets_size', 0);

		if(empty($assets_stats)){
			$assets_dir = \SpeedyCache\Util::cache_path('assets');
			$assets_stats = 0;

			if(file_exists($assets_dir)){
				$assets_stats = \SpeedyCache\Util::dir_size($assets_dir);
			}
			
			update_option('speedycache_assets_size', $assets_stats);
		}
		
		$img_count = 0;
		if(class_exists('\SpeedyCache\Image')){
			$img_count = \SpeedyCache\Image::optimized_file_count();
		}

		echo '<div class="speedycache-admin-row">
			<div class="speedycache-stats-block speedycache-is-block">
				<div class="speedycache-stats-name">Cache Stats</div>
				<div class="speedycache-stats-number">'.esc_html(size_format($cache_stats)).'</div>
				<div class="speedycache-stat-status"><span class="speedycache-stat-status-indicator" '.(!empty($speedycache->options['status'])? 'style="background-color:#0c6;"' : '').'></span><span>Enabled</span></div>
			</div>
			<div class="speedycache-stats-block speedycache-is-block">
				<div class="speedycache-stats-name">Assets Stats</div>
				<div class="speedycache-stats-number">'.esc_html(size_format($assets_stats)).'</div>
			</div>
			<div class="speedycache-stats-block speedycache-is-block">
				<div class="speedycache-stats-name">Object Cache Stats</div>
				<div class="speedycache-stats-number">'.esc_html($speedycache->object_memory).'</div>
				<div class="speedycache-stat-status"><span class="speedycache-stat-status-indicator" '.(!empty($speedycache->object['enable'])? 'style="background-color:#0c6;"' : '').'></span><span>Enabled</span></div>
			</div>
			<div class="speedycache-stats-block speedycache-is-block">
				<div class="speedycache-stats-name">Image Stats</div>
				<div class="speedycache-stats-number">'.esc_html($img_count).' IMG</div>
			</div>
		</div>';
	}
	
	static function image_optm(){
		echo '<h2><img src="'.SPEEDYCACHE_URL.'/assets/images/icons/image.svg" height="32" width="32"/> Image Optimization</h2>';
		
		\SpeedyCache\Image::statics();
		\SpeedyCache\Image::settings();
		\SpeedyCache\Image::list_image_html();
	}
	
	static function bloat_tab(){
		global $speedycache;
		
		echo '<h2><img src="'.SPEEDYCACHE_URL.'/assets/images/icons/broom.svg" height="32" width="32"/> Bloat Remover</h2>
		<form method="post">
		<input type="hidden" name="action" value="speedycache_save_bloat_settings"/>';
		wp_nonce_field('speedycache_ajax_nonce');

		if(!defined('SPEEDYCACHE_PRO')){
			return;
		}
		
		$bloat_options = array(
			'disable_xmlrpc' => array(
				'id' => 'speedycache_disable_xmlrpc',
				'title' => __('Disable XML RPC', 'speedycache'),
				'description' => __('XML-RPC can cause performance and security issues'),
			),
			'remove_gfonts' => array(
				'id' => 'speedycache_remove_gfonts',
				'title' => __('Disable Google Fonts', 'speedycache'),
				'description' => __('Use users system fonts to prevent loading of fonts from server', 'speedycache'),
			),
			'disable_jmigrate' => array(
				'id' => 'speedycache_disable_jmigrate',
				'title' => __('Disable jQuery Migrate', 'speedycache'),
				'description' => __('Disable jQuery Migrate for better speed.', 'speedycache'),
				'docs' => 'https://speedycache.com/docs/bloat-remover/how-to-remove-jquery-migrate-in-wordpress/',
			),
			'disable_dashicons' => array(
				'id' => 'speedycache_disable_dashicons',
				'title' => __('Disable DashIcons', 'speedycache'),
				'description' => __('DashIcons are used on WordPress admin and might not be used on Front End.', 'speedycache'),
			),
			'disable_gutenberg' => array(
				'id' => 'speedycache_disable_gutenberg',
				'title' => __('Disable Gutenberg', 'speedycache'),
				'description' => __('Decouple Gutenberg if you use another page builder.', 'speedycache'),
			),
			'disable_block_css' => array(
				'id' => 'speedycache_disable_block_css',
				'title' => __('Disable Block Editor CSS', 'speedycache'),
				'description' => __('Some themes might not use Block Editor CSS on the front.', 'speedycache'),
			),
			'disable_oembeds' => array(
				'id' => 'speedycache_disable_oembeds',
				'title' => __('Disable OEmbeds', 'speedycache'),
				'description' => __('OEmbeds increases load on site if a lot of embeds are being used.', 'speedycache'),
			),
			'update_heartbeat' => array(
				'id' => 'speedycache_update_heartbeat',
				'title' => __('Update Heartbeat', 'speedycache'),
				'description' => __('Change how frequently heartbeat is checked.', 'speedycache'),
				'settings' => 'speedycache_update_heartbeat',
			),
			'limit_post_revision' => array(
				'id' => 'speedycache_limit_post_revision',
				'title' => __('Limit Post Revision', 'speedycache'),
				'description' => __('Change how many post revision you want to keep.', 'speedycache'),
				'settings' => 'speedycache_limit_post_revision',
			),
			'disable_cart_fragment' => array(
				'id' => 'speedycache_disable_cart_fragment',
				'title' => __('Disable Cart Fragments', 'speedycache'),
				'description' => __('Disable WooCommerce cart fragments for better performance.', 'speedycache'),
			),
			'disable_woo_assets' => array(
				'id' => 'speedycache_disable_woo_assets',
				'title' => __('Disable WooCommerce Assets', 'speedycache'),
				'description' => __('Disables WooCommerce assets to reduce unwanted asset loading.', 'speedycache'),
				'docs' => 'https://speedycache.com/docs/bloat-remover/how-to-remove-woocommerce-assets/',
			),
			'disable_rss' => array(
				'id' => 'speedycache_disable_rss',
				'title' => __('Disable RSS feeds', 'speedycache'),
				'description' => __('Disable RSS feeds to reduce request which use server resources.', 'speedycache'),
			),
		);
		
		foreach($bloat_options as $bloat_key => $bloat_option){
			echo '<div class="speedycache-option-wrap">
			<label for="'.esc_attr($bloat_option['id']).'" class="speedycache-custom-checkbox">
				<input type="checkbox" id="'.esc_attr($bloat_option['id']).'" name="'.esc_attr($bloat_key).'" '. (!empty($speedycache->bloat[$bloat_key]) ? ' checked' : '').'/>
				<div class="speedycache-input-slider"></div>
			</label>
			<div class="speedycache-option-info">
				<span class="speedycache-option-name"><span>'.esc_html($bloat_option['title']). '</span>';
				
				// Docs Link here
				if(isset($bloat_option['docs'])){
					echo '<a href="'.esc_url($bloat_option['docs']).'" target="_blank"><span class="dashicons dashicons-info" style="font-size:14px"></span></a>';
				}
				
				// Setting if any
				if(isset($bloat_option['settings'])){
				echo '<span class="speedycache-modal-settings-link" setting-id="'.esc_attr($bloat_option['settings']).'" style="display:'. (!empty($speedycache->bloat[$bloat_key]) ? 'inline-block' : 'none').';">- '.esc_html__('Settings', 'speedycache').'</span>';
				}
				echo '</span>
				<span class="speedycache-option-desc">'. esc_html($bloat_option['description']).'</span> 
			</div>
		</div>';
		}
		
		// Bloat modals
		echo '<div modal-id="speedycache_limit_post_revision" class="speedycache-modal">
			<div class="speedycache-modal-wrap">
				<div class="speedycache-modal-header">
					<div>'.esc_html__('Limit Post Revision', 'speedycache').'</div>
					<div title="Close Modal" class="speedycache-close-modal">
						<span class="dashicons dashicons-no"></span>
					</div>
				</div>
				<div class="speedycache-modal-content">
					<label for="speedycache_post_revision_count">'.esc_html__('Select Post Revision Count', 'speedycache').'</label>
					<select id="speedycache_post_revision_count" name="post_revision_count" value="'.(!empty($speedycache->bloat['post_revision_count']) ? esc_attr($speedycache->bloat['post_revision_count']) : '').'">';
						$post_revision_opts = array(
							'disable' => esc_html__('Disable', 'speedycache'),
							'1' => '1',
							'2' => '2',
							'3' => '3',
							'4' => '4',
							'5' => '5',
							'10' => '10',
							'20' => '20',
						);
						
						foreach($post_revision_opts as $value => $post_revision_opt){
							$selected = '';
							
							if(!empty($speedycache->bloat['post_revision_count']) && $speedycache->bloat['post_revision_count'] == $value){
								$selected = 'selected';
							} elseif(empty($speedycache->bloat['post_revision_count']) && $value == '10'){
								$selected = 'selected';
							}

							echo '<option value="'.esc_attr($value).'" '.esc_attr($selected).'>'.esc_html($post_revision_opt).'</option>';
						}
					echo '</select>
	
				</div>
				<div class="speedycache-modal-footer">
					<button type="button" action="close">
						<span>'.esc_html__('Submit', 'speedycache').'</span>
					</button>
				</div>
			</div>
		</div>
		
		<!-- Modal Settings for heartbeat of WordPress -->
		<div modal-id="speedycache_update_heartbeat" class="speedycache-modal">
			<div class="speedycache-modal-wrap">
				<div class="speedycache-modal-header">
					<div>'.esc_html__('Update HeartBeat', 'speedycache').'</div>
					<div title="Close Modal" class="speedycache-close-modal">
						<span class="dashicons dashicons-no"></span>
					</div>
				</div>
				<div class="speedycache-modal-content">';
					$heartbeat_modes = array(
						'15' => esc_html__('15 Seconds(Default)', 'speedycache'),
						'30' => esc_html__('30 seconds', 'speedycache'),
						'45' => esc_html__('45 Seconds', 'speedycache'),
						'60' => esc_html__('60 seconds', 'speedycache'),
						'120' => esc_html__('2 Minutes', 'speedycache'),
					);
					
					$disable_heartbeat = array(
						'dont' => esc_html__('Do not Disable', 'speedycache'),
						'disable' => esc_html__('Disable', 'speedycache'),
						'editor' => esc_html__('Allow on Editor only', 'speedycache'),
					);

					echo '<table>
					
					<tr>
					<td style="text-align:left;">
					<label for="speedycache_heartbeat_backend">'.esc_html__('Heartbeat Frequency', 'speedycache').'</label></td>
					<td><select id="speedycache_heartbeat_frequency" name="heartbeat_frequency" value="'.(!empty($speedycache->bloat['heartbeat_frequency']) ? esc_attr($speedycache->bloat['heartbeat_frequency']) : '').'">';
						foreach($heartbeat_modes as $value => $heartbeat_mode){
							$selected = '';
							
							if(!empty($speedycache->bloat['heartbeat_frequency']) && $speedycache->bloat['heartbeat_frequency'] == $value){
								$selected = 'selected';
							} elseif(empty($speedycache->bloat['heartbeat_frequency']) && $value == '120'){
								$selected = 'selected';
							}

							echo '<option value="'.esc_attr($value).'" '.esc_attr($selected).'>'.esc_html($heartbeat_mode).'</option>';
						}
					echo '</select></td></tr>';

					echo '<tr><td style="text-align:left;"><label for="speedycache_disable_heartbeat">'.esc_html__('Disable Heartbeat', 'speedycache').'</label></td>
					<td><select id="speedycache_disable_heartbeat" name="disable_heartbeat" value="'.(!empty($speedycache->bloat['disable_heartbeat']) ? esc_attr($speedycache->bloat['disable_heartbeat']) : '').'">';
						foreach($disable_heartbeat as $value => $disable_mode){
							$selected = '';
							
							if(!empty($speedycache->bloat['disable_heartbeat']) && $speedycache->bloat['disable_heartbeat'] == $value){
								$selected = 'selected';
							} elseif(empty($speedycache->bloat['disable_heartbeat']) && $value == 'dont'){
								$selected = 'selected';
							}

							echo '<option value="'.esc_attr($value).'" '.esc_attr($selected).'>'.esc_html($disable_mode).'</option>';
						}
					echo '</select></td></tr></table>';

				echo '</div>
				<div class="speedycache-modal-footer">
					<button type="button" action="close">
						<span>'.esc_html__('Submit', 'speedycache').'</span>
					</button>
				</div>
			</div>
		</div>';
		\SpeedyCache\Settings::save_btn();
		echo '</form>';
	}
	
	static function db_tab(){
		global $wpdb;
		
		echo '<h2><img src="'.SPEEDYCACHE_URL.'/assets/images/icons/db.svg" height="32" width="32"/> Database Optimizer</h2>';
		
		// TODO: Show notice which mentions about the bloat settings as we will slowly migrate the html code of bloat to the Pro version, to prevent the GPL plugin providers from making users fool.
		if(!defined('SPEEDYCACHE_PRO')){
			return;
		}
		
		$statics = array('all_warnings' => 0, 'post_revisions' => 0, 'trashed_contents' => 0, 'trashed_spam_comments' => 0, 'trackback_pingback' => 0, 'transient_options' => 0, 'expired_transient' => 0);
	
		$statics['post_revisions'] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_type = 'revision';");

		$statics['trashed_contents'] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->posts` WHERE post_status = 'trash';");

		$statics['trashed_spam_comments'] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_approved = 'spam' OR comment_approved = 'trash' ;");

		$statics['trackback_pingback'] = $wpdb->get_var("SELECT COUNT(*) FROM `$wpdb->comments` WHERE comment_type = 'trackback' OR comment_type = 'pingback' ;");

		$element = "SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '%\_transient\_%' ;";
		$statics['transient_options'] = $wpdb->get_var( $element ) > 20 ? $wpdb->get_var( $element ) : 0;	

		$statics['expired_transient'] = $wpdb->get_var( "SELECT COUNT(*) FROM `$wpdb->options` WHERE option_name LIKE '_transient_timeout%' AND option_value < " . time() );

		$statics['all_warnings'] = $statics['all_warnings'] + $statics['transient_options'] + $statics['trackback_pingback']+ $statics['trashed_spam_comments']+ $statics['trashed_contents']+ $statics['post_revisions'];
		
		
		
		echo '<div speedycache-db-name="all_warnings" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Clean everything', 'speedycache').' <span class="speedycache-db-number">('.esc_html($statics['all_warnings']).')</span></div>
					<div>'.esc_html__('Run the all options', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>

		<div speedycache-db-name="post_revisions" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Post Revisions', 'speedycache').' <span class="speedycache-db-number">('.esc_html($statics['post_revisions']).')</span></div>
					<div>'.esc_html__('Clean the all post revisions', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>

		<div speedycache-db-name="trashed_contents" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Trashed Contents', 'speedycache').'<span class="speedycache-db-number">('.esc_html($statics['trashed_contents']).')</span></div>
					<div>'.esc_html__('Clean the all trashed posts & pages', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>

		<div speedycache-db-name="trashed_spam_comments" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Trashed & Spam Comments', 'speedycache').' <span class="speedycache-db-number">('.esc_html($statics['trashed_spam_comments']).')</span></div>
					<div>'.esc_html__('Clean the all comments from trash & spam', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>

		<div speedycache-db-name="trackback_pingback" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Trackbacks and Pingbacks', 'speedycache').' <span class="speedycache-db-number">('.esc_html($statics['trackback_pingback']).')</span></div>
					<div>'.esc_html__('Clean the all trackbacks and pingbacks', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>

		<div speedycache-db-name="transient_options" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Transient Options', 'speedycache').' <span class="speedycache-db-number">('.esc_html($statics['transient_options']).')</span></div>
					<div>'.esc_html__('Clean the all transient options', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>
		<div speedycache-db-name="expired_transient" class="speedycache-db-row">
			<div>
				<div class="speedycache-db-info db">
					<div>'.esc_html__('Expired Transients', 'speedycache').' <span class="speedycache-db-number">('.esc_html($statics['expired_transient']).')</span></div>
					<div>'.esc_html__('Clean the expired transients', 'speedycache').'</div>
				</div>
			</div>
			<button class="speedycache-button speedycache-btn-black speedycache-db-optm-btn">'.esc_html__('Run optimization', 'speedycache').'<span class="speedycache-spinner"></span></button>
		</div>';
	}
	
	static function object_tab(){
		global $speedycache;
	
		echo '<h2><img src="'.SPEEDYCACHE_URL.'/assets/images/icons/object.svg" height="32" width="32"/> '.esc_html__('Object Cache', 'speedycache').'</h2>';

		echo '<div class="speedycache-block">
			<div class="speedycache-admin-row">
				<div class="speedycache-is-block speedycache-object-stat">
					<div style="display:flex; justify-content:space-between;">
						<div><strong>Caching Status:</strong>  '.(!empty($speedycache->object['enable']) ? '<span style="color:green;">Enabled</span>' : '<span style="color:red;">Disabled</span>').'</div>
						<div><strong>Memory Usage:</strong> <span>'.esc_html__($speedycache->object_memory).'</span></div>
					</div>
					<div class="speedycache-drop-in"><strong>Drop In:</strong> '.(defined('SPEEDYCACHE_OBJECT_CACHE') ? '<span style="color:green;">Valid</span>' : '<span style="color:red;">Not Valid</span>').'</div>
					<div><strong>phpRedis Status:</strong> '.(empty(phpversion('redis')) ? '<span style="color:red">' . esc_html__('phpRedis Not Found', 'speedycache') : (version_compare(phpversion('redis'), '3.1.1') > 0 ? '<span style="color:green">'. esc_html__('Available', 'speedycache') . '('.esc_html(phpversion('redis')).')' : '<span style="color:red">' . esc_html__('You are using older version of PHPRedis'))).'</span></div>';
					if(!empty($speedycache->object['hashed_prefix'])){
						echo'<div><strong>Hashed Prefix:</strong> <span>'.esc_html($speedycache->object['hashed_prefix']).'</span></div>';
					}
					echo'<button class="speedycache-button speedycache-btn-black speedycache-flush-db">Flush DB<span class="speedycache-spinner"></span></button>
				</div>
			</div>
			<div class="speedycache-object-charts"></div>
		</div>
		
		<div class="speedycache-block">
			<form method="POST">';
			wp_nonce_field('speedycache_ajax_nonce');
			echo '<input type="hidden" value="speedycache_save_object_settings" name="action">

			<div class="speedycache-block-title">
				<h2>'.esc_html__('Settings', 'speedycache').'</h2>
			</div>
			<table class="wp-list-table speedycache-table" style="width:100%;">
				<tr>
					<th><label for="speedycache_enable_object">'.esc_html__('Enable', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_enable_object" class="speedycache-custom-checkbox">
							<input type="checkbox" id="speedycache_enable_object" name="enable_object" '.((isset($speedycache->object['enable']) && $speedycache->object['enable']) ? ' checked="true"' : '').'/>
							<div class="speedycache-input-slider"></div>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Enables Object caching, if you have full page caching then it might show some conflicts.', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr style="display:none;">
					<th><label for="speedycache_object_driver">'.esc_html__('Driver', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_driver">
							<select name="driver" id="speedycache_object_driver">
								<option value="Redis" selected>Redis</option>
							</select>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Choose which Object Cache Driver you want to use.', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_object_host">'.esc_html__('Host', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_host">
							<input type="text" name="host" id="speedycache_object_host" value="'.(!empty($speedycache->object['host']) ? esc_attr($speedycache->object['host']) : 'localhost').'"/>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Your Redis host name or IP address.', 'speedycache').'</div>
					</td>
				</tr>

				<tr>
					<th><label for="speedycache_object_port">'.esc_html__('Port', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_port">
							<input type="text" name="port" id="speedycache_object_port" value="'.(!empty($speedycache->object['port']) ? esc_attr($speedycache->object['port']) : '6379').'"/>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Your Redis host port number', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_object_username">'.esc_html__('Username', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_username">
							<input type="password" id="speedycache_object_username" name="username" value="'. ((!empty($speedycache->object['username'])) ? esc_html($speedycache->object['username']) : '').'" />
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Username of your Redis acccount.', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_object_password">'.esc_html__('Password', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_password">
							<input type="password" id="speedycache_object_password" name="password" value="'.((!empty($speedycache->object['password'])) ? esc_html($speedycache->object['password']) : '').'" />
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Password for your Redis Account.', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_object_ttl">'.esc_html__('Object Time to live', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_ttl">
							<input type="text" name="ttl" id="speedycache_object_ttl" value="'.(!empty($speedycache->object['ttl']) ? esc_attr($speedycache->object['ttl']) : '360').'"/>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('How long you want the cached Object to persist', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_object_db_id">'.esc_html__('Redis DB ID', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_db_id">
							<input type="text" name="db-id" id="speedycache_object_db_id" value="'. (!empty($speedycache->object['db-id']) ? esc_attr($speedycache->object['db-id']) : '0').'" style="width:45px;"/>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Set the database number, make sure to keep it different for every website you use it on', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_persistant_object">'.esc_html__('Persistent Connection', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_persistent_object" class="speedycache-custom-checkbox">
							<input type="checkbox" id="speedycache_persistent_object" name="persistent" '. ((!empty($speedycache->object['persistent'])) ? ' checked="true"' : '').'/>
							<div class="speedycache-input-slider"></div>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('This will Keep Alive the connection to redis.', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_object_admin">'.esc_html__('Cache WP_Admin', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_object_admin" class="speedycache-custom-checkbox">
							<input type="checkbox" id="speedycache_object_admin" name="admin" '.((!empty($speedycache->object['admin'])) ? ' checked="true"' : '').'/>
							<div class="speedycache-input-slider"></div>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('This will cache the admin pages too.', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_async_flush">'.esc_html__('Asynchronous Flushing', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_async_flush" class="speedycache-custom-checkbox">
							<input type="checkbox" id="speedycache_async_flush" name="async_flush" '.((!empty($speedycache->object['async_flush'])) ? ' checked="true"' : '').'/>
							<div class="speedycache-input-slider"></div>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('Deletes asynchronously, without blocking', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_serialization_method">'.esc_html__('Serialization Method', 'speedycache').'</label></th>
					<td>';
						$serialization_methods = ['SERIALIZER_PHP', 'SERIALIZER_IGBINARY'];

						echo '<label for="speedycache_serialization_method">
						
							<select id="speedycache_serialization_method" name="serialization" value="'. (!empty($speedycache->object['serialization']) ? esc_attr($speedycache->object['serialization']) : 'php').'">
								<option value="none">None</option>';

								foreach($serialization_methods as $method){
									$selected = '';

									if(empty($speedycache->object['serialization']) && $method === 'SERIALIZER_PHP'){
										$selected = 'selected';
									}else if(!empty($speedycache->object['serialization']) && $speedycache->object['serialization'] === $method){
										$selected = 'selected';
									}

									if(defined('Redis::'.$method)){
										echo '<option value="'.esc_attr($method).'" '.esc_attr($selected).'>'.esc_html($method).'</option>';
									}
								}
							echo '</select>
						</label>
						<div class="speedycache-option-desc">'.esc_html('If you don\'t see IG_BINARY option then the phpredis is not built with IG_BINARY, IG_BINARY can save upto 50% space', 'speedycache').'</div>
					</td>
				</tr>

				<tr>
					<th><label for="speedycache_compression_method">'.esc_html__('Compression Method', 'speedycache').'</label>
					</th>
					<td>';
						$serialization_methods = ['None', 'COMPRESSION_ZSTD', 'COMPRESSION_LZ4', 'COMPRESSION_LZF'];

						echo '<label for="speedycache_compression_method">
						
							<select id="speedycache_compression_method" name="compress" value="'. (!empty($speedycache->object['compress']) ? esc_attr($speedycache->object['compress']) : 'php').'">
								<option value="none">None</option>';

								foreach($serialization_methods as $method){
									$selected = '';

									if(empty($speedycache->object['compress']) && $method === 'None'){
										$selected = 'selected';
									}else if(!empty($speedycache->object['compress']) && $speedycache->object['compress'] === $method){
										$selected = 'selected';
									}

									if(defined('Redis::'.$method)){
										echo '<option value="'.esc_attr($method).'" '.esc_attr($selected).'>'.esc_html($method).'</option>';
									}
								}
							echo '</select>
						</label>
						<div class="speedycache-option-desc">'.esc_html('If you dont see any option then your phpredis is not built with compression options', 'speedycache').'</div>
					</td>
				</tr>
				
				<tr>
					<th><label for="speedycache_non_cache_group">'.esc_html__('Do not cache groups', 'speedycache').'</label></th>
					<td>
						<label for="speedycache_non_cache_group">
							<textarea id="speedycache_non_cache_group" name="non_cache_group" rows="5" cols="30">';
								if(empty($speedycache->object['non_cache_group'])){
									$speedycache->object['non_cache_group'] = ['plugins', 'comment', 'counts', 'wc_session_id'];
								}

								foreach($speedycache->object['non_cache_group'] as $group){
									echo esc_html($group) . "\n";
								}
							echo '</textarea>
						</label>
						<div class="speedycache-option-desc">'.esc_html__('These are the groups which should not be cached, One Per Line', 'speedycache').'</div>
					</td>
				</tr>
				
			</table>';

			\SpeedyCache\Settings::save_btn();
			echo '</form>
		</div>';
	}
}
main/plugin-update-checker.php000064400000151563151526423640012404 0ustar00<?php
/**
 * Plugin Update Checker Library 3.2
 * http://w-shadow.com/
 * 
 * Copyright 2016 Janis Elsts
 * Released under the MIT license. See license.txt for details.
 */

if ( !class_exists('SpeedyCacheUpdateChecker_3_2', false) ):

/**
 * A custom plugin update checker. 
 * 
 * @author Janis Elsts
 * @copyright 2016
 * @version 3.2
 * @access public
 */
#[\AllowDynamicProperties]
class SpeedyCacheUpdateChecker_3_2 {
	public $metadataUrl = ''; //The URL of the plugin's metadata file.
	public $pluginAbsolutePath = ''; //Full path of the main plugin file.
	public $pluginFile = '';  //Plugin filename relative to the plugins directory. Many WP APIs use this to identify plugins.
	public $slug = '';        //Plugin slug.
	public $optionName = '';  //Where to store the update info.
	public $muPluginFile = ''; //For MU plugins, the plugin filename relative to the mu-plugins directory.

	public $debugMode = false; //Set to TRUE to enable error reporting. Errors are raised using trigger_error()
                               //and should be logged to the standard PHP error log.
	public $scheduler;

	protected $upgraderStatus;

	private $debugBarPlugin = null;
	private $cachedInstalledVersion = null;

	private $metadataHost = ''; //The host component of $metadataUrl.

	/**
	 * Class constructor.
	 *
	 * @param string $metadataUrl The URL of the plugin's metadata file.
	 * @param string $pluginFile Fully qualified path to the main plugin file.
	 * @param string $slug The plugin's 'slug'. If not specified, the filename part of $pluginFile sans '.php' will be used as the slug.
	 * @param integer $checkPeriod How often to check for updates (in hours). Defaults to checking every 12 hours. Set to 0 to disable automatic update checks.
	 * @param string $optionName Where to store book-keeping info about update checks. Defaults to 'external_updates-$slug'.
	 * @param string $muPluginFile Optional. The plugin filename relative to the mu-plugins directory.
	 */
	public function __construct($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = ''){
		$this->metadataUrl = $metadataUrl;
		$this->pluginAbsolutePath = $pluginFile;
		$this->pluginFile = plugin_basename($this->pluginAbsolutePath);
		$this->muPluginFile = $muPluginFile;
		$this->slug = $slug;
		$this->optionName = $optionName;
		$this->debugMode = (bool)(constant('WP_DEBUG'));

		//If no slug is specified, use the name of the main plugin file as the slug.
		//For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'.
		if ( empty($this->slug) ){
			$this->slug = basename($this->pluginFile, '.php');
		}

		//Plugin slugs must be unique.
		$slugCheckFilter = 'puc_is_slug_in_use-' . $this->slug;
		$slugUsedBy = apply_filters($slugCheckFilter, false);
		if ( $slugUsedBy ) {
			$this->triggerError(sprintf(
				'Plugin slug "%s" is already in use by %s. Slugs must be unique.',
				htmlentities($this->slug),
				htmlentities($slugUsedBy)
			), E_USER_ERROR);
		}
		add_filter($slugCheckFilter, array($this, 'getAbsolutePath'));

		
		if ( empty($this->optionName) ){
			$this->optionName = 'external_updates-' . $this->slug;
		}

		//Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume
		//it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir).
		if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) {
			$this->muPluginFile = $this->pluginFile;
		}

		$this->scheduler = $this->createScheduler($checkPeriod);
		$this->upgraderStatus = new SpeedyCache_PucUpgraderStatus_3_2();

		$this->installHooks();
	}

	/**
	 * Create an instance of the scheduler.
	 *
	 * This is implemented as a method to make it possible for plugins to subclass the update checker
	 * and substitute their own scheduler.
	 *
	 * @param int $checkPeriod
	 * @return SpeedyCache_PucScheduler_3_2
	 */
	protected function createScheduler($checkPeriod) {
		return new SpeedyCache_PucScheduler_3_2($this, $checkPeriod);
	}
	
	/**
	 * Install the hooks required to run periodic update checks and inject update info 
	 * into WP data structures. 
	 * 
	 * @return void
	 */
	protected function installHooks(){
		//Override requests for plugin information
		add_filter('plugins_api', array($this, 'injectInfo'), 20, 3);
		
		//Insert our update info into the update array maintained by WP.
		add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+
		add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+
		add_filter('site_transient_update_plugins', array($this, 'injectTranslationUpdates'));

		add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2);
		add_action('admin_init', array($this, 'handleManualCheck'));
		add_action('all_admin_notices', array($this, 'displayManualCheckResult'));

		//Clear the version number cache when something - anything - is upgraded or WP clears the update cache.
		add_filter('upgrader_post_install', array($this, 'clearCachedVersion'));
		add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion'));
		//Clear translation updates when WP clears the update cache.
		//This needs to be done directly because the library doesn't actually remove obsolete plugin updates,
		//it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O.
		add_action('delete_site_transient_update_plugins', array($this, 'clearCachedTranslationUpdates'));

		if ( did_action('plugins_loaded') ) {
			$this->initDebugBarPanel();
		} else {
			add_action('plugins_loaded', array($this, 'initDebugBarPanel'));
		}

		//Rename the update directory to be the same as the existing directory.
		add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3);

		//Enable language support (i18n).
		load_plugin_textdomain('plugin-update-checker', false, plugin_basename(dirname(__FILE__)) . '/languages');

		//Allow HTTP requests to the metadata URL even if it's on a local host.
		$this->metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST);
		add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2);
	}
	
	/**
	 * Explicitly allow HTTP requests to the metadata URL.
	 *
	 * WordPress has a security feature where the HTTP API will reject all requests that are sent to
	 * another site hosted on the same server as the current site (IP match), a local host, or a local
	 * IP, unless the host exactly matches the current site.
	 *
	 * This feature is opt-in (at least in WP 4.4). Apparently some people enable it.
	 *
	 * That can be a problem when you're developing your plugin and you decide to host the update information
	 * on the same server as your test site. Update requests will mysteriously fail.
	 *
	 * We fix that by adding an exception for the metadata host.
	 *
	 * @param bool $allow
	 * @param string $host
	 * @return bool
	 */
	public function allowMetadataHost($allow, $host) {
		if ( strtolower($host) === strtolower($this->metadataHost) ) {
			return true;
		}
		return $allow;
	}

	/**
	 * Retrieve plugin info from the configured API endpoint.
	 * 
	 * @uses wp_remote_get()
	 * 
	 * @param array $queryArgs Additional query arguments to append to the request. Optional.
	 * @return SpeedyCacheInfo_3_2
	 */
	public function requestInfo($queryArgs = array()){
		//Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()).
		$installedVersion = $this->getInstalledVersion();
		$queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : '';
		$queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs);
		
		//Various options for the wp_remote_get() call. Plugins can filter these, too.
		$options = array(
			'timeout' => 10, //seconds
			'headers' => array(
				'Accept' => 'application/json'
			),
		);
		$options = apply_filters('puc_request_info_options-'.$this->slug, $options);
		
		//The plugin info should be at 'http://your-api.com/url/here/$slug/info.json'
		$url = $this->metadataUrl; 
		if ( !empty($queryArgs) ){
			$url = add_query_arg($queryArgs, $url);
		}
		
		$result = wp_remote_get(
			$url,
			$options
		);

		//Try to parse the response
		$status = $this->validateApiResponse($result);
		$pluginInfo = null;
		if ( !is_wp_error($status) ){
			$pluginInfo = SpeedyCacheInfo_3_2::fromJson($result['body']);
			if ( $pluginInfo !== null ) {
				$pluginInfo->filename = $this->pluginFile;
				$pluginInfo->slug = $this->slug;
			}
		} else {
			$this->triggerError(
				sprintf('The URL %s does not point to a valid plugin metadata file. ', $url)
					. $status->get_error_message(),
				E_USER_WARNING
			);
		}

		$pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result);
		return $pluginInfo;
	}

	/**
	 * Check if $result is a successful update API response.
	 *
	 * @param array|WP_Error $result
	 * @return true|WP_Error
	 */
	private function validateApiResponse($result) {
		if ( is_wp_error($result) ) { /** @var WP_Error $result */
			return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message());
		}

		if ( !isset($result['response']['code']) ) {
			return new WP_Error('puc_no_response_code', 'wp_remote_get() returned an unexpected result.');
		}

		if ( $result['response']['code'] !== 200 ) {
			return new WP_Error(
				'puc_unexpected_response_code',
				'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)'
			);
		}

		if ( empty($result['body']) ) {
			return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.');
		}

		return true;
	}

	/**
	 * Retrieve the latest update (if any) from the configured API endpoint.
	 *
	 * @uses SpeedyCacheUpdateChecker::requestInfo()
	 *
	 * @return SpeedyCacheUpdate_3_2 An instance of SpeedyCacheUpdate, or NULL when no updates are available.
	 */
	public function requestUpdate(){
		//For the sake of simplicity, this function just calls requestInfo() 
		//and transforms the result accordingly.
		$pluginInfo = $this->requestInfo(array('checking_for_updates' => '1'));
		if ( $pluginInfo == null ){
			return null;
		}
		$update = SpeedyCacheUpdate_3_2::fromSpeedyCacheInfo($pluginInfo);

		//Keep only those translation updates that apply to this site.
		$update->translations = $this->filterApplicableTranslations($update->translations);

		return $update;
	}

	/**
	 * Filter a list of translation updates and return a new list that contains only updates
	 * that apply to the current site.
	 *
	 * @param array $translations
	 * @return array
	 */
	private function filterApplicableTranslations($translations) {
		$languages = array_flip(array_values(get_available_languages()));
		$installedTranslations = wp_get_installed_translations('plugins');
		if ( isset($installedTranslations[$this->slug]) ) {
			$installedTranslations = $installedTranslations[$this->slug];
		} else {
			$installedTranslations = array();
		}

		$applicableTranslations = array();
		foreach($translations as $translation) {
			//Does it match one of the available core languages?
			$isApplicable = array_key_exists($translation->language, $languages);
			//Is it more recent than an already-installed translation?
			if ( isset($installedTranslations[$translation->language]) ) {
				$updateTimestamp = strtotime($translation->updated);
				$installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']);
				$isApplicable = $updateTimestamp > $installedTimestamp;
			}

			if ( $isApplicable ) {
				$applicableTranslations[] = $translation;
			}
		}

		return $applicableTranslations;
	}
	
	/**
	 * Get the currently installed version of the plugin.
	 * 
	 * @return string Version number.
	 */
	public function getInstalledVersion(){
		if ( isset($this->cachedInstalledVersion) ) {
			return $this->cachedInstalledVersion;
		}

		$pluginHeader = $this->getPluginHeader();
		if ( isset($pluginHeader['Version']) ) {
			$this->cachedInstalledVersion = $pluginHeader['Version'];
			return $pluginHeader['Version'];
		} else {
			//This can happen if the filename points to something that is not a plugin.
			$this->triggerError(
				sprintf(
					"Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.",
					$this->pluginFile
				),
				E_USER_WARNING
			);
			return null;
		}
	}

	/**
	 * Get plugin's metadata from its file header.
	 *
	 * @return array
	 */
	protected function getPluginHeader() {
		if ( !is_file($this->pluginAbsolutePath) ) {
			//This can happen if the plugin filename is wrong.
			$this->triggerError(
				sprintf(
					"Can't to read the plugin header for '%s'. The file does not exist.",
					$this->pluginFile
				),
				E_USER_WARNING
			);
			return array();
		}

		if ( !function_exists('get_plugin_data') ){
			/** @noinspection PhpIncludeInspection */
			require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
		}
		return get_plugin_data($this->pluginAbsolutePath, false, false);
	}

	/**
	 * Check for plugin updates.
	 * The results are stored in the DB option specified in $optionName.
	 *
	 * @return SpeedyCacheUpdate_3_2|null
	 */
	public function checkForUpdates(){
		$installedVersion = $this->getInstalledVersion();
		//Fail silently if we can't find the plugin or read its header.
		if ( $installedVersion === null ) {
			$this->triggerError(
				sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile),
				E_USER_WARNING
			);
			return null;
		}

		$state = $this->getUpdateState();
		if ( empty($state) ){
			$state = new stdClass;
			$state->lastCheck = 0;
			$state->checkedVersion = '';
			$state->update = null;
		}
		
		$state->lastCheck = time();
		$state->checkedVersion = $installedVersion;
		$this->setUpdateState($state); //Save before checking in case something goes wrong 
		
		$state->update = $this->requestUpdate();
		$this->setUpdateState($state);

		return $this->getUpdate();
	}
	
	/**
	 * Load the update checker state from the DB.
	 *  
	 * @return stdClass|null
	 */
	public function getUpdateState() {
		$state = get_site_option($this->optionName, null);
		if ( empty($state) || !is_object($state)) {
			$state = null;
		}

		if ( isset($state, $state->update) && is_object($state->update) ) {
			$state->update = SpeedyCacheUpdate_3_2::fromObject($state->update);
		}
		return $state;
	}
	
	
	/**
	 * Persist the update checker state to the DB.
	 * 
	 * @param StdClass $state
	 * @return void
	 */
	private function setUpdateState($state) {
		if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) {
			$update = $state->update; /** @var SpeedyCacheUpdate_3_2 $update */
			$state->update = $update->toStdClass();
		}
		update_site_option($this->optionName, $state);
	}

	/**
	 * Reset update checker state - i.e. last check time, cached update data and so on.
	 *
	 * Call this when your plugin is being uninstalled, or if you want to
	 * clear the update cache.
	 */
	public function resetUpdateState() {
		delete_site_option($this->optionName);
	}
	
	/**
	 * Intercept plugins_api() calls that request information about our plugin and 
	 * use the configured API endpoint to satisfy them. 
	 * 
	 * @see plugins_api()
	 * 
	 * @param mixed $result
	 * @param string $action
	 * @param array|object $args
	 * @return mixed
	 */
	public function injectInfo($result, $action = null, $args = null){
    	$relevant = ($action == 'plugin_information') && isset($args->slug) && (
			($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile))
		);
		if ( !$relevant ) {
			return $result;
		}
		
		$pluginInfo = $this->requestInfo();
		$pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo);
		if ( $pluginInfo ) {
			return $pluginInfo->toWpFormat();
		}
				
		return $result;
	}
	
	/**
	 * Insert the latest update (if any) into the update list maintained by WP.
	 * 
	 * @param StdClass $updates Update list.
	 * @return StdClass Modified update list.
	 */
	public function injectUpdate($updates){
		//Is there an update to insert?
		$update = $this->getUpdate();

		//No update notifications for mu-plugins unless explicitly enabled. The MU plugin file
		//is usually different from the main plugin file so the update wouldn't show up properly anyway.
		if ( $this->isUnknownMuPlugin() ) {
			$update = null;
		}

		if ( !empty($update) ) {
			//Let plugins filter the update info before it's passed on to WordPress.
			$update = apply_filters('puc_pre_inject_update-' . $this->slug, $update);
			$updates = $this->addUpdateToList($updates, $update);
		} else {
			//Clean up any stale update info.
			$updates = $this->removeUpdateFromList($updates);
		}

		return $updates;
	}

	/**
	 * @param StdClass|null $updates
	 * @param SpeedyCacheUpdate_3_2 $updateToAdd
	 * @return StdClass
	 */
	private function addUpdateToList($updates, $updateToAdd) {
		if ( !is_object($updates) ) {
			$updates = new stdClass();
			$updates->response = array();
		}

		$wpUpdate = $updateToAdd->toWpFormat();
		$pluginFile = $this->pluginFile;

		if ( $this->isMuPlugin() ) {
			//WP does not support automatic update installation for mu-plugins, but we can still display a notice.
			$wpUpdate->package = null;
			$pluginFile = $this->muPluginFile;
		}
		$updates->response[$pluginFile] = $wpUpdate;
		return $updates;
	}

	/**
	 * @param stdClass|null $updates
	 * @return stdClass|null
	 */
	private function removeUpdateFromList($updates) {
		if ( isset($updates, $updates->response) ) {
			unset($updates->response[$this->pluginFile]);
			if ( !empty($this->muPluginFile) ) {
				unset($updates->response[$this->muPluginFile]);
			}
		}
		return $updates;
	}

	/**
	 * Insert translation updates into the list maintained by WordPress.
	 *
	 * @param stdClass $updates
	 * @return stdClass
	 */
	public function injectTranslationUpdates($updates) {
		$translationUpdates = $this->getTranslationUpdates();
		if ( empty($translationUpdates) ) {
			return $updates;
		}

		//Being defensive.
		if ( !is_object($updates) ) {
			$updates = new stdClass();
		}
		if ( !isset($updates->translations) ) {
			$updates->translations = array();
		}

		//In case there's a name collision with a plugin hosted on wordpress.org,
		//remove any preexisting updates that match our plugin.
		$translationType = 'plugin';
		$filteredTranslations = array();
		foreach($updates->translations as $translation) {
			if ( ($translation['type'] === $translationType) && ($translation['slug'] === $this->slug) ) {
				continue;
			}
			$filteredTranslations[] = $translation;
		}
		$updates->translations = $filteredTranslations;

		//Add our updates to the list.
		foreach($translationUpdates as $update) {
			$convertedUpdate = array_merge(
				array(
					'type' => $translationType,
					'slug' => $this->slug,
					'autoupdate' => 0,
					//AFAICT, WordPress doesn't actually use the "version" field for anything.
					//But lets make sure it's there, just in case.
					'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)),
				),
				(array)$update
			);

			$updates->translations[] = $convertedUpdate;
		}

		return $updates;
	}

	/**
	 * Rename the update directory to match the existing plugin directory.
	 *
	 * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain
	 * exactly one directory, and that the directory name will be the same as the directory where
	 * the plugin/theme is currently installed.
	 *
	 * GitHub and other repositories provide ZIP downloads, but they often use directory names like
	 * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder.
	 *
	 * This is a hook callback. Don't call it from a plugin.
	 *
	 * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource.
	 * @param string $remoteSource WordPress has extracted the update to this directory.
	 * @param WP_Upgrader $upgrader
	 * @return string|WP_Error
	 */
	public function fixDirectoryName($source, $remoteSource, $upgrader) {
		global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */

		//Basic sanity checks.
		if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) {
			return $source;
		}

		//If WordPress is upgrading anything other than our plugin, leave the directory name unchanged.
		if ( !$this->isPluginBeingUpgraded($upgrader) ) {
			return $source;
		}

		//Rename the source to match the existing plugin directory.
		$pluginDirectoryName = dirname($this->pluginFile);
		if ( $pluginDirectoryName === '.' ) {
			return $source;
		}
		$correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/';
		if ( $source !== $correctedSource ) {
			//The update archive should contain a single directory that contains the rest of plugin files. Otherwise,
			//WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename
			//$remoteSource because that would break WordPress code that cleans up temporary files after update.
			if ( $this->isBadDirectoryStructure($remoteSource) ) {
				return new WP_Error(
					'puc-incorrect-directory-structure',
					sprintf(
						'The directory structure of the update is incorrect. All plugin files should be inside ' .
						'a directory named <span class="code">%s</span>, not at the root of the ZIP file.',
						htmlentities($this->slug)
					)
				);
			}

			/** @var WP_Upgrader_Skin $upgrader->skin */
			$upgrader->skin->feedback(sprintf(
				'Renaming %s to %s&#8230;',
				'<span class="code">' . basename($source) . '</span>',
				'<span class="code">' . $pluginDirectoryName . '</span>'
			));

			if ( $wp_filesystem->move($source, $correctedSource, true) ) {
				$upgrader->skin->feedback('Plugin directory successfully renamed.');
				return $correctedSource;
			} else {
				return new WP_Error(
					'puc-rename-failed',
					'Unable to rename the update to match the existing plugin directory.'
				);
			}
		}

		return $source;
	}

	/**
	 * Check for incorrect update directory structure. An update must contain a single directory,
	 * all other files should be inside that directory.
	 *
	 * @param string $remoteSource Directory path.
	 * @return bool
	 */
	private function isBadDirectoryStructure($remoteSource) {
		global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */

		$sourceFiles = $wp_filesystem->dirlist($remoteSource);
		if ( is_array($sourceFiles) ) {
			$sourceFiles = array_keys($sourceFiles);
			$firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0];
			return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath));
		}

		//Assume it's fine.
		return false;
	}

	/**
	 * Is there and update being installed RIGHT NOW, for this specific plugin?
	 *
	 * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
	 * @return bool
	 */
	public function isPluginBeingUpgraded($upgrader = null) {
		return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader);
	}

	/**
	 * Get the details of the currently available update, if any.
	 *
	 * If no updates are available, or if the last known update version is below or equal
	 * to the currently installed version, this method will return NULL.
	 *
	 * Uses cached update data. To retrieve update information straight from
	 * the metadata URL, call requestUpdate() instead.
	 *
	 * @return SpeedyCacheUpdate_3_2|null
	 */
	public function getUpdate() {
		$state = $this->getUpdateState(); /** @var StdClass $state */

		//Is there an update available?
		if ( isset($state, $state->update) ) {
			$update = $state->update;
			//Check if the update is actually newer than the currently installed version.
			$installedVersion = $this->getInstalledVersion();
			if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){
				$update->filename = $this->pluginFile;
				return $update;
			}
		}
		return null;
	}

	/**
	 * Get a list of available translation updates.
	 *
	 * This method will return an empty array if there are no updates.
	 * Uses cached update data.
	 *
	 * @return array
	 */
	public function getTranslationUpdates() {
		$state = $this->getUpdateState();
		if ( isset($state, $state->update, $state->update->translations) ) {
			return $state->update->translations;
		}
		return array();
	}

	/**
	 * Remove all cached translation updates.
	 *
	 * @see wp_clean_update_cache
	 */
	public function clearCachedTranslationUpdates() {
		$state = $this->getUpdateState();
		if ( isset($state, $state->update, $state->update->translations) ) {
			$state->update->translations = array();
			$this->setUpdateState($state);
		}
	}

	/**
	 * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default,
	 * the new link will appear after the "Visit plugin site" link.
	 *
	 * You can change the link text by using the "puc_manual_check_link-$slug" filter.
	 * Returning an empty string from the filter will disable the link.
	 *
	 * @param array $pluginMeta Array of meta links.
	 * @param string $pluginFile
	 * @return array
	 */
	public function addCheckForUpdatesLink($pluginMeta, $pluginFile) {
		$isRelevant = ($pluginFile == $this->pluginFile)
		              || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile);

		if ( $isRelevant && current_user_can('update_plugins') ) {
			$linkUrl = wp_nonce_url(
				add_query_arg(
					array(
						'puc_check_for_updates' => 1,
						'puc_slug' => $this->slug,
					),
					self_admin_url('plugins.php')
				),
				'puc_check_for_updates'
			);

			$linkText = apply_filters('puc_manual_check_link-' . $this->slug, __('Check for updates', 'plugin-update-checker'));
			if ( !empty($linkText) ) {
				$final_link = sprintf('<a href="%s">%s</a>', esc_attr($linkUrl), $linkText);
				$pluginMeta[] = apply_filters('puc_manual_final_check_link-' . $this->slug, $final_link);
			}
		}
		return $pluginMeta;
	}

	/**
	 * Check for updates when the user clicks the "Check for updates" link.
	 * @see self::addCheckForUpdatesLink()
	 *
	 * @return void
	 */
	public function handleManualCheck() {
		$shouldCheck =
			   isset($_GET['puc_check_for_updates'], $_GET['puc_slug'])
			&& $_GET['puc_slug'] == $this->slug
			&& current_user_can('update_plugins')
			&& check_admin_referer('puc_check_for_updates');

		if ( $shouldCheck ) {
			$update = $this->checkForUpdates();
			$status = ($update === null) ? 'no_update' : 'update_available';
			wp_redirect(add_query_arg(
				array(
					'puc_update_check_result' => $status,
					'puc_slug' => $this->slug,
				),
				self_admin_url('plugins.php')
			));
		}
	}

	/**
	 * Display the results of a manual update check.
	 * @see self::handleManualCheck()
	 *
	 * You can change the result message by using the "puc_manual_check_message-$slug" filter.
	 */
	public function displayManualCheckResult() {
		if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) {
			$status = strval($_GET['puc_update_check_result']);
			if ( $status == 'no_update' ) {
				$message = __('This plugin is up to date.', 'plugin-update-checker');
			} else if ( $status == 'update_available' ) {
				$message = __('A new version of this plugin is available.', 'plugin-update-checker');
			} else {
				$message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status));
			}
			printf(
				'<div class="updated notice is-dismissible"><p>%s</p></div>',
				apply_filters('puc_manual_check_message-' . $this->slug, $message, $status)
			);
		}
	}

	/**
	 * Check if the plugin file is inside the mu-plugins directory.
	 *
	 * @return bool
	 */
	protected function isMuPlugin() {
		static $cachedResult = null;

		if ( $cachedResult === null ) {
			//Convert both paths to the canonical form before comparison.
			$muPluginDir = realpath(WPMU_PLUGIN_DIR);
			$pluginPath  = realpath($this->pluginAbsolutePath);
			
			if(!empty($muPluginDir)){
				$cachedResult = (strpos($pluginPath, $muPluginDir) === 0);
			}else{
				$cachedResult = false;
			}
		}

		return $cachedResult;
	}

	/**
	 * MU plugins are partially supported, but only when we know which file in mu-plugins
	 * corresponds to this plugin.
	 *
	 * @return bool
	 */
	protected function isUnknownMuPlugin() {
		return empty($this->muPluginFile) && $this->isMuPlugin();
	}

	/**
	 * Clear the cached plugin version. This method can be set up as a filter (hook) and will
	 * return the filter argument unmodified.
	 *
	 * @param mixed $filterArgument
	 * @return mixed
	 */
	public function clearCachedVersion($filterArgument = null) {
		$this->cachedInstalledVersion = null;
		return $filterArgument;
	}

	/**
	 * Get absolute path to the main plugin file.
	 *
	 * @return string
	 */
	public function getAbsolutePath() {
		return $this->pluginAbsolutePath;
	}

	/**
	 * Register a callback for filtering query arguments. 
	 * 
	 * The callback function should take one argument - an associative array of query arguments.
	 * It should return a modified array of query arguments.
	 * 
	 * @uses add_filter() This method is a convenience wrapper for add_filter().
	 * 
	 * @param callable $callback
	 * @return void
	 */
	public function addQueryArgFilter($callback){
		add_filter('puc_request_info_query_args-'.$this->slug, $callback);
	}
	
	/**
	 * Register a callback for filtering arguments passed to wp_remote_get().
	 * 
	 * The callback function should take one argument - an associative array of arguments -
	 * and return a modified array or arguments. See the WP documentation on wp_remote_get()
	 * for details on what arguments are available and how they work. 
	 * 
	 * @uses add_filter() This method is a convenience wrapper for add_filter().
	 * 
	 * @param callable $callback
	 * @return void
	 */
	public function addHttpRequestArgFilter($callback){
		add_filter('puc_request_info_options-'.$this->slug, $callback);
	}
	
	/**
	 * Register a callback for filtering the plugin info retrieved from the external API.
	 * 
	 * The callback function should take two arguments. If the plugin info was retrieved 
	 * successfully, the first argument passed will be an instance of  SpeedyCacheInfo. Otherwise, 
	 * it will be NULL. The second argument will be the corresponding return value of 
	 * wp_remote_get (see WP docs for details).
	 *  
	 * The callback function should return a new or modified instance of SpeedyCacheInfo or NULL.
	 * 
	 * @uses add_filter() This method is a convenience wrapper for add_filter().
	 * 
	 * @param callable $callback
	 * @return void
	 */
	public function addResultFilter($callback){
		add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2);
	}

	/**
	 * Register a callback for one of the update checker filters.
	 *
	 * Identical to add_filter(), except it automatically adds the "puc_" prefix
	 * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result"
	 * becomes "puc_request_info_result-your_plugin_slug".
	 *
	 * @param string $tag
	 * @param callable $callback
	 * @param int $priority
	 * @param int $acceptedArgs
	 */
	public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) {
		add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs);
	}

	/**
	 * Initialize the update checker Debug Bar plugin/add-on thingy.
	 */
	public function initDebugBarPanel() {
		$debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php';
		if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) {
			/** @noinspection PhpIncludeInspection */
			require_once $debugBarPlugin;
			$this->debugBarPlugin = new SpeedyCache_PucDebugBarPlugin_3_2($this);
		}
	}

	/**
	 * Trigger a PHP error, but only when $debugMode is enabled.
	 *
	 * @param string $message
	 * @param int $errorType
	 */
	protected function triggerError($message, $errorType) {
		if ( $this->debugMode ) {
			trigger_error($message, $errorType);
		}
	}
}

endif;

if ( !class_exists('SpeedyCacheInfo_3_2', false) ):

/**
 * A container class for holding and transforming various plugin metadata.
 * 
 * @author Janis Elsts
 * @copyright 2016
 * @version 3.2
 * @access public
 */
#[\AllowDynamicProperties]
class SpeedyCacheInfo_3_2 {
	//Most fields map directly to the contents of the plugin's info.json file.
	//See the relevant docs for a description of their meaning.  
	public $name;
	public $slug;
	public $version;
	public $homepage;
	public $sections = array();
	public $banners;
	public $translations = array();
	public $download_url;

	public $author;
	public $author_homepage;
	
	public $requires;
	public $tested;
	public $upgrade_notice;
	
	public $rating;
	public $num_ratings;
	public $downloaded;
	public $active_installs;
	public $last_updated;
	
	public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything.

	public $filename; //Plugin filename relative to the plugins directory.
		
	/**
	 * Create a new instance of SpeedyCacheInfo from JSON-encoded plugin info 
	 * returned by an external update API.
	 * 
	 * @param string $json Valid JSON string representing plugin info.
	 * @return SpeedyCacheInfo_3_2|null New instance of SpeedyCacheInfo, or NULL on error.
	 */
	public static function fromJson($json){
		/** @var StdClass $apiResponse */
		$apiResponse = json_decode($json);
		if ( empty($apiResponse) || !is_object($apiResponse) ){
			trigger_error(
				"Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/",
				E_USER_NOTICE
			);
			return null;
		}
		
		$valid = self::validateMetadata($apiResponse);
		if ( is_wp_error($valid) ){
			trigger_error($valid->get_error_message(), E_USER_NOTICE);
			return null;
		}
		
		$info = new self();
		foreach(get_object_vars($apiResponse) as $key => $value){
			$info->$key = $value;
		}

		//json_decode decodes assoc. arrays as objects. We want it as an array.
		$info->sections = (array)$info->sections;
		
		return $info;		
	}

	/**
	 * Very, very basic validation.
	 *
	 * @param StdClass $apiResponse
	 * @return bool|WP_Error
	 */
	protected static function validateMetadata($apiResponse) {
		if (
			!isset($apiResponse->name, $apiResponse->version)
			|| empty($apiResponse->name)
			|| empty($apiResponse->version)
		) {
			return new WP_Error(
				'puc-invalid-metadata',
				"The plugin metadata file does not contain the required 'name' and/or 'version' keys."
			);
		}
		return true;
	}

	
	/**
	 * Transform plugin info into the format used by the native WordPress.org API
	 * 
	 * @return object
	 */
	public function toWpFormat(){
		$info = new stdClass;
		
		//The custom update API is built so that many fields have the same name and format
		//as those returned by the native WordPress.org API. These can be assigned directly. 
		$sameFormat = array(
			'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice',
			'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated',
		);
		foreach($sameFormat as $field){
			if ( isset($this->$field) ) {
				$info->$field = $this->$field;
			} else {
				$info->$field = null;
			}
		}

		//Other fields need to be renamed and/or transformed.
		$info->download_link = $this->download_url;
		$info->author = $this->getFormattedAuthor();
		$info->sections = array_merge(array('description' => ''), $this->sections);

		if ( !empty($this->banners) ) {
			//WP expects an array with two keys: "high" and "low". Both are optional.
			//Docs: https://wordpress.org/plugins/about/faq/#banners
			$info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners;
			$info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true));
		}

		return $info;
	}

	protected function getFormattedAuthor() {
		if ( !empty($this->author_homepage) ){
			return sprintf('<a href="%s">%s</a>', $this->author_homepage, $this->author);
		}
		return $this->author;
	}
}
	
endif;

if ( !class_exists('SpeedyCacheUpdate_3_2', false) ):

/**
 * A simple container class for holding information about an available update.
 * 
 * @author Janis Elsts
 * @copyright 2016
 * @version 3.2
 * @access public
 */
#[\AllowDynamicProperties]
class SpeedyCacheUpdate_3_2 {
	public $id = 0;
	public $slug;
	public $version;
	public $homepage;
	public $download_url;
	public $upgrade_notice;
	public $tested;
	public $translations = array();
	public $filename; //Plugin filename relative to the plugins directory.

	private static $fields = array(
		'id', 'slug', 'version', 'homepage', 'tested',
		'download_url', 'upgrade_notice', 'filename',
		'translations'
	);
	
	/**
	 * Create a new instance of SpeedyCacheUpdate from its JSON-encoded representation.
	 * 
	 * @param string $json
	 * @return SpeedyCacheUpdate_3_2|null
	 */
	public static function fromJson($json){
		//Since update-related information is simply a subset of the full plugin info,
		//we can parse the update JSON as if it was a plugin info string, then copy over
		//the parts that we care about.
		$pluginInfo = SpeedyCacheInfo_3_2::fromJson($json);
		if ( $pluginInfo != null ) {
			return self::fromSpeedyCacheInfo($pluginInfo);
		} else {
			return null;
		}
	}

	/**
	 * Create a new instance of SpeedyCacheUpdate based on an instance of SpeedyCacheInfo.
	 * Basically, this just copies a subset of fields from one object to another.
	 * 
	 * @param SpeedyCacheInfo_3_2 $info
	 * @return SpeedyCacheUpdate_3_2
	 */
	public static function fromSpeedyCacheInfo($info){
		return self::fromObject($info);
	}
	
	/**
	 * Create a new instance of SpeedyCacheUpdate by copying the necessary fields from 
	 * another object.
	 *  
	 * @param StdClass|SpeedyCacheInfo_3_2|SpeedyCacheUpdate_3_2 $object The source object.
	 * @return SpeedyCacheUpdate_3_2 The new copy.
	 */
	public static function fromObject($object) {
		$update = new self();
		$fields = self::$fields;
		if ( !empty($object->slug) ) {
			$fields = apply_filters('puc_retain_fields-' . $object->slug, $fields);
		}
		foreach($fields as $field){
			if (property_exists($object, $field)) {
				$update->$field = $object->$field;
			}
		}
		return $update;
	}
	
	/**
	 * Create an instance of StdClass that can later be converted back to 
	 * a SpeedyCacheUpdate. Useful for serialization and caching, as it avoids
	 * the "incomplete object" problem if the cached value is loaded before
	 * this class.
	 * 
	 * @return StdClass
	 */
	public function toStdClass() {
		$object = new stdClass();
		$fields = self::$fields;
		if ( !empty($this->slug) ) {
			$fields = apply_filters('puc_retain_fields-' . $this->slug, $fields);
		}
		foreach($fields as $field){
			if (property_exists($this, $field)) {
				$object->$field = $this->$field;
			}
		}
		return $object;
	}
	
	
	/**
	 * Transform the update into the format used by WordPress native plugin API.
	 * 
	 * @return object
	 */
	public function toWpFormat(){
		$update = new stdClass;

		$update->id = $this->id;
		$update->slug = $this->slug;
		$update->new_version = $this->version;
		$update->url = $this->homepage;
		$update->package = $this->download_url;
		$update->tested = $this->tested;
		$update->plugin = $this->filename;

		if ( !empty($this->upgrade_notice) ){
			$update->upgrade_notice = $this->upgrade_notice;
		}
		
		return $update;
	}
}
	
endif;

if ( !class_exists('SpeedyCache_PucScheduler_3_2', false) ):

/**
 * The scheduler decides when and how often to check for updates.
 * It calls @see SpeedyCacheUpdateChecker::checkForUpdates() to perform the actual checks.
 *
 * @version 3.2
 */
#[\AllowDynamicProperties]
class SpeedyCache_PucScheduler_3_2 {
	public $checkPeriod = 12; //How often to check for updates (in hours).
	public $throttleRedundantChecks = false; //Check less often if we already know that an update is available.
	public $throttledCheckPeriod = 72;

	/**
	 * @var SpeedyCacheUpdateChecker_3_2
	 */
	protected $updateChecker;

	private $cronHook = null;

	/**
	 * Scheduler constructor.
	 *
	 * @param SpeedyCacheUpdateChecker_3_2 $updateChecker
	 * @param int $checkPeriod How often to check for updates (in hours).
	 */
	public function __construct($updateChecker, $checkPeriod) {
		$this->updateChecker = $updateChecker;
		$this->checkPeriod = $checkPeriod;

		//Set up the periodic update checks
		$this->cronHook = 'check_plugin_updates-' . $this->updateChecker->slug;
		if ( $this->checkPeriod > 0 ){

			//Trigger the check via Cron.
			//Try to use one of the default schedules if possible as it's less likely to conflict
			//with other plugins and their custom schedules.
			$defaultSchedules = array(
				1  => 'hourly',
				12 => 'twicedaily',
				24 => 'daily',
			);
			if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) {
				$scheduleName = $defaultSchedules[$this->checkPeriod];
			} else {
				//Use a custom cron schedule.
				$scheduleName = 'every' . $this->checkPeriod . 'hours';
				add_filter('cron_schedules', array($this, '_addCustomSchedule'));
			}

			if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) {
				wp_schedule_event(time(), $scheduleName, $this->cronHook);
			}
			add_action($this->cronHook, array($this, 'maybeCheckForUpdates'));

			register_deactivation_hook($this->updateChecker->pluginFile, array($this, '_removeUpdaterCron'));

			//In case Cron is disabled or unreliable, we also manually trigger
			//the periodic checks while the user is browsing the Dashboard.
			add_action( 'admin_init', array($this, 'maybeCheckForUpdates') );

			//Like WordPress itself, we check more often on certain pages.
			/** @see wp_update_plugins */
			add_action('load-update-core.php', array($this, 'maybeCheckForUpdates'));
			add_action('load-plugins.php', array($this, 'maybeCheckForUpdates'));
			add_action('load-update.php', array($this, 'maybeCheckForUpdates'));
			//This hook fires after a bulk update is complete.
			add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0);

		} else {
			//Periodic checks are disabled.
			wp_clear_scheduled_hook($this->cronHook);
		}
	}

	/**
	 * Check for updates if the configured check interval has already elapsed.
	 * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron.
	 *
	 * You can override the default behaviour by using the "puc_check_now-$slug" filter.
	 * The filter callback will be passed three parameters:
	 *     - Current decision. TRUE = check updates now, FALSE = don't check now.
	 *     - Last check time as a Unix timestamp.
	 *     - Configured check period in hours.
	 * Return TRUE to check for updates immediately, or FALSE to cancel.
	 *
	 * This method is declared public because it's a hook callback. Calling it directly is not recommended.
	 */
	public function maybeCheckForUpdates(){
		if ( empty($this->checkPeriod) ){
			return;
		}

		$state = $this->updateChecker->getUpdateState();
		$shouldCheck =
			empty($state) ||
			!isset($state->lastCheck) ||
			( (time() - $state->lastCheck) >= $this->getEffectiveCheckPeriod() );

		//Let plugin authors substitute their own algorithm.
		$shouldCheck = apply_filters(
			'puc_check_now-' . $this->updateChecker->slug,
			$shouldCheck,
			(!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0,
			$this->checkPeriod
		);

		if ( $shouldCheck ) {
			$this->updateChecker->checkForUpdates();
		}
	}

	/**
	 * Calculate the actual check period based on the current status and environment.
	 *
	 * @return int Check period in seconds.
	 */
	protected function getEffectiveCheckPeriod() {
		$currentFilter = current_filter();
		if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) {
			//Check more often when the user visits "Dashboard -> Updates" or does a bulk update.
			$period = 60;
		} else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) {
			//Also check more often on the "Plugins" page and /wp-admin/update.php.
			$period = 3600;
		} else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) {
			//Check less frequently if it's already known that an update is available.
			$period = $this->throttledCheckPeriod * 3600;
		} else if ( defined('DOING_CRON') && constant('DOING_CRON') ) {
			//WordPress cron schedules are not exact, so lets do an update check even
			//if slightly less than $checkPeriod hours have elapsed since the last check.
			$cronFuzziness = 20 * 60;
			$period = $this->checkPeriod * 3600 - $cronFuzziness;
		} else {
			$period = $this->checkPeriod * 3600;
		}

		return $period;
	}

	/**
	 * Add our custom schedule to the array of Cron schedules used by WP.
	 *
	 * @param array $schedules
	 * @return array
	 */
	public function _addCustomSchedule($schedules){
		if ( $this->checkPeriod && ($this->checkPeriod > 0) ){
			$scheduleName = 'every' . $this->checkPeriod . 'hours';
			$schedules[$scheduleName] = array(
				'interval' => $this->checkPeriod * 3600,
				'display' => sprintf('Every %d hours', $this->checkPeriod),
			);
		}
		return $schedules;
	}

	/**
	 * Remove the scheduled cron event that the library uses to check for updates.
	 *
	 * @return void
	 */
	public function _removeUpdaterCron(){
		wp_clear_scheduled_hook($this->cronHook);
	}

	/**
	 * Get the name of the update checker's WP-cron hook. Mostly useful for debugging.
	 *
	 * @return string
	 */
	public function getCronHookName() {
		return $this->cronHook;
	}
}

endif;


if ( !class_exists('SpeedyCache_PucUpgraderStatus_3_2', false) ):

/**
 * A utility class that helps figure out which plugin WordPress is upgrading.
 *
 * It may seem strange to have an separate class just for that, but the task is surprisingly complicated.
 * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT).
 * This class uses a few workarounds and heuristics to get the file name.
 */
#[\AllowDynamicProperties]
class SpeedyCache_PucUpgraderStatus_3_2 {
	private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress.

	public function __construct() {
		//Keep track of which plugin WordPress is currently upgrading.
		add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2);
		add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1);
		add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1);
		add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1);
	}

	/**
	 * Is there and update being installed RIGHT NOW, for a specific plugin?
	 *
	 * Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading,
	 * and upgrader implementations are liable to change without notice.
	 *
	 * @param string $pluginFile The plugin to check.
	 * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update.
	 * @return bool True if the plugin identified by $pluginFile is being upgraded.
	 */
	public function isPluginBeingUpgraded($pluginFile, $upgrader = null) {
		if ( isset($upgrader) ) {
			$upgradedPluginFile = $this->getPluginBeingUpgradedBy($upgrader);
			if ( !empty($upgradedPluginFile) ) {
				$this->upgradedPluginFile = $upgradedPluginFile;
			}
		}
		return ( !empty($this->upgradedPluginFile) && ($this->upgradedPluginFile === $pluginFile) );
	}

	/**
	 * Get the file name of the plugin that's currently being upgraded.
	 *
	 * @param Plugin_Upgrader|WP_Upgrader $upgrader
	 * @return string|null
	 */
	private function getPluginBeingUpgradedBy($upgrader) {
		if ( !isset($upgrader, $upgrader->skin) ) {
			return null;
		}

		//Figure out which plugin is being upgraded.
		$pluginFile = null;
		$skin = $upgrader->skin;
		if ( $skin instanceof Plugin_Upgrader_Skin ) {
			if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) {
				$pluginFile = $skin->plugin;
			}
		} elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) {
			//This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin
			//filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can
			//do is compare those headers to the headers of installed plugins.
			$pluginFile = $this->identifyPluginByHeaders($skin->plugin_info);
		}

		return $pluginFile;
	}

	/**
	 * Identify an installed plugin based on its headers.
	 *
	 * @param array $searchHeaders The plugin file header to look for.
	 * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin.
	 */
	private function identifyPluginByHeaders($searchHeaders) {
		if ( !function_exists('get_plugins') ){
			/** @noinspection PhpIncludeInspection */
			require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
		}

		$installedPlugins = get_plugins();
		$matches = array();
		foreach($installedPlugins as $pluginBasename => $headers) {
			$diff1 = array_diff_assoc($headers, $searchHeaders);
			$diff2 = array_diff_assoc($searchHeaders, $headers);
			if ( empty($diff1) && empty($diff2) ) {
				$matches[] = $pluginBasename;
			}
		}

		//It's possible (though very unlikely) that there could be two plugins with identical
		//headers. In that case, we can't unambiguously identify the plugin that's being upgraded.
		if ( count($matches) !== 1 ) {
			return null;
		}

		return reset($matches);
	}

	/**
	 * @access private
	 *
	 * @param mixed $input
	 * @param array $hookExtra
	 * @return mixed Returns $input unaltered.
	 */
	public function setUpgradedPlugin($input, $hookExtra) {
		if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) {
			$this->upgradedPluginFile = $hookExtra['plugin'];
		} else {
			$this->upgradedPluginFile = null;
		}
		return $input;
	}

	/**
	 * @access private
	 *
	 * @param array $options
	 * @return array
	 */
	public function setUpgradedPluginFromOptions($options) {
		if (isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin'])) {
			$this->upgradedPluginFile = $options['hook_extra']['plugin'];
		} else {
			$this->upgradedPluginFile = null;
		}
		return $options;
	}

	/**
	 * @access private
	 *
	 * @param mixed $input
	 * @return mixed Returns $input unaltered.
	 */
	public function clearUpgradedPlugin($input = null) {
		$this->upgradedPluginFile = null;
		return $input;
	}
}

endif;


if ( !class_exists('SpeedyCache_PucFactory', false) ):

/**
 * A factory that builds instances of other classes from this library.
 *
 * When multiple versions of the same class have been loaded (e.g. SpeedyCacheUpdateChecker 1.2
 * and 1.3), this factory will always use the latest available version. Register class
 * versions by calling {@link SpeedyCache_PucFactory::addVersion()}.
 *
 * At the moment it can only build instances of the SpeedyCacheUpdateChecker class. Other classes
 * are intended mainly for internal use and refer directly to specific implementations. If you
 * want to instantiate one of them anyway, you can use {@link SpeedyCache_PucFactory::getLatestClassVersion()}
 * to get the class name and then create it with <code>new $class(...)</code>.
 */
#[\AllowDynamicProperties]
class SpeedyCache_PucFactory {
	protected static $classVersions = array();
	protected static $sorted = false;

	/**
	 * Create a new instance of SpeedyCacheUpdateChecker.
	 *
	 * @see SpeedyCacheUpdateChecker::__construct()
	 *
	 * @param $metadataUrl
	 * @param $pluginFile
	 * @param string $slug
	 * @param int $checkPeriod
	 * @param string $optionName
	 * @param string $muPluginFile
	 * @return SpeedyCacheUpdateChecker_3_2
	 */
	public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') {
		$class = self::getLatestClassVersion('SpeedyCacheUpdateChecker');
		return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile);
	}

	/**
	 * Get the specific class name for the latest available version of a class.
	 *
	 * @param string $class
	 * @return string|null
	 */
	public static function getLatestClassVersion($class) {
		if ( !self::$sorted ) {
			self::sortVersions();
		}

		if ( isset(self::$classVersions[$class]) ) {
			return reset(self::$classVersions[$class]);
		} else {
			return null;
		}
	}

	/**
	 * Sort available class versions in descending order (i.e. newest first).
	 */
	protected static function sortVersions() {
		foreach ( self::$classVersions as $class => $versions ) {
			uksort($versions, array(__CLASS__, 'compareVersions'));
			self::$classVersions[$class] = $versions;
		}
		self::$sorted = true;
	}

	protected static function compareVersions($a, $b) {
		return -version_compare($a, $b);
	}

	/**
	 * Register a version of a class.
	 *
	 * @access private This method is only for internal use by the library.
	 *
	 * @param string $generalClass Class name without version numbers, e.g. 'SpeedyCacheUpdateChecker'.
	 * @param string $versionedClass Actual class name, e.g. 'SpeedyCacheUpdateChecker_1_2'.
	 * @param string $version Version number, e.g. '1.2'.
	 */
	public static function addVersion($generalClass, $versionedClass, $version) {
		if ( !isset(self::$classVersions[$generalClass]) ) {
			self::$classVersions[$generalClass] = array();
		}
		self::$classVersions[$generalClass][$version] = $versionedClass;
		self::$sorted = false;
	}
}

endif;

//Register classes defined in this file with the factory.
SpeedyCache_PucFactory::addVersion('SpeedyCacheUpdateChecker', 'SpeedyCacheUpdateChecker_3_2', '3.2');
SpeedyCache_PucFactory::addVersion('SpeedyCacheUpdate', 'SpeedyCacheUpdate_3_2', '3.2');
SpeedyCache_PucFactory::addVersion('SpeedyCacheInfo', 'SpeedyCacheInfo_3_2', '3.2');
SpeedyCache_PucFactory::addVersion('SpeedyCache_PucGitHubChecker', 'SpeedyCache_PucGitHubChecker_3_2', '3.2');
main/lazyload.php000064400000035312151526423640010034 0ustar00<?php
/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class LazyLoad{
	static function init(){
		global $speedycache;
		
		$speedycache->lazy_load = array();
		$speedycache->lazy_load['exclude'] = array();
		$speedycache->lazy_load['host'] = '';
		$speedycache->lazy_load['placeholder'] = '';
		$url = parse_url(site_url());
		$speedycache->lazy_load['host'] = $url['host'];

		if(!empty($speedycache->options['lazy_load_keywords']) && $speedycache->options['lazy_load_keywords']){
			if(is_string($speedycache->options['lazy_load_keywords'])){
				$speedycache->lazy_load['exclude'] = explode(',', $speedycache->options['lazy_load_keywords']);
			} else {
				$speedycache->lazy_load['exclude'] = $speedycache->options['lazy_load_keywords'];
			}
		}
		
		self::set_placeholder();
	}

	static function set_placeholder(){
		global $speedycache;
		
		if(!empty($speedycache->options['lazy_load_placeholder']) && $speedycache->options['lazy_load_placeholder']){
			
			if($speedycache->options['lazy_load_placeholder'] === 'default'){
				$speedycache->lazy_load['placeholder'] = SPEEDYCACHE_PRO_URL . '/assets/images/image-palceholder.png';
			} else if($speedycache->options['lazy_load_placeholder'] === 'base64'){
				$speedycache->lazy_load['placeholder'] = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
			} else if($speedycache->options['lazy_load_placeholder'] === 'custom' && !empty($speedycache->options['lazy_load_placeholder_custom_url'])){
				$speedycache->lazy_load['placeholder'] = $speedycache->options['lazy_load_placeholder_custom_url'];
			}
			
			return;
		} 
		
		$speedycache->lazy_load['placeholder'] = SPEEDYCACHE_PRO_URL . '/assets/images/image-palceholder.png';
		return;
	}

	static function instagram($tag){
		$src = false;

		if(preg_match("/src\s*\=\s*[\"\']([^\"\']+sb-instagram\.min\.js)/", $tag, $out)){
			$src = $out[1];
		}

		if(empty($src)){
			return $tag;
		}

		$tmp_script = '<script type="text/javascript">'.
		"window.addEventListener('scroll',function(){".
		"(function(d,s){".
		"if(document.querySelectorAll("."\"script[src='\""." + s + "."\"']\"".").length > 0){return;}".
		"var t = d.createElement('script');".
		't.setAttribute("src", s);'.
		"d.body.appendChild(t);".
		'})(document, "'.$src.'");'.
		"});".
		"</script>\n";

		return $tmp_script;
	}

	static function mark_images($content){
		global $speedycache;

		if(speedycache_is_mobile()){
			return $content;
		}

		preg_match_all('/<img[^\>]+>/i', $content, $matches);

		if(count($matches[0]) <= 0){
			return $content;
		}

		foreach($matches[0] as $img){
			if(self::is_thumbnail($img) || self::is_third_party($img) || !self::is_full($img)){
				continue;
			}

			$tmp_img = $img;

			if(strpos($img, 'decoding') === FALSE){
				$tmp_img = preg_replace("/<img\s/", '<img decoding="async" ', $img);
			}

			$tmp_img = preg_replace("/<img\s/", '<img speedycache-lazyload-disable="true" ', $tmp_img);

			$content = str_replace($img, $tmp_img, $content);
		}

		return $content;
	}

	static function mark_attachment_page_images($attr, $attachment){

		if(speedycache_is_mobile()){
			return $attr;
		}

		if(isset($attr['src'])){
			if(self::is_thumbnail($attr['src'])){
				return $attr;
			}

			if(self::is_third_party($attr['src'])){
				return $attr;
			}

			if(!self::is_full('<img src="' . $attr['src'] . '" class="' . $attr['class'] . '">')){
				return $attr;
			}
		}

		if(empty($attachment)){
			return $attr;
		}

		$attr['speedycache-lazyload-disable'] = 'true';

		return $attr;
	}

	static function is_thumbnail($src){
		
		$resolution_pregs = array(
			'/\-[12]\d{0,2}x[12]\d{0,2}\.(jpg|jpeg|png)/i', // < 299x299
			'/\-[12]\d{0,2}x\d{0,2}\.(jpg|jpeg|png)/i', // < 299x99
			'/\-\d{0,2}x[12]\d{0,2}\.(jpg|jpeg|png)/i', // < 99x299
			'/\-\d{0,2}x\d{0,2}\.(jpg|jpeg|png)/i' // < 99x99
		);
		
		foreach($resolution_pregs as $resolution_preg){
			if(preg_match($resolution_preg, $src)){
				return true;
			}
		}

		return false;
	}

	static function is_third_party($src){
		global $speedycache;
		
		if(preg_match('/' . preg_quote($speedycache->lazy_load['host'], '/') . '/i', $src)){
			return false;
		}

		return true;
	}

	static function is_full($img){
		
		// to check homepage. sometimes is_home() does not work
		if(isset($_SERVER['REQUEST_URI']) && strlen($_SERVER['REQUEST_URI']) < 2){
			return false;
		}

		if(is_home() || is_archive()){
			return false;
		}

		if(preg_match("/-\d+x\d+\.(jpg|jpeg|png)/i", $img)){
			if(preg_match("/\sclass\=[\"\'][^\"\']*size-medium[^\"\']*[\"\']/", $img)){
				return false;
			}
		}

		return true;
	}

	static function is_exclude($source){
		global $speedycache;
		
		/*
			to disable lazy load for rav-slider images
			<img data-bgposition="center center" data-bgparallax="8" data-bgfit="cover" data-bgrepeat="no-repeat"class="rev-slidebg" data-no-retina>
			<img width="1920" height="600" data-parallax="8" class="rev-slidebg" data-no-retina>
		*/
		if(preg_match('/class\="rev-slidebg"/i', $source) && preg_match("/data-(bg)*parallax\=/i", $source)){
			return true;
		}

		/*
			to exclude img tag which exists in json
			var xxx = {"content":"<a href=\"https:\/\/www.abc.com\"><img src='https:\/\/www.abc.com\/img.gif' \/><\/a>"}
		*/
		if(preg_match("/\\\\\//", $source)){
			return true;
		}

		/*
			<img src="my-image.jpg" data-no-lazy="1" alt="" width="100" width="100" />
			<img src="my-image.jpg" data-skip-lazy="1" alt="" width="100" width="100" />
		*/
		if(preg_match("/data-(no|skip)-lazy\s*\=\s*[\"\']\s*1\s*[\"\']/i", $source)){
			return true;
		}

		//Slider Revolution
		//<img src="dummy.png" data-lazyload="transparent.png" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" data-bgparallax="off" class="rev-slidebg" data-no-retina>
		if(preg_match("/\sdata-lazyload\=[\"\']/i", $source)){
			return true;
		}

		//<img src="dummy.png" data-lazy-src="transparent.png">
		//<img src="dummy.png" data-gg-lazy-src="transparent.png">
		if(preg_match("/\sdata-([a-z-]*)lazy-src\=[\"\']/i", $source)){
			return true;
		}

		//<div style="background-image:url(&#039;https://www.g.com/site-data/plugins/bold-page-builder/img/image-palceholder.png&#039;);background-position:top;background-size:cover;" data-background_image_src="https://www.g.com/site-data/1.jpg">
		if(preg_match("/\sdata-background_image_src\=[\"\']/i", $source)){
			return true;
		}

		/*
		Smash Balloon Social Photo Feed
		<img src="https://site.com/site-data/plugins/instagram-feed/img/placeholder.png"
		*/
		if(preg_match('/instagram-feed\/img\/placeholder\.png/i', $source)){
			return true;
		}

		// don't to the replacement if the image is a data-uri
		if(preg_match("/src\=[\'\"]data\:image/i", $source)){
			return true;
		}


		foreach((array)$speedycache->lazy_load['exclude'] as $key => $value){
			if(preg_match('/' . preg_quote($value, '/') . '/i', $source)){
				return true;
			}
		}

		return false;
	}

	static function video($data, $inline_scripts){
		global $speedycache;
		
		if(isset($speedycache->settings['noscript'])){
			$inline_scripts = $inline_scripts . $speedycache->settings['noscript'];
		}

		$video_list = array();
		$video_start_index = false;

		for ($i = 0; $i < strlen($data); $i++){
			if(isset($data[$i - 5])){
				if(substr($data, $i - 5, 6) == '<video'){
					$video_start_index = $i - 5;
				}
			}

			if(isset($data[$i - 7])){
				if($video_start_index){
					if(substr($data, $i - 7, 8) == '</video>'){
						array_push($video_list, array('start' => $video_start_index, 'end' => $i));
						$video_start_index = false;
					}
				}
			}
		}

		if(!empty($video_list)){
			foreach(array_reverse($video_list) as $key => $value){
				$video_html = substr($data, $value['start'], ($value['end'] - $value['start'] + 1));

				if(self::is_exclude($video_html)){
					continue;
				}

				$video_html = '<noscript data-type="speedycache">' . $video_html . '</noscript>';

				$data = substr_replace($data, $video_html, $value['start'], ($value['end'] - $value['start'] + 1));
			}
		}

		return $data;
	}

	static function background($content, $inline_scripts){
		global $speedycache;

		if(isset($speedycache->settings['noscript'])){
			$inline_scripts = $inline_scripts . $speedycache->settings['noscript'];
		}

		preg_match_all('/<(div|span|a|section|li)\s[^\>]*style\s*\=\s*[\"\'][^\"\']*(background\-image\s*\:\s*url\s*\(([^\)\(]+)\)\;?)[^\"\']*[\"\'][^\>]*>/i', $content, $matches, PREG_SET_ORDER);

		if(count($matches) > 0){
			/*
				[0] = full
				[1] = tag
				[2] = backgound image
				[3] = url
			*/
			foreach($matches as $key => $div){
				// don't to the replacement if the image appear in js
				if(preg_match("/" . preg_quote($div[0], '/') . '/i', $inline_scripts)){
					continue;
				}

				if(self::is_exclude($div[0])){
					continue;
				}

				$tmp = $div[0];
				//to remove backgound attribute
				$tmp = str_replace($div[2], '', $tmp);
				//to add lazy load attribute
				$div[3] = preg_replace("/[\"\']/", '', $div[3]);
				$tmp = preg_replace("/<([a-z]{1,4})\s/i", "<$1 data-speedycache-original-src='" . $div[3] . "' ", $tmp);

				$content = str_replace($div[0], $tmp, $content);
			}
		}

		return $content;
	}

	static function images($content, $inline_scripts){
		global $speedycache;

		if(isset($speedycache->settings['noscript'])){
			$inline_scripts = $inline_scripts . $speedycache->settings['noscript'];
		}

		$offset = 2;

		preg_match_all('/<img[^\>]+>/i', $content, $matches);
		$count = 0;
		if(count($matches[0]) > 0){
			foreach($matches[0] as $key => $img){
				$count++;
				$tmp_img = false;
				
				if(preg_match("/onload=[\"\']/i", $img)){
					continue;
				}

				if(preg_match("/src\s*\=\s*[\'\"]\s*[\'\"]/i", $img)){
					continue;
				}
				
				// Excluding images from lazy loading and adding fetchpriority to high,
				// as we need to load that image faster if we are not lazy loading them
				if(!empty($speedycache->options['exclude_above_fold']) && is_numeric($speedycache->options['exclude_above_fold'])){
					if($count < $speedycache->options['exclude_above_fold']){
						$tmp_img = $img;
						$img = preg_replace('/fetchpriority=["\'].*["\']/Us', '', $img);
						$img = preg_replace('/loading=["\'].*["\']/Us', '', $img);
						$img = preg_replace('/decoding=["\'].*["\']/Us', '', $img);
						
						$img = str_replace('<img', '<img fetchpriority="high" loading="eager" decoding="async" ', $img);
						$content = str_replace($tmp_img, $img, $content);

						continue;
					}
				}

				$should_continue = self::replace_img($inline_scripts, $img, $content);
				
				if(!empty($should_continue)){
					continue;
				}

				$tmp_img = preg_replace("/\sspeedycache-lazyload-disable\=[\"\']true[\"\']\s*/", " ", $img);
				$content = str_replace($img, $tmp_img, $content);
			}
		}

		return $content;
	}

	static function inject_data_src($img){
		global $speedycache;
		
		if(!preg_match("/\ssrc\s*\=[\"\'][^\"\']+[\"\']/i", $img)){
			return $img;
		}
		
		if(preg_match("/mc\.yandex\.ru\/watch/i", $img)){
			return $img;
		}

		$tmp_img = $img;
		$tmp_img = preg_replace('/\ssrc\s*\=/i', ' data-speedycache-original-src=', $tmp_img);
		$tmp_img = preg_replace('/\ssrcset\s*\=/i', ' data-speedycache-original-srcset=', $tmp_img);
		$tmp_img = preg_replace('/\ssizes\s*\=/i', ' data-speedycache-original-sizes=', $tmp_img);
		$tmp_img = preg_replace('/<img\s/i', '<img onload="speedycachell.r(this,true);" src="' . $speedycache->lazy_load['placeholder'] . "$2\" ", $tmp_img);

		// to add alt attribute for seo
		$tmp_img = preg_replace('/\salt\s*\=\s*[\"|\']\s*[\"|\']/', ' alt="blank"', $tmp_img);
		if(!preg_match('/\salt\s*\=\s*/i', $tmp_img)){
			$tmp_img = preg_replace('/<img\s+/i', '<img alt="blank" ', $tmp_img);
		}

		return $tmp_img;
	}

	static function replace_img($inline_scripts, $img, &$content){
		
		$tmp_img = false;
		
		// Don't do the replacement if the image appear in js
		if(preg_match('/' . preg_quote($img, '/') . '/i', $inline_scripts)){
			return false;
		}

		// Don't do the replacement if quote of src does not exist
		if(!preg_match("/\ssrc\s*\=[\"\']/i", $img) && preg_match("/<img/i", $img)){
			return true;
		}

		if(self::is_exclude($img)){
			$tmp_img = preg_replace('/\sspeedycache-lazyload-disable\=[\"\']true[\"\']\s*/', ' ', $img);
		} else if(preg_match('/speedycache-lazyload-disable/', $img)){
			$tmp_img = preg_replace('/\sspeedycache-lazyload-disable\=[\"\']true[\"\']\s*/', ' ', $img);
		} else {
			$tmp_img = self::inject_data_src($img);
		}
		
		if($tmp_img){
			$content = str_replace($img, $tmp_img, $content);
		}
		
		return true;
	}

	static function iframe($content, $inline_scripts){
		
		preg_match_all('/<iframe[^\>]+>/i', $content, $matches);

		if(count($matches[0]) > 0){
			foreach($matches[0] as $iframe){
				if(self::is_exclude($iframe)){
					continue;
				}

				self::iframe_replace($inline_scripts, $iframe, $content);
			}
		}

		return $content;
	}

	static function iframe_replace($inline_scripts, $iframe, &$content){
		// don't to the replacement if the frame appear in js
		if(preg_match('/' . preg_quote($iframe, "/") . '/i', $inline_scripts)){
			return;
		}

		if(preg_match("/onload=[\"\']/i", $iframe)){
			return;
		}

		if(preg_match("/(youtube|youtube-nocookie)\.com\/embed/i", $iframe) && !preg_match("/videoseries\?list/i", $iframe)){
			// to exclude /videoseries?list= because of problem with getting thumbnail
			$tmp_iframe = preg_replace("/\ssrc\=[\"\'](https?\:)?\/\/(www\.)?(youtube|youtube-nocookie)\.com\/embed\/([^\"\']+)[\"\']/i", " onload=\"speedycachell.r(this,true);\" data-speedycache-original-src=\"" . SPEEDYCACHE_WP_CONTENT_URL . "/plugins/".SPEEDYCACHE_PRO_BASE_NAME."/main/youtube.html#$4\"", $iframe);
		} else {
			$tmp_iframe = preg_replace("/\ssrc\=/i", " onload=\"speedycachell.r(this,true);\" data-speedycache-original-src=", $iframe);
		}

		$content = str_replace($iframe, $tmp_iframe, $content);

	}

	static function get_js_source(){
		
		$js = "\n<script data-speedycache-render=\"false\">" . file_get_contents(SPEEDYCACHE_PRO_DIR . '/assets/js/lazy-load.js') . "</script>\n";

		/**
		  * Structure of this array is
		  * searchable => replacer
		*/
		$js_replaces = array(
			'/\/\*[^\n]+\*\//' =>  '', //to remove comments
			'/var\sself/' => 'var s',
			'/self\./' => 's.',
			'/speedycache_lazy_load/' => 'speedycachell',
			'/(\.?)init(\:?)/' => '$1i$2',
			'/(\.?)load_images(\:?)/' => '$1li$2',
			'/\s*(\+|\=|\:|\;|\{|\}|\,)\s*/' => '$1',
			'/originalsrcset/' => 'ot',
			'/originalsrc/' => 'oc',
			'/load_sources/' => 'ls',
			'/set_source/' => 'ss',
			'/sources/' => 's',
			'/winH/' => 'w',
			'/number/' => 'n',
			'/elemRect/' => 'er',
			'/parentRect/' => 'pr',
			'/parentOfE/' => 'p',
			'/top(\=|\+)/' => 't$1'
		);
		
		foreach($js_replaces as $search => $replace){
			$js = preg_replace($search, $replace, $js);
		}

		return $js;
	}

}

main/enhanced.php000064400000134337151526423640007771 0ustar00<?php
/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if( !defined('SPEEDYCACHE_PRO_VERSION') ){
	die('HACKING ATTEMPT!');
}

class Enhanced{

	static function init(){
		global $speedycache;
		
		$speedycache->enhanced = array();
		$speedycache->enhanced['html'] = '';
		$speedycache->enhanced['head_html'] = '';
		$speedycache->enhanced['body_html'] = '';
		$speedycache->enhanced['inline_scripts'] = '';
		$speedycache->enhanced['cache_speedycache_minified'] = '';
		$speedycache->enhanced['cache_speedycache_minified'] = 'cache/speedycache/'.SPEEDYCACHE_SERVER_HOST. '/assets';
	}
	
	// Removes white space after </html> & \r & any white space 
	static function remove_trailing_html_space($content){
		global $speedycache;
		
		$content = preg_replace("/<\/html>\s+/", '</html>', $content);
		$content = str_replace("\r", '', $content);
		return preg_replace("/^\s+/m", '', ((string) $content));
	}

	static function remove_head_comments(){
		global $speedycache;
		
		$data = $speedycache->enhanced['head_html'];
		$comment_list = array();
		$comment_start_index = false;

		for($i = 0; $i < strlen( $data ); $i++){
			if(isset($data[$i-3])){
				if($data[$i-3].$data[$i-2].$data[$i-1].$data[$i] == '<!--'){
					if(!preg_match("/if\s+|endif\s*\]/", substr($data, $i, 17))){
						$comment_start_index = $i-3;
					}
				}
			}

			if(isset($data[$i-2])){
				if($comment_start_index){
					if($data[$i-2].$data[$i-1].$data[$i] == '-->'){
						array_push($comment_list, array('start' => $comment_start_index, 'end' => $i));
						$comment_start_index = false;
					}
				}
			}
		}

		if(!empty($comment_list)){
			foreach(array_reverse($comment_list) as $key => $value){
				$data = substr_replace($data, '', $value['start'], ($value['end'] - $value['start'] + 1));
			}

			$speedycache->enhanced['html'] = str_replace($speedycache->enhanced['head_html'], $data, $speedycache->enhanced['html']);
		}

		return $speedycache->enhanced['html'];
	}

	static function eliminate_newline($start_string, $end_string, $tmp_html){
		$data = $tmp_html;

		$list = array();
		$start_index = false;
		$end_index = false;

		for($i = 0; $i < strlen( $data ); $i++){
			if(substr($data, $i, strlen($start_string)) == $start_string){
				if(!$end_index){
					$start_index = $i;
				}
			}

			if($start_index && $i > $start_index){
				if(substr($data, $i, strlen($end_string)) == $end_string){
					$end_index = $i + strlen($end_string) - 1;
					$text = substr($data, $start_index, ($end_index - $start_index + 1));
					
					array_push($list, array('start' => $start_index, 'end' => $end_index, 'text' => $text));

					$start_index = false;
					$end_index = false;
				}
			}
		}

		if(isset($list[0])){
			$list = array_reverse($list);

			foreach($list as $key => $value){
				if(preg_match("/(<script|<style|<textarea)/i", $value['text'])){
					continue;
				}

				//var $bodybg=$('<div id="ncf-body-bg"/>').prependTo($body);
				if(preg_match("/\)\.prependTo\(/i", $value['text'])){
					continue;
				}

				//<div class="wp_syntax" style="position:relative;">
				if(preg_match("/<div\s+class\=\"wp\_syntax\"[^\>]*>/i", $value['text'])){
					continue;
				}

				$value['text'] = preg_replace("/\s+/", " ", ((string)$value['text']));

				$tmp_html = substr_replace($tmp_html, $value['text'], $value['start'], ($value['end'] - $value['start'] + 1));
			}
		}

		return $tmp_html;
	}

	static function minify_inline_css($data){
		global $speedycache;
		
		$style_list = array();
		$style_start_index = false;

		for($i = 0; $i < strlen( $data ); $i++){
			if(isset($data[$i-5])){
				if(substr($data, $i - 5, 6) == '<style'){
					$style_start_index = $i - 5;
				}
			}

			if(isset($data[$i-7])){
				if($style_start_index){
					if(substr($data, $i - 7, 8) == '</style>'){
						array_push($style_list, array('start' => $style_start_index, 'end' => $i));
						$style_start_index = false;
					}
				}
			}
		}

		if(!empty($style_list)){
			foreach(array_reverse($style_list) as $key => $value){
				// document.write('<style type="text/css">div{}</style')
				$prev_20_chars = substr($data, $value['start'] - 20, 20);
				
				if(strpos($prev_20_chars, 'document.write') !== false){
					continue;
				}

				$inline_style = substr($data, $value['start'], ($value['end'] - $value['start'] + 1));
				
				if(strlen($inline_style) > 15000){
					$part_of_inline_style = substr($inline_style, 0, 15000);
				}else{
					$part_of_inline_style = $inline_style;
				}

				if(preg_match('/'.preg_quote($part_of_inline_style, '/').'/i', $speedycache->enhanced['inline_scripts'])){
					continue;
				}

				if(preg_match("/<style\s+(amp-boilerplate|amp-custom)>/", $inline_style)){
					continue;	
				}

				$inline_style = \SpeedyCache\Enhanced::minify_css($inline_style);

				$inline_style = preg_replace("/\/\*(.*?)\*\//s", "\n", $inline_style); //replaces comments with \n
				$inline_style = preg_replace("/(<style[^\>]*>)\s+/i", "$1", $inline_style); //removes white space after <style> tag
				$inline_style = preg_replace("/\s+(<\/style[^\>]*>)/i", "$1", $inline_style); //removes white space before </style> tag

				$inline_style = str_replace(' type="text/css"', '', $inline_style);
				$inline_style = str_replace(' type="text/css"', '', $inline_style);

				$data = substr_replace($data, $inline_style, $value['start'], ($value['end'] - $value['start'] + 1));
			}
		}

		return $data;
	}

	static function remove_html_comments($data){
		$comment_list = array();
		$comment_start_index = false;

		for($i = 0; $i < strlen($data); $i++){
			if(isset($data[$i-3])){
				if($data[$i-3].$data[$i-2].$data[$i-1].$data[$i] == "<!--"){
					if(!preg_match("/if\s+|endif\s*\]/", substr($data, $i, 17))){
						$comment_start_index = $i-3;
					}
				}
			}

			if(isset($data[$i-2])){
				if($comment_start_index){
					if($data[$i-2].$data[$i-1].$data[$i] == '-->'){
						array_push($comment_list, array('start' => $comment_start_index, 'end' => $i));
						$comment_start_index = false;
					}
				}
			}
		}

		if(!empty($comment_list)){
			foreach(array_reverse($comment_list) as $key => $value){
				if(($value['end'] - $value['start']) > 4){
					$comment_html = substr($data, $value['start'], ($value['end'] - $value['start'] + 1));

					if(preg_match("/google\_ad\_slot/i", $comment_html)){
					}else{
						$data = substr_replace($data, '', $value['start'], ($value['end'] - $value['start'] + 1));
					}
				}
			}
		}

		return $data;
	}

	static function minify_html(&$content){
		global $speedycache;
		
		if(defined('SPEEDYCACHE_VERSION') && version_compare(SPEEDYCACHE_VERSION, '1.2.0', '<')){
			return $speedycache->enhanced['html'];
		}
		
		$tmp_html = $content;

		$tmp_html = self::remove_trailing_html_space($tmp_html);
		$tmp_html = self::eliminate_newline('<div', '</div>', $tmp_html);
		$tmp_html = self::eliminate_newline('<li', '</li>', $tmp_html);

		$tmp_html = self::minify_inline_js($tmp_html);
		$tmp_html = self::minify_inline_css($tmp_html);

		$tmp_html = self::remove_html_comments($tmp_html);

		$tag_list = 'p|div|span|img|nav|ul|li|header|a|b|i|article|section|footer|style|script|link|meta|body';

		$tmp_html = preg_replace_callback("/\<(".$tag_list.")\s+[^\>\<]+\>/i", '\SpeedyCache\Enhanced::remove_spaces_in_tag', $tmp_html);
		$tmp_html = preg_replace('/\h+<\//', '</', $tmp_html);
		
		// BECAUSE of JsemÂ<span class="label">
		// - need to remove spaces between >  <
		// - need to remove spaces between <span>  Assdfdf </span>
		// $tmp_html = preg_replace("/\h*\<(".$tag_list.")\s+([^\>]+)>\h*/i", "<$1 $2>", $tmp_html);
		// $tmp_html = preg_replace("/\h*\<\/(".$tag_list.")>\h*/i", "</$1>", $tmp_html);
		$tmp_html = preg_replace("/\s*<\/div>\s*/is", "</div>", $tmp_html);
		
		$content = $tmp_html;
	}

	static function search_in_inline_scripts($content){
		global $speedycache;
		
		if(strpos($speedycache->enhanced['inline_scripts'], $content) === false){
			return false;
		}
		
		return true;
	}

	static function remove_spaces_in_tag($matches){
		if(self::search_in_inline_scripts($matches[0])){
			return $matches[0];
		}
		
		/**
		  * Structure of this array is
		  * searchable => replacer
		*/	
		$pregs_replaces = array(
			'/([\"\'])\s+\/>/' => '$1/>', //  <img id="1"  />
			'/\s+/' => ' ', // <div      id="1">
			'/\s+([\"\'])/' => '$1', // <div id="1  ">
			'/([a-z])\=([\"\'])\s+/' => '$1=$2', // <div id="  1"> <img src="data:image/gif;base64,R0lAICRAEAOw==" lazy="image.jpg" />
			'/\h*class\=\'\'\h*/' => ' ', // <ul class="">
			'/\h*class\=\"\"\h*/' => ' ', // <ul class=''>
		);
		
		foreach($pregs_replaces as $searchable => $replacer){
			$matches[0] = preg_replace($searchable, $replacer, $matches[0]);
		}

		// <div style="">
		if(!preg_match("/id\=\"ctf_/", $matches[0])){
			/* 
			to exclude for Custom Twitter Feeds Pro Personal
			<div class="ctf-item ctf-author-msdsmarine ctf-new ctf-hide-avatar ctf-retweet ctf-tc-checked" id="ctf_1323705595325800448" style="">
			*/
			$matches[0] = preg_replace("/\h*style\=[\"\'][\"\']\h*/", " ", $matches[0]);
		}

		// <div id="1"  >
		// <div  >
		$matches[0] = preg_replace("/\h+\>/", ">", $matches[0]);

		// <script src='//bqcmw.js' type="text/javascript"></script>
		//$matches[0] = self::remove_type_attribute_for_js($matches[0]);

		return $matches[0];
	}

	static function remove_type_attribute_for_js($script){
		if(preg_match("/src\s*\=\s*[\"\']/", $script)){
			$script = preg_replace("/\stype\s*\=\s*[\'\"][^\"\']+[\'\"]/", " ", $script);
			$script = preg_replace("/\s+/", " ", $script);
			$script = preg_replace("/([\'\"])\s>/", "$1>", $script);
		}

		return $script;
	}

	static function remove_single_line_comments($html){
		$html = preg_replace("/<!--((?:(?!-->).)+)-->/", '', $html);
		$html = preg_replace("/\/\*((?:(?!\*\/).)+)\*\//", '', $html);
		return $html;
	}

	/* CSS Part Start */
	static function minify_css($source){
		$data = $source;
		$curl_list = array();
		$curl_start_index = false;

		$curl_start_count = 0;
		$curl_end_count = 0;

		for($i = 0; $i < strlen( $data ); $i++){
			if($data[$i] == '{'){
				$curl_start_count++;
				if(!$curl_start_index){
					$curl_start_index = $i;
				}
			}

			if($data[$i] == '}'){
				// .icon-basic-printer:before{content:"}";}
				if(isset($data[$i+1]) && $data[$i+1] != "'" && $data[$i+1] != "'"){
					$curl_end_count++;
				}
			}

			if($curl_start_count && $curl_start_count == $curl_end_count){
				array_push($curl_list, array('start' => $curl_start_index - 3, 'end' => $i + 3));

				$curl_start_count = 0;
				$curl_end_count = 0;
				$curl_start_index = false;
			}
		}

		if(!empty($curl_list)){
			foreach(array_reverse($curl_list) as $key => $value){
				$new_data = substr($data, $value['start'], ($value['end'] - $value['start'] + 1));

				if(!preg_match("/[^\{]+\{[^\{]+\{/", $new_data)){
					$new_data = preg_replace("/\s+/", " ", ((string) $new_data));
					$new_data = preg_replace("/\s+}/", "}", $new_data); //removes white space before "}"
					$new_data = preg_replace("/}\s+/", "} ", $new_data); //removes white space after "}"
					$new_data = preg_replace("/\s*(\{|\;|\:)\s*/", "$1", $new_data);

					$data = substr_replace($data, $new_data, $value['start'], ($value['end'] - $value['start'] + 1));

				}else{
					$first = strpos($new_data, '{');
					$last = strrpos($new_data, '}');
					$new_data_tmp = substr($new_data, $first+1, $last-$first-1);
					$new_data_tmp = \SpeedyCache\Enhanced::minify_css($new_data_tmp);

					$new_data = substr_replace($new_data, $new_data_tmp, $first+1, ($last-$first-1));

					$data = substr_replace($data, $new_data, $value['start'], ($value['end'] - $value['start'] + 1));
				}
			}

			$source = $data;
		}

		//@media (max-width: 767px){
		$source = preg_replace("/\@media\s*\(\s*(max-width|min-width)\s*\:\s*([^\(\)\{\}\s]+)\s*\)\s*\{/", "@media($1:$2){", $source);
		//@media (min-width: 768px) and (max-width: 1018px){
		$source = preg_replace("/\@media\s*\(\s*(max-width|min-width)\s*\:\s*([^\(\)\{\}\s]+)\s*\)\s*and\s*\(\s*(max-width|min-width)\s*\:\s*([^\(\)\{\}\s]+)\s*\)\s*\{/", "@media($1:$2) and ($3:$4){", $source);
		//@media screen and (max-width: 479px){
		$source = preg_replace("/\@media\s+screen\s+and\s*\(\s*(max-width|min-width)\s*\:\s*([^\(\)\{\}\s]+)\s*\)\s*\{/", "@media screen and ($1:$2){", $source);

		/*
		article,
		h2,
		div:first-child,
		.main{padding:0;}
		*/
		$source = preg_replace("/^([a-z0-9\_\.\-\:\>\s]+\,)\s+/im", "$1 ", $source);

		return $source;

		//$source = preg_replace_callback("/\s*\{((?:(?!content|\}).)+)\}\s*/", '\SpeedyCache\Enhanced::eliminate_newline_for_css'), $source);
		//return $source;
	}

	// Regex to replace new line after \n /\s*\;(?:\s*|\n)/
	//Replaces Space before and after { } ; :
	static function eliminate_newline_for_css($matches){
		$matches[0] = preg_replace("/\s+/", " ", ((string) $matches[0]));
		$matches[0] = preg_replace("/\s*{\s*/", "{", $matches[0]);
		$matches[0] = preg_replace("/\s*}\s*/", "}", $matches[0]);
		$matches[0] = preg_replace("/\s*\;\s*/", ";", $matches[0]);
		$matches[0] = preg_replace("/\s*\:\s*/", ":", $matches[0]);

		return $matches[0]."\n";
	}

	static function render_blocking($html, $render_blocking_css = false){
		\SpeedyCache\RenderBlocking::init($html);
		return \SpeedyCache\RenderBlocking::action($render_blocking_css);
	}

	static function google_fonts(){
		//for checking
	}

	static function lazy_load($content){
		global $speedycache;

		\SpeedyCache\LazyLoad::init();
		
		$funcs = array(
			'\SpeedyCache\LazyLoad::images',
			'\SpeedyCache\LazyLoad::iframe',
			'\SpeedyCache\LazyLoad::background',
			'\SpeedyCache\LazyLoad::video'
		);
		
		foreach($funcs as $fn){
			// if(!function_exists($fn)){
				// continue;
			// }

			$fn_res = call_user_func_array($fn, array($content, $speedycache->enhanced['inline_scripts']));
			
			if(empty($fn_res)){
				continue;
			}
			
			$content = $fn_res;
		
		}
		
		return $content;
	}

	/* CSS Part Start */

	/* Js Part Start */
	// TODO:: not used anywhere
	static function single_line_js($source){
		$source = preg_replace("/\n/", '', $source);

		return $source;
	}

	static function minify_js($source, $inline_js = false){
		//$source = preg_replace("/\n\/\/.*/", "", $source);
		//$source = preg_replace("/\/\*.*?\*\//s", "", $source);

		if(preg_match("/dynamicgoogletags\.update\(\)/i", $source)){
			$source = "<script>dynamicgoogletags.update();</script>";
			
			return $source;
		}

		// <script>
		//   (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
		//   (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		//   m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
		//   })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

		//   ga('create', 'UA-9999-9', 'auto');
		//   ga('send', 'pageview');
		// </script>
		if(preg_match("/<script[^\>]*>\s*\(function\(i,s,o,g,r,a,m\)\{i\[\'GoogleAnalyticsObject\'\]/i", $source)){
			if(preg_match("/ga\(\'send\',\s*\'pageview\'\)\;\s*<\/script>/i", $source)){
				$source = preg_replace("/\s+/", " ", ((string) $source));
				$source = preg_replace("/\s*<(\/?)script([^\>]*)>\s*/", "<$1script$2>", $source);

				return $source;
			}
		}

		// sometimes the lines are ended with "\r" instead of "\n"
		$source = str_replace("\r", "\n", $source);

		$source = preg_replace("/^\s+/m", '', $source);

		if(empty($inline_js)){
			// // --></script> in html
			//$source = preg_replace("/\n\/\/[^\n]+/", "", $source); // to remove single line comments
			$source = preg_replace_callback("/\n\/\/[^\n]+/", '\SpeedyCache\Enhanced::remove_single_line_comments_from_js', $source);
		}

		if(!empty($inline_js)){
			if(preg_match("/var\sptsTables/i", $source) && preg_match("/var\sptsBuildConst/i", $source)){
			}
			//to remove only CDATA from inline js
			$source = preg_replace("/\/\*\s*\<\!\[CDATA\[\s*\*\//", "", $source);
			$source = preg_replace("/\/\*\s*\]\]\>\s*\*\//", "", $source);
		}

		//<script>//alert();</script>
		if(preg_match("/<script[^\>]*>\s*\/\/[^\n]*<\/script>/i", $source)){
			return '';
		}
		
		$source = preg_replace_callback("/([a-z]{4,5}\:)?\/\/[^\n]*/", '\SpeedyCache\Enhanced::remove_single_line_comments_from_js', $source);

		$source = preg_replace("/\}\)\;[^\S\r\n]+/", "});", $source);

		$source = preg_replace("/^\s+/m", "", $source);

		
		$source = preg_replace("/\s*(\!|\=)(\={1,3})\s*/", "$1$2", $source);

		// to remove spaces at the end of the line
		$source = preg_replace("/(\D)[^\S\r\n]+\n/", "$1\n", $source);

		$source = preg_replace("/([^\[\.\?])[^\S\r\n]+\:[^\S\r\n]+([^\]\.\?])/", "$1:$2", $source);

		$source = preg_replace("/([^\s\|])[^\S\r\n]*\&\&[^\S\r\n]*([^\s\|])/", "$1&&$2", $source);
		$source = preg_replace("/([^\s\&])[^\S\r\n]*\|\|[^\S\r\n]*([^\s\&])/", "$1||$2", $source);
		// @media all and (width), maybe later we  can do preg_replace_callback()
		//b.match(/^(<div><br( ?\/), no need to remove the spage between ( and ?
		//dashArray.replace(/( *, *)/g, no need to remove the spage between ( and *
		$source = preg_replace("/[^\S\r\n]*\([^\S\r\n]+([^\?\*\+])/", "($1", $source);
		$source = preg_replace("/and\(/", "and (", $source);
		//------
		$source = preg_replace("/([^\s\=\!])[^\S\r\n]*\=[^\S\r\n]*([^\s\=\!])/", "$1=$2", $source);

		$source = preg_replace("/\)\s+\{/", "){", $source);
		$source = preg_replace("/\}\s+}/s", "}}", $source);
		$source = preg_replace("/\};\s+}/s", "};}", $source);
		$source = preg_replace("/\}\s*else\s*\{/", "}else{", $source);
		$source = preg_replace("/\}[^\S\r\n]*else[^\S\r\n]*if[^\S\r\n]*\(/", "}else if(", $source);
		$source = preg_replace("/if\s*\(\s*/", "if(", $source);
		$source = preg_replace("/[^\S\r\n]+\)/", ")", $source);

		$source = preg_replace("/<script([^\>\<]*)>\s*/i", "<script$1>", $source);
		$source = preg_replace("/\s*<\/script>/i", "</script>", $source);

		// .name( something)
		$source = preg_replace("/(\.[A-Za-z\_]+\()\s{1,2}/", "$1", $source);

		// Muli-Line Comments Start
		$source = preg_replace_callback("/\/\*(.*?)\*\//s", '\SpeedyCache\Enhanced::remove_multi_line_comments_from_js', $source);
		// END

		$source = str_replace("\xEF\xBB\xBF", '', $source);

		$source = preg_replace("/^\s+/m", '', $source);

		//<script><!--
		//var x=5;
		//</script>
		if(!empty($inline_js)){
			if(preg_match("/<script[^\>]*><\!--/i", $source)){
				if(!preg_match("/-->/i", $source)){
					$source = preg_replace("/(<script[^\>]*>)<\!--\n/i", "$1", $source);
				}
			}
		}

		return $source;
	}

	static function minify_inline_js($data){
		global $speedycache;
		
		$script_list = array();
		$script_start_index = false;

		for($i = 0; $i < strlen( $data ); $i++){
			if(isset($data[$i - 6])){
				if(substr($data, $i - 6, 7) == '<script'){
					$script_start_index = $i - 6;
				}
			}

			if(isset($data[$i - 8])){
				if($script_start_index){
					if(substr($data, $i - 8, 9) == '</script>'){
						array_push($script_list, array('start' => $script_start_index, 'end' => $i));
						$script_start_index = false;
					}
				}
			}
		}

		if(!empty($script_list)){
			foreach(array_reverse($script_list) as $key => $value){
				$inline_script = substr($data, $value['start'], ($value['end'] - $value['start'] + 1));
				
				if(preg_match("/google\_ad\_slot/i", $inline_script)){
					$speedycache->enhanced['inline_scripts'] = $speedycache->enhanced['inline_scripts'].$inline_script;
					continue;
				}

				if(preg_match("/<script[^\>]+src=[\'\"][^\>]+>/i", $inline_script)){
					continue;
				}

				if(preg_match("/<script[^\>]+text\/template[^\>]+>/i", $inline_script)){
					continue;
				}

				$speedycache->enhanced['inline_scripts'] = $speedycache->enhanced['inline_scripts'].$inline_script;
					
				$inline_script = \SpeedyCache\Enhanced::minify_js($inline_script, true);

				$inline_script = str_replace(' type="text/javascript"', '', $inline_script);
				$inline_script = str_replace(' type="text/javascript"', '', $inline_script);

				$speedycache->enhanced['inline_scripts'] = $speedycache->enhanced['inline_scripts'].$inline_script;

				$data = substr_replace($data, $inline_script, $value['start'], ($value['end'] - $value['start'] + 1));

			}
		}

		return $data;
	}

	static function remove_multi_line_comments_from_js($matches){

		//segs.unshift('//*[@id="' + elm.getAttribute('id') + '"]');
		if(preg_match("/\/\*\[\@/", $matches[0])){
			return $matches[0];
		}
		
		if(preg_match("/\/\*\@cc_on/i", $matches[0])){
			return $matches[0];
		}

		if(preg_match("/\.exec\(|\.test\(|\.match\(|\.search\(|\.replace\(|\.split/", $matches[0])){
			return $matches[0];
		}

		if(preg_match("/function\(/", $matches[0])){
			return $matches[0];
		}

		//c("unmatched `/*`");
		if(preg_match("/^\/\*\`\"\)\;/", $matches[0])){
			return $matches[0];
		}

		// <script type='text/javascript'>
		// /* <![CDATA[ */
		// var icegram_data = {"custom_js":"<script type=\"text\/javascript\">\/* add your js code here *\/ <\/script>"};
		// /* ]]> */
		// </script>
		if(preg_match("/\\/script>/", $matches[0]) && preg_match("/\*\\//", $matches[0])){
			return $matches[0];
		}

		// {comment:{pattern:/^([ \t]*)\/[\/*].*(?:(?:\r?\n|\r)\1[ \t]+.+)*/m,lookbehind:!0}}
		if(preg_match("/\.\+\)\*\//", $matches[0])){
			return $matches[0];
		}

		// var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
		if(preg_match("/\/\*\\\\n\/\/\#\s+sourceURL/i", $matches[0])){
			return $matches[0];
		}

		// function(e){return"/*# sourceURL=".concat(r.sourceRoot).concat(e," */")
		if(preg_match("/\/\*\#\s+sourceURL/i", $matches[0])){
			return $matches[0];
		}

		// /*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */
		if(preg_match("/\/\*\#\s+sourceMappingURL/i", $matches[0])){
			return $matches[0];
		}

		// var COMMON_HEADERS = {'Accept': 'application/json, text/plain, */*'};
		if(preg_match("/\/\*\'\}\;/", $matches[0])){
			return $matches[0];
		}

		return '';
	}

	static function remove_single_line_comments_from_js($matches){
		if(preg_match("/\n\/\/[^\n]+/", $matches[0])){
			// // */
			if(preg_match("/\/\/\s*\*\//", $matches[0])){
				return $matches[0];
			}

			return '';
		}

		// // something */
		if(preg_match("/\/\/[^\n\t]*\*\//", $matches[0])){
			return $matches[0];
		}

		// var url = {"name" : "something",
		// 		   "url"  : '//$1/p/$2/media/?size=l'
		// 		  };
		if(preg_match("/\'\h*$/", $matches[0])){
			if(substr_count($matches[0], "'") == 1){
				return $matches[0];
			}
		}

		// ia=/^\.\//;x=Object.prototype;var K=x.toString,
		if(preg_match("/^\/\/\;/", $matches[0])){
			return $matches[0];
		}

		// var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQw3kuZGUAAAAAAAAAACU=");
		if(preg_match("/^\/\/[A-Za-z0-9\+\/\=]+[\'\"]\)\;/", $matches[0])){
			return $matches[0];
		}

		// "data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w==":"about:blank",
		if(preg_match("/^\/\/w\=\=\"/", $matches[0])){
			return $matches[0];
		}


		// var div = {"background-image":"url(data:image/png;base64,wD/AP+gvatMW2UYx//POaRK5CYII=)"};
		if(preg_match("/^\/\/[A-Za-z0-9\+\/\=]+\)[\'\"]\}/", $matches[0])){
			return $matches[0];
		}

		// base64
		if(preg_match("/^\/\/[A-Za-z0-9\+\/\=]{150}/", $matches[0])){
			return $matches[0];
		}

		// var a = '<a href="javascript://" id="nextLink" title="' + opts.strings.nextLinkTitle + '"></a>';
		if(preg_match("/^cript\:\/\/\"/", $matches[0])){
			return $matches[0];
		}

		// url.replace( /^http:\/\//i, 'https://' );
		//domain = domain.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");
		if(preg_match("/^\/\/i(\,|\))/", $matches[0])){
			return $matches[0];
		}

		// {pattern:/\/\*[\*!][\s\S]*?\*\//gm,alias:"co2"}
		// d=b?/[&<>"'\/]/g:/&(?!#?\w+;)|<|>|"|'|\//g;
		// replace(/\//g,"")
		// e.match(/^https?:\/\//g)
		if(preg_match("/^\/\/gm?(\,|\)|\;)/", $matches[0])){
			return $matches[0];
		}

		// match(/^https?:\/\//)
		// var pattern = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
		if(preg_match("/^\/\/(\)|\()/", $matches[0])){
			return $matches[0];
		}

		//src="//about:blank" frameborder="0" allowfullscreen></iframe>'+
		if(preg_match("/^\/\/about\:blank/", $matches[0])){
			return $matches[0];
		}

		//"<img src='http"+(location.href.indexOf('https:')==0?'s://www':'://track')+".websiteceo.com/m/?"+q+"' width='1' height='1' border='0' align='left'>";
		if(preg_match("/^\/\/www\'/", $matches[0])){
			return $matches[0];
		}

		// if(URL.match( /^https?:\/\// ) ){
		if(preg_match("/^\/\/\s*\)\s*\)\s*\{/", $matches[0])){
			return $matches[0];
		}

		// "string".replace(/\//,3);
		if(preg_match("/^\/\/\s*\,/", $matches[0])){
			return $matches[0];
		}

		// src = src.replace('https?://[^./].','');
		if(preg_match("/^\/\/\[[^\]\[]+\]/", $matches[0])){
			return $matches[0];
		}

		// comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi,
		if(preg_match("/^\/\/\s*gi\s*\,/", $matches[0])){
			return $matches[0];
		}

		// var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
		if(preg_match("/^\/\/static\./i", $matches[0])){
			return $matches[0];
		}

		// whatsapp://send?text=
		// NOTE: preg_match_replace gets only 5 chars so we check "tsapp://" instead of "whatsapp://"
		if(preg_match("/^tsapp\:\/\/send/", $matches[0])){
			return $matches[0];
		}

		// sms://?&body="+postTitle+" "+postUrl
		if(preg_match("/^\/\/\?\&/", $matches[0])){
			return $matches[0];
		}

		// viber://forward?text="+postTitle+" "+postUrl
		if(preg_match("/^viber\:\/\//", $matches[0])){
			return $matches[0];
		}

		//threema://compose?text="+postTitle+" "+postUrl
		if(preg_match("/^reema\:\/\//", $matches[0])){
			return $matches[0];
		}

		// weixin://
		if(preg_match("/^eixin\:\/\//", $matches[0])){
			return $matches[0];
		}

		// fb-messenger://share?
		if(preg_match("/^enger\:\/\//", $matches[0])){
			return $matches[0];
		}

		// rtmp://37.77.2.234:1935/redirect/live.flv
		if(preg_match("/^rtmp\:\/\//", $matches[0])){
			return $matches[0];
		}

		// comgooglemaps://?q=40.956572,29.0859053&directionsmode=driving
		if(preg_match("/^emaps\:\/\//", $matches[0])){
			return $matches[0];
		}

		// javascript://
		if(preg_match("/^cript\:\/\//", $matches[0])){
			return $matches[0];
		}

		// jsFileLocation:"//29.59.155.173/~cfo/site-data/plugins/revslider/public/assets/js/",
		if(preg_match("/^\/\/([0-9]{1,3}\.){3}[0-9]{1,3}\/\~/", $matches[0])){
			return $matches[0];
		}

		// var url = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
		if(preg_match("/\/\/\=\]/", $matches[0])){
			return $matches[0];
		}

		if(preg_match("/^maps\:\/\//", $matches[0])){
			return $matches[0];
		}

		// "line://msg/text/" + postTitle + "! " + postUrl
		if(preg_match("/^line\:\/\//", $matches[0])){
			return $matches[0];
		}

		// document.write('<script defer src="//:"></script>');
		if(preg_match("/^\/\/\:\"/", $matches[0])){
			return $matches[0];
		}

		// url: "//$1/p/$2/media/?size=l"
		if(preg_match("/^\/\/\\$/", $matches[0])){
			return $matches[0];
		}
		
		if(preg_match("/^\/\/\//", $matches[0])){
			return $matches[0];
		}
		
		if(preg_match("/^http/", $matches[0])){
			return $matches[0];
		}

		// var xxx={"case":"\nhttp://www.google.com"};
		if(preg_match("/^nhttp/", $matches[0])){
			return $matches[0];
		}

		// var currUrl = 'file://' + "something";
		if(preg_match("/^file\:\/\//i", $matches[0])){
			return $matches[0];
		}

		//<a href="javascript://nop/" class="morelink">
		if(preg_match("/cript\:\/\/nop/i", $matches[0])){
			return $matches[0];
		}

		// Flash.RTMP_RE = /^rtmp[set]?:\/\//i;
		if(preg_match("/^\/\/i\;/", $matches[0])){
			return $matches[0];
		}

		//segs.unshift('//*[@id="' + elm.getAttribute('id') + '"]');
		if(preg_match("/^\/\/\*\[/", $matches[0])){
			return $matches[0];
		}

		// e.write('<!DOCTYPE html "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
		if(preg_match("/^\/\/W3C\/\/DTD\s+XHTML/i", $matches[0])){
			return $matches[0];
		}

		// var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
		// var xxx = "} catch (e){ throw 'TemplateError: ' + e + ' (on " + name + "' + ' line ' + this.line + ')'; } " + "//@ sourceURL=" + name + "\n" // source map
		if(preg_match("/^\/\/(\#|\@)\s+sourceURL/i", $matches[0])){
			return $matches[0];
		}

		// options.tileLayerThem = '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
		if(preg_match("/^\/\/\{[^\}]+\}\./", $matches[0])){
			return $matches[0];
		}

		// document.write("<"+"script defer src=\"//:\" id=\"__onload_ie_pixastic__\"></"+"script>");
		if(preg_match("/^\/\/\:\\\\(\"|\')/", $matches[0])){
			return $matches[0];
		}

		// a.src='//cdn.'+w[r+'h']+'/libs/b.js';
		if(preg_match("/^\/\/cdn\./", $matches[0])){
			return $matches[0];
		}

		//<!DOCTYPE svg "-//W3C//DTD SVG 1.1//EN
		if(preg_match("/^\/\/W3C/i", $matches[0])){
			return $matches[0];
		}

		/*
		//# sourceMappingURL=angular.min.js.map
		//# sourceMappingURL=data:application
		*/
		if(preg_match("/sourceMappingURL\s*\=\s*(angular\.min\.js\.map|data\:application)/i", $matches[0])){
			return $matches[0];
		}

		if(preg_match("/\.exec\(|\.test\(|\.match\(|\.search\(|\.replace\(|\.split/", $matches[0])){
			return $matches[0];
		}

		if(preg_match("/^\/\/(?!\-)(?:[a-zA-Z\d\-]{0,62}[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}/", $matches[0])){
			return $matches[0];
		}

		if(preg_match("/\'|\"/", $matches[0])){
			// ' something
			if(preg_match("/^\/\/\s*[\'|\"]/", $matches[0])){
				return $matches[0];
			}

			// new Validator.Assert().Regexp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i');
			if(preg_match("/[\'\"]\,\s*[\'\"]i[\'\"]\)\;/", $matches[0])){
				return $matches[0];
			}

			/*static function speedycache_powerful_html_Uc(a,b){var c=Q&&Q.isAvailable(),d=c&&!(nb.kd||!0===nb.get("previous_websocket_failure"));b.ce&&(c||L("
			wss:// URL used, but browser isn't known to support websockets.  Trying anyway."),d=!0);if(d)a.Mb=[Q];else{var e=a.Mb=[];Vb(Vc,function(a,b){b&&b.isAvailable()&&e.push(b)})}}static function speedycache_powerful_html_Wc(a){if(0<a.Mb.length)return a.Mb[0];throw Error("No transports available");};static function speedycache_powerful_html_Xc(a,b,c,d,e,f){this.id=a;this.e=Mb("c:"+this.id+":");this.Lc=c;this.Ab=d;this.S=e;this.Kc=f;this.M=b;this.fc=[];this.Zc=0;this.yd=new Tc(b);this.ma=0;this.e("Connection created");Yc(this)}
			*/
			if(preg_match("/if\(/", $matches[0]) && preg_match("/this\./", $matches[0]) && preg_match('/function/', $matches[0])){
				return $matches[0];
			}

			// <script defer src="//:" id="__onload_ie_pixastic__">\x3c/script>
			if(preg_match("/x3c\/script>/i", $matches[0])){
				return $matches[0];
			}

			return '';
		}

		if(preg_match("/<\/script>/", $matches[0])){
			return preg_replace("/\/\/[^\<]+<\/script>/", '</script>', $matches[0]);
		}

		return '';
	}

	static function minify_js_in_body($exclude_rules = false){
		global $speedycache;
		
		$data = $speedycache->enhanced['html'];
		$script_list = array();
		$script_start_index = false;

		for($i = 0; $i < strlen( $data ); $i++){
			if(isset($data[$i - 6])){
				if(substr($data, $i - 6, 7) == '<script'){
					$script_start_index = $i - 6;
				}
			}

			if(isset($data[$i - 8]) && !empty($script_start_index)){
				if(substr($data, $i - 8, 9) == '</script>'){
					array_push($script_list, array('start' => $script_start_index, 'end' => $i));
					$script_start_index = false;
				}
			}
		}

		if(empty($script_list)){
			return $speedycache->enhanced['html'];
		}
		
		foreach(array_reverse($script_list) as $key => $value){
			$script_tag = substr($data, $value['start'], ($value['end'] - $value['start'] + 1));

			if(!preg_match("/^<script[^\>\<]+src\=[^\>\<]+>/i", $script_tag) && preg_match("/\/speedycache\-assets\//i", $script_tag)){
				continue;
			}

			preg_match("/src\=[\"\']([^\'\"]+)[\"\']/i", $script_tag, $src);

			$http_host = str_replace(array('http://', 'www.'), '', sanitize_text_field($_SERVER['HTTP_HOST']));
			
			if(!isset($src[1])){
				continue;
			}

			if(!preg_match('/'.preg_quote($http_host, '/').'/i', $src[1])){
				continue;
			}

			if(!empty($exclude_rules)){
				$is_excluded = false;

				foreach((array)$exclude_rules as $exclude_key => $exclude_value){
					if(!empty($exclude_value['prefix']) && $exclude_value['type'] === 'js'){
						if($exclude_value['prefix'] === 'contain'){
							$preg_match_rule = preg_quote($exclude_value['content'], '/');
						}

						if(preg_match('/'.$preg_match_rule.'/i', $src[1])){
							$is_excluded = true;
							break;
						}
					}
				}

				if(!empty($is_excluded)){
					continue;
				}
			}
			
			// Skip if the file is already minified.
			if(strpos($src[1], '.min.') !== FALSE){
				continue;
			}

			if(preg_match("/alexa\.com\/site\_stats/i", $src[1])){
				continue;
			}

			if(preg_match("/wp-spamshield\/js\/jscripts\.php/i", $src[1])){
				continue;
			}

			//amazonjs/components/js/jquery-tmpl/jquery.tmpl.min.js?ver=1.0.0pre
			if(preg_match("/jquery-tmpl\/jquery\.tmpl\.min\.js/i", $src[1])){
				continue;
			}

			//<script src="https://server1.opentracker.net/?site=www.site.com"></script>
			if(preg_match("/[\?\=].*".preg_quote($http_host, '/').'/i', $src[1])){
				continue;
			}
			
			$js_file_name = md5($src[1]);

			$cache_file_path = WP_CONTENT_DIR.'/'.$speedycache->enhanced['cache_speedycache_minified'].'/'.$js_file_name;
			
			if(!defined('SPEEDYCACHE_WP_CONTENT_URL')){
				$js_script = content_url().'/'.$speedycache->enhanced['cache_speedycache_minified'].'/'.$js_file_name;
			}else{
				$js_script = SPEEDYCACHE_WP_CONTENT_URL.'/'.$speedycache->enhanced['cache_speedycache_minified'].'/'.$js_file_name;
			}

			$js_script = str_replace(array('http://', 'https://'), '//', $js_script);
			
			$args = array(
				'src' => $src[1],
				'cache_file_path' => $cache_file_path,
				'js_script' => $js_script,
				'script_tag' => $script_tag,
				'value' => $value
			);
			
			self::fetch_and_minify_js($args);
		}

		return $speedycache->enhanced['html'];
	}


	static function fetch_and_minify_js($args){
		global $speedycache;
		
		$response = wp_remote_get(\SpeedyCache\Enhanced::fix_protocol($args['src']), array('timeout' => 10 ) );

		if(empty($response) || is_wp_error($response)){
			return false;
		}

		if(wp_remote_retrieve_response_code($response) != 200){
			return false;
		}

		$js_content = wp_remote_retrieve_body($response);

		if(preg_match('/<\/\s*html\s*>\s*$/i', $js_content)){
			return false;
		}
		
		$minified_js_content = \SpeedyCache\Enhanced::minify_js($js_content);

		if(!is_dir($args['cache_file_path'])){
			$prefix = time();
			\SpeedyCache\Cache::create_dir($args['cache_file_path'], $minified_js_content, 'js');
		}

		if(file_exists($args['cache_file_path']) && $js_files = @scandir($args['cache_file_path'], 1)){
			$new_script = str_replace($args['src'], $args['js_script'].'/'.$js_files[0], $args['script_tag']);
			$speedycache->enhanced['html'] = substr_replace($speedycache->enhanced['html'], $new_script, $args['value']['start'], ($args['value']['end'] - $args['value']['start'] + 1));
		}

	}

	static function combine_js_in_footer($minify = false){
		global $speedycache;
		
		$footer = strstr($speedycache->enhanced['html'], '<!--SPEEDYCACHE_FOOTER_START-->');

		\SpeedyCache\JS::init($footer, $minify);
		$tmp_footer = \SpeedyCache\JS::combine();
		
		if(!empty($speedycache->options['render_blocking'])){
			\SpeedyCache\RenderBlocking::init($tmp_footer);
			$tmp_footer = \SpeedyCache\RenderBlocking::action(false, true);
		}
		
		$speedycache->enhanced['html'] = str_replace($footer, $tmp_footer, $speedycache->enhanced['html']);
		
		return $speedycache->enhanced['html'];
	}
	/* Js Part End */

	static function fix_protocol($url){
		if(!preg_match('/^\/\//', $url)){
			return $url;
		}

		if(preg_match('/^https:\/\//', home_url())){
			return 'https:'.$url;
		}

		return 'http:'.$url;
	}

	static function set_html($html){
		global $speedycache;
		
		$speedycache->enhanced['html'] = $html;
		self::set_head_html();
		self::set_body_html();
	}

	static function set_body_html(){
		global $speedycache;
		
		preg_match("/<body(.+)<\/body>/si", $speedycache->enhanced['html'], $out);

		if(isset($out[0])){
			$speedycache->enhanced['body_html'] = $out[0];
			return;
		}

		$speedycache->enhanced['body_html'] = '';
	}

	static function set_head_html(){
		global $speedycache;
		
		preg_match("/<head(.+)<\/head>/si", $speedycache->enhanced['html'], $out);

		if(isset($out[0])){
			$speedycache->enhanced['head_html'] = $out[0];
			return;
		}

		$speedycache->enhanced['head_html'] = '';

	}
	
	static function delay_js($content){
		global $speedycache;

		// If Delay js mode is selected and the scripts are empty then return
		if(empty($speedycache->options['delay_js_mode']) || (!empty($speedycache->options['delay_js_mode']) && $speedycache->options['delay_js_mode'] == 'selected' && empty($speedycache->options['delay_js_scripts']))){
			return $content;
		}
		
		$scripts = self::find_tags('<script', '</script>', $content);
		
		if(empty($scripts)){
			return $content;
		}

		foreach($scripts as $tag => $script){
			// Dont process a tag without src
			$is_inline = false;
			
			if(strpos($script['text'], ' src') === FALSE){
				$is_inline = true;
			}
			
			// We dont want to delay structured data
			if(strpos($script['text'], 'application/ld+json') !== FALSE){
				continue;
			}

			if(strpos($script['text'], 'text/template') !== FALSE){
				continue;
			}
			
			// Don't delay a module.
			if(strpos($script['text'], 'type="module"') !== FALSE){
				continue;
			}
			
			// Don't touch any import maps as they are meant to be loaded early.
			if(strpos($script['text'], 'importmap') !== FALSE){
				continue;
			}

			// We dont want to delay jQuery
			if(preg_match('/jquery\./U', $script['text'], $match)){
				continue;
			}

			// Excluding Scripts
			if($speedycache->options['delay_js_mode'] == 'all' && !empty($speedycache->options['delay_js_excludes'])){
				foreach($speedycache->options['delay_js_excludes'] as $to_delay){
					if(empty($to_delay)){
						continue;
					}

					if(strpos($script['text'], trim($to_delay)) !== FALSE){
						continue 2;
					}
				}
			}

			// Delay Selected Scripts
			if($speedycache->options['delay_js_mode'] == 'selected' && !empty($speedycache->options['delay_js_scripts'])){
				$script_found = false;
				foreach($speedycache->options['delay_js_scripts'] as $to_delay){
					if(empty($to_delay)){
						continue;
					}

					if(strpos($script['text'], trim($to_delay)) !== FALSE){
						$script_found = true;
						break;
					}
				}

				if(empty($script_found)){
					continue;
				}
			}

			$new_tag = self::updating_tag($script['text'], $is_inline);

			if(!empty($new_tag)){
				$content = str_replace($script['text'], $new_tag, $content);
			}
		}
		
		// Adds the script which loads the JS files on user interaction
		self::inject_js($content);

		return $content;

	}
	
	static function updating_tag($tag, $is_inline){
		global $speedycache;
	
		if(preg_match('/src=["\'](.*)["\']/U', $tag, $src)){
			return '<script type="speedycache/javascript" data-src="' . esc_url($src[1]) . '"></script>';
		}

		if($is_inline){
			// taking out the attributes
			preg_match_all('/<script([^>]+)?>/i', $tag, $matches);

			$attributes = [];
			// Parsing the attributes
			if(!empty($matches)){
				foreach($matches[1] as $attr_str){
					preg_match_all('/(\w+)(?:=["\']([^"\']*)["\'])?/i', trim($attr_str), $attrs, PREG_SET_ORDER);

					foreach($attrs as $attr){
						$attributes[$attr[1]] = $attr[2] ?? true;
					}
				}
			}

			// Adding our delayjs type
			$attributes['type'] = 'speedycache/javascript';
			
			// Rebulding the attributes
			$script_attr = '';
			foreach($attributes as $name => $value){
				$script_attr .= ' ' . esc_attr($name).'="'.esc_attr($value).'"';
			}

			return preg_replace('/<script([^>]+)?>/i', '<script'.$script_attr.'>', $tag);
		}
		
	}
	
	static function inject_js(&$content){
		$js = file_get_contents(SPEEDYCACHE_PRO_DIR . '/assets/js/delayjs.min.js');

		$js = '<script>'.$js.'</script>';
		$content = str_replace('</body>', $js . "\n</body>", $content);
	}
	
	static function find_tags($start_string, $end_string, $html = false){
		global $speedycache;

		if(!empty($html)){
			$data = $html;
		}

		$list = array();
		$start_index = false;
		$end_index = false;

		for($i = 0; $i < strlen($data); $i++){
			if(substr($data, $i, strlen($start_string)) == $start_string){
				if(!$start_index && !$end_index){
					$start_index = $i;
				}
			}

			if(empty($start_index) || $i < $start_index){
				continue;
			}

			if(substr($data, $i, strlen($end_string)) !== $end_string){
				continue;
			}
			
			$end_index = $i + strlen($end_string) - 1;
			$text = substr($data, $start_index, ($end_index - $start_index + 1));

			if($html === false){
				$tag = self::get_tags($start_index, $text, $end_index);

				if($tag !== FALSE){
					array_push($list, $tag);
				}
			}else{
				array_push($list, array('start' => $start_index, 'end' => $end_index, 'text' => $text));
			}

			$start_index = false;
			$end_index = false;
		}

		return $list;
	}
	
	// Adds Image dimensions to the images where height and width is not present
	// It helps in reducing the Cumulative Layout shift(CLS) as the browser knows how much space to allocate for the image.
	static function image_dimensions($content){
		
		if(!function_exists('getimagesize')){
			return $content;
		}
		
		// Get Images without height and width
		$images_regex = '<img(?:[^>](?!height=[\'\"](?:\S+)[\'\"]))*+>|<img(?:[^>](?!width=[\'\"](?:\S+)[\'\"]))*+>';

		preg_match_all('/'.$images_regex.'/Uis', $content, $image_matches);

		if(empty($image_matches)){
			return $content;
		}

		$images = $image_matches[0];
		$site_url = site_url();
		
		foreach($images as $image){

			// Get the SRC
			if(!preg_match( '/\s+src\s*=\s*[\'"](?<url>[^\'"]+)/i', $image, $src_match)){
				continue;
			}
			
			$url = $src_match['url'];

			// We will proccess image which is uploaded inside wp-content
			if(strpos($url, 'wp-content') === FALSE || strpos($url, '.svg') !== FALSE || strpos($url, $site_url) === FALSE){
				continue;
			}

			$url = str_replace($site_url, '', $url);
			$image_path = str_replace('/wp-content', '', WP_CONTENT_DIR) . $url;
	
			if(!file_exists($image_path)){
				continue;
			}

			$sizes = getimagesize($image_path);

			if(empty($sizes)){
				continue;
			}

			preg_match('/<img.*\sheight=[\'\"]?(?<height>[^\'\"\s]+)[\'\"]?.*>/i', $image, $initial_height);
			preg_match('/<img.*\swidth=[\'\"]?(?<width>[^\'\"\s]+)[\'\"]?.*>/i', $image, $initial_width);

			$dimensions_attr = '';

			if(empty($initial_height['height']) && empty($initial_width['width'])){
				$dimensions_attr = $sizes[3];
			}

			if(!empty($initial_height['height']) && empty($dimensions_attr)){
				if(!is_numeric($initial_height['height'])){
					continue;
				}

				$ratio = $initial_height['height'] / $sizes[1];

				$dimensions_attr = 'width="' . (int) round($sizes[0] * $ratio) . '" height="' . $initial_height['height'] . '"';
			}

			if(!empty($initial_width['width']) && empty($dimensions_attr)){
				if(!is_numeric( $initial_width['width'])){
					continue;
				}

				$ratio = $initial_width['width'] / $sizes[0];

				$dimensions_attr = 'width="' . $initial_width['width'] . '" height="' . (int) round($sizes[1] * $ratio) . '"';
			}
			
			$changed_image = preg_replace('/\s(height|width)=(?:[\'"]?(?:[^\'\"\s]+)*[\'"]?)?/i', '', $image);
			$changed_image = preg_replace('/<\s*img/i', '<img ' . $dimensions_attr, $changed_image);

			if(!empty($changed_image)){
				$content = str_replace($image, $changed_image, $content);
			}

		}
		
		return $content;
	}
	
	// Lazy Loads HTML elements.
	static function lazy_load_html($content){
		global $speedycache;

		$content = str_replace('</head>', '<style>' . implode(',', $speedycache->options['lazy_load_html_elements']) . '{content-visibility:auto;contain-intrinsic-size:1px 1000px;}</style></head>', $content);
		
		return $content;
	}
	
	static function preload_critical_images($content){
		global $speedycache;
		
		preg_match_all('#(<picture.*?)?<img([^>]+?)\/?>(?><\/picture>)?#is', $content, $images, PREG_SET_ORDER);

		if(empty($images)){
			return $content;
		}

		$count = 0;
		$preload_tags = '';
		foreach($images as $image){

			// Break once the Critical Image Count is reached.
			if($count >= $speedycache->options['critical_image_count']){
				break;
			}

			if(strpos($image[0], 'secure.gravatar.com') !== FALSE){
				continue;
			}

			// NOTE:: Will remove this in future, firt we will just support <IMG> tag
			if(strpos($image[0], '<picture>') !== FALSE){
				continue;
			}

			// Excluding base64 image from preloading.
			if(strpos($image[0], ';base64') !== FALSE){
				continue;
			}

			$atts_array = wp_kses_hair($image[2], wp_allowed_protocols());
			$atts = [];

			foreach($atts_array as $name => $attr){
				$atts[$name] = $attr['value'];
			}

			if(empty($atts['src'])){
				continue;
			}
			
			// To preload unique images.
			if(strpos($preload_tags, $atts['src']) === FALSE){
				$preload_tags .= '<link rel="preload" as="image" href="'.esc_attr($atts['src']).'"'. (!empty($atts['srcset']) ? ' imagesrcset="'. esc_attr($atts['srcset']).'"' : '') . (!empty($atts['sizes']) ? 'imagesizes="'.esc_attr($atts['sizes']).'"' : '') . ' />';
			}

			$count++;
		}

		if(empty($preload_tags)){
			return $content;
		}

		// If title tag is not there then don't add the preload.
		if(strpos($content, '</title>') === FALSE){
			return $content;
		}

		$content = str_replace('</title>', '</title>' . $preload_tags, $content);

		return $content;
	}
	
	static function pre_connect_hint($urls, $relation_type){
		global $speedycache;

		if($relation_type !== 'preconnect'){
			return $urls;
		}

		foreach($speedycache->options['pre_connect_list'] as $url) {
			if(empty($url) || empty($url['resource'])){
				continue;
			}
			
			$preconnect = array('href' => $url['resource']);

			if(!empty($url['crossorigin'])){
				$preconnect['crossorigin'] = 'crossorigin'; 
			}
			
			$urls[] = $preconnect;
			
		}

		return $urls;
	}

	static function preload_resource(){
		global $speedycache;

		if(empty($speedycache->options['preload_resource_list']) || !is_array($speedycache->options['preload_resource_list'])){
			return;
		}

		foreach($speedycache->options['preload_resource_list'] as $preload_resource){
			if(empty($preload_resource['resource']) || empty($preload_resource['type'])){
				continue;
			}

			$crossorigin = '';
			if(!empty($preload_resource['crossorigin'])){
				$crossorigin = 'crossorigin';
			}

			echo '<link rel="preload" href="'.esc_url_raw($preload_resource['resource']).'" as="'.esc_attr($preload_resource['type']).'" '.esc_attr($crossorigin) .'/>';
		}
	}

}
main/unusedcss.php000064400000016717151526423640010241 0ustar00<?php

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c) SpeedyCache Team
*/

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('Hacking Attempt');
}

class UnusedCss extends CommonCss{

	static function generate($urls){
		global $speedycache;

		$time = time() + 50;
		set_time_limit(60);
		
		$api = self::get_endpoint(true);
		
		if(empty($urls)){
			self::log('speedycache_unused_css_logs', 'URL not found');
			return false;
		}

		if(empty($speedycache->license['license'])){
			self::log('speedycache_unused_css_logs', 'License Not found, please link your License');
			return false;
		}

		foreach($urls as $url){
			// Handeling php timeout here
			if($time < time()){
				$urls = array_diff($urls, $attempted_url);
				self::schedule('speedycache_unused_css', $urls);
				return;
			}

			$url = trim($url, '/');
			$license = strpos($speedycache->license['license'], 'SPDFY') !== 0 ? '' : $speedycache->license['license'];
			$attempted_url[] = $url;

			$response = wp_remote_post($api, array(
				'timeout' => 30,
				'body' => array(
					'url' => $url,
					'license' => $license,
					'excludes' => !empty($speedycache->options['unused_css_exclude_stylesheets']) ? json_encode($speedycache->options['unused_css_exclude_stylesheets']) : '',
					'include_selectors' => !empty($speedycache->options['speedycache_unusedcss_include_selector']) ? json_encode($speedycache->options['speedycache_unusedcss_include_selector']) : '',
				),
				'sslverify' => false,
			));

			if(is_wp_error($response)){
				$error = $response->get_error_message();
				self::log('speedycache_unused_css_logs', $response->get_error_message(), $url);
				continue;
			}

			$body = json_decode(wp_remote_retrieve_body($response), true);

			if(empty($body)){
				$error = __('The response recieved is empty.', 'speedycache');
				self::log('speedycache_unused_css_logs', __('The response recieved is empty.', 'speedycache'), $url);
				continue;
			}

			if(empty($body['success'])){
				$error = !empty($body['message']) ? wp_strip_all_tags($body['message']) : __('Unable to extract UsedCSS', 'speedycache');
				self::log('speedycache_unused_css_logs', !empty($body['message']) ? wp_strip_all_tags($body['message']) : __('Unable to extract UsedCSS', 'speedycache'), $url);
				continue;
			}

			if(empty($body['css']) || strlen($body['css']) < 20){
				$error = __('Was unable to generate Used CSS', 'speedycache');
				self::log('speedycache_unused_css_logs', __('Was unable to generate Used CSS', 'speedycache'), $url);
				continue;
			}

			self::update_css($url, $body['css']);

			self::log('speedycache_unused_css_logs', 'success', $url); //Updates the log on success
			
			if(!empty($error)){
				return $error;
			}

			return true;
		}
	}
	
	// Adds the generated css and asynchronyses the css includes
	static function update_css($url, $css){
		global $speedycache;

		if(empty($url)){
			return false;
		}
		
		if(empty($css)){
			return false;
		}

		$css = '<style id="speedycache-used-css">'. "\n". wp_strip_all_tags($css) . '</style>';

		$url = parse_url($url);
		$uri = !empty($url['path']) ?  $url['path'] : '';
		$cache_loc = $uri . '/index.html';

		if(empty($cache_loc)){
			return;
		}
		
		if(!empty($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] === 'SpeedyCacheTest'){
			$cache_path = speedycache_cache_path('test' . $cache_loc);
		} else {
			$cache_path = speedycache_cache_path('all' . $cache_loc);
		}
		
		$cache_path = rtrim($cache_path, '/');
		
		// For Desktop
		\SpeedyCache\UnusedCss::update_cached($cache_path, $css);

		if(!empty($speedycache->options['mobile_theme']) && $_SERVER['HTTP_USER_AGENT'] !== 'SpeedyCacheTest'){
			$cache_mobile = speedycache_cache_path('mobile-cache' . $cache_loc);

			// For Mobile Cache
			if(file_exists($cache_mobile)){
				\SpeedyCache\UnusedCss::update_cached($cache_mobile, $css);
			}
		}
	}

	// Updates the content of the cached file
	static function update_content($content, $css){
		global $speedycache;

		// Includes the Used CSS file in the head.
		$content = str_replace('</title>', '</title>' . $css, $content);

		$css_links = '/(?=<link[^>]*\s(rel\s*=\s*[\'"]stylesheet["\']))<link[^>]*\shref\s*=\s*[\'"]([^\'"]+)[\'"](.*)>/iU';
		
		preg_match_all($css_links, $content, $matches, PREG_SET_ORDER, 0);
		
		if(empty($matches)){
			return $content;
		}
		
		$exclude_stylesheets = array(
			'/widget-google-reviews/assets/css/public-main.css',
			'/uploads/elementor/css/post-',
			'/uploads/oxygen/css/',
			'/uploads/bb-plugin/cache/',
			'/et-cache/',
			'woocommerce-smallscreen.css',
			'dashicons.min.css',
			'animations.min.css',
			'/uploads/generateblocks/',
			'woocommerce-mobile.min.css',
			'fonts.googleapis.com',
		);
		
		// Mergeing user added excludes which the one we have.
		if(!empty($speedycache->options['unused_css_exclude_stylesheets']) && !is_array($speedycache->options['unused_css_exclude_stylesheets'])){
			$exclude_stylesheets = array_merge($exclude_stylesheets, $speedycache->options['unused_css_exclude_stylesheets']);
		}
		
		$noscript_wrap = '';
		
		foreach($matches as $tag){

			foreach($exclude_stylesheets as $style){
				if(strpos($tag[0], $style) !== FALSE){
					continue 2;
				}
			}
			
			// We dont want to delay te Used CSS file
			if(strpos($tag[0], 'unused-css') !== FALSE){
				continue;
			}

			// Removing the styles after getting unused css
			if(!empty($speedycache->options['unusedcss_load']) && $speedycache->options['unusedcss_load'] === 'remove'){
				$content = str_replace($tag[0], '', $content);		
			} elseif(!empty($speedycache->options['unusedcss_load']) && $speedycache->options['unusedcss_load'] === 'interaction'){
				$new_tag = preg_replace('#href=([\'"]).+?\1#', 'data-spcdelay="' . $tag[2] . '"',$tag[0]);
			
				$content = str_replace($tag[0], $new_tag, $content);
				
				$noscript_wrap .= $tag[0];
			} else {
				// Loading the Unused CSS Async
				$preload = str_replace('stylesheet', 'preload', $tag[1]);
				$onload = preg_replace('~' . preg_quote($tag[3], '~') . '~iU', ' as="style" onload="" ' . $tag[3] . '>', $tag[3]);

				$new_tag = str_replace($tag[3] . '>', $onload, $tag[0]);
				$new_tag = str_replace($tag[1], $preload, $new_tag);
				$new_tag = str_replace('onload=""', 'onload="this.onload=null;this.rel=\'stylesheet\'"', $new_tag);
				$new_tag = preg_replace('/(id\s*=\s*[\"\'](?:[^\"\']*)*[\"\'])/i', '', $new_tag);

				$content = str_replace($tag[0], $new_tag, $content);
				
				$noscript_wrap .= $tag[0];
			}
		}
		
		if(!empty($noscript_wrap)){
			$noscript_wrap .= '</noscript>';
			
			if(!empty($speedycache->options['unusedcss_load']) && $speedycache->options['unusedcss_load'] === 'interaction'){
				$noscript_wrap .= '<script type="text/javascript" id="speedycache-delayed-styles">!function(){const e=["keydown","mousemove","wheel","touchmove","touchstart","touchend"];function t(){document.querySelectorAll("link[data-spcdelay]").forEach(function(e){e.setAttribute("href",e.getAttribute("data-spcdelay"))}),e.forEach(function(e){window.removeEventListener(e,t,{passive:!0})})}e.forEach(function(e){window.addEventListener(e,t,{passive:!0})})}();</script>';
			}
			
			$noscript_wrap = '<noscript>' . $noscript_wrap;
		
			$content = str_replace($noscript_wrap, '', $content);
			
			$content = str_replace('</body>', $noscript_wrap . '</body>', $content);
		}

		return $content;
	}
}
main/objectcache.php000064400000020261151526423640010444 0ustar00<?php

namespace SpeedyCache;

if(!defined('ABSPATH')){
	die('HACKING ATTEMPT!');
}

class ObjectCache{
	static $oc_driver = 'Redis';
	static $port = '6379';
	static $host = '127.0.0.1';
	static $conn;
	static $ttl = 360; // in seconds
	static $is_multisite = false;
	static $blog_id;
	static $prefix = 'speedycache';
	static $conf_file = WP_CONTENT_DIR . '/.speedycache-object.dat';
	static $conf;
	static $instance;
	static $persistent;
	static $async_flush;
	static $serialize;
	static $non_cache_group;
	
	static function get_instance(){
		if(self::$instance){
			return self::$instance;
		}

		self::$instance = new self();
		
		try{
			self::boot();
		} catch(\Exception $e){
			// Don't need to log here as the error has been already logged before, this it just to prevent error
		}

		return self::$instance;
	}

	static function boot(){
		self::$conf = self::get_conf();

		self::$host = !empty(self::$conf['host']) ? self::$conf['host'] : '127.0.0.1';
		self::$port = !empty(self::$conf['port']) ? self::$conf['port'] : '6379';
		self::$ttl = !empty(self::$conf['ttl']) ? (int) self::$conf['ttl'] : 360;
		self::$persistent = !empty(self::$conf['persistent']) ? true : false;
		self::$async_flush = !empty(self::$conf['async_flush']) ? true : false;
		self::$serialize = !empty(self::$conf['serialization']) ? self::$conf['serialization'] : 'none';
		$compress = !empty(self::$conf['compress']) ? self::$conf['compress'] : 'COMPRESSION_NONE';
		self::$non_cache_group = (!empty(self::$conf['non_cache_group']) && is_array(self::$conf['non_cache_group'])) ? self::$conf['non_cache_group'] : [];
		self::$prefix = !empty(self::$conf['hashed_prefix']) ? self::$conf['hashed_prefix'] : '';

		if(self::$host === 'localhost'){
			self::$host = '127.0.0.1';
		}
		
		if(empty(self::connect())){
			error_log('SpeedyCache: Unable to connect to Redis');
			return false;
		}
		
		try{
			
			switch(self::$serialize){
				case 'SERIALIZER_PHP':
					self::$conn->setOption(self::$conn::OPT_SERIALIZER, self::$conn::SERIALIZER_PHP);
					break;
					
				case 'SERIALIZER_IGBINARY':
					self::$conn->setOption(self::$conn::OPT_SERIALIZER, self::$conn::SERIALIZER_IGBINARY);
					break;
					
				default:
					self::$conn->setOption(self::$conn::OPT_SERIALIZER, self::$conn::SERIALIZER_NONE);
					break;
			}

			switch($compress){
				case 'COMPRESSION_NONE':
					self::$conn->setOption(self::$conn::OPT_COMPRESSION, self::$conn::COMPRESSION_NONE);
					break;
					
				case 'COMPRESSION_ZSTD':
					self::$conn->setOption(self::$conn::OPT_COMPRESSION, self::$conn::COMPRESSION_ZSTD);
					self::$conn->setOption(self::$conn::OPT_COMPRESSION_LEVEL, (string) -5);
					break;
					
				case 'COMPRESSION_LZ4':
					self::$conn->setOption(self::$conn::OPT_COMPRESSION, self::$conn::COMPRESSION_LZ4);
					break;

				case 'COMPRESSION_LZF':
					self::$conn->setOption(self::$conn::OPT_COMPRESSION, self::$conn::COMPRESSION_LZF);
					break;
					
			}

		} catch(\RedisException $e){
			error_log($e->getMessage());
			throw new \Exception($e->getMessage()); // To show on settings page
			return false;
		}

	}
	
	static function get_conf(){
		if(!file_exists(self::$conf_file)){
			return [];
		}

		$conf = file_get_contents(self::$conf_file);
		
		if(empty($conf)){
			error_log('SpeedyCache: Conf file was empty');
			return;
		}

		return json_decode($conf, true);
	}
	
	// Creates a unique id based on blogID, group and key
	static function id($key, $group){
		return self::$prefix  . ':' . self::$blog_id.$group . ':' . $key;
	}
	
	// Updates object-cache.php file at wp-content/object-cache.php
	static function update_file(){
		$file = WP_CONTENT_DIR . '/object-cache.php';
		
		if(!file_exists($file)){
			touch($file);
		}
		
		$code = '<?php

if(!defined("WPINC")){
	die();
}

if(!defined("SPEEDYCACHE_OBJECT_CACHE")){
	define("SPEEDYCACHE_OBJECT_CACHE", true);
}

$plugin_dir = (defined("WP_PLUGIN_DIR") ? WP_PLUGIN_DIR : WP_CONTENT_DIR . "/plugins") . "/speedycache-pro";
$conf_file = WP_CONTENT_DIR . "/.speedycache-object.dat";
$lib_file = $plugin_dir . "/main/object-cache-lib.php";


if(file_exists($plugin_dir) && file_exists($conf_file) && file_exists($lib_file)){
	$spdf_config = file_get_contents($conf_file);
	$spdf_config = json_decode($spdf_config, true);
	
	if (! SPEEDYCACHE_OBJECT_CACHE || (empty($spdf_config["admin"]) && defined("WP_ADMIN"))){
		wp_using_ext_object_cache(false);
	}else if (file_exists($lib_file)) {
		include_once $lib_file;
	}
}';
		file_put_contents($file, $code);

	}
	
	static function connect(){

		if(!empty(self::$conn)){
			return true;
		}
		
		if(!class_exists(self::$oc_driver)){
			error_log('SpeedyCache: The defined driver ' . self::$oc_driver . 'not present');
			return false;
		}
		
		$failed = false;
		$is_socket = false;
		
		if(strpos(self::$host, '.sock')){
			$is_socket = true;
		}

		$persistent = !empty(self::$persistent) ? 'pconnect' : 'connect';

		if(self::$oc_driver == 'Redis'){

			try {
				self::$conn = new \Redis();
				
				if($is_socket){
					self::$conn->{$persistent}(self::$host);
				} else {
					self::$conn->{$persistent}(self::$host, self::$port);
				}
				
				if(!empty(self::$conf['username']) && !empty(self::$conf['password'])){
					self::$conn->auth(['user' => self::$conf['username'], 'pass' => self::$conf['password']]);
				} else if(!empty(self::$conf['password'])){
					self::$conn->auth(self::$conf['password']);
				}

				// Testing if connection worked
				$res = self::$conn->ping();
				
				if(empty($res) && $res !== '+PONG'){
					$failed = true;
				}
				
				if(!empty($failed)){
					self::$conn = null;
					return false;
				}

				self::$conn->select((int) (!empty(self::$conf['db-id']) ? self::$conf['db-id'] : 0));

			}catch(\RedisException $e){
				error_log('SpeedyCache' . $e->getMessage());
				throw new \Exception($e->getMessage()); // To show on settings page
				return false;
			}
			catch(\Exception $e){
				error_log('SpeedyCache  ->>' . $e->getMessage());
				throw new \Exception($e->getMessage()); // To show on settings page
			}
		}
		
		return true;

	}
	
	static function set($key, $data, $expire = 0){
		
		if(empty(self::$conn)){
			return false;
		}

		$ttl = $expire ?: self::$ttl;
		
		if((is_array($data) || is_object($data)) && self::$serialize === 'none'){
			$data = serialize($data);
		}
		
		$key = self::$prefix . $key;

		try{
			$res = self::$conn->setEx($key, $ttl, $data);
		} catch (\RedisException $ex) {
			error_log($ex->getMessage());
		}
	}
	
	static function get($key){
		
		if(empty(self::$conn)){
			return false;
		}
		
		$key = self::$prefix . $key;

		try{
			return self::$conn->get($key);
		}catch(\RedisException $e){
			error_log($e->getMessage());
			return false;
		}
	}
	
	static function exists($key){
		
		if(empty(self::$conn)){
			return false;
		}
		
		$key = self::$prefix . $key;

		try{
			return self::$conn->exists($key);
		}catch(\RedisException $e){
			error_log($e->getMessage());
			return false;
		}
	}
	
	static function delete($key){
		
		$del = self::$async_flush ? 'unlink' : 'del';

		if(empty(self::$conf['enable'])){
			return false;
		}
		
		if(empty(self::$conn)){
			return false;
		}

		$key = self::$prefix . $key;

		try{
			self::$conn->{$del}($key);
		} catch(\RedisException $e){
			error_log($e->getMessage());
			return false;
		}
	}
	
	static function get_memory(){
		self::boot();
		
		if(empty(self::$conn)){
			return 'None';
		}
		
		try{
			$memory = self::$conn->info('memory');
		} catch(\RedisException $e){
			error_log($e->getMessage());
			return 'None';
		}
		
		if(!empty($memory['used_memory'])){
			return size_format($memory['used_memory']);
		}

		return 'None';
	}
	
	// Flushes whole database
	static function flush_db($sync = true){
		if(empty(self::$conf['enable'])){
			return false;
		}

		if(empty(self::$conn)){
			return false;
		}
		
		try{
			return self::$conn->flushDb($sync);
		} catch(\RedisException $e){
			error_log($e->getMessage());
			return false;
		}
	}

}


upgrader.php000064400000013452151526423640007103 0ustar00<?php

// Are we being accessed directly ?
if(!defined('SPEEDYCACHE_PRO_VERSION')) {
	exit('Hacking Attempt !');
}

// Ok so we are now ready to go
register_activation_hook(SPEEDYCACHE_PRO_FILE, 'speedycache_pro_activate');

// Prevent update of speedycache free
// This also work for auto update
add_filter('site_transient_update_plugins', 'speedycache_pro_disable_manual_update_for_plugin');
add_filter('pre_site_transient_update_plugins', 'speedycache_pro_disable_manual_update_for_plugin');

// Auto update free version after update pro version
add_action('upgrader_process_complete', 'speedycache_pro_update_free_after_pro', 10, 2);

if(!class_exists('SpeedyCache')){
#[\AllowDynamicProperties]
class SpeedyCache{}
}

add_action('plugins_loaded', 'speedycache_pro_load_plugin');
function speedycache_pro_load_plugin(){
	global $speedycache;
	
	if(empty($speedycache)){
		$speedycache = new \SpeedyCache();
	}
	
	speedycache_pro_load_license();
	
	// Check if the installed version is outdated
	speedycache_pro_update_check();
	
	// Check for updates
	include_once(SPEEDYCACHE_PRO_DIR.'/main/plugin-update-checker.php');
	$speedycache_updater = SpeedyCache_PucFactory::buildUpdateChecker(speedycache_pro_api_url().'/updates.php?version='.SPEEDYCACHE_PRO_VERSION, SPEEDYCACHE_PRO_FILE);
	
	// Add the license key to query arguments
	$speedycache_updater->addQueryArgFilter('speedycache_pro_updater_filter_args');
	
	// Show the text to install the license key
	add_filter('puc_manual_final_check_link-speedycache-pro', 'speedycache_pro_updater_check_link', 10, 1);
	
	// Nag informing the user to install the free version.
	if(current_user_can('activate_plugins')){
		add_action('admin_notices', 'speedycache_pro_free_version_nag', 9);
		add_action('admin_menu', 'speedycache_pro_add_menu', 9);
	}
	
	$is_network_wide = speedycache_pro_is_network_active('speedycache-pro');
	$_sc_version = get_option('speedycache_version');
	$req_free_update = !empty($_sc_version) && version_compare($_sc_version, '1.2.0', '<');
	
	if($is_network_wide){
		$sc_free_installed = get_site_option('speedycache_free_installed');
	}else{
		$sc_free_installed = get_option('speedycache_free_installed');
	}
	
	if(!empty($sc_free_installed)){
		return;
	}
	
	// Include the necessary stuff
	include_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
	include_once(ABSPATH . 'wp-admin/includes/plugin.php');
	include_once(ABSPATH . 'wp-admin/includes/file.php');
	
	if( file_exists( WP_PLUGIN_DIR . '/speedycache/speedycache.php' ) && is_plugin_inactive( '/speedycache/speedycache.php' ) && empty($req_free_update) ) {
		
		if($is_network_wide){
			update_site_option('speedycache_free_installed', time());
		}else{
			update_option('speedcache_free_installed', time());
		}
		
		activate_plugin('/speedycache/speedycache.php', '', $is_network_wide);
		remove_action('admin_notices', 'speedycache_pro_free_version_nag', 9);
		remove_action('admin_menu', 'speedycache_pro_add_menu', 9);
		return;
	}

	// Includes necessary for Plugin_Upgrader and Plugin_Installer_Skin
	include_once(ABSPATH . 'wp-admin/includes/misc.php');
	include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');

	// Filter to prevent the activate text
	add_filter('install_plugin_complete_actions', 'speedycache_pro_prevent_activation_text', 10, 3);

	$upgrader = new Plugin_Upgrader(new WP_Ajax_Upgrader_Skin());

	// Upgrade the plugin to the latest version of free already installed.
	if(!empty($req_free_update) && file_exists( WP_PLUGIN_DIR . '/speedycache/speedycache.php' )){
		$installed = $upgrader->upgrade('speedycache/speedycache.php');
	}else{
		$installed = $upgrader->install('https://downloads.wordpress.org/plugin/speedycache.zip');
	}
	
	if(!is_wp_error($installed) && $installed){
		
		if($is_network_wide){
			update_site_option('speedycache_free_installed', time());
		}else{
			update_option('speedycache_free_installed', time());
		}
		
		activate_plugin('speedycache/speedycache.php', '', $is_network_wide);
		remove_action('admin_notices', 'speedycache_pro_free_version_nag', 9);
		remove_action('admin_menu', 'speedycache_pro_add_menu', 9);
	}
}

// Do not shows the activation text if 
function speedycache_pro_prevent_activation_text($install_actions, $api, $plugin_file){
	if($plugin_file == 'speedycache/speedycache.php'){
		return array();
	}

	return $install_actions;
}

function speedycache_pro_free_version_nag(){
	
	$sc_version = get_option('speedycache_version');
	
	$lower_version = __('You have not installed/activated the free version of SpeedCache. SpeedyCache Pro depends on the free version, so you must install/activate it first in order to use SpeedyCache Pro.');
	$btn_text = __('Install / Activate Now');
	
	if(!empty($sc_version) && version_compare($sc_version, '1.2.0', '<')){
		$lower_version = __('You are using an older version of the free version of SpeedyCache, please update SpeedyCache to work without any issues');
		$btn_text = __('Update Now');
	}

	echo '<div class="notice notice-error">
		<p style="font-size:16px;">'.esc_html($lower_version).' <a href="'.admin_url('plugin-install.php?s=speedycache&tab=search').'" class="button button-primary">'.esc_html($btn_text).'</a></p>
	</div>';
}

function speedycache_pro_add_menu(){
	add_menu_page('SpeedyCache', 'SpeedyCache Pro', 'activate_plugins', 'speedycache-pro', 'speedycache_pro_menu_page');
}

function speedycache_pro_menu_page(){
	echo '<div style="color: #333;padding: 50px;text-align: center;">
		<h1 style="font-size: 2em;margin-bottom: 10px;">SpeedyCache Free version is not installed / outdated!</h>
		<p style=" font-size: 16px;margin-bottom: 20px; font-weight:400;">SpeedyCache Pro depends on the free version of SpeedyCache, so you need to install / update the free version first.</p>
		<a href="'.admin_url('plugin-install.php?s=speedycache&tab=search').'" style="text-decoration: none;font-size:16px;">Install/Update Now</a>
	</div>';
}license.txt000064400000104515151526423640006745 0ustar00                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
speedycache-pro.php000064400000004731151526423640010345 0ustar00<?php
/*
Plugin Name: SpeedyCache Pro
Plugin URI: https://speedycache.com
Description: SpeedyCache is a plugin that helps you reduce the load time of your website by means of caching, minification, and compression of your website.
Version: 1.3.2
Author: Softaculous Team
Author URI: https://speedycache.com/
Text Domain: speedycache
Require Plugins: speedycache
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html
*/

/*
* SPEEDYCACHE
* https://speedycache.com/
* (c 2024) SpeedyCache Team
*/

/*
SpeedyCache is fork of WP Fastest Cache :
https://wordpress.org/plugins/wp-fastest-cache/
Copyright (C) 2013 Emre Vona

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.	
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
*/

// We need the ABSPATH
if(!defined('ABSPATH')) exit;

if(!function_exists('add_action')){
	echo 'You are not allowed to access this page directly.';
	exit;
}

// If SPEEDYCACHE_PRO_VERSION exists then the plugin is loaded already !
if(defined('SPEEDYCACHE_PRO_VERSION')){
	return;
}

// Constants
define('SPEEDYCACHE_PRO', plugin_basename(__FILE__));
define('SPEEDYCACHE_PRO_FILE', __FILE__);
define('SPEEDYCACHE_PRO_VERSION', '1.3.2');
define('SPEEDYCACHE_PRO_DIR', dirname(__FILE__));
define('SPEEDYCACHE_PRO_BASE', 'speedycache-pro/speedycache-pro.php');
define('SPEEDYCACHE_PRO_BASE_NAME', basename(SPEEDYCACHE_PRO_DIR));
define('SPEEDYCACHE_PRO_URL', plugins_url('', __FILE__));

if(!defined('SPEEDYCACHE_API')){
	define('SPEEDYCACHE_API', 'https://api.speedycache.com/');
}

$_tmp_plugins = get_option('active_plugins');
$_sc_version = get_option('speedycache_version');

include_once SPEEDYCACHE_PRO_DIR . '/functions.php';

if(
	!defined('SITEPAD') && (
	!(in_array('speedycache/speedycache.php', $_tmp_plugins) || 
	speedycache_pro_is_network_active('speedycache')) || 
	!file_exists(WP_PLUGIN_DIR . '/speedycache/speedycache.php') || 
	(!empty($_sc_version) && version_compare($_sc_version, '1.2.0', '<')))
){
	include_once(SPEEDYCACHE_PRO_DIR .'/upgrader.php');
	return;
}

include_once(__DIR__ . '/init.php');