WordPress Cos-html-cache Cache Plugin Source code interpretation

Source: Internet
Author: User
Tags explode file size flock hash html page php file sql error strlen
The code is as follows Copy Code

/* Config */
Whether to create a static file on the first page
Define (' Is_index ', true);/false = does not create home page cache

/*end of config*/

Define (' cosversion ', ' 2.7.3 '); To define a plug-in version

The introduction of WP's file operation function, which will be used in the following Get_home_path
Require_once (Abspath. ' wp-admin/includes/file.php ');
/* End of Config * *
$sm _locale = Get_locale (); Getting the language environment to facilitate localized processing later

To get a localized translation document corresponding to the locale, of course, now only Chinese cosbeta-zh_cn.mo
$sm _mofile = dirname (__file__). "/cosbeta-$sm _locale.mo";
Load localized translations (Http://codex.wordpress.org/Function_Reference/load_textdomain)
Load_textdomain (' Cosbeta ', $sm _mofile);
Get the URL of the blog site (http://codex.wordpress.org/Option_Reference)
$cossithome = get_option (' home ');
Get the full URL of the call link
$script _uri = RTrim ("http://". $_server["Http_host"].$_server["Request_uri"], "/");
$home _path = Get_home_path (); Get the absolute physical directory that WP installed

Define (' Script_uri ', $script _uri); Define Call Link
Define (' Cossitehome ', $cossithome); Define Site URL
Define (' Cosblogpath ', $home _path); Define site Installation Physical location
Define plug-in entry Mark
Define ("Cosmeta", "<!--this are a real static HTML file created at". Date ("Y-m-d h:i:s").
"By Cos-html-cache". Cosversion. "-->");

function to create a static file
function Createhtmlfile ($FilePath, $Content) {
Remove some illegal symbols from the filename
$FilePath = Preg_replace ('/[<>\ ') \r\n\t\ (\)]/', ', $FilePath);

If there is http://$FilePath'll return to its BAS path
Separate file paths, such as/home/xxx/xxx/xxx/xxx.html,
If it is similar to http://xxx.com/html/y2012/xxx.html, the/html/y2012/xxx.html will be passed in
(http://cn2.php.net/manual/zh/function.explode.php)
$dir _array = Explode ("/", $FilePath);

Split the FilePath
$max _index = count ($dir _array);
$i = 0;
$path = $_server[' Document_root ']. " /"; Get the root directory of a Web site, such as/home/username/

while ($i < $max _index) {
$path. = "/" $dir _array[$i]; The first level of the directory added to the path
$path = Str_replace ("//", "/", $path); If there is//is replaced by/

if ($dir _array[$i] = = "") {//Skip over if the directory value is empty, this judgment may be more appropriate at the front of the loop
$i + +;
Continue
}
The code above seems to be more concise.

if (Substr_count ($path, ' & ')) return true; If there are & symbols in the path, this is difficult to handle, regardless of
if (Substr_count ($path, '? ')) return true; Yes? I don't care.
if (!substr_count ($path, '. htm ')) {//If No. htm is included, a path has been sent in.
If is a directory
If the path does not exist, the cheap, and read and write run right, if exist, that 80% is also here the cheap
if (!file_exists ($path)) {
@mkdir ($path, 0777);
@chmod ($path, 0777);
}
}
$i + +; Get this done.
}

if (Is_dir ($path)) {//If the above toss, the discovery is a directory, that is, to create index.html
$path = $path. " /index.html ";
}
If the HTML page is not created intact, it still doesn't matter.
if (!strstr strtolower ($Content), '

If SQL Error Ignore ...
$fp = @fopen ($path, "w+"); Okay, start writing, the file is ready to cover the content, not on the cheap
if ($FP) {//description has permission to write
@chmod ($path, 0666); Assign permissions to a file first
@flock ($fp, LOCK_EX); Lock

Write the file.
Fwrite ($fp, $Content);//write Static file contents
@flock ($fp, Lock_un); Unlock
Fclose ($FP); Done
}
}

/* Read the content from output buffer */
After the user login, will have movement, first initialized to no matter, this is a very good habit,
In order to be safe, the general does not understand the thing or avoid forget
$is _buffer = false;
If the URL that is called is/year/y2012/xxx.html or accessed is the Web site URL
if (Substr_count ($_server[' Request_uri '), '. htm ') | | (Script_uri = = Cossitehome)) {
if (strlen ($_cookie[' Wordpress_logged_in_ '). Cookiehash] < 4) {//user logged in, estimated to work
$is _buffer = true;
}
if (Substr_count ($_server[' Request_uri '], '? ')) $is _buffer = false; Parameter call, hide
if (Substr_count ($_server[' Request_uri '), '.. /') $is _buffer = false; It's too dangerous to avoid.
}

if ($is _buffer) {//I really have to work.
Ob_start (' Cos_cache_ob_callback '); Open Dry
Register_shutdown_function (' Cos_cache_shutdown_callback '); The climax and the end, soon
}

function Cos_cache_ob_callback ($buffer) {//Here is the output buffer from WP to get content ready to write to the static file
The following a bunch of regular expressions, not for the average person, I am the average person, so do not read
But apparently in the process of commenting on the relevant information
$buffer = Preg_replace ('/(<\s*input[^>]+? name=["\ ']author[\ '"]) [^>]+?value= (["\]])" ([^] \]+?) \3/i ', ' \1\3 ', $buffer);

$buffer = Preg_replace ('/(<\s*input[^>]+?value=) ([\ ' "]) [^\ ']]+\2 ([^>]+?name=[\ '"]author[\ ' "])/I ', ' \1 '" \ 3 ', $buffer);

$buffer = Preg_replace ('/(<\s*input[^>]+? name=["\ ']url[\ '"]) [^>]+?value= (["\]])" ([^] \]+?) \3/i ', ' \1\3 ', $buffer);

$buffer = Preg_replace ('/(<\s*input[^>]+?value=) ([\ ' "]) [^\ ']]+\2 ([^>]+?name=[\ '"]url[\ ' "])/I ', ' \1 ', ' \3 ', $buffer);

$buffer = Preg_replace ('/(<\s*input[^>]+? name=["\ ']email[\ '"]) [^>]+?value= (["\]])" ([^] \]+?) \3/i ', ' \1\3 ', $buffer);

$buffer = Preg_replace ('/(<\s*input[^>]+?value=) ([\ ' "]) [^\ ']]+\2 ([^>]+?name=[\ '"]email[\ ' "])/I ', ' \1 '" \ 3 ', $buffer);
Not the average person to see the end of Things

The content does not have the plugin to make the mark, cannot manage
if (!substr_count ($buffer, ' <!--cos-html-cache-safe-tag--> ') return $buffer;
A password-protected article doesn't control
if (Substr_count ($buffer, ' Post_password ') > 0) return $buffer;//to check if post password protected
$wppasscookie = "Wp-postpass_". Cookiehash;
Still can't manage
if (strlen ($_cookie[$wppasscookie]) > 0) return $buffer;//to check if post password protected
* * These content is still in the common.js.php, with JS to deal with it
$comment _author_url= ';
$comment _author_email= ';
$comment _author= ';


ElseIf (Script_uri = = Cossitehome) {//creat homepage//Oh, home, this is a pipe
$fp = @fopen (Cosblogpath.) Index.bak "," w+ "); Get the contents into the Index.bak first.
if ($fp) {
@flock ($fp, LOCK_EX);
Write the file.
Fwrite ($FP, $buffer. Cosmeta); Write, followed by a little markup to indicate that the static file was created successfully
@flock ($fp, Lock_un);
Fclose ($FP);
}
if (is_index)//If you really want to create a home page static file, change the Index.bak to index.html
@rename (Cosblogpath.) Index.bak ", Cosblogpath." Index.html ");
}
else//Other case, try to create a static file and add a tag to the back
Createhtmlfile ($_server[' Request_uri '), $buffer. Cosmeta);
return $buffer;
}

function Cos_cache_shutdown_callback () {//The static file is really written to the physical hard drive, the climax process is always very short
Ob_end_flush ();
Flush ();
}

if (!function_exists (' Delcachebyurl ')) {
function Delcachebyurl ($url) {//delete static file via URL
$url = Cosblogpath.str_replace (Cossitehome, "", $url); If it's a complete URL, remove the site.
$url = Str_replace ("//", "/", $url); Put all//replace into/
if (file_exists ($url)) {//File exists
If it is a directory, first delete the index.html, and then delete the catalogue
if (Is_dir ($url)) {@unlink ($url.) /index.html "); @rmdir ($url);}
else @unlink ($url); Otherwise delete the static file directly
}
}
}

if (!function_exists (' Htmlcachedel ')) {
Create single HTML
function Htmlcachedel ($post _id) {//delete static file by article ID
if ($post _id = "") return true;
$uri = Get_permalink ($post _id);
Delcachebyurl ($uri);
}
}

If (!function_exists (' HTMLCACHEDELNB ')) {
 //delete nabour posts
 //If you delete the article, you'll also have to remove the static articles from both the neighbors. Avoid the next issue in the previous article
 //but you see it, for the article ID is larger than the deleted article SQL statement a little problem, the new version will be resolved (2.7.4 version has been resolved)
 function HTMLCACHEDELNB ($ post_id) {
 if ($post _id = = "") return true;

$uri = Get_permalink ($post _id);
 delcachebyurl ($uri);
 global $wpdb;
  $postRes = $wpdb->get_results (' select ' ID ' from '. $wpdb->posts. "' WHERE post_status = ' publish ' and post_type= ' post ' and ID < '. $post _id." ORDER by ID DESC LIMIT 0, 1; ");
  $uri 1 = get_permalink ($postRes [0]->id);
 delcachebyurl ($uri 1);
  $postRes = $wpdb->get_results (' select ' ID ' from '. $wpdb->posts. "' WHERE post_status = ' publish ' and post_type= ' post ' and ID > '. $post _id." ORDER by ID DESC LIMIT 0, 1; ");
 if ($postRes [0]->id!= ') {
  $uri 2 = Get_permalink ($postRes [0]->id);
 delcachebyurl ($uri 2);
 }
 }
}

Create index.html
if (!function_exists (' createindexhtml ')) {
The user edits, deletes, creates the article, the homepage will have the change,
So you have to change the first static file first name, to avoid or direct access to static files, do not see the effect
function createindexhtml ($post _id) {
if ($post _id = "") return true;
[Menghao] @rename (abspath.) Index.html ", Abspath." Index.bak ");
@rename (Cosblogpath.) Index.html ", Cosblogpath." Index.bak ");//[menghao]
}
}

if (!function_exists ("Htmlcachedel_reg_admin")) {//Add the delete static file function to WP's admin menu
/**
* Add The Options page in the admin menu
*/
function Htmlcachedel_reg_admin () {
if (function_exists (' add_options_page ')) {
Add_options_page (' Html-cache-creator ', ' Coshtmlcache ', 8, basename (__file__), ' coshtmloption ');
Add_options_page ($page _title, $menu _title, $access _level, $file).
}
}
}

Add_action (' Admin_menu ', ' htmlcachedel_reg_admin ');

If (!function_exists ("Coshtmloption")) {//This is WP cos-html-cache OPTION feature
function coshtmloption () {
 do_ Cos_html_cache_action ();

 <div class= "wrap" style= "padding:10px 0 0 10px;text-align:left"
 <form method= " Post "action=" <?php echo $_server["Request_uri";?> "
 <p>
 <?php _e (" click the Button bellow to delete all HTML cache files, "Cosbeta");? ></p>
 <p><?php _e ("Note:this won't delete data from your Databases", "Cosbeta");? ></p>
 <p><?php _e ("If you want to rebuild all cache files, you should delete them First,and th En the cache files would be built when post or page "visited", "Cosbeta");? ></p>

<p><b><?php _e ("Specify a post ID or Title to delete" related cache file, "Cosbeta");? ></b> <input type= "text" id= "cache_id" name= "cache_id" value= ""/> <?php _e ("Leave blank if you want to Delete all caches "," Cosbeta ");? ></p>
<p><input type= "Submit" value= "<?php _e" ("Delete Html Cache Files", "Cosbeta");? > "id=" HTMLCACHEDELBT "name=" HTMLCACHEDELBT "onclick=" return Checkcacheinput (); "/>
</form>
</div>

<script language= "JavaScript" >
<!--
function Checkcacheinput () {
document.getElementById (' HTMLCACHEDELBT '). Value = ' Please wait ... ';
return true;
}
-->
</SCRIPT>
<?php
}
}
/*
End of Get URL
*/
Deal with rebuild or delete
function Do_cos_html_cache_action () {//Completing removal of static files in Cos-html-cache option in WP
if (!empty ($_post[' HTMLCACHEDELBT ')) {
@rename (Cosblogpath.) Index.html ", Cosblogpath." Index.bak ");
@chmod (Cosblogpath.) Index.bak ", 0666);
Global $wpdb;
if ($_post[' cache_id '] * 1 > 0) {
Delete Cache by ID
Delcachebyurl (Get_permalink ($_post[' cache_id '));
$msg = __ (' The post cache was deleted successfully:id= ', ' Cosbeta '). $_post[' cache_id '];
}
else if (strlen ($_post[' cache_id ') > 2) {
$postRes = $wpdb->get_results (' select ' ID ' from '. $wpdb->posts. "' WHERE post_title like '% '. $_post[' cache_id ']." % ' LIMIT 0,1 ');
Delcachebyurl (Get_permalink ($postRes [0]->id));
$msg = __ (' The post cache was deleted successfully:title= ', ' Cosbeta '). $_post[' cache_id '];
}
else{
$postRes = $wpdb->get_results (' select ' ID ' from '. $wpdb->posts. "' WHERE post_status = ' publish ' and (post_type= ' post ' OR post_type= ' page ') Order by post_modified DESC");
foreach ($postRes as $post) {
Delcachebyurl (Get_permalink ($post->id));
}
$msg = __ (' HTML caches were deleted successfully ', ' Cosbeta ');
}
}
if ($msg)
Echo ' <div class= ' updated ' ><strong><p> '. $msg. ' </p></strong></div> ';
}
$is _add_comment_is = true; The following is processing article comments, added JS to deal with, related JS in the common.js.php
/*
* With Ajax comments
*/
if (!function_exists ("Cos_comments_js")) {
function Cos_comments_js ($postID) {
Global $is _add_comment_is;
if ($is _add_comment_is) {
$is _add_comment_is = false;
?>
<script language= "JavaScript" type= "Text/javascript" src= "<?php echo cossitehome;? >/wp-content/plugins/cos-html-cache/common.js.php?hash=<?php echo cookiehash;? > "></script>
<script language= "JavaScript" type= "Text/javascript" >
<! [cdata[
var hash = "<?php echo cookiehash;? > ";
var Author_cookie = "Comment_author_" + hash;
var Email_cookie = "Comment_author_email_" + hash;
var Url_cookie = "Comment_author_url_" + hash;
var adminmail = "<?php echo str_replace" (' @ ', ' {_} ', Get_option (' Admin_email '));? > ";
var adminurl = "<?php echo get_option" (' SiteURL ');? > ";
Setcommform ();
]]>
</script>
<?php
}
}
}

function Cossafetag () {//Add security tag
if (Is_single () | | (Is_home () && is_index)) {
echo "<!--cos-html-cache-safe-tag-->";
}
}
function Clearcommenthistory () {//
Global $comment _author_url, $comment _author_email, $comment _author;
$comment _author_url= ';
$comment _author_email= ';
$comment _author= ';
}
Add_action (' Comments_array ', ' clearcommenthistory ');
Add_action (' Get_footer ', ' Cossafetag '); Put the security tag in front of footer.
Add_action (' Comment_form ', ' cos_comments_js '); Comment Special Handling

/* End of ajaxcomments*/
if (is_index) add_action (' Publish_post ', ' createindexhtml '); A new article on the home page to deal with
Add_action (' Publish_post ', ' HTMLCACHEDELNB '); New articles to deal with related static files

if (is_index) add_action (' Delete_post ', ' createindexhtml '); Deleted the article also to the homepage processing
Add_action (' Delete_post ', ' HTMLCACHEDELNB '); Delete files to handle related static files

If comments add
Add_action (' Edit_post ', ' Htmlcachedel '); Update static file with changes to articles and comments
if (is_index) add_action (' Edit_post ', ' createindexhtml '); May affect the home page, anyway also update it

Interpretation completed, in fact, in the use of the process will also appear a small bug:index.php file will be modified into index.html, the name is not the same, but the file size, this will lead to the latest article directly show the content of the first page.

By reading the description of Cos-html-cache, and then through the above interpretation, you can find Cos-html-cache is really a super efficient WordPress cache class Plug-ins, and the server's resource footprint is very small. Through this plug-in, you can say that your site quickly become a pure static page of the site. No, I'm so sorry Cosbeta.

Special reminders are needed:

Cos-html-cache will only generate static HTML files on the article and Home page, which is suitable for blogs or cms,cos-html-cache that are mainly articles. For those with the main page, in addition to the first page, there is no effect

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.