commit 472c6415831aa921f96ff295de5aa562e74037ca Author: Andrew Davidson Date: Mon Sep 28 18:42:15 2015 -0400 initial commit diff --git a/index.php b/index.php new file mode 100644 index 0000000..49403ec --- /dev/null +++ b/index.php @@ -0,0 +1,18 @@ + \ No newline at end of file diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..d31195a --- /dev/null +++ b/license.txt @@ -0,0 +1,281 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110, USA + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + END OF TERMS AND CONDITIONS + diff --git a/readme.html b/readme.html new file mode 100644 index 0000000..95e1c17 --- /dev/null +++ b/readme.html @@ -0,0 +1,91 @@ + + + + + WordPress › ReadMe + + + +

+ WordPress +
Version 2.8.4 +

+

Semantic Personal Publishing Platform

+ +

First Things First

+

Welcome. WordPress is a very special project to me. Every developer and contributor adds something unique to the mix, and together we create something beautiful that I'm proud to be a part of. Thousands of hours have gone into WordPress, and we're dedicated to making it better every day. Thank you for making it part of your world.

+

— Matt Mullenweg

+ +

Installation: Famous 5-minute install

+
    +
  1. Unzip the package in an empty directory.
  2. +
  3. Open up wp-config-sample.php with a text editor like WordPad or similar and fill in your database connection details.
  4. +
  5. Save the file as wp-config.php
  6. +
  7. Upload everything.
  8. +
  9. Open /wp-admin/install.php in your browser. This should setup the tables needed for your blog. If there is an error, double check your wp-config.php file, and try again. If it fails again, please go to the support forums with as much data as you can gather.
  10. +
  11. Note the password given to you.
  12. +
  13. The install script should then send you to the login page. Sign in with the username admin and the password generated during the installation. You can then click on 'Profile' to change the password.
  14. +
+ +

Upgrading

+

Before you upgrade anything, make sure you have backup copies of any files you may have modified such as index.php.

+

Upgrading from any previous WordPress to 2.8.4:

+
    +
  1. Delete your old WP files, saving ones you've modified.
  2. +
  3. Upload the new files.
  4. +
  5. Point your browser to /wp-admin/upgrade.php.
  6. +
  7. You wanted more, perhaps? That's it!
  8. +
+

Template Changes

+

If you have customized your templates you will probably have to make some changes to them. If you're converting your 1.2 or earlier templates, we've created a special guide for you.

+ +

Online Resources

+

If you have any questions that aren't addressed in this document, please take advantage of WordPress' numerous online resources:

+
+
The WordPress Codex
+
The Codex is the encyclopedia of all things WordPress. It is the most comprehensive source of information for WordPress available.
+
The Development Blog
+
This is where you'll find the latest updates and news related to WordPress. Bookmark and check often.
+
WordPress Planet
+
The WordPress Planet is a news aggregator that brings together posts from WordPress blogs around the web.
+
WordPress Support Forums
+
If you've looked everywhere and still can't find an answer, the support forums are very active and have a large community ready to help. To help them help you be sure to use a descriptive thread title and describe your question in as much detail as possible.
+
WordPress IRC Channel
+
Finally, there is an online chat channel that is used for discussion among people who use WordPress and occasionally support topics. The above wiki page should point you in the right direction. (irc.freenode.net #wordpress)
+
+ +

System Recommendations

+ +

WordPress is the official continuation of b2/cafélog, which came from Michel V. The work has been continued by the WordPress developers. If you would like to support WordPress, please consider donating.

+ +

Upgrading from another system

+

WordPress can import from a number of systems. First you need to get WordPress installed and working as described above.

+ +

XML-RPC and Atom Interface

+

You can now post to your WordPress blog with tools like Windows Live Writer, Ecto, Bloggar, Radio Userland (which means you can use Radio's email-to-blog feature), NewzCrawler, and other tools that support the Blogging APIs! :) You can read more about XML-RPC support on the Codex.

+ +

Post via Email

+

You can post from an email client! To set this up go to your "Writing" options screen and fill in the connection details for your secret POP3 account. Then you need to set up wp-mail.php to execute periodically to check the mailbox for new posts. You can do it with Cron-jobs, or if your host doesn't support it you can look into the various website-monitoring services, and make them check your wp-mail.php URL.

+

Posting is easy: Any email sent to the address you specify will be posted, with the subject as the title. It is best to keep the address discrete. The script will delete emails that are successfully posted.

+ +

User Roles

+

We've eliminated user levels in order to make way for the much more flexible roles system introduced in 2.0. You can read more about Roles and Capabilities on the Codex.

+ +

Final notes

+ + +

Share the Love

+

WordPress has no multi-million dollar marketing campaign or celebrity sponsors, but we do have something even better—you. If you enjoy WordPress please consider telling a friend, setting it up for someone less knowledgable than yourself, or writing the author of a media article that overlooks us.

+ +

Copyright

+

WordPress is released under the GPL (see license.txt).

+ + + diff --git a/wp-admin/admin-ajax.php b/wp-admin/admin-ajax.php new file mode 100644 index 0000000..7f04dd7 --- /dev/null +++ b/wp-admin/admin-ajax.php @@ -0,0 +1,1356 @@ +ALERT: You are logged out! Could not save draft. Please log in again.'), wp_login_url() ); + $x = new WP_Ajax_Response( array( + 'what' => 'autosave', + 'id' => $id, + 'data' => $message + ) ); + $x->send(); + } + + if ( !empty( $_POST['action']) ) + do_action( 'wp_ajax_nopriv_' . $_POST['action'] ); + + die('-1'); +} + +if ( isset( $_GET['action'] ) ) : +switch ( $action = $_GET['action'] ) : +case 'ajax-tag-search' : + if ( !current_user_can( 'edit_posts' ) ) + die('-1'); + + $s = $_GET['q']; // is this slashed already? + + if ( isset($_GET['tax']) ) + $taxonomy = sanitize_title($_GET['tax']); + else + die('0'); + + if ( false !== strpos( $s, ',' ) ) { + $s = explode( ',', $s ); + $s = $s[count( $s ) - 1]; + } + $s = trim( $s ); + if ( strlen( $s ) < 2 ) + die; // require 2 chars for matching + + $results = $wpdb->get_col( "SELECT t.name FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = '$taxonomy' AND t.name LIKE ('%" . $s . "%')" ); + + echo join( $results, "\n" ); + die; + break; +case 'wp-compression-test' : + if ( !current_user_can( 'manage_options' ) ) + die('-1'); + + if ( ini_get('zlib.output_compression') || 'ob_gzhandler' == ini_get('output_handler') ) { + update_site_option('can_compress_scripts', 0); + die('0'); + } + + if ( isset($_GET['test']) ) { + header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' ); + header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); + header( 'Cache-Control: no-cache, must-revalidate, max-age=0' ); + header( 'Pragma: no-cache' ); + header('Content-Type: application/x-javascript; charset=UTF-8'); + $force_gzip = ( defined('ENFORCE_GZIP') && ENFORCE_GZIP ); + $test_str = '"wpCompressionTest Lorem ipsum dolor sit amet consectetuer mollis sapien urna ut a. Eu nonummy condimentum fringilla tempor pretium platea vel nibh netus Maecenas. Hac molestie amet justo quis pellentesque est ultrices interdum nibh Morbi. Cras mattis pretium Phasellus ante ipsum ipsum ut sociis Suspendisse Lorem. Ante et non molestie. Porta urna Vestibulum egestas id congue nibh eu risus gravida sit. Ac augue auctor Ut et non a elit massa id sodales. Elit eu Nulla at nibh adipiscing mattis lacus mauris at tempus. Netus nibh quis suscipit nec feugiat eget sed lorem et urna. Pellentesque lacus at ut massa consectetuer ligula ut auctor semper Pellentesque. Ut metus massa nibh quam Curabitur molestie nec mauris congue. Volutpat molestie elit justo facilisis neque ac risus Ut nascetur tristique. Vitae sit lorem tellus et quis Phasellus lacus tincidunt nunc Fusce. Pharetra wisi Suspendisse mus sagittis libero lacinia Integer consequat ac Phasellus. Et urna ac cursus tortor aliquam Aliquam amet tellus volutpat Vestibulum. Justo interdum condimentum In augue congue tellus sollicitudin Quisque quis nibh."'; + + if ( 1 == $_GET['test'] ) { + echo $test_str; + die; + } elseif ( 2 == $_GET['test'] ) { + if ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'deflate') && function_exists('gzdeflate') && ! $force_gzip ) { + header('Content-Encoding: deflate'); + $out = gzdeflate( $test_str, 1 ); + } elseif ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'gzip') && function_exists('gzencode') ) { + header('Content-Encoding: gzip'); + $out = gzencode( $test_str, 1 ); + } else { + die('-1'); + } + echo $out; + die; + } elseif ( 'no' == $_GET['test'] ) { + update_site_option('can_compress_scripts', 0); + } elseif ( 'yes' == $_GET['test'] ) { + update_site_option('can_compress_scripts', 1); + } + } + + die('0'); + break; +default : + do_action( 'wp_ajax_' . $_GET['action'] ); + die('0'); + break; +endswitch; +endif; + +/** + * Sends back current comment total and new page links if they need to be updated. + * + * Contrary to normal success AJAX response ("1"), die with time() on success. + * + * @since 2.7 + * + * @param int $comment_id + * @return die + */ +function _wp_ajax_delete_comment_response( $comment_id ) { + $total = (int) @$_POST['_total']; + $per_page = (int) @$_POST['_per_page']; + $page = (int) @$_POST['_page']; + $url = esc_url_raw( @$_POST['_url'] ); + // JS didn't send us everything we need to know. Just die with success message + if ( !$total || !$per_page || !$page || !$url ) + die( (string) time() ); + + if ( --$total < 0 ) // Take the total from POST and decrement it (since we just deleted one) + $total = 0; + + if ( 0 != $total % $per_page && 1 != mt_rand( 1, $per_page ) ) // Only do the expensive stuff on a page-break, and about 1 other time per page + die( (string) time() ); + + $status = 'total_comments'; // What type of comment count are we looking for? + $parsed = parse_url( $url ); + if ( isset( $parsed['query'] ) ) { + parse_str( $parsed['query'], $query_vars ); + if ( !empty( $query_vars['comment_status'] ) ) + $status = $query_vars['comment_status']; + } + + $comment_count = wp_count_comments(); + $time = time(); // The time since the last comment count + + if ( isset( $comment_count->$status ) ) // We're looking for a known type of comment count + $total = $comment_count->$status; + // else use the decremented value from above + + $page_links = paginate_links( array( + 'base' => add_query_arg( 'apage', '%#%', $url ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil($total / $per_page), + 'current' => $page + ) ); + $x = new WP_Ajax_Response( array( + 'what' => 'comment', + 'id' => $comment_id, // here for completeness - not used + 'supplemental' => array( + 'pageLinks' => $page_links, + 'total' => $total, + 'time' => $time + ) + ) ); + $x->send(); +} + +$id = isset($_POST['id'])? (int) $_POST['id'] : 0; +switch ( $action = $_POST['action'] ) : +case 'delete-comment' : // On success, die with time() instead of 1 + check_ajax_referer( "delete-comment_$id" ); + if ( !$comment = get_comment( $id ) ) + die( (string) time() ); + if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) ) + die('-1'); + + if ( isset($_POST['spam']) && 1 == $_POST['spam'] ) { + if ( 'spam' == wp_get_comment_status( $comment->comment_ID ) ) + die( (string) time() ); + $r = wp_set_comment_status( $comment->comment_ID, 'spam' ); + } else { + $r = wp_delete_comment( $comment->comment_ID ); + } + if ( $r ) // Decide if we need to send back '1' or a more complicated response including page links and comment counts + _wp_ajax_delete_comment_response( $comment->comment_ID ); + die( '0' ); + break; +case 'delete-cat' : + check_ajax_referer( "delete-category_$id" ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + + $cat = get_category( $id ); + if ( !$cat || is_wp_error( $cat ) ) + die('1'); + + if ( wp_delete_category( $id ) ) + die('1'); + else + die('0'); + break; +case 'delete-tag' : + check_ajax_referer( "delete-tag_$id" ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + + if ( !empty($_POST['taxonomy']) ) + $taxonomy = $_POST['taxonomy']; + else + $taxonomy = 'post_tag'; + + $tag = get_term( $id, $taxonomy ); + if ( !$tag || is_wp_error( $tag ) ) + die('1'); + + if ( wp_delete_term($id, $taxonomy)) + die('1'); + else + die('0'); + break; +case 'delete-link-cat' : + check_ajax_referer( "delete-link-category_$id" ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + + $cat = get_term( $id, 'link_category' ); + if ( !$cat || is_wp_error( $cat ) ) + die('1'); + + $cat_name = get_term_field('name', $id, 'link_category'); + + $default = get_option('default_link_category'); + + // Don't delete the default cats. + if ( $id == $default ) { + $x = new WP_AJAX_Response( array( + 'what' => 'link-cat', + 'id' => $id, + 'data' => new WP_Error( 'default-link-cat', sprintf(__("Can’t delete the %s category: this is the default one"), $cat_name) ) + ) ); + $x->send(); + } + + $r = wp_delete_term($id, 'link_category', array('default' => $default)); + if ( !$r ) + die('0'); + if ( is_wp_error($r) ) { + $x = new WP_AJAX_Response( array( + 'what' => 'link-cat', + 'id' => $id, + 'data' => $r + ) ); + $x->send(); + } + die('1'); + break; +case 'delete-link' : + check_ajax_referer( "delete-bookmark_$id" ); + if ( !current_user_can( 'manage_links' ) ) + die('-1'); + + $link = get_bookmark( $id ); + if ( !$link || is_wp_error( $link ) ) + die('1'); + + if ( wp_delete_link( $id ) ) + die('1'); + else + die('0'); + break; +case 'delete-meta' : + check_ajax_referer( "delete-meta_$id" ); + if ( !$meta = get_post_meta_by_id( $id ) ) + die('1'); + + if ( !current_user_can( 'edit_post', $meta->post_id ) ) + die('-1'); + if ( delete_meta( $meta->meta_id ) ) + die('1'); + die('0'); + break; +case 'delete-post' : + check_ajax_referer( "{$action}_$id" ); + if ( !current_user_can( 'delete_post', $id ) ) + die('-1'); + + if ( !get_post( $id ) ) + die('1'); + + if ( wp_delete_post( $id ) ) + die('1'); + else + die('0'); + break; +case 'delete-page' : + check_ajax_referer( "{$action}_$id" ); + if ( !current_user_can( 'delete_page', $id ) ) + die('-1'); + + if ( !get_page( $id ) ) + die('1'); + + if ( wp_delete_post( $id ) ) + die('1'); + else + die('0'); + break; +case 'dim-comment' : // On success, die with time() instead of 1 + + if ( !$comment = get_comment( $id ) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'comment', + 'id' => new WP_Error('invalid_comment', sprintf(__('Comment %d does not exist'), $id)) + ) ); + $x->send(); + } + + if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) ) + die('-1'); + if ( !current_user_can( 'moderate_comments' ) ) + die('-1'); + + $current = wp_get_comment_status( $comment->comment_ID ); + if ( $_POST['new'] == $current ) + die( (string) time() ); + + $r = 0; + if ( in_array( $current, array( 'unapproved', 'spam' ) ) ) { + check_ajax_referer( "approve-comment_$id" ); + $result = wp_set_comment_status( $comment->comment_ID, 'approve', true ); + } else { + check_ajax_referer( "unapprove-comment_$id" ); + $result = wp_set_comment_status( $comment->comment_ID, 'hold', true ); + } + if ( is_wp_error($result) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'comment', + 'id' => $result + ) ); + $x->send(); + } + + // Decide if we need to send back '1' or a more complicated response including page links and comment counts + _wp_ajax_delete_comment_response( $comment->comment_ID ); + die( '0' ); + break; +case 'add-category' : // On the Fly + check_ajax_referer( $action ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + $names = explode(',', $_POST['newcat']); + if ( 0 > $parent = (int) $_POST['newcat_parent'] ) + $parent = 0; + $post_category = isset($_POST['post_category'])? (array) $_POST['post_category'] : array(); + $checked_categories = array_map( 'absint', (array) $post_category ); + $popular_ids = isset( $_POST['popular_ids'] ) ? + array_map( 'absint', explode( ',', $_POST['popular_ids'] ) ) : + false; + + $x = new WP_Ajax_Response(); + foreach ( $names as $cat_name ) { + $cat_name = trim($cat_name); + $category_nicename = sanitize_title($cat_name); + if ( '' === $category_nicename ) + continue; + $cat_id = wp_create_category( $cat_name, $parent ); + $checked_categories[] = $cat_id; + if ( $parent ) // Do these all at once in a second + continue; + $category = get_category( $cat_id ); + ob_start(); + wp_category_checklist( 0, $cat_id, $checked_categories, $popular_ids ); + $data = ob_get_contents(); + ob_end_clean(); + $x->add( array( + 'what' => 'category', + 'id' => $cat_id, + 'data' => $data, + 'position' => -1 + ) ); + } + if ( $parent ) { // Foncy - replace the parent and all its children + $parent = get_category( $parent ); + ob_start(); + dropdown_categories( 0, $parent ); + $data = ob_get_contents(); + ob_end_clean(); + $x->add( array( + 'what' => 'category', + 'id' => $parent->term_id, + 'old_id' => $parent->term_id, + 'data' => $data, + 'position' => -1 + ) ); + + } + $x->send(); + break; +case 'add-link-category' : // On the Fly + check_ajax_referer( $action ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + $names = explode(',', $_POST['newcat']); + $x = new WP_Ajax_Response(); + foreach ( $names as $cat_name ) { + $cat_name = trim($cat_name); + $slug = sanitize_title($cat_name); + if ( '' === $slug ) + continue; + if ( !$cat_id = is_term( $cat_name, 'link_category' ) ) { + $cat_id = wp_insert_term( $cat_name, 'link_category' ); + } + $cat_id = $cat_id['term_id']; + $cat_name = esc_html(stripslashes($cat_name)); + $x->add( array( + 'what' => 'link-category', + 'id' => $cat_id, + 'data' => "", + 'position' => -1 + ) ); + } + $x->send(); + break; +case 'add-cat' : // From Manage->Categories + check_ajax_referer( 'add-category' ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + + if ( '' === trim($_POST['cat_name']) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'cat', + 'id' => new WP_Error( 'cat_name', __('You did not enter a category name.') ) + ) ); + $x->send(); + } + + if ( category_exists( trim( $_POST['cat_name'] ), $_POST['category_parent'] ) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'cat', + 'id' => new WP_Error( 'cat_exists', __('The category you are trying to create already exists.'), array( 'form-field' => 'cat_name' ) ), + ) ); + $x->send(); + } + + $cat = wp_insert_category( $_POST, true ); + + if ( is_wp_error($cat) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'cat', + 'id' => $cat + ) ); + $x->send(); + } + + if ( !$cat || (!$cat = get_category( $cat )) ) + die('0'); + + $level = 0; + $cat_full_name = $cat->name; + $_cat = $cat; + while ( $_cat->parent ) { + $_cat = get_category( $_cat->parent ); + $cat_full_name = $_cat->name . ' — ' . $cat_full_name; + $level++; + } + $cat_full_name = esc_attr($cat_full_name); + + $x = new WP_Ajax_Response( array( + 'what' => 'cat', + 'id' => $cat->term_id, + 'position' => -1, + 'data' => _cat_row( $cat, $level, $cat_full_name ), + 'supplemental' => array('name' => $cat_full_name, 'show-link' => sprintf(__( 'Category %s added' ), "cat-$cat->term_id", $cat_full_name)) + ) ); + $x->send(); + break; +case 'add-link-cat' : // From Blogroll -> Categories + check_ajax_referer( 'add-link-category' ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + + if ( '' === trim($_POST['name']) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'link-cat', + 'id' => new WP_Error( 'name', __('You did not enter a category name.') ) + ) ); + $x->send(); + } + + $r = wp_insert_term($_POST['name'], 'link_category', $_POST ); + if ( is_wp_error( $r ) ) { + $x = new WP_AJAX_Response( array( + 'what' => 'link-cat', + 'id' => $r + ) ); + $x->send(); + } + + extract($r, EXTR_SKIP); + + if ( !$link_cat = link_cat_row( $term_id ) ) + die('0'); + + $x = new WP_Ajax_Response( array( + 'what' => 'link-cat', + 'id' => $term_id, + 'position' => -1, + 'data' => $link_cat + ) ); + $x->send(); + break; +case 'add-tag' : // From Manage->Tags + check_ajax_referer( 'add-tag' ); + if ( !current_user_can( 'manage_categories' ) ) + die('-1'); + + if ( '' === trim($_POST['name']) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'tag', + 'id' => new WP_Error( 'name', __('You did not enter a tag name.') ) + ) ); + $x->send(); + } + + if ( !empty($_POST['taxonomy']) ) + $taxonomy = $_POST['taxonomy']; + else + $taxonomy = 'post_tag'; + + $tag = wp_insert_term($_POST['name'], $taxonomy, $_POST ); + + if ( is_wp_error($tag) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'tag', + 'id' => $tag + ) ); + $x->send(); + } + + if ( !$tag || (!$tag = get_term( $tag['term_id'], $taxonomy )) ) + die('0'); + + $tag_full_name = $tag->name; + $tag_full_name = esc_attr($tag_full_name); + + $x = new WP_Ajax_Response( array( + 'what' => 'tag', + 'id' => $tag->term_id, + 'position' => '-1', + 'data' => _tag_row( $tag, '', $taxonomy ), + 'supplemental' => array('name' => $tag_full_name, 'show-link' => sprintf(__( 'Tag %s added' ), "tag-$tag->term_id", $tag_full_name)) + ) ); + $x->send(); + break; +case 'get-tagcloud' : + if ( !current_user_can( 'edit_posts' ) ) + die('-1'); + + if ( isset($_POST['tax']) ) + $taxonomy = sanitize_title($_POST['tax']); + else + die('0'); + + $tags = get_terms( $taxonomy, array( 'number' => 45, 'orderby' => 'count', 'order' => 'DESC' ) ); + + if ( empty( $tags ) ) + die( __('No tags found!') ); + + if ( is_wp_error($tags) ) + die($tags->get_error_message()); + + foreach ( $tags as $key => $tag ) { + $tags[ $key ]->link = '#'; + $tags[ $key ]->id = $tag->term_id; + } + + // We need raw tag names here, so don't filter the output + $return = wp_generate_tag_cloud( $tags, array('filter' => 0) ); + + if ( empty($return) ) + die('0'); + + echo $return; + + exit; + break; +case 'add-comment' : + check_ajax_referer( $action ); + if ( !current_user_can( 'edit_post', $id ) ) + die('-1'); + $search = isset($_POST['s']) ? $_POST['s'] : false; + $status = isset($_POST['comment_status']) ? $_POST['comment_status'] : 'all'; + $per_page = isset($_POST['per_page']) ? (int) $_POST['per_page'] + 8 : 28; + $start = isset($_POST['page']) ? ( intval($_POST['page']) * $per_page ) -1 : $per_page - 1; + if ( 1 > $start ) + $start = 27; + + $mode = isset($_POST['mode']) ? $_POST['mode'] : 'detail'; + $p = isset($_POST['p']) ? $_POST['p'] : 0; + $comment_type = isset($_POST['comment_type']) ? $_POST['comment_type'] : ''; + list($comments, $total) = _wp_get_comment_list( $status, $search, $start, 1, $p, $comment_type ); + + if ( get_option('show_avatars') ) + add_filter( 'comment_author', 'floated_admin_avatar' ); + + if ( !$comments ) + die('1'); + $x = new WP_Ajax_Response(); + foreach ( (array) $comments as $comment ) { + get_comment( $comment ); + ob_start(); + _wp_comment_row( $comment->comment_ID, $mode, $status, true, true ); + $comment_list_item = ob_get_contents(); + ob_end_clean(); + $x->add( array( + 'what' => 'comment', + 'id' => $comment->comment_ID, + 'data' => $comment_list_item + ) ); + } + $x->send(); + break; +case 'get-comments' : + check_ajax_referer( $action ); + + $post_ID = (int) $_POST['post_ID']; + if ( !current_user_can( 'edit_post', $post_ID ) ) + die('-1'); + + $start = isset($_POST['start']) ? intval($_POST['start']) : 0; + $num = isset($_POST['num']) ? intval($_POST['num']) : 10; + + list($comments, $total) = _wp_get_comment_list( false, false, $start, $num, $post_ID ); + + if ( !$comments ) + die('1'); + + $comment_list_item = ''; + $x = new WP_Ajax_Response(); + foreach ( (array) $comments as $comment ) { + get_comment( $comment ); + ob_start(); + _wp_comment_row( $comment->comment_ID, 'single', false, false ); + $comment_list_item .= ob_get_contents(); + ob_end_clean(); + } + $x->add( array( + 'what' => 'comments', + 'data' => $comment_list_item + ) ); + $x->send(); + break; +case 'replyto-comment' : + check_ajax_referer( $action ); + + $comment_post_ID = (int) $_POST['comment_post_ID']; + if ( !current_user_can( 'edit_post', $comment_post_ID ) ) + die('-1'); + + $status = $wpdb->get_var( $wpdb->prepare("SELECT post_status FROM $wpdb->posts WHERE ID = %d", $comment_post_ID) ); + + if ( empty($status) ) + die('1'); + elseif ( in_array($status, array('draft', 'pending') ) ) + die( __('Error: you are replying to a comment on a draft post.') ); + + $user = wp_get_current_user(); + if ( $user->ID ) { + $comment_author = $wpdb->escape($user->display_name); + $comment_author_email = $wpdb->escape($user->user_email); + $comment_author_url = $wpdb->escape($user->user_url); + $comment_content = trim($_POST['content']); + if ( current_user_can('unfiltered_html') ) { + if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) { + kses_remove_filters(); // start with a clean slate + kses_init_filters(); // set up the filters + } + } + } else { + die( __('Sorry, you must be logged in to reply to a comment.') ); + } + + if ( '' == $comment_content ) + die( __('Error: please type a comment.') ); + + $comment_parent = absint($_POST['comment_ID']); + $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID'); + + $comment_id = wp_new_comment( $commentdata ); + $comment = get_comment($comment_id); + if ( ! $comment ) die('1'); + + $modes = array( 'single', 'detail', 'dashboard' ); + $mode = isset($_POST['mode']) && in_array( $_POST['mode'], $modes ) ? $_POST['mode'] : 'detail'; + $position = ( isset($_POST['position']) && (int) $_POST['position']) ? (int) $_POST['position'] : '-1'; + $checkbox = ( isset($_POST['checkbox']) && true == $_POST['checkbox'] ) ? 1 : 0; + + if ( get_option('show_avatars') && 'single' != $mode ) + add_filter( 'comment_author', 'floated_admin_avatar' ); + + $x = new WP_Ajax_Response(); + + ob_start(); + if ( 'dashboard' == $mode ) { + require_once( ABSPATH . 'wp-admin/includes/dashboard.php' ); + _wp_dashboard_recent_comments_row( $comment, false ); + } else { + _wp_comment_row( $comment->comment_ID, $mode, false, $checkbox ); + } + $comment_list_item = ob_get_contents(); + ob_end_clean(); + + $x->add( array( + 'what' => 'comment', + 'id' => $comment->comment_ID, + 'data' => $comment_list_item, + 'position' => $position + )); + + $x->send(); + break; +case 'edit-comment' : + check_ajax_referer( 'replyto-comment' ); + + $comment_post_ID = (int) $_POST['comment_post_ID']; + if ( ! current_user_can( 'edit_post', $comment_post_ID ) ) + die('-1'); + + if ( '' == $_POST['content'] ) + die( __('Error: please type a comment.') ); + + $comment_id = (int) $_POST['comment_ID']; + $_POST['comment_status'] = $_POST['status']; + edit_comment(); + + $mode = ( isset($_POST['mode']) && 'single' == $_POST['mode'] ) ? 'single' : 'detail'; + $position = ( isset($_POST['position']) && (int) $_POST['position']) ? (int) $_POST['position'] : '-1'; + $checkbox = ( isset($_POST['checkbox']) && true == $_POST['checkbox'] ) ? 1 : 0; + $comments_listing = isset($_POST['comments_listing']) ? $_POST['comments_listing'] : ''; + + if ( get_option('show_avatars') && 'single' != $mode ) + add_filter( 'comment_author', 'floated_admin_avatar' ); + + $x = new WP_Ajax_Response(); + + ob_start(); + _wp_comment_row( $comment_id, $mode, $comments_listing, $checkbox ); + $comment_list_item = ob_get_contents(); + ob_end_clean(); + + $x->add( array( + 'what' => 'edit_comment', + 'id' => $comment->comment_ID, + 'data' => $comment_list_item, + 'position' => $position + )); + + $x->send(); + break; +case 'add-meta' : + check_ajax_referer( 'add-meta' ); + $c = 0; + $pid = (int) $_POST['post_id']; + if ( isset($_POST['metakeyselect']) || isset($_POST['metakeyinput']) ) { + if ( !current_user_can( 'edit_post', $pid ) ) + die('-1'); + if ( isset($_POST['metakeyselect']) && '#NONE#' == $_POST['metakeyselect'] && empty($_POST['metakeyinput']) ) + die('1'); + if ( $pid < 0 ) { + $now = current_time('timestamp', 1); + if ( $pid = wp_insert_post( array( + 'post_title' => sprintf('Draft created on %s at %s', date(get_option('date_format'), $now), date(get_option('time_format'), $now)) + ) ) ) { + if ( is_wp_error( $pid ) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'meta', + 'data' => $pid + ) ); + $x->send(); + } + if ( !$mid = add_meta( $pid ) ) + die(__('Please provide a custom field value.')); + } else { + die('0'); + } + } else if ( !$mid = add_meta( $pid ) ) { + die(__('Please provide a custom field value.')); + } + + $meta = get_post_meta_by_id( $mid ); + $pid = (int) $meta->post_id; + $meta = get_object_vars( $meta ); + $x = new WP_Ajax_Response( array( + 'what' => 'meta', + 'id' => $mid, + 'data' => _list_meta_row( $meta, $c ), + 'position' => 1, + 'supplemental' => array('postid' => $pid) + ) ); + } else { + $mid = (int) array_pop(array_keys($_POST['meta'])); + $key = $_POST['meta'][$mid]['key']; + $value = $_POST['meta'][$mid]['value']; + if ( !$meta = get_post_meta_by_id( $mid ) ) + die('0'); // if meta doesn't exist + if ( !current_user_can( 'edit_post', $meta->post_id ) ) + die('-1'); + if ( $meta->meta_value != stripslashes($value) ) { + if ( !$u = update_meta( $mid, $key, $value ) ) + die('0'); // We know meta exists; we also know it's unchanged (or DB error, in which case there are bigger problems). + } + + $key = stripslashes($key); + $value = stripslashes($value); + $x = new WP_Ajax_Response( array( + 'what' => 'meta', + 'id' => $mid, 'old_id' => $mid, + 'data' => _list_meta_row( array( + 'meta_key' => $key, + 'meta_value' => $value, + 'meta_id' => $mid + ), $c ), + 'position' => 0, + 'supplemental' => array('postid' => $meta->post_id) + ) ); + } + $x->send(); + break; +case 'add-user' : + check_ajax_referer( $action ); + if ( !current_user_can('create_users') ) + die('-1'); + require_once(ABSPATH . WPINC . '/registration.php'); + if ( !$user_id = add_user() ) + die('0'); + elseif ( is_wp_error( $user_id ) ) { + $x = new WP_Ajax_Response( array( + 'what' => 'user', + 'id' => $user_id + ) ); + $x->send(); + } + $user_object = new WP_User( $user_id ); + + $x = new WP_Ajax_Response( array( + 'what' => 'user', + 'id' => $user_id, + 'data' => user_row( $user_object, '', $user_object->roles[0] ), + 'supplemental' => array( + 'show-link' => sprintf(__( 'User %s added' ), "user-$user_id", $user_object->user_login), + 'role' => $user_object->roles[0] + ) + ) ); + $x->send(); + break; +case 'autosave' : // The name of this action is hardcoded in edit_post() + define( 'DOING_AUTOSAVE', true ); + + $nonce_age = check_ajax_referer( 'autosave', 'autosavenonce' ); + global $current_user; + + $_POST['post_category'] = explode(",", $_POST['catslist']); + if($_POST['post_type'] == 'page' || empty($_POST['post_category'])) + unset($_POST['post_category']); + + $do_autosave = (bool) $_POST['autosave']; + $do_lock = true; + + $data = ''; + /* translators: draft saved date format, see http://php.net/date */ + $draft_saved_date_format = __('g:i:s a'); + $message = sprintf( __('Draft Saved at %s.'), date_i18n( $draft_saved_date_format ) ); + + $supplemental = array(); + + $id = $revision_id = 0; + if($_POST['post_ID'] < 0) { + $_POST['post_status'] = 'draft'; + $_POST['temp_ID'] = $_POST['post_ID']; + if ( $do_autosave ) { + $id = wp_write_post(); + $data = $message; + } + } else { + $post_ID = (int) $_POST['post_ID']; + $_POST['ID'] = $post_ID; + $post = get_post($post_ID); + + if ( $last = wp_check_post_lock( $post->ID ) ) { + $do_autosave = $do_lock = false; + + $last_user = get_userdata( $last ); + $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' ); + $data = new WP_Error( 'locked', sprintf( + $_POST['post_type'] == 'page' ? __( 'Autosave disabled: %s is currently editing this page.' ) : __( 'Autosave disabled: %s is currently editing this post.' ), + esc_html( $last_user_name ) + ) ); + + $supplemental['disable_autosave'] = 'disable'; + } + + if ( 'page' == $post->post_type ) { + if ( !current_user_can('edit_page', $post_ID) ) + die(__('You are not allowed to edit this page.')); + } else { + if ( !current_user_can('edit_post', $post_ID) ) + die(__('You are not allowed to edit this post.')); + } + + if ( $do_autosave ) { + // Drafts are just overwritten by autosave + if ( 'draft' == $post->post_status ) { + $id = edit_post(); + } else { // Non drafts are not overwritten. The autosave is stored in a special post revision. + $revision_id = wp_create_post_autosave( $post->ID ); + if ( is_wp_error($revision_id) ) + $id = $revision_id; + else + $id = $post->ID; + } + $data = $message; + } else { + $id = $post->ID; + } + } + + if ( $do_lock && $id && is_numeric($id) ) + wp_set_post_lock( $id ); + + if ( $nonce_age == 2 ) { + $supplemental['replace-autosavenonce'] = wp_create_nonce('autosave'); + $supplemental['replace-getpermalinknonce'] = wp_create_nonce('getpermalink'); + $supplemental['replace-samplepermalinknonce'] = wp_create_nonce('samplepermalink'); + $supplemental['replace-closedpostboxesnonce'] = wp_create_nonce('closedpostboxes'); + if ( $id ) { + if ( $_POST['post_type'] == 'post' ) + $supplemental['replace-_wpnonce'] = wp_create_nonce('update-post_' . $id); + elseif ( $_POST['post_type'] == 'page' ) + $supplemental['replace-_wpnonce'] = wp_create_nonce('update-page_' . $id); + } + } + + $x = new WP_Ajax_Response( array( + 'what' => 'autosave', + 'id' => $id, + 'data' => $id ? $data : '', + 'supplemental' => $supplemental + ) ); + $x->send(); + break; +case 'autosave-generate-nonces' : + check_ajax_referer( 'autosave', 'autosavenonce' ); + $ID = (int) $_POST['post_ID']; + if($_POST['post_type'] == 'post') { + if(current_user_can('edit_post', $ID)) + die(wp_create_nonce('update-post_' . $ID)); + } + if($_POST['post_type'] == 'page') { + if(current_user_can('edit_page', $ID)) { + die(wp_create_nonce('update-page_' . $ID)); + } + } + die('0'); +break; +case 'closed-postboxes' : + check_ajax_referer( 'closedpostboxes', 'closedpostboxesnonce' ); + $closed = isset( $_POST['closed'] ) ? $_POST['closed'] : ''; + $closed = explode( ',', $_POST['closed'] ); + $hidden = isset( $_POST['hidden'] ) ? $_POST['hidden'] : ''; + $hidden = explode( ',', $_POST['hidden'] ); + $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; + + if ( !preg_match( '/^[a-z_-]+$/', $page ) ) + die('-1'); + + if ( ! $user = wp_get_current_user() ) + die('-1'); + + if ( is_array($closed) ) + update_usermeta($user->ID, 'closedpostboxes_'.$page, $closed); + + if ( is_array($hidden) ) { + $hidden = array_diff( $hidden, array('submitdiv', 'pagesubmitdiv', 'linksubmitdiv') ); // postboxes that are always shown + update_usermeta($user->ID, 'meta-box-hidden_'.$page, $hidden); + } + + die('1'); + break; +case 'hidden-columns' : + check_ajax_referer( 'screen-options-nonce', 'screenoptionnonce' ); + $hidden = isset( $_POST['hidden'] ) ? $_POST['hidden'] : ''; + $hidden = explode( ',', $_POST['hidden'] ); + $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; + + if ( !preg_match( '/^[a-z_-]+$/', $page ) ) + die('-1'); + + if ( ! $user = wp_get_current_user() ) + die('-1'); + + if ( is_array($hidden) ) + update_usermeta($user->ID, "manage-$page-columns-hidden", $hidden); + + die('1'); + break; +case 'meta-box-order': + check_ajax_referer( 'meta-box-order' ); + $order = isset( $_POST['order'] ) ? (array) $_POST['order'] : false; + $page_columns = isset( $_POST['page_columns'] ) ? (int) $_POST['page_columns'] : 0; + $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; + + if ( !preg_match( '/^[a-z_-]+$/', $page ) ) + die('-1'); + + if ( ! $user = wp_get_current_user() ) + die('-1'); + + if ( $order ) + update_user_option($user->ID, "meta-box-order_$page", $order); + + if ( $page_columns ) + update_usermeta($user->ID, "screen_layout_$page", $page_columns); + + die('1'); + break; +case 'get-permalink': + check_ajax_referer( 'getpermalink', 'getpermalinknonce' ); + $post_id = isset($_POST['post_id'])? intval($_POST['post_id']) : 0; + die(add_query_arg(array('preview' => 'true'), get_permalink($post_id))); +break; +case 'sample-permalink': + check_ajax_referer( 'samplepermalink', 'samplepermalinknonce' ); + $post_id = isset($_POST['post_id'])? intval($_POST['post_id']) : 0; + $title = isset($_POST['new_title'])? $_POST['new_title'] : ''; + $slug = isset($_POST['new_slug'])? $_POST['new_slug'] : ''; + die(get_sample_permalink_html($post_id, $title, $slug)); +break; +case 'inline-save': + check_ajax_referer( 'inlineeditnonce', '_inline_edit' ); + + if ( ! isset($_POST['post_ID']) || ! ( $post_ID = (int) $_POST['post_ID'] ) ) + exit; + + if ( 'page' == $_POST['post_type'] ) { + if ( ! current_user_can( 'edit_page', $post_ID ) ) + die( __('You are not allowed to edit this page.') ); + } else { + if ( ! current_user_can( 'edit_post', $post_ID ) ) + die( __('You are not allowed to edit this post.') ); + } + + if ( $last = wp_check_post_lock( $post_ID ) ) { + $last_user = get_userdata( $last ); + $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' ); + printf( $_POST['post_type'] == 'page' ? __( 'Saving is disabled: %s is currently editing this page.' ) : __( 'Saving is disabled: %s is currently editing this post.' ), esc_html( $last_user_name ) ); + exit; + } + + $data = &$_POST; + + $post = get_post( $post_ID, ARRAY_A ); + $post = add_magic_quotes($post); //since it is from db + + $data['content'] = $post['post_content']; + $data['excerpt'] = $post['post_excerpt']; + + // rename + $data['user_ID'] = $GLOBALS['user_ID']; + + if ( isset($data['post_parent']) ) + $data['parent_id'] = $data['post_parent']; + + // status + if ( isset($data['keep_private']) && 'private' == $data['keep_private'] ) + $data['post_status'] = 'private'; + else + $data['post_status'] = $data['_status']; + + if ( empty($data['comment_status']) ) + $data['comment_status'] = 'closed'; + if ( empty($data['ping_status']) ) + $data['ping_status'] = 'closed'; + + // update the post + edit_post(); + + $post = array(); + if ( 'page' == $_POST['post_type'] ) { + $post[] = get_post($_POST['post_ID']); + page_rows($post); + } elseif ( 'post' == $_POST['post_type'] ) { + $mode = $_POST['post_view']; + $post[] = get_post($_POST['post_ID']); + post_rows($post); + } + + exit; + break; +case 'inline-save-tax': + check_ajax_referer( 'taxinlineeditnonce', '_inline_edit' ); + + if ( ! current_user_can('manage_categories') ) + die( __('Cheatin’ uh?') ); + + if ( ! isset($_POST['tax_ID']) || ! ( $id = (int) $_POST['tax_ID'] ) ) + die(-1); + + switch ($_POST['tax_type']) { + case 'cat' : + $data = array(); + $data['cat_ID'] = $id; + $data['cat_name'] = $_POST['name']; + $data['category_nicename'] = $_POST['slug']; + if ( isset($_POST['parent']) && (int) $_POST['parent'] > 0 ) + $data['category_parent'] = $_POST['parent']; + + $cat = get_category($id, ARRAY_A); + $data['category_description'] = $cat['category_description']; + + $updated = wp_update_category($data); + + if ( $updated && !is_wp_error($updated) ) + echo _cat_row( $updated, 0 ); + else + die( __('Category not updated.') ); + + break; + case 'link-cat' : + $updated = wp_update_term($id, 'link_category', $_POST); + + if ( $updated && !is_wp_error($updated) ) + echo link_cat_row($updated['term_id']); + else + die( __('Category not updated.') ); + + break; + case 'tag' : + if ( !empty($_POST['taxonomy']) ) + $taxonomy = $_POST['taxonomy']; + else + $taxonomy = 'post_tag'; + + $tag = get_term( $id, $taxonomy ); + $_POST['description'] = $tag->description; + + $updated = wp_update_term($id, $taxonomy, $_POST); + if ( $updated && !is_wp_error($updated) ) { + $tag = get_term( $updated['term_id'], $taxonomy ); + if ( !$tag || is_wp_error( $tag ) ) + die( __('Tag not updated.') ); + + echo _tag_row($tag); + } else { + die( __('Tag not updated.') ); + } + + break; + } + + exit; + break; +case 'find_posts': + check_ajax_referer( 'find-posts' ); + + if ( empty($_POST['ps']) ) + exit; + + $what = isset($_POST['pages']) ? 'page' : 'post'; + $s = stripslashes($_POST['ps']); + preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $s, $matches); + $search_terms = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]); + + $searchand = $search = ''; + foreach( (array) $search_terms as $term) { + $term = addslashes_gpc($term); + $search .= "{$searchand}(($wpdb->posts.post_title LIKE '%{$term}%') OR ($wpdb->posts.post_content LIKE '%{$term}%'))"; + $searchand = ' AND '; + } + $term = $wpdb->escape($s); + if ( count($search_terms) > 1 && $search_terms[0] != $s ) + $search .= " OR ($wpdb->posts.post_title LIKE '%{$term}%') OR ($wpdb->posts.post_content LIKE '%{$term}%')"; + + $posts = $wpdb->get_results( "SELECT ID, post_title, post_status, post_date FROM $wpdb->posts WHERE post_type = '$what' AND $search ORDER BY post_date_gmt DESC LIMIT 50" ); + + if ( ! $posts ) + exit( __('No posts found.') ); + + $html = ''; + foreach ( $posts as $post ) { + + switch ( $post->post_status ) { + case 'publish' : + case 'private' : + $stat = __('Published'); + break; + case 'future' : + $stat = __('Scheduled'); + break; + case 'pending' : + $stat = __('Pending Review'); + break; + case 'draft' : + $stat = __('Unpublished'); + break; + } + + if ( '0000-00-00 00:00:00' == $post->post_date ) { + $time = ''; + } else { + /* translators: date format in table columns, see http://php.net/date */ + $time = mysql2date(__('Y/m/d'), $post->post_date); + } + + $html .= ''; + $html .= ''."\n\n"; + } + $html .= '

'.__('Title').''.__('Time').''.__('Status').'
'.esc_html( $time ).''.esc_html( $stat ).'
'; + + $x = new WP_Ajax_Response(); + $x->add( array( + 'what' => $what, + 'data' => $html + )); + $x->send(); + + break; +case 'lj-importer' : + check_ajax_referer( 'lj-api-import' ); + if ( !current_user_can( 'publish_posts' ) ) + die('-1'); + if ( empty( $_POST['step'] ) ) + die( '-1' ); + define('WP_IMPORTING', true); + include( ABSPATH . 'wp-admin/import/livejournal.php' ); + $result = $lj_api_import->{ 'step' . ( (int) $_POST['step'] ) }(); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + die; + break; +case 'widgets-order' : + check_ajax_referer( 'save-sidebar-widgets', 'savewidgets' ); + + if ( !current_user_can('switch_themes') ) + die('-1'); + + unset( $_POST['savewidgets'], $_POST['action'] ); + + // save widgets order for all sidebars + if ( is_array($_POST['sidebars']) ) { + $sidebars = array(); + foreach ( $_POST['sidebars'] as $key => $val ) { + $sb = array(); + if ( !empty($val) ) { + $val = explode(',', $val); + foreach ( $val as $k => $v ) { + if ( strpos($v, 'widget-') === false ) + continue; + + $sb[$k] = substr($v, strpos($v, '_') + 1); + } + } + $sidebars[$key] = $sb; + } + wp_set_sidebars_widgets($sidebars); + die('1'); + } + + die('-1'); + break; +case 'save-widget' : + check_ajax_referer( 'save-sidebar-widgets', 'savewidgets' ); + + if ( !current_user_can('switch_themes') || !isset($_POST['id_base']) ) + die('-1'); + + unset( $_POST['savewidgets'], $_POST['action'] ); + + do_action('load-widgets.php'); + do_action('widgets.php'); + do_action('sidebar_admin_setup'); + + $id_base = $_POST['id_base']; + $widget_id = $_POST['widget-id']; + $sidebar_id = $_POST['sidebar']; + $multi_number = !empty($_POST['multi_number']) ? (int) $_POST['multi_number'] : 0; + $settings = isset($_POST['widget-' . $id_base]) && is_array($_POST['widget-' . $id_base]) ? $_POST['widget-' . $id_base] : false; + $error = '

' . __('An error has occured. Please reload the page and try again.') . '

'; + + $sidebars = wp_get_sidebars_widgets(); + $sidebar = isset($sidebars[$sidebar_id]) ? $sidebars[$sidebar_id] : array(); + + // delete + if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) { + + if ( !isset($wp_registered_widgets[$widget_id]) ) + die($error); + + $sidebar = array_diff( $sidebar, array($widget_id) ); + $_POST = array('sidebar' => $sidebar_id, 'widget-' . $id_base => array(), 'the-widget-id' => $widget_id, 'delete_widget' => '1'); + } elseif ( $settings && preg_match( '/__i__|%i%/', key($settings) ) ) { + if ( !$multi_number ) + die($error); + + $_POST['widget-' . $id_base] = array( $multi_number => array_shift($settings) ); + $widget_id = $id_base . '-' . $multi_number; + $sidebar[] = $widget_id; + } + $_POST['widget-id'] = $sidebar; + + foreach ( (array) $wp_registered_widget_updates as $name => $control ) { + + if ( $name == $id_base ) { + if ( !is_callable( $control['callback'] ) ) + continue; + + ob_start(); + call_user_func_array( $control['callback'], $control['params'] ); + ob_end_clean(); + break; + } + } + + if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) { + $sidebars[$sidebar_id] = $sidebar; + wp_set_sidebars_widgets($sidebars); + echo "deleted:$widget_id"; + die(); + } + + if ( !empty($_POST['add_new']) ) + die(); + + if ( $form = $wp_registered_widget_controls[$widget_id] ) + call_user_func_array( $form['callback'], $form['params'] ); + + die(); + break; +default : + do_action( 'wp_ajax_' . $_POST['action'] ); + die('0'); + break; +endswitch; +?> diff --git a/wp-admin/admin-footer.php b/wp-admin/admin-footer.php new file mode 100644 index 0000000..a43a4e4 --- /dev/null +++ b/wp-admin/admin-footer.php @@ -0,0 +1,44 @@ + + +
+
+
+ + + + + + + + diff --git a/wp-admin/admin-functions.php b/wp-admin/admin-functions.php new file mode 100644 index 0000000..b8c84fd --- /dev/null +++ b/wp-admin/admin-functions.php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/wp-admin/admin-header.php b/wp-admin/admin-header.php new file mode 100644 index 0000000..27c496a --- /dev/null +++ b/wp-admin/admin-header.php @@ -0,0 +1,128 @@ + + + > + + +<?php echo $title; ?> ‹ <?php bloginfo('name') ?> — WordPress + + + + + + +"> + + +
+
+ + +
+ + +
+ \ No newline at end of file diff --git a/wp-admin/admin.php b/wp-admin/admin.php new file mode 100644 index 0000000..f8405f9 --- /dev/null +++ b/wp-admin/admin.php @@ -0,0 +1,159 @@ +flush_rules(); + update_option( 'db_upgraded', false ); + + /** + * Runs on the next page load after successful upgrade + * + * @since 2.8 + */ + do_action('after_db_upgrade'); +} elseif ( get_option('db_version') != $wp_db_version ) { + wp_redirect(admin_url('upgrade.php?_wp_http_referer=' . urlencode(stripslashes($_SERVER['REQUEST_URI'])))); + exit; +} + +require_once(ABSPATH . 'wp-admin/includes/admin.php'); + +auth_redirect(); + +nocache_headers(); + +update_category_cache(); + +set_screen_options(); + +$posts_per_page = get_option('posts_per_page'); +$date_format = get_option('date_format'); +$time_format = get_option('time_format'); + +wp_reset_vars(array('profile', 'redirect', 'redirect_url', 'a', 'popuptitle', 'popupurl', 'text', 'trackback', 'pingback')); + +wp_admin_css_color('classic', __('Blue'), admin_url("css/colors-classic.css"), array('#073447', '#21759B', '#EAF3FA', '#BBD8E7')); +wp_admin_css_color('fresh', __('Gray'), admin_url("css/colors-fresh.css"), array('#464646', '#6D6D6D', '#F1F1F1', '#DFDFDF')); + +wp_enqueue_script( 'common' ); +wp_enqueue_script( 'jquery-color' ); + +$editing = false; + +if (isset($_GET['page'])) { + $plugin_page = stripslashes($_GET['page']); + $plugin_page = plugin_basename($plugin_page); +} + +require(ABSPATH . 'wp-admin/menu.php'); + +do_action('admin_init'); + +// Handle plugin admin pages. +if (isset($plugin_page)) { + if( ! $page_hook = get_plugin_page_hook($plugin_page, $pagenow) ) { + $page_hook = get_plugin_page_hook($plugin_page, $plugin_page); + // backwards compatibility for plugins using add_management_page + if ( empty( $page_hook ) && 'edit.php' == $pagenow && '' != get_plugin_page_hook($plugin_page, 'tools.php') ) { + // There could be plugin specific params on the URL, so we need the whole query string + if ( !empty($_SERVER[ 'QUERY_STRING' ]) ) + $query_string = $_SERVER[ 'QUERY_STRING' ]; + else + $query_string = 'page=' . $plugin_page; + wp_redirect( 'tools.php?' . $query_string ); + exit; + } + } + + if ( $page_hook ) { + do_action('load-' . $page_hook); + if (! isset($_GET['noheader'])) + require_once(ABSPATH . 'wp-admin/admin-header.php'); + + do_action($page_hook); + } else { + if ( validate_file($plugin_page) ) { + wp_die(__('Invalid plugin page')); + } + + if (! ( file_exists(WP_PLUGIN_DIR . "/$plugin_page") && is_file(WP_PLUGIN_DIR . "/$plugin_page") ) ) + wp_die(sprintf(__('Cannot load %s.'), htmlentities($plugin_page))); + + do_action('load-' . $plugin_page); + + if (! isset($_GET['noheader'])) + require_once(ABSPATH . 'wp-admin/admin-header.php'); + + include(WP_PLUGIN_DIR . "/$plugin_page"); + } + + include(ABSPATH . 'wp-admin/admin-footer.php'); + + exit(); +} else if (isset($_GET['import'])) { + + $importer = $_GET['import']; + + if ( ! current_user_can('import') ) + wp_die(__('You are not allowed to import.')); + + if ( validate_file($importer) ) { + wp_die(__('Invalid importer.')); + } + + // Allow plugins to define importers as well + if ( !isset($wp_importers) || !isset($wp_importers[$importer]) || ! is_callable($wp_importers[$importer][2])) + { + if (! file_exists(ABSPATH . "wp-admin/import/$importer.php")) + { + wp_die(__('Cannot load importer.')); + } + include(ABSPATH . "wp-admin/import/$importer.php"); + } + + $parent_file = 'tools.php'; + $submenu_file = 'import.php'; + $title = __('Import'); + + if (! isset($_GET['noheader'])) + require_once(ABSPATH . 'wp-admin/admin-header.php'); + + require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); + + define('WP_IMPORTING', true); + + call_user_func($wp_importers[$importer][2]); + + include(ABSPATH . 'wp-admin/admin-footer.php'); + + // Make sure rules are flushed + global $wp_rewrite; + $wp_rewrite->flush_rules(false); + + exit(); +} else { + do_action("load-$pagenow"); +} + +if ( !empty($_REQUEST['action']) ) + do_action('admin_action_' . $_REQUEST['action']); + +?> diff --git a/wp-admin/async-upload.php b/wp-admin/async-upload.php new file mode 100644 index 0000000..4197c86 --- /dev/null +++ b/wp-admin/async-upload.php @@ -0,0 +1,59 @@ + false, 'delete' => true )); + } else { + add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2); + echo get_media_item($id); + } + exit; +} + +check_admin_referer('media-form'); + +$id = media_handle_upload('async-upload', $_REQUEST['post_id']); +if (is_wp_error($id)) { + echo '
'.esc_html($id->get_error_message()).'
'; + exit; +} + +if ( $_REQUEST['short'] ) { + // short form response - attachment ID only + echo $id; +} +else { + // long form response - big chunk o html + $type = $_REQUEST['type']; + echo apply_filters("async_upload_{$type}", $id); +} + +?> diff --git a/wp-admin/categories.php b/wp-admin/categories.php new file mode 100644 index 0000000..8d26b9e --- /dev/null +++ b/wp-admin/categories.php @@ -0,0 +1,306 @@ +%s category: this is the default one"), $cat_name)); + + wp_delete_category($cat_ID); + + wp_safe_redirect( add_query_arg( 'message', 2, wp_get_referer() ) ); + exit; + +break; + +case 'bulk-delete': + check_admin_referer('bulk-categories'); + + if ( !current_user_can('manage_categories') ) + wp_die( __('You are not allowed to delete categories.') ); + + foreach ( (array) $_GET['delete'] as $cat_ID ) { + $cat_name = get_cat_name($cat_ID); + + // Don't delete the default cats. + if ( $cat_ID == get_option('default_category') ) + wp_die(sprintf(__("Can’t delete the %s category: this is the default one"), $cat_name)); + + wp_delete_category($cat_ID); + } + + wp_safe_redirect( wp_get_referer() ); + exit(); + +break; +case 'edit': + + $title = __('Edit Category'); + + require_once ('admin-header.php'); + $cat_ID = (int) $_GET['cat_ID']; + $category = get_category_to_edit($cat_ID); + include('edit-category-form.php'); + +break; + +case 'editedcat': + $cat_ID = (int) $_POST['cat_ID']; + check_admin_referer('update-category_' . $cat_ID); + + if ( !current_user_can('manage_categories') ) + wp_die(__('Cheatin’ uh?')); + + $location = 'categories.php'; + if ( $referer = wp_get_original_referer() ) { + if ( false !== strpos($referer, 'categories.php') ) + $location = $referer; + } + + if ( wp_update_category($_POST) ) + $location = add_query_arg('message', 3, $location); + else + $location = add_query_arg('message', 5, $location); + + wp_redirect($location); + + exit; +break; + +default: + +if ( isset($_GET['_wp_http_referer']) && ! empty($_GET['_wp_http_referer']) ) { + wp_redirect( remove_query_arg( array('_wp_http_referer', '_wpnonce'), stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; +} + +wp_enqueue_script('admin-categories'); +if ( current_user_can('manage_categories') ) + wp_enqueue_script('inline-edit-tax'); + +require_once ('admin-header.php'); + +$messages[1] = __('Category added.'); +$messages[2] = __('Category deleted.'); +$messages[3] = __('Category updated.'); +$messages[4] = __('Category not added.'); +$messages[5] = __('Category not updated.'); +?> + +
+ +

' . __('Search results for “%s”') . '', esc_html( stripslashes($_GET['s']) ) ); ?> +

+ + +

+ + +
+ +
+
+ +
+ +
+
+
+
+ + 0, 'search' => $_GET['s']))); +else + $num_cats = wp_count_terms('category'); + +$page_links = paginate_links( array( + 'base' => add_query_arg( 'pagenum', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil($num_cats / $cats_per_page), + 'current' => $pagenum +)); + +if ( $page_links ) + echo "
$page_links
"; +?> + +
+ + + +
+ +
+
+ +
+ + + + + + + + + + + + + + + + + +
+ +
+$page_links
"; +?> + +
+ + + +
+ +
+
+ + + +
+

Note:
Deleting a category does not delete the posts in that category. Instead, posts that were only assigned to the deleted category are set to the category %s.'), apply_filters('the_category', get_cat_name(get_option('default_category')))) ?>

+

category to tag converter.'), 'admin.php?import=wp-cat2tag') ?>

+
+ +
+
+ +
+
+ + +parent = 0; do_action('add_category_form_pre', $category); ?> + +
+

+
+
+ + + +
+ + +

+
+ +
+ + +

+
+ +
+ + 0, 'name' => 'category_parent', 'orderby' => 'name', 'selected' => $category->parent, 'hierarchical' => true, 'show_option_none' => __('None'))); ?> +

+
+ +
+ + +

+
+ +

+ +
+ + + +
+
+ +
+
+ + diff --git a/wp-admin/comment.php b/wp-admin/comment.php new file mode 100644 index 0000000..6499c08 --- /dev/null +++ b/wp-admin/comment.php @@ -0,0 +1,240 @@ +

$msg

"; + include('admin-footer.php'); + die; +} + +switch( $action ) { + +case 'editcomment' : + $title = __('Edit Comment'); + + wp_enqueue_script('comment'); + require_once('admin-header.php'); + + $comment_id = absint( $_GET['c'] ); + + if ( !$comment = get_comment( $comment_id ) ) + comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' '.__('Go back').'!', 'javascript:history.go(-1)') ); + + if ( !current_user_can('edit_post', $comment->comment_post_ID) ) + comment_footer_die( __('You are not allowed to edit comments on this post.') ); + + $comment = get_comment_to_edit( $comment_id ); + + include('edit-form-comment.php'); + + break; + +case 'cdc' : +case 'mac' : + + require_once('admin-header.php'); + + $comment_id = absint( $_GET['c'] ); + $formaction = 'cdc' == $action ? 'deletecomment' : 'approvecomment'; + $nonce_action = 'cdc' == $action ? 'delete-comment_' : 'approve-comment_'; + $nonce_action .= $comment_id; + + if ( !$comment = get_comment_to_edit( $comment_id ) ) + comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' '.__('Go back').'!', 'edit.php') ); + + if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) ) + comment_footer_die( 'cdc' == $action ? __('You are not allowed to delete comments on this post.') : __('You are not allowed to edit comments on this post, so you cannot approve this comment.') ); +?> +
+ +
+ + +

+ +

+ +
+ + + + + + +
' onclick="self.location='" />
+ + + + + + + + + +
+ + + + + + +comment_author_email ) { ?> + + + + + +comment_author_url ) { ?> + + + + + + + + + +
comment_author; ?>
comment_author_email; ?>
comment_author_url; ?>
comment_content; ?>
+ +
+
+'.__('Go back').'!', 'edit-comments.php') ); + + if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) ) + comment_footer_die( __('You are not allowed to edit comments on this post.') ); + + if ( 'spam' == $_REQUEST['dt'] ) + wp_set_comment_status( $comment->comment_ID, 'spam' ); + else + wp_delete_comment( $comment->comment_ID ); + + if ( '' != wp_get_referer() && false == $noredir && false === strpos(wp_get_referer(), 'comment.php' ) ) + wp_redirect( wp_get_referer() ); + else if ( '' != wp_get_original_referer() && false == $noredir ) + wp_redirect( wp_get_original_referer() ); + else + wp_redirect( admin_url('edit-comments.php') ); + + die; + break; + +case 'unapprovecomment' : + $comment_id = absint( $_GET['c'] ); + check_admin_referer( 'unapprove-comment_' . $comment_id ); + + if ( isset( $_GET['noredir'] ) ) + $noredir = true; + else + $noredir = false; + + if ( !$comment = get_comment( $comment_id ) ) + comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' '.__('Go back').'!', 'edit.php') ); + + if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) ) + comment_footer_die( __('You are not allowed to edit comments on this post, so you cannot disapprove this comment.') ); + + wp_set_comment_status( $comment->comment_ID, 'hold' ); + + if ( '' != wp_get_referer() && false == $noredir ) + wp_redirect( wp_get_referer() ); + else + wp_redirect( admin_url('edit-comments.php?p=' . absint( $comment->comment_post_ID ) . '#comments') ); + + exit(); + break; + +case 'approvecomment' : + $comment_id = absint( $_GET['c'] ); + check_admin_referer( 'approve-comment_' . $comment_id ); + + if ( isset( $_GET['noredir'] ) ) + $noredir = true; + else + $noredir = false; + + if ( !$comment = get_comment( $comment_id ) ) + comment_footer_die( __('Oops, no comment with this ID.') . sprintf(' '.__('Go back').'!', 'edit.php') ); + + if ( !current_user_can('edit_post', $comment->comment_post_ID) ) + comment_footer_die( __('You are not allowed to edit comments on this post, so you cannot approve this comment.') ); + + wp_set_comment_status( $comment->comment_ID, 'approve' ); + + if ( '' != wp_get_referer() && false == $noredir ) + wp_redirect( wp_get_referer() ); + else + wp_redirect( admin_url('edit-comments.php?p=' . absint( $comment->comment_post_ID ) . '#comments') ); + + exit(); + break; + +case 'editedcomment' : + + $comment_id = absint( $_POST['comment_ID'] ); + $comment_post_id = absint( $_POST['comment_post_ID'] ); + + check_admin_referer( 'update-comment_' . $comment_id ); + + edit_comment(); + + $location = ( empty( $_POST['referredby'] ) ? "edit-comments.php?p=$comment_post_id" : $_POST['referredby'] ) . '#comment-' . $comment_id; + $location = apply_filters( 'comment_edit_redirect', $location, $comment_id ); + wp_redirect( $location ); + + exit(); + break; + +default: + wp_die( __('Unknown action.') ); + break; + +} // end switch + +include('admin-footer.php'); + +?> \ No newline at end of file diff --git a/wp-admin/css/colors-classic-rtl.css b/wp-admin/css/colors-classic-rtl.css new file mode 100644 index 0000000..99239be --- /dev/null +++ b/wp-admin/css/colors-classic-rtl.css @@ -0,0 +1,80 @@ +.bar { + border-right-color: transparent; + border-left-color: #99d; +} + +.plugins .togl { + border-right-color: transparent; + border-left-color: #ccc; +} + +.post-com-count { + background-image: url(../images/bubble_bg-rtl.gif); +} +.tablenav .tablenav-pages a { + background: #eee url('../images/menu-bits-rtl-vs.gif') repeat-x scroll right -379px; +} +#upload-menu li.current { + border-right-color: transparent; + border-left-color: #448abd; +} + +#adminmenu .wp-submenu .current a.current { + background: transparent url(../images/menu-bits-rtl-vs.gif) no-repeat scroll right -289px; +} + +#adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll right -34px; +} + +.folded #adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll left 5px; +} + +#adminmenu li.wp-has-current-submenu .wp-menu-toggle, +#adminmenu li.wp-has-current-submenu:hover .wp-menu-toggle { + background: transparent url(../images/menu-bits-rtl-vs.gif) repeat-x scroll right -207px; +} + +#adminmenu .wp-has-current-submenu ul li a.current { + background: url(../images/menu-dark-rtl.gif) top right no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu a.wp-has-current-submenu, +#adminmenu .menu-top .current { + background: url(../images/menu-bits-rtl-vs.gif) top right repeat-x; +} + +#adminmenu li.wp-has-current-submenu ul li a { + background: url(../images/menu-dark-rtl.gif) bottom right no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu.wp-menu-open .wp-menu-toggle, #adminmenu li.wp-has-current-submenu:hover .wp-menu-toggle { + background: transparent url(../images/menu-bits-rtl-vs.gif) no-repeat right -207px; +} + +#adminmenu .wp-has-submenu:hover .wp-menu-toggle, +#adminmenu .wp-menu-open .wp-menu-toggle { + background: transparent url(../images/menu-bits-rtl-vs.gif) repeat-x scroll right -109px; +} + +#adminmenu a.wp-has-submenu { + background: #f1f1f1 url(../images/menu-bits-rtl-vs.gif) repeat-x scroll right -379px; +} + +#adminmenu .wp-submenu a { + background: #FFFFFF url(../images/menu-bits-rtl-vs.gif) no-repeat scroll right -310px; +} + +#adminmenu li.current a, +#adminmenu .wp-submenu a:hover { + background: transparent url(../images/menu-bits-rtl-vs.gif) no-repeat scroll right -289px; +} + +#adminmenu li.wp-has-current-submenu a.wp-has-submenu { + background: #b5b5b5 url(../images/menu-bits-rtl-vs.gif) repeat-x scroll right top; +} + +.meta-box-sortables .postbox:hover .handlediv { + background: transparent url(../images/menu-bits-rtl-vs.gif) no-repeat scroll right -111px; +} diff --git a/wp-admin/css/colors-classic.css b/wp-admin/css/colors-classic.css new file mode 100644 index 0000000..a6cb4f9 --- /dev/null +++ b/wp-admin/css/colors-classic.css @@ -0,0 +1,1671 @@ +html { + background-color: #f7f6f1; +} + +* html input, +* html .widget { + border-color: #8cbdd5; +} + +textarea, +input, +select { + border-color: #dfdfdf; +} + +kbd, +code { + background: #eaeaea; +} + +input[readonly] { + background-color: #eee; +} + +.find-box-search { + border-color: #dfdfdf; + background-color: #f1f1f1; +} + +.find-box { + background-color: #f1f1f1; +} + +.find-box-inside { + background-color: #fff; +} + +a.page-numbers:hover { + border-color: #999; +} + +body, +#wpbody, +.form-table .pre { + color: #333; +} + +body > #upload-menu { + border-bottom-color: #fff; +} + +#postcustomstuff table, +#your-profile fieldset, +#rightnow, +div.dashboard-widget, +#dashboard-widgets p.dashboard-widget-links, +#replyrow #ed_reply_toolbar input { + border-color: #ccc; +} + +#poststuff .inside label.spam { + color: red; +} + +#poststuff .inside label.waiting { + color: orange; +} + +#poststuff .inside label.approved { + color: green; +} + +#postcustomstuff table { + border-color: #dfdfdf; + background-color: #f9f9f9; +} + +#postcustomstuff thead th { + background-color: #f1f1f1; +} + +#postcustomstuff table input, +#postcustomstuff table textarea { + border-color: #dfdfdf; + background-color: #fff; +} + +.widefat { + border-color: #dfdfdf; + background-color: #fff; +} + +div.dashboard-widget-error { + background-color: #c43; +} + +div.dashboard-widget-notice { + background-color: #cfe1ef; +} + +div.dashboard-widget-submit { + border-top-color: #ccc; +} + +div.tabs-panel, +ul#category-tabs li.tabs { + border-color: #dfdfdf; +} + +ul#category-tabs li.tabs { + background-color: #f1f1f1; +} + +input.disabled, +textarea.disabled { + background-color: #ccc; +} +/* #upload-menu li a.upload-tab-link, */ +.login #backtoblog a:hover, +#plugin-information .action-button a, +#plugin-information .action-button a:hover, +#plugin-information .action-button a:visited { + color: #fff; +} + +.widget .widget-top, +.postbox h3, +.stuffbox h3 { + background: #d5e6f2 url("../images/blue-grad.png") repeat-x left top; + text-shadow: #fff 0 1px 0; +} + +.form-table th, +.form-wrap label { + color: #222; + text-shadow: #fff 0 1px 0; +} + +.description, +.form-wrap p { + color: #666; +} + +strong .post-com-count span { + background-color: #21759b; +} + +.sorthelper { + background-color: #ccf3fa; +} + +.ac_match, +.subsubsub a.current { + color: #000; +} + +.wrap h2 { + color: #093e56; +} + +.ac_over { + background-color: #f0f0b8; +} + +.ac_results { + background-color: #fff; + border-color: #808080; +} + +.ac_results li { + color: #101010; +} + +.alt +.alternate { + background-color: #edfbfc; +} + +.available-theme a.screenshot { + background-color: #f1f1f1; + border-color: #ddd; +} + +.bar { + background-color: #e8e8e8; + border-right-color: #99d; +} + +#media-upload { + background: #fff; +} + +#media-upload .slidetoggle { + border-top-color: #dfdfdf; +} + +.error, +#login #login_error { + background-color: #ffebe8; + border-color: #c00; +} + +.error a { + color: #c00; +} + +.form-invalid { + background-color: #ffebe8 !important; +} + +.form-invalid input { + border-color: #c00 !important; +} + +.submit { + border-color: #8cbdd5; +} + +.highlight { + background-color: #e4f2fd; + color: #d54e21; +} + +.howto, +.nonessential, +#edit-slug-box, +.form-input-tip, +.rss-widget span.rss-date, +.subsubsub { + color: #666; +} + +.media-item { + border-bottom-color: #dfdfdf; +} + +#wpbody-content #media-items .describe { + border-top-color: #dfdfdf; +} + +.describe input[type="text"], +.describe textarea { + border-color: #dfdfdf; +} + +.media-upload-form label.form-help, +td.help { + color: #9a9a9a; +} + +.post-com-count { + background-image: url(../images/bubble_bg.gif); + color: #fff; +} + +.post-com-count span { + background-color: #bbb; + color: #fff; +} + +.post-com-count:hover span { + background-color: #d54e21; +} + +.quicktags, .search { + background-color: #ccc; + color: #000; +} + +.side-info h5 { + border-bottom-color: #dadada; +} + +.side-info ul { + color: #666; +} + +.button, +.button-secondary, +.submit input, +input[type=button], +input[type=submit] { + border-color: #dfdfdf; + color: #464646; +} + +.button:hover, +.button-secondary:hover, +.submit input:hover, +input[type=button]:hover, +input[type=submit]:hover { + color: #000; + border-color: #adaca7; +} + +.button, +.submit input, +.button-secondary { + background: #f2f2f2 url(../images/white-grad.png) repeat-x scroll left top; +} + +.button:active, +.submit input:active, +.button-secondary:active { + background: #eee url(../images/white-grad-active.png) repeat-x scroll left top; +} + +.button-primary, +.submit .button-primary, +#login form .submit input { + border-color: #5b86ab !important; + font-weight: bold; + color: #fff !important; + background: #5580a6 url(../images/button-grad-vs.png) repeat-x scroll left top; +} + +.button-primary:active, +#login form .submit input:active { + background: #21759b url(../images/button-grad-active-vs.png) repeat-x scroll left top !important; +} + +.button[disabled], +.button:disabled, +.button-secondary[disabled], +.button-secondary:disabled, +a.button.disabled { + color: #ccc !important; + border-color: #ccc; +} + +.button-primary[disabled], +.button-primary:disabled { + color: #80a3d2 !important; +} + +a:active, +a:focus { + color: #d54e21; +} + +a:hover, +#wphead #viewsite a:hover, +#adminmenu a:hover, +#adminmenu ul.wp-submenu a:hover, +#the-comment-list .comment a:hover, +#rightnow a:hover, +#login form .submit input:hover, +#media-upload a.del-link:hover, +div.dashboard-widget-submit input:hover, +.subsubsub a:hover, +.subsubsub a.current:hover, +.ui-tabs-nav a:hover, +.plugins .inactive a:hover, +#all-plugins-table .plugins .inactive a:hover, +#search-plugins-table .plugins .inactive a:hover { + color: #d54e21; +} + +#the-comment-list .comment-item, +#dashboard-widgets #dashboard_quick_press form p.submit { + border-color: #dfdfdf; +} + +#dashboard_right_now .table { + background:#faf9f7 !important; +} + +.button-primary:hover, +#login form .submit input:hover { + border-color: #2e5475 !important; + color: #eaf2fa !important; +} + +#side-sortables #category-tabs .tabs a { + color: #333; +} + +#rightnow .rbutton { + background-color: #ebebeb; + color: #264761; +} + +.submitbox .submit { + background-color: #464646; + color: #ccc; +} + +.plugins a.delete:hover, +#all-plugins-table .plugins a.delete:hover, +#search-plugins-table .plugins a.delete:hover, +.submitbox .submitdelete, +a.delete { + color: #f00; + border-bottom-color: #f00; +} + +.submitbox .submitdelete:hover, +#media-items a.delete:hover { + color: #fff; + background-color: #f00; + border-bottom-color: #f00; +} + +#normal-sortables .submitbox .submitdelete:hover { + color: #000; + background-color: #f00; + border-bottom-color: #f00; +} + +.tablenav .dots { + border-color: transparent; +} + +.tablenav .next, +.tablenav .prev { + border-color: transparent; + color: #21759b; +} + +.tablenav .next:hover, +.tablenav .prev:hover { + border-color: transparent; + color: #d54e21; +} + +.updated, +.login #login_error, +.login .message { + background-color: #ffffe0; + border-color: #e6db55; +} + +.update-message { + color: #000000; +} + +a.page-numbers { + border-bottom-color: #b8d3e2; +} + +.commentlist li { + border-bottom-color: #ccc; +} + +.widefat td, +.widefat th, +#install-plugins .plugins td, +#install-plugins .plugins th { + border-color: #dfdfdf; +} + +.widefat th { + text-shadow: rgba(255,255,255,0.8) 0 1px 0; +} + +.widefat thead tr th, +.widefat tfoot tr th, +h3.dashboard-widget-title, +h3.dashboard-widget-title span, +h3.dashboard-widget-title small, +.find-box-head { + color: #333; + background: #d5e6f2 url(../images/blue-grad.png) repeat-x scroll left top; +} + +h3.dashboard-widget-title small a { + color: #d7d7d7; +} + +h3.dashboard-widget-title small a:hover { + color: #fff; +} + +a, +#adminmenu a, +#poststuff #edButtonPreview, +#poststuff #edButtonHTML, +#the-comment-list p.comment-author strong a, +#media-upload a.del-link, +#media-items a.delete, +.plugins a.delete, +.ui-tabs-nav a { + color: #1c6280; +} + +/* Because we don't want visited on these links */ +body.press-this .tabs a, +body.press-this .tabs a:hover { + background-color: #fff; + border-color: #c6d9e9; + border-bottom-color: #fff; + color: #d54e21; +} + +#adminmenu #awaiting-mod, +#adminmenu .update-plugins, +#sidemenu a .update-plugins, +#rightnow .reallynow, +#plugin-information .action-button { + background-color: #d54e21; + color: #fff; +} + +#adminmenu li a:hover #awaiting-mod, +#adminmenu li a:hover .update-plugins, +#sidemenu li a:hover .update-plugins { + background-color: #264761; + color: #fff; +} + +#adminmenu li.current a #awaiting-mod, +#adminmenu li.current a .update-plugins, +#adminmenu li.wp-has-current-submenu a .update-plugins, +#adminmenu li.wp-has-current-submenu a .update-plugins { + background-color: #ddd; + color: #000; + text-shadow: none; + -moz-box-shadow: rgba(0,0,0,0.2) 0 -1px 0; + -khtml-box-shadow: rgba(0,0,0,0.2) 0 -1px 0; + -webkit-box-shadow: rgba(0,0,0,0.2) 0 -1px 0; + box-shadow: rgba(0,0,0,0.2) 0 -1px 0; +} + +#adminmenu li.current a:hover #awaiting-mod, +#adminmenu li.current a:hover .update-plugins, +#adminmenu li.wp-has-current-submenu a:hover #awaiting-mod, +#adminmenu li.wp-has-current-submenu a:hover .update-plugins { + background-color: #264761; + color: #fff; +} + +div#media-upload-header, +div#plugin-information-header { + background-color: #f9f9f9; + border-bottom-color: #dfdfdf; +} + +#currenttheme img { + border-color: #666; +} + +#dashboard_secondary div.dashboard-widget-content ul li a { + background-color: #f9f9f9; +} + +input.readonly, textarea.readonly { + background-color: #ddd; +} + +#ed_toolbar input, +#ed_reply_toolbar input { + background: #fff url("../images/fade-butt.png") repeat-x 0 -2px; +} + +#editable-post-name { + background-color: #fffbcc; +} + +#edit-slug-box strong, +.tablenav .displaying-num, +#submitted-on { + color: #777; +} + +.login #nav a { + color: #21759b !important; +} + +.login #nav a:hover { + color: #d54e21 !important; +} + +#footer, +#footer-upgrade { + background: #1d507d; + color: #b6d1e4; +} + +#media-items { + border-color: #dfdfdf; +} + +.checkbox, +.side-info, +.plugins tr, +.postbox, +#your-profile #rich_editing { + background-color: #fff; +} + +.plugins .inactive, +.plugins .inactive th, +.plugins .inactive td, +tr.inactive + tr.plugin-update-tr .plugin-update { + background-color: #ebeeef; +} + +.plugin-update-tr .update-message { + background-color: #fffbe4; + border-color: #dfdfdf; +} + +.plugins .active, +.plugins .active th, +.plugins .active td { + color: #000; +} + +.plugins .inactive a { + color: #557799; +} + +#the-comment-list .unapproved, +#the-comment-list .unapproved th, +#the-comment-list .unapproved td { + background-color: #ffffe0; +} + +#the-comment-list .approve a { + color: #006505; +} + +#the-comment-list .unapprove a { + color: #d98500; +} + +#the-comment-list .delete a { + color: #bc0b0b; +} + +.widget, +#widget-list .widget-top, +.postbox, +#titlediv, +#poststuff .postarea, +.stuffbox { + border-color: #dfdfdf; +} + +.widget, +.postbox { + background-color: #fff; +} + +.ui-sortable .postbox h3 { + color: #093e56; +} + +.widget .widget-top, +.ui-sortable .postbox h3:hover { + color: #000; +} + +.curtime #timestamp { + background-image: url(../images/date-button.gif); +} + +#quicktags #ed_link { + color: #00f; +} + +#rightnow .youhave { + background-color: #f0f6fb; +} + +#rightnow a { + color: #448abd; +} + +.tagchecklist span a, +#bulk-titles div a { + background: url(../images/xit.gif) no-repeat; +} + +.tagchecklist span a:hover, +#bulk-titles div a:hover { + background: url(../images/xit.gif) no-repeat -10px 0; +} + +#update-nag { + background-color: #fffeeb; + border-color: #ccc; + color: #555; +} + +.login #backtoblog a { + color: #ccc; +} + +#wphead { + background-color: #1d507d; +} + +body.login { + border-top-color: #093e56; +} + +#wphead h1 a { + color: #fff; +} + +#login form input { + color: #555; +} + +#user_info { + color: #b6d1e4; +} + +#user_info a:link, +#user_info a:visited, +#footer a:link, +#footer a:visited { + color: #fff; + text-decoration: none; +} + +#user_info a:hover, +#user_info a:active, +#footer a:hover, +#footer a:active { + text-decoration: underline; +} + +div#media-upload-error, +.file-error, +abbr.required, +.widget-control-remove:hover, +.delete a:hover { + color: #f00; +} + +/* password strength meter */ +#pass-strength-result { + background-color: #eee; + border-color: #ddd !important; +} + +#pass-strength-result.bad { + background-color: #ffb78c; + border-color: #ff853c !important; +} + +#pass-strength-result.good { + background-color: #ffec8b; + border-color: #fc0 !important; +} + +#pass-strength-result.short { + background-color: #ffa0a0; + border-color: #f04040 !important; +} + +#pass-strength-result.strong { + background-color: #c3ff88; + border-color: #8dff1c !important; +} + +/* editors */ +#quicktags { + border-color: #dfdfdf; + background-color: #dfdfdf; +} + +#ed_toolbar input { + border-color: #c3c3c3; +} + +#ed_toolbar input:hover { + border-color: #aaa; + background: #ddd; +} + +#poststuff .wp_themeSkin .mceStatusbar { + border-color: #ededed; +} + +#poststuff #edButtonPreview, +#poststuff #edButtonHTML { + background-color: #f2f1eb; + border-color: #dfdfdf; + color: #999; +} + +#poststuff #editor-toolbar .active { + border-bottom-color: #e3eef7; + background-color: #e3eef7; + color: #333; +} + +/* TinyMCE */ +#post-status-info { + background-color: #ededed; +} + +.wp_themeSkin *, +.wp_themeSkin a:hover, +.wp_themeSkin a:link, +.wp_themeSkin a:visited, +.wp_themeSkin a:active { + color: #000; +} + +/* Containers */ +.wp_themeSkin iframe { + background: #fff; +} + +/* Layout */ +.wp_themeSkin .mceStatusbar { + color: #000; + background-color: #f5f5f5; +} + +/* Button */ +.wp_themeSkin .mceButton { + background-color: #e9e8e8; + border-color: #b2b2b2; +} + +.wp_themeSkin a.mceButtonEnabled:hover, +.wp_themeSkin a.mceButtonActive, +.wp_themeSkin a.mceButtonSelected { + background-color: #d5d5d5; + border-color: #777 !important; +} + +.wp_themeSkin .mceButtonDisabled { + border-color: #ccc !important; +} + +/* ListBox */ +.wp_themeSkin .mceListBox .mceText, +.wp_themeSkin .mceListBox .mceOpen { + border-color: #b2b2b2; + background-color: #d5d5d5; +} + +.wp_themeSkin table.mceListBoxEnabled:hover .mceOpen, +.wp_themeSkin .mceListBoxHover .mceOpen, +.wp_themeSkin .mceListBoxSelected .mceOpen, +.wp_themeSkin .mceListBoxSelected .mceText { + border-color: #777 !important; + background-color: #d5d5d5; +} + +.wp_themeSkin table.mceListBoxEnabled:hover .mceText, +.wp_themeSkin .mceListBoxHover .mceText { + border-color: #777 !important; +} + +.wp_themeSkin select.mceListBox { + border-color: #b2b2b2; + background-color: #fff; +} + +/* SplitButton */ +.wp_themeSkin .mceSplitButton a.mceAction, +.wp_themeSkin .mceSplitButton a.mceOpen { + border-color: #b2b2b2; +} + +.wp_themeSkin .mceSplitButton a.mceOpen:hover, +.wp_themeSkin .mceSplitButtonSelected a.mceOpen, +.wp_themeSkin table.mceSplitButtonEnabled:hover a.mceAction, +.wp_themeSkin .mceSplitButton a.mceAction:hover { + background-color: #d5d5d5; + border-color: #777 !important; +} + +.wp_themeSkin .mceSplitButtonActive { + background-color: #b2b2b2; +} + +/* ColorSplitButton */ +.wp_themeSkin div.mceColorSplitMenu table { + background-color: #ebebeb; + border-color: #b2b2b2; +} + +.wp_themeSkin .mceColorSplitMenu a { + border-color: #b2b2b2; +} + +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors { + border-color: #fff; +} + +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover { + border-color: #0a246a; + background-color: #b6bdd2; +} + +.wp_themeSkin a.mceMoreColors:hover { + border-color: #0a246a; +} + +/* Menu */ +.wp_themeSkin .mceMenu { + border-color: #ddd; +} + +.wp_themeSkin .mceMenu table { + background-color: #ebeaeb; +} + +.wp_themeSkin .mceMenu .mceText { + color: #000; +} + +.wp_themeSkin .mceMenu .mceMenuItemEnabled a:hover, +.wp_themeSkin .mceMenu .mceMenuItemActive { + background-color: #f5f5f5; +} +.wp_themeSkin td.mceMenuItemSeparator { + background-color: #aaa; +} +.wp_themeSkin .mceMenuItemTitle a { + background-color: #ccc; + border-bottom-color: #aaa; +} +.wp_themeSkin .mceMenuItemTitle span.mceText { + color: #000; +} +.wp_themeSkin .mceMenuItemDisabled .mceText { + color: #888; +} + +#quicktags, +.wp_themeSkin tr.mceFirst td.mceToolbar { + background: #e3eef7 url("../images/ed-bg-vs.gif") repeat-x scroll left top; +} +.wp_themeSkin tr.mceFirst td.mceToolbar { + border-color: #dfdfdf; +} + +.wp-admin #mceModalBlocker { + background: #000; +} + +.wp-admin .clearlooks2 .mceFocus .mceTop .mceLeft { + background: #444; + border-left: 1px solid #999; + border-top: 1px solid #999; + -moz-border-radius: 4px 0 0 0; + -webkit-border-top-left-radius: 4px; + -khtml-border-top-left-radius: 4px; + border-top-left-radius: 4px; +} + +.wp-admin .clearlooks2 .mceFocus .mceTop .mceRight { + background: #444; + border-right: 1px solid #999; + border-top: 1px solid #999; + border-top-right-radius: 4px; + -khtml-border-top-right-radius: 4px; + -webkit-border-top-right-radius: 4px; + -moz-border-radius: 0 4px 0 0; +} + +.wp-admin .clearlooks2 .mceMiddle .mceLeft { + background: #f1f1f1; + border-left: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceMiddle .mceRight { + background: #f1f1f1; + border-right: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom { + background: #f1f1f1; + border-bottom: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom .mceLeft { + background: #f1f1f1; + border-bottom: 1px solid #999; + border-left: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom .mceCenter { + background: #f1f1f1; + border-bottom: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom .mceRight { + background: #f1f1f1; + border-bottom: 1px solid #999; + border-right: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceFocus .mceTop span { + color: #e5e5e5; +} +/* end TinyMCE */ + +#editorcontainer, +#post-status-info, +#titlediv #title, +.editwidget .widget-inside { + border-color: #dfdfdf; +} + +#titlediv #title { + background-color: #fff; +} + +#tTips p#tTips_inside { + background-color: #ddd; + color: #333; +} + +#timestampdiv input, +#namediv input, +#poststuff .inside .the-tagcloud { + border-color: #dfdfdf; +} + +/* menu */ +#adminmenu * { + border-color: #dfdfdf; +} + +#adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll left 5px; +} + +.folded #adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll right -34px; +} + +#adminmenu li.wp-has-current-submenu.wp-menu-open .wp-menu-toggle, +#adminmenu li.wp-has-current-submenu:hover .wp-menu-toggle { + background: transparent url(../images/menu-bits-vs.gif) no-repeat scroll left -207px; +} + +#adminmenu .wp-has-submenu:hover .wp-menu-toggle, +#adminmenu .wp-menu-open .wp-menu-toggle { + background: transparent url(../images/menu-bits-vs.gif) no-repeat scroll left -109px; +} + +#adminmenu a.menu-top { + background: #eaf3fa url(../images/menu-bits-vs.gif) repeat-x scroll left -379px; +} + +#adminmenu .wp-submenu a { + background: #fff url(../images/menu-bits-vs.gif) no-repeat scroll 0 -310px; +} + +#adminmenu .wp-has-current-submenu ul li a { + background: none; +} + +#adminmenu .wp-has-current-submenu ul li a.current { + background: url(../images/menu-dark.gif) top left no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu a.wp-has-current-submenu, +#adminmenu .menu-top .current { + background: #3c6b95 url(../images/menu-bits-vs.gif) top left repeat-x; + border-color: #1d507d; + color: #fff; + text-shadow: rgba(0,0,0,0.4) 0 -1px 0; +} + +#adminmenu li.wp-has-current-submenu .wp-submenu, +#adminmenu li.wp-has-current-submenu ul li a { + border-color: #aaa !important; +} + +#adminmenu li.wp-has-current-submenu ul li a { + background: url(../images/menu-dark.gif) bottom left no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu ul { + border-bottom-color: #aaa; +} + +#adminmenu li.menu-top .current:hover { + border-color: #6583c0; +} + +#adminmenu .wp-submenu .current a.current { + background: transparent url(../images/menu-bits-vs.gif) no-repeat scroll 0 -289px; +} + +#adminmenu .wp-submenu a:hover { + background-color: #eaf2fa !important; + color: #333 !important; +} + +#adminmenu .wp-submenu li.current, +#adminmenu .wp-submenu li.current a, +#adminmenu .wp-submenu li.current a:hover { + color: #333; + background-color: #f5f5f5; + background-image: none; + border-color: #e3e3e3; + text-shadow: rgba(255,255,255,1) 0 1px 0; +} + +#adminmenu .wp-submenu ul { + background-color: #fff; +} + +.folded #adminmenu li.menu-top, +#adminmenu .wp-submenu .wp-submenu-head { + background-color: #eaf2fa; +} + +.folded #adminmenu li.wp-has-current-submenu, +.folded #adminmenu li.menu-top.current { + background-color: #bbd8e7; +} + +#adminmenu .wp-has-current-submenu .wp-submenu .wp-submenu-head { + background-color: #bbd8e7; + border-color: #8cbdd5; +} + +#adminmenu div.wp-submenu { + background-color: transparent; +} + +/* menu icons */ +#adminmenu #menu-dashboard div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -61px -33px; +} + +#adminmenu #menu-dashboard:hover div.wp-menu-image, +#adminmenu #menu-dashboard.wp-has-current-submenu div.wp-menu-image, +#adminmenu #menu-dashboard.current div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -61px -1px; +} + +#adminmenu #menu-posts div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -272px -33px; +} + +#adminmenu #menu-posts:hover div.wp-menu-image, +#adminmenu #menu-posts.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -272px -1px; +} + +#adminmenu #menu-media div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -121px -33px; +} + +#adminmenu #menu-media:hover div.wp-menu-image, +#adminmenu #menu-media.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -121px -1px; +} + +#adminmenu #menu-links div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -91px -33px; +} + +#adminmenu #menu-links:hover div.wp-menu-image, +#adminmenu #menu-links.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -91px -1px; +} + +#adminmenu #menu-pages div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -151px -33px; +} + +#adminmenu #menu-pages:hover div.wp-menu-image, +#adminmenu #menu-pages.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -151px -1px; +} + +#adminmenu #menu-comments div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -31px -33px; +} + +#adminmenu #menu-comments:hover div.wp-menu-image, +#adminmenu #menu-comments.wp-has-current-submenu div.wp-menu-image, +#adminmenu #menu-comments.current div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -31px -1px; +} + +#adminmenu #menu-appearance div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -1px -33px; +} + +#adminmenu #menu-appearance:hover div.wp-menu-image, +#adminmenu #menu-appearance.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -1px -1px; +} + +#adminmenu #menu-plugins div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -181px -33px; +} + +#adminmenu #menu-plugins:hover div.wp-menu-image, +#adminmenu #menu-plugins.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -181px -1px; +} + +#adminmenu #menu-users div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -301px -33px; +} + +#adminmenu #menu-users:hover div.wp-menu-image, +#adminmenu #menu-users.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -301px -1px; +} + +#adminmenu #menu-tools div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -211px -33px; +} + +#adminmenu #menu-tools:hover div.wp-menu-image, +#adminmenu #menu-tools.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -211px -1px; +} + +#adminmenu #menu-settings div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -241px -33px; +} + +#adminmenu #menu-settings:hover div.wp-menu-image, +#adminmenu #menu-settings.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu-vs.png") no-repeat scroll -241px -1px; +} +/* end menu */ + + +/* Diff */ +table.diff .diff-deletedline { + background-color: #fdd; +} + +table.diff .diff-deletedline del { + background-color: #f99; +} + +table.diff .diff-addedline { + background-color: #dfd; +} + +table.diff .diff-addedline ins { + background-color: #9f9; +} + +#att-info { + background-color: #e4f2fd; +} + +/* edit image */ +#sidemenu a { + background-color: #f9f9f9; + border-color: #f9f9f9; + border-bottom-color: #dfdfdf; +} + +#sidemenu a.current { + background-color: #fff; + border-color: #dfdfdf #dfdfdf #fff; + color: #d54e21; +} + +#screen-options-wrap, +#contextual-help-wrap { + background-color: #eae9e4; + border-color: #dfdfdf; +} + +#screen-meta-links a.show-settings { + color: #606060; +} + +#screen-meta-links a.show-settings:hover { + color: #000; +} + +#replysubmit { + background-color: #f1f1f1; + border-top-color: #ddd; +} + +#replyerror { + border-color: #ddd; + background-color: #f9f9f9; +} + +#edithead, +#replyhead { + background-color: #f1f1f1; +} + +#ed_reply_toolbar { + background-color: #e9e9e9; +} + +/* table vim shortcuts */ +.vim-current, +.vim-current th, +.vim-current td { + background-color: #e4f2fd !important; +} + +/* Install Plugins */ +.star-average, +.star.star-rating { + background-color: #fc0; +} + +div.star.select:hover { + background-color: #d00; +} + +#plugin-information .fyi ul { + background-color: #eaf3fa; +} + +#plugin-information .fyi h2.mainheader { + background-color: #cee1ef; +} + +#plugin-information pre, +#plugin-information code { + background-color: #ededff; +} + +#plugin-information pre { + border: 1px solid #ccc; +} + +/* inline editor */ +.inline-edit-row fieldset input[type="text"], +.inline-edit-row fieldset textarea, +#bulk-titles, +#replyrow input { + border-color: #ddd; +} + +.inline-editor div.title { + background-color: #eaf3fa; +} + +.inline-editor ul.cat-checklist { + background-color: #fff; + border-color: #ddd; +} + +.inline-editor .categories .catshow, +.inline-editor .categories .cathide { + color: #21759b; +} + +.inline-editor .quick-edit-save { + background-color: #f1f1f1; +} + +#replyrow #ed_reply_toolbar input:hover { + border-color: #aaa; + background: #ddd; +} + +fieldset.inline-edit-col-right .inline-edit-col { + border-color: #dfdfdf; +} + +.attention { + color: #d54e21; +} + +.meta-box-sortables .postbox:hover .handlediv { + background: transparent url(../images/menu-bits-vs.gif) no-repeat scroll left -111px; +} + +#major-publishing-actions { + background: #eaf2fa; +} + +.tablenav .tablenav-pages { + color: #555; +} + +.tablenav .tablenav-pages a { + border-color: #e3e3e3; + background: #eee url('../images/menu-bits-vs.gif') repeat-x scroll left -379px; +} + +.tablenav .tablenav-pages a:hover { + color: #d54e21; + border-color: #d54321; +} + +.tablenav .tablenav-pages a:active { + color: #fff !important; +} + +.tablenav .tablenav-pages .current { + background: #dfdfdf; + border-color: #d3d3d3; +} + +#availablethemes, +#availablethemes td { + border-color: #ddd; +} + +#current-theme img { + border-color: #999; +} + +#TB_window #TB_title a.tb-theme-preview-link, +#TB_window #TB_title a.tb-theme-preview-link:visited { + color: #999; +} + +#TB_window #TB_title a.tb-theme-preview-link:hover, +#TB_window #TB_title a.tb-theme-preview-link:focus { + color: #ccc; +} + +.misc-pub-section { + border-bottom-color: #eee; +} + +#minor-publishing { + border-bottom-color: #ddd; +} + +#post-body .misc-pub-section { + border-right-color: #eee; +} + +.post-com-count span { + background-color: #bbb; +} + +.form-table .color-palette td { + border-color: #fff; +} + +.sortable-placeholder { + border-color: #bbb; + background-color: #f5f5f5; +} + +#post-body ul#category-tabs li.tabs a { + color: #333; +} + +#wp_editimgbtn, +#wp_delimgbtn, +#wp_editgallery, +#wp_delgallery { + border-color: #999; + background-color: #eee; +} + +#wp_editimgbtn:hover, +#wp_delimgbtn:hover, +#wp_editgallery:hover, +#wp_delgallery:hover { + border-color: #555; + background-color: #ccc; +} + +#favorite-first { + background: #5580a6 url(../images/fav-vs.png) repeat-x 0 center; + border-color: #517ea5 !important; + border-bottom-color: #416686 !important; +} + +#favorite-actions .slide-down { + background-image: url(../images/fav-top-vs.gif); + background-position:0 0; + background-repeat: repeat-x; +} + +#favorite-inside { + border-color: #5b86ac; + background-color: #5580a6; +} + +#favorite-toggle { + background: transparent url(../images/fav-arrow-vs.gif) no-repeat 0 -4px; +} + +#favorite-actions a { + color: #ddd; +} + +#favorite-actions a:hover { + color: #fff; +} + +#favorite-inside a:hover { + text-decoration: underline; +} + +#favorite-actions .slide-down { + border-bottom-color: #626262; +} + +.submit input, +.button, +.button-primary, +.button-secondary, +.button-highlighted, +#postcustomstuff .submit input { + text-shadow: rgba(255,255,255,1) 0 1px 0; +} + +.button-primary, +.submit .button-primary { + text-shadow: rgba(0,0,0,0.3) 0 -1px 0; +} + +#screen-meta a.show-settings { + background-color: transparent; + text-shadow: rgba(255,255,255,0.7) 0 1px 0; +} + +#icon-edit, +#icon-post { + background: transparent url(../images/icons32-vs.png) no-repeat -552px -5px; +} + +#icon-index { + background: transparent url(../images/icons32-vs.png) no-repeat -137px -5px; +} + +#icon-upload { + background: transparent url(../images/icons32-vs.png) no-repeat -251px -5px; +} + +#icon-link-manager, +#icon-link, +#icon-link-category { + background: transparent url(../images/icons32-vs.png) no-repeat -190px -5px; +} + +#icon-edit-pages, +#icon-page { + background: transparent url(../images/icons32-vs.png) no-repeat -312px -5px; +} + +#icon-edit-comments { + background: transparent url(../images/icons32-vs.png) no-repeat -72px -5px; +} + +#icon-themes { + background: transparent url(../images/icons32-vs.png) no-repeat -11px -5px; +} + +#icon-plugins { + background: transparent url(../images/icons32-vs.png) no-repeat -370px -5px; +} + +#icon-users, +#icon-profile, +#icon-user-edit { + background: transparent url(../images/icons32-vs.png) no-repeat -600px -5px; +} + +#icon-tools, +#icon-admin { + background: transparent url(../images/icons32-vs.png) no-repeat -432px -5px; +} + +#icon-options-general { + background: transparent url(../images/icons32-vs.png) no-repeat -492px -5px; +} + +.view-switch #view-switch-list { + background: transparent url(../images/list-vs.png) no-repeat 0 0; +} + +.view-switch #view-switch-list.current { + background: transparent url(../images/list-vs.png) no-repeat -40px 0; +} + +.view-switch #view-switch-excerpt { + background: transparent url(../images/list-vs.png) no-repeat -20px 0; +} + +.view-switch #view-switch-excerpt.current { + background: transparent url(../images/list-vs.png) no-repeat -60px 0; +} + +#header-logo { + background: transparent url(../images/wp-logo-vs.gif) no-repeat scroll center center; +} + +#wphead #site-visit-button { + background-color: #3c6b95; + background-image: url(../images/visit-site-button-grad-vs.gif); + color: #b6d1e4; + text-shadow: #3f3f3f 0 -1px 0; +} + +#wphead a:hover #site-visit-button { + color: #fff; +} + +#wphead a:focus #site-visit-button, +#wphead a:active #site-visit-button { + background-position: 0 -27px; +} + +.popular-tags, +.feature-filter { + background-color: #fff; + border-color: #dfdfdf; +} + +#theme-information .action-button { + border-top-color: #dfdfdf; +} + +.theme-listing br.line { + border-bottom-color: #ccc; +} + +div.widgets-sortables, +#widgets-left .inactive { + background-color: #f1f1f1; + border-color: #ddd; +} + +#available-widgets .widget-holder { + background-color: #fff; + border-color: #ddd; +} + +#widgets-left .sidebar-name { + background-color: #aaa; + background-image: url(../images/ed-bg-vs.gif); + text-shadow: #FFFFFF 0 1px 0; + border-color: #dfdfdf; +} + +#widgets-right .sidebar-name { + background-image: url(../images/fav-vs.png); + text-shadow: #3f3f3f 0 -1px 0; + background-color: #636363; + border-color: #636363; + color: #fff; +} + +.sidebar-name:hover, +#removing-widget { + color: #d54e21; +} + +#removing-widget span { + color: black; +} + +#widgets-left .sidebar-name-arrow { + background: transparent url(../images/menu-bits-vs.gif) no-repeat scroll left -109px; +} + +#widgets-right .sidebar-name-arrow { + background: transparent url(../images/fav-arrow-vs.gif) no-repeat scroll 0 -1px; +} + +.in-widget-title { + color: #606060; +} + +.deleting .widget-title * { + color: #aaa; +} diff --git a/wp-admin/css/colors-fresh-rtl.css b/wp-admin/css/colors-fresh-rtl.css new file mode 100644 index 0000000..b6d88bb --- /dev/null +++ b/wp-admin/css/colors-fresh-rtl.css @@ -0,0 +1,83 @@ +.bar { + border-right-color: transparent; + border-left-color: #99d; +} + +.plugins .togl { + border-right-color: transparent; + border-left-color: #ccc; +} + +.post-com-count { + background-image: url(../images/bubble_bg-rtl.gif); +} +.tablenav .tablenav-pages a { + background: #eee url('../images/menu-bits-rtl.gif') repeat-x scroll right -379px; +} +#upload-menu li.current { + border-right-color: transparent; + border-left-color: #448abd; +} + +#adminmenu .wp-submenu .current a.current { + background: transparent url(../images/menu-bits-rtl.gif) no-repeat scroll right -289px; +} + +#adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll right -34px; +} + +.folded #adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll left 5px; +} + +#adminmenu li.wp-has-current-submenu .wp-menu-toggle, +#adminmenu li.wp-has-current-submenu:hover .wp-menu-toggle { + background: transparent url(../images/menu-bits-rtl.gif) repeat-x scroll right -207px; +} + +#adminmenu .wp-has-current-submenu ul li a.current { + background: url(../images/menu-dark-rtl.gif) top right no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu a.wp-has-current-submenu, +#adminmenu .menu-top .current { + background: url(../images/menu-bits-rtl.gif) top right repeat-x; +} + +#adminmenu li.wp-has-current-submenu ul li a { + background: url(../images/menu-dark-rtl.gif) bottom right no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu.wp-menu-open .wp-menu-toggle, #adminmenu li.wp-has-current-submenu:hover .wp-menu-toggle { + background: transparent url(../images/menu-bits-rtl.gif) no-repeat right -207px; +} + +#adminmenu .wp-has-submenu:hover .wp-menu-toggle, +#adminmenu .wp-menu-open .wp-menu-toggle { + background: transparent url(../images/menu-bits-rtl.gif) repeat-x scroll right -109px; +} + +#adminmenu a.wp-has-submenu { + background: #f1f1f1 url(../images/menu-bits-rtl.gif) repeat-x scroll right -379px; +} + +#adminmenu .wp-submenu a { + background: #FFFFFF url(../images/menu-bits-rtl.gif) no-repeat scroll right -310px; +} + +#adminmenu li.current a, +#adminmenu .wp-submenu a:hover { + background: transparent url(../images/menu-bits-rtl.gif) no-repeat scroll right -289px; +} + +#adminmenu li.wp-has-current-submenu a.wp-has-submenu { + background: #b5b5b5 url(../images/menu-bits-rtl.gif) repeat-x scroll right top; +} + +.meta-box-sortables .postbox:hover .handlediv { + background: transparent url(../images/menu-bits-rtl.gif) no-repeat scroll right -111px; +} +#favorite-toggle { + background: transparent url(../images/fav-arrow-rtl.gif) no-repeat right -4px; +} diff --git a/wp-admin/css/colors-fresh.css b/wp-admin/css/colors-fresh.css new file mode 100644 index 0000000..7b73e98 --- /dev/null +++ b/wp-admin/css/colors-fresh.css @@ -0,0 +1,1660 @@ +html { + background-color: #f9f9f9; +} + +* html input, +* html .widget { + border-color: #dfdfdf; +} + +textarea, +input, +select { + border-color: #DFDFDF; +} + +kbd, +code { + background: #eaeaea; +} + +input[readonly] { + background-color: #eee; +} + +.find-box-search { + border-color: #dfdfdf; + background-color: #f1f1f1; +} + +.find-box { + background-color: #f1f1f1; +} + +.find-box-inside { + background-color: #fff; +} + +a.page-numbers:hover { + border-color: #999; +} + +body, +#wpbody, +.form-table .pre { + color: #333; +} + +body > #upload-menu { + border-bottom-color: #fff; +} + +#postcustomstuff table, +#your-profile fieldset, +#rightnow, +div.dashboard-widget, +#dashboard-widgets p.dashboard-widget-links, +#replyrow #ed_reply_toolbar input { + border-color: #ccc; +} + +#poststuff .inside label.spam { + color: red; +} + +#poststuff .inside label.waiting { + color: orange; +} + +#poststuff .inside label.approved { + color: green; +} + +#postcustomstuff table { + border-color: #dfdfdf; + background-color: #F9F9F9; +} + +#postcustomstuff thead th { + background-color: #F1F1F1; +} + +#postcustomstuff table input, +#postcustomstuff table textarea { + border-color: #dfdfdf; + background-color: #fff; +} + +.widefat { + border-color: #dfdfdf; + background-color: #fff; +} + +div.dashboard-widget-error { + background-color: #c43; +} + +div.dashboard-widget-notice { + background-color: #cfe1ef; +} + +div.dashboard-widget-submit { + border-top-color: #ccc; +} + +div.tabs-panel, +ul#category-tabs li.tabs { + border-color: #dfdfdf; +} + +ul#category-tabs li.tabs { + background-color: #f1f1f1; +} + +input.disabled, +textarea.disabled { + background-color: #ccc; +} +/* #upload-menu li a.upload-tab-link, */ +.login #backtoblog a:hover, +#plugin-information .action-button a, +#plugin-information .action-button a:hover, +#plugin-information .action-button a:visited { + color: #fff; +} + +.widget .widget-top, +.postbox h3, +.stuffbox h3 { + background: #dfdfdf url("../images/gray-grad.png") repeat-x left top; + text-shadow: #fff 0 1px 0; +} + +.form-table th, +.form-wrap label { + color: #222; + text-shadow: #fff 0 1px 0; +} + +.description, +.form-wrap p { + color: #666; +} + +strong .post-com-count span { + background-color: #21759b; +} + +.sorthelper { + background-color: #ccf3fa; +} + +.ac_match, +.subsubsub a.current { + color: #000; +} + +.wrap h2 { + color: #464646; +} + +.ac_over { + background-color: #f0f0b8; +} + +.ac_results { + background-color: #fff; + border-color: #808080; +} + +.ac_results li { + color: #101010; +} + +.alternate, +.alt { + background-color: #f9f9f9; +} + +.available-theme a.screenshot { + background-color: #f1f1f1; + border-color: #ddd; +} + +.bar { + background-color: #e8e8e8; + border-right-color: #99d; +} + +#media-upload { + background: #fff; +} + +#media-upload .slidetoggle { + border-top-color: #dfdfdf; +} + +.error, +#login #login_error { + background-color: #ffebe8; + border-color: #c00; +} + +.error a { + color: #c00; +} + +.form-invalid { + background-color: #ffebe8 !important; +} + +.form-invalid input { + border-color: #c00 !important; +} + +.submit { + border-color: #DFDFDF; +} + +.highlight { + background-color: #e4f2fd; + color: #d54e21; +} + +.howto, +.nonessential, +#edit-slug-box, +.form-input-tip, +.rss-widget span.rss-date, +.subsubsub { + color: #666; +} + +.media-item { + border-bottom-color: #dfdfdf; +} + +#wpbody-content #media-items .describe { + border-top-color: #dfdfdf; +} + +.describe input[type="text"], +.describe textarea { + border-color: #dfdfdf; +} + +.media-upload-form label.form-help, +td.help { + color: #9a9a9a; +} + +.post-com-count { + background-image: url(../images/bubble_bg.gif); + color: #fff; +} + +.post-com-count span { + background-color: #bbb; + color: #fff; +} + +.post-com-count:hover span { + background-color: #d54e21; +} + +.quicktags, .search { + background-color: #ccc; + color: #000; +} + +.side-info h5 { + border-bottom-color: #dadada; +} + +.side-info ul { + color: #666; +} + +.button, +.button-secondary, +.submit input, +input[type=button], +input[type=submit] { + border-color: #bbb; + color: #464646; +} + +.button:hover, +.button-secondary:hover, +.submit input:hover, +input[type=button]:hover, +input[type=submit]:hover { + color: #000; + border-color: #666; +} + +.button, +.submit input, +.button-secondary { + background: #f2f2f2 url(../images/white-grad.png) repeat-x scroll left top; +} + +.button:active, +.submit input:active, +.button-secondary:active { + background: #eee url(../images/white-grad-active.png) repeat-x scroll left top; +} + +.button-primary, +.submit .button-primary, +#login form .submit input { + border-color: #298cba !important; + font-weight: bold; + color: #FFF !important; + background: #21759B url(../images/button-grad.png) repeat-x scroll left top; +} + +.button-primary:active, +#login form .submit input:active { + background: #21759b url(../images/button-grad-active.png) repeat-x scroll left top !important; +} + +.button[disabled], +.button:disabled, +.button-secondary[disabled], +.button-secondary:disabled, +a.button.disabled { + color: #ccc !important; + border-color: #ccc; +} + +.button-primary[disabled], +.button-primary:disabled { + color: #2fa0d5 !important; +} + +a:active, +a:focus { + color: #d54e21; +} + +a:hover, +#wphead #viewsite a:hover, +#adminmenu a:hover, +#adminmenu ul.wp-submenu a:hover, +#the-comment-list .comment a:hover, +#rightnow a:hover, +#login form .submit input:hover, +#media-upload a.del-link:hover, +div.dashboard-widget-submit input:hover, +.subsubsub a:hover, +.subsubsub a.current:hover, +.ui-tabs-nav a:hover, +.plugins .inactive a:hover, +#all-plugins-table .plugins .inactive a:hover, +#search-plugins-table .plugins .inactive a:hover { + color: #d54e21; +} + +#the-comment-list .comment-item, +#dashboard-widgets #dashboard_quick_press form p.submit { + border-color: #dfdfdf; +} + +.button-primary:hover, +#login form .submit input:hover { + border-color: #13455b !important; + color: #EAF2FA !important; +} + +#side-sortables #category-tabs .tabs a { + color: #333; +} + +#rightnow .rbutton { + background-color: #ebebeb; + color: #264761; +} + +.submitbox .submit { + background-color: #464646; + color: #ccc; +} + +.plugins a.delete:hover, +#all-plugins-table .plugins a.delete:hover, +#search-plugins-table .plugins a.delete:hover, +.submitbox .submitdelete, +a.delete { + color: #f00; + border-bottom-color: #f00; +} + +.submitbox .submitdelete:hover, +#media-items a.delete:hover { + color: #fff; + background-color: #f00; + border-bottom-color: #f00; +} + +#normal-sortables .submitbox .submitdelete:hover { + color: #000; + background-color: #f00; + border-bottom-color: #f00; +} + +.tablenav .dots { + border-color: transparent; +} + +.tablenav .next, +.tablenav .prev { + border-color: transparent; + color: #21759b; +} + +.tablenav .next:hover, +.tablenav .prev:hover { + border-color: transparent; + color: #d54e21; +} + +.updated, +.login #login_error, +.login .message { + background-color: #ffffe0; + border-color: #e6db55; +} + +.update-message { + color: #000000; +} + +a.page-numbers { + border-bottom-color: #B8D3E2; +} + +.commentlist li { + border-bottom-color: #ccc; +} + +.widefat td, +.widefat th, +#install-plugins .plugins td, +#install-plugins .plugins th { + border-color: #dfdfdf; +} + +.widefat th { + text-shadow: rgba(255,255,255,0.8) 0 1px 0; +} + +.widefat thead tr th, +.widefat tfoot tr th, +h3.dashboard-widget-title, +h3.dashboard-widget-title span, +h3.dashboard-widget-title small, +.find-box-head { + color: #333; + background: #dfdfdf url(../images/gray-grad.png) repeat-x scroll left top; +} + +h3.dashboard-widget-title small a { + color: #d7d7d7; +} + +h3.dashboard-widget-title small a:hover { + color: #fff; +} + +a, +#adminmenu a, +#poststuff #edButtonPreview, +#poststuff #edButtonHTML, +#the-comment-list p.comment-author strong a, +#media-upload a.del-link, +#media-items a.delete, +.plugins a.delete, +.ui-tabs-nav a { + color: #21759b; +} + +/* Because we don't want visited on these links */ +body.press-this .tabs a, +body.press-this .tabs a:hover { + background-color: #fff; + border-color: #c6d9e9; + border-bottom-color: #fff; + color: #d54e21; +} + +#adminmenu #awaiting-mod, +#adminmenu .update-plugins, +#sidemenu a .update-plugins, +#rightnow .reallynow, +#plugin-information .action-button { + background-color: #d54e21; + color: #fff; +} + +#adminmenu li a:hover #awaiting-mod, +#adminmenu li a:hover .update-plugins, +#sidemenu li a:hover .update-plugins { + background-color: #264761; + color: #fff; +} + +#adminmenu li.current a #awaiting-mod, +#adminmenu li.current a .update-plugins, +#adminmenu li.wp-has-current-submenu a .update-plugins, +#adminmenu li.wp-has-current-submenu a .update-plugins { + background-color: #ddd; + color: #000; + text-shadow: none; + -moz-box-shadow: rgba(0,0,0,0.2) 0 -1px 0; + -khtml-box-shadow: rgba(0,0,0,0.2) 0 -1px 0; + -webkit-box-shadow: rgba(0,0,0,0.2) 0 -1px 0; + box-shadow: rgba(0,0,0,0.2) 0 -1px 0; +} + +#adminmenu li.current a:hover #awaiting-mod, +#adminmenu li.current a:hover .update-plugins, +#adminmenu li.wp-has-current-submenu a:hover #awaiting-mod, +#adminmenu li.wp-has-current-submenu a:hover .update-plugins { + background-color: #264761; + color: #fff; +} + +div#media-upload-header, +div#plugin-information-header { + background-color: #f9f9f9; + border-bottom-color: #dfdfdf; +} + +#currenttheme img { + border-color: #666; +} + +#dashboard_secondary div.dashboard-widget-content ul li a { + background-color: #f9f9f9; +} + +input.readonly, textarea.readonly { + background-color: #ddd; +} + +#ed_toolbar input, +#ed_reply_toolbar input { + background: #fff url("../images/fade-butt.png") repeat-x 0 -2px; +} + +#editable-post-name { + background-color: #fffbcc; +} + +#edit-slug-box strong, +.tablenav .displaying-num, +#submitted-on { + color: #777; +} + +.login #nav a { + color: #21759b !important; +} + +.login #nav a:hover { + color: #d54e21 !important; +} + +#footer, +#footer-upgrade { + background: #464646; + color: #999; +} + +#media-items { + border-color: #dfdfdf; +} + +.checkbox, +.side-info, +.plugins tr, +#your-profile #rich_editing { + background-color: #fff; +} + +.plugins .inactive, +.plugins .inactive th, +.plugins .inactive td, +tr.inactive + tr.plugin-update-tr .plugin-update { + background-color: #eee; +} + +.plugin-update-tr .update-message { + background-color: #fffbe4; + border-color: #dfdfdf; +} + +.plugins .active, +.plugins .active th, +.plugins .active td { + color: #000; +} + +.plugins .inactive a { + color: #557799; +} + +#the-comment-list .unapproved, +#the-comment-list .unapproved th, +#the-comment-list .unapproved td { + background-color: #ffffe0; +} + +#the-comment-list .approve a { + color: #006505; +} + +#the-comment-list .unapprove a { + color: #d98500; +} + +#the-comment-list .delete a { + color: #bc0b0b; +} + +.widget, +#widget-list .widget-top, +.postbox, +#titlediv, +#poststuff .postarea, +.stuffbox { + border-color: #dfdfdf; +} + +.widget, +.postbox { + background-color: #fff; +} + +.ui-sortable .postbox h3 { + color: #464646; +} + +.widget .widget-top, +.ui-sortable .postbox h3:hover { + color: #000; +} + +.curtime #timestamp { + background-image: url(../images/date-button.gif); +} + +#quicktags #ed_link { + color: #00f; +} + +#rightnow .youhave { + background-color: #f0f6fb; +} + +#rightnow a { + color: #448abd; +} + +.tagchecklist span a, +#bulk-titles div a { + background: url(../images/xit.gif) no-repeat; +} + +.tagchecklist span a:hover, +#bulk-titles div a:hover { + background: url(../images/xit.gif) no-repeat -10px 0; +} + +#update-nag { + background-color: #fffeeb; + border-color: #ccc; + color: #555; +} + +.login #backtoblog a { + color: #ccc; +} + +#wphead { + background-color: #464646; +} + +body.login { + border-top-color: #464646; +} + +#wphead h1 a { + color: #fff; +} + +#login form input { + color: #555; +} + +#user_info { + color: #999; +} + +#user_info a:link, +#user_info a:visited, +#footer a:link, +#footer a:visited { + color: #ccc; + text-decoration: none; +} + +#user_info a:hover, +#footer a:hover { + color: #fff; + text-decoration: underline !important; +} + +#user_info a:active, +#footer a:active { + color: #ccc !important; +} + +div#media-upload-error, +.file-error, +abbr.required, +.widget-control-remove:hover, +.delete a:hover { + color: #f00; +} + +#pass-strength-result { + background-color: #eee; + border-color: #ddd !important; +} + +#pass-strength-result.bad { + background-color: #ffb78c; + border-color: #ff853c !important; +} + +#pass-strength-result.good { + background-color: #ffec8b; + border-color: #fc0 !important; +} + +#pass-strength-result.short { + background-color: #ffa0a0; + border-color: #f04040 !important; +} + +#pass-strength-result.strong { + background-color: #c3ff88; + border-color: #8dff1c !important; +} + +/* editors */ +#quicktags { + border-color: #dfdfdf; + background-color: #dfdfdf; +} + +#ed_toolbar input { + border-color: #C3C3C3; +} + +#ed_toolbar input:hover { + border-color: #aaa; + background: #ddd; +} + +#poststuff .wp_themeSkin .mceStatusbar { + border-color: #EDEDED; +} + +#poststuff #edButtonPreview, +#poststuff #edButtonHTML { + background-color: #f1f1f1; + border-color: #dfdfdf; + color: #999; +} + +#poststuff #editor-toolbar .active { + border-bottom-color: #e9e9e9; + background-color: #e9e9e9; + color: #333; +} + +/* TinyMCE */ +#post-status-info { + background-color: #EDEDED; +} + +.wp_themeSkin *, +.wp_themeSkin a:hover, +.wp_themeSkin a:link, +.wp_themeSkin a:visited, +.wp_themeSkin a:active { + color: #000; +} + +/* Containers */ +.wp_themeSkin iframe { + background: #fff; +} + +/* Layout */ +.wp_themeSkin .mceStatusbar { + color: #000; + background-color: #f5f5f5; +} + +/* Button */ +.wp_themeSkin .mceButton { + background-color: #e9e8e8; + border-color: #B2B2B2; +} + +.wp_themeSkin a.mceButtonEnabled:hover, +.wp_themeSkin a.mceButtonActive, +.wp_themeSkin a.mceButtonSelected { + background-color: #d5d5d5; + border-color: #777 !important; +} + +.wp_themeSkin .mceButtonDisabled { + border-color: #ccc !important; +} + +/* ListBox */ +.wp_themeSkin .mceListBox .mceText, +.wp_themeSkin .mceListBox .mceOpen { + border-color: #B2B2B2; + background-color: #d5d5d5; +} + +.wp_themeSkin table.mceListBoxEnabled:hover .mceOpen, +.wp_themeSkin .mceListBoxHover .mceOpen, +.wp_themeSkin .mceListBoxSelected .mceOpen, +.wp_themeSkin .mceListBoxSelected .mceText { + border-color: #777 !important; + background-color: #d5d5d5; +} + +.wp_themeSkin table.mceListBoxEnabled:hover .mceText, +.wp_themeSkin .mceListBoxHover .mceText { + border-color: #777 !important; +} + +.wp_themeSkin select.mceListBox { + border-color: #B2B2B2; + background-color: #fff; +} + +/* SplitButton */ +.wp_themeSkin .mceSplitButton a.mceAction, +.wp_themeSkin .mceSplitButton a.mceOpen { + border-color: #B2B2B2; +} + +.wp_themeSkin .mceSplitButton a.mceOpen:hover, +.wp_themeSkin .mceSplitButtonSelected a.mceOpen, +.wp_themeSkin table.mceSplitButtonEnabled:hover a.mceAction, +.wp_themeSkin .mceSplitButton a.mceAction:hover { + background-color: #d5d5d5; + border-color: #777 !important; +} + +.wp_themeSkin .mceSplitButtonActive { + background-color: #B2B2B2; +} + +/* ColorSplitButton */ +.wp_themeSkin div.mceColorSplitMenu table { + background-color: #ebebeb; + border-color: #B2B2B2; +} + +.wp_themeSkin .mceColorSplitMenu a { + border-color: #B2B2B2; +} + +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors { + border-color: #fff; +} + +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover { + border-color: #0A246A; + background-color: #B6BDD2; +} + +.wp_themeSkin a.mceMoreColors:hover { + border-color: #0A246A; +} + +/* Menu */ +.wp_themeSkin .mceMenu { + border-color: #ddd; +} + +.wp_themeSkin .mceMenu table { + background-color: #ebeaeb; +} + +.wp_themeSkin .mceMenu .mceText { + color: #000; +} + +.wp_themeSkin .mceMenu .mceMenuItemEnabled a:hover, +.wp_themeSkin .mceMenu .mceMenuItemActive { + background-color: #f5f5f5; +} +.wp_themeSkin td.mceMenuItemSeparator { + background-color: #aaa; +} +.wp_themeSkin .mceMenuItemTitle a { + background-color: #ccc; + border-bottom-color: #aaa; +} +.wp_themeSkin .mceMenuItemTitle span.mceText { + color: #000; +} +.wp_themeSkin .mceMenuItemDisabled .mceText { + color: #888; +} + +.wp_themeSkin tr.mceFirst td.mceToolbar { + background: #dfdfdf url("../images/ed-bg.gif") repeat-x scroll left top; + border-color: #dfdfdf; +} + +.wp-admin #mceModalBlocker { + background: #000; +} + +.wp-admin .clearlooks2 .mceFocus .mceTop .mceLeft { + background: #444444; + border-left: 1px solid #999; + border-top: 1px solid #999; + -moz-border-radius: 4px 0 0 0; + -webkit-border-top-left-radius: 4px; + -khtml-border-top-left-radius: 4px; + border-top-left-radius: 4px; +} + +.wp-admin .clearlooks2 .mceFocus .mceTop .mceRight { + background: #444444; + border-right: 1px solid #999; + border-top: 1px solid #999; + border-top-right-radius: 4px; + -khtml-border-top-right-radius: 4px; + -webkit-border-top-right-radius: 4px; + -moz-border-radius: 0 4px 0 0; +} + +.wp-admin .clearlooks2 .mceMiddle .mceLeft { + background: #f1f1f1; + border-left: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceMiddle .mceRight { + background: #f1f1f1; + border-right: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom { + background: #f1f1f1; + border-bottom: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom .mceLeft { + background: #f1f1f1; + border-bottom: 1px solid #999; + border-left: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom .mceCenter { + background: #f1f1f1; + border-bottom: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceBottom .mceRight { + background: #f1f1f1; + border-bottom: 1px solid #999; + border-right: 1px solid #999; +} + +.wp-admin .clearlooks2 .mceFocus .mceTop span { + color: #e5e5e5; +} +/* end TinyMCE */ + +#editorcontainer, +#post-status-info, +#titlediv #title, +.editwidget .widget-inside { + border-color: #dfdfdf; +} + +#titlediv #title { + background-color: #fff; +} + +#tTips p#tTips_inside { + background-color: #ddd; + color: #333; +} + +#timestampdiv input, +#namediv input, +#poststuff .inside .the-tagcloud { + border-color: #ddd; +} + +/* menu */ +#adminmenu * { + border-color: #e3e3e3; +} + +#adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll left 5px; +} + +.folded #adminmenu li.wp-menu-separator { + background: transparent url(../images/menu-arrows.gif) no-repeat scroll right -34px; +} + +#adminmenu li.wp-has-current-submenu.wp-menu-open .wp-menu-toggle, +#adminmenu li.wp-has-current-submenu:hover .wp-menu-toggle { + background: transparent url(../images/menu-bits.gif) no-repeat scroll left -207px; +} + +#adminmenu .wp-has-submenu:hover .wp-menu-toggle, +#adminmenu .wp-menu-open .wp-menu-toggle { + background: transparent url(../images/menu-bits.gif) no-repeat scroll left -109px; +} + +#adminmenu a.menu-top { + background: #f1f1f1 url(../images/menu-bits.gif) repeat-x scroll left -379px; +} + +#adminmenu .wp-submenu a { + background: #FFFFFF url(../images/menu-bits.gif) no-repeat scroll 0 -310px; +} + +#adminmenu .wp-has-current-submenu ul li a { + background: none; +} + +#adminmenu .wp-has-current-submenu ul li a.current { + background: url(../images/menu-dark.gif) top left no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu a.wp-has-current-submenu, +#adminmenu .menu-top .current { + background: #6d6d6d url(../images/menu-bits.gif) top left repeat-x; + border-color: #6d6d6d; + color: #fff; + text-shadow: rgba(0,0,0,0.4) 0px -1px 0px; +} + +#adminmenu li.wp-has-current-submenu .wp-submenu, +#adminmenu li.wp-has-current-submenu ul li a { + border-color: #aaa !important; +} + +#adminmenu li.wp-has-current-submenu ul li a { + background: url(../images/menu-dark.gif) bottom left no-repeat !important; +} + +#adminmenu li.wp-has-current-submenu ul { + border-bottom-color: #aaa; +} + +#adminmenu li.menu-top .current:hover { + border-color: #B5B5B5; +} + +#adminmenu .wp-submenu .current a.current { + background: transparent url(../images/menu-bits.gif) no-repeat scroll 0 -289px; +} + +#adminmenu .wp-submenu a:hover { + background-color: #EAF2FA !important; + color: #333 !important; +} + +#adminmenu .wp-submenu li.current, +#adminmenu .wp-submenu li.current a, +#adminmenu .wp-submenu li.current a:hover { + color: #333; + background-color: #f5f5f5; + background-image: none; + border-color: #e3e3e3; + text-shadow: rgba(255,255,255,1) 0px 1px 0px; +} + +#adminmenu .wp-submenu ul { + background-color: #fff; +} + +.folded #adminmenu li.menu-top, +#adminmenu .wp-submenu .wp-submenu-head { + background-color: #F1F1F1; +} + +.folded #adminmenu li.wp-has-current-submenu, +.folded #adminmenu li.menu-top.current { + background-color: #e6e6e6; +} + +#adminmenu .wp-has-current-submenu .wp-submenu .wp-submenu-head { + background-color: #EAEAEA; + border-color: #aaa; +} + +#adminmenu div.wp-submenu { + background-color: transparent; +} + +/* menu icons */ +#adminmenu #menu-dashboard div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -61px -33px; +} + +#adminmenu #menu-dashboard:hover div.wp-menu-image, +#adminmenu #menu-dashboard.wp-has-current-submenu div.wp-menu-image, +#adminmenu #menu-dashboard.current div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -61px -1px; +} + +#adminmenu #menu-posts div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -272px -33px; +} + +#adminmenu #menu-posts:hover div.wp-menu-image, +#adminmenu #menu-posts.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -272px -1px; +} + +#adminmenu #menu-media div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -121px -33px; +} + +#adminmenu #menu-media:hover div.wp-menu-image, +#adminmenu #menu-media.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -121px -1px; +} + +#adminmenu #menu-links div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -91px -33px; +} + +#adminmenu #menu-links:hover div.wp-menu-image, +#adminmenu #menu-links.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -91px -1px; +} + +#adminmenu #menu-pages div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -151px -33px; +} + +#adminmenu #menu-pages:hover div.wp-menu-image, +#adminmenu #menu-pages.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -151px -1px; +} + +#adminmenu #menu-comments div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -31px -33px; +} + +#adminmenu #menu-comments:hover div.wp-menu-image, +#adminmenu #menu-comments.wp-has-current-submenu div.wp-menu-image, +#adminmenu #menu-comments.current div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -31px -1px; +} + +#adminmenu #menu-appearance div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -1px -33px; +} + +#adminmenu #menu-appearance:hover div.wp-menu-image, +#adminmenu #menu-appearance.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -1px -1px; +} + +#adminmenu #menu-plugins div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -181px -33px; +} + +#adminmenu #menu-plugins:hover div.wp-menu-image, +#adminmenu #menu-plugins.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -181px -1px; +} + +#adminmenu #menu-users div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -301px -33px; +} + +#adminmenu #menu-users:hover div.wp-menu-image, +#adminmenu #menu-users.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -301px -1px; +} + +#adminmenu #menu-tools div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -211px -33px; +} + +#adminmenu #menu-tools:hover div.wp-menu-image, +#adminmenu #menu-tools.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -211px -1px; +} + +#adminmenu #menu-settings div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -241px -33px; +} + +#adminmenu #menu-settings:hover div.wp-menu-image, +#adminmenu #menu-settings.wp-has-current-submenu div.wp-menu-image { + background: transparent url("../images/menu.png") no-repeat scroll -241px -1px; +} +/* end menu */ + + +/* Diff */ +table.diff .diff-deletedline { + background-color: #ffdddd; +} + +table.diff .diff-deletedline del { + background-color: #ff9999; +} + +table.diff .diff-addedline { + background-color: #ddffdd; +} + +table.diff .diff-addedline ins { + background-color: #99ff99; +} + +#att-info { + background-color: #E4F2FD; +} + +/* edit image */ +#sidemenu a { + background-color: #f9f9f9; + border-color: #f9f9f9; + border-bottom-color: #dfdfdf; +} + +#sidemenu a.current { + background-color: #fff; + border-color: #dfdfdf #dfdfdf #fff; + color: #D54E21; +} + +#screen-options-wrap, +#contextual-help-wrap { + background-color: #f1f1f1; + border-color: #dfdfdf; +} + +#screen-meta-links a.show-settings { + color: #606060; +} + +#screen-meta-links a.show-settings:hover { + color: #000; +} + +#replysubmit { + background-color: #f1f1f1; + border-top-color: #ddd; +} + +#replyerror { + border-color: #ddd; + background-color: #f9f9f9; +} + +#edithead, +#replyhead { + background-color: #f1f1f1; +} + +#ed_reply_toolbar { + background-color: #e9e9e9; +} + +/* table vim shortcuts */ +.vim-current, +.vim-current th, +.vim-current td { + background-color: #E4F2FD !important; +} + +/* Install Plugins */ +.star-average, +.star.star-rating { + background-color: #fc0; +} + +div.star.select:hover { + background-color: #d00; +} + +#plugin-information .fyi ul { + background-color: #eaf3fa; +} + +#plugin-information .fyi h2.mainheader { + background-color: #cee1ef; +} + +#plugin-information pre, +#plugin-information code { + background-color: #ededff; +} + +#plugin-information pre { + border: 1px solid #ccc; +} + +/* inline editor */ +.inline-edit-row fieldset input[type="text"], +.inline-edit-row fieldset textarea, +#bulk-titles, +#replyrow input { + border-color: #ddd; +} + +.inline-editor div.title { + background-color: #EAF3FA; +} + +.inline-editor ul.cat-checklist { + background-color: #FFFFFF; + border-color: #ddd; +} + +.inline-editor .categories .catshow, +.inline-editor .categories .cathide { + color: #21759b; +} + +.inline-editor .quick-edit-save { + background-color: #f1f1f1; +} + +#replyrow #ed_reply_toolbar input:hover { + border-color: #aaa; + background: #ddd; +} + +fieldset.inline-edit-col-right .inline-edit-col { + border-color: #dfdfdf; +} + +.attention { + color: #D54E21; +} + +.meta-box-sortables .postbox:hover .handlediv { + background: transparent url(../images/menu-bits.gif) no-repeat scroll left -111px; +} + +#major-publishing-actions { + background: #eaf2fa; +} + +.tablenav .tablenav-pages { + color: #555; +} + +.tablenav .tablenav-pages a { + border-color: #e3e3e3; + background: #eee url('../images/menu-bits.gif') repeat-x scroll left -379px; +} + +.tablenav .tablenav-pages a:hover { + color: #d54e21; + border-color: #d54321; +} + +.tablenav .tablenav-pages a:active { + color: #fff !important; +} + +.tablenav .tablenav-pages .current { + background: #dfdfdf; + border-color: #d3d3d3; +} + +#availablethemes, +#availablethemes td { + border-color: #ddd; +} + +#current-theme img { + border-color: #999; +} + +#TB_window #TB_title a.tb-theme-preview-link, +#TB_window #TB_title a.tb-theme-preview-link:visited { + color: #999; +} + +#TB_window #TB_title a.tb-theme-preview-link:hover, +#TB_window #TB_title a.tb-theme-preview-link:focus { + color: #ccc; +} + +.misc-pub-section { + border-bottom-color: #eee; +} + +#minor-publishing { + border-bottom-color: #ddd; +} + +#post-body .misc-pub-section { + border-right-color: #eee; +} + +.post-com-count span { + background-color: #bbb; +} + +.form-table .color-palette td { + border-color: #fff; +} + +.sortable-placeholder { + border-color: #bbb; + background-color: #f5f5f5; +} + +#post-body ul#category-tabs li.tabs a { + color: #333; +} + +#wp_editimgbtn, +#wp_delimgbtn, +#wp_editgallery, +#wp_delgallery { + border-color: #999; + background-color: #eee; +} + +#wp_editimgbtn:hover, +#wp_delimgbtn:hover, +#wp_editgallery:hover, +#wp_delgallery:hover { + border-color: #555; + background-color: #ccc; +} + +#favorite-first { + background: #797979 url(../images/fav.png) repeat-x left center; + border-color: #777 !important; + border-bottom-color: #666 !important; +} + +#favorite-inside { + border-color: #797979; + background-color: #797979; +} + +#favorite-toggle { + background: transparent url(../images/fav-arrow.gif) no-repeat 0 -4px; +} + +#favorite-actions a { + color: #ddd; +} + +#favorite-actions a:hover { + color: #fff; +} + +#favorite-inside a:hover { + text-decoration: underline; +} + +#favorite-actions .slide-down { + border-bottom-color: #626262; +} + +.submit input, +.button, +.button-primary, +.button-secondary, +.button-highlighted, +#postcustomstuff .submit input { + text-shadow: rgba(255,255,255,1) 0 1px 0; +} + +.button-primary, +.submit .button-primary { + text-shadow: rgba(0,0,0,0.3) 0 -1px 0; +} + +#screen-meta a.show-settings { + background-color: transparent; + text-shadow: rgba(255,255,255,0.7) 0 1px 0; +} + +#icon-edit, +#icon-post { + background: transparent url(../images/icons32.png) no-repeat -552px -5px; +} + +#icon-index { + background: transparent url(../images/icons32.png) no-repeat -137px -5px; +} + +#icon-upload { + background: transparent url(../images/icons32.png) no-repeat -251px -5px; +} + +#icon-link-manager, +#icon-link, +#icon-link-category { + background: transparent url(../images/icons32.png) no-repeat -190px -5px; +} + +#icon-edit-pages, +#icon-page { + background: transparent url(../images/icons32.png) no-repeat -312px -5px; +} + +#icon-edit-comments { + background: transparent url(../images/icons32.png) no-repeat -72px -5px; +} + +#icon-themes { + background: transparent url(../images/icons32.png) no-repeat -11px -5px; +} + +#icon-plugins { + background: transparent url(../images/icons32.png) no-repeat -370px -5px; +} + +#icon-users, +#icon-profile, +#icon-user-edit { + background: transparent url(../images/icons32.png) no-repeat -600px -5px; +} + +#icon-tools, +#icon-admin { + background: transparent url(../images/icons32.png) no-repeat -432px -5px; +} + +#icon-options-general { + background: transparent url(../images/icons32.png) no-repeat -492px -5px; +} + +.view-switch #view-switch-list { + background: transparent url(../images/list.png) no-repeat 0 0; +} + +.view-switch #view-switch-list.current { + background: transparent url(../images/list.png) no-repeat -40px 0; +} + +.view-switch #view-switch-excerpt { + background: transparent url(../images/list.png) no-repeat -20px 0; +} + +.view-switch #view-switch-excerpt.current { + background: transparent url(../images/list.png) no-repeat -60px 0; +} + +#header-logo { + background: transparent url(../images/wp-logo.gif) no-repeat scroll center center; +} + +#wphead #site-visit-button { + background-color:#585858; + background-image: url(../images/visit-site-button-grad.gif); + color:#aaa; + text-shadow: #3F3F3F 0 -1px 0; +} + +#wphead a:hover #site-visit-button { + color:#fff; +} + +#wphead a:focus #site-visit-button, +#wphead a:active #site-visit-button { + background-position:0 -27px; +} + +.popular-tags, +.feature-filter { + background-color: #FFFFFF; + border-color: #DFDFDF; +} + +#theme-information .action-button { + border-top-color: #DFDFDF; +} + +.theme-listing br.line { + border-bottom-color: #ccc; +} + +div.widgets-sortables, +#widgets-left .inactive { + background-color: #f1f1f1; + border-color: #ddd; +} + +#available-widgets .widget-holder { + background-color: #fff; + border-color: #ddd; +} + +#widgets-left .sidebar-name { + background-color: #aaa; + background-image: url(../images/ed-bg.gif); + text-shadow: #FFFFFF 0 1px 0; + border-color: #dfdfdf; +} + +#widgets-right .sidebar-name { + background-image: url(../images/fav.png); + text-shadow: #3f3f3f 0 -1px 0; + background-color: #636363; + border-color: #636363; + color: #fff; +} + +.sidebar-name:hover, +#removing-widget { + color: #d54e21; +} + +#removing-widget span { + color: black; +} + +#widgets-left .sidebar-name-arrow { + background: transparent url(../images/menu-bits.gif) no-repeat scroll left -109px; +} + +#widgets-right .sidebar-name-arrow { + background: transparent url(../images/fav-arrow.gif) no-repeat scroll 0 -1px; +} + +.in-widget-title { + color: #606060; +} + +.deleting .widget-title * { + color: #aaa; +} diff --git a/wp-admin/css/dashboard-rtl.css b/wp-admin/css/dashboard-rtl.css new file mode 100644 index 0000000..60a97ba --- /dev/null +++ b/wp-admin/css/dashboard-rtl.css @@ -0,0 +1,93 @@ +#dashboard-widgets-wrap .has-sidebar { + margin-right: 0; + margin-left: -51%; +} +#dashboard-widgets-wrap .has-sidebar .has-sidebar-content { + margin-right: 0; + margin-left: 51%; +} +.view-all { + right: auto; + left: 0; +} +#dashboard_right_now p.sub, #dashboard-widgets h4, #dashboard_quick_press h4, a.rsswidget, #dashboard_plugins h4, #dashboard_plugins h5, #dashboard_recent_comments .comment-meta .approve { + font-family: Tahoma, Arial; +} +#dashboard_right_now td.b { + padding-right: 0; + padding-left: 6px; + text-align: left; + font-family: Tahoma, Arial; +} +#dashboard_right_now .t { + padding-right: 0; + padding-left: 12px; +} +#dashboard_right_now .versions a { + font-family: Tahoma, Arial; +} +#dashboard_right_now a.button { + float: left; + clear: left; +} +#dashboard-widgets h3 .postbox-title-action { + right: auto; + left: 30px; +} +#the-comment-list .pingback { + padding-left: 0 !important; + padding-right: 9px !important; +} +/* Recent Comments */ +#the-comment-list .comment-item { + padding: 1em 70px 1em 10px; +} +#the-comment-list .comment-item .avatar { + float: right; + margin-left: 0; + margin-right: -60px; +} +/* Feeds */ +.rss-widget cite { + text-align: left; +} +.rss-widget span.rss-date { + font-family: Tahoma, Arial; + margin-left: 0; + margin-right: 3px; +} +/* QuickPress */ +#dashboard_quick_press h4 { + float: right; + text-align: left; +} +#dashboard_quick_press h4 label { + margin-right: 0; + margin-left: 10px; +} +#dashboard_quick_press .input-text-wrap, #dashboard_quick_press .textarea-wrap { + margin: 0 5em 1em 0; +} +#dashboard_quick_press #media-buttons { + margin: 0 5em .5em 0; + padding: 0 10px 0 0; +} +#dashboard-widgets #dashboard_quick_press form p.submit { + margin-left: 0; + margin-right: 4.6em; +} +#dashboard-widgets #dashboard_quick_press form p.submit input { + float: right; +} +#dashboard-widgets #dashboard_quick_press form p.submit #save-post { + margin: 0 10px 0 1em; +} +#dashboard-widgets #dashboard_quick_press form p.submit #publish { + float: left; +} +/* Recent Drafts */ +#dashboard_recent_drafts h4 abbr { + font-family: Tahoma, Arial; + margin-left:0; + margin-right: 3px; +} diff --git a/wp-admin/css/dashboard.css b/wp-admin/css/dashboard.css new file mode 100644 index 0000000..2784301 --- /dev/null +++ b/wp-admin/css/dashboard.css @@ -0,0 +1,390 @@ +.postbox p, .postbox ul, .postbox ol, .postbox blockquote, #wp-version-message { font-size: 11px; } + +.edit-box { + display: none; +} + +h3:hover .edit-box { + display: inline; +} + +form .input-text-wrap { + border-style: solid; + border-width: 1px; + padding: 2px 3px; + border-color: #ccc; +} + +#dashboard-widgets form .input-text-wrap input { + border: 0 none; + outline: none; + margin: 0; + padding: 0; + width: 99%; + color: #333; +} + +form .textarea-wrap { + border-style: solid; + border-width: 1px; + padding: 2px; + border-color: #ccc; +} + +#dashboard-widgets form .textarea-wrap textarea { + border: 0 none; + padding: 0; + outline: none; + width: 99%; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +#dashboard-widgets .postbox form .submit { + float: none; + margin: .5em 0 0; + padding: 0; + border: none; +} + +#dashboard-widgets-wrap #dashboard-widgets .postbox form .submit input { + margin: 0; +} + +#dashboard-widgets-wrap #dashboard-widgets .postbox form .submit #publish { + min-width: 0; +} + +div.postbox div.inside { + margin: 10px; + position: relative; +} + +#dashboard-widgets a { + text-decoration: none; +} + +#dashboard-widgets h3 a { + text-decoration: underline; +} + +#dashboard-widgets h3 .postbox-title-action { + position: absolute; + right: 30px; + padding: 0; +} + +#dashboard-widgets h4 { + font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + font-size: 13px; + margin: 0 0 .2em; + padding: 0; +} + +/* Right Now */ + +#dashboard_right_now p.sub, +#dashboard_right_now .table, #dashboard_right_now .versions { + margin: -12px; +} + +#dashboard_right_now .inside { + font-size: 12px; +} + +#dashboard_right_now p.sub { + font-style: italic; + font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + padding: 5px 10px 15px; + color: #777; + font-size: 13px; +} + +#dashboard_right_now .table { + background: #f9f9f9; + border-top: #ececec 1px solid; + border-bottom: #ececec 1px solid; + margin: 0 -9px 10px; + padding: 0 10px; +} + +#dashboard_right_now table { + width: 100%; +} + +#dashboard_right_now table td { + border-top: #ececec 1px solid; + padding: 3px 0; + white-space: nowrap; +} + +#dashboard_right_now table tr.first td { + border-top: none; +} + +#dashboard_right_now td.b { + padding-right: 6px; + text-align: right; + font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + font-size: 14px; +} + +#dashboard_right_now td.b a { + font-size: 18px; +} + +#dashboard_right_now td.b a:hover { + color: #d54e21; +} + +#dashboard_right_now .t { + font-size: 12px; + padding-right: 12px; + padding-top: 6px; + color: #777; +} + +#dashboard_right_now td.first, +#dashboard_right_now td.last { + width: 1px; +} + +#dashboard_right_now .spam { + color: red; +} + +#dashboard_right_now .waiting { + color: #e66f00; +} + +#dashboard_right_now .approved { + color: green; +} + +#dashboard_right_now .versions { + padding: 6px 10px 12px; +} + +#dashboard_right_now .versions .b { + font-weight: bold; +} + +#dashboard_right_now a.button { + float: right; + clear: right; + position: relative; + top: -5px; +} + +/* Recent Comments */ + +#dashboard_recent_comments h3 { + margin-bottom: 0; +} + +#dashboard_recent_comments .inside { + margin-top: 0; +} + +#dashboard_recent_comments .comment-meta .approve { + font-style: italic; + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + font-size: 10px; +} + +#the-comment-list { + position: relative; +} + +#the-comment-list .comment-item { + padding: 1em 10px; + border-top: 1px solid; +} + +#the-comment-list .pingback { + padding-left: 9px !important; +} + +#the-comment-list .comment-item, +#the-comment-list #replyrow { + margin: 0 -10px; +} + +#the-comment-list .comment-item:first-child { + border-top: none; +} + +#the-comment-list .comment-item .avatar { + float: left; + margin: 0 10px 5px 0; +} + +#the-comment-list .comment-item h4 { + line-height: 1.4; + margin-top: -.2em; + font-weight: normal; + color: #999; +} + +#the-comment-list .comment-item h4 cite { + font-style: normal; + font-weight: normal; +} + +#the-comment-list .comment-item blockquote, +#the-comment-list .comment-item blockquote p { + margin: 0; + padding: 0; + display: inline; +} + +#dashboard_recent_comments #the-comment-list .trackback blockquote, +#dashboard_recent_comments #the-comment-list .pingback blockquote { + display: block; +} + +#the-comment-list .comment-item p.row-actions { + margin: 3px 0 0; + padding: 0; + font-size: 10px; +} + +/* QuickPress */ + +#dashboard_quick_press h4 { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + float: left; + width: 5.5em; + clear: both; + font-weight: normal; + text-align: right; + padding-top: 5px; + font-size: 12px; +} + +#dashboard_quick_press h4 label { + margin-right: 10px; +} + +#dashboard_quick_press .input-text-wrap, +#dashboard_quick_press .textarea-wrap { + margin: 0 0 1em 5em; +} + +#dashboard_quick_press #media-buttons { + margin: 0 0 .5em 5em; + padding: 0 0 0 10px; + font-size: 11px; +} + +#dashboard_quick_press #media-buttons a { + vertical-align: bottom; +} + +#dashboard-widgets #dashboard_quick_press form p.submit { + margin-left: 4.6em; +} + +#dashboard-widgets #dashboard_quick_press form p.submit input { + float: left; +} + +#dashboard-widgets #dashboard_quick_press form p.submit #save-post { + margin: 0 1em 0 10px; +} + +#dashboard-widgets #dashboard_quick_press form p.submit #publish { + float: right; +} + +/* Recent Drafts */ +#dashboard_recent_drafts ul { + margin: 0; + padding: 0; + list-style: none; +} + +#dashboard_recent_drafts ul li { + margin-bottom: 0.6em; +} + +#dashboard_recent_drafts h4 { + font-weight: normal; +} + +#dashboard_recent_drafts h4 abbr { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + font-size: 11px; + color: #999; + margin-left: 3px; +} + +#dashboard_recent_drafts p { + margin: 0; + padding: 0; +} + +/* Feeds */ + +.rss-widget ul { + margin: 0; + padding: 0; + list-style: none; +} + +a.rsswidget { + font-size: 13px; + font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + line-height: 1.7em; +} + +.rss-widget ul li { + line-height: 1.5em; + margin-bottom: 12px; +} + +.rss-widget span.rss-date { + margin-left: 3px; +} + +.rss-widget cite { + display: block; + text-align: right; + margin: 0 0 1em; + padding: 0; +} + +.rss-widget cite:before { + content: '\2014'; +} + +/* Plugins */ + +#dashboard_plugins h4 { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; +} + +#dashboard_plugins h5 { + font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + font-size: 13px !important; + margin: 0; + display: inline; + line-height: 1.4em; +} + +#dashboard_plugins h5 a { + font-weight: normal; + line-height: 1.7em; +} + +#dashboard_plugins p { + margin: 0 0 1.4em; + line-height: 1.4em; +} + +.dashboard-comment-wrap { + overflow: hidden; + word-wrap: break-word; +} + diff --git a/wp-admin/css/farbtastic-rtl.css b/wp-admin/css/farbtastic-rtl.css new file mode 100644 index 0000000..7a8badb --- /dev/null +++ b/wp-admin/css/farbtastic-rtl.css @@ -0,0 +1,7 @@ +.farbtastic .color, .farbtastic .overlay { + left: 0; + right: 47px; +} +.farbtastic .marker { + margin: -8px -8px 0 0; +} diff --git a/wp-admin/css/farbtastic.css b/wp-admin/css/farbtastic.css new file mode 100644 index 0000000..71ad3c1 --- /dev/null +++ b/wp-admin/css/farbtastic.css @@ -0,0 +1,32 @@ +.farbtastic { + position: relative; +} +.farbtastic * { + position: absolute; + cursor: crosshair; +} +.farbtastic, .farbtastic .wheel { + width: 195px; + height: 195px; +} +.farbtastic .color, .farbtastic .overlay { + top: 47px; + left: 47px; + width: 101px; + height: 101px; +} +.farbtastic .wheel { + background: url(../images/wheel.png) no-repeat; + width: 195px; + height: 195px; +} +.farbtastic .overlay { + background: url(../images/mask.png) no-repeat; +} +.farbtastic .marker { + width: 17px; + height: 17px; + margin: -8px 0 0 -8px; + overflow: hidden; + background: url(../images/marker.png) no-repeat; +} \ No newline at end of file diff --git a/wp-admin/css/global-rtl.css b/wp-admin/css/global-rtl.css new file mode 100644 index 0000000..78b2c40 --- /dev/null +++ b/wp-admin/css/global-rtl.css @@ -0,0 +1,83 @@ +/* 2 column liquid layout */ +#adminmenu { + float: right; + clear: right; + margin-right:-160px; + margin-left: 5px; +} +body.folded #adminmenu { + margin-left: 0; + margin-right: -45px; +} +/* inner 2 column liquid layout */ +.inner-sidebar { + float: left; + clear: left; +} + +.has-right-sidebar #post-body { + clear:right; + float:right; + margin-right:0; + margin-left:-340px; +} + +.has-right-sidebar #post-body-content { + margin-left: 300px; + margin-right:0; +} + +#wpbody { + margin-left:0; + margin-right: 175px; +} +.folded #wpbody { + margin-left: 0; + margin-right: 60px; +} +#wpbody-content { + float: right; +} +/* 2 columns main area */ +#col-right { + float: left; + clear: left; +} +.wrap { + margin: 0 5px 0 15px; +} +/* styles for use by people extending the WordPress interface */ +body, td, textarea, input, select { + font-family: Tahoma, arial; +} +.alignleft { + float: right; +} +.alignright { + float: left; +} +.subsubsub { + float: right; +} +.widefat th { + text-align: right; +} +.widefat th input { + margin: 0 8px 0 0; +} +.wrap h2 { + font-family: arial; + padding: 14px 0 3px 15px; +} +.wrap h2.long-header { + padding-left: 0; +} +.updated, .error { + clear: both; +} + +.screen-reader-text, .screen-reader-text span { + left:auto; + right:-1000em; +} +} \ No newline at end of file diff --git a/wp-admin/css/global.css b/wp-admin/css/global.css new file mode 100644 index 0000000..0ca0832 --- /dev/null +++ b/wp-admin/css/global.css @@ -0,0 +1,487 @@ +/* http://meyerweb.com/eric/tools/css/reset/ */ +/* v1.0 | 20080212 */ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, font, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td { + margin: 0; + padding: 0; + border: 0; + outline: 0; +/* font-size: 100%; + vertical-align: baseline; */ + background: transparent; +} +body { + line-height: 1; +} +ol, ul { + list-style: none; +} +blockquote, q { + quotes: none; +} +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} + +/* remember to define focus styles! */ +/* +:focus { + outline: 0; +} +*/ +/* remember to highlight inserts somehow! */ +ins { + text-decoration: none; +} +del { + text-decoration: line-through; +} + +/* tables still need 'cellspacing="0"' in the markup */ +/* +table { + border-collapse: collapse; + border-spacing: 0; +} +*/ +/* end reset css */ + + +/* 2 column liquid layout */ +#wpwrap { + height: auto; + min-height: 100%; + width: 100%; +} + +#wpcontent { + height: 100%; + padding-bottom: 50px; +} + +#wpbody { + clear: both; + margin-left: 175px; +} + +.folded #wpbody { + margin-left: 60px; +} + +#wpbody-content { + float: left; + width: 100%; +} + +#adminmenu { + float: left; + clear: left; + width: 145px; + margin-top: 15px; + margin-right: 5px; + margin-bottom: 15px; + margin-left: -160px; + position: relative; + padding: 0; + list-style: none; +} + +.folded #adminmenu { + margin-left: -45px; +} + +.folded #adminmenu, +.folded #adminmenu li.menu-top { + width: 28px; +} + +#footer { + clear: both; + position: relative; + width: 100%; +} + +/* inner 2 column liquid layout */ +.inner-sidebar { + float: right; + clear: right; + display: none; + width: 281px; + position: relative; +} + +.inner-sidebar #side-sortables { + width: 280px; + min-height: 300px; +} + +.has-right-sidebar .inner-sidebar { + display: block; +} + +.has-right-sidebar #post-body { + float: left; + clear: left; + width: 100%; + margin-right: -340px; +} + +.has-right-sidebar #post-body-content { + margin-right: 300px; +} + +/* 2 columns main area */ + +#col-container { + overflow: hidden; + padding: 0; + margin: 0; +} + +#col-left { + padding: 0; + margin: 0; + overflow: hidden; + width: 39%; +} + +#col-right { + float: right; + clear: right; + overflow: hidden; + padding: 0; + margin: 0; + width: 59%; +} + +/* utility classes */ +.alignleft { + float: left; +} + +.alignright { + float: right; +} + +.textleft { + text-align: left; +} + +.textright { + text-align: right; +} + +.clear { + clear: both; +} + +/* Hide visually but not from screen readers */ +.screen-reader-text, +.screen-reader-text span { + position: absolute; + left: -1000em; + height: 1px; + width: 1px; + overflow: hidden; +} + +.hidden, +.js .closed .inside, +.js .hide-if-js, +.no-js .hide-if-no-js { + display: none; +} + +/* include margin and padding in the width calculation of input and textarea */ +input[type="text"], +input[type="password"], +textarea { + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + -ms-box-sizing: border-box; /* ie8 only */ + box-sizing: border-box; +} + +input[type="checkbox"], +input[type="radio"] { + vertical-align: middle; +} + +/* styles for use by people extending the WordPress interface */ +html, +body { + height: 100%; +} + +body, +td, +textarea, +input, +select { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + font-size: 13px; +} + +body, +textarea { + line-height: 1.4em; +} + +input, +select { + line-height: 1em; +} + +p { + margin: 1em 0; +} + +blockquote { + margin: 1em; +} + +label { + cursor: pointer; +} + +li, +dd { + margin-bottom: 6px; +} + +p, +li, +dl, +dd, +dt { + line-height: 140%; +} + +textarea, +input, +select { + margin: 1px; + padding: 3px; +} + +h1 { + display: block; + font-size: 2em; + font-weight: bold; + margin: .67em 0; +} + +h2 { + display: block; + font-size: 1.5em; + font-weight: bold; + margin: .83em 0; +} + +h3 { + display: block; + font-size: 1.17em; + font-weight: bold; + margin: 1em 0; +} + +h4 { + display: block; + font-size: 1em; + font-weight: bold; + margin: 1.33em 0; +} + +h5 { + display: block; + font-size: 0.83em; + font-weight: bold; + margin: 1.67em 0; +} + +h6 { + display: block; + font-size: 0.67em; + font-weight: bold; + margin: 2.33em 0; +} + +ul.ul-disc { + list-style: disc outside; +} + +ul.ul-square { + list-style: square outside; +} + +ol.ol-decimal { + list-style: decimal outside; +} + +ul.ul-disc, +ul.ul-square, +ol.ol-decimal { + margin-left: 1.8em; +} + +ul.ul-disc > li, +ul.ul-square > li, +ol.ol-decimal > li { + margin: 0 0 0.5em; +} + +.subsubsub { + list-style: none; + margin: 8px 0 5px; + padding: 0; + white-space: nowrap; + font-size: 11px; + float: left; +} + +.subsubsub a { + line-height: 2; + padding: .2em; + text-decoration: none; +} + +.subsubsub a .count, .subsubsub a.current .count { + color: #999; + font-weight: normal; +} + +.subsubsub a.current { + font-weight: bold; + background: none; + border: none; +} + +.subsubsub li { + display: inline; + margin: 0; + padding: 0; +} + +.widefat { + border-width: 1px; + border-style: solid; + border-spacing: 0; + width: 100%; + clear: both; + margin: 0; + -moz-border-radius: 4px; + -khtml-border-radius: 4px; + -webkit-border-radius: 4px; + border-radius: 4px; +} + +.widefat * { + word-wrap: break-word; +} + +.widefat a { + text-decoration: none; +} + +.widefat td, +.widefat th { + border-bottom-width: 1px; + border-bottom-style: solid; + font-size: 11px; + vertical-align: text-top; +} + +.widefat td { + padding: 3px 7px; + vertical-align: top; +} + +.widefat td p, +.widefat td ol, +.widefat td ul { + font-size: 11px; +} + +.widefat th { + padding: 7px 7px 8px; + text-align: left; + line-height: 1.3em; +} + +.widefat th input { + margin: 0 0 0 8px; + padding: 0; + vertical-align: text-top; +} + +.widefat .check-column { + width: 2.2em; + padding: 0; + +} + +.widefat tbody th.check-column { + padding: 7px 0 22px; +} + +.widefat .num, +.column-comments, +.column-links, +.column-posts, +.column-parent { + text-align: center; +} + +.widefat th#comments { + vertical-align: middle; +} + +.wrap { + margin: 0 15px 0 5px; +} + +.updated, +.error { + border-width: 1px; + border-style: solid; + padding: 0 0.6em; + margin: 5px 15px 2px; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} + +.updated p, +.error p { + margin: 0.5em 0; + line-height: 1; + padding: 2px; +} + +.wrap .updated, +.wrap .error { + margin: 5px 0 15px; +} + +.wrap h2 { + font: italic normal normal 24px/29px Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + margin: 0; + padding: 14px 15px 3px 0; + line-height: 35px; + text-shadow: rgba(255,255,255,1) 0px 1px 0px; +} + +.wrap h2.long-header { + padding-right: 0; +} diff --git a/wp-admin/css/ie-rtl.css b/wp-admin/css/ie-rtl.css new file mode 100644 index 0000000..1a6db48 --- /dev/null +++ b/wp-admin/css/ie-rtl.css @@ -0,0 +1,91 @@ +* html #wpcontent #adminmenu .wp-has-submenu .wp-menu-toggle { + background: url(../images/menu-bits-rtl.gif) no-repeat scroll right -109px; +} + +* html #wpcontent #adminmenu li.wp-has-current-submenu .wp-menu-toggle { + background: url(../images/menu-bits-rtl.gif) no-repeat scroll right -206px; +} +* html #adminmenu { + margin-left:0; + margin-right: -80px; +} +* html div.folded #adminmenu { + margin-left: 0; + margin-right: -22px; +} +#wpcontent #adminmenu .wp-submenu li.wp-submenu-head { + padding: 3px 10px 4px 4px; +} +.inline-edit-row fieldset label span.title { + float: right; +} +.inline-edit-row fieldset label span.input-text-wrap { + margin-right: 0; +} +p.search-box { + float: left; +} +* html #poststuff h2 { + margin-right: 0; +} +#bh { + margin: 7px 10px 0 0; + float: left; +} +#user_info + div#favorite-actions { + right: auto; + left: 15px; +} +#wphead-info { + float: left; +} +/* without this dashboard widgets appear in one column for some screen widths */ +div#dashboard-widgets { + padding-right: 0; + padding-left: 1px; +} +.tagchecklist span a { + margin: 4px -9px 0 0; +} +.widefat th input { + margin: 0 5px 0 0; +} +/* ---------- add by navid */ +#TB_window { + width: 670px; + position: absolute; + top: 50%; + left: 50%; + margin-right: 335px !important; +} +#dashboard_plugins { + direction: ltr; +} +#dashboard_plugins h3.hndle { + direction: rtl; +} +#dashboard_incoming_links ul li, +#dashboard_secondary ul li, +#dashboard_primary ul li, +p.row-actions { + width: 100%; +} +#favorite-inside { + position: absolute; + right:0; +} +#post-status-info { + height: 25px; +} +#screen-meta { + position: static; +} +p.submit { /* quick edit and reply in edit-comments.php */ + height:22px; +} +.inner-sidebar { /* fix edit single comment */ + position: static; +} +form#widgets-filter { /* fix widget page */ + position: static; +} diff --git a/wp-admin/css/ie.css b/wp-admin/css/ie.css new file mode 100644 index 0000000..3ced032 --- /dev/null +++ b/wp-admin/css/ie.css @@ -0,0 +1,401 @@ +/* Fixes for IE bugs */ + +input.button, +input.button-secondary, +input.button-highlighted { + padding: 0; +} + +#minor-publishing-actions input, +#major-publishing-actions input { + min-width: auto; + padding-left: 0; + padding-right: 0; +} + +#wpbody-content .postbox { + border: 1px solid #dfdfdf; +} + +#wpbody-content .postbox h3 { + margin-bottom: -1px; +} + +* html .inner-sidebar #side-sortables, +* html .postbox-container .meta-box-sortables { + height: 300px; +} + +* html #wpbody-content #screen-options-link-wrap { + display: inline-block; + width: 150px; + text-align: center; +} + +* html #wpbody-content #contextual-help-link-wrap { + display: inline-block; + width: 100px; + text-align: center; +} + +* html #adminmenu { + margin-left: -80px; +} + +* html .folded #adminmenu { + margin-left: -22px; +} + +* html #wpcontent #adminmenu li.menu-top { + display: inline; + padding: 0; + margin: 0; +} + +* html #footer { + margin: 0; +} + +.folded #adminmenu li.menu-top { + display: block; + zoom: 100%; +} + +ul#adminmenu { + z-index: 99; +} + +#adminmenu li.menu-top a.menu-top { + min-width: auto; + width: auto; +} + +#wpcontent #adminmenu li.wp-has-current-submenu a.wp-has-submenu { + font-style: normal; +} + +* html #wpcontent #adminmenu .wp-menu-open .wp-menu-toggle { + background: none; +} + +* html #wpcontent #adminmenu .wp-has-submenu .wp-menu-toggle { + background: url(../images/menu-bits.gif) no-repeat scroll left -109px; +} + +* html #wpcontent #adminmenu li.wp-has-current-submenu .wp-menu-toggle { + background: url(../images/menu-bits.gif) no-repeat scroll left -206px; +} + +* html #adminmenu div.wp-menu-image { + height: 29px; +} + +#wpcontent #adminmenu .wp-submenu li { + padding: 0; +} + +#adminmenu, +.wp-submenu, +.wp-submenu li, +.wp-menu-toggle { + zoom: 100%; +} + +.folded #adminmenu li.wp-menu-separator { + width: 28px; +} + +#wpcontent #adminmenu .wp-submenu li.wp-submenu-head { + padding: 3px 4px 4px 10px; + zoom: 100%; +} + +.folded #adminmenu .menu-top { + height: 30px; +} + +.folded #adminmenu .wp-submenu { + margin: -1px 0 0 0; +} + +#template, +#template div, +#editcat, +#addcat, +* html .stuffbox h3 { + zoom: 100%; +} + +.submitbox { + margin-top: 10px; +} + +/* Inline Editor */ +#wpbody-content .quick-edit-row-post .inline-edit-col-left { + width: 39%; +} + +#wpbody-content .inline-edit-row-post .inline-edit-col-center { + width: 19%; +} + +#wpbody-content .quick-edit-row-page .inline-edit-col-left { + width: 49%; +} + +#wpbody-content .bulk-edit-row .inline-edit-col-left { + width: 29%; +} + +.inline-edit-row p.submit { + zoom: 100%; +} + +.inline-edit-row fieldset label span.title { + display: block; + float: left; + width: 5em; +} + +.inline-edit-row fieldset label span.input-text-wrap { + margin-left: 0; + zoom: 100%; +} + +#wpbody-content .inline-edit-row fieldset label span.input-text-wrap input { + line-height: 130%; +} + +#wpbody-content .inline-edit-row .input-text-wrap input { + width: 95%; +} + +#wpbody-content .inline-edit-row .input-text-wrap input.inline-edit-password-input { + width: 8em; +} +/* end Inline Editor */ + +input { + line-height: 1; +} + +* html .row-actions { + visibility: visible; +} + +#dashboard-widgets h3 a { + height: 20px; + line-height: 20px; +} + +#wphead-info { + float: right; +} + +#titlediv #title { + width: 98%; +} + +a.button { + line-height: 1.4em; + margin: 1px; + padding: 4px 6px; +} + +* html div.widget-liquid-left, +* html div.widget-liquid-right { + display: block; + position: relative; +} + +#screen-options-wrap { + overflow: hidden; +} + +#favorite-actions { + z-index: 12; +} + +#favorite-inside, +#favorite-inside a, +.favorite-action { + zoom: 100%; +} + +#the-comment-list .comment-item, +#post-status-info, +#wpwrap, +#wpcontent, +#wrap, +#postdivrich, +#postdiv, +#poststuff, +.metabox-holder, +#titlediv, +#post-body, +#editorcontainer, +.tablenav, +.widget-liquid-left, +.widget-liquid-right, +#widgets-left, +.widgets-sortables, +#dragHelper, +.widget .widget-top, +.widget, +.widget-control-actions, +.tagchecklist, +#col-container, +#col-left, +#col-right, +.fileedit-sub { + display: block; + zoom: 100%; +} + +p.search-box { + position: static; + float: right; + margin: -3px 0 4px; +} + +* html #editorcontainer { + padding: 0; +} + +#editorcontainer #content { + overflow: auto; + margin: auto; + width: 98%; +} + +form#template div { + width: 100%; +} + +#ed_toolbar input, +#ed_reply_toolbar input { + overflow: visible; + padding: 0 4px; +} + +#poststuff h2 { + font-size: 1.6em; +} + +* html #poststuff h2 { + margin-left: 0; +} + +#bh { + margin: 7px 10px 0 0; + float: right; +} + +/* without this dashboard widgets appear in one column for some screen widths */ +div#dashboard-widgets { + padding-right: 1px; +} + +.tagchecklist span, .tagchecklist span a { + display: inline-block; + display: block; +} + +.tagchecklist span a { + margin: 4px 0 0 -9px; +} + +.tablenav .button-secondary, .nav .button-secondary { + padding: 0 1px; + vertical-align: middle; +} + +.tablenav select { + font-size: 13px; + display: inline-block; + vertical-align: top; + margin-top: 2px; +} + +table.ie-fixed { + table-layout: fixed; +} + +.widefat tr, .widefat th { + margin-bottom: 0; + border-spacing: 0; +} + +.widefat th input { + margin: 0 0 0 5px; +} + +.widefat .check-column { + padding: 6px 0 2px; +} + +.widefat tbody th.check-column { + padding: 4px 0 22px; +} + +.widefat { + empty-cells: show; + border-collapse: collapse; +} + +.tablenav a.button-secondary { + display: inline-block; + padding: 2px 5px; +} + +* html .stuffbox, +* html .stuffbox input, +* html .stuffbox textarea { + border: 1px solid #DFDFDF; +} + +* html .feature-filter .feature-group li { + width: 145px; +} + +* html .widget-top .widget-title-action a { + background: url("../images/menu-bits.gif") no-repeat scroll 0 -110px; +} + +* html div.widget-liquid-left { + width: 99%; +} + +#wp_inactive_widgets { + padding-bottom: 8px; +} + +* html .widgets-sortables { + height: 50px; +} + +* html a#content_resize { + right: -2px; +} + +* html .widget-title h4 { + width: 205px; +} + +* html #removing-widget .in-widget-title { + display: none; +} + +#available-widgets .widget-holder { + padding-bottom: 65px; +} + +#widgets-left .inactive { + padding-bottom: 10px; +} + +.widget-liquid-right .widget, +#wp_inactive_widgets .widget { + position: relative; +} + diff --git a/wp-admin/css/install-rtl.css b/wp-admin/css/install-rtl.css new file mode 100644 index 0000000..f44484f --- /dev/null +++ b/wp-admin/css/install-rtl.css @@ -0,0 +1,16 @@ +body { + font-family: Tahoma, arial; +} +h1 { + font-family: arial; + margin: 5px -4px 0 0; +} +ul, ol { padding: 5px 22px 5px 5px; } +.step, th { text-align: right; } +.submit input, .button, .button-secondary { + font-family: Tahoma, arial; + margin-right:0; +} +.form-table th { + text-align: right; +} diff --git a/wp-admin/css/install.css b/wp-admin/css/install.css new file mode 100644 index 0000000..6be5ba7 --- /dev/null +++ b/wp-admin/css/install.css @@ -0,0 +1,133 @@ +html { background: #f7f7f7; } + +body { + background: #fff; + color: #333; + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + margin: 2em auto 0 auto; + width: 700px; + padding: 1em 2em; + -moz-border-radius: 11px; + -khtml-border-radius: 11px; + -webkit-border-radius: 11px; + border-radius: 11px; + border: 1px solid #dfdfdf; +} + +a { color: #2583ad; text-decoration: none; } + +a:hover { color: #d54e21; } + +h1 { + border-bottom: 1px solid #dadada; + clear: both; + color: #666; + font: 24px Georgia, "Times New Roman", Times, serif; + margin: 5px 0 0 -4px; + padding: 0; + padding-bottom: 7px; +} + +h2 { font-size: 16px; } + +p, li { + padding-bottom: 2px; + font-size: 12px; + line-height: 18px; +} + +code { font-size: 13px; } + +ul, ol { padding: 5px 5px 5px 22px; } + +#logo { margin: 6px 0 14px 0; border-bottom: none;} + +.step { + margin: 20px 0 15px; +} + +.step, th { text-align: left; padding: 0; } + +.submit input, .button, .button-secondary { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + text-decoration: none; + font-size: 14px !important; + line-height: 16px; + padding: 6px 12px; + cursor: pointer; + border: 1px solid #bbb; + color: #464646; + -moz-border-radius: 15px; + -khtml-border-radius: 15px; + -webkit-border-radius: 15px; + border-radius: 15px; + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + -khtml-box-sizing: content-box; + box-sizing: content-box; +} + +.button:hover, .button-secondary:hover, .submit input:hover { + color: #000; + border-color: #666; +} + +.button, .submit input, .button-secondary { + background: #f2f2f2 url(../images/white-grad.png) repeat-x scroll left top; +} + +.button:active, .submit input:active, .button-secondary:active { + background: #eee url(../images/white-grad-active.png) repeat-x scroll left top; +} + +.form-table { + border-collapse: collapse; + margin-top: 1em; + width: 100%; +} + +.form-table td { + margin-bottom: 9px; + padding: 10px; + border-bottom: 8px solid #fff; + font-size: 12px; +} + +.form-table th { + font-size: 13px; + text-align: left; + padding: 16px 10px 10px 10px; + border-bottom: 8px solid #fff; + width: 110px; + vertical-align: top; +} + +.form-table tr { + background: #f3f3f3; +} + +.form-table code { + line-height: 18px; + font-size: 18px; +} + +.form-table p { + margin: 4px 0 0 0; + font-size: 11px; +} + +.form-table input { + line-height: 20px; + font-size: 15px; + padding: 2px; +} + +#error-page { margin-top: 50px; } + +#error-page p { + font-size: 12px; + line-height: 18px; + margin: 25px 0 20px; +} + +#error-page code { font-family: Consolas, Monaco, Courier, monospace; } diff --git a/wp-admin/css/login-rtl.css b/wp-admin/css/login-rtl.css new file mode 100644 index 0000000..4a5c5f0 --- /dev/null +++ b/wp-admin/css/login-rtl.css @@ -0,0 +1,30 @@ +body { + font-family: Tahoma, arial; +} +form { + margin-right: 8px; + margin-left: 0; +} +form .forgetmenot { + float: right; +} +#login form .submit input { + font-family: Tahoma, arial; +} +form .submit { float: left; } +#backtoblog a { + left: auto; + right: 15px; +} +#login_error, .message { + margin: 0 8px 16px 0; +} +#nav { margin: 0 8px 0 0; } +#user_pass, #user_login, #user_email { + margin-left: 6px; + margin-right: 0; + direction:ltr; +} +h1 a { + text-decoration: none; +} diff --git a/wp-admin/css/login.css b/wp-admin/css/login.css new file mode 100644 index 0000000..bd89d91 --- /dev/null +++ b/wp-admin/css/login.css @@ -0,0 +1,111 @@ +* { margin: 0; padding: 0; } + +body { + border-top-width: 30px; + border-top-style: solid; + font: 11px "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; +} + +form { + margin-left: 8px; + padding: 16px 16px 40px 16px; + font-weight: normal; + -moz-border-radius: 11px; + -khtml-border-radius: 11px; + -webkit-border-radius: 11px; + border-radius: 5px; + background: #fff; + border: 1px solid #e5e5e5; + -moz-box-shadow: rgba(200,200,200,1) 0 4px 18px; + -webkit-box-shadow: rgba(200,200,200,1) 0 4px 18px; + -khtml-box-shadow: rgba(200,200,200,1) 0 4px 18px; + box-shadow: rgba(200,200,200,1) 0 4px 18px; +} + +form .forgetmenot { font-weight: normal; float: left; margin-bottom: 0; } + +#login form .submit input { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + padding: 3px 10px; + border: none; + font-size: 12px; + border-width: 1px; + border-style: solid; + -moz-border-radius: 11px; + -khtml-border-radius: 11px; + -webkit-border-radius: 11px; + border-radius: 11px; + cursor: pointer; + text-decoration: none; + margin-top: -3px; + text-shadow: rgba(0,0,0,0.3) 0 -1px 0; +} + +#login form p { + margin-bottom: 0; +} + +label { + color: #777; + font-size: 13px; +} + +form .forgetmenot label { + font-size: 11px; + line-height: 19px; +} + +form .submit { float: right; } + +form p { margin-bottom: 24px; } + +h1 a { + background: url(../images/logo-login.gif) no-repeat top center; + width: 326px; + height: 67px; + text-indent: -9999px; + overflow: hidden; + padding-bottom: 15px; + display: block; +} + +#nav { + text-shadow: rgba(255,255,255,1) 0 1px 0; +} + +#backtoblog a { + position: absolute; + top: 7px; + left: 15px; + text-decoration: none; +} + +#login { width: 320px; margin: 7em auto; } + +#login_error, .message { + margin: 0 0 16px 8px; + border-width: 1px; + border-style: solid; + padding: 12px; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} + +#nav { margin: 0 0 0 8px; padding: 16px; } + +#user_pass, #user_login, #user_email { + font-size: 24px; + width: 97%; + padding: 3px; + margin-top: 2px; + margin-right: 6px; + margin-bottom: 16px; + border: 1px solid #e5e5e5; + background: #fbfbfb; +} + +.clear { + clear: both; +} diff --git a/wp-admin/css/media-rtl.css b/wp-admin/css/media-rtl.css new file mode 100644 index 0000000..5aeab26 --- /dev/null +++ b/wp-admin/css/media-rtl.css @@ -0,0 +1,93 @@ +body#media-upload ul#sidemenu { + left: auto; + right: 0; +} +#search-filter { + text-align: left; +} +/* specific to the image upload form */ +.align .field label { + padding: 0 28px 0 0; + margin: 0 0 0 1em; +} +.image-align-none-label, .image-align-left-label, .image-align-center-label, .image-align-right-label { + background-position: center right; +} +tr.image-size div.image-size-item { + float: right; +} +tr.image-size label { + margin: 0 1em 0 0; +} +.filename.original { + float: right; +} +.crunching { + text-align: left; + margin-right: 0; + margin-left: 5px; +} +button.dismiss { + right: auto; + left: 5px; +} +.file-error { + margin: 0 50px 5px 0; +} +.progress { + left: auto; + right: 0; +} +.describe td { + padding: 0 0 0 5px; +} +.bar { + border-right-width: 0; + border-left-width: 3px; + border-right-style: none; + border-left-style: solid; +} +.media-item .pinkynail { + float: right; +} +.describe-toggle-on, +.describe-toggle-off { + float: left; + margin-right: 0; + margin-left: 20px; +} +/* Specific to Uploader */ +#media-upload .media-upload-form p { + margin: 0 0 1em 1em; +} +.filename { + float: right; + margin-left: 0; + margin-right: 10px; +} +#media-upload .describe th.label { + text-align: right; +} +.menu_order { + float: left; +} +.media-upload-form label.form-help, td.help, #media-upload p.help, #media-upload label.help { + font-family: Tahoma, Arial; +} +#gallery-settings #basic th.label { + padding: 5px 0 5px 5px; +} +#gallery-settings .title, h3.media-title { + font-family: Tahoma, Arial; +} +#gallery-settings .describe th.label { + text-align: right; +} +#gallery-settings label, +#gallery-settings legend { + margin-right: 0; + margin-left: 15px; +} +#gallery-settings .align .field label { + margin: 0 0 0 1.5em; +} diff --git a/wp-admin/css/media.css b/wp-admin/css/media.css new file mode 100644 index 0000000..f3ccaf0 --- /dev/null +++ b/wp-admin/css/media.css @@ -0,0 +1,400 @@ +div#media-upload-header { + margin: 0; + padding: 0 5px; + font-weight: bold; + position: relative; + border-bottom-width: 1px; + border-bottom-style: solid; + height: 2.5em; +} + +body#media-upload ul#sidemenu { + font-weight: normal; + margin: 0 5px; + position: absolute; + left: 0px; + bottom: -1px; +} + +div#media-upload-error { + margin: 1em; + font-weight: bold; +} + +form { + margin: 1em; +} + +#search-filter { + text-align: right; +} + +.media-upload-form label, +.media-upload-form legend { + display: block; + font-weight: bold; + font-size: 13px; + margin-bottom: 0.5em; + margin: 0 0 0.5em 0; +} + +th { + position: relative; +} + +.media-upload-form label.form-help, td.help { + font-family: "Lucida Grande", "Bitstream Vera Sans", Verdana, Arial, sans-serif; + font-style: italic; + font-weight: normal; +} + +.media-upload-form p.help { + margin: 0; + padding: 0; +} + +.media-upload-form fieldset { + width: 100%; + border: none; + text-align: justify; + margin: 0 0 1em 0; + padding: 0; +} + +/* specific to the image upload form */ +.align .field label { + display: inline; + padding: 0 0 0 28px; + margin: 0 1em 0 0; +} + +.image-align-none-label { + background: url(../images/align-none.png) no-repeat center left; +} + +.image-align-left-label { + background: url(../images/align-left.png) no-repeat center left; +} + +.image-align-center-label { + background: url(../images/align-center.png) no-repeat center left; +} + +.image-align-right-label { + background: url(../images/align-right.png) no-repeat center left; +} + +tr.image-size td { + width: 460px; +} + +tr.image-size div.image-size-item { + float: left; + width: 25%; + margin: 0; +} + +tr.image-size label { + display: inline; + margin: 0 0 0 1em; +} + +.pinkynail { + max-width: 40px; + max-height: 40px; +} + +#library-form .progress, +#gallery-form .progress, +#flash-upload-ui, +.insert-gallery, +.describe.startopen, +.describe.startclosed { + display: none; +} + +.media-item .thumbnail { + max-width: 128px; + max-height: 128px; +} + +.media-item .pinkynail { + float: left; + margin: 2px; + height: 32px; + max-width: 40px; +} + +thead.media-item-info tr { + background-color: transparent; +} + +thead.media-item-info th, +thead.media-item-info td { + border: none; + margin: 0; +} + +.form-table thead.media-item-info { + border: 8px solid #fff; +} + +abbr.required { + text-decoration: none; + border: none; +} + +.describe label { + display: inline; +} + +.describe td { + vertical-align: middle; + padding: 0 5px 0 0; +} + +.describe td.A1 { + width: 132px; +} + +.describe input[type="text"], +.describe textarea { + width: 460px; + border-width: 1px; + border-style: solid; +} + +.describe-toggle-on, +.describe-toggle-off { + display: block; + line-height: 36px; + float: right; + margin-right: 20px; +} + +.describe-toggle-off { + display: none; +} + +.hidden { + height: 0; + width: 0; + overflow: hidden; + border: none; +} + +/* Specific to Uploader */ + +#media-upload .media-upload-form p { + margin: 0 1em 1em 0; +} + +#media-upload p.ml-submit { + padding: 1em 0; +} + +#media-upload p.help, +#media-upload label.help { + font-family: "Lucida Grande", "Bitstream Vera Sans", Verdana, Arial, sans-serif; + font-style: italic; + font-weight: normal; +} + +#media-upload tr.image-size td.field { + text-align: center; +} + +#media-upload #media-items { + border-width: 1px; + border-style: solid; + border-bottom: none; + width: 623px; +} + +#media-upload .media-item { + border-bottom-width: 1px; + border-bottom-style: solid; + min-height: 36px; + width: 100%; +} + +#media-upload .ui-sortable .media-item { + cursor: move; +} + +.filename { + line-height: 36px; + padding: 0 10px; + overflow: hidden; +} + +#media-upload .describe { + padding: 5px; + width: 100%; + clear: both; + cursor: default; +} + +#media-upload .slidetoggle { + border-top-width: 1px; + border-top-style: solid; +} + +#media-upload .describe th.label { + padding-top: .5em; + text-align: left; + min-width: 120px; +} + +#media-upload tr.align td.field { + text-align: center; +} + +#media-upload tr.image-size { + margin-bottom: 1em; + height: 3em; +} + +#media-upload #filter { + width: 623px; +} + +#media-upload #filter .subsubsub { + margin: 8px 0; +} + +#filter .tablenav select { + border-style: solid; + border-width: 1px; + padding: 2px; + vertical-align: top; + width: auto; +} + +#media-upload .del-attachment { + display: none; + margin: 5px 0; +} + +.menu_order { + float: right; + font-size: 11px; + margin: 10px 10px 0; +} + +.menu_order_input { + border: 1px solid #ddd; + font-size: 10px; + padding: 1px; + width: 23px; +} + +.ui-sortable-helper { + background-color: #fff; + border: 1px solid #aaa; + opacity: 0.6; + filter: alpha(opacity=60); +} + +#media-upload th.order-head { + width: 25%; + text-align: center; +} + +#media-upload .widefat { + width: 626px; + border-style: solid solid none; +} + +.sorthelper { + height: 37px; + width: 623px; + display: block; +} + +#gallery-settings th.label { + width: 160px; +} + +#gallery-settings #basic th.label { + padding: 5px 5px 5px 0; +} + +#gallery-settings .title { + clear: both; + padding: 0 0 3px; + border-bottom-style: solid; + border-bottom-width: 1px; + font-family: Georgia,"Times New Roman",Times,serif; + font-size: 1.6em; + border-bottom-color: #DADADA; + color: #5A5A5A; +} + +h3.media-title { + color: #5A5A5A; + font-family: Georgia,"Times New Roman",Times,serif; + font-size: 1.6em; + font-weight: normal; +} + +#gallery-settings .describe td { + vertical-align: middle; + height: 3.5em; +} + +#gallery-settings .describe th.label { + padding-top: .5em; + text-align: left; +} + +#gallery-settings .describe { + padding: 5px; + width: 615px; + clear: both; + cursor: default; +} + +#gallery-settings .describe select { + width: 15em; + border: 1px solid #dfdfdf; +} + +#gallery-settings label, +#gallery-settings legend { + font-size: 13px; + color: #464646; + margin-right: 15px; +} + +#gallery-settings .align .field label { + margin: 0 1.5em 0 0; +} + +#gallery-settings p.ml-submit { + border-top: 1px solid #dfdfdf; +} + +#gallery-settings select#columns { + width: 6em; +} + +#sort-buttons { + font-size: 0.8em; + margin: 3px 25px -8px 0; + text-align: right; + max-width: 625px; +} + +#sort-buttons a { + text-decoration: none; +} + +#sort-buttons #asc, +#sort-buttons #showall { + padding-left: 5px; +} + +#sort-buttons span { + margin-right: 25px; +} diff --git a/wp-admin/css/plugin-install-rtl.css b/wp-admin/css/plugin-install-rtl.css new file mode 100644 index 0000000..9a6dd11 --- /dev/null +++ b/wp-admin/css/plugin-install-rtl.css @@ -0,0 +1,43 @@ +div.star { + left: auto; + right: 0; + letter-spacing: 0; +} +.star img, div.star a, div.star a:hover, div.star a:visited { + right: auto; + left: 0; +} +#plugin-information ul#sidemenu { + left: auto; + right: 0; +} +#plugin-information h2 { + margin-right: 0; + margin-left: 200px; +} +#plugin-information .fyi { + margin-left: 5px; + margin-right: 20px; +} +#plugin-information .fyi h2 { + margin-left: 0; +} +#plugin-information .fyi ul { + padding: 10px 7px 10px 5px; +} +#plugin-information #section-screenshots li p { + padding-left: 0; + padding-right: 20px; +} +#plugin-information .updated, +#plugin-information pre { + margin-right: 0; + margin-left: 215px; +} +#plugin-information .updated, #plugin-information .error { + clear: none; + direction: rtl; +} +#section-description { + direction: ltr; +} diff --git a/wp-admin/css/plugin-install.css b/wp-admin/css/plugin-install.css new file mode 100644 index 0000000..87fc417 --- /dev/null +++ b/wp-admin/css/plugin-install.css @@ -0,0 +1,148 @@ +/* NOTE: the following CSS rules(.star*) are taken more or less straight from the bbPress rating plugin. */ +div.star-holder { + position: relative; + height: 19px; + width: 100px; + font-size: 19px; +} + +div.star { + height: 100%; + position: absolute; + top: 0; + left: 0; + background-color: transparent; + letter-spacing: 1ex; + border: none; +} + +.star1 { width: 20%; } +.star2 { width: 40%; } +.star3 { width: 60%; } +.star4 { width: 80%; } +.star5 { width: 100%; } + +.star img, div.star a, div.star a:hover, div.star a:visited { + display: block; + position: absolute; + right: 0; + border: none; + text-decoration: none; +} + +div.star img { + width: 19px; + height: 19px; + border-left: 1px solid #fff; + border-right: 1px solid #fff; +} + +/* Start custom CSS */ +/* Header on thickbox */ +#plugin-information-header { + margin: 0; + padding: 0 5px; + font-weight: bold; + position: relative; + border-bottom-width: 1px; + border-bottom-style: solid; + height: 2.5em; +} +#plugin-information ul#sidemenu { + font-weight: normal; + margin: 0 5px; + position: absolute; + left: 0; + bottom: -1px; +} + +/* Install sidemenu */ +#plugin-information p.action-button { + width: 100%; + padding-bottom: 0; + margin-bottom: 0; + margin-top: 10px; + -moz-border-radius: 3px 0 0 3px; + -webkit-border-top-left-radius: 3px; + -khtml-border-top-left-radius: 3px; + border-top-left-radius: 3px; + -webkit-border-bottom-left-radius: 3px; + -khtml-border-bottom-left-radius: 3px; + border-bottom-left-radius: 3px; +} + +#plugin-information .action-button a { + text-align: center; + font-weight: bold; + text-decoration: none; + display: block; + line-height: 2em; +} + +#plugin-information h2 { + clear: none !important; + margin-right: 200px; +} + +#plugin-information .fyi { + margin: 0 10px 50px; + width: 210px; +} + +#plugin-information .fyi h2 { + font-size: 0.9em; + margin-bottom: 0; + margin-right: 0; +} + +#plugin-information .fyi h2.mainheader { + padding: 5px; + -moz-border-radius-topleft: 3px; + -webkit-border-top-left-radius: 3px; + -khtml-border-top-left-radius: 3px; + border-top-left-radius: 3px; +} + +#plugin-information .fyi ul { + padding: 10px 5px 10px 7px; + margin: 0; + list-style: none; + -moz-border-radius-bottomleft: 3px; + -webkit-border-bottom-left-radius: 3px; + -khtml-border-bottom-left-radius: 3px; + border-bottom-left-radius: 3px; +} + +#plugin-information .fyi li { + margin-right: 0; +} + +#plugin-information #section-holder { + padding: 10px; +} + +#plugin-information .section ul, +#plugin-information .section ol { + margin-left: 16px; + list-style-type: square; + list-style-image: none; +} + +#plugin-information #section-screenshots li img { + vertical-align: text-top; +} + +#plugin-information #section-screenshots li p { + font-style: italic; + padding-left: 20px; + padding-bottom: 2em; +} + +#plugin-information .updated, +#plugin-information pre { + margin-right: 215px; +} + +#plugin-information pre { + padding: 7px; +} diff --git a/wp-admin/css/press-this-rtl.css b/wp-admin/css/press-this-rtl.css new file mode 100644 index 0000000..9f4a37e --- /dev/null +++ b/wp-admin/css/press-this-rtl.css @@ -0,0 +1,128 @@ +body { + font-family: Tahoma, Arial; +} + +#poststuff #edButtonPreview, +#poststuff #edButtonHTML { + margin: 0 0 0 5px; + float: right; +} + +/* Editor/Main Column */ +div#poststuff { + padding-left: 0; + padding-right: 10px; +} + +.posting { + margin-right: 0; + margin-left: 228px; + left: auto; + right: 0; +} + +#side-info-column { + float: left; + right: auto; + left: 0; + margin-right: 0; + margin-left: 10px; +} + +#side-info-column .sleeve { + padding-left: 0; + padding-right: 10px; +} + +h3.tb { + margin-left: 0; + margin-right: 5px; +} + +#actions { + float: left; +} + +#extra_fields #actions { + right: auto; + left: 4px; +} + +#actions li { + float: right; + margin-right: 0; + margin-left: 10px; +} + +#extra_fields .button { + margin-right: 0; + margin-left: 5px; +} + +/* Photo Styles */ +#img_container a { + float: right; +} + +#category-add input, #category-add select { + font-family: Tahoma, Arial; +} + +#categorydiv ul.categorychecklist ul { + margin-left: 0; + margin-right: 18px; +} + +/* Tags */ +#tagsdiv #newtag { + margin-right: 0; + margin-left: 5px; +} + +#tagadd { + margin-left: 0; + margin-right: 3px; +} + +#tagchecklist span { + margin-left: .5em; + margin-right: 10px; + float: right; +} +#tagchecklist span a { + margin: 6px -9px 0 0; + float: right; +} + +#content { + margin-left: 0; + margin-right: 1%; +} + +.submit input, +.button, +.button-primary, +.button-secondary, +.button-highlighted, +#postcustomstuff .submit input { + font-family: Tahoma, Arial, sans-serif; +} + +.ac_results li { + text-align: right; +} + +#TB_ajaxContent #options { + right: auto; + left: 25px; +} + +#post_status { + margin-left: 0; + margin-right: 10px; +} + +/* Footer */ +#footer { + padding: 10px 60px 0 0; +} diff --git a/wp-admin/css/press-this.css b/wp-admin/css/press-this.css new file mode 100644 index 0000000..2b45356 --- /dev/null +++ b/wp-admin/css/press-this.css @@ -0,0 +1,559 @@ +body { + font: 13px "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + color: #333; + margin: 0; + padding: 0; +} + +img { + border: none; +} + +/* Header */ +#wphead { + border-top: none; + padding-top: 4px; + background: #444 !important; +} + +.tagchecklist span a { +background: transparent url(../images/xit.gif) no-repeat 0 0; +} + +#poststuff #edButtonPreview, +#poststuff #edButtonHTML { + -moz-border-radius: 3px 3px 0 0; + -webkit-border-top-right-radius: 3px; + -webkit-border-top-left-radius: 3px; + -khtml-border-top-right-radius: 3px; + -khtml-border-top-left-radius: 3px; + border-top-right-radius: 3px; + border-top-left-radius: 3px; + border-style: solid; + border-width: 1px; + cursor: pointer; + display: block; + height: 18px; + margin: 0 5px 0 0; + padding: 0 5px 0; + font-size: 10px; + line-height: 18px; + float: left; +} + +.howto { + margin-top: 2px; + margin-bottom: 3px; + font-size: 11px; + font-style: italic; + display: block; +} + +input.text { + outline-color: -moz-use-text-color; + outline-style: none; + outline-width: medium; + width: 100%; +} + +#message { + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; +} + +/* Editor/Main Column */ +div#poststuff { + padding-left: 10px; + margin-top: 10px; +} + +div.zerosize { + border: 0 none; + height: 0; + margin: 0; + overflow: hidden; + padding: 0; + position: absolute; + width: 0; +} + +#poststuff #edButtonPreview.active, +#poststuff #edButtonHTML.active { + display: none; +} + +.posting { + margin-right: 228px; + position: relative; + left: 0; +} + +#side-info-column { + float: right; + width: 218px; + position: absolute; + right: 0; + margin-right: 10px; +} + +#side-info-column .sleeve { + padding-top: 5px; + padding-left: 10px; +} + +#poststuff .inside { + font-size: 11px; + margin: 0 12px 12px; +} + +#poststuff h2, #poststuff h3 { + font-size: 12px; + font-weight: bold; + line-height: 1; + margin: 0 0 10px; + padding: 7px 9px; +} + +h3.tb { + text-shadow: 0 1px 0 #fff; + font-weight: bold; + font-size: 12px; + margin-left: 5px; +} + +#TB_window { + border: 1px solid #333; + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; +} + +.postbox, +.stuffbox { + margin-bottom: 10px; + border-width: 1px; + border-style: solid; + line-height: 1; + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; +} + +#title, +.tbtitle { + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + border-style: solid; + border-width: 1px; + font-size: 1.7em; + outline: none; + padding: 3px 4px; + border-color: #dfdfdf; +} + +.tbtitle { + font-size: 12px; + padding: 3px; +} + +#title { + width: 98%; +} + +.editor-container { + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + border: 1px solid #dfdfdf; + background-color: #fff; +} + +.postdivrich { + position: relative; + padding-top: 25px; +} + +#actions { + clear: both; + float: right; + margin-top: -19px; + position: relative; +} + +#extra_fields #actions { + clear: both; + position: relative; + right: 0px; + margin: -24px 0 0; +} + +#actions li { + float: left; + list-style: none; + margin-right: 10px; +} + +#extra_fields .button { + margin-right: 5px; + padding: 3px 6px; + border-radius: 10px; + -webkit-border-radius: 10px; + -khtml-border-radius: 10px; + -moz-border-radius: 10px; +} + +/* Photo Styles */ +.photolist { + margin-top: -10px; +} + +#photo_saving { + margin: 0 8px 8px; + vertical-align: middle; +} + +#img_container { + background-color: #fff; +} +#img_container_container { + overflow: auto; +} + +#extra_fields { + margin-top: 10px; + position: relative; +} + +#extra_fields .postbox { + margin-bottom: 5px; +} + +#extra_fields .titlewrap { + padding: 0; + overflow: auto; + height: 100px; +} + +#img_container { + position: relative; +} + +#img_container a { + display: block; + float: left; + overflow: hidden; + vertical-align: center; +} + +#img_container img, +#img_container a { + width: 68px; + height: 68px; +} + +#img_container img { + border: none; + background-color: #f4f4f4; + cursor: pointer; +} + +#img_container a, +#img_container a:link, +#img_container a:visited { + border: 1px solid #ccc; + display: block; + position: relative; +} + +#img_container a:hover, +#img_container a:active { + border-color: #000; + z-index: 1000; + border-width: 2px; + margin: -1px; +} + +/* Video */ +#embed-code { + width: 100%; + height: 98px; +} + +/* Submit Column */ +#viewsite { + padding: 0; + margin: 0 0 20px 0; + font-size: 10px; + clear: both; +} + +#viewsite .button { + margin: 0; + display: block; +} + +.wp-hidden-children +.wp-hidden-child { + display: none; +} + +#category-adder { + padding: 4px 0; +} + +#category-adder h4 { + margin: 0 0 8px; +} + +#category-add input { + width: 94%; + font-family: Verdana, Arial, Helvetica, sans-serif; + font-size: 13px; + margin: 1px; + padding: 3px; +} + +#category-add select { + width: 70%; + -x-system-font: none; + border-style: solid; + border-width: 1px; + font-family: "Lucida Grande", "Bitstream Vera Sans", Verdana, Arial, sans-serif; + font-size: 12px; + height: 2em; + line-height: 20px; + padding: 2px; + margin: 1px; + vertical-align: top; +} + +#category-add input, +#category-add-sumbit { + width: auto; +} + +/* Categories */ +#categorydiv ul, +#linkcategorydiv ul { + list-style: none; + padding: 0; + margin: 0; +} + +#categorydiv ul.categorychecklist ul { + margin-left: 18px; +} + +#categorydiv div.tabs-panel { + height: 140px; + overflow: auto; +} + +ul.categorychecklist li { + margin: 0; + padding: 0; + line-height: 19px; +} + +/* Tags */ +.tagsdiv .newtag { + margin-right: 5px; +} + +.jaxtag { + clear: both; + margin: 0; +} + +.tagadd { + margin-left: 3px; +} + +.tagchecklist { + margin-top: 3px; + margin-bottom: 1em; + font-size: 12px; + overflow: auto; +} + +.tagchecklist strong { + position: absolute; + font-size: .75em; +} + +.tagchecklist span { + margin-right: .5em; + margin-left: 10px; + display: block; + float: left; + font-size: 11px; + line-height: 1.8em; + white-space: nowrap; + cursor: default; +} + +.tagchecklist span a { + margin: 6px 0 0 -9px; + cursor: pointer; + width: 10px; + height: 10px; + display: block; + float: left; + text-indent: -9999px; + overflow: hidden; + position: absolute; +} + +#content { + width: 96% !important; + margin-left: 1%; + margin-bottom: 10px; + border: 0 none; + height: 365px; +} + +/* Submit */ + +#saving { + display: inline; + vertical-align: middle; +} + +.submit input, +.button, +.button-primary, +.button-secondary, +.button-highlighted, +#postcustomstuff .submit input { + font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; + text-decoration: none; + font-size: 11px !important; + line-height: 16px; + padding: 2px 8px; + cursor: pointer; + border-width: 1px; + border-style: solid; + -moz-border-radius: 11px; + -khtml-border-radius: 11px; + -webkit-border-radius: 11px; + border-radius: 11px; +} + +.button-primary { + background: #21759B url(../images/button-grad.png) repeat-x scroll left top; + border-color: #21759B; + color: #fff; +} + +.ac_results { + padding: 0; + margin: 0; + list-style: none; + position: absolute; + z-index: 10000; + display: none; + border-width: 1px; + border-style: solid; +} + +.ac_results li { + padding: 2px 5px; + white-space: nowrap; + text-align: left; +} + +.ac_over { + cursor: pointer; +} + +.ac_match { + text-decoration: underline; +} + +#TB_ajaxContent #options { + position: absolute; + top: 20px; + right: 25px; + padding: 5px; +} + +#TB_ajaxContent h3 { + margin-bottom: .25em; +} + +.updated { + margin: 10px 0; + padding: 0; + border-width: 1px; + border-style: solid; + width: 99%; +} + +.updated p, +.error p { + margin: 0.6em 0; + padding: 0 0.6em; +} + +.error a { + text-decoration: underline; +} + +.updated a { + text-decoration: none; + padding-bottom: 2px; +} + +#post_status { + margin-left: 10px; + margin-bottom: 1em; + display: block; +} + +/* Footer */ +#footer { + height: 65px; + display: block; + width: 640px; + padding: 10px 0 0 60px; + margin: 0; + position: absolute; + bottom: 0; + font-size: 12px; +} + +#footer p { + margin: 0; + padding: 7px 0; +} + +#footer p a { + text-decoration: none; +} +#footer p a:hover { + text-decoration: underline; +} + +/* Utility Classes */ +.centered { + text-align: center; +} + +.hidden { + display: none; +} + +.postbox input[type="text"], +.postbox textarea, +.stuffbox input[type="text"], +.stuffbox textarea { + border-width: 1px; + border-style: solid; +} diff --git a/wp-admin/css/theme-editor-rtl.css b/wp-admin/css/theme-editor-rtl.css new file mode 100644 index 0000000..a4dcb46 --- /dev/null +++ b/wp-admin/css/theme-editor-rtl.css @@ -0,0 +1,3 @@ +#templateside { + float: left; +} diff --git a/wp-admin/css/theme-editor.css b/wp-admin/css/theme-editor.css new file mode 100644 index 0000000..0a2a554 --- /dev/null +++ b/wp-admin/css/theme-editor.css @@ -0,0 +1,60 @@ +#template textarea { + font-family: Consolas, Monaco, Courier, monospace; + font-size: 12px; + width: 97%; +} + +#template p { + width: 97%; +} + +#templateside { + float: right; + width: 190px; + word-wrap: break-word; +} + +#templateside h3, +#postcustomstuff p.submit { + margin: 0; +} + +#templateside h4 { + margin: 1em 0 0; +} + +#templateside ol, +#templateside ul { + margin: .5em; + padding: 0; +} + +#templateside li { + margin: 4px 0; +} + +.nonessential { + font-size: small; +} + +.highlight { + padding: 1px; +} + +div.tablenav { + margin-right: 210px; +} + +#documentation { + margin-top: 10px; +} +#documentation label { + line-height: 22px; + vertical-align: top; + font-weight: bold; +} + +.fileedit-sub { + padding: 10px 0 8px; + line-height: 180%; +} diff --git a/wp-admin/css/theme-install.css b/wp-admin/css/theme-install.css new file mode 100644 index 0000000..576dec4 --- /dev/null +++ b/wp-admin/css/theme-install.css @@ -0,0 +1,142 @@ +/* NOTE: the following CSS rules(.star*) are taken more or less straight from the bbPress rating plugin. */ +div.star-holder { + position: relative; + height: 19px; + width: 100px; + font-size: 19px; +} + +div.star { + height: 100%; + position: absolute; + top: 0; + left: 0; + background-color: transparent; + letter-spacing: 1ex; + border: none; +} + +.star1 { width: 20%; } +.star2 { width: 40%; } +.star3 { width: 60%; } +.star4 { width: 80%; } +.star5 { width: 100%; } + +.star img, div.star a, div.star a:hover, div.star a:visited { + display: block; + position: absolute; + right: 0; + border: none; + text-decoration: none; +} + +div.star img { + width: 19px; + height: 19px; + border-left: 1px solid #fff; + border-right: 1px solid #fff; +} + +.theme-listing .theme-item { + display: inline-block; + width: 200px; + border: thin solid #ccc; + vertical-align: top; +} + +.theme-listing .theme-item h3 { + text-align: center; + font-size: 14px; + font-style: italic; + margin: 0; + padding: 0; +} + +.theme-listing .theme-item img { + max-width: 150px; + max-height: 150px; +} + +.theme-listing .theme-item-info span { + display: none; +} +.theme-listing .theme-item:hover .theme-item-info span { + display: inline; +} +.theme-listing .theme-item:hover .theme-item-info span.dots { + display: none; +} +.theme-listing .theme-item-info span.action-links { + font-weight: bold; + text-align: center; +} + +.theme-listing br.line { + border-bottom-width: 1px; + border-bottom-style: solid; + margin-bottom: 3px; +} + +.available-theme { + padding: 20px 15px; +} + +#theme-information .theme-preview-img { + float: left; + margin: 5px 25px 10px 15px; + width: 300px; +} + +#theme-information .action-button { + border-top-width: 1px; + border-top-style: solid; + margin: 10px 5px 20px; +} + +#theme-information .action-button #cancel { + float: left; + margin: 10px 15px; +} + +#theme-information .action-button #install { + float: right; + margin: 10px 15px; +} + +#theme-information .available-theme h3 { + margin: 1em 0; +} + +body#theme-information { + height: auto; +} + +.feature-filter { + -moz-border-radius: 8px; + -khtml-border-radius: 8px; + -webkit-border-radius: 8px; + border-radius: 8px; + border-width: 1px; + border-style: solid; + padding: 8px 12px 0; +} + +.feature-filter .feature-group { + float: left; + margin-bottom: 20px; + width: 695px; +} + +.feature-filter .feature-name { + float: left; + text-align: right; + width: 95px; +} + +.feature-filter .feature-group li { + display: inline; + float: left; + list-style-type: none; + padding-right: 25px; + min-width: 145px; +} diff --git a/wp-admin/css/widgets-rtl.css b/wp-admin/css/widgets-rtl.css new file mode 100644 index 0000000..b349972 --- /dev/null +++ b/wp-admin/css/widgets-rtl.css @@ -0,0 +1,11 @@ + +ul#widget-list li.widget-list-item div.widget-description { + margin: 0 200px 0 0; + padding: 0 4em 0 0; +} +.widget-control-save, +.widget-control-remove { + margin-right: 0; + margin-left: 8px; + float: right; +} diff --git a/wp-admin/css/widgets.css b/wp-admin/css/widgets.css new file mode 100644 index 0000000..c896f5b --- /dev/null +++ b/wp-admin/css/widgets.css @@ -0,0 +1,365 @@ +html, +body { + min-width: 950px; +} + +/* 2 column liquid layout */ +div.widget-liquid-left { + float: left; + clear: left; + width: 100%; + margin-right: -325px; +} + +div#widgets-left { + margin-left: 5px; + margin-right: 325px; +} + +div#widgets-right { + width: 285px; + margin: 0 auto; +} + +div.widget-liquid-right { + float: right; + clear: right; + width: 300px; +} + +.widget-liquid-right .widget, +#wp_inactive_widgets .widget { + width: 250px; + margin: 0 auto 20px; + overflow: hidden; +} + +#wp_inactive_widgets .widget { + margin: 0 10px 20px; + float: left; +} + +div.sidebar-name h3 { + margin: 0; + padding: 5px 12px; + font-size: 13px; + height: 19px; + overflow: hidden; + white-space: nowrap; +} + +div.sidebar-name { + background-repeat: repeat-x; + background-position: 0 0; + cursor: pointer; + font-size: 13px; + border-width: 1px; + border-style: solid; + -moz-border-radius-topleft: 8px; + -moz-border-radius-topright: 8px; + -webkit-border-top-right-radius: 8px; + -webkit-border-top-left-radius: 8px; + -khtml-border-top-right-radius: 8px; + -khtml-border-top-left-radius: 8px; + border-top-right-radius: 8px; + border-top-left-radius: 8px; +} + +.js .closed .sidebar-name { + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; + -webkit-border-bottom-right-radius: 8px; + -webkit-border-bottom-left-radius: 8px; + -khtml-border-bottom-right-radius: 8px; + -khtml-border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; + border-bottom-left-radius: 8px; +} + +.widget-liquid-right .widgets-sortables, +#widgets-left .widget-holder { + border-width: 0 1px 1px; + border-style: none solid solid; + -moz-border-radius-bottomleft: 8px; + -moz-border-radius-bottomright: 8px; + -webkit-border-bottom-right-radius: 8px; + -webkit-border-bottom-left-radius: 8px; + -khtml-border-bottom-right-radius: 8px; + -khtml-border-bottom-left-radius: 8px; + border-bottom-right-radius: 8px; + border-bottom-left-radius: 8px; +} + +.js .closed .widgets-sortables, +.js .closed .widget-holder { + display: none; +} + +.widget-liquid-right .widgets-sortables { + padding: 15px 0 0; +} + +#available-widgets .widget-holder { + padding: 7px 5px 0; +} + +#wp_inactive_widgets { + padding: 5px 5px 0; +} + +#widget-list .widget { + width: 250px; + margin: 0 10px 15px; + border: 0 none; + float: left; +} + +#widget-list .widget-description { + padding: 5px 8px; +} + +#widget-list .widget-top { + border-width: 1px; + border-style: solid; + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; +} + +.widget-placeholder { + border-width: 1px; + border-style: dashed; + margin: 0 auto 20px; + height: 26px; + width: 250px; +} + +#wp_inactive_widgets .widget-placeholder { + margin: 0 10px 20px; + float: left; +} + +div.widgets-holder-wrap { + padding: 0; + margin: 10px 0 20px; +} + +#widgets-left #available-widgets { + background-color: transparent; + border: 0 none; +} + +ul#widget-list { + list-style: none; + margin: 0; + padding: 0; + min-height: 100px; +} + +.widget .widget-top { + font-size: 12px; + font-weight: bold; + height: 26px; + overflow: hidden; +} + +.widget-top .widget-title { + padding: 5px 9px; +} + +.widget-top .widget-title-action { + float: right; +} + +a.widget-action { + display: block; + width: 24px; + height: 26px; +} + +#available-widgets a.widget-action { + display: none; +} + +.widget-top a.widget-action { + background: url("../images/menu-bits.gif") no-repeat scroll 0 -110px; +} + +.widget .widget-inside, +.widget .widget-description { + padding: 12px 12px 10px; + font-size: 11px; + line-height: 16px; +} + +.widget-inside, +.widget-description { + display: none; +} + +#available-widgets .widget-description { + display: block; +} + +.widget .widget-inside p { + margin: 0 0 1em; + padding: 0; +} + +.widget-title h4 { + margin: 0; + line-height: 1.3; + overflow: hidden; + white-space: nowrap; +} + +.widgets-sortables { + min-height: 90px; +} + +.widget-control-actions { + margin-top: 8px; +} + +.widget-control-actions a { + text-decoration: none; +} + +.widget-control-actions a:hover { + text-decoration: underline; +} + +.widget-control-actions .ajax-feedback { + padding-bottom: 3px; +} + +.widget-control-actions div.alignleft { + margin-top: 6px; +} + +div#sidebar-info { + padding: 0 1em; + margin-bottom: 1em; + font-size: 11px; +} + +.widget-title a, +.widget-title a:hover { + text-decoration: none; + border-bottom: none; +} + +.widget-control-edit { + display: block; + font-size: 11px; + font-weight: normal; + line-height: 26px; + padding: 0 8px 0 0; +} + +a.widget-control-edit { + text-decoration: none; +} + +.widget-control-edit .add, +.widget-control-edit .edit { + display: none; +} + +#available-widgets .widget-control-edit .add, +#widgets-right .widget-control-edit .edit, +#wp_inactive_widgets .widget-control-edit .edit { + display: inline; +} + +.editwidget { + margin: 0 auto 15px; +} + +.editwidget .widget-inside { + display: block; + border-width: 1px; + border-style: solid; + padding: 10px; + -moz-border-radius: 6px; + -khtml-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; +} + +.inactive p.description { + margin: 5px 15px 8px; +} + +#available-widgets p.description { + margin: 0 12px 12px; +} + +.widget-position { + margin-top: 8px; +} + +.inactive { + padding-top: 2px; +} + +.sidebar-name-arrow { + float: right; + height: 29px; + width: 26px; +} + +.widget-title .in-widget-title { + font-size: 11px; + white-space: nowrap; +} + +#removing-widget { + display: none; + font-weight: normal; + padding-left: 15px; + font-size: 12px; +} + +.widget-control-noform, +#access-off, +.widgets_access .widget-action, +.widgets_access .sidebar-name-arrow, +.widgets_access #access-on, +.widgets_access .widget-holder .description { + display: none; +} + +.widgets_access .widget-holder, +.widgets_access #widget-list { + padding-top: 10px; +} + +.widgets_access #access-off { + display: inline; +} + +.widgets_access #wpbody-content .widget-title-action, +.widgets_access #wpbody-content .widget-control-edit, +.widgets_access .closed .widgets-sortables, +.widgets_access .closed .widget-holder { + display: block; +} + +.widgets_access .closed .sidebar-name { + -moz-border-radius-bottomleft: 0; + -moz-border-radius-bottomright: 0; + -webkit-border-bottom-right-radius: 0; + -webkit-border-bottom-left-radius: 0; + -khtml-border-bottom-right-radius: 0; + -khtml-border-bottom-left-radius: 0; + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; +} + +.widgets_access .sidebar-name, +.widgets_access .widget .widget-top { + cursor: default; +} + diff --git a/wp-admin/custom-header.php b/wp-admin/custom-header.php new file mode 100644 index 0000000..fb07fe8 --- /dev/null +++ b/wp-admin/custom-header.php @@ -0,0 +1,478 @@ +admin_header_callback = $admin_header_callback; + } + + /** + * Setup the hooks for the Custom Header admin page. + * + * @since unknown + */ + function init() { + $page = add_theme_page(__('Custom Header'), __('Custom Header'), 'edit_themes', 'custom-header', array(&$this, 'admin_page')); + + add_action("admin_print_scripts-$page", array(&$this, 'js_includes')); + add_action("admin_print_styles-$page", array(&$this, 'css_includes')); + add_action("admin_head-$page", array(&$this, 'take_action'), 50); + add_action("admin_head-$page", array(&$this, 'js'), 50); + add_action("admin_head-$page", $this->admin_header_callback, 51); + } + + /** + * Get the current step. + * + * @since unknown + * + * @return int Current step + */ + function step() { + if ( ! isset( $_GET['step'] ) ) + return 1; + + $step = (int) $_GET['step']; + if ( $step < 1 || 3 < $step ) + $step = 1; + + return $step; + } + + /** + * Setup the enqueue for the JavaScript files. + * + * @since unknown + */ + function js_includes() { + $step = $this->step(); + + if ( 1 == $step ) + wp_enqueue_script('farbtastic'); + elseif ( 2 == $step ) + wp_enqueue_script('jcrop'); + } + + /** + * Setup the enqueue for the CSS files + * + * @since 2.7 + */ + function css_includes() { + $step = $this->step(); + + if ( 1 == $step ) + wp_enqueue_style('farbtastic'); + elseif ( 2 == $step ) + wp_enqueue_style('jcrop'); + } + + /** + * Execute custom header modification. + * + * @since unknown + */ + function take_action() { + if ( isset( $_POST['textcolor'] ) ) { + check_admin_referer('custom-header'); + if ( 'blank' == $_POST['textcolor'] ) { + set_theme_mod('header_textcolor', 'blank'); + } else { + $color = preg_replace('/[^0-9a-fA-F]/', '', $_POST['textcolor']); + if ( strlen($color) == 6 || strlen($color) == 3 ) + set_theme_mod('header_textcolor', $color); + } + } + if ( isset($_POST['resetheader']) ) { + check_admin_referer('custom-header'); + remove_theme_mods(); + } + } + + /** + * Execute Javascript depending on step. + * + * @since unknown + */ + function js() { + $step = $this->step(); + if ( 1 == $step ) + $this->js_1(); + elseif ( 2 == $step ) + $this->js_2(); + } + + /** + * Display Javascript based on Step 1. + * + * @since unknown + */ + function js_1() { ?> + + + + +
+

+
+ + +
+ +

+

+ +
+

+
+
+ +
+ + + +
+ + + +
+
+

+

%1$d x %2$d pixels will be used as-is.'), HEADER_IMAGE_WIDTH, HEADER_IMAGE_HEIGHT); ?>

+ +
+
+ + +

+ +

+
+ +
+ + +
+

+

+
+ + +
+
+ false); + $file = wp_handle_upload($_FILES['import'], $overrides); + + if ( isset($file['error']) ) + die( $file['error'] ); + + $url = $file['url']; + $type = $file['type']; + $file = $file['file']; + $filename = basename($file); + + // Construct the object array + $object = array( + 'post_title' => $filename, + 'post_content' => $url, + 'post_mime_type' => $type, + 'guid' => $url); + + // Save the data + $id = wp_insert_attachment($object, $file); + + list($width, $height, $type, $attr) = getimagesize( $file ); + + if ( $width == HEADER_IMAGE_WIDTH && $height == HEADER_IMAGE_HEIGHT ) { + // Add the meta-data + wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); + + set_theme_mod('header_image', esc_url($url)); + do_action('wp_create_file_in_uploads', $file, $id); // For replication + return $this->finished(); + } elseif ( $width > HEADER_IMAGE_WIDTH ) { + $oitar = $width / HEADER_IMAGE_WIDTH; + $image = wp_crop_image($file, 0, 0, $width, $height, HEADER_IMAGE_WIDTH, $height / $oitar, false, str_replace(basename($file), 'midsize-'.basename($file), $file)); + $image = apply_filters('wp_create_file_in_uploads', $image, $id); // For replication + + $url = str_replace(basename($url), basename($image), $url); + $width = $width / $oitar; + $height = $height / $oitar; + } else { + $oitar = 1; + } + ?> + +
+ +
+ +

+
+ +
+ +

+ + + + + + + + + + +

+ +
+
+ 1 ) { + $_POST['x1'] = $_POST['x1'] * $_POST['oitar']; + $_POST['y1'] = $_POST['y1'] * $_POST['oitar']; + $_POST['width'] = $_POST['width'] * $_POST['oitar']; + $_POST['height'] = $_POST['height'] * $_POST['oitar']; + } + + $original = get_attached_file( $_POST['attachment_id'] ); + + $cropped = wp_crop_image($_POST['attachment_id'], $_POST['x1'], $_POST['y1'], $_POST['width'], $_POST['height'], HEADER_IMAGE_WIDTH, HEADER_IMAGE_HEIGHT); + $cropped = apply_filters('wp_create_file_in_uploads', $cropped, $_POST['attachment_id']); // For replication + + $parent = get_post($_POST['attachment_id']); + $parent_url = $parent->guid; + $url = str_replace(basename($parent_url), basename($cropped), $parent_url); + + // Construct the object array + $object = array( + 'ID' => $_POST['attachment_id'], + 'post_title' => basename($cropped), + 'post_content' => $url, + 'post_mime_type' => 'image/jpeg', + 'guid' => $url + ); + + // Update the attachment + wp_insert_attachment($object, $cropped); + wp_update_attachment_metadata( $_POST['attachment_id'], wp_generate_attachment_metadata( $_POST['attachment_id'], $cropped ) ); + + set_theme_mod('header_image', $url); + + // cleanup + $medium = str_replace(basename($original), 'midsize-'.basename($original), $original); + @unlink( apply_filters( 'wp_delete_file', $medium ) ); + @unlink( apply_filters( 'wp_delete_file', $original ) ); + + return $this->finished(); + } + + /** + * Display last step of custom header image page. + * + * @since unknown + */ + function finished() { + ?> +
+

+ +

+ +
+ step(); + if ( 1 == $step ) + $this->step_1(); + elseif ( 2 == $step ) + $this->step_2(); + elseif ( 3 == $step ) + $this->step_3(); + } + +} +?> diff --git a/wp-admin/edit-attachment-rows.php b/wp-admin/edit-attachment-rows.php new file mode 100644 index 0000000..3842a6c --- /dev/null +++ b/wp-admin/edit-attachment-rows.php @@ -0,0 +1,212 @@ + + + + + + + + + + + + + + + +ID == $post->post_author ? 'self' : 'other' ); +$att_title = _draft_or_post_title(); + +?> + post_status ); ?>' valign="top"> + + $column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch($column_name) { + + case 'cb': + ?> + + + + + + + + + + + + post_date && 'date' == $column_name ) { + $t_time = $h_time = __('Unpublished'); + } else { + $t_time = get_the_time(__('Y/m/d g:i:s A')); + $m_time = $post->post_date; + $time = get_post_time( 'G', true, $post, false ); + if ( ( abs($t_diff = time() - $time) ) < 86400 ) { + if ( $t_diff < 0 ) + $h_time = sprintf( __('%s from now'), human_time_diff( $time ) ); + else + $h_time = sprintf( __('%s ago'), human_time_diff( $time ) ); + } else { + $h_time = mysql2date(__('Y/m/d'), $m_time); + } + } + ?> + + post_parent > 0 ) { + if ( get_post($post->post_parent) ) { + $title =_draft_or_post_title($post->post_parent); + } + ?> + + + + + + + + + + + + + +
>ID, array(80, 60), true ) ) { +?> + + + + + +>
+ ID))); ?> +

+ ID) ) + $actions['edit'] = '' . __('Edit') . ''; + if ( current_user_can('delete_post', $post->ID) ) + $actions['delete'] = "ID) . "' onclick=\"if ( confirm('" . esc_js(sprintf( ('draft' == $post->post_status) ? __("You are about to delete this attachment '%s'\n 'Cancel' to stop, 'OK' to delete.") : __("You are about to delete this attachment '%s'\n 'Cancel' to stop, 'OK' to delete."), $post->post_title )) . "') ) { return true;}return false;\">" . __('Delete') . ""; + $actions['view'] = '' . __('View') . ''; + $action_count = count($actions); + $i = 0; + echo '

'; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + echo "$link$sep"; + } + echo '
'; + ?>

>>slug'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'post_tag', 'display')) . ""; + echo join( ', ', $out ); + } else { + _e('No Tags'); + } + ?>>post_excerpt : ''; ?>>>, >
+ ID ); + $pending_phrase = sprintf( __('%s pending'), number_format( $left ) ); + if ( $left ) + echo ''; + comments_number("" . /* translators: comment count link */ _x('0', 'comment count') . '', "" . /* translators: comment count link */ _x('1', 'comment count') . '', "" . /* translators: comment count link: % will be substituted by comment count */ _x('%', 'comment count') . ''); + if ( $left ) + echo ''; + ?> +
> + | + + >
+ + +

+ + + diff --git a/wp-admin/edit-category-form.php b/wp-admin/edit-category-form.php new file mode 100644 index 0000000..27417f6 --- /dev/null +++ b/wp-admin/edit-category-form.php @@ -0,0 +1,84 @@ +name ) ) + $category->name = ''; + + if ( ! isset( $category->slug ) ) + $category->slug = ''; + + if ( ! isset( $category->parent ) ) + $category->parent = ''; + + if ( ! isset( $category->description ) ) + $category->description = ''; +} + +do_action('edit_category_form_pre', $category); + +_fill_empty_category($category); +?> + +
+ +

+
+
+ + + + + + + + + + + + + + + + + + + + + +

+

+
+ 0, 'name' => 'category_parent', 'orderby' => 'name', 'selected' => $category->parent, 'hierarchical' => true, 'show_option_none' => __('None'))); ?>
+ +

+
+

+ +
+
diff --git a/wp-admin/edit-comments.php b/wp-admin/edit-comments.php new file mode 100644 index 0000000..dd5f867 --- /dev/null +++ b/wp-admin/edit-comments.php @@ -0,0 +1,386 @@ +escape( $_REQUEST['pagegen_timestamp'] ); + if ( current_user_can('moderate_comments')) { + $deleted_spam = $wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_approved = 'spam' AND '$delete_time' > comment_date_gmt" ); + } else { + $deleted_spam = 0; + } + $redirect_to = 'edit-comments.php?comment_status=spam&deleted=' . (int) $deleted_spam; + if ( $post_id ) + $redirect_to = add_query_arg( 'p', absint( $post_id ), $redirect_to ); + wp_redirect( $redirect_to ); +} elseif ( isset($_REQUEST['delete_comments']) && isset($_REQUEST['action']) && ( -1 != $_REQUEST['action'] || -1 != $_REQUEST['action2'] ) ) { + check_admin_referer('bulk-comments'); + $doaction = ( -1 != $_REQUEST['action'] ) ? $_REQUEST['action'] : $_REQUEST['action2']; + + $deleted = $approved = $unapproved = $spammed = 0; + foreach ( (array) $_REQUEST['delete_comments'] as $comment_id) : // Check the permissions on each + $comment_id = (int) $comment_id; + $_post_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT comment_post_ID FROM $wpdb->comments WHERE comment_ID = %d", $comment_id) ); + + if ( !current_user_can('edit_post', $_post_id) ) + continue; + + switch( $doaction ) { + case 'markspam' : + wp_set_comment_status($comment_id, 'spam'); + $spammed++; + break; + case 'delete' : + wp_set_comment_status($comment_id, 'delete'); + $deleted++; + break; + case 'approve' : + wp_set_comment_status($comment_id, 'approve'); + $approved++; + break; + case 'unapprove' : + wp_set_comment_status($comment_id, 'hold'); + $unapproved++; + break; + } + endforeach; + + $redirect_to = 'edit-comments.php?deleted=' . $deleted . '&approved=' . $approved . '&spam=' . $spammed . '&unapproved=' . $unapproved; + if ( $post_id ) + $redirect_to = add_query_arg( 'p', absint( $post_id ), $redirect_to ); + if ( isset($_REQUEST['apage']) ) + $redirect_to = add_query_arg( 'apage', absint($_REQUEST['apage']), $redirect_to ); + if ( !empty($_REQUEST['mode']) ) + $redirect_to = add_query_arg('mode', $_REQUEST['mode'], $redirect_to); + if ( !empty($_REQUEST['comment_status']) ) + $redirect_to = add_query_arg('comment_status', $_REQUEST['comment_status'], $redirect_to); + if ( !empty($_REQUEST['s']) ) + $redirect_to = add_query_arg('s', $_REQUEST['s'], $redirect_to); + wp_redirect( $redirect_to ); +} elseif ( isset($_GET['_wp_http_referer']) && ! empty($_GET['_wp_http_referer']) ) { + wp_redirect( remove_query_arg( array('_wp_http_referer', '_wpnonce'), stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; +} + +if ( $post_id ) + $title = sprintf(__('Edit Comments on “%s”'), wp_html_excerpt(_draft_or_post_title($post_id), 50)); +else + $title = __('Edit Comments'); + +require_once('admin-header.php'); + +$mode = ( ! isset($_GET['mode']) || empty($_GET['mode']) ) ? 'detail' : esc_attr($_GET['mode']); + +$comment_status = isset($_REQUEST['comment_status']) ? $_REQUEST['comment_status'] : 'all'; +if ( !in_array($comment_status, array('all', 'moderated', 'approved', 'spam')) ) + $comment_status = 'all'; + +$comment_type = !empty($_GET['comment_type']) ? esc_attr($_GET['comment_type']) : ''; + +$search_dirty = ( isset($_GET['s']) ) ? $_GET['s'] : ''; +$search = esc_attr( $search_dirty ); ?> + +
+ +

' . sprintf( __( 'Search results for “%s”' ), wp_html_excerpt( esc_html( stripslashes( $_GET['s'] ) ), 50 ) ) . '' ); ?> +

+ + 0 || $deleted > 0 || $spam > 0 ) { + echo '

'; + + if ( $approved > 0 ) { + printf( _n( '%s comment approved', '%s comments approved', $approved ), $approved ); + echo '
'; + } + + if ( $deleted > 0 ) { + printf( _n( '%s comment deleted', '%s comments deleted', $deleted ), $deleted ); + echo '
'; + } + + if ( $spam > 0 ) { + printf( _n( '%s comment marked as spam', '%s comments marked as spam', $spam ), $spam ); + echo '
'; + } + + echo '

'; + } +} +?> + +
+
    +moderated) ), "" . number_format_i18n($num_comments->moderated) . ""), +//, number_format_i18n($num_comments->spam) ), "" . number_format_i18n($num_comments->spam) . "") +$stati = array( + 'all' => _n_noop('All', 'All'), // singular not used + 'moderated' => _n_noop('Pending (%s)', 'Pending (%s)'), + 'approved' => _n_noop('Approved', 'Approved'), // singular not used + 'spam' => _n_noop('Spam (%s)', 'Spam (%s)') + ); +$link = 'edit-comments.php'; +if ( !empty($comment_type) && 'all' != $comment_type ) + $link = add_query_arg( 'comment_type', $comment_type, $link ); +foreach ( $stati as $status => $label ) { + $class = ''; + + if ( $status == $comment_status ) + $class = ' class="current"'; + if ( !isset( $num_comments->$status ) ) + $num_comments->$status = 10; + $link = add_query_arg( 'comment_status', $status, $link ); + if ( $post_id ) + $link = add_query_arg( 'p', absint( $post_id ), $link ); + /* + // I toyed with this, but decided against it. Leaving it in here in case anyone thinks it is a good idea. ~ Mark + if ( !empty( $_GET['s'] ) ) + $link = add_query_arg( 's', esc_attr( stripslashes( $_GET['s'] ) ), $link ); + */ + $status_links[] = "
  • " . sprintf( + _n( $label[0], $label[1], $num_comments->$status ), + number_format_i18n( $num_comments->$status ) + ) . ''; +} + +$status_links = apply_filters( 'comment_status_links', $status_links ); + +echo implode( " |
  • \n", $status_links) . ''; +unset($status_links); +?> +
+ + + +comment_post_ID; +} +$_comment_pending_count_temp = (array) get_pending_comments_num($_comment_post_ids); +foreach ( (array) $_comment_post_ids as $_cpid ) + $_comment_pending_count[$_cpid] = isset( $_comment_pending_count_temp[$_cpid] ) ? $_comment_pending_count_temp[$_cpid] : 0; +if ( empty($_comment_pending_count) ) + $_comment_pending_count = array(); + +$comments = array_slice($_comments, 0, $comments_per_page); +$extra_comments = array_slice($_comments, $comments_per_page); + +$page_links = paginate_links( array( + 'base' => add_query_arg( 'apage', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil($total / $comments_per_page), + 'current' => $page +)); + +?> + + + + + + + + +
+ + +
' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( $start + 1 ), + number_format_i18n( min( $page * $comments_per_page, $total ) ), + '' . number_format_i18n( $total ) . '', + $page_links +); echo $page_links_text; ?>
+ + + + + +
+ + + + + + + + + + + + + +
+ +
+ +
+ +
+ + + + + + + + + + + + + + + + +comment_ID, $mode, $comment_status ); +?> + + +comment_ID, $mode, $comment_status ); +?> + +
+ +
+$page_links_text
"; +?> + +
+ + + + + + + +
+ +
+
+ + + + + +
+ + +

+ + + +

+ + + +
+ + diff --git a/wp-admin/edit-form-advanced.php b/wp-admin/edit-form-advanced.php new file mode 100644 index 0000000..dadf6c0 --- /dev/null +++ b/wp-admin/edit-form-advanced.php @@ -0,0 +1,669 @@ +View post'), get_permalink($post_ID)); +$messages[2] = __('Custom field updated.'); +$messages[3] = __('Custom field deleted.'); +$messages[4] = __('Post updated.'); +$messages[6] = sprintf(__('Post published. View post'), get_permalink($post_ID)); +$messages[7] = __('Post saved.'); +$messages[8] = sprintf(__('Post submitted. Preview post'), add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ); + +if ( isset($_GET['revision']) ) + $messages[5] = sprintf( __('Post restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ); + +$notice = false; +$notices[1] = __( 'There is an autosave of this post that is more recent than the version below. View the autosave.' ); + +if ( 0 == $post_ID ) { + $form_action = 'post'; + $temp_ID = -1 * time(); // don't change this formula without looking at wp_write_post() + $form_extra = ""; + $autosave = false; +} else { + $form_action = 'editpost'; + $form_extra = ""; + $autosave = wp_get_post_autosave( $post_ID ); + + // Detect if there exists an autosave newer than the post and if that autosave is different than the post + if ( $autosave && mysql2date( 'U', $autosave->post_modified_gmt, false ) > mysql2date( 'U', $post->post_modified_gmt, false ) ) { + foreach ( _wp_post_revision_fields() as $autosave_field => $_autosave_field ) { + if ( normalize_whitespace( $autosave->$autosave_field ) != normalize_whitespace( $post->$autosave_field ) ) { + $notice = sprintf( $notices[1], get_edit_post_link( $autosave->ID ) ); + break; + } + } + unset($autosave_field, $_autosave_field); + } +} + +// All meta boxes should be defined and added before the first do_meta_boxes() call (or potentially during the do_meta_boxes action). + +/** + * Display post submit form fields. + * + * @since 2.7.0 + * + * @param object $post + */ +function post_submit_meta_box($post) { + global $action; + + $can_publish = current_user_can('publish_posts'); +?> +
+ +
+ + +
+ +
+ +
+
+post_status && 'future' != $post->post_status && 'pending' != $post->post_status ) { ?> +post_status ) { ?>style="display:none" type="submit" name="save" id="save-post" value="" tabindex="4" class="button button-highlighted" /> +post_status && $can_publish ) { ?> + + +
+ +
+post_status ) { + $preview_link = esc_url(get_permalink($post->ID)); + $preview_button = __('Preview Changes'); +} else { + $preview_link = esc_url(apply_filters('preview_post_link', add_query_arg('preview', 'true', get_permalink($post->ID)))); + $preview_button = __('Preview'); +} +?> + + +
+ +
+
+ +
+ +
+ +post_status ) { + case 'private': + _e('Privately Published'); + break; + case 'publish': + _e('Published'); + break; + case 'future': + _e('Scheduled'); + break; + case 'pending': + _e('Pending Review'); + break; + case 'draft': + _e('Draft'); + break; +} +?> + +post_status || 'private' == $post->post_status || $can_publish ) { ?> +post_status ) { ?>style="display:none;" class="edit-post-status hide-if-no-js" tabindex='4'> + +
+ + + + +
+ + +
+ +
+ post_status ) { + $post->post_password = ''; + $visibility = 'private'; + $visibility_trans = __('Private'); +} elseif ( !empty( $post->post_password ) ) { + $visibility = 'password'; + $visibility_trans = __('Password protected'); +} elseif ( is_sticky( $post->ID ) ) { + $visibility = 'public'; + $visibility_trans = __('Public, Sticky'); +} else { + $visibility = 'public'; + $visibility_trans = __('Public'); +} + +?> + +
+ +ID)); ?> /> + + + + />
+ID)); ?> tabindex="4" />
+ />
+
+ />
+ +

+ + +

+
+ + +
+ + +ID ) { + if ( 'future' == $post->post_status ) { // scheduled for publishing at a future date + $stamp = __('Scheduled for: %1$s'); + } else if ( 'publish' == $post->post_status || 'private' == $post->post_status ) { // already published + $stamp = __('Published on: %1$s'); + } else if ( '0000-00-00 00:00:00' == $post->post_date_gmt ) { // draft, 1 or more saves, no date specified + $stamp = __('Publish immediately'); + } else if ( time() < strtotime( $post->post_date_gmt . ' +0000' ) ) { // draft, 1 or more saves, future date specified + $stamp = __('Schedule for: %1$s'); + } else { // draft, 1 or more saves, date specified + $stamp = __('Publish on: %1$s'); + } + $date = date_i18n( $datef, strtotime( $post->post_date ) ); +} else { // draft (no saves, and thus no date specified) + $stamp = __('Publish immediately'); + $date = date_i18n( $datef, strtotime( current_time('mysql') ) ); +} + +if ( $can_publish ) : // Contributors don't get to choose the date of publish ?> +
+ + + +
+
+ + +
+
+
+ +
+ + + +
+post_status, array('publish', 'future', 'private') ) || 0 == $post->ID ) { + if ( current_user_can('publish_posts') ) : + if ( !empty($post->post_date_gmt) && time() < strtotime( $post->post_date_gmt . ' +0000' ) ) : ?> + + + + + + + + + + + + +
+
+
+
+ +helps) ? esc_attr($taxonomy->helps) : __('Separate tags with commas.'); +?> +
+
+
+

+
+ + + + + +
+

+
+
+ +label) ? esc_attr($taxonomy->label) : $tax_name; + + add_meta_box('tagsdiv-' . $tax_name, $label, 'post_tags_meta_box', 'post', 'side', 'core'); + } +} + +/** + * Display post categories form fields. + * + * @since 2.6.0 + * + * @param object $post + */ +function post_categories_meta_box($post) { +?> + + + + +
+
    +ID, false, false, $popular_ids) ?> +
+
+ + +
+

+

+ + 0, 'name' => 'newcat_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => __('Parent category'), 'tab_index' => 3 ) ); ?> + + +

+
+ +

+

+

+

+ + +

Learn more about manual excerpts.'); ?>

+to_ping) ) .'" />'; + if ('' != $post->pinged) { + $pings = '

'. __('Already pinged:') . '

'; + } + +?> +


()

+

pingbacks, no other action necessary.'); ?>

+ +
+
+ID); +list_meta($metadata); +meta_form(); ?> +
+

use in your theme.'); ?>

+ + +

+
+

+get_var($wpdb->prepare("SELECT count(1) FROM $wpdb->comments WHERE comment_post_ID = '%d' AND ( comment_approved = '0' OR comment_approved = '1')", $post_ID)); + + if ( 1 > $total ) { + echo '

' . __('No comments yet.') . '

'; + return; + } + + wp_nonce_field( 'get-comments', 'add_comment_nonce', false ); +?> + + + + + + + + +

+ + +post_status || 'private' == $post->post_status ) + add_meta_box('commentsdiv', __('Comments'), 'post_comment_meta_box', 'post', 'normal', 'core'); + +/** + * Display post slug form fields. + * + * @since 2.6.0 + * + * @param object $post + */ +function post_slug_meta_box($post) { +?> + +post_status && !current_user_can( 'publish_posts' ) ) ) + add_meta_box('slugdiv', __('Post Slug'), 'post_slug_meta_box', 'post', 'normal', 'core'); + +$authors = get_editable_user_ids( $current_user->id ); // TODO: ROLE SYSTEM +if ( $post->post_author && !in_array($post->post_author, $authors) ) + $authors[] = $post->post_author; +if ( $authors && count( $authors ) > 1 ) : +/** + * Display form field with list of authors. + * + * @since 2.6.0 + * + * @param object $post + */ +function post_author_meta_box($post) { + global $current_user, $user_ID; + $authors = get_editable_user_ids( $current_user->id ); // TODO: ROLE SYSTEM + if ( $post->post_author && !in_array($post->post_author, $authors) ) + $authors[] = $post->post_author; +?> + $authors, 'name' => 'post_author_override', 'selected' => empty($post->ID) ? $user_ID : $post->post_author) ); ?> + + + + + + +
+ +

+ +

+ + +

+ +
+ + + + + + + + + +post_status ) + wp_original_referer_field(true, 'previous'); + +echo $form_extra ?> + +
+
+ + + + +
+ +
+
+
+
+ + +
+
+ID); +if ( !( 'pending' == $post->post_status && !current_user_can( 'publish_posts' ) ) ) { ?> +
+ID) && ! empty($sample_permalink_html) ) : + echo $sample_permalink_html; +endif; ?> +
+ +
+
+ +
+ +post_content); ?> + + + + +
+   +'; + if ( $last_id = get_post_meta($post_ID, '_edit_last', true) ) { + $last_user = get_userdata($last_id); + printf(__('Last edited by %1$s on %2$s at %3$s'), esc_html( $last_user->display_name ), mysql2date(get_option('date_format'), $post->post_modified), mysql2date(get_option('time_format'), $post->post_modified)); + } else { + printf(__('Last edited on %1$s at %2$s'), mysql2date(get_option('date_format'), $post->post_modified), mysql2date(get_option('time_format'), $post->post_modified)); + } + echo ''; + } ?> +
+ + +
+ + + +
+
+
+
+
+
+ + + +post_title) && '' == $post->post_title) || (isset($_GET['message']) && 2 > $_GET['message'])) : ?> + + diff --git a/wp-admin/edit-form-comment.php b/wp-admin/edit-form-comment.php new file mode 100644 index 0000000..f361ad7 --- /dev/null +++ b/wp-admin/edit-form-comment.php @@ -0,0 +1,143 @@ +comment_ID); +$form_action = 'editedcomment'; +$form_extra = "' />\n\ncomment_ID) ?> +
+ +

+ +
+ + + +
+
+

+
+
+
+ +
+
+ +
+
+
+ +
+ +
+
+
+ +
+ +
+%1$s'); +$date = date_i18n( $datef, strtotime( $comment->comment_date ) ); +?> +  +
+
+
+
+
+ +
+
+comment_ID&_wp_original_http_referer=" . urlencode(wp_get_referer()), 'delete-comment_' . $comment->comment_ID) . "' onclick=\"if ( confirm('" . esc_js(__("You are about to delete this comment. \n 'Cancel' to stop, 'OK' to delete.")) . "') ){return true;}return false;\">" . __('Delete') . "\n"; ?> +
+
+ +
+
+
+
+
+
+
+ +
+
+
+

+
+ + + + + + + + + + + + + + + +
+ comment_author_email ) { + printf( __( 'E-mail (%s):' ), get_comment_author_email_link( __( 'send e-mail' ), '', '' ) ); + } else { + _e( 'E-mail:' ); + } +?>
+ comment_author_url ) && 'http://' != $comment->comment_author_url ) { + $link = '' . __('visit site') . ''; + printf( __( 'URL (%s):' ), apply_filters('get_comment_author_link', $link ) ); + } else { + _e( 'URL:' ); + } ?>
+
+
+
+ +
+comment_content, 'content', 'newcomment_author_url', false, 4); ?> + +
+ + + + + + + + + +
+
+
+
+ + + diff --git a/wp-admin/edit-link-categories.php b/wp-admin/edit-link-categories.php new file mode 100644 index 0000000..691f326 --- /dev/null +++ b/wp-admin/edit-link-categories.php @@ -0,0 +1,228 @@ +%s category: this is the default one"), $cat_name)); + + wp_delete_term($cat_ID, 'link_category', array('default' => $default_cat_id)); + } + + $location = 'edit-link-categories.php'; + if ( $referer = wp_get_referer() ) { + if ( false !== strpos($referer, 'edit-link-categories.php') ) + $location = $referer; + } + + $location = add_query_arg('message', 6, $location); + wp_redirect($location); + exit(); + } +} elseif ( isset($_GET['_wp_http_referer']) && ! empty($_GET['_wp_http_referer']) ) { + wp_redirect( remove_query_arg( array('_wp_http_referer', '_wpnonce'), stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; +} + +$title = __('Link Categories'); + +wp_enqueue_script('admin-categories'); +if ( current_user_can('manage_categories') ) + wp_enqueue_script('inline-edit-tax'); + +require_once ('admin-header.php'); + +$messages[1] = __('Category added.'); +$messages[2] = __('Category deleted.'); +$messages[3] = __('Category updated.'); +$messages[4] = __('Category not added.'); +$messages[5] = __('Category not updated.'); +$messages[6] = __('Categories deleted.'); ?> + +
+ +

' . __('Search results for “%s”') . '', esc_html( stripslashes($_GET['s']) ) ); ?> +

+ + +

+ + +
+ +
+
+ +
+ +
+
+
+
+ + add_query_arg( 'pagenum', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil(wp_count_terms('link_category') / $catsperpage), + 'current' => $pagenum +)); + +if ( $page_links ) + echo "
$page_links
"; +?> + +
+ + + +
+ +
+
+ +
+ + + + + + + + + + + + + + + + $start, 'number' => $catsperpage, 'hide_empty' => 0); +if ( !empty( $_GET['s'] ) ) + $args['search'] = $_GET['s']; + +$categories = get_terms( 'link_category', $args ); +if ( $categories ) { + $output = ''; + foreach ( $categories as $category ) { + $output .= link_cat_row($category); + } + echo $output; + unset($category); +} + +?> + +
+ +
+$page_links
"; +?> + +
+ + +
+ +
+
+
+ + +
+

Note:
Deleting a category does not delete the links in that category. Instead, links that were only assigned to the deleted category are set to the category %s.'), get_term_field('name', get_option('default_link_category'), 'link_category')) ?>

+
+ + +
+
+ +
+
+ +parent = 0; do_action('add_link_category_form_pre', $category); ?> + +
+

+
+
+ + + +
+ + +
+ +
+ + +

+
+ +
+ + +
+ +

+ +
+
+ + + +
+
+ +
+
+ + + diff --git a/wp-admin/edit-link-category-form.php b/wp-admin/edit-link-category-form.php new file mode 100644 index 0000000..df1727d --- /dev/null +++ b/wp-admin/edit-link-category-form.php @@ -0,0 +1,89 @@ +' . __('Edit Link Category') . ''; + $submit_text = __('Update Category'); + $form = '
'; + $action = 'editedcat'; + $nonce_action = 'update-link-category_' . $cat_ID; + do_action('edit_link_category_form_pre', $category); +} else { + $heading = '

' . __('Add Link Category') . '

'; + $submit_text = __('Add Category'); + $form = ''; + $action = 'addcat'; + $nonce_action = 'add-link-category'; + do_action('add_link_category_form_pre', $category); +} + +/** + * @ignore + * @since 2.7 + * @internal Used to prevent errors in page when no category is being edited. + * + * @param object $category + */ +function _fill_empty_link_category(&$category) { + if ( ! isset( $category->name ) ) + $category->name = ''; + + if ( ! isset( $category->slug ) ) + $category->slug = ''; + + if ( ! isset( $category->description ) ) + $category->description = ''; +} + +_fill_empty_link_category($category); +?> + +
+ + +
+ + + + + + + + + + + + + + + + + + +

+
+

+ + +
diff --git a/wp-admin/edit-link-form.php b/wp-admin/edit-link-form.php new file mode 100644 index 0000000..11ec684 --- /dev/null +++ b/wp-admin/edit-link-form.php @@ -0,0 +1,422 @@ +Links / Edit Link' ), 'link-manager.php' ); + $submit_text = __('Update Link'); + $form = ' diff --git a/wp-admin/edit-page-form.php b/wp-admin/edit-page-form.php new file mode 100644 index 0000000..516b8eb --- /dev/null +++ b/wp-admin/edit-page-form.php @@ -0,0 +1,499 @@ +View page'), get_permalink($post_ID)); +$messages[2] = __('Custom field updated.'); +$messages[3] = __('Custom field deleted.'); +$messages[5] = sprintf(__('Page published. View page'), get_permalink($post_ID)); +$messages[6] = sprintf(__('Page submitted. Preview page'), add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ); + +if ( isset($_GET['revision']) ) + $messages[5] = sprintf( __('Page restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ); + +$notice = false; +$notices[1] = __( 'There is an autosave of this page that is more recent than the version below. View the autosave.' ); + +if ( 0 == $post_ID) { + $form_action = 'post'; + $nonce_action = 'add-page'; + $temp_ID = -1 * time(); // don't change this formula without looking at wp_write_post() + $form_extra = ""; +} else { + $post_ID = (int) $post_ID; + $form_action = 'editpost'; + $nonce_action = 'update-page_' . $post_ID; + $form_extra = ""; + $autosave = wp_get_post_autosave( $post_ID ); + if ( $autosave && mysql2date( 'U', $autosave->post_modified_gmt, false ) > mysql2date( 'U', $post->post_modified_gmt, false ) ) + $notice = sprintf( $notices[1], get_edit_post_link( $autosave->ID ) ); +} + +$temp_ID = (int) $temp_ID; +$user_ID = (int) $user_ID; + +/** + * Display submit form fields. + * + * @since 2.7.0 + * + * @param object $post + */ +function page_submit_meta_box($post) { + global $action; + + $can_publish = current_user_can('publish_pages'); +?> +
+ +
+ + +
+ +
+ +
+
+post_status && 'future' != $post->post_status && 'pending' != $post->post_status ) { ?> +post_status ) { ?>style="display:none" type="submit" name="save" id="save-post" value="" tabindex="4" class="button button-highlighted" /> +post_status && $can_publish ) { ?> + + +
+ +
+post_status ) { + $preview_link = esc_url(get_permalink($post->ID)); + $preview_button = __('Preview Changes'); +} else { + $preview_link = esc_url(apply_filters('preview_post_link', add_query_arg('preview', 'true', get_permalink($post->ID)))); + $preview_button = __('Preview'); +} +?> + + +
+ +
+
+ +
+ +
+ +post_status ) { + case 'private': + _e('Privately Published'); + break; + case 'publish': + _e('Published'); + break; + case 'future': + _e('Scheduled'); + break; + case 'pending': + _e('Pending Review'); + break; + case 'draft': + _e('Draft'); + break; +} +?> + +post_status || 'private' == $post->post_status || $can_publish ) { ?> +post_status ) { ?>style="display:none;" class="edit-post-status hide-if-no-js" tabindex='4'> + +
+ + + + + +
+ + +
+ +
+ post_status ) { + $post->post_password = ''; + $visibility = 'private'; + $visibility_trans = __('Private'); +} elseif ( !empty( $post->post_password ) ) { + $visibility = 'password'; + $visibility_trans = __('Password protected'); +} else { + $visibility = 'public'; + $visibility_trans = __('Public'); +} + +echo esc_html( $visibility_trans ); ?> + + + +
+ + + + />
+ />
+
+ />
+ +

+

+
+ + +
+ +ID ) { + if ( 'future' == $post->post_status ) { // scheduled for publishing at a future date + $stamp = __('Scheduled for: %1$s'); + } else if ( 'publish' == $post->post_status || 'private' == $post->post_status ) { // already published + $stamp = __('Published on: %1$s'); + } else if ( '0000-00-00 00:00:00' == $post->post_date_gmt ) { // draft, 1 or more saves, no date specified + $stamp = __('Publish immediately'); + } else if ( time() < strtotime( $post->post_date_gmt . ' +0000' ) ) { // draft, 1 or more saves, future date specified + $stamp = __('Schedule for: %1$s'); + } else { // draft, 1 or more saves, date specified + $stamp = __('Publish on: %1$s'); + } + $date = date_i18n( $datef, strtotime( $post->post_date ) ); +} else { // draft (no saves, and thus no date specified) + $stamp = __('Publish immediately'); + $date = date_i18n( $datef, strtotime( current_time('mysql') ) ); +} + +if ( $can_publish ) : // Contributors don't get to choose the date of publish ?> +
+ + +
+
+ +
+
+
+ +
+ + + +
+post_status, array('publish', 'future', 'private') ) || 0 == $post->ID ) { ?> +post_date_gmt) && time() < strtotime( $post->post_date_gmt . ' +0000' ) ) : ?> + + + + + + + + + + + + +
+
+
+
+ +

+

+

+

+ +
+ + $post->ID, 'selected' => $post->post_parent, 'name' => 'parent_id', 'show_option_none' => __('Main Page (no parent)'), 'sort_column'=> 'menu_order, post_title')); ?> +

+ +
+ +

+ +
+

+

+ +
+ID); + list_meta($metadata); + meta_form(); ?> +
+
+

use in your theme.'); ?>

+ + +

+

+

trackbacks and pingbacks.'); ?>

+ + +id, true, 'page' ); // TODO: ROLE SYSTEM +if ( $post->post_author && !in_array($post->post_author, $authors) ) + $authors[] = $post->post_author; +if ( $authors && count( $authors ) > 1 ) { + /** + * Display page author form fields, when more than one author exists. + * + * @since 2.6.0 + * + * @param object $post + */ + function page_author_meta_box($post){ + global $current_user, $user_ID; + $authors = get_editable_user_ids( $current_user->id, true, 'page' ); // TODO: ROLE SYSTEM + if ( $post->post_author && !in_array($post->post_author, $authors) ) + $authors[] = $post->post_author; +?> + $authors, 'name' => 'post_author_override', 'selected' => empty($post->ID) ? $user_ID : $post->post_author) ); ?> + + +
+ +

+ +
+ +

+ + +

+ + +'; +?> + + + + + + + + +post_status ) wp_original_referer_field(true, 'previous'); ?> + +
+ +
+ +
+ +
+
+
+
+ + +
+
+ID); ?> +
+ID) && ! empty($sample_permalink_html) ) : + echo $sample_permalink_html; +endif; ?> +
+
+
+ +
+ +post_content); ?> + + + +
+   + +display_name ), mysql2date(get_option('date_format'), $post->post_modified), mysql2date(get_option('time_format'), $post->post_modified)); + } else { + printf(__('Last edited on %1$s at %2$s'), mysql2date(get_option('date_format'), $post->post_modified), mysql2date(get_option('time_format'), $post->post_modified)); + } + } +?> +
+ + +
+ + + +
+
+
+ +
+
+ + diff --git a/wp-admin/edit-pages.php b/wp-admin/edit-pages.php new file mode 100644 index 0000000..b2fa38b --- /dev/null +++ b/wp-admin/edit-pages.php @@ -0,0 +1,324 @@ +post_type == 'attachment' ) { + if ( ! wp_delete_attachment($post_id_del) ) + wp_die( __('Error in deleting...') ); + } else { + if ( !wp_delete_post($post_id_del) ) + wp_die( __('Error in deleting...') ); + } + $deleted++; + } + } + break; + case 'edit': + if ( isset($_GET['post']) && isset($_GET['bulk_edit']) ) { + check_admin_referer('bulk-pages'); + + if ( -1 == $_GET['_status'] ) { + $_GET['post_status'] = null; + unset($_GET['_status'], $_GET['post_status']); + } else { + $_GET['post_status'] = $_GET['_status']; + } + + $done = bulk_edit_posts($_GET); + } + break; + } + + $sendback = wp_get_referer(); + if (strpos($sendback, 'page.php') !== false) $sendback = admin_url('page-new.php'); + elseif (strpos($sendback, 'attachments.php') !== false) $sendback = admin_url('attachments.php'); + if ( isset($done) ) { + $done['updated'] = count( $done['updated'] ); + $done['skipped'] = count( $done['skipped'] ); + $done['locked'] = count( $done['locked'] ); + $sendback = add_query_arg( $done, $sendback ); + } + if ( isset($deleted) ) + $sendback = add_query_arg('deleted', $deleted, $sendback); + wp_redirect($sendback); + exit(); +} elseif ( isset($_GET['_wp_http_referer']) && ! empty($_GET['_wp_http_referer']) ) { + wp_redirect( remove_query_arg( array('_wp_http_referer', '_wpnonce'), stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; +} + +if ( empty($title) ) + $title = __('Edit Pages'); +$parent_file = 'edit-pages.php'; +wp_enqueue_script('inline-edit-post'); + +$post_stati = array( // array( adj, noun ) + 'publish' => array(_x('Published', 'page'), __('Published pages'), _nx_noop('Published (%s)', 'Published (%s)', 'page')), + 'future' => array(_x('Scheduled', 'page'), __('Scheduled pages'), _nx_noop('Scheduled (%s)', 'Scheduled (%s)', 'page')), + 'pending' => array(_x('Pending Review', 'page'), __('Pending pages'), _nx_noop('Pending Review (%s)', 'Pending Review (%s)', 'page')), + 'draft' => array(_x('Draft', 'page'), _x('Drafts', 'manage posts header'), _nx_noop('Draft (%s)', 'Drafts (%s)', 'page')), + 'private' => array(_x('Private', 'page'), __('Private pages'), _nx_noop('Private (%s)', 'Private (%s)', 'page')) + ); + +$post_stati = apply_filters('page_stati', $post_stati); + +$query = array('post_type' => 'page', 'orderby' => 'menu_order title', + 'posts_per_page' => -1, 'posts_per_archive_page' => -1, 'order' => 'asc'); + +$post_status_label = __('Pages'); +if ( isset($_GET['post_status']) && in_array( $_GET['post_status'], array_keys($post_stati) ) ) { + $post_status_label = $post_stati[$_GET['post_status']][1]; + $query['post_status'] = $_GET['post_status']; + $query['perm'] = 'readable'; +} + +$query = apply_filters('manage_pages_query', $query); +wp($query); + +if ( is_singular() ) { + wp_enqueue_script( 'admin-comments' ); + enqueue_comment_hotkeys_js(); +} + +require_once('admin-header.php'); ?> + +
+ +

' . __('Search results for “%s”') . '', esc_html( get_search_query() ) ); ?> +

+ + +

+ +

+ + + +

|

+ + +
+ + + + + + + + + + +
+ +post_count / $per_page); +$page_links = paginate_links( array( + 'base' => add_query_arg( 'pagenum', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => $num_pages, + 'current' => $pagenum +)); + +if ( $page_links ) : ?> +
' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( ( $pagenum - 1 ) * $per_page + 1 ), + number_format_i18n( min( $pagenum * $per_page, $wp_query->post_count ) ), + number_format_i18n( $wp_query->post_count ), + $page_links +); echo $page_links_text; ?>
+ + +
+ + + +
+ +
+
+ +
+ + + + + + + + + + + + + + + + + +
+ +
+$page_links_text
"; +?> + +
+ + +
+ +
+
+ + +
+

+ + + + + + +
+ + +get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved != 'spam' ORDER BY comment_date", $id) ); + if ( $comments ) : + // Make sure comments, post, and post_author are cached + update_comment_cache($comments); + $post = get_post($id); + $authordata = get_userdata($post->post_author); + ?> + +
+ + + + + + + + + + +comment_ID, 'single', false, false ); +?> + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + +
\ No newline at end of file diff --git a/wp-admin/edit-tag-form.php b/wp-admin/edit-tag-form.php new file mode 100644 index 0000000..250ba7a --- /dev/null +++ b/wp-admin/edit-tag-form.php @@ -0,0 +1,54 @@ + +

+ + +
+ +

+
+
+ + + + + + + + + + + + + + + + + + +
+

+


+
+

+ +
+
diff --git a/wp-admin/edit-tags.php b/wp-admin/edit-tags.php new file mode 100644 index 0000000..9f083b9 --- /dev/null +++ b/wp-admin/edit-tags.php @@ -0,0 +1,320 @@ + + +
+ +

' . __('Search results for “%s”') . '', esc_html( stripslashes($_GET['s']) ) ); ?> +

+ + +

+ + +
+ + +
+
+ +
+ +
+
+
+ +
+ add_query_arg( 'pagenum', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil(wp_count_terms($taxonomy) / $tags_per_page), + 'current' => $pagenum +)); + +if ( $page_links ) + echo "
$page_links
"; +?> + +
+ + + +
+ +
+
+ +
+ + + + + + + + + + + + + + + + + +
+ +
+$page_links
"; +?> + +
+ + +
+ +
+
+ +
+ +
+
+ +
+
+ +
+

+ $taxonomy, 'link' => 'edit')); +else + wp_tag_cloud(array('taxonomy' => $taxonomy)); +?> +
+ + + +
+

+
+
+ + + + +
+ + +

+
+ +
+ + +

+
+ +
+ + +

+
+ +

+ +
+ + +
+
+ +
+ + + + + diff --git a/wp-admin/edit.php b/wp-admin/edit.php new file mode 100644 index 0000000..ae5bee9 --- /dev/null +++ b/wp-admin/edit.php @@ -0,0 +1,303 @@ +post_type == 'attachment' ) { + if ( ! wp_delete_attachment($post_id_del) ) + wp_die( __('Error in deleting...') ); + } else { + if ( !wp_delete_post($post_id_del) ) + wp_die( __('Error in deleting...') ); + } + $deleted++; + } + } + break; + case 'edit': + if ( isset($_GET['post']) && isset($_GET['bulk_edit']) ) { + check_admin_referer('bulk-posts'); + + if ( -1 == $_GET['_status'] ) { + $_GET['post_status'] = null; + unset($_GET['_status'], $_GET['post_status']); + } else { + $_GET['post_status'] = $_GET['_status']; + } + + $done = bulk_edit_posts($_GET); + } + break; + } + + $sendback = wp_get_referer(); + if ( strpos($sendback, 'post.php') !== false ) $sendback = admin_url('post-new.php'); + elseif ( strpos($sendback, 'attachments.php') !== false ) $sendback = admin_url('attachments.php'); + if ( isset($done) ) { + $done['updated'] = count( $done['updated'] ); + $done['skipped'] = count( $done['skipped'] ); + $done['locked'] = count( $done['locked'] ); + $sendback = add_query_arg( $done, $sendback ); + } + if ( isset($deleted) ) + $sendback = add_query_arg('deleted', $deleted, $sendback); + wp_redirect($sendback); + exit(); +} elseif ( isset($_GET['_wp_http_referer']) && ! empty($_GET['_wp_http_referer']) ) { + wp_redirect( remove_query_arg( array('_wp_http_referer', '_wpnonce'), stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; +} + +if ( empty($title) ) + $title = __('Edit Posts'); +$parent_file = 'edit.php'; +wp_enqueue_script('inline-edit-post'); + +list($post_stati, $avail_post_stati) = wp_edit_posts_query(); + +require_once('admin-header.php'); + +if ( !isset( $_GET['paged'] ) ) + $_GET['paged'] = 1; + +if ( empty($_GET['mode']) ) + $mode = 'list'; +else + $mode = esc_attr($_GET['mode']); ?> + +
+ +

' . __('Search results for “%s”') . '', esc_html( get_search_query() ) ); ?> +

+ + +

|

+ + + +

+ +

+ + +
+ + + + + + + + + + + + +
+ add_query_arg( 'paged', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => $wp_query->max_num_pages, + 'current' => $_GET['paged'] +)); + +?> + +
+ + + + +posts WHERE post_type = 'post' ORDER BY post_date DESC"; + +$arc_result = $wpdb->get_results( $arc_query ); + +$month_count = count($arc_result); + +if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) { +$m = isset($_GET['m']) ? (int)$_GET['m'] : 0; +?> + + + + __('View all categories'), 'hide_empty' => 0, 'hierarchical' => 1, + 'show_count' => 0, 'orderby' => 'name', 'selected' => $cat); +wp_dropdown_categories($dropdown_options); +do_action('restrict_manage_posts'); +?> + + + +
+ + +
' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( ( $_GET['paged'] - 1 ) * $wp_query->query_vars['posts_per_page'] + 1 ), + number_format_i18n( min( $_GET['paged'] * $wp_query->query_vars['posts_per_page'], $wp_query->found_posts ) ), + number_format_i18n( $wp_query->found_posts ), + $page_links +); echo $page_links_text; ?>
+ + + + +
+
+ +
+ + + +
+ +$page_links_text
"; +?> + +
+ + +
+
+
+
+ + +
+

+ + + + + + +
+ +
+ + + + + +
+ +

+ +

+

+

+
+

+ + + + + + +
+ +
+

+ +

+
+
+ + diff --git a/wp-admin/gears-manifest.php b/wp-admin/gears-manifest.php new file mode 100644 index 0000000..6bd926b --- /dev/null +++ b/wp-admin/gears-manifest.php @@ -0,0 +1,51 @@ + +{ +"betaManifestVersion" : 1, +"version" : "", +"entries" : [ + + +]} diff --git a/wp-admin/images/align-center.png b/wp-admin/images/align-center.png new file mode 100644 index 0000000..a412226 Binary files /dev/null and b/wp-admin/images/align-center.png differ diff --git a/wp-admin/images/align-left.png b/wp-admin/images/align-left.png new file mode 100644 index 0000000..2e433fc Binary files /dev/null and b/wp-admin/images/align-left.png differ diff --git a/wp-admin/images/align-none.png b/wp-admin/images/align-none.png new file mode 100644 index 0000000..5fb9af2 Binary files /dev/null and b/wp-admin/images/align-none.png differ diff --git a/wp-admin/images/align-right.png b/wp-admin/images/align-right.png new file mode 100644 index 0000000..9b92578 Binary files /dev/null and b/wp-admin/images/align-right.png differ diff --git a/wp-admin/images/archive-link.png b/wp-admin/images/archive-link.png new file mode 100644 index 0000000..4c70895 Binary files /dev/null and b/wp-admin/images/archive-link.png differ diff --git a/wp-admin/images/blue-grad.png b/wp-admin/images/blue-grad.png new file mode 100644 index 0000000..36e0f6b Binary files /dev/null and b/wp-admin/images/blue-grad.png differ diff --git a/wp-admin/images/browse-happy.gif b/wp-admin/images/browse-happy.gif new file mode 100644 index 0000000..c5b64a5 Binary files /dev/null and b/wp-admin/images/browse-happy.gif differ diff --git a/wp-admin/images/bubble_bg-rtl.gif b/wp-admin/images/bubble_bg-rtl.gif new file mode 100644 index 0000000..5cfbefe Binary files /dev/null and b/wp-admin/images/bubble_bg-rtl.gif differ diff --git a/wp-admin/images/bubble_bg.gif b/wp-admin/images/bubble_bg.gif new file mode 100644 index 0000000..315ab52 Binary files /dev/null and b/wp-admin/images/bubble_bg.gif differ diff --git a/wp-admin/images/button-grad-active-vs.png b/wp-admin/images/button-grad-active-vs.png new file mode 100644 index 0000000..dc64172 Binary files /dev/null and b/wp-admin/images/button-grad-active-vs.png differ diff --git a/wp-admin/images/button-grad-active.png b/wp-admin/images/button-grad-active.png new file mode 100644 index 0000000..0177e5b Binary files /dev/null and b/wp-admin/images/button-grad-active.png differ diff --git a/wp-admin/images/button-grad-vs.png b/wp-admin/images/button-grad-vs.png new file mode 100644 index 0000000..51c55a3 Binary files /dev/null and b/wp-admin/images/button-grad-vs.png differ diff --git a/wp-admin/images/button-grad.png b/wp-admin/images/button-grad.png new file mode 100644 index 0000000..3f96366 Binary files /dev/null and b/wp-admin/images/button-grad.png differ diff --git a/wp-admin/images/comment-grey-bubble.png b/wp-admin/images/comment-grey-bubble.png new file mode 100644 index 0000000..6f1e765 Binary files /dev/null and b/wp-admin/images/comment-grey-bubble.png differ diff --git a/wp-admin/images/date-button.gif b/wp-admin/images/date-button.gif new file mode 100644 index 0000000..7ee32cb Binary files /dev/null and b/wp-admin/images/date-button.gif differ diff --git a/wp-admin/images/ed-bg-vs.gif b/wp-admin/images/ed-bg-vs.gif new file mode 100644 index 0000000..0b3d2ba Binary files /dev/null and b/wp-admin/images/ed-bg-vs.gif differ diff --git a/wp-admin/images/ed-bg.gif b/wp-admin/images/ed-bg.gif new file mode 100644 index 0000000..a00467c Binary files /dev/null and b/wp-admin/images/ed-bg.gif differ diff --git a/wp-admin/images/fade-butt.png b/wp-admin/images/fade-butt.png new file mode 100644 index 0000000..42f08b7 Binary files /dev/null and b/wp-admin/images/fade-butt.png differ diff --git a/wp-admin/images/fav-arrow-rtl.gif b/wp-admin/images/fav-arrow-rtl.gif new file mode 100644 index 0000000..9c9fd15 Binary files /dev/null and b/wp-admin/images/fav-arrow-rtl.gif differ diff --git a/wp-admin/images/fav-arrow-vs.gif b/wp-admin/images/fav-arrow-vs.gif new file mode 100644 index 0000000..73d59fd Binary files /dev/null and b/wp-admin/images/fav-arrow-vs.gif differ diff --git a/wp-admin/images/fav-arrow.gif b/wp-admin/images/fav-arrow.gif new file mode 100644 index 0000000..69e0352 Binary files /dev/null and b/wp-admin/images/fav-arrow.gif differ diff --git a/wp-admin/images/fav-top-vs.gif b/wp-admin/images/fav-top-vs.gif new file mode 100644 index 0000000..b9aa3d3 Binary files /dev/null and b/wp-admin/images/fav-top-vs.gif differ diff --git a/wp-admin/images/fav-top.png b/wp-admin/images/fav-top.png new file mode 100644 index 0000000..85a6852 Binary files /dev/null and b/wp-admin/images/fav-top.png differ diff --git a/wp-admin/images/fav-vs.png b/wp-admin/images/fav-vs.png new file mode 100644 index 0000000..51a2186 Binary files /dev/null and b/wp-admin/images/fav-vs.png differ diff --git a/wp-admin/images/fav.png b/wp-admin/images/fav.png new file mode 100644 index 0000000..f3cbe54 Binary files /dev/null and b/wp-admin/images/fav.png differ diff --git a/wp-admin/images/generic.png b/wp-admin/images/generic.png new file mode 100644 index 0000000..3bcbc04 Binary files /dev/null and b/wp-admin/images/generic.png differ diff --git a/wp-admin/images/gray-grad.png b/wp-admin/images/gray-grad.png new file mode 100644 index 0000000..99c45ce Binary files /dev/null and b/wp-admin/images/gray-grad.png differ diff --git a/wp-admin/images/icons32-vs.png b/wp-admin/images/icons32-vs.png new file mode 100644 index 0000000..4683174 Binary files /dev/null and b/wp-admin/images/icons32-vs.png differ diff --git a/wp-admin/images/icons32.png b/wp-admin/images/icons32.png new file mode 100644 index 0000000..6677d1c Binary files /dev/null and b/wp-admin/images/icons32.png differ diff --git a/wp-admin/images/list-vs.png b/wp-admin/images/list-vs.png new file mode 100644 index 0000000..85faa8a Binary files /dev/null and b/wp-admin/images/list-vs.png differ diff --git a/wp-admin/images/list.png b/wp-admin/images/list.png new file mode 100644 index 0000000..827556e Binary files /dev/null and b/wp-admin/images/list.png differ diff --git a/wp-admin/images/loading-publish.gif b/wp-admin/images/loading-publish.gif new file mode 100644 index 0000000..4282004 Binary files /dev/null and b/wp-admin/images/loading-publish.gif differ diff --git a/wp-admin/images/loading.gif b/wp-admin/images/loading.gif new file mode 100644 index 0000000..85b99d4 Binary files /dev/null and b/wp-admin/images/loading.gif differ diff --git a/wp-admin/images/logo-ghost.png b/wp-admin/images/logo-ghost.png new file mode 100644 index 0000000..58335f7 Binary files /dev/null and b/wp-admin/images/logo-ghost.png differ diff --git a/wp-admin/images/logo-login.gif b/wp-admin/images/logo-login.gif new file mode 100644 index 0000000..72422b2 Binary files /dev/null and b/wp-admin/images/logo-login.gif differ diff --git a/wp-admin/images/logo.gif b/wp-admin/images/logo.gif new file mode 100644 index 0000000..8024d48 Binary files /dev/null and b/wp-admin/images/logo.gif differ diff --git a/wp-admin/images/marker.png b/wp-admin/images/marker.png new file mode 100644 index 0000000..3929bbb Binary files /dev/null and b/wp-admin/images/marker.png differ diff --git a/wp-admin/images/mask.png b/wp-admin/images/mask.png new file mode 100644 index 0000000..b0a4d40 Binary files /dev/null and b/wp-admin/images/mask.png differ diff --git a/wp-admin/images/media-button-image.gif b/wp-admin/images/media-button-image.gif new file mode 100644 index 0000000..11278c8 Binary files /dev/null and b/wp-admin/images/media-button-image.gif differ diff --git a/wp-admin/images/media-button-music.gif b/wp-admin/images/media-button-music.gif new file mode 100644 index 0000000..f85cd43 Binary files /dev/null and b/wp-admin/images/media-button-music.gif differ diff --git a/wp-admin/images/media-button-other.gif b/wp-admin/images/media-button-other.gif new file mode 100644 index 0000000..f3f2f8a Binary files /dev/null and b/wp-admin/images/media-button-other.gif differ diff --git a/wp-admin/images/media-button-video.gif b/wp-admin/images/media-button-video.gif new file mode 100644 index 0000000..ceb2734 Binary files /dev/null and b/wp-admin/images/media-button-video.gif differ diff --git a/wp-admin/images/menu-arrows.gif b/wp-admin/images/menu-arrows.gif new file mode 100644 index 0000000..ec854c1 Binary files /dev/null and b/wp-admin/images/menu-arrows.gif differ diff --git a/wp-admin/images/menu-bits-rtl-vs.gif b/wp-admin/images/menu-bits-rtl-vs.gif new file mode 100644 index 0000000..15bca80 Binary files /dev/null and b/wp-admin/images/menu-bits-rtl-vs.gif differ diff --git a/wp-admin/images/menu-bits-rtl.gif b/wp-admin/images/menu-bits-rtl.gif new file mode 100644 index 0000000..3765bfb Binary files /dev/null and b/wp-admin/images/menu-bits-rtl.gif differ diff --git a/wp-admin/images/menu-bits-vs.gif b/wp-admin/images/menu-bits-vs.gif new file mode 100644 index 0000000..c6ad931 Binary files /dev/null and b/wp-admin/images/menu-bits-vs.gif differ diff --git a/wp-admin/images/menu-bits.gif b/wp-admin/images/menu-bits.gif new file mode 100644 index 0000000..9a10a9a Binary files /dev/null and b/wp-admin/images/menu-bits.gif differ diff --git a/wp-admin/images/menu-dark-rtl.gif b/wp-admin/images/menu-dark-rtl.gif new file mode 100644 index 0000000..7bfd25d Binary files /dev/null and b/wp-admin/images/menu-dark-rtl.gif differ diff --git a/wp-admin/images/menu-dark.gif b/wp-admin/images/menu-dark.gif new file mode 100644 index 0000000..739b888 Binary files /dev/null and b/wp-admin/images/menu-dark.gif differ diff --git a/wp-admin/images/menu-vs.png b/wp-admin/images/menu-vs.png new file mode 100644 index 0000000..eb53fe8 Binary files /dev/null and b/wp-admin/images/menu-vs.png differ diff --git a/wp-admin/images/menu.png b/wp-admin/images/menu.png new file mode 100644 index 0000000..cc299fc Binary files /dev/null and b/wp-admin/images/menu.png differ diff --git a/wp-admin/images/no.png b/wp-admin/images/no.png new file mode 100644 index 0000000..e2db55f Binary files /dev/null and b/wp-admin/images/no.png differ diff --git a/wp-admin/images/required.gif b/wp-admin/images/required.gif new file mode 100644 index 0000000..119350f Binary files /dev/null and b/wp-admin/images/required.gif differ diff --git a/wp-admin/images/resize.gif b/wp-admin/images/resize.gif new file mode 100644 index 0000000..6a1b41c Binary files /dev/null and b/wp-admin/images/resize.gif differ diff --git a/wp-admin/images/screen-options-left.gif b/wp-admin/images/screen-options-left.gif new file mode 100644 index 0000000..d692d86 Binary files /dev/null and b/wp-admin/images/screen-options-left.gif differ diff --git a/wp-admin/images/screen-options-right-up.gif b/wp-admin/images/screen-options-right-up.gif new file mode 100644 index 0000000..908e37f Binary files /dev/null and b/wp-admin/images/screen-options-right-up.gif differ diff --git a/wp-admin/images/screen-options-right.gif b/wp-admin/images/screen-options-right.gif new file mode 100644 index 0000000..e2508a0 Binary files /dev/null and b/wp-admin/images/screen-options-right.gif differ diff --git a/wp-admin/images/se.png b/wp-admin/images/se.png new file mode 100644 index 0000000..c9d8fdd Binary files /dev/null and b/wp-admin/images/se.png differ diff --git a/wp-admin/images/star.gif b/wp-admin/images/star.gif new file mode 100644 index 0000000..ff671f7 Binary files /dev/null and b/wp-admin/images/star.gif differ diff --git a/wp-admin/images/toggle-arrow-rtl.gif b/wp-admin/images/toggle-arrow-rtl.gif new file mode 100644 index 0000000..c96b944 Binary files /dev/null and b/wp-admin/images/toggle-arrow-rtl.gif differ diff --git a/wp-admin/images/toggle-arrow.gif b/wp-admin/images/toggle-arrow.gif new file mode 100644 index 0000000..86cb448 Binary files /dev/null and b/wp-admin/images/toggle-arrow.gif differ diff --git a/wp-admin/images/visit-site-button-grad-vs.gif b/wp-admin/images/visit-site-button-grad-vs.gif new file mode 100644 index 0000000..34eb814 Binary files /dev/null and b/wp-admin/images/visit-site-button-grad-vs.gif differ diff --git a/wp-admin/images/visit-site-button-grad.gif b/wp-admin/images/visit-site-button-grad.gif new file mode 100644 index 0000000..a7b703e Binary files /dev/null and b/wp-admin/images/visit-site-button-grad.gif differ diff --git a/wp-admin/images/wheel.png b/wp-admin/images/wheel.png new file mode 100644 index 0000000..97b343d Binary files /dev/null and b/wp-admin/images/wheel.png differ diff --git a/wp-admin/images/white-grad-active.png b/wp-admin/images/white-grad-active.png new file mode 100644 index 0000000..0478015 Binary files /dev/null and b/wp-admin/images/white-grad-active.png differ diff --git a/wp-admin/images/white-grad.png b/wp-admin/images/white-grad.png new file mode 100644 index 0000000..aaf57aa Binary files /dev/null and b/wp-admin/images/white-grad.png differ diff --git a/wp-admin/images/wordpress-logo.png b/wp-admin/images/wordpress-logo.png new file mode 100644 index 0000000..7421f21 Binary files /dev/null and b/wp-admin/images/wordpress-logo.png differ diff --git a/wp-admin/images/wp-logo-vs.gif b/wp-admin/images/wp-logo-vs.gif new file mode 100644 index 0000000..7154d49 Binary files /dev/null and b/wp-admin/images/wp-logo-vs.gif differ diff --git a/wp-admin/images/wp-logo.gif b/wp-admin/images/wp-logo.gif new file mode 100644 index 0000000..42bc676 Binary files /dev/null and b/wp-admin/images/wp-logo.gif differ diff --git a/wp-admin/images/wpspin_dark.gif b/wp-admin/images/wpspin_dark.gif new file mode 100644 index 0000000..daebe0d Binary files /dev/null and b/wp-admin/images/wpspin_dark.gif differ diff --git a/wp-admin/images/wpspin_light.gif b/wp-admin/images/wpspin_light.gif new file mode 100644 index 0000000..e10b97f Binary files /dev/null and b/wp-admin/images/wpspin_light.gif differ diff --git a/wp-admin/images/xit.gif b/wp-admin/images/xit.gif new file mode 100644 index 0000000..6f1cc4f Binary files /dev/null and b/wp-admin/images/xit.gif differ diff --git a/wp-admin/images/yes.png b/wp-admin/images/yes.png new file mode 100644 index 0000000..2f86f0a Binary files /dev/null and b/wp-admin/images/yes.png differ diff --git a/wp-admin/import.php b/wp-admin/import.php new file mode 100644 index 0000000..86dcb14 --- /dev/null +++ b/wp-admin/import.php @@ -0,0 +1,77 @@ + + +
+ +

+

+ +'.__('No importers are available.').'

'; // TODO: make more helpful +} else { +?> + + + $data) { + $style = ('class="alternate"' == $style || 'class="alternate active"' == $style) ? '' : 'alternate'; + $action = "{$data[0]}"; + + if ($style != '') + $style = 'class="'.$style.'"'; + echo " + + + + "; + } +?> + +
$action{$data[1]}
+ + +
+ + + diff --git a/wp-admin/import/blogger.php b/wp-admin/import/blogger.php new file mode 100644 index 0000000..57fc066 --- /dev/null +++ b/wp-admin/import/blogger.php @@ -0,0 +1,1062 @@ + + ".screen_icon()." +

$title

+

$welcome

$prereqs

$stepone

+
+

+ + + + + +

+
+ \n"; + } + + function uh_oh($title, $message, $info) { + echo "
"; + screen_icon(); + echo "

$title

$message

$info
"; + } + + function auth() { + // We have a single-use token that must be upgraded to a session token. + $token = preg_replace( '/[^-_0-9a-zA-Z]/', '', $_GET['token'] ); + $headers = array( + "GET /accounts/AuthSubSessionToken HTTP/1.0", + "Authorization: AuthSub token=\"$token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_auth_sock( ); + if ( ! $sock ) return false; + $response = $this->_txrx( $sock, $request ); + preg_match( '/token=([-_0-9a-z]+)/i', $response, $matches ); + if ( empty( $matches[1] ) ) { + $this->uh_oh( + __( 'Authorization failed' ), + __( 'Something went wrong. If the problem persists, send this info to support:' ), + htmlspecialchars($response) + ); + return false; + } + $this->token = $matches[1]; + + wp_redirect( remove_query_arg( array( 'token', 'noheader' ) ) ); + } + + function get_token_info() { + $headers = array( + "GET /accounts/AuthSubTokenInfo HTTP/1.0", + "Authorization: AuthSub token=\"$this->token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_auth_sock( ); + if ( ! $sock ) return; + $response = $this->_txrx( $sock, $request ); + return $this->parse_response($response); + } + + function token_is_valid() { + $info = $this->get_token_info(); + + if ( $info['code'] == 200 ) + return true; + + return false; + } + + function show_blogs($iter = 0) { + if ( empty($this->blogs) ) { + $headers = array( + "GET /feeds/default/blogs HTTP/1.0", + "Host: www.blogger.com", + "Authorization: AuthSub token=\"$this->token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_blogger_sock( ); + if ( ! $sock ) return; + $response = $this->_txrx( $sock, $request ); + + // Quick and dirty XML mining. + list( $headers, $xml ) = explode( "\r\n\r\n", $response ); + $p = xml_parser_create(); + xml_parse_into_struct($p, $xml, $vals, $index); + xml_parser_free($p); + + $this->title = $vals[$index['TITLE'][0]]['value']; + + // Give it a few retries... this step often flakes out the first time. + if ( empty( $index['ENTRY'] ) ) { + if ( $iter < 3 ) { + return $this->show_blogs($iter + 1); + } else { + $this->uh_oh( + __('Trouble signing in'), + __('We were not able to gain access to your account. Try starting over.'), + '' + ); + return false; + } + } + + foreach ( $index['ENTRY'] as $i ) { + $blog = array(); + while ( ( $tag = $vals[$i] ) && ! ( $tag['tag'] == 'ENTRY' && $tag['type'] == 'close' ) ) { + if ( $tag['tag'] == 'TITLE' ) { + $blog['title'] = $tag['value']; + } elseif ( $tag['tag'] == 'SUMMARY' ) { + $blog['summary'] == $tag['value']; + } elseif ( $tag['tag'] == 'LINK' ) { + if ( $tag['attributes']['REL'] == 'alternate' && $tag['attributes']['TYPE'] == 'text/html' ) { + $parts = parse_url( $tag['attributes']['HREF'] ); + $blog['host'] = $parts['host']; + } elseif ( $tag['attributes']['REL'] == 'edit' ) + $blog['gateway'] = $tag['attributes']['HREF']; + } + ++$i; + } + if ( ! empty ( $blog ) ) { + $blog['total_posts'] = $this->get_total_results('posts', $blog['host']); + $blog['total_comments'] = $this->get_total_results('comments', $blog['host']); + $blog['mode'] = 'init'; + $this->blogs[] = $blog; + } + } + + if ( empty( $this->blogs ) ) { + $this->uh_oh( + __('No blogs found'), + __('We were able to log in but there were no blogs. Try a different account next time.'), + '' + ); + return false; + } + } +//echo '
'.print_r($this,1).'
'; + $start = esc_js( __('Import') ); + $continue = esc_js( __('Continue') ); + $stop = esc_js( __('Importing...') ); + $authors = esc_js( __('Set Authors') ); + $loadauth = esc_js( __('Preparing author mapping form...') ); + $authhead = esc_js( __('Final Step: Author Mapping') ); + $nothing = esc_js( __('Nothing was imported. Had you already imported this blog?') ); + $title = __('Blogger Blogs'); + $name = __('Blog Name'); + $url = __('Blog URL'); + $action = __('The Magic Button'); + $posts = __('Posts'); + $comments = __('Comments'); + $noscript = __('This feature requires Javascript but it seems to be disabled. Please enable Javascript and then reload this page. Don’t worry, you can turn it back off when you’re done.'); + + $interval = STATUS_INTERVAL * 1000; + + foreach ( $this->blogs as $i => $blog ) { + if ( $blog['mode'] == 'init' ) + $value = $start; + elseif ( $blog['mode'] == 'posts' || $blog['mode'] == 'comments' ) + $value = $continue; + else + $value = $authors; + $value = esc_attr($value); + $blogtitle = esc_js( $blog['title'] ); + $pdone = isset($blog['posts_done']) ? (int) $blog['posts_done'] : 0; + $cdone = isset($blog['comments_done']) ? (int) $blog['comments_done'] : 0; + $init .= "blogs[$i]=new blog($i,'$blogtitle','{$blog['mode']}'," . $this->get_js_status($i) . ');'; + $pstat = "
 
$pdone/{$blog['total_posts']}
"; + $cstat = "
 
$cdone/{$blog['total_comments']}
"; + $rows .= "$blogtitle{$blog['host']}$pstat$cstat\n"; + } + + echo "

$title

\n$rows
$name$url$posts$comments$action
"; + echo " + \n"; + } + + // Handy function for stopping the script after a number of seconds. + function have_time() { + global $importer_started; + if ( time() - $importer_started > MAX_EXECUTION_TIME ) + die('continue'); + return true; + } + + function get_total_results($type, $host) { + $headers = array( + "GET /feeds/$type/default?max-results=1&start-index=2 HTTP/1.0", + "Host: $host", + "Authorization: AuthSub token=\"$this->token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_blogger_sock( $host ); + if ( ! $sock ) return; + $response = $this->_txrx( $sock, $request ); + $response = $this->parse_response( $response ); + $parser = xml_parser_create(); + xml_parse_into_struct($parser, $response['body'], $struct, $index); + xml_parser_free($parser); + $total_results = $struct[$index['OPENSEARCH:TOTALRESULTS'][0]]['value']; + return (int) $total_results; + } + + function import_blog($blogID) { + global $importing_blog; + $importing_blog = $blogID; + + if ( isset($_GET['authors']) ) + return print($this->get_author_form()); + + header('Content-Type: text/plain'); + + if ( isset($_GET['status']) ) + die($this->get_js_status()); + + if ( isset($_GET['saveauthors']) ) + die($this->save_authors()); + + $blog = $this->blogs[$blogID]; + $total_results = $this->get_total_results('posts', $blog['host']); + $this->blogs[$importing_blog]['total_posts'] = $total_results; + + $start_index = $total_results - MAX_RESULTS + 1; + + if ( isset( $this->blogs[$importing_blog]['posts_start_index'] ) ) + $start_index = (int) $this->blogs[$importing_blog]['posts_start_index']; + elseif ( $total_results > MAX_RESULTS ) + $start_index = $total_results - MAX_RESULTS + 1; + else + $start_index = 1; + + // This will be positive until we have finished importing posts + if ( $start_index > 0 ) { + // Grab all the posts + $this->blogs[$importing_blog]['mode'] = 'posts'; + $query = "start-index=$start_index&max-results=" . MAX_RESULTS; + do { + $index = $struct = $entries = array(); + $headers = array( + "GET /feeds/posts/default?$query HTTP/1.0", + "Host: {$blog['host']}", + "Authorization: AuthSub token=\"$this->token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_blogger_sock( $blog['host'] ); + if ( ! $sock ) return; // TODO: Error handling + $response = $this->_txrx( $sock, $request ); + + $response = $this->parse_response( $response ); + + // Extract the entries and send for insertion + preg_match_all( '/]*>.*?<\/entry>/s', $response['body'], $matches ); + if ( count( $matches[0] ) ) { + $entries = array_reverse($matches[0]); + foreach ( $entries as $entry ) { + $entry = "$entry"; + $AtomParser = new AtomParser(); + $AtomParser->parse( $entry ); + $result = $this->import_post($AtomParser->entry); + if ( is_wp_error( $result ) ) + return $result; + unset($AtomParser); + } + } else break; + + // Get the 'previous' query string which we'll use on the next iteration + $query = ''; + $links = preg_match_all('/]*)>/', $response['body'], $matches); + if ( count( $matches[1] ) ) + foreach ( $matches[1] as $match ) + if ( preg_match('/rel=.previous./', $match) ) + $query = @html_entity_decode( preg_replace('/^.*href=[\'"].*\?(.+)[\'"].*$/', '$1', $match), ENT_COMPAT, get_option('blog_charset') ); + + if ( $query ) { + parse_str($query, $q); + $this->blogs[$importing_blog]['posts_start_index'] = (int) $q['start-index']; + } else + $this->blogs[$importing_blog]['posts_start_index'] = 0; + $this->save_vars(); + } while ( !empty( $query ) && $this->have_time() ); + } + + $total_results = $this->get_total_results( 'comments', $blog['host'] ); + $this->blogs[$importing_blog]['total_comments'] = $total_results; + + if ( isset( $this->blogs[$importing_blog]['comments_start_index'] ) ) + $start_index = (int) $this->blogs[$importing_blog]['comments_start_index']; + elseif ( $total_results > MAX_RESULTS ) + $start_index = $total_results - MAX_RESULTS + 1; + else + $start_index = 1; + + if ( $start_index > 0 ) { + // Grab all the comments + $this->blogs[$importing_blog]['mode'] = 'comments'; + $query = "start-index=$start_index&max-results=" . MAX_RESULTS; + do { + $index = $struct = $entries = array(); + $headers = array( + "GET /feeds/comments/default?$query HTTP/1.0", + "Host: {$blog['host']}", + "Authorization: AuthSub token=\"$this->token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_blogger_sock( $blog['host'] ); + if ( ! $sock ) return; // TODO: Error handling + $response = $this->_txrx( $sock, $request ); + + $response = $this->parse_response( $response ); + + // Extract the comments and send for insertion + preg_match_all( '/]*>.*?<\/entry>/s', $response['body'], $matches ); + if ( count( $matches[0] ) ) { + $entries = array_reverse( $matches[0] ); + foreach ( $entries as $entry ) { + $entry = "$entry"; + $AtomParser = new AtomParser(); + $AtomParser->parse( $entry ); + $this->import_comment($AtomParser->entry); + unset($AtomParser); + } + } + + // Get the 'previous' query string which we'll use on the next iteration + $query = ''; + $links = preg_match_all('/]*)>/', $response['body'], $matches); + if ( count( $matches[1] ) ) + foreach ( $matches[1] as $match ) + if ( preg_match('/rel=.previous./', $match) ) + $query = @html_entity_decode( preg_replace('/^.*href=[\'"].*\?(.+)[\'"].*$/', '$1', $match), ENT_COMPAT, get_option('blog_charset') ); + + parse_str($query, $q); + + $this->blogs[$importing_blog]['comments_start_index'] = (int) $q['start-index']; + $this->save_vars(); + } while ( !empty( $query ) && $this->have_time() ); + } + $this->blogs[$importing_blog]['mode'] = 'authors'; + $this->save_vars(); + if ( !$this->blogs[$importing_blog]['posts_done'] && !$this->blogs[$importing_blog]['comments_done'] ) + die('nothing'); + do_action('import_done', 'blogger'); + die('done'); + } + + function convert_date( $date ) { + preg_match('#([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(Z|[\+|\-][0-9]{2,4}){0,1}#', $date, $date_bits); + $offset = iso8601_timezone_to_offset( $date_bits[7] ); + $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]); + $timestamp -= $offset; // Convert from Blogger local time to GMT + $timestamp += get_option('gmt_offset') * 3600; // Convert from GMT to WP local time + return gmdate('Y-m-d H:i:s', $timestamp); + } + + function no_apos( $string ) { + return str_replace( ''', "'", $string); + } + + function min_whitespace( $string ) { + return preg_replace( '|\s+|', ' ', $string ); + } + + function import_post( $entry ) { + global $importing_blog; + + // The old permalink is all Blogger gives us to link comments to their posts. + if ( isset( $entry->draft ) ) + $rel = 'self'; + else + $rel = 'alternate'; + foreach ( $entry->links as $link ) { + if ( $link['rel'] == $rel ) { + $parts = parse_url( $link['href'] ); + $entry->old_permalink = $parts['path']; + break; + } + } + + $post_date = $this->convert_date( $entry->published ); + $post_content = trim( addslashes( $this->no_apos( @html_entity_decode( $entry->content, ENT_COMPAT, get_option('blog_charset') ) ) ) ); + $post_title = trim( addslashes( $this->no_apos( $this->min_whitespace( $entry->title ) ) ) ); + $post_status = isset( $entry->draft ) ? 'draft' : 'publish'; + + // Clean up content + $post_content = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $post_content); + $post_content = str_replace('
', '
', $post_content); + $post_content = str_replace('
', '
', $post_content); + + // Checks for duplicates + if ( isset( $this->blogs[$importing_blog]['posts'][$entry->old_permalink] ) ) { + ++$this->blogs[$importing_blog]['posts_skipped']; + } elseif ( $post_id = post_exists( $post_title, $post_content, $post_date ) ) { + $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id; + ++$this->blogs[$importing_blog]['posts_skipped']; + } else { + $post = compact('post_date', 'post_content', 'post_title', 'post_status'); + + $post_id = wp_insert_post($post); + if ( is_wp_error( $post_id ) ) + return $post_id; + + wp_create_categories( array_map( 'addslashes', $entry->categories ), $post_id ); + + $author = $this->no_apos( strip_tags( $entry->author ) ); + + add_post_meta( $post_id, 'blogger_blog', $this->blogs[$importing_blog]['host'], true ); + add_post_meta( $post_id, 'blogger_author', $author, true ); + add_post_meta( $post_id, 'blogger_permalink', $entry->old_permalink, true ); + + $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id; + ++$this->blogs[$importing_blog]['posts_done']; + } + $this->save_vars(); + return; + } + + function import_comment( $entry ) { + global $importing_blog; + + // Drop the #fragment and we have the comment's old post permalink. + foreach ( $entry->links as $link ) { + if ( $link['rel'] == 'alternate' ) { + $parts = parse_url( $link['href'] ); + $entry->old_permalink = $parts['fragment']; + $entry->old_post_permalink = $parts['path']; + break; + } + } + + $comment_post_ID = (int) $this->blogs[$importing_blog]['posts'][$entry->old_post_permalink]; + preg_match('#(.+?).*(?:\(.+?))?#', $entry->author, $matches); + $comment_author = addslashes( $this->no_apos( strip_tags( (string) $matches[1] ) ) ); + $comment_author_url = addslashes( $this->no_apos( strip_tags( (string) $matches[2] ) ) ); + $comment_date = $this->convert_date( $entry->updated ); + $comment_content = addslashes( $this->no_apos( @html_entity_decode( $entry->content, ENT_COMPAT, get_option('blog_charset') ) ) ); + + // Clean up content + $comment_content = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $comment_content); + $comment_content = str_replace('
', '
', $comment_content); + $comment_content = str_replace('
', '
', $comment_content); + + // Checks for duplicates + if ( + isset( $this->blogs[$importing_blog]['comments'][$entry->old_permalink] ) || + comment_exists( $comment_author, $comment_date ) + ) { + ++$this->blogs[$importing_blog]['comments_skipped']; + } else { + $comment = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_date', 'comment_content'); + + $comment_id = wp_insert_comment($comment); + + $this->blogs[$importing_blog]['comments'][$entry->old_permalink] = $comment_id; + + ++$this->blogs[$importing_blog]['comments_done']; + } + $this->save_vars(); + } + + function get_js_status($blog = false) { + global $importing_blog; + if ( $blog === false ) + $blog = $this->blogs[$importing_blog]; + else + $blog = $this->blogs[$blog]; + $p1 = isset( $blog['posts_done'] ) ? (int) $blog['posts_done'] : 0; + $p2 = isset( $blog['total_posts'] ) ? (int) $blog['total_posts'] : 0; + $c1 = isset( $blog['comments_done'] ) ? (int) $blog['comments_done'] : 0; + $c2 = isset( $blog['total_comments'] ) ? (int) $blog['total_comments'] : 0; + return "{p1:$p1,p2:$p2,c1:$c1,c2:$c2}"; + } + + function get_author_form($blog = false) { + global $importing_blog, $wpdb, $current_user; + if ( $blog === false ) + $blog = & $this->blogs[$importing_blog]; + else + $blog = & $this->blogs[$blog]; + + if ( !isset( $blog['authors'] ) ) { + $post_ids = array_values($blog['posts']); + $authors = (array) $wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'blogger_author' AND post_id IN (" . join( ',', $post_ids ) . ")"); + $blog['authors'] = array_map(null, $authors, array_fill(0, count($authors), $current_user->ID)); + $this->save_vars(); + } + + $directions = __('All posts were imported with the current user as author. Use this form to move each Blogger user’s posts to a different WordPress user. You may add users and then return to this page and complete the user mapping. This form may be used as many times as you like until you activate the “Restart” function below.'); + $heading = __('Author mapping'); + $blogtitle = "{$blog['title']} ({$blog['host']})"; + $mapthis = __('Blogger username'); + $tothis = __('WordPress login'); + $submit = esc_js( __('Save Changes') ); + + foreach ( $blog['authors'] as $i => $author ) + $rows .= ""; + + return "

$heading

$blogtitle

$directions

$rows
$mapthis$tothis
"; + } + + function get_user_options($current) { + global $importer_users; + if ( ! isset( $importer_users ) ) + $importer_users = (array) get_users_of_blog(); + + foreach ( $importer_users as $user ) { + $sel = ( $user->user_id == $current ) ? " selected='selected'" : ''; + $options .= ""; + } + + return $options; + } + + function save_authors() { + global $importing_blog, $wpdb; + $authors = (array) $_POST['authors']; + + $host = $this->blogs[$importing_blog]['host']; + + // Get an array of posts => authors + $post_ids = (array) $wpdb->get_col( $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'blogger_blog' AND meta_value = %s", $host) ); + $post_ids = join( ',', $post_ids ); + $results = (array) $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = 'blogger_author' AND post_id IN ($post_ids)"); + foreach ( $results as $row ) + $authors_posts[$row->post_id] = $row->meta_value; + + foreach ( $authors as $author => $user_id ) { + $user_id = (int) $user_id; + + // Skip authors that haven't been changed + if ( $user_id == $this->blogs[$importing_blog]['authors'][$author][1] ) + continue; + + // Get a list of the selected author's posts + $post_ids = (array) array_keys( $authors_posts, $this->blogs[$importing_blog]['authors'][$author][0] ); + $post_ids = join( ',', $post_ids); + + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE id IN ($post_ids)", $user_id) ); + $this->blogs[$importing_blog]['authors'][$author][1] = $user_id; + } + $this->save_vars(); + + wp_redirect('edit.php'); + } + + function _get_auth_sock() { + // Connect to https://www.google.com + if ( !$sock = @ fsockopen('ssl://www.google.com', 443, $errno, $errstr) ) { + $this->uh_oh( + __('Could not connect to https://www.google.com'), + __('There was a problem opening a secure connection to Google. This is what went wrong:'), + "$errstr ($errno)" + ); + return false; + } + return $sock; + } + + function _get_blogger_sock($host = 'www2.blogger.com') { + if ( !$sock = @ fsockopen($host, 80, $errno, $errstr) ) { + $this->uh_oh( + sprintf( __('Could not connect to %s'), $host ), + __('There was a problem opening a connection to Blogger. This is what went wrong:'), + "$errstr ($errno)" + ); + return false; + } + return $sock; + } + + function _txrx( $sock, $request ) { + fwrite( $sock, $request ); + while ( ! feof( $sock ) ) + $response .= @ fread ( $sock, 8192 ); + fclose( $sock ); + return $response; + } + + function revoke($token) { + $headers = array( + "GET /accounts/AuthSubRevokeToken HTTP/1.0", + "Authorization: AuthSub token=\"$token\"" + ); + $request = join( "\r\n", $headers ) . "\r\n\r\n"; + $sock = $this->_get_auth_sock( ); + if ( ! $sock ) return false; + $this->_txrx( $sock, $request ); + } + + function restart() { + global $wpdb; + $options = get_option( 'blogger_importer' ); + + if ( isset( $options['token'] ) ) + $this->revoke( $options['token'] ); + + delete_option('blogger_importer'); + $wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key = 'blogger_author'"); + wp_redirect('?import=blogger'); + } + + // Returns associative array of code, header, cookies, body. Based on code from php.net. + function parse_response($this_response) { + // Split response into header and body sections + list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2); + $response_header_lines = explode("\r\n", $response_headers); + + // First line of headers is the HTTP response code + $http_response_line = array_shift($response_header_lines); + if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; } + + // put the rest of the headers in an array + $response_header_array = array(); + foreach($response_header_lines as $header_line) { + list($header,$value) = explode(': ', $header_line, 2); + $response_header_array[$header] .= $value."\n"; + } + + $cookie_array = array(); + $cookies = explode("\n", $response_header_array["Set-Cookie"]); + foreach($cookies as $this_cookie) { array_push($cookie_array, "Cookie: ".$this_cookie); } + + return array("code" => $response_code, "header" => $response_header_array, "cookies" => $cookie_array, "body" => $response_body); + } + + // Step 9: Congratulate the user + function congrats() { + $blog = (int) $_GET['blog']; + echo '

'.__('Congratulations!').'

'.__('Now that you have imported your Blogger blog into WordPress, what are you going to do? Here are some suggestions:').'

  • '.__('That was hard work! Take a break.').'
  • '; + if ( count($this->import['blogs']) > 1 ) + echo '
  • '.__('In case you haven’t done it already, you can import the posts from your other blogs:'). $this->show_blogs() . '
  • '; + if ( $n = count($this->import['blogs'][$blog]['newusers']) ) + echo '
  • '.sprintf(__('Go to Authors & Users, where you can modify the new user(s) or delete them. If you want to make all of the imported posts yours, you will be given that option when you delete the new authors.'), 'users.php', '_parent').'
  • '; + echo '
  • '.__('For security, click the link below to reset this importer.').'
  • '; + echo '
'; + } + + // Figures out what to do, then does it. + function start() { + if ( isset($_POST['restart']) ) + $this->restart(); + + $options = get_option('blogger_importer'); + + if ( is_array($options) ) + foreach ( $options as $key => $value ) + $this->$key = $value; + + if ( isset( $_REQUEST['blog'] ) ) { + $blog = is_array($_REQUEST['blog']) ? array_shift( $keys = array_keys( $_REQUEST['blog'] ) ) : $_REQUEST['blog']; + $blog = (int) $blog; + $result = $this->import_blog( $blog ); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + } elseif ( isset($_GET['token']) ) + $this->auth(); + elseif ( isset($this->token) && $this->token_is_valid() ) + $this->show_blogs(); + else + $this->greet(); + + $saved = $this->save_vars(); + + if ( $saved && !isset($_GET['noheader']) ) { + $restart = __('Restart'); + $message = __('We have saved some information about your Blogger account in your WordPress database. Clearing this information will allow you to start over. Restarting will not affect any posts you have already imported. If you attempt to re-import a blog, duplicate posts and comments will be skipped.'); + $submit = esc_attr__('Clear account information'); + echo "

$restart

$message

"; + } + } + + function save_vars() { + $vars = get_object_vars($this); + update_option( 'blogger_importer', $vars ); + + return !empty($vars); + } + + function admin_head() { +?> + +entry = new AtomEntry(); + $this->map_attrs_func = create_function('$k,$v', 'return "$k=\"$v\"";'); + $this->map_xmlns_func = create_function('$p,$n', '$xd = "xmlns"; if(strlen($n[0])>0) $xd .= ":{$n[0]}"; return "{$xd}=\"{$n[1]}\"";'); + } + + function parse($xml) { + + global $app_logging; + array_unshift($this->ns_contexts, array()); + + $parser = xml_parser_create_ns(); + xml_set_object($parser, $this); + xml_set_element_handler($parser, "start_element", "end_element"); + xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); + xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,0); + xml_set_character_data_handler($parser, "cdata"); + xml_set_default_handler($parser, "_default"); + xml_set_start_namespace_decl_handler($parser, "start_ns"); + xml_set_end_namespace_decl_handler($parser, "end_ns"); + + $contents = ""; + + xml_parse($parser, $xml); + + xml_parser_free($parser); + + return true; + } + + function start_element($parser, $name, $attrs) { + + $tag = array_pop(split(":", $name)); + + array_unshift($this->ns_contexts, $this->ns_decls); + + $this->depth++; + + if(!empty($this->in_content)) { + $attrs_prefix = array(); + + // resolve prefixes for attributes + foreach($attrs as $key => $value) { + $attrs_prefix[$this->ns_to_prefix($key)] = $this->xml_escape($value); + } + $attrs_str = join(' ', array_map($this->map_attrs_func, array_keys($attrs_prefix), array_values($attrs_prefix))); + if(strlen($attrs_str) > 0) { + $attrs_str = " " . $attrs_str; + } + + $xmlns_str = join(' ', array_map($this->map_xmlns_func, array_keys($this->ns_contexts[0]), array_values($this->ns_contexts[0]))); + if(strlen($xmlns_str) > 0) { + $xmlns_str = " " . $xmlns_str; + } + + // handle self-closing tags (case: a new child found right-away, no text node) + if(count($this->in_content) == 2) { + array_push($this->in_content, ">"); + } + + array_push($this->in_content, "<". $this->ns_to_prefix($name) ."{$xmlns_str}{$attrs_str}"); + } else if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS) || in_array($tag, $this->ATOM_SIMPLE_ELEMENTS)) { + $this->in_content = array(); + $this->is_xhtml = $attrs['type'] == 'xhtml'; + array_push($this->in_content, array($tag,$this->depth)); + } else if($tag == 'link') { + array_push($this->entry->links, $attrs); + } else if($tag == 'category') { + array_push($this->entry->categories, $attrs['term']); + } + + $this->ns_decls = array(); + } + + function end_element($parser, $name) { + + $tag = array_pop(split(":", $name)); + + if(!empty($this->in_content)) { + if($this->in_content[0][0] == $tag && + $this->in_content[0][1] == $this->depth) { + array_shift($this->in_content); + if($this->is_xhtml) { + $this->in_content = array_slice($this->in_content, 2, count($this->in_content)-3); + } + $this->entry->$tag = join('',$this->in_content); + $this->in_content = array(); + } else { + $endtag = $this->ns_to_prefix($name); + if (strpos($this->in_content[count($this->in_content)-1], '<' . $endtag) !== false) { + array_push($this->in_content, "/>"); + } else { + array_push($this->in_content, ""); + } + } + } + + array_shift($this->ns_contexts); + + #print str_repeat(" ", $this->depth * $this->indent) . "end_element('$name')" ."\n"; + + $this->depth--; + } + + function start_ns($parser, $prefix, $uri) { + #print str_repeat(" ", $this->depth * $this->indent) . "starting: " . $prefix . ":" . $uri . "\n"; + array_push($this->ns_decls, array($prefix,$uri)); + } + + function end_ns($parser, $prefix) { + #print str_repeat(" ", $this->depth * $this->indent) . "ending: #" . $prefix . "#\n"; + } + + function cdata($parser, $data) { + #print str_repeat(" ", $this->depth * $this->indent) . "data: #" . $data . "#\n"; + if(!empty($this->in_content)) { + // handle self-closing tags (case: text node found, need to close element started) + if (strpos($this->in_content[count($this->in_content)-1], '<') !== false) { + array_push($this->in_content, ">"); + } + array_push($this->in_content, $this->xml_escape($data)); + } + } + + function _default($parser, $data) { + # when does this gets called? + } + + + function ns_to_prefix($qname) { + $components = split(":", $qname); + $name = array_pop($components); + + if(!empty($components)) { + $ns = join(":",$components); + foreach($this->ns_contexts as $context) { + foreach($context as $mapping) { + if($mapping[1] == $ns && strlen($mapping[0]) > 0) { + return "$mapping[0]:$name"; + } + } + } + } + return $name; + } + + function xml_escape($string) + { + return str_replace(array('&','"',"'",'<','>'), + array('&','"',''','<','>'), + $string ); + } +} + +?> diff --git a/wp-admin/import/blogware.php b/wp-admin/import/blogware.php new file mode 100644 index 0000000..500a08b --- /dev/null +++ b/wp-admin/import/blogware.php @@ -0,0 +1,215 @@ +'; + screen_icon(); + echo '

'.__('Import Blogware').'

'; + } + + function footer() { + echo ''; + } + + function unhtmlentities($string) { // From php.net for < 4.3 compat + $trans_tbl = get_html_translation_table(HTML_ENTITIES); + $trans_tbl = array_flip($trans_tbl); + return strtr($string, $trans_tbl); + } + + function greet() { + echo '
'; + echo '

'.__('Howdy! This importer allows you to extract posts from Blogware XML export file into your blog. Pick a Blogware file to upload and click Import.').'

'; + wp_import_upload_form("admin.php?import=blogware&step=1"); + echo '
'; + } + + function import_posts() { + global $wpdb, $current_user; + + set_magic_quotes_runtime(0); + $importdata = file($this->file); // Read the file into an array + $importdata = implode('', $importdata); // squish it + $importdata = str_replace(array ("\r\n", "\r"), "\n", $importdata); + + preg_match_all('|(]+>(.*?))|is', $importdata, $posts); + $posts = $posts[1]; + unset($importdata); + echo '
    '; + foreach ($posts as $post) { + flush(); + preg_match('||is', $post, $post_type); + $post_type = $post_type[1]; + if($post_type == "photo") { + preg_match('|(.*?)|is', $post, $post_title); + } else { + preg_match('|(.*?)|is', $post, $post_title); + } + $post_title = $wpdb->escape(trim($post_title[1])); + + preg_match('|(.*?)|is', $post, $post_date); + $post_date = strtotime($post_date[1]); + $post_date = gmdate('Y-m-d H:i:s', $post_date); + + preg_match_all('|(.*?)|is', $post, $categories); + $categories = $categories[1]; + + $cat_index = 0; + foreach ($categories as $category) { + $categories[$cat_index] = $wpdb->escape($this->unhtmlentities($category)); + $cat_index++; + } + + if(strcasecmp($post_type, "photo") === 0) { + preg_match('|(.*?)|is', $post, $post_content); + $post_content = ''; + $post_content = $this->unhtmlentities($post_content); + } else { + preg_match('|(.*?)|is', $post, $post_content); + $post_content = str_replace(array (''), '', trim($post_content[1])); + $post_content = $this->unhtmlentities($post_content); + } + + // Clean up content + $post_content = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $post_content); + $post_content = str_replace('
    ', '
    ', $post_content); + $post_content = str_replace('
    ', '
    ', $post_content); + $post_content = $wpdb->escape($post_content); + + $post_author = $current_user->ID; + preg_match('|(.*?)|is', $post, $post_status); + $post_status = trim($post_status[1]); + + echo '
  1. '; + if ($post_id = post_exists($post_title, $post_content, $post_date)) { + printf(__('Post %s already exists.'), stripslashes($post_title)); + } else { + printf(__('Importing post %s...'), stripslashes($post_title)); + $postdata = compact('post_author', 'post_date', 'post_content', 'post_title', 'post_status'); + $post_id = wp_insert_post($postdata); + if ( is_wp_error( $post_id ) ) { + return $post_id; + } + if (!$post_id) { + _e('Couldn’t get post ID'); + echo '
  2. '; + break; + } + if(0 != count($categories)) + wp_create_categories($categories, $post_id); + } + + preg_match_all('|(.*?)|is', $post, $comments); + $comments = $comments[1]; + + if ( $comments ) { + $comment_post_ID = (int) $post_id; + $num_comments = 0; + foreach ($comments as $comment) { + preg_match('|(.*?)|is', $comment, $comment_content); + $comment_content = str_replace(array (''), '', trim($comment_content[1])); + $comment_content = $this->unhtmlentities($comment_content); + + // Clean up content + $comment_content = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $comment_content); + $comment_content = str_replace('
    ', '
    ', $comment_content); + $comment_content = str_replace('
    ', '
    ', $comment_content); + $comment_content = $wpdb->escape($comment_content); + + preg_match('|(.*?)|is', $comment, $comment_date); + $comment_date = trim($comment_date[1]); + $comment_date = date('Y-m-d H:i:s', strtotime($comment_date)); + + preg_match('|(.*?)|is', $comment, $comment_author); + $comment_author = $wpdb->escape(trim($comment_author[1])); + + $comment_author_email = NULL; + + $comment_approved = 1; + // Check if it's already there + if (!comment_exists($comment_author, $comment_date)) { + $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_date', 'comment_content', 'comment_approved'); + $commentdata = wp_filter_comment($commentdata); + wp_insert_comment($commentdata); + $num_comments++; + } + } + } + if ( $num_comments ) { + echo ' '; + printf( _n('%s comment', '%s comments', $num_comments), $num_comments ); + } + echo ''; + flush(); + ob_flush(); + } + echo '
'; + } + + function import() { + $file = wp_import_handle_upload(); + if ( isset($file['error']) ) { + echo $file['error']; + return; + } + + $this->file = $file['file']; + $result = $this->import_posts(); + if ( is_wp_error( $result ) ) + return $result; + wp_import_cleanup($file['id']); + do_action('import_done', 'blogware'); + echo '

'; + printf(__('All done. Have fun!'), get_option('home')); + echo '

'; + } + + function dispatch() { + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + + $this->header(); + + switch ($step) { + case 0 : + $this->greet(); + break; + case 1 : + $result = $this->import(); + if ( is_wp_error( $result ) ) + $result->get_error_message(); + break; + } + + $this->footer(); + } + + function BW_Import() { + // Nothing. + } +} + +$blogware_import = new BW_Import(); + +register_importer('blogware', __('Blogware'), __('Import posts from Blogware.'), array ($blogware_import, 'dispatch')); +?> diff --git a/wp-admin/import/btt.php b/wp-admin/import/btt.php new file mode 100644 index 0000000..a2aab3f --- /dev/null +++ b/wp-admin/import/btt.php @@ -0,0 +1,130 @@ +'; + screen_icon(); + echo '

'.__('Import Bunny’s Technorati Tags').'

'; + echo '

'.__('Steps may take a few minutes depending on the size of your database. Please be patient.').'

'; + } + + function footer() { + echo ''; + } + + function greet() { + echo '
'; + echo '

'.__('Howdy! This imports tags from Bunny’s Technorati Tags into WordPress tags.').'

'; + echo '

'.__('This is suitable for Bunny’s Technorati Tags version 0.6.').'

'; + echo '

'.__('All existing Bunny’s Technorati Tags will be removed after import.').'

'; + echo '

'.__('Don’t be stupid - backup your database before proceeding!').'

'; + echo '
'; + wp_nonce_field('import-btt'); + echo '

'; + echo '
'; + echo '
'; + } + + function dispatch() { + if ( empty($_GET['step']) ) + $step = 0; + else + $step = absint($_GET['step']); + + // load the header + $this->header(); + + switch ( $step ) { + case 0 : + $this->greet(); + break; + case 1 : + check_admin_referer('import-btt'); + $this->check_post_keyword( true ); + break; + case 2 : + check_admin_referer('import-btt'); + $this->check_post_keyword( false ); + break; + case 3: + $this->done(); + break; + } + + // load the footer + $this->footer(); + } + + function check_post_keyword($precheck = true) { + global $wpdb; + + echo '
'; + echo '

'.__('Reading Bunny’s Technorati Tags…').'

'; + + // import Bunny's Keywords tags + $metakeys = $wpdb->get_results("SELECT post_id, meta_id, meta_key, meta_value FROM $wpdb->postmeta WHERE $wpdb->postmeta.meta_key = 'tags'"); + if ( !is_array($metakeys)) { + echo '

' . __('No Tags Found!') . '

'; + return false; + } else { + $count = count($metakeys); + echo '

' . sprintf( _n('Done! %s post with tags were read.', 'Done! %s posts with tags were read.', $count), $count ) . '

'; + echo '
    '; + foreach ( $metakeys as $post_meta ) { + if ( $post_meta->meta_value != '' ) { + $post_keys = explode(' ', $post_meta->meta_value); + foreach ( $post_keys as $keyword ) { + $keyword = addslashes(trim(str_replace('+',' ',$keyword))); + if ( '' != $keyword ) { + echo '
  • ' . $post_meta->post_id . ' - ' . $keyword . '
  • '; + if ( !$precheck ) + wp_add_post_tags($post_meta->post_id, $keyword); + } + } + } + if ( !$precheck ) + delete_post_meta($post_meta->post_id, 'tags'); + } + echo '
'; + } + + echo '
'; + wp_nonce_field('import-btt'); + echo '

'; + echo '
'; + echo '
'; + } + + function done() { + echo '
'; + echo '

'.__('Import Complete!').'

'; + echo '
'; + } + + function BunnyTags_Import() { + } + +} + +// create the import object +$btt_import = new BunnyTags_Import(); + +// add it to the import page! +register_importer('btt', 'Bunny’s Technorati Tags', __('Import Bunny’s Technorati Tags into WordPress tags.'), array($btt_import, 'dispatch')); + +?> diff --git a/wp-admin/import/dotclear.php b/wp-admin/import/dotclear.php new file mode 100644 index 0000000..d6552f7 --- /dev/null +++ b/wp-admin/import/dotclear.php @@ -0,0 +1,729 @@ +get_var( $wpdb->prepare("SELECT count(*) FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) ); + } +} + +if(!function_exists('link_exists')) +{ + /** + * Check whether link already exists. + * + * @package WordPress + * @subpackage Dotclear_Import + * + * @param string $linkname + * @return int + */ + function link_exists($linkname) + { + global $wpdb; + return $wpdb->get_var( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_name = %s", $linkname) ); + } +} + +/** + * Convert from dotclear charset to utf8 if required + * + * @package WordPress + * @subpackage Dotclear_Import + * + * @param string $s + * @return string + */ +function csc ($s) { + if (seems_utf8 ($s)) { + return $s; + } else { + return iconv(get_option ("dccharset"),"UTF-8",$s); + } +} + +/** + * @package WordPress + * @subpackage Dotclear_Import + * + * @param string $s + * @return string + */ +function textconv ($s) { + return csc (preg_replace ('|(?)\s*\n|', ' ', $s)); +} + +/** + * Dotclear Importer class + * + * Will process the WordPress eXtended RSS files that you upload from the export + * file. + * + * @package WordPress + * @subpackage Importer + * + * @since unknown + */ +class Dotclear_Import { + + function header() + { + echo '
'; + screen_icon(); + echo '

'.__('Import DotClear').'

'; + echo '

'.__('Steps may take a few minutes depending on the size of your database. Please be patient.').'

'; + } + + function footer() + { + echo '
'; + } + + function greet() + { + echo '

'.__('Howdy! This importer allows you to extract posts from a DotClear database into your blog. Mileage may vary.').'

'; + echo '

'.__('Your DotClear Configuration settings are as follows:').'

'; + echo '
'; + wp_nonce_field('import-dotclear'); + $this->db_form(); + echo '

'; + echo '
'; + } + + function get_dc_cats() + { + global $wpdb; + // General Housekeeping + $dcdb = new wpdb(get_option('dcuser'), get_option('dcpass'), get_option('dcname'), get_option('dchost')); + set_magic_quotes_runtime(0); + $dbprefix = get_option('dcdbprefix'); + + // Get Categories + return $dcdb->get_results('SELECT * FROM '.$dbprefix.'categorie', ARRAY_A); + } + + function get_dc_users() + { + global $wpdb; + // General Housekeeping + $dcdb = new wpdb(get_option('dcuser'), get_option('dcpass'), get_option('dcname'), get_option('dchost')); + set_magic_quotes_runtime(0); + $dbprefix = get_option('dcdbprefix'); + + // Get Users + + return $dcdb->get_results('SELECT * FROM '.$dbprefix.'user', ARRAY_A); + } + + function get_dc_posts() + { + // General Housekeeping + $dcdb = new wpdb(get_option('dcuser'), get_option('dcpass'), get_option('dcname'), get_option('dchost')); + set_magic_quotes_runtime(0); + $dbprefix = get_option('dcdbprefix'); + + // Get Posts + return $dcdb->get_results('SELECT '.$dbprefix.'post.*, '.$dbprefix.'categorie.cat_libelle_url AS post_cat_name + FROM '.$dbprefix.'post INNER JOIN '.$dbprefix.'categorie + ON '.$dbprefix.'post.cat_id = '.$dbprefix.'categorie.cat_id', ARRAY_A); + } + + function get_dc_comments() + { + global $wpdb; + // General Housekeeping + $dcdb = new wpdb(get_option('dcuser'), get_option('dcpass'), get_option('dcname'), get_option('dchost')); + set_magic_quotes_runtime(0); + $dbprefix = get_option('dcdbprefix'); + + // Get Comments + return $dcdb->get_results('SELECT * FROM '.$dbprefix.'comment', ARRAY_A); + } + + function get_dc_links() + { + //General Housekeeping + $dcdb = new wpdb(get_option('dcuser'), get_option('dcpass'), get_option('dcname'), get_option('dchost')); + set_magic_quotes_runtime(0); + $dbprefix = get_option('dcdbprefix'); + + return $dcdb->get_results('SELECT * FROM '.$dbprefix.'link ORDER BY position', ARRAY_A); + } + + function cat2wp($categories='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $dccat2wpcat = array(); + // Do the Magic + if(is_array($categories)) + { + echo '

'.__('Importing Categories...').'

'; + foreach ($categories as $category) + { + $count++; + extract($category); + + // Make Nice Variables + $name = $wpdb->escape($cat_libelle_url); + $title = $wpdb->escape(csc ($cat_libelle)); + $desc = $wpdb->escape(csc ($cat_desc)); + + if($cinfo = category_exists($name)) + { + $ret_id = wp_insert_category(array('cat_ID' => $cinfo, 'category_nicename' => $name, 'cat_name' => $title, 'category_description' => $desc)); + } + else + { + $ret_id = wp_insert_category(array('category_nicename' => $name, 'cat_name' => $title, 'category_description' => $desc)); + } + $dccat2wpcat[$id] = $ret_id; + } + + // Store category translation for future use + add_option('dccat2wpcat',$dccat2wpcat); + echo '

'.sprintf(_n('Done! %1$s category imported.', 'Done! %1$s categories imported.', $count), $count).'

'; + return true; + } + echo __('No Categories to Import!'); + return false; + } + + function users2wp($users='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $dcid2wpid = array(); + + // Midnight Mojo + if(is_array($users)) + { + echo '

'.__('Importing Users...').'

'; + foreach($users as $user) + { + $count++; + extract($user); + + // Make Nice Variables + $name = $wpdb->escape(csc ($name)); + $RealName = $wpdb->escape(csc ($user_pseudo)); + + if($uinfo = get_userdatabylogin($name)) + { + + $ret_id = wp_insert_user(array( + 'ID' => $uinfo->ID, + 'user_login' => $user_id, + 'user_nicename' => $Realname, + 'user_email' => $user_email, + 'user_url' => 'http://', + 'display_name' => $Realname) + ); + } + else + { + $ret_id = wp_insert_user(array( + 'user_login' => $user_id, + 'user_nicename' => csc ($user_pseudo), + 'user_email' => $user_email, + 'user_url' => 'http://', + 'display_name' => $Realname) + ); + } + $dcid2wpid[$user_id] = $ret_id; + + // Set DotClear-to-WordPress permissions translation + + // Update Usermeta Data + $user = new WP_User($ret_id); + $wp_perms = $user_level + 1; + if(10 == $wp_perms) { $user->set_role('administrator'); } + else if(9 == $wp_perms) { $user->set_role('editor'); } + else if(5 <= $wp_perms) { $user->set_role('editor'); } + else if(4 <= $wp_perms) { $user->set_role('author'); } + else if(3 <= $wp_perms) { $user->set_role('contributor'); } + else if(2 <= $wp_perms) { $user->set_role('contributor'); } + else { $user->set_role('subscriber'); } + + update_usermeta( $ret_id, 'wp_user_level', $wp_perms); + update_usermeta( $ret_id, 'rich_editing', 'false'); + update_usermeta( $ret_id, 'first_name', csc ($user_prenom)); + update_usermeta( $ret_id, 'last_name', csc ($user_nom)); + }// End foreach($users as $user) + + // Store id translation array for future use + add_option('dcid2wpid',$dcid2wpid); + + + echo '

'.sprintf(__('Done! %1$s users imported.'), $count).'

'; + return true; + }// End if(is_array($users) + + echo __('No Users to Import!'); + return false; + + }// End function user2wp() + + function posts2wp($posts='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $dcposts2wpposts = array(); + $cats = array(); + + // Do the Magic + if(is_array($posts)) + { + echo '

'.__('Importing Posts...').'

'; + foreach($posts as $post) + { + $count++; + extract($post); + + // Set DotClear-to-WordPress status translation + $stattrans = array(0 => 'draft', 1 => 'publish'); + $comment_status_map = array (0 => 'closed', 1 => 'open'); + + //Can we do this more efficiently? + $uinfo = ( get_userdatabylogin( $user_id ) ) ? get_userdatabylogin( $user_id ) : 1; + $authorid = ( is_object( $uinfo ) ) ? $uinfo->ID : $uinfo ; + + $Title = $wpdb->escape(csc ($post_titre)); + $post_content = textconv ($post_content); + $post_excerpt = ""; + if ($post_chapo != "") { + $post_excerpt = textconv ($post_chapo); + $post_content = $post_excerpt ."\n\n".$post_content; + } + $post_excerpt = $wpdb->escape ($post_excerpt); + $post_content = $wpdb->escape ($post_content); + $post_status = $stattrans[$post_pub]; + + // Import Post data into WordPress + + if($pinfo = post_exists($Title,$post_content)) + { + $ret_id = wp_insert_post(array( + 'ID' => $pinfo, + 'post_author' => $authorid, + 'post_date' => $post_dt, + 'post_date_gmt' => $post_dt, + 'post_modified' => $post_upddt, + 'post_modified_gmt' => $post_upddt, + 'post_title' => $Title, + 'post_content' => $post_content, + 'post_excerpt' => $post_excerpt, + 'post_status' => $post_status, + 'post_name' => $post_titre_url, + 'comment_status' => $comment_status_map[$post_open_comment], + 'ping_status' => $comment_status_map[$post_open_tb], + 'comment_count' => $post_nb_comment + $post_nb_trackback) + ); + if ( is_wp_error( $ret_id ) ) + return $ret_id; + } + else + { + $ret_id = wp_insert_post(array( + 'post_author' => $authorid, + 'post_date' => $post_dt, + 'post_date_gmt' => $post_dt, + 'post_modified' => $post_modified_gmt, + 'post_modified_gmt' => $post_modified_gmt, + 'post_title' => $Title, + 'post_content' => $post_content, + 'post_excerpt' => $post_excerpt, + 'post_status' => $post_status, + 'post_name' => $post_titre_url, + 'comment_status' => $comment_status_map[$post_open_comment], + 'ping_status' => $comment_status_map[$post_open_tb], + 'comment_count' => $post_nb_comment + $post_nb_trackback) + ); + if ( is_wp_error( $ret_id ) ) + return $ret_id; + } + $dcposts2wpposts[$post_id] = $ret_id; + + // Make Post-to-Category associations + $cats = array(); + $category1 = get_category_by_slug($post_cat_name); + $category1 = $category1->term_id; + + if($cat1 = $category1) { $cats[1] = $cat1; } + + if(!empty($cats)) { wp_set_post_categories($ret_id, $cats); } + } + } + // Store ID translation for later use + add_option('dcposts2wpposts',$dcposts2wpposts); + + echo '

'.sprintf(__('Done! %1$s posts imported.'), $count).'

'; + return true; + } + + function comments2wp($comments='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $dccm2wpcm = array(); + $postarr = get_option('dcposts2wpposts'); + + // Magic Mojo + if(is_array($comments)) + { + echo '

'.__('Importing Comments...').'

'; + foreach($comments as $comment) + { + $count++; + extract($comment); + + // WordPressify Data + $comment_ID = (int) ltrim($comment_id, '0'); + $comment_post_ID = (int) $postarr[$post_id]; + $comment_approved = "$comment_pub"; + $name = $wpdb->escape(csc ($comment_auteur)); + $email = $wpdb->escape($comment_email); + $web = "http://".$wpdb->escape($comment_site); + $message = $wpdb->escape(textconv ($comment_content)); + + if($cinfo = comment_exists($name, $comment_dt)) + { + // Update comments + $ret_id = wp_update_comment(array( + 'comment_ID' => $cinfo, + 'comment_post_ID' => $comment_post_ID, + 'comment_author' => $name, + 'comment_author_email' => $email, + 'comment_author_url' => $web, + 'comment_author_IP' => $comment_ip, + 'comment_date' => $comment_dt, + 'comment_date_gmt' => $comment_dt, + 'comment_content' => $message, + 'comment_approved' => $comment_approved) + ); + } + else + { + // Insert comments + $ret_id = wp_insert_comment(array( + 'comment_post_ID' => $comment_post_ID, + 'comment_author' => $name, + 'comment_author_email' => $email, + 'comment_author_url' => $web, + 'comment_author_IP' => $comment_ip, + 'comment_date' => $comment_dt, + 'comment_date_gmt' => $comment_dt, + 'comment_content' => $message, + 'comment_approved' => $comment_approved) + ); + } + $dccm2wpcm[$comment_ID] = $ret_id; + } + // Store Comment ID translation for future use + add_option('dccm2wpcm', $dccm2wpcm); + + // Associate newly formed categories with posts + get_comment_count($ret_id); + + + echo '

'.sprintf(__('Done! %1$s comments imported.'), $count).'

'; + return true; + } + echo __('No Comments to Import!'); + return false; + } + + function links2wp($links='') + { + // General Housekeeping + global $wpdb; + $count = 0; + + // Deal with the links + if(is_array($links)) + { + echo '

'.__('Importing Links...').'

'; + foreach($links as $link) + { + $count++; + extract($link); + + if ($title != "") { + if ($cinfo = is_term(csc ($title), 'link_category')) { + $category = $cinfo['term_id']; + } else { + $category = wp_insert_term($wpdb->escape (csc ($title)), 'link_category'); + $category = $category['term_id']; + } + } else { + $linkname = $wpdb->escape(csc ($label)); + $description = $wpdb->escape(csc ($title)); + + if($linfo = link_exists($linkname)) { + $ret_id = wp_insert_link(array( + 'link_id' => $linfo, + 'link_url' => $href, + 'link_name' => $linkname, + 'link_category' => $category, + 'link_description' => $description) + ); + } else { + $ret_id = wp_insert_link(array( + 'link_url' => $url, + 'link_name' => $linkname, + 'link_category' => $category, + 'link_description' => $description) + ); + } + $dclinks2wplinks[$link_id] = $ret_id; + } + } + add_option('dclinks2wplinks',$dclinks2wplinks); + echo '

'; + printf(_n('Done! %s link or link category imported.', 'Done! %s links or link categories imported.', $count), $count); + echo '

'; + return true; + } + echo __('No Links to Import!'); + return false; + } + + function import_categories() + { + // Category Import + $cats = $this->get_dc_cats(); + $this->cat2wp($cats); + add_option('dc_cats', $cats); + + + + echo '
'; + wp_nonce_field('import-dotclear'); + printf('

', esc_attr__('Import Users')); + echo '
'; + + } + + function import_users() + { + // User Import + $users = $this->get_dc_users(); + $this->users2wp($users); + + echo '
'; + wp_nonce_field('import-dotclear'); + printf('

', esc_attr__('Import Posts')); + echo '
'; + } + + function import_posts() + { + // Post Import + $posts = $this->get_dc_posts(); + $result = $this->posts2wp($posts); + if ( is_wp_error( $result ) ) + return $result; + + echo '
'; + wp_nonce_field('import-dotclear'); + printf('

', esc_attr__('Import Comments')); + echo '
'; + } + + function import_comments() + { + // Comment Import + $comments = $this->get_dc_comments(); + $this->comments2wp($comments); + + echo '
'; + wp_nonce_field('import-dotclear'); + printf('

', esc_attr__('Import Links')); + echo '
'; + } + + function import_links() + { + //Link Import + $links = $this->get_dc_links(); + $this->links2wp($links); + add_option('dc_links', $links); + + echo '
'; + wp_nonce_field('import-dotclear'); + printf('

', esc_attr__('Finish')); + echo '
'; + } + + function cleanup_dcimport() + { + delete_option('dcdbprefix'); + delete_option('dc_cats'); + delete_option('dcid2wpid'); + delete_option('dccat2wpcat'); + delete_option('dcposts2wpposts'); + delete_option('dccm2wpcm'); + delete_option('dclinks2wplinks'); + delete_option('dcuser'); + delete_option('dcpass'); + delete_option('dcname'); + delete_option('dchost'); + delete_option('dccharset'); + do_action('import_done', 'dotclear'); + $this->tips(); + } + + function tips() + { + echo '

'.__('Welcome to WordPress. We hope (and expect!) that you will find this platform incredibly rewarding! As a new WordPress user coming from DotClear, there are some things that we would like to point out. Hopefully, they will help your transition go as smoothly as possible.').'

'; + echo '

'.__('Users').'

'; + echo '

'.sprintf(__('You have already setup WordPress and have been assigned an administrative login and password. Forget it. You didn’t have that login in DotClear, why should you have it here? Instead we have taken care to import all of your users into our system. Unfortunately there is one downside. Because both WordPress and DotClear uses a strong encryption hash with passwords, it is impossible to decrypt it and we are forced to assign temporary passwords to all your users. Every user has the same username, but their passwords are reset to password123. So Login and change it.'), '/wp-login.php').'

'; + echo '

'.__('Preserving Authors').'

'; + echo '

'.__('Secondly, we have attempted to preserve post authors. If you are the only author or contributor to your blog, then you are safe. In most cases, we are successful in this preservation endeavor. However, if we cannot ascertain the name of the writer due to discrepancies between database tables, we assign it to you, the administrative user.').'

'; + echo '

'.__('Textile').'

'; + echo '

'.__('Also, since you’re coming from DotClear, you probably have been using Textile to format your comments and posts. If this is the case, we recommend downloading and installing Textile for WordPress. Trust me… You’ll want it.').'

'; + echo '

'.__('WordPress Resources').'

'; + echo '

'.__('Finally, there are numerous WordPress resources around the internet. Some of them are:').'

'; + echo ''; + echo '

'.sprintf(__('That’s it! What are you waiting for? Go login!'), '../wp-login.php').'

'; + } + + function db_form() + { + echo ''; + printf('', __('DotClear Database User:')); + printf('', __('DotClear Database Password:')); + printf('', __('DotClear Database Name:')); + printf('', __('DotClear Database Host:')); + printf('', __('DotClear Table prefix:')); + printf('', __('Originating character set:')); + echo '
'; + } + + function dispatch() + { + + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + $this->header(); + + if ( $step > 0 ) + { + check_admin_referer('import-dotclear'); + + if($_POST['dbuser']) + { + if(get_option('dcuser')) + delete_option('dcuser'); + add_option('dcuser', sanitize_user($_POST['dbuser'], true)); + } + if($_POST['dbpass']) + { + if(get_option('dcpass')) + delete_option('dcpass'); + add_option('dcpass', sanitize_user($_POST['dbpass'], true)); + } + + if($_POST['dbname']) + { + if(get_option('dcname')) + delete_option('dcname'); + add_option('dcname', sanitize_user($_POST['dbname'], true)); + } + if($_POST['dbhost']) + { + if(get_option('dchost')) + delete_option('dchost'); + add_option('dchost', sanitize_user($_POST['dbhost'], true)); + } + if($_POST['dccharset']) + { + if(get_option('dccharset')) + delete_option('dccharset'); + add_option('dccharset', sanitize_user($_POST['dccharset'], true)); + } + if($_POST['dbprefix']) + { + if(get_option('dcdbprefix')) + delete_option('dcdbprefix'); + add_option('dcdbprefix', sanitize_user($_POST['dbprefix'], true)); + } + + + } + + switch ($step) + { + default: + case 0 : + $this->greet(); + break; + case 1 : + $this->import_categories(); + break; + case 2 : + $this->import_users(); + break; + case 3 : + $result = $this->import_posts(); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + break; + case 4 : + $this->import_comments(); + break; + case 5 : + $this->import_links(); + break; + case 6 : + $this->cleanup_dcimport(); + break; + } + + $this->footer(); + } + + function Dotclear_Import() + { + // Nothing. + } +} + +$dc_import = new Dotclear_Import(); + +register_importer('dotclear', __('DotClear'), __('Import categories, users, posts, comments, and links from a DotClear blog.'), array ($dc_import, 'dispatch')); + +?> diff --git a/wp-admin/import/greymatter.php b/wp-admin/import/greymatter.php new file mode 100644 index 0000000..7e06f67 --- /dev/null +++ b/wp-admin/import/greymatter.php @@ -0,0 +1,334 @@ +'; + screen_icon(); + echo '

'.__('Import GreyMatter').'

'; + } + + function footer() { + echo ''; + } + + function greet() { + $this->header(); +?> +

+

+
    +
  • +
  • If authors are found not to be in gm-authors.cgi, imports them at level 0.') ?>
  • +
  • +
+

+
    +
  • +
  • +
  • +
+

 

+ +
+ + + +

+ + + + + + + + + + + + + +

+ so you need to enter the number of the last GM post here.
(if you don’t know that number, just log into your FTP and look it out
in the entries’ folder)') ?>
+

+
+footer(); + } + + + + function gm2autobr($string) { // transforms GM's |*| into b2's
\n + $string = str_replace("|*|","
\n",$string); + return($string); + } + + function import() { + global $wpdb; + + $wpvarstoreset = array('gmpath', 'archivespath', 'lastentry'); + for ($i=0; $iheader(); +?> +

+
    +
    • escape($userdata[0]); + $pass1=$wpdb->escape($userdata[1]); + $user_nickname=$wpdb->escape($userdata[0]); + $user_email=$wpdb->escape($userdata[2]); + $user_url=$wpdb->escape($userdata[3]); + $user_joindate=$wpdb->escape($user_joindate); + + $user_id = username_exists($user_login); + if ($user_id) { + printf('
    • '.__('user %s').''.__('Already exists').'
    • ', "$user_login"); + $this->gmnames[$userdata[0]] = $user_id; + continue; + } + + $user_info = array("user_login"=>"$user_login", "user_pass"=>"$pass1", "user_nickname"=>"$user_nickname", "user_email"=>"$user_email", "user_url"=>"$user_url", "user_ip"=>"$user_ip", "user_domain"=>"$user_domain", "user_browser"=>"$user_browser", "dateYMDhour"=>"$user_joindate", "user_level"=>"1", "user_idmode"=>"nickname"); + $user_id = wp_insert_user($user_info); + $this->gmnames[$userdata[0]] = $user_id; + + printf('
    • '.__('user %s...').' '.__('Done').'
    • ', "$user_login"); + } + +?>
  • +

    • gm2autobr($entry[2]); + $postmorecontent=$this->gm2autobr($entry[3]); + + $post_author=trim($wpdb->escape($postinfo[1])); + + $post_title=$this->gm2autobr($postinfo[2]); + printf('
    • '.__('entry # %s : %s : by %s'), $entryfile, $post_title, $postinfo[1]); + $post_title=$wpdb->escape($post_title); + + $postyear=$postinfo[6]; + $postmonth=zeroise($postinfo[4],2); + $postday=zeroise($postinfo[5],2); + $posthour=zeroise($postinfo[7],2); + $postminute=zeroise($postinfo[8],2); + $postsecond=zeroise($postinfo[9],2); + + if (($postinfo[10]=="PM") && ($posthour!="12")) + $posthour=$posthour+12; + + $post_date="$postyear-$postmonth-$postday $posthour:$postminute:$postsecond"; + + $post_content=$postmaincontent; + if (strlen($postmorecontent)>3) + $post_content .= "

      ".$postmorecontent; + $post_content=$wpdb->escape($post_content); + + $post_karma=$postinfo[12]; + + $post_status = 'publish'; //in greymatter, there are no drafts + $comment_status = 'open'; + $ping_status = 'closed'; + + if ($post_ID = post_exists($post_title, '', $post_date)) { + echo ' '; + _e('(already exists)'); + } else { + //just so that if a post already exists, new users are not created by checkauthor + // we'll check the author is registered, or if it's a deleted author + $user_id = username_exists($post_author); + if (!$user_id) { // if deleted from GM, we register the author as a level 0 user + $user_ip="127.0.0.1"; + $user_domain="localhost"; + $user_browser="server"; + $user_joindate="1979-06-06 00:41:00"; + $user_login=$wpdb->escape($post_author); + $pass1=$wpdb->escape("password"); + $user_nickname=$wpdb->escape($post_author); + $user_email=$wpdb->escape("user@deleted.com"); + $user_url=$wpdb->escape(""); + $user_joindate=$wpdb->escape($user_joindate); + + $user_info = array("user_login"=>$user_login, "user_pass"=>$pass1, "user_nickname"=>$user_nickname, "user_email"=>$user_email, "user_url"=>$user_url, "user_ip"=>$user_ip, "user_domain"=>$user_domain, "user_browser"=>$user_browser, "dateYMDhour"=>$user_joindate, "user_level"=>0, "user_idmode"=>"nickname"); + $user_id = wp_insert_user($user_info); + $this->gmnames[$postinfo[1]] = $user_id; + + echo ': '; + printf(__('registered deleted user %s at level 0 '), "$user_login"); + } + + if (array_key_exists($postinfo[1], $this->gmnames)) { + $post_author = $this->gmnames[$postinfo[1]]; + } else { + $post_author = $user_id; + } + + $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt'); + $post_ID = wp_insert_post($postdata); + if ( is_wp_error( $post_ID ) ) + return $post_ID; + } + + $c=count($entry); + if ($c>4) { + $numAddedComments = 0; + $numComments = 0; + for ($j=4;$j<$c;$j++) { + $entry[$j]=$this->gm2autobr($entry[$j]); + $commentinfo=explode("|",$entry[$j]); + $comment_post_ID=$post_ID; + $comment_author=$wpdb->escape($commentinfo[0]); + $comment_author_email=$wpdb->escape($commentinfo[2]); + $comment_author_url=$wpdb->escape($commentinfo[3]); + $comment_author_IP=$wpdb->escape($commentinfo[1]); + + $commentyear=$commentinfo[7]; + $commentmonth=zeroise($commentinfo[5],2); + $commentday=zeroise($commentinfo[6],2); + $commenthour=zeroise($commentinfo[8],2); + $commentminute=zeroise($commentinfo[9],2); + $commentsecond=zeroise($commentinfo[10],2); + if (($commentinfo[11]=="PM") && ($commenthour!="12")) + $commenthour=$commenthour+12; + $comment_date="$commentyear-$commentmonth-$commentday $commenthour:$commentminute:$commentsecond"; + + $comment_content=$wpdb->escape($commentinfo[12]); + + if (!comment_exists($comment_author, $comment_date)) { + $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_content', 'comment_approved'); + $commentdata = wp_filter_comment($commentdata); + wp_insert_comment($commentdata); + $numAddedComments++; + } + $numComments++; + } + if ($numAddedComments > 0) { + echo ': '; + printf( _n('imported %s comment', 'imported %s comments', $numAddedComments) , $numAddedComments); + } + $preExisting = $numComments - numAddedComments; + if ($preExisting > 0) { + echo ' '; + printf( _n( 'ignored %s pre-existing comment', 'ignored %s pre-existing comments', $preExisting ) , $preExisting); + } + } + echo '... '.__('Done').'
    • '; + } + } + do_action('import_done', 'greymatter'); + ?> +
+

 

+

+footer(); + return; + } + + function dispatch() { + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + + switch ($step) { + case 0 : + $this->greet(); + break; + case 1: + check_admin_referer('import-greymatter'); + $result = $this->import(); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + break; + } + } + + function GM_Import() { + // Nothing. + } +} + +$gm_import = new GM_Import(); + +register_importer('greymatter', __('GreyMatter'), __('Import users, posts, and comments from a Greymatter blog.'), array ($gm_import, 'dispatch')); +?> diff --git a/wp-admin/import/jkw.php b/wp-admin/import/jkw.php new file mode 100644 index 0000000..d21d79a --- /dev/null +++ b/wp-admin/import/jkw.php @@ -0,0 +1,192 @@ +'; + screen_icon(); + echo '

'.__('Import Jerome’s Keywords').'

'; + echo '

'.__('Steps may take a few minutes depending on the size of your database. Please be patient.').'

'; + } + + function footer() { + echo ''; + } + + function greet() { + echo '
'; + echo '

'.__('Howdy! This imports tags from Jerome’s Keywords into WordPress tags.').'

'; + echo '

'.__('This is suitable for Jerome’s Keywords version 1.x and 2.0a.').'

'; + echo '

'.__('All existing Jerome’s Keywords will be removed after import.').'

'; + echo '

'.__('Don’t be stupid - backup your database before proceeding!').'

'; + echo '
'; + wp_nonce_field('import-jkw'); + echo '

'; + echo '
'; + echo '
'; + wp_nonce_field('import-jkw'); + echo '

'; + echo '
'; + echo '
'; + } + + function dispatch() { + if ( empty($_GET['step']) ) + $step = 0; + else + $step = absint($_GET['step']); + + // load the header + $this->header(); + + switch ( $step ) { + case 0 : + $this->greet(); + break; + case 1 : + check_admin_referer('import-jkw'); + $this->check_V1_post_keyword( true ); + break; + case 2 : + check_admin_referer('import-jkw'); + $this->check_V1_post_keyword( false ); + break; + case 3 : + check_admin_referer('import-jkw'); + $this->check_V2_post_keyword( true ); + break; + case 4 : + check_admin_referer('import-jkw'); + $this->check_V2_post_keyword( false ); + break; + case 5: + check_admin_referer('import-jkw'); + $this->cleanup_V2_import(); + break; + case 6: + $this->done(); + break; + } + + // load the footer + $this->footer(); + } + + function check_V1_post_keyword($precheck = true) { + global $wpdb; + + echo '
'; + echo '

'.__('Reading Jerome’s Keywords Tags…').'

'; + + // import Jerome's Keywords tags + $metakeys = $wpdb->get_results("SELECT post_id, meta_id, meta_key, meta_value FROM $wpdb->postmeta WHERE $wpdb->postmeta.meta_key = 'keywords'"); + if ( !is_array($metakeys)) { + echo '

' . __('No Tags Found!') . '

'; + return false; + } else { + $count = count($metakeys); + echo '

' . sprintf( _n('Done! %s post with tags were read.', 'Done! %s posts with tags were read.', $count), $count ) . '

'; + echo '
    '; + foreach ( $metakeys as $post_meta ) { + if ( $post_meta->meta_value != '' ) { + $post_keys = explode(',', $post_meta->meta_value); + foreach ( $post_keys as $keyword ) { + $keyword = addslashes(trim($keyword)); + if ( '' != $keyword ) { + echo '
  • ' . $post_meta->post_id . ' - ' . $keyword . '
  • '; + if ( !$precheck ) + wp_add_post_tags($post_meta->post_id, $keyword); + } + } + } + if ( !$precheck ) + delete_post_meta($post_meta->post_id, 'keywords'); + } + echo '
'; + } + + echo '
'; + wp_nonce_field('import-jkw'); + echo '

'; + echo '
'; + echo '
'; + } + + function check_V2_post_keyword($precheck = true) { + global $wpdb; + + echo '
'; + echo '

'.__('Reading Jerome’s Keywords Tags…').'

'; + + // import Jerome's Keywords tags + $tablename = $wpdb->prefix . substr(get_option('jkeywords_keywords_table'), 1, -1); + $metakeys = $wpdb->get_results("SELECT post_id, tag_name FROM $tablename"); + if ( !is_array($metakeys) ) { + echo '

' . __('No Tags Found!') . '

'; + return false; + } else { + $count = count($metakeys); + echo '

' . sprintf( _n('Done! %s tag were read.', 'Done! %s tags were read.', $count), $count ) . '

'; + echo '
    '; + foreach ( $metakeys as $post_meta ) { + $keyword = addslashes(trim($post_meta->tag_name)); + if ( $keyword != '' ) { + echo '
  • ' . $post_meta->post_id . ' - ' . $keyword . '
  • '; + if ( !$precheck ) + wp_add_post_tags($post_meta->post_id, $keyword); + } + } + echo '
'; + } + echo '
'; + wp_nonce_field('import-jkw'); + echo '

'; + echo '
'; + echo '
'; + } + + function cleanup_V2_import() { + global $wpdb; + + /* options from V2.0a (jeromes-keywords.php) */ + $options = array('version', 'keywords_table', 'query_varname', 'template', 'meta_always_include', 'meta_includecats', 'meta_autoheader', 'search_strict', 'use_feed_cats', 'post_linkformat', 'post_tagseparator', 'post_includecats', 'post_notagstext', 'cloud_linkformat', 'cloud_tagseparator', 'cloud_includecats', 'cloud_sortorder', 'cloud_displaymax', 'cloud_displaymin', 'cloud_scalemax', 'cloud_scalemin'); + + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . substr(get_option('jkeywords_keywords_table'), 1, -1)); + + foreach ( $options as $o ) + delete_option('jkeywords_' . $o); + + $this->done(); + } + + function done() { + echo '
'; + echo '

'.__('Import Complete!').'

'; + echo '
'; + } + + function JeromesKeyword_Import() { + } + +} + +// create the import object +$jkw_import = new JeromesKeyword_Import(); + +// add it to the import page! +register_importer('jkw', 'Jerome’s Keywords', __('Import Jerome’s Keywords into WordPress tags.'), array($jkw_import, 'dispatch')); + +?> diff --git a/wp-admin/import/livejournal.php b/wp-admin/import/livejournal.php new file mode 100644 index 0000000..bfebe71 --- /dev/null +++ b/wp-admin/import/livejournal.php @@ -0,0 +1,1054 @@ + 'aggravated', + '10' => 'discontent', + '100' => 'rushed', + '101' => 'contemplative', + '102' => 'nerdy', + '103' => 'geeky', + '104' => 'cynical', + '105' => 'quixotic', + '106' => 'crazy', + '107' => 'creative', + '108' => 'artistic', + '109' => 'pleased', + '11' => 'energetic', + '110' => 'bitchy', + '111' => 'guilty', + '112' => 'irritated', + '113' => 'blank', + '114' => 'apathetic', + '115' => 'dorky', + '116' => 'impressed', + '117' => 'naughty', + '118' => 'predatory', + '119' => 'dirty', + '12' => 'enraged', + '120' => 'giddy', + '121' => 'surprised', + '122' => 'shocked', + '123' => 'rejected', + '124' => 'numb', + '125' => 'cheerful', + '126' => 'good', + '127' => 'distressed', + '128' => 'intimidated', + '129' => 'crushed', + '13' => 'enthralled', + '130' => 'devious', + '131' => 'thankful', + '132' => 'grateful', + '133' => 'jealous', + '134' => 'nervous', + '14' => 'exhausted', + '15' => 'happy', + '16' => 'high', + '17' => 'horny', + '18' => 'hungry', + '19' => 'infuriated', + '2' => 'angry', + '20' => 'irate', + '21' => 'jubilant', + '22' => 'lonely', + '23' => 'moody', + '24' => 'pissed off', + '25' => 'sad', + '26' => 'satisfied', + '27' => 'sore', + '28' => 'stressed', + '29' => 'thirsty', + '3' => 'annoyed', + '30' => 'thoughtful', + '31' => 'tired', + '32' => 'touched', + '33' => 'lazy', + '34' => 'drunk', + '35' => 'ditzy', + '36' => 'mischievous', + '37' => 'morose', + '38' => 'gloomy', + '39' => 'melancholy', + '4' => 'anxious', + '40' => 'drained', + '41' => 'excited', + '42' => 'relieved', + '43' => 'hopeful', + '44' => 'amused', + '45' => 'determined', + '46' => 'scared', + '47' => 'frustrated', + '48' => 'indescribable', + '49' => 'sleepy', + '5' => 'bored', + '51' => 'groggy', + '52' => 'hyper', + '53' => 'relaxed', + '54' => 'restless', + '55' => 'disappointed', + '56' => 'curious', + '57' => 'mellow', + '58' => 'peaceful', + '59' => 'bouncy', + '6' => 'confused', + '60' => 'nostalgic', + '61' => 'okay', + '62' => 'rejuvenated', + '63' => 'complacent', + '64' => 'content', + '65' => 'indifferent', + '66' => 'silly', + '67' => 'flirty', + '68' => 'calm', + '69' => 'refreshed', + '7' => 'crappy', + '70' => 'optimistic', + '71' => 'pessimistic', + '72' => 'giggly', + '73' => 'pensive', + '74' => 'uncomfortable', + '75' => 'lethargic', + '76' => 'listless', + '77' => 'recumbent', + '78' => 'exanimate', + '79' => 'embarrassed', + '8' => 'cranky', + '80' => 'envious', + '81' => 'sympathetic', + '82' => 'sick', + '83' => 'hot', + '84' => 'cold', + '85' => 'worried', + '86' => 'loved', + '87' => 'awake', + '88' => 'working', + '89' => 'productive', + '9' => 'depressed', + '90' => 'accomplished', + '91' => 'busy', + '92' => 'blah', + '93' => 'full', + '95' => 'grumpy', + '96' => 'weird', + '97' => 'nauseated', + '98' => 'ecstatic', + '99' => 'chipper' ); + + function header() { + echo '
'; + screen_icon(); + echo '

' . __( 'Import LiveJournal' ) . '

'; + } + + function footer() { + echo '
'; + } + + function greet() { + ?> +
+
+ + + +

+

+ +

+

+

+ + + +

+

+ + + + + + + + + + + + + +
+ +

+

+

+ + + + + + + +
+ +

WARNING: This can take a really long time if you have a lot of entries in your LiveJournal, or a lot of comments. Ideally, you should only start this process if you can leave your computer alone while it finishes the import." ) ?>

+ +

+ +

+ +

NOTE: If the import process is interrupted for any reason, come back to this page and it will continue from where it stopped automatically.' ) ?>

+ + + +
+
+ lj_ixr( 'syncitems', array( 'ver' => 1, 'lastsync' => $lastsync ) ); + if ( is_wp_error( $synclist ) ) + return $synclist; + + // Keep track of if we've downloaded everything + $total = $synclist['total']; + $count = $synclist['count']; + + foreach ( $synclist['syncitems'] as $event ) { + if ( substr( $event['item'], 0, 2 ) == 'L-' ) { + $sync_item_times[ str_replace( 'L-', '', $event['item'] ) ] = $event['time']; + if ( $event['time'] > $lastsync ) { + $lastsync = $event['time']; + update_option( 'ljapi_lastsync', $lastsync ); + } + } + } + } while ( $total > $count ); + // endwhile - all post meta is cached locally + unset( $synclist ); + update_option( 'ljapi_sync_item_times', $sync_item_times ); + update_option( 'ljapi_total', $total ); + update_option( 'ljapi_count', $count ); + + echo '

' . __( 'Post metadata has been downloaded, proceeding with posts...' ) . '

'; + } + + function download_post_bodies() { + $imported_count = (int) get_option( 'ljapi_imported_count' ); + $sync_item_times = get_option( 'ljapi_sync_item_times' ); + $lastsync = get_option( 'ljapi_lastsync_posts' ); + if ( !$lastsync ) + update_option( 'ljapi_lastsync_posts', date( 'Y-m-d H:i:s', 0 ) ); + + $count = 0; + echo '
    '; + do { + $lastsync = date( 'Y-m-d H:i:s', strtotime( get_option( 'ljapi_lastsync_posts' ) ) ); + + // Get the batch of items that match up with the syncitems list + $itemlist = $this->lj_ixr( 'getevents', array( 'ver' => 1, + 'selecttype' => 'syncitems', + 'lineendings' => 'pc', + 'lastsync' => $lastsync ) ); + if ( is_wp_error( $itemlist ) ) + return $itemlist; + + if ( $num = count( $itemlist['events'] ) ) { + for ( $e = 0; $e < count( $itemlist['events'] ); $e++ ) { + $event = $itemlist['events'][$e]; + $imported_count++; + $inserted = $this->import_post( $event ); + if ( is_wp_error( $inserted ) ) + return $inserted; + if ( $sync_item_times[ $event['itemid'] ] > $lastsync ) + $lastsync = $sync_item_times[ $event['itemid'] ]; + wp_cache_flush(); + } + update_option( 'ljapi_lastsync_posts', $lastsync ); + update_option( 'ljapi_imported_count', $imported_count ); + update_option( 'ljapi_last_sync_count', $num ); + } + $count++; + } while ( $num > 0 && $count < 3 ); // Doing up to 3 requests at a time to avoid memory problems + + // Used so that step1 knows when to stop posting back on itself + update_option( 'ljapi_last_sync_count', $num ); + + // Counter just used to show progress to user + update_option( 'ljapi_post_batch', ( (int) get_option( 'ljapi_post_batch' ) + 1 ) ); + + echo '
'; + } + + function import_post( $post ) { + global $wpdb; + + // Make sure we haven't already imported this one + if ( $this->get_wp_post_ID( $post['itemid'] ) ) + return; + + $user = wp_get_current_user(); + $post_author = $user->ID; + $post['security'] = !empty( $post['security'] ) ? $post['security'] : ''; + $post_status = ( 'private' == trim( $post['security'] ) ) ? 'private' : 'publish'; // Only me + $post_password = ( 'usemask' == trim( $post['security'] ) ) ? $this->protected_password : ''; // "Friends" via password + + // For some reason, LJ sometimes sends a date as "2004-04-1408:38:00" (no space btwn date/time) + $post_date = $post['eventtime']; + if ( 18 == strlen( $post_date ) ) + $post_date = substr( $post_date, 0, 10 ) . ' ' . substr( $post_date, 10 ); + + // Cleaning up and linking the title + $post_title = isset( $post['subject'] ) ? trim( $post['subject'] ) : ''; + $post_title = $this->translate_lj_user( $post_title ); // Translate it, but then we'll strip the link + $post_title = strip_tags( $post_title ); // Can't have tags in the title in WP + $post_title = $wpdb->escape( $post_title ); + + // Clean up content + $post_content = $post['event']; + $post_content = preg_replace_callback( '|<(/?[A-Z]+)|', create_function( '$match', 'return "<" . strtolower( $match[1] );' ), $post_content ); + // XHTMLize some tags + $post_content = str_replace( '
', '
', $post_content ); + $post_content = str_replace( '
', '
', $post_content ); + // lj-cut ==> + $post_content = preg_replace( '||is', '', $post_content ); + $post_content = str_replace( array( '', '' ), array( '', '' ), $post_content ); + $first = strpos( $post_content, '|sUi', '', substr( $post_content, $first + 1 ) ); + // lj-user ==> a href + $post_content = $this->translate_lj_user( $post_content ); + //$post_content = force_balance_tags( $post_content ); + $post_content = $wpdb->escape( $post_content ); + + // Handle any tags associated with the post + $tags_input = !empty( $post['props']['taglist'] ) ? $post['props']['taglist'] : ''; + + // Check if comments are closed on this post + $comment_status = !empty( $post['props']['opt_nocomments'] ) ? 'closed' : 'open'; + + echo '
  • '; + if ( $post_id = post_exists( $post_title, $post_content, $post_date ) ) { + printf( __( 'Post %s already exists.' ), stripslashes( $post_title ) ); + } else { + printf( __( 'Imported post %s...' ), stripslashes( $post_title ) ); + $postdata = compact( 'post_author', 'post_date', 'post_content', 'post_title', 'post_status', 'post_password', 'tags_input', 'comment_status' ); + $post_id = wp_insert_post( $postdata, true ); + if ( is_wp_error( $post_id ) ) { + if ( 'empty_content' == $post_id->get_error_code() ) + return; // Silent skip on "empty" posts + return $post_id; + } + if ( !$post_id ) { + _e( 'Couldn’t get post ID (creating post failed!)' ); + echo '
  • '; + return new WP_Error( 'insert_post_failed', __( 'Failed to create post.' ) ); + } + + // Handle all the metadata for this post + $this->insert_postmeta( $post_id, $post ); + } + echo ''; + } + + // Convert lj-user tags to links to that user + function translate_lj_user( $str ) { + return preg_replace( '||', '$1', $str ); + } + + function insert_postmeta( $post_id, $post ) { + // Need the original LJ id for comments + add_post_meta( $post_id, 'lj_itemid', $post['itemid'] ); + + // And save the permalink on LJ in case we want to link back or something + add_post_meta( $post_id, 'lj_permalink', $post['url'] ); + + // Supports the following "props" from LJ, saved as lj_ in wp_postmeta + // Adult Content - adult_content + // Location - current_coords + current_location + // Mood - current_mood (translated from current_moodid) + // Music - current_music + // Userpic - picture_keyword + foreach ( array( 'adult_content', 'current_coords', 'current_location', 'current_moodid', 'current_music', 'picture_keyword' ) as $prop ) { + if ( !empty( $post['props'][$prop] ) ) { + if ( 'current_moodid' == $prop ) { + $prop = 'current_mood'; + $val = $this->moods[ $post['props']['current_moodid'] ]; + } else { + $val = $post['props'][$prop]; + } + add_post_meta( $post_id, 'lj_' . $prop, $val ); + } + } + } + + // Set up a session (authenticate) with LJ + function get_session() { + // Get a session via XMLRPC + $cookie = $this->lj_ixr( 'sessiongenerate', array( 'ver' => 1, 'expiration' => 'short' ) ); + if ( is_wp_error( $cookie ) ) + return new WP_Error( 'cookie', __( 'Could not get a cookie from LiveJournal. Please try again soon.' ) ); + return new WP_Http_Cookie( array( 'name' => 'ljsession', 'value' => $cookie['ljsession'] ) ); + } + + // Loops through and gets comment meta from LJ in batches + function download_comment_meta() { + $cookie = $this->get_session(); + if ( is_wp_error( $cookie ) ) + return $cookie; + + // Load previous state (if any) + $this->usermap = (array) get_option( 'ljapi_usermap' ); + $maxid = get_option( 'ljapi_maxid' ) ? get_option( 'ljapi_maxid' ) : 1; + $highest_id = get_option( 'ljapi_highest_id' ) ? get_option( 'ljapi_highest_id' ) : 0; + + // We need to loop over the metadata request until we have it all + while ( $maxid > $highest_id ) { + // Now get the meta listing + $results = wp_remote_get( $this->comments_url . '?get=comment_meta&startid=' . ( $highest_id + 1 ), + array( 'cookies' => array( $cookie ), 'timeout' => 20 ) ); + if ( is_wp_error( $results ) ) + return new WP_Error( 'comment_meta', __( 'Failed to retrieve comment meta information from LiveJournal. Please try again soon.' ) ); + + $results = wp_remote_retrieve_body( $results ); + + // Get the maxid so we know if we have them all yet + preg_match( '|(\d+)|', $results, $matches ); + if ( 0 == $matches[1] ) { + // No comment meta = no comments for this journal + echo '

    ' . __( 'You have no comments to import!' ) . '

    '; + update_option( 'ljapi_highest_id', 1 ); + update_option( 'ljapi_highest_comment_id', 1 ); + return false; // Bail out of comment importing entirely + } + $maxid = !empty( $matches[1] ) ? $matches[1] : $maxid; + + // Parse comments and get highest id available + preg_match_all( '| $highest_id ) + $highest_id = $id; + } + + // Parse out the list of user mappings, and add it to the known list + preg_match_all( '||', $results, $matches ); + foreach ( $matches[1] as $count => $userid ) + $this->usermap[$userid] = $matches[2][$count]; // need this in memory for translating ids => names + + wp_cache_flush(); + } + // endwhile - should have seen all comment meta at this point + + update_option( 'ljapi_usermap', $this->usermap ); + update_option( 'ljapi_maxid', $maxid ); + update_option( 'ljapi_highest_id', $highest_id ); + + echo '

    ' . __( ' Comment metadata downloaded successfully, proceeding with comment bodies...' ) . '

    '; + + return true; + } + + // Downloads actual comment bodies from LJ + // Inserts them all directly to the DB, with additional info stored in "spare" fields + function download_comment_bodies() { + global $wpdb; + $cookie = $this->get_session(); + if ( is_wp_error( $cookie ) ) + return $cookie; + + // Load previous state (if any) + $this->usermap = (array) get_option( 'ljapi_usermap' ); + $maxid = get_option( 'ljapi_maxid' ) ? (int) get_option( 'ljapi_maxid' ) : 1; + $highest_id = (int) get_option( 'ljapi_highest_comment_id' ); + $loop = 0; + while ( $maxid > $highest_id && $loop < 5 ) { // We do 5 loops per call to avoid memory limits + $loop++; + + // Get a batch of comments, using the highest_id we've already got as a starting point + $results = wp_remote_get( $this->comments_url . '?get=comment_body&startid=' . ( $highest_id + 1 ), + array( 'cookies' => array( $cookie ), 'timeout' => 20 ) ); + if ( is_wp_error( $results ) ) + return new WP_Error( 'comment_bodies', __( 'Failed to retrieve comment bodies from LiveJournal. Please try again soon.' ) ); + + $results = wp_remote_retrieve_body( $results ); + + // Parse out each comment and insert directly + preg_match_all( '||iUs', $results, $matches ); + for ( $c = 0; $c < count( $matches[0] ); $c++ ) { + // Keep track of highest id seen + if ( $matches[1][$c] > $highest_id ) { + $highest_id = $matches[1][$c]; + update_option( 'ljapi_highest_comment_id', $highest_id ); + } + + $comment = $matches[0][$c]; + + // Filter out any captured, deleted comments (nothing useful to import) + $comment = preg_replace( '||is', '', $comment ); + + // Parse this comment into an array and insert + $comment = $this->parse_comment( $comment ); + $id = wp_insert_comment( $comment ); + + // Clear cache + clean_comment_cache( $id ); + } + + // Clear cache to preseve memory + wp_cache_flush(); + } + // endwhile - all comments downloaded and ready for bulk processing + + // Counter just used to show progress to user + update_option( 'ljapi_comment_batch', ( (int) get_option( 'ljapi_comment_batch' ) + 1 ) ); + + return true; + } + + // Takes a block of XML and parses out all the elements of the comment + function parse_comment( $comment ) { + global $wpdb; + + // Get the top-level attributes + preg_match( '|]+)>|i', $comment, $attribs ); + preg_match( '| id=\'(\d+)\'|i', $attribs[1], $matches ); + $lj_comment_ID = $matches[1]; + preg_match( '| jitemid=\'(\d+)\'|i', $attribs[1], $matches ); + $lj_comment_post_ID = $matches[1]; + preg_match( '| posterid=\'(\d+)\'|i', $attribs[1], $matches ); + $comment_author_ID = isset( $matches[1] ) ? $matches[1] : 0; + preg_match( '| parentid=\'(\d+)\'|i', $attribs[1], $matches ); // optional + $lj_comment_parent = isset( $matches[1] ) ? $matches[1] : 0; + preg_match( '| state=\'([SDFA])\'|i', $attribs[1], $matches ); // optional + $lj_comment_state = isset( $matches[1] ) ? $matches[1] : 'A'; + + // Clean up "subject" - this will become the first line of the comment in WP + preg_match( '|(.*)|is', $comment, $matches ); + if ( isset( $matches[1] ) ) { + $comment_subject = $wpdb->escape( trim( $matches[1] ) ); + if ( 'Re:' == $comment_subject ) + $comment_subject = ''; + } + + // Get the body and HTMLize it + preg_match( '|(.*)|is', $comment, $matches ); + $comment_content = !empty( $comment_subject ) ? $comment_subject . "\n\n" . $matches[1] : $matches[1]; + $comment_content = @html_entity_decode( $comment_content, ENT_COMPAT, get_option('blog_charset') ); + $comment_content = str_replace( ''', "'", $comment_content ); + $comment_content = wpautop( $comment_content ); + $comment_content = str_replace( '
    ', '
    ', $comment_content ); + $comment_content = str_replace( '
    ', '
    ', $comment_content ); + $comment_content = preg_replace_callback( '|<(/?[A-Z]+)|', create_function( '$match', 'return "<" . strtolower( $match[1] );' ), $comment_content ); + $comment_content = $wpdb->escape( trim( $comment_content ) ); + + // Get and convert the date + preg_match( '|(.*)|i', $comment, $matches ); + $comment_date = trim( str_replace( array( 'T', 'Z' ), ' ', $matches[1] ) ); + + // Grab IP if available + preg_match( '|(.*)|i', $comment, $matches ); // optional + $comment_author_IP = isset( $matches[1] ) ? $matches[1] : ''; + + // Try to get something useful for the comment author, especially if it was "my" comment + $author = ( empty( $comment_author_ID ) || empty( $this->usermap[$comment_author_ID] ) || substr( $this->usermap[$comment_author_ID], 0, 4 ) == 'ext_' ) ? __( 'Anonymous' ) : $this->usermap[$comment_author_ID]; + if ( get_option( 'ljapi_username' ) == $author ) { + $user = wp_get_current_user(); + $user_id = $user->ID; + $author = $user->display_name; + $url = trailingslashit( get_option( 'home' ) ); + } else { + $user_id = 0; + $url = ( __( 'Anonymous' ) == $author ) ? '' : 'http://' . $author . '.livejournal.com/'; + } + + // Send back the array of details + return array( 'lj_comment_ID' => $lj_comment_ID, + 'lj_comment_post_ID' => $lj_comment_post_ID, + 'lj_comment_parent' => ( !empty( $lj_comment_parent ) ? $lj_comment_parent : 0 ), + 'lj_comment_state' => $lj_comment_state, + 'comment_post_ID' => $this->get_wp_post_ID( $lj_comment_post_ID ), + 'comment_author' => $author, + 'comment_author_url' => $url, + 'comment_author_email' => '', + 'comment_content' => $comment_content, + 'comment_date' => $comment_date, + 'comment_author_IP' => ( !empty( $comment_author_IP ) ? $comment_author_IP : '' ), + 'comment_approved' => ( in_array( $lj_comment_state, array( 'A', 'F' ) ) ? 1 : 0 ), + 'comment_karma' => $lj_comment_ID, // Need this and next value until rethreading is done + 'comment_agent' => $lj_comment_parent, + 'comment_type' => 'livejournal', // Custom type, so we can find it later for processing + 'user_ID' => $user_id + ); + } + + + // Gets the post_ID that a LJ post has been saved as within WP + function get_wp_post_ID( $post ) { + global $wpdb; + + if ( empty( $this->postmap[$post] ) ) + $this->postmap[$post] = (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'lj_itemid' AND meta_value = %d", $post ) ); + + return $this->postmap[$post]; + } + + // Gets the comment_ID that a LJ comment has been saved as within WP + function get_wp_comment_ID( $comment ) { + global $wpdb; + if ( empty( $this->commentmap[$comment] ) ) + $this->commentmap[$comment] = $wpdb->get_var( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_karma = %d", $comment ) ); + return $this->commentmap[$comment]; + } + + function lj_ixr() { + if ( $challenge = $this->ixr->query( 'LJ.XMLRPC.getchallenge' ) ) { + $challenge = $this->ixr->getResponse(); + } + if ( isset( $challenge['challenge'] ) ) { + $params = array( 'username' => $this->username, + 'auth_method' => 'challenge', + 'auth_challenge' => $challenge['challenge'], + 'auth_response' => md5( $challenge['challenge'] . md5( $this->password ) ) ); + } else { + return new WP_Error( 'IXR', __( 'LiveJournal is not responding to authentication requests. Please wait a while and then try again.' ) ); + } + + $args = func_get_args(); + $method = array_shift( $args ); + if ( isset( $args[0] ) ) + $params = array_merge( $params, $args[0] ); + if ( $this->ixr->query( 'LJ.XMLRPC.' . $method, $params ) ) { + return $this->ixr->getResponse(); + } else { + return new WP_Error( 'IXR', __( 'XML-RPC Request Failed -- ' ) . $this->ixr->getErrorCode() . ': ' . $this->ixr->getErrorMessage() ); + } + } + + function dispatch() { + if ( empty( $_REQUEST['step'] ) ) + $step = 0; + else + $step = (int) $_REQUEST['step']; + + $this->header(); + + switch ( $step ) { + case -1 : + $this->cleanup(); + // Intentional no break + case 0 : + $this->greet(); + break; + case 1 : + case 2 : + case 3 : + check_admin_referer( 'lj-api-import' ); + $result = $this->{ 'step' . $step }(); + if ( is_wp_error( $result ) ) { + $this->throw_error( $result, $step ); + } + break; + } + + $this->footer(); + } + + // Technically the first half of step 1, this is separated to allow for AJAX + // calls. Sets up some variables and options and confirms authentication. + function setup() { + global $verified; + // Get details from form or from DB + if ( !empty( $_POST['lj_username'] ) && !empty( $_POST['lj_password'] ) ) { + // Store details for later + $this->username = $_POST['lj_username']; + $this->password = $_POST['lj_password']; + update_option( 'ljapi_username', $this->username ); + update_option( 'ljapi_password', $this->password ); + } else { + $this->username = get_option( 'ljapi_username' ); + $this->password = get_option( 'ljapi_password' ); + } + + // This is the password to set on protected posts + if ( !empty( $_POST['protected_password'] ) ) { + $this->protected_password = $_POST['protected_password']; + update_option( 'ljapi_protected_password', $this->protected_password ); + } else { + $this->protected_password = get_option( 'ljapi_protected_password' ); + } + + // Login to confirm the details are correct + if ( empty( $this->username ) || empty( $this->password ) ) { + ?> +

    and password so we can download your posts and comments.' ) ?>

    +

    + lj_ixr( 'login' ); + if ( is_wp_error( $verified ) ) { + if ( 100 == $this->ixr->getErrorCode() || 101 == $this->ixr->getErrorCode() ) { + delete_option( 'ljapi_username' ); + delete_option( 'ljapi_password' ); + delete_option( 'ljapi_protected_password' ); + ?> +

    +

    + ixr ) $this->ixr = new IXR_Client( $this->ixr_url, false, 80, 30 ); + if ( empty( $_POST['login'] ) ) { + // We're looping -- load some details from DB + $this->username = get_option( 'ljapi_username' ); + $this->password = get_option( 'ljapi_password' ); + $this->protected_password = get_option( 'ljapi_protected_password' ); + } else { + // First run (non-AJAX) + $setup = $this->setup(); + if ( !$setup ) { + return false; + } else if ( is_wp_error( $setup ) ) { + $this->throw_error( $setup, 1 ); + return false; + } + } + + echo '
    '; + echo '

    ' . __( 'Importing Posts' ) . '

    '; + echo '

    ' . __( 'We’re downloading and importing your LiveJournal posts...' ) . '

    '; + if ( get_option( 'ljapi_post_batch' ) && count( get_option( 'ljapi_sync_item_times' ) ) ) { + $batch = count( get_option( 'ljapi_sync_item_times' ) ); + $batch = $count > 300 ? ceil( $batch / 300 ) : 1; + echo '

    ' . sprintf( __( 'Imported post batch %d of approximately %d' ), ( get_option( 'ljapi_post_batch' ) + 1 ), $batch ) . '

    '; + } + ob_flush(); flush(); + + if ( !get_option( 'ljapi_lastsync' ) || '1900-01-01 00:00:00' == get_option( 'ljapi_lastsync' ) ) { + // We haven't downloaded meta yet, so do that first + $result = $this->download_post_meta(); + if ( is_wp_error( $result ) ) { + $this->throw_error( $result, 1 ); + return false; + } + } + + // Download a batch of actual posts + $result = $this->download_post_bodies(); + if ( is_wp_error( $result ) ) { + if ( 406 == $this->ixr->getErrorCode() ) { + ?> +

    +

    + next_step( 1, __( 'Try Again' ) ); + return false; + } else { + $this->throw_error( $result, 1 ); + return false; + } + } + + if ( get_option( 'ljapi_last_sync_count' ) > 0 ) { + ?> +
    + + +

    +
    + auto_ajax( 'ljapi-auto-repost', 'auto-message', 0 ); ?> + ' . __( 'Your posts have all been imported, but wait – there’s more! Now we need to download & import your comments.' ) . '

    '; + echo $this->next_step( 2, __( 'Download my comments »' ) ); + $this->auto_submit(); + } + echo '
    '; + } + + // Download comments to local XML + function step2() { + set_time_limit( 0 ); + update_option( 'ljapi_step', 2 ); + $this->username = get_option( 'ljapi_username' ); + $this->password = get_option( 'ljapi_password' ); + $this->ixr = new IXR_Client( $this->ixr_url, false, 80, 30 ); + + echo '
    '; + echo '

    ' . __( 'Downloading Comments' ) . '

    '; + echo '

    ' . __( 'Now we will download your comments so we can import them (this could take a long time if you have lots of comments)...' ) . '

    '; + ob_flush(); flush(); + + if ( !get_option( 'ljapi_usermap' ) ) { + // We haven't downloaded meta yet, so do that first + $result = $this->download_comment_meta(); + if ( is_wp_error( $result ) ) { + $this->throw_error( $result, 2 ); + return false; + } + } + + // Download a batch of actual comments + $result = $this->download_comment_bodies(); + if ( is_wp_error( $result ) ) { + $this->throw_error( $result, 2 ); + return false; + } + + $maxid = get_option( 'ljapi_maxid' ) ? (int) get_option( 'ljapi_maxid' ) : 1; + $highest_id = (int) get_option( 'ljapi_highest_comment_id' ); + if ( $maxid > $highest_id ) { + $batch = $maxid > 5000 ? ceil( $maxid / 5000 ) : 1; + ?> +
    +

    approximately %d' ), get_option( 'ljapi_comment_batch' ), $batch ) ?>

    + + +

    +
    + auto_ajax( 'ljapi-auto-repost', 'auto-message', 0 ); ?> + ' . __( 'Your comments have all been imported now, but we still need to rebuild your conversation threads.' ) . '

    '; + echo $this->next_step( 3, __( 'Rebuild my comment threads »' ) ); + $this->auto_submit(); + } + echo '
    '; + } + + // Re-thread comments already in the DB + function step3() { + global $wpdb; + set_time_limit( 0 ); + update_option( 'ljapi_step', 3 ); + + echo '
    '; + echo '

    ' . __( 'Threading Comments' ) . '

    '; + echo '

    ' . __( 'We are now re-building the threading of your comments (this can also take a while if you have lots of comments)...' ) . '

    '; + ob_flush(); flush(); + + // Only bother adding indexes if they have over 5000 comments (arbitrary number) + $imported_comments = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_type = 'livejournal'" ); + $added_indices = false; + if ( 5000 < $imported_comments ) { + include_once(ABSPATH . 'wp-admin/includes/upgrade.php'); + $added_indices = true; + add_clean_index( $wpdb->comments, 'comment_type' ); + add_clean_index( $wpdb->comments, 'comment_karma' ); + add_clean_index( $wpdb->comments, 'comment_agent' ); + } + + // Get LJ comments, which haven't been threaded yet, 5000 at a time and thread them + while ( $comments = $wpdb->get_results( "SELECT comment_ID, comment_agent FROM {$wpdb->comments} WHERE comment_type = 'livejournal' AND comment_agent != '0' LIMIT 5000", OBJECT ) ) { + foreach ( $comments as $comment ) { + $wpdb->update( $wpdb->comments, + array( 'comment_parent' => $this->get_wp_comment_ID( $comment->comment_agent ), 'comment_type' => 'livejournal-done' ), + array( 'comment_ID' => $comment->comment_ID ) ); + } + wp_cache_flush(); + $wpdb->flush(); + } + + // Revert the comments table back to normal and optimize it to reclaim space + if ( $added_indices ) { + drop_index( $wpdb->comments, 'comment_type' ); + drop_index( $wpdb->comments, 'comment_karma' ); + drop_index( $wpdb->comments, 'comment_agent' ); + $wpdb->query( "OPTIMIZE TABLE {$wpdb->comments}" ); + } + + // Clean up database and we're out + $this->cleanup(); + do_action( 'import_done', 'livejournal' ); + if ( $imported_comments > 1 ) + echo '

    ' . sprintf( __( "Successfully re-threaded %s comments." ), number_format( $imported_comments ) ) . '

    '; + echo '

    '; + printf( __( 'All done. Have fun!' ), get_option( 'home' ) ); + echo '

    '; + echo '
    '; + } + + // Output an error message with a button to try again. + function throw_error( $error, $step ) { + echo '

    ' . $error->get_error_message() . '

    '; + echo $this->next_step( $step, __( 'Try Again' ) ); + } + + // Returns the HTML for a link to the next page + function next_step( $next_step, $label, $id = 'ljapi-next-form' ) { + $str = '
    '; + $str .= wp_nonce_field( 'lj-api-import', '_wpnonce', true, false ); + $str .= wp_referer_field( false ); + $str .= ''; + $str .= '

    '; + $str .= '
    '; + + return $str; + } + + // Automatically submit the specified form after $seconds + // Include a friendly countdown in the element with id=$msg + function auto_submit( $id = 'ljapi-next-form', $msg = 'auto-message', $seconds = 10 ) { + ?>update( $wpdb->comments, + array( 'comment_karma' => 0, 'comment_agent' => 'WP LJ Importer', 'comment_type' => '' ), + array( 'comment_type' => 'livejournal-done' ) ); + $wpdb->update( $wpdb->comments, + array( 'comment_karma' => 0, 'comment_agent' => 'WP LJ Importer', 'comment_type' => '' ), + array( 'comment_type' => 'livejournal' ) ); + } + + function LJ_API_Import() { + $this->__construct(); + } + + function __construct() { + // Nothing + } +} + +$lj_api_import = new LJ_API_Import(); + +register_importer( 'livejournal', __( 'LiveJournal' ), __( 'Import posts from LiveJournal using their API.' ), array( $lj_api_import, 'dispatch' ) ); +?> diff --git a/wp-admin/import/mt.php b/wp-admin/import/mt.php new file mode 100644 index 0000000..7b75020 --- /dev/null +++ b/wp-admin/import/mt.php @@ -0,0 +1,514 @@ +'; + screen_icon(); + echo '

    '.__('Import Movable Type or TypePad').'

    '; + } + + function footer() { + echo ''; + } + + function greet() { + $this->header(); +?> +
    +

    mt-export.txt in your /wp-content/ directory and then click "Import mt-export.txt"'); ?>

    + + +
    + + +

    + +mt-export.txt in your /wp-content/ directory'); ?>

    +

    + +

    +
    +

    out of memory error try splitting up the import file into pieces.'); ?>

    +
    +footer(); + } + + function users_form($n) { + global $wpdb; + $users = $wpdb->get_results("SELECT * FROM $wpdb->users ORDER BY ID"); +?> + has_gzip() ) + return gzopen($filename, $mode); + return fopen($filename, $mode); + } + + function feof($fp) { + if ( $this->has_gzip() ) + return gzeof($fp); + return feof($fp); + } + + function fgets($fp, $len=8192) { + if ( $this->has_gzip() ) + return gzgets($fp, $len); + return fgets($fp, $len); + } + + function fclose($fp) { + if ( $this->has_gzip() ) + return gzclose($fp); + return fclose($fp); + } + + //function to check the authorname and do the mapping + function checkauthor($author) { + //mtnames is an array with the names in the mt import file + $pass = wp_generate_password(); + if (!(in_array($author, $this->mtnames))) { //a new mt author name is found + ++ $this->j; + $this->mtnames[$this->j] = $author; //add that new mt author name to an array + $user_id = username_exists($this->newauthornames[$this->j]); //check if the new author name defined by the user is a pre-existing wp user + if (!$user_id) { //banging my head against the desk now. + if ($this->newauthornames[$this->j] == 'left_blank') { //check if the user does not want to change the authorname + $user_id = wp_create_user($author, $pass); + $this->newauthornames[$this->j] = $author; //now we have a name, in the place of left_blank. + } else { + $user_id = wp_create_user($this->newauthornames[$this->j], $pass); + } + } else { + return $user_id; // return pre-existing wp username if it exists + } + } else { + $key = array_search($author, $this->mtnames); //find the array key for $author in the $mtnames array + $user_id = username_exists($this->newauthornames[$key]); //use that key to get the value of the author's name from $newauthornames + } + + return $user_id; + } + + function get_mt_authors() { + $temp = array(); + $authors = array(); + + $handle = $this->fopen($this->file, 'r'); + if ( $handle == null ) + return false; + + $in_comment = false; + while ( $line = $this->fgets($handle) ) { + $line = trim($line); + + if ( 'COMMENT:' == $line ) + $in_comment = true; + else if ( '-----' == $line ) + $in_comment = false; + + if ( $in_comment || 0 !== strpos($line,"AUTHOR:") ) + continue; + + $temp[] = trim( substr($line, strlen("AUTHOR:")) ); + } + + //we need to find unique values of author names, while preserving the order, so this function emulates the unique_value(); php function, without the sorting. + $authors[0] = array_shift($temp); + $y = count($temp) + 1; + for ($x = 1; $x < $y; $x ++) { + $next = array_shift($temp); + if (!(in_array($next, $authors))) + array_push($authors, "$next"); + } + + $this->fclose($handle); + + return $authors; + } + + function get_authors_from_post() { + $formnames = array (); + $selectnames = array (); + + foreach ($_POST['user'] as $key => $line) { + $newname = trim(stripslashes($line)); + if ($newname == '') + $newname = 'left_blank'; //passing author names from step 1 to step 2 is accomplished by using POST. left_blank denotes an empty entry in the form. + array_push($formnames, "$newname"); + } // $formnames is the array with the form entered names + + foreach ($_POST['userselect'] as $user => $key) { + $selected = trim(stripslashes($key)); + array_push($selectnames, "$selected"); + } + + $count = count($formnames); + for ($i = 0; $i < $count; $i ++) { + if ($selectnames[$i] != '#NONE#') { //if no name was selected from the select menu, use the name entered in the form + array_push($this->newauthornames, "$selectnames[$i]"); + } else { + array_push($this->newauthornames, "$formnames[$i]"); + } + } + } + + function mt_authors_form() { +?> +
    + +

    +

    +

    italics. For each of these names, you can either pick an author in your WordPress installation from the menu, or enter a name for the author in the textbox.'); ?>

    +

    + get_mt_authors(); + echo '
      '; + echo '
      '; + wp_nonce_field('import-mt'); + $j = -1; + foreach ($authors as $author) { + ++ $j; + echo '
    1. '; + } + + echo '

      '.'
      '; + echo '
      '; + echo '
    '; + + } + + function select_authors() { + if ( $_POST['upload_type'] === 'ftp' ) { + $file['file'] = WP_CONTENT_DIR . '/mt-export.txt'; + if ( !file_exists($file['file']) ) + $file['error'] = __('mt-export.txt does not exist'); + } else { + $file = wp_import_handle_upload(); + } + if ( isset($file['error']) ) { + $this->header(); + echo '

    '.__('Sorry, there has been an error').'.

    '; + echo '

    ' . $file['error'] . '

    '; + $this->footer(); + return; + } + $this->file = $file['file']; + $this->id = (int) $file['id']; + + $this->mt_authors_form(); + } + + function save_post(&$post, &$comments, &$pings) { + // Reset the counter + set_time_limit(30); + $post = get_object_vars($post); + $post = add_magic_quotes($post); + $post = (object) $post; + + if ( $post_id = post_exists($post->post_title, '', $post->post_date) ) { + echo '
  • '; + printf(__('Post %s already exists.'), stripslashes($post->post_title)); + } else { + echo '
  • '; + printf(__('Importing post %s...'), stripslashes($post->post_title)); + + if ( '' != trim( $post->extended ) ) + $post->post_content .= "\n\n$post->extended"; + + $post->post_author = $this->checkauthor($post->post_author); //just so that if a post already exists, new users are not created by checkauthor + $post_id = wp_insert_post($post); + if ( is_wp_error( $post_id ) ) + return $post_id; + + // Add categories. + if ( 0 != count($post->categories) ) { + wp_create_categories($post->categories, $post_id); + } + + // Add tags or keywords + if ( 1 < strlen($post->post_keywords) ) { + // Keywords exist. + printf(__('
    Adding tags %s...'), stripslashes($post->post_keywords)); + wp_add_post_tags($post_id, $post->post_keywords); + } + } + + $num_comments = 0; + foreach ( $comments as $comment ) { + $comment = get_object_vars($comment); + $comment = add_magic_quotes($comment); + + if ( !comment_exists($comment['comment_author'], $comment['comment_date'])) { + $comment['comment_post_ID'] = $post_id; + $comment = wp_filter_comment($comment); + wp_insert_comment($comment); + $num_comments++; + } + } + + if ( $num_comments ) + printf(' '._n('(%s comment)', '(%s comments)', $num_comments), $num_comments); + + $num_pings = 0; + foreach ( $pings as $ping ) { + $ping = get_object_vars($ping); + $ping = add_magic_quotes($ping); + + if ( !comment_exists($ping['comment_author'], $ping['comment_date'])) { + $ping['comment_content'] = "{$ping['title']}\n\n{$ping['comment_content']}"; + $ping['comment_post_ID'] = $post_id; + $ping = wp_filter_comment($ping); + wp_insert_comment($ping); + $num_pings++; + } + } + + if ( $num_pings ) + printf(' '._n('(%s ping)', '(%s pings)', $num_pings), $num_pings); + + echo "
  • "; + //ob_flush();flush(); + } + + function process_posts() { + global $wpdb; + + $handle = $this->fopen($this->file, 'r'); + if ( $handle == null ) + return false; + + $context = ''; + $post = new StdClass(); + $comment = new StdClass(); + $comments = array(); + $ping = new StdClass(); + $pings = array(); + + echo "
      "; + + while ( $line = $this->fgets($handle) ) { + $line = trim($line); + + if ( '-----' == $line ) { + // Finishing a multi-line field + if ( 'comment' == $context ) { + $comments[] = $comment; + $comment = new StdClass(); + } else if ( 'ping' == $context ) { + $pings[] = $ping; + $ping = new StdClass(); + } + $context = ''; + } else if ( '--------' == $line ) { + // Finishing a post. + $context = ''; + $result = $this->save_post($post, $comments, $pings); + if ( is_wp_error( $result ) ) + return $result; + $post = new StdClass; + $comment = new StdClass(); + $ping = new StdClass(); + $comments = array(); + $pings = array(); + } else if ( 'BODY:' == $line ) { + $context = 'body'; + } else if ( 'EXTENDED BODY:' == $line ) { + $context = 'extended'; + } else if ( 'EXCERPT:' == $line ) { + $context = 'excerpt'; + } else if ( 'KEYWORDS:' == $line ) { + $context = 'keywords'; + } else if ( 'COMMENT:' == $line ) { + $context = 'comment'; + } else if ( 'PING:' == $line ) { + $context = 'ping'; + } else if ( 0 === strpos($line, "AUTHOR:") ) { + $author = trim( substr($line, strlen("AUTHOR:")) ); + if ( '' == $context ) + $post->post_author = $author; + else if ( 'comment' == $context ) + $comment->comment_author = $author; + } else if ( 0 === strpos($line, "TITLE:") ) { + $title = trim( substr($line, strlen("TITLE:")) ); + if ( '' == $context ) + $post->post_title = $title; + else if ( 'ping' == $context ) + $ping->title = $title; + } else if ( 0 === strpos($line, "STATUS:") ) { + $status = trim( strtolower( substr($line, strlen("STATUS:")) ) ); + if ( empty($status) ) + $status = 'publish'; + $post->post_status = $status; + } else if ( 0 === strpos($line, "ALLOW COMMENTS:") ) { + $allow = trim( substr($line, strlen("ALLOW COMMENTS:")) ); + if ( $allow == 1 ) + $post->comment_status = 'open'; + else + $post->comment_status = 'closed'; + } else if ( 0 === strpos($line, "ALLOW PINGS:") ) { + $allow = trim( substr($line, strlen("ALLOW PINGS:")) ); + if ( $allow == 1 ) + $post->ping_status = 'open'; + else + $post->ping_status = 'closed'; + } else if ( 0 === strpos($line, "CATEGORY:") ) { + $category = trim( substr($line, strlen("CATEGORY:")) ); + if ( '' != $category ) + $post->categories[] = $category; + } else if ( 0 === strpos($line, "PRIMARY CATEGORY:") ) { + $category = trim( substr($line, strlen("PRIMARY CATEGORY:")) ); + if ( '' != $category ) + $post->categories[] = $category; + } else if ( 0 === strpos($line, "DATE:") ) { + $date = trim( substr($line, strlen("DATE:")) ); + $date = strtotime($date); + $date = date('Y-m-d H:i:s', $date); + $date_gmt = get_gmt_from_date($date); + if ( '' == $context ) { + $post->post_modified = $date; + $post->post_modified_gmt = $date_gmt; + $post->post_date = $date; + $post->post_date_gmt = $date_gmt; + } else if ( 'comment' == $context ) { + $comment->comment_date = $date; + } else if ( 'ping' == $context ) { + $ping->comment_date = $date; + } + } else if ( 0 === strpos($line, "EMAIL:") ) { + $email = trim( substr($line, strlen("EMAIL:")) ); + if ( 'comment' == $context ) + $comment->comment_author_email = $email; + else + $ping->comment_author_email = ''; + } else if ( 0 === strpos($line, "IP:") ) { + $ip = trim( substr($line, strlen("IP:")) ); + if ( 'comment' == $context ) + $comment->comment_author_IP = $ip; + else + $ping->comment_author_IP = $ip; + } else if ( 0 === strpos($line, "URL:") ) { + $url = trim( substr($line, strlen("URL:")) ); + if ( 'comment' == $context ) + $comment->comment_author_url = $url; + else + $ping->comment_author_url = $url; + } else if ( 0 === strpos($line, "BLOG NAME:") ) { + $blog = trim( substr($line, strlen("BLOG NAME:")) ); + $ping->comment_author = $blog; + } else { + // Processing multi-line field, check context. + + if( !empty($line) ) + $line .= "\n"; + + if ( 'body' == $context ) { + $post->post_content .= $line; + } else if ( 'extended' == $context ) { + $post->extended .= $line; + } else if ( 'excerpt' == $context ) { + $post->post_excerpt .= $line; + } else if ( 'keywords' == $context ) { + $post->post_keywords .= $line; + } else if ( 'comment' == $context ) { + $comment->comment_content .= $line; + } else if ( 'ping' == $context ) { + $ping->comment_content .= $line; + } + } + } + + $this->fclose($handle); + + echo '
    '; + + wp_import_cleanup($this->id); + do_action('import_done', 'mt'); + + echo '

    '.sprintf(__('All done. Have fun!'), get_option('home')).'

    '; + } + + function import() { + $this->id = (int) $_GET['id']; + if ( $this->id == 0 ) + $this->file = WP_CONTENT_DIR . '/mt-export.txt'; + else + $this->file = get_attached_file($this->id); + $this->get_authors_from_post(); + $result = $this->process_posts(); + if ( is_wp_error( $result ) ) + return $result; + } + + function dispatch() { + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + + switch ($step) { + case 0 : + $this->greet(); + break; + case 1 : + check_admin_referer('import-upload'); + $this->select_authors(); + break; + case 2: + check_admin_referer('import-mt'); + $result = $this->import(); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + break; + } + } + + function MT_Import() { + // Nothing. + } +} + +$mt_import = new MT_Import(); + +register_importer('mt', __('Movable Type and TypePad'), __('Import posts and comments from a Movable Type or Typepad blog.'), array ($mt_import, 'dispatch')); +?> diff --git a/wp-admin/import/opml.php b/wp-admin/import/opml.php new file mode 100644 index 0000000..7f2e1dc --- /dev/null +++ b/wp-admin/import/opml.php @@ -0,0 +1,156 @@ + + * @author Mike Little + * @package WordPress + * @subpackage Administration + */ + +/** Load WordPress Administration Bootstrap */ +$parent_file = 'tools.php'; +$submenu_file = 'import.php'; +$title = __('Import Blogroll'); + +class OPML_Import { + + function dispatch() { + global $wpdb, $user_ID; +$step = $_POST['step']; +if (!$step) $step = 0; +?> + + +
    + +

    +
    + + +

    +
    + + +
    +

    + +
    + +
    +

    + +
    + +
    + +


    +

    + +

    +
    + +
    + +
    + +

    + false, 'test_type' => false); + $_FILES['userfile']['name'] .= '.txt'; + $file = wp_handle_upload($_FILES['userfile'], $overrides); + + if ( isset($file['error']) ) + wp_die($file['error']); + + $url = $file['url']; + $opml_url = $file['file']; + $blogrolling = false; + } + + global $opml, $updated_timestamp, $all_links, $map, $names, $urls, $targets, $descriptions, $feeds; + if ( isset($opml_url) && $opml_url != '' ) { + if ( $blogrolling === true ) { + $opml = wp_remote_fopen($opml_url); + } else { + $opml = file_get_contents($opml_url); + } + + /** Load OPML Parser */ + include_once('link-parse-opml.php'); + + $link_count = count($names); + for ( $i = 0; $i < $link_count; $i++ ) { + if ('Last' == substr($titles[$i], 0, 4)) + $titles[$i] = ''; + if ( 'http' == substr($titles[$i], 0, 4) ) + $titles[$i] = ''; + $link = array( 'link_url' => $urls[$i], 'link_name' => $wpdb->escape($names[$i]), 'link_category' => array($cat_id), 'link_description' => $wpdb->escape($descriptions[$i]), 'link_owner' => $user_ID, 'link_rss' => $feeds[$i]); + wp_insert_link($link); + echo sprintf('

    '.__('Inserted %s').'

    ', $names[$i]); + } +?> + +

    manage those links.'), $link_count, $cat_id, 'link-manager.php') ?>

    + +" . __("You need to supply your OPML url. Press back on your browser and try again") . "

    \n"; +} // end else + +if ( ! $blogrolling ) + do_action( 'wp_delete_file', $opml_url); + @unlink($opml_url); +?> +
    + diff --git a/wp-admin/import/rss.php b/wp-admin/import/rss.php new file mode 100644 index 0000000..9a85df3 --- /dev/null +++ b/wp-admin/import/rss.php @@ -0,0 +1,198 @@ +'; + screen_icon(); + echo '

    '.__('Import RSS').'

    '; + } + + function footer() { + echo ''; + } + + function unhtmlentities($string) { // From php.net for < 4.3 compat + $trans_tbl = get_html_translation_table(HTML_ENTITIES); + $trans_tbl = array_flip($trans_tbl); + return strtr($string, $trans_tbl); + } + + function greet() { + echo '
    '; + echo '

    '.__('Howdy! This importer allows you to extract posts from an RSS 2.0 file into your blog. This is useful if you want to import your posts from a system that is not handled by a custom import tool. Pick an RSS file to upload and click Import.').'

    '; + wp_import_upload_form("admin.php?import=rss&step=1"); + echo '
    '; + } + + function get_posts() { + global $wpdb; + + set_magic_quotes_runtime(0); + $datalines = file($this->file); // Read the file into an array + $importdata = implode('', $datalines); // squish it + $importdata = str_replace(array ("\r\n", "\r"), "\n", $importdata); + + preg_match_all('|(.*?)|is', $importdata, $this->posts); + $this->posts = $this->posts[1]; + $index = 0; + foreach ($this->posts as $post) { + preg_match('|(.*?)|is', $post, $post_title); + $post_title = str_replace(array(''), '', $wpdb->escape( trim($post_title[1]) )); + + preg_match('|(.*?)|is', $post, $post_date_gmt); + + if ($post_date_gmt) { + $post_date_gmt = strtotime($post_date_gmt[1]); + } else { + // if we don't already have something from pubDate + preg_match('|(.*?)|is', $post, $post_date_gmt); + $post_date_gmt = preg_replace('|([-+])([0-9]+):([0-9]+)$|', '\1\2\3', $post_date_gmt[1]); + $post_date_gmt = str_replace('T', ' ', $post_date_gmt); + $post_date_gmt = strtotime($post_date_gmt); + } + + $post_date_gmt = gmdate('Y-m-d H:i:s', $post_date_gmt); + $post_date = get_date_from_gmt( $post_date_gmt ); + + preg_match_all('|(.*?)|is', $post, $categories); + $categories = $categories[1]; + + if (!$categories) { + preg_match_all('|(.*?)|is', $post, $categories); + $categories = $categories[1]; + } + + $cat_index = 0; + foreach ($categories as $category) { + $categories[$cat_index] = $wpdb->escape($this->unhtmlentities($category)); + $cat_index++; + } + + preg_match('|(.*?)|is', $post, $guid); + if ($guid) + $guid = $wpdb->escape(trim($guid[1])); + else + $guid = ''; + + preg_match('|(.*?)|is', $post, $post_content); + $post_content = str_replace(array (''), '', $wpdb->escape(trim($post_content[1]))); + + if (!$post_content) { + // This is for feeds that put content in description + preg_match('|(.*?)|is', $post, $post_content); + $post_content = $wpdb->escape($this->unhtmlentities(trim($post_content[1]))); + } + + // Clean up content + $post_content = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $post_content); + $post_content = str_replace('
    ', '
    ', $post_content); + $post_content = str_replace('
    ', '
    ', $post_content); + + $post_author = 1; + $post_status = 'publish'; + $this->posts[$index] = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_status', 'guid', 'categories'); + $index++; + } + } + + function import_posts() { + echo '
      '; + + foreach ($this->posts as $post) { + echo "
    1. ".__('Importing post...'); + + extract($post); + + if ($post_id = post_exists($post_title, $post_content, $post_date)) { + _e('Post already imported'); + } else { + $post_id = wp_insert_post($post); + if ( is_wp_error( $post_id ) ) + return $post_id; + if (!$post_id) { + _e('Couldn’t get post ID'); + return; + } + + if (0 != count($categories)) + wp_create_categories($categories, $post_id); + _e('Done !'); + } + echo '
    2. '; + } + + echo '
    '; + + } + + function import() { + $file = wp_import_handle_upload(); + if ( isset($file['error']) ) { + echo $file['error']; + return; + } + + $this->file = $file['file']; + $this->get_posts(); + $result = $this->import_posts(); + if ( is_wp_error( $result ) ) + return $result; + wp_import_cleanup($file['id']); + do_action('import_done', 'rss'); + + echo '

    '; + printf(__('All done. Have fun!'), get_option('home')); + echo '

    '; + } + + function dispatch() { + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + + $this->header(); + + switch ($step) { + case 0 : + $this->greet(); + break; + case 1 : + check_admin_referer('import-upload'); + $result = $this->import(); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + break; + } + + $this->footer(); + } + + function RSS_Import() { + // Nothing. + } +} + +$rss_import = new RSS_Import(); + +register_importer('rss', __('RSS'), __('Import posts from an RSS feed.'), array ($rss_import, 'dispatch')); +?> diff --git a/wp-admin/import/stp.php b/wp-admin/import/stp.php new file mode 100644 index 0000000..4568428 --- /dev/null +++ b/wp-admin/import/stp.php @@ -0,0 +1,170 @@ +'; + screen_icon(); + echo '

    '.__('Import Simple Tagging').'

    '; + echo '

    '.__('Steps may take a few minutes depending on the size of your database. Please be patient.').'

    '; + } + + function footer() { + echo ''; + } + + function greet() { + echo '
    '; + echo '

    '.__('Howdy! This imports tags from Simple Tagging 1.6.2 into WordPress tags.').'

    '; + echo '

    '.__('This has not been tested on any other versions of Simple Tagging. Mileage may vary.').'

    '; + echo '

    '.__('To accommodate larger databases for those tag-crazy authors out there, we have made this into an easy 4-step program to help you kick that nasty Simple Tagging habit. Just keep clicking along and we will let you know when you are in the clear!').'

    '; + echo '

    '.__('Don’t be stupid - backup your database before proceeding!').'

    '; + echo '
    '; + wp_nonce_field('import-stp'); + echo '

    '; + echo '
    '; + echo '
    '; + } + + function dispatch () { + if ( empty( $_GET['step'] ) ) { + $step = 0; + } else { + $step = (int) $_GET['step']; + } + // load the header + $this->header(); + switch ( $step ) { + case 0 : + $this->greet(); + break; + case 1 : + check_admin_referer('import-stp'); + $this->import_posts(); + break; + case 2: + check_admin_referer('import-stp'); + $this->import_t2p(); + break; + case 3: + check_admin_referer('import-stp'); + $this->cleanup_import(); + break; + } + // load the footer + $this->footer(); + } + + + function import_posts ( ) { + echo '
    '; + echo '

    '.__('Reading STP Post Tags…').'

    '; + + // read in all the STP tag -> post settings + $posts = $this->get_stp_posts(); + + // if we didn't get any tags back, that's all there is folks! + if ( !is_array($posts) ) { + echo '

    ' . __('No posts were found to have tags!') . '

    '; + return false; + } + else { + // if there's an existing entry, delete it + if ( get_option('stpimp_posts') ) { + delete_option('stpimp_posts'); + } + + add_option('stpimp_posts', $posts); + $count = count($posts); + echo '

    ' . sprintf( _n('Done! %s tag to post relationships were read.', 'Done! %s tags to post relationships were read.', $count), $count ) . '

    '; + } + + echo '
    '; + wp_nonce_field('import-stp'); + echo '

    '; + echo '
    '; + echo '
    '; + } + + + function import_t2p ( ) { + echo '
    '; + echo '

    '.__('Adding Tags to Posts…').'

    '; + + // run that funky magic! + $tags_added = $this->tag2post(); + + echo '

    ' . sprintf( _n('Done! %s tag was added!', 'Done! %s tags were added!', $tags_added), $tags_added ) . '

    '; + echo '
    '; + wp_nonce_field('import-stp'); + echo '

    '; + echo '
    '; + echo '
    '; + } + + function get_stp_posts ( ) { + global $wpdb; + // read in all the posts from the STP post->tag table: should be wp_post2tag + $posts_query = "SELECT post_id, tag_name FROM " . $wpdb->prefix . "stp_tags"; + $posts = $wpdb->get_results($posts_query); + return $posts; + } + + function tag2post ( ) { + global $wpdb; + + // get the tags and posts we imported in the last 2 steps + $posts = get_option('stpimp_posts'); + + // null out our results + $tags_added = 0; + + // loop through each post and add its tags to the db + foreach ( $posts as $this_post ) { + $the_post = (int) $this_post->post_id; + $the_tag = $wpdb->escape($this_post->tag_name); + // try to add the tag + wp_add_post_tags($the_post, $the_tag); + $tags_added++; + } + + // that's it, all posts should be linked to their tags properly, pending any errors we just spit out! + return $tags_added; + } + + function cleanup_import ( ) { + delete_option('stpimp_posts'); + $this->done(); + } + + function done ( ) { + echo '
    '; + echo '

    '.__('Import Complete!').'

    '; + echo '

    ' . __('OK, so we lied about this being a 4-step program! You’re done!') . '

    '; + echo '

    ' . __('Now wasn’t that easy?') . '

    '; + echo '
    '; + } + + function STP_Import ( ) { + // Nothing. + } +} + +// create the import object +$stp_import = new STP_Import(); + +// add it to the import page! +register_importer('stp', 'Simple Tagging', __('Import Simple Tagging tags into WordPress tags.'), array($stp_import, 'dispatch')); +?> diff --git a/wp-admin/import/textpattern.php b/wp-admin/import/textpattern.php new file mode 100644 index 0000000..2cbf36e --- /dev/null +++ b/wp-admin/import/textpattern.php @@ -0,0 +1,700 @@ +get_var( $wpdb->prepare("SELECT count(*) FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) ); + } +} + +if(!function_exists('link_exists')) +{ + /** + * Check whether link already exists. + * + * @package WordPress + * @subpackage Textpattern_Import + * + * @param string $linkname + * @return int + */ + function link_exists($linkname) + { + global $wpdb; + return $wpdb->get_var( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_name = %s", $linkname) ); + } +} + +/** + * TextPattern Importer Class + * + * @since unknown + */ +class Textpattern_Import { + + function header() + { + echo '
    '; + screen_icon(); + echo '

    '.__('Import Textpattern').'

    '; + echo '

    '.__('Steps may take a few minutes depending on the size of your database. Please be patient.').'

    '; + } + + function footer() + { + echo '
    '; + } + + function greet() { + echo '
    '; + echo '

    '.__('Howdy! This imports categories, users, posts, comments, and links from any Textpattern 4.0.2+ into this blog.').'

    '; + echo '

    '.__('This has not been tested on previous versions of Textpattern. Mileage may vary.').'

    '; + echo '

    '.__('Your Textpattern Configuration settings are as follows:').'

    '; + echo '
    '; + wp_nonce_field('import-textpattern'); + $this->db_form(); + echo '

    '; + echo '
    '; + echo '
    '; + } + + function get_txp_cats() + { + global $wpdb; + // General Housekeeping + $txpdb = new wpdb(get_option('txpuser'), get_option('txppass'), get_option('txpname'), get_option('txphost')); + set_magic_quotes_runtime(0); + $prefix = get_option('tpre'); + + // Get Categories + return $txpdb->get_results('SELECT + id, + name, + title + FROM '.$prefix.'txp_category + WHERE type = "article"', + ARRAY_A); + } + + function get_txp_users() + { + global $wpdb; + // General Housekeeping + $txpdb = new wpdb(get_option('txpuser'), get_option('txppass'), get_option('txpname'), get_option('txphost')); + set_magic_quotes_runtime(0); + $prefix = get_option('tpre'); + + // Get Users + + return $txpdb->get_results('SELECT + user_id, + name, + RealName, + email, + privs + FROM '.$prefix.'txp_users', ARRAY_A); + } + + function get_txp_posts() + { + // General Housekeeping + $txpdb = new wpdb(get_option('txpuser'), get_option('txppass'), get_option('txpname'), get_option('txphost')); + set_magic_quotes_runtime(0); + $prefix = get_option('tpre'); + + // Get Posts + return $txpdb->get_results('SELECT + ID, + Posted, + AuthorID, + LastMod, + Title, + Body, + Excerpt, + Category1, + Category2, + Status, + Keywords, + url_title, + comments_count + FROM '.$prefix.'textpattern + ', ARRAY_A); + } + + function get_txp_comments() + { + global $wpdb; + // General Housekeeping + $txpdb = new wpdb(get_option('txpuser'), get_option('txppass'), get_option('txpname'), get_option('txphost')); + set_magic_quotes_runtime(0); + $prefix = get_option('tpre'); + + // Get Comments + return $txpdb->get_results('SELECT * FROM '.$prefix.'txp_discuss', ARRAY_A); + } + + function get_txp_links() + { + //General Housekeeping + $txpdb = new wpdb(get_option('txpuser'), get_option('txppass'), get_option('txpname'), get_option('txphost')); + set_magic_quotes_runtime(0); + $prefix = get_option('tpre'); + + return $txpdb->get_results('SELECT + id, + date, + category, + url, + linkname, + description + FROM '.$prefix.'txp_link', + ARRAY_A); + } + + function cat2wp($categories='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $txpcat2wpcat = array(); + // Do the Magic + if(is_array($categories)) + { + echo '

    '.__('Importing Categories...').'

    '; + foreach ($categories as $category) + { + $count++; + extract($category); + + + // Make Nice Variables + $name = $wpdb->escape($name); + $title = $wpdb->escape($title); + + if($cinfo = category_exists($name)) + { + $ret_id = wp_insert_category(array('cat_ID' => $cinfo, 'category_nicename' => $name, 'cat_name' => $title)); + } + else + { + $ret_id = wp_insert_category(array('category_nicename' => $name, 'cat_name' => $title)); + } + $txpcat2wpcat[$id] = $ret_id; + } + + // Store category translation for future use + add_option('txpcat2wpcat',$txpcat2wpcat); + echo '

    '.sprintf(_n('Done! %1$s category imported.', 'Done! %1$s categories imported.', $count), $count).'

    '; + return true; + } + echo __('No Categories to Import!'); + return false; + } + + function users2wp($users='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $txpid2wpid = array(); + + // Midnight Mojo + if(is_array($users)) + { + echo '

    '.__('Importing Users...').'

    '; + foreach($users as $user) + { + $count++; + extract($user); + + // Make Nice Variables + $name = $wpdb->escape($name); + $RealName = $wpdb->escape($RealName); + + if($uinfo = get_userdatabylogin($name)) + { + + $ret_id = wp_insert_user(array( + 'ID' => $uinfo->ID, + 'user_login' => $name, + 'user_nicename' => $RealName, + 'user_email' => $email, + 'user_url' => 'http://', + 'display_name' => $name) + ); + } + else + { + $ret_id = wp_insert_user(array( + 'user_login' => $name, + 'user_nicename' => $RealName, + 'user_email' => $email, + 'user_url' => 'http://', + 'display_name' => $name) + ); + } + $txpid2wpid[$user_id] = $ret_id; + + // Set Textpattern-to-WordPress permissions translation + $transperms = array(1 => '10', 2 => '9', 3 => '5', 4 => '4', 5 => '3', 6 => '2', 7 => '0'); + + // Update Usermeta Data + $user = new WP_User($ret_id); + if('10' == $transperms[$privs]) { $user->set_role('administrator'); } + if('9' == $transperms[$privs]) { $user->set_role('editor'); } + if('5' == $transperms[$privs]) { $user->set_role('editor'); } + if('4' == $transperms[$privs]) { $user->set_role('author'); } + if('3' == $transperms[$privs]) { $user->set_role('contributor'); } + if('2' == $transperms[$privs]) { $user->set_role('contributor'); } + if('0' == $transperms[$privs]) { $user->set_role('subscriber'); } + + update_usermeta( $ret_id, 'wp_user_level', $transperms[$privs] ); + update_usermeta( $ret_id, 'rich_editing', 'false'); + }// End foreach($users as $user) + + // Store id translation array for future use + add_option('txpid2wpid',$txpid2wpid); + + + echo '

    '.sprintf(__('Done! %1$s users imported.'), $count).'

    '; + return true; + }// End if(is_array($users) + + echo __('No Users to Import!'); + return false; + + }// End function user2wp() + + function posts2wp($posts='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $txpposts2wpposts = array(); + $cats = array(); + + // Do the Magic + if(is_array($posts)) + { + echo '

    '.__('Importing Posts...').'

    '; + foreach($posts as $post) + { + $count++; + extract($post); + + // Set Textpattern-to-WordPress status translation + $stattrans = array(1 => 'draft', 2 => 'private', 3 => 'draft', 4 => 'publish', 5 => 'publish'); + + //Can we do this more efficiently? + $uinfo = ( get_userdatabylogin( $AuthorID ) ) ? get_userdatabylogin( $AuthorID ) : 1; + $authorid = ( is_object( $uinfo ) ) ? $uinfo->ID : $uinfo ; + + $Title = $wpdb->escape($Title); + $Body = $wpdb->escape($Body); + $Excerpt = $wpdb->escape($Excerpt); + $post_status = $stattrans[$Status]; + + // Import Post data into WordPress + + if($pinfo = post_exists($Title,$Body)) + { + $ret_id = wp_insert_post(array( + 'ID' => $pinfo, + 'post_date' => $Posted, + 'post_date_gmt' => $post_date_gmt, + 'post_author' => $authorid, + 'post_modified' => $LastMod, + 'post_modified_gmt' => $post_modified_gmt, + 'post_title' => $Title, + 'post_content' => $Body, + 'post_excerpt' => $Excerpt, + 'post_status' => $post_status, + 'post_name' => $url_title, + 'comment_count' => $comments_count) + ); + if ( is_wp_error( $ret_id ) ) + return $ret_id; + } + else + { + $ret_id = wp_insert_post(array( + 'post_date' => $Posted, + 'post_date_gmt' => $post_date_gmt, + 'post_author' => $authorid, + 'post_modified' => $LastMod, + 'post_modified_gmt' => $post_modified_gmt, + 'post_title' => $Title, + 'post_content' => $Body, + 'post_excerpt' => $Excerpt, + 'post_status' => $post_status, + 'post_name' => $url_title, + 'comment_count' => $comments_count) + ); + if ( is_wp_error( $ret_id ) ) + return $ret_id; + } + $txpposts2wpposts[$ID] = $ret_id; + + // Make Post-to-Category associations + $cats = array(); + $category1 = get_category_by_slug($Category1); + $category1 = $category1->term_id; + $category2 = get_category_by_slug($Category2); + $category2 = $category2->term_id; + if($cat1 = $category1) { $cats[1] = $cat1; } + if($cat2 = $category2) { $cats[2] = $cat2; } + + if(!empty($cats)) { wp_set_post_categories($ret_id, $cats); } + } + } + // Store ID translation for later use + add_option('txpposts2wpposts',$txpposts2wpposts); + + echo '

    '.sprintf(__('Done! %1$s posts imported.'), $count).'

    '; + return true; + } + + function comments2wp($comments='') + { + // General Housekeeping + global $wpdb; + $count = 0; + $txpcm2wpcm = array(); + $postarr = get_option('txpposts2wpposts'); + + // Magic Mojo + if(is_array($comments)) + { + echo '

    '.__('Importing Comments...').'

    '; + foreach($comments as $comment) + { + $count++; + extract($comment); + + // WordPressify Data + $comment_ID = ltrim($discussid, '0'); + $comment_post_ID = $postarr[$parentid]; + $comment_approved = (1 == $visible) ? 1 : 0; + $name = $wpdb->escape($name); + $email = $wpdb->escape($email); + $web = $wpdb->escape($web); + $message = $wpdb->escape($message); + + if($cinfo = comment_exists($name, $posted)) + { + // Update comments + $ret_id = wp_update_comment(array( + 'comment_ID' => $cinfo, + 'comment_post_ID' => $comment_post_ID, + 'comment_author' => $name, + 'comment_author_email' => $email, + 'comment_author_url' => $web, + 'comment_date' => $posted, + 'comment_content' => $message, + 'comment_approved' => $comment_approved) + ); + } + else + { + // Insert comments + $ret_id = wp_insert_comment(array( + 'comment_post_ID' => $comment_post_ID, + 'comment_author' => $name, + 'comment_author_email' => $email, + 'comment_author_url' => $web, + 'comment_author_IP' => $ip, + 'comment_date' => $posted, + 'comment_content' => $message, + 'comment_approved' => $comment_approved) + ); + } + $txpcm2wpcm[$comment_ID] = $ret_id; + } + // Store Comment ID translation for future use + add_option('txpcm2wpcm', $txpcm2wpcm); + + // Associate newly formed categories with posts + get_comment_count($ret_id); + + + echo '

    '.sprintf(__('Done! %1$s comments imported.'), $count).'

    '; + return true; + } + echo __('No Comments to Import!'); + return false; + } + + function links2wp($links='') + { + // General Housekeeping + global $wpdb; + $count = 0; + + // Deal with the links + if(is_array($links)) + { + echo '

    '.__('Importing Links...').'

    '; + foreach($links as $link) + { + $count++; + extract($link); + + // Make nice vars + $category = $wpdb->escape($category); + $linkname = $wpdb->escape($linkname); + $description = $wpdb->escape($description); + + if($linfo = link_exists($linkname)) + { + $ret_id = wp_insert_link(array( + 'link_id' => $linfo, + 'link_url' => $url, + 'link_name' => $linkname, + 'link_category' => $category, + 'link_description' => $description, + 'link_updated' => $date) + ); + } + else + { + $ret_id = wp_insert_link(array( + 'link_url' => $url, + 'link_name' => $linkname, + 'link_category' => $category, + 'link_description' => $description, + 'link_updated' => $date) + ); + } + $txplinks2wplinks[$link_id] = $ret_id; + } + add_option('txplinks2wplinks',$txplinks2wplinks); + echo '

    '; + printf(_n('Done! %s link imported', 'Done! %s links imported', $count), $count); + echo '

    '; + return true; + } + echo __('No Links to Import!'); + return false; + } + + function import_categories() + { + // Category Import + $cats = $this->get_txp_cats(); + $this->cat2wp($cats); + add_option('txp_cats', $cats); + + + + echo '
    '; + wp_nonce_field('import-textpattern'); + printf('

    ', esc_attr__('Import Users')); + echo '
    '; + + } + + function import_users() + { + // User Import + $users = $this->get_txp_users(); + $this->users2wp($users); + + echo '
    '; + wp_nonce_field('import-textpattern'); + printf('

    ', esc_attr__('Import Posts')); + echo '
    '; + } + + function import_posts() + { + // Post Import + $posts = $this->get_txp_posts(); + $result = $this->posts2wp($posts); + if ( is_wp_error( $result ) ) + return $result; + + echo '
    '; + wp_nonce_field('import-textpattern'); + printf('

    ', esc_attr__('Import Comments')); + echo '
    '; + } + + function import_comments() + { + // Comment Import + $comments = $this->get_txp_comments(); + $this->comments2wp($comments); + + echo '
    '; + wp_nonce_field('import-textpattern'); + printf('

    ', esc_attr__('Import Links')); + echo '
    '; + } + + function import_links() + { + //Link Import + $links = $this->get_txp_links(); + $this->links2wp($links); + add_option('txp_links', $links); + + echo '
    '; + wp_nonce_field('import-textpattern'); + printf('

    ', esc_attr__('Finish')); + echo '
    '; + } + + function cleanup_txpimport() + { + delete_option('tpre'); + delete_option('txp_cats'); + delete_option('txpid2wpid'); + delete_option('txpcat2wpcat'); + delete_option('txpposts2wpposts'); + delete_option('txpcm2wpcm'); + delete_option('txplinks2wplinks'); + delete_option('txpuser'); + delete_option('txppass'); + delete_option('txpname'); + delete_option('txphost'); + do_action('import_done', 'textpattern'); + $this->tips(); + } + + function tips() + { + echo '

    '.__('Welcome to WordPress. We hope (and expect!) that you will find this platform incredibly rewarding! As a new WordPress user coming from Textpattern, there are some things that we would like to point out. Hopefully, they will help your transition go as smoothly as possible.').'

    '; + echo '

    '.__('Users').'

    '; + echo '

    '.sprintf(__('You have already setup WordPress and have been assigned an administrative login and password. Forget it. You didn’t have that login in Textpattern, why should you have it here? Instead we have taken care to import all of your users into our system. Unfortunately there is one downside. Because both WordPress and Textpattern uses a strong encryption hash with passwords, it is impossible to decrypt it and we are forced to assign temporary passwords to all your users. Every user has the same username, but their passwords are reset to password123. So Login and change it.'), get_bloginfo( 'wpurl' ) . '/wp-login.php').'

    '; + echo '

    '.__('Preserving Authors').'

    '; + echo '

    '.__('Secondly, we have attempted to preserve post authors. If you are the only author or contributor to your blog, then you are safe. In most cases, we are successful in this preservation endeavor. However, if we cannot ascertain the name of the writer due to discrepancies between database tables, we assign it to you, the administrative user.').'

    '; + echo '

    '.__('Textile').'

    '; + echo '

    '.__('Also, since you’re coming from Textpattern, you probably have been using Textile to format your comments and posts. If this is the case, we recommend downloading and installing Textile for WordPress. Trust me... You’ll want it.').'

    '; + echo '

    '.__('WordPress Resources').'

    '; + echo '

    '.__('Finally, there are numerous WordPress resources around the internet. Some of them are:').'

    '; + echo ''; + echo '

    '.sprintf(__('That’s it! What are you waiting for? Go login!'), get_bloginfo( 'wpurl' ) . '/wp-login.php').'

    '; + } + + function db_form() + { + echo ''; + printf('', __('Textpattern Database User:')); + printf('', __('Textpattern Database Password:')); + printf('', __('Textpattern Database Name:')); + printf('', __('Textpattern Database Host:')); + printf('', __('Textpattern Table prefix (if any):')); + echo '
    '; + } + + function dispatch() + { + + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + $this->header(); + + if ( $step > 0 ) + { + check_admin_referer('import-textpattern'); + + if($_POST['dbuser']) + { + if(get_option('txpuser')) + delete_option('txpuser'); + add_option('txpuser', sanitize_user($_POST['dbuser'], true)); + } + if($_POST['dbpass']) + { + if(get_option('txppass')) + delete_option('txppass'); + add_option('txppass', sanitize_user($_POST['dbpass'], true)); + } + + if($_POST['dbname']) + { + if(get_option('txpname')) + delete_option('txpname'); + add_option('txpname', sanitize_user($_POST['dbname'], true)); + } + if($_POST['dbhost']) + { + if(get_option('txphost')) + delete_option('txphost'); + add_option('txphost', sanitize_user($_POST['dbhost'], true)); + } + if($_POST['dbprefix']) + { + if(get_option('tpre')) + delete_option('tpre'); + add_option('tpre', sanitize_user($_POST['dbprefix'])); + } + + + } + + switch ($step) + { + default: + case 0 : + $this->greet(); + break; + case 1 : + $this->import_categories(); + break; + case 2 : + $this->import_users(); + break; + case 3 : + $result = $this->import_posts(); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + break; + case 4 : + $this->import_comments(); + break; + case 5 : + $this->import_links(); + break; + case 6 : + $this->cleanup_txpimport(); + break; + } + + $this->footer(); + } + + function Textpattern_Import() + { + // Nothing. + } +} + +$txp_import = new Textpattern_Import(); + +register_importer('textpattern', __('Textpattern'), __('Import categories, users, posts, comments, and links from a Textpattern blog.'), array ($txp_import, 'dispatch')); + +?> diff --git a/wp-admin/import/utw.php b/wp-admin/import/utw.php new file mode 100644 index 0000000..3add5b6 --- /dev/null +++ b/wp-admin/import/utw.php @@ -0,0 +1,290 @@ +'; + screen_icon(); + echo '

    '.__('Import Ultimate Tag Warrior').'

    '; + echo '

    '.__('Steps may take a few minutes depending on the size of your database. Please be patient.').'

    '; + } + + function footer() { + echo ''; + } + + function greet() { + echo '
    '; + echo '

    '.__('Howdy! This imports tags from Ultimate Tag Warrior 3 into WordPress tags.').'

    '; + echo '

    '.__('This has not been tested on any other versions of Ultimate Tag Warrior. Mileage may vary.').'

    '; + echo '

    '.__('To accommodate larger databases for those tag-crazy authors out there, we have made this into an easy 5-step program to help you kick that nasty UTW habit. Just keep clicking along and we will let you know when you are in the clear!').'

    '; + echo '

    '.__('Don’t be stupid - backup your database before proceeding!').'

    '; + echo '
    '; + echo '

    '; + echo '
    '; + echo '
    '; + } + + + function dispatch () { + if ( empty( $_GET['step'] ) ) { + $step = 0; + } else { + $step = (int) $_GET['step']; + } + + if ( $step > 1 ) + check_admin_referer('import-utw'); + + // load the header + $this->header(); + + switch ( $step ) { + case 0 : + $this->greet(); + break; + case 1 : + $this->import_tags(); + break; + case 2 : + $this->import_posts(); + break; + case 3: + $this->import_t2p(); + break; + case 4: + $this->cleanup_import(); + break; + } + + // load the footer + $this->footer(); + } + + + function import_tags ( ) { + echo '
    '; + echo '

    '.__('Reading UTW Tags…').'

    '; + + $tags = $this->get_utw_tags(); + + // if we didn't get any tags back, that's all there is folks! + if ( !is_array($tags) ) { + echo '

    ' . __('No Tags Found!') . '

    '; + return false; + } + else { + + // if there's an existing entry, delete it + if ( get_option('utwimp_tags') ) { + delete_option('utwimp_tags'); + } + + add_option('utwimp_tags', $tags); + + + $count = count($tags); + + echo '

    ' . sprintf( _n('Done! %s tag were read.', 'Done! %s tags were read.', $count), $count ) . '

    '; + echo '

    ' . __('The following tags were found:') . '

    '; + + echo '
      '; + + foreach ( $tags as $tag_id => $tag_name ) { + + echo '
    • ' . $tag_name . '
    • '; + + } + + echo '
    '; + + echo '
    '; + + echo '

    ' . __('If you don’t want to import any of these tags, you should delete them from the UTW tag management page and then re-run this import.') . '

    '; + + + } + + echo '
    '; + wp_nonce_field('import-utw'); + echo '

    '; + echo '
    '; + echo '
    '; + } + + + function import_posts ( ) { + echo '
    '; + echo '

    '.__('Reading UTW Post Tags…').'

    '; + + // read in all the UTW tag -> post settings + $posts = $this->get_utw_posts(); + + // if we didn't get any tags back, that's all there is folks! + if ( !is_array($posts) ) { + echo '

    ' . __('No posts were found to have tags!') . '

    '; + return false; + } + else { + + // if there's an existing entry, delete it + if ( get_option('utwimp_posts') ) { + delete_option('utwimp_posts'); + } + + add_option('utwimp_posts', $posts); + + + $count = count($posts); + + echo '

    ' . sprintf( _n('Done! %s tag to post relationships were read.', 'Done! %s tags to post relationships were read.', $count), $count ) . '

    '; + + } + + echo '
    '; + wp_nonce_field('import-utw'); + echo '

    '; + echo '
    '; + echo '
    '; + + } + + + function import_t2p ( ) { + + echo '
    '; + echo '

    '.__('Adding Tags to Posts…').'

    '; + + // run that funky magic! + $tags_added = $this->tag2post(); + + echo '

    ' . sprintf( _n( 'Done! %s tag were added!', 'Done! %s tags were added!', $tags_added ), $tags_added ) . '

    '; + + echo '
    '; + wp_nonce_field('import-utw'); + echo '

    '; + echo '
    '; + echo '
    '; + + } + + + function get_utw_tags ( ) { + + global $wpdb; + + // read in all the tags from the UTW tags table: should be wp_tags + $tags_query = "SELECT tag_id, tag FROM " . $wpdb->prefix . "tags"; + + $tags = $wpdb->get_results($tags_query); + + // rearrange these tags into something we can actually use + foreach ( $tags as $tag ) { + + $new_tags[$tag->tag_id] = $tag->tag; + + } + + return $new_tags; + + } + + function get_utw_posts ( ) { + + global $wpdb; + + // read in all the posts from the UTW post->tag table: should be wp_post2tag + $posts_query = "SELECT tag_id, post_id FROM " . $wpdb->prefix . "post2tag"; + + $posts = $wpdb->get_results($posts_query); + + return $posts; + + } + + + function tag2post ( ) { + + // get the tags and posts we imported in the last 2 steps + $tags = get_option('utwimp_tags'); + $posts = get_option('utwimp_posts'); + + // null out our results + $tags_added = 0; + + // loop through each post and add its tags to the db + foreach ( $posts as $this_post ) { + + $the_post = (int) $this_post->post_id; + $the_tag = (int) $this_post->tag_id; + + // what's the tag name for that id? + $the_tag = $tags[$the_tag]; + + // screw it, just try to add the tag + wp_add_post_tags($the_post, $the_tag); + + $tags_added++; + + } + + // that's it, all posts should be linked to their tags properly, pending any errors we just spit out! + return $tags_added; + + + } + + + function cleanup_import ( ) { + + delete_option('utwimp_tags'); + delete_option('utwimp_posts'); + + $this->done(); + + } + + + function done ( ) { + + echo '
    '; + echo '

    '.__('Import Complete!').'

    '; + + echo '

    ' . __('OK, so we lied about this being a 5-step program! You’re done!') . '

    '; + + echo '

    ' . __('Now wasn’t that easy?') . '

    '; + + echo '
    '; + + } + + + function UTW_Import ( ) { + + // Nothing. + + } + +} + + +// create the import object +$utw_import = new UTW_Import(); + +// add it to the import page! +register_importer('utw', 'Ultimate Tag Warrior', __('Import Ultimate Tag Warrior tags into WordPress tags.'), array($utw_import, 'dispatch')); + +?> diff --git a/wp-admin/import/wordpress.php b/wp-admin/import/wordpress.php new file mode 100644 index 0000000..9990348 --- /dev/null +++ b/wp-admin/import/wordpress.php @@ -0,0 +1,807 @@ +'; + screen_icon(); + echo '

    '.__('Import WordPress').'

    '; + } + + function footer() { + echo ''; + } + + function unhtmlentities($string) { // From php.net for < 4.3 compat + $trans_tbl = get_html_translation_table(HTML_ENTITIES); + $trans_tbl = array_flip($trans_tbl); + return strtr($string, $trans_tbl); + } + + function greet() { + echo '
    '; + echo '

    '.__('Howdy! Upload your WordPress eXtended RSS (WXR) file and we’ll import the posts, pages, comments, custom fields, categories, and tags into this blog.').'

    '; + echo '

    '.__('Choose a WordPress WXR file to upload, then click Upload file and import.').'

    '; + wp_import_upload_form("admin.php?import=wordpress&step=1"); + echo '
    '; + } + + function get_tag( $string, $tag ) { + global $wpdb; + preg_match("|<$tag.*?>(.*?)|is", $string, $return); + $return = preg_replace('|^$|s', '$1', $return[1]); + $return = $wpdb->escape( trim( $return ) ); + return $return; + } + + function has_gzip() { + return is_callable('gzopen'); + } + + function fopen($filename, $mode='r') { + if ( $this->has_gzip() ) + return gzopen($filename, $mode); + return fopen($filename, $mode); + } + + function feof($fp) { + if ( $this->has_gzip() ) + return gzeof($fp); + return feof($fp); + } + + function fgets($fp, $len=8192) { + if ( $this->has_gzip() ) + return gzgets($fp, $len); + return fgets($fp, $len); + } + + function fclose($fp) { + if ( $this->has_gzip() ) + return gzclose($fp); + return fclose($fp); + } + + function get_entries($process_post_func=NULL) { + set_magic_quotes_runtime(0); + + $doing_entry = false; + $is_wxr_file = false; + + $fp = $this->fopen($this->file, 'r'); + if ($fp) { + while ( !$this->feof($fp) ) { + $importline = rtrim($this->fgets($fp)); + + // this doesn't check that the file is perfectly valid but will at least confirm that it's not the wrong format altogether + if ( !$is_wxr_file && preg_match('|xmlns:wp="http://wordpress[.]org/export/\d+[.]\d+/"|', $importline) ) + $is_wxr_file = true; + + if ( false !== strpos($importline, '') ) { + preg_match('|(.*?)|is', $importline, $url); + $this->base_url = $url[1]; + continue; + } + if ( false !== strpos($importline, '') ) { + preg_match('|(.*?)|is', $importline, $category); + $this->categories[] = $category[1]; + continue; + } + if ( false !== strpos($importline, '') ) { + preg_match('|(.*?)|is', $importline, $tag); + $this->tags[] = $tag[1]; + continue; + } + if ( false !== strpos($importline, '') ) { + $this->post = ''; + $doing_entry = true; + continue; + } + if ( false !== strpos($importline, '') ) { + $doing_entry = false; + if ($process_post_func) + call_user_func($process_post_func, $this->post); + continue; + } + if ( $doing_entry ) { + $this->post .= $importline . "\n"; + } + } + + $this->fclose($fp); + } + + return $is_wxr_file; + + } + + function get_wp_authors() { + // We need to find unique values of author names, while preserving the order, so this function emulates the unique_value(); php function, without the sorting. + $temp = $this->allauthornames; + $authors[0] = array_shift($temp); + $y = count($temp) + 1; + for ($x = 1; $x < $y; $x ++) { + $next = array_shift($temp); + if (!(in_array($next, $authors))) + array_push($authors, "$next"); + } + + return $authors; + } + + function get_authors_from_post() { + global $current_user; + + // this will populate $this->author_ids with a list of author_names => user_ids + + foreach ( $_POST['author_in'] as $i => $in_author_name ) { + + if ( !empty($_POST['user_select'][$i]) ) { + // an existing user was selected in the dropdown list + $user = get_userdata( intval($_POST['user_select'][$i]) ); + if ( isset($user->ID) ) + $this->author_ids[$in_author_name] = $user->ID; + } + elseif ( $this->allow_create_users() ) { + // nothing was selected in the dropdown list, so we'll use the name in the text field + + $new_author_name = trim($_POST['user_create'][$i]); + // if the user didn't enter a name, assume they want to use the same name as in the import file + if ( empty($new_author_name) ) + $new_author_name = $in_author_name; + + $user_id = username_exists($new_author_name); + if ( !$user_id ) { + $user_id = wp_create_user($new_author_name, wp_generate_password()); + } + + $this->author_ids[$in_author_name] = $user_id; + } + + // failsafe: if the user_id was invalid, default to the current user + if ( empty($this->author_ids[$in_author_name]) ) { + $this->author_ids[$in_author_name] = intval($current_user->ID); + } + } + + } + + function wp_authors_form() { +?> + +

    +

    admins entries.'); ?>

    +allow_create_users() ) { + echo '

    '.__('If a new user is created by WordPress, a password will be randomly generated. Manually change the user’s details if necessary.')."

    \n"; + } + + + $authors = $this->get_wp_authors(); + echo '
    '; + wp_nonce_field('import-wordpress'); + echo '
      '; + $j = -1; + foreach ($authors as $author) { + ++ $j; + echo '
    1. '.__('Import author:').' '.$author.'
      '; + $this->users_form($j, $author); + echo '
    2. '; + } + + if ( $this->allow_fetch_attachments() ) { +?> +
    + +

    +

    + + +

    + +'; + echo ''.'
    '; + echo '

    '; + echo '
    '; + + } + + function users_form($n, $author) { + + if ( $this->allow_create_users() ) { + printf('
    '); + } + else { + echo __('Map to existing').'
    '; + } + + // keep track of $n => $author name + echo ''; + + $users = get_users_of_blog(); +?> + get_entries(array(&$this, 'process_author')); + if ( $is_wxr_file ) { + $this->wp_authors_form(); + } + else { + echo '

    '.__('Invalid file').'

    '; + echo '

    '.__('Please upload a valid WXR (WordPress eXtended RSS) export file.').'

    '; + } + } + + // fetch the user ID for a given author name, respecting the mapping preferences + function checkauthor($author) { + global $current_user; + + if ( !empty($this->author_ids[$author]) ) + return $this->author_ids[$author]; + + // failsafe: map to the current user + return $current_user->ID; + } + + + + function process_categories() { + global $wpdb; + + $cat_names = (array) get_terms('category', 'fields=names'); + + while ( $c = array_shift($this->categories) ) { + $cat_name = trim($this->get_tag( $c, 'wp:cat_name' )); + + // If the category exists we leave it alone + if ( in_array($cat_name, $cat_names) ) + continue; + + $category_nicename = $this->get_tag( $c, 'wp:category_nicename' ); + $category_description = $this->get_tag( $c, 'wp:category_description' ); + $posts_private = (int) $this->get_tag( $c, 'wp:posts_private' ); + $links_private = (int) $this->get_tag( $c, 'wp:links_private' ); + + $parent = $this->get_tag( $c, 'wp:category_parent' ); + + if ( empty($parent) ) + $category_parent = '0'; + else + $category_parent = category_exists($parent); + + $catarr = compact('category_nicename', 'category_parent', 'posts_private', 'links_private', 'posts_private', 'cat_name', 'category_description'); + + $cat_ID = wp_insert_category($catarr); + } + } + + function process_tags() { + global $wpdb; + + $tag_names = (array) get_terms('post_tag', 'fields=names'); + + while ( $c = array_shift($this->tags) ) { + $tag_name = trim($this->get_tag( $c, 'wp:tag_name' )); + + // If the category exists we leave it alone + if ( in_array($tag_name, $tag_names) ) + continue; + + $slug = $this->get_tag( $c, 'wp:tag_slug' ); + $description = $this->get_tag( $c, 'wp:tag_description' ); + + $tagarr = compact('slug', 'description'); + + $tag_ID = wp_insert_term($tag_name, 'post_tag', $tagarr); + } + } + + function process_author($post) { + $author = $this->get_tag( $post, 'dc:creator' ); + if ($author) + $this->allauthornames[] = $author; + } + + function process_posts() { + echo '
      '; + + $this->get_entries(array(&$this, 'process_post')); + + echo '
    '; + + wp_import_cleanup($this->id); + do_action('import_done', 'wordpress'); + + echo '

    '.sprintf(__('All done.').' '.__('Have fun!').'', get_option('home')).'

    '; + } + + function process_post($post) { + global $wpdb; + + $post_ID = (int) $this->get_tag( $post, 'wp:post_id' ); + if ( $post_ID && !empty($this->post_ids_processed[$post_ID]) ) // Processed already + return 0; + + set_time_limit( 60 ); + + // There are only ever one of these + $post_title = $this->get_tag( $post, 'title' ); + $post_date = $this->get_tag( $post, 'wp:post_date' ); + $post_date_gmt = $this->get_tag( $post, 'wp:post_date_gmt' ); + $comment_status = $this->get_tag( $post, 'wp:comment_status' ); + $ping_status = $this->get_tag( $post, 'wp:ping_status' ); + $post_status = $this->get_tag( $post, 'wp:status' ); + $post_name = $this->get_tag( $post, 'wp:post_name' ); + $post_parent = $this->get_tag( $post, 'wp:post_parent' ); + $menu_order = $this->get_tag( $post, 'wp:menu_order' ); + $post_type = $this->get_tag( $post, 'wp:post_type' ); + $post_password = $this->get_tag( $post, 'wp:post_password' ); + $guid = $this->get_tag( $post, 'guid' ); + $post_author = $this->get_tag( $post, 'dc:creator' ); + + $post_excerpt = $this->get_tag( $post, 'excerpt:encoded' ); + $post_excerpt = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $post_excerpt); + $post_excerpt = str_replace('
    ', '
    ', $post_excerpt); + $post_excerpt = str_replace('
    ', '
    ', $post_excerpt); + + $post_content = $this->get_tag( $post, 'content:encoded' ); + $post_content = preg_replace_callback('|<(/?[A-Z]+)|', create_function('$match', 'return "<" . strtolower($match[1]);'), $post_content); + $post_content = str_replace('
    ', '
    ', $post_content); + $post_content = str_replace('
    ', '
    ', $post_content); + + preg_match_all('|(.*?)|is', $post, $tags); + $tags = $tags[1]; + + $tag_index = 0; + foreach ($tags as $tag) { + $tags[$tag_index] = $wpdb->escape($this->unhtmlentities(str_replace(array (''), '', $tag))); + $tag_index++; + } + + preg_match_all('|(.*?)|is', $post, $categories); + $categories = $categories[1]; + + $cat_index = 0; + foreach ($categories as $category) { + $categories[$cat_index] = $wpdb->escape($this->unhtmlentities(str_replace(array (''), '', $category))); + $cat_index++; + } + + $post_exists = post_exists($post_title, '', $post_date); + + if ( $post_exists ) { + echo '
  • '; + printf(__('Post %s already exists.'), stripslashes($post_title)); + $comment_post_ID = $post_id = $post_exists; + } else { + + // If it has parent, process parent first. + $post_parent = (int) $post_parent; + if ($post_parent) { + // if we already know the parent, map it to the local ID + if ( $parent = $this->post_ids_processed[$post_parent] ) { + $post_parent = $parent; // new ID of the parent + } + else { + // record the parent for later + $this->orphans[intval($post_ID)] = $post_parent; + } + } + + echo '
  • '; + + $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor + + $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_excerpt', 'post_title', 'post_status', 'post_name', 'comment_status', 'ping_status', 'guid', 'post_parent', 'menu_order', 'post_type', 'post_password'); + $postdata['import_id'] = $post_ID; + if ($post_type == 'attachment') { + $remote_url = $this->get_tag( $post, 'wp:attachment_url' ); + if ( !$remote_url ) + $remote_url = $guid; + + $comment_post_ID = $post_id = $this->process_attachment($postdata, $remote_url); + if ( !$post_id or is_wp_error($post_id) ) + return $post_id; + } + else { + printf(__('Importing post %s...'), stripslashes($post_title)); + $comment_post_ID = $post_id = wp_insert_post($postdata); + } + + if ( is_wp_error( $post_id ) ) + return $post_id; + + // Memorize old and new ID. + if ( $post_id && $post_ID ) { + $this->post_ids_processed[intval($post_ID)] = intval($post_id); + } + + // Add categories. + if (count($categories) > 0) { + $post_cats = array(); + foreach ($categories as $category) { + if ( '' == $category ) + continue; + $slug = sanitize_term_field('slug', $category, 0, 'category', 'db'); + $cat = get_term_by('slug', $slug, 'category'); + $cat_ID = 0; + if ( ! empty($cat) ) + $cat_ID = $cat->term_id; + if ($cat_ID == 0) { + $category = $wpdb->escape($category); + $cat_ID = wp_insert_category(array('cat_name' => $category)); + if ( is_wp_error($cat_ID) ) + continue; + } + $post_cats[] = $cat_ID; + } + wp_set_post_categories($post_id, $post_cats); + } + + // Add tags. + if (count($tags) > 0) { + $post_tags = array(); + foreach ($tags as $tag) { + if ( '' == $tag ) + continue; + $slug = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); + $tag_obj = get_term_by('slug', $slug, 'post_tag'); + $tag_id = 0; + if ( ! empty($tag_obj) ) + $tag_id = $tag_obj->term_id; + if ( $tag_id == 0 ) { + $tag = $wpdb->escape($tag); + $tag_id = wp_insert_term($tag, 'post_tag'); + if ( is_wp_error($tag_id) ) + continue; + $tag_id = $tag_id['term_id']; + } + $post_tags[] = intval($tag_id); + } + wp_set_post_tags($post_id, $post_tags); + } + } + + // Now for comments + preg_match_all('|(.*?)|is', $post, $comments); + $comments = $comments[1]; + $num_comments = 0; + if ( $comments) { foreach ($comments as $comment) { + $comment_author = $this->get_tag( $comment, 'wp:comment_author'); + $comment_author_email = $this->get_tag( $comment, 'wp:comment_author_email'); + $comment_author_IP = $this->get_tag( $comment, 'wp:comment_author_IP'); + $comment_author_url = $this->get_tag( $comment, 'wp:comment_author_url'); + $comment_date = $this->get_tag( $comment, 'wp:comment_date'); + $comment_date_gmt = $this->get_tag( $comment, 'wp:comment_date_gmt'); + $comment_content = $this->get_tag( $comment, 'wp:comment_content'); + $comment_approved = $this->get_tag( $comment, 'wp:comment_approved'); + $comment_type = $this->get_tag( $comment, 'wp:comment_type'); + $comment_parent = $this->get_tag( $comment, 'wp:comment_parent'); + + // if this is a new post we can skip the comment_exists() check + if ( !$post_exists || !comment_exists($comment_author, $comment_date) ) { + $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_approved', 'comment_type', 'comment_parent'); + wp_insert_comment($commentdata); + $num_comments++; + } + } } + + if ( $num_comments ) + printf(' '._n('(%s comment)', '(%s comments)', $num_comments), $num_comments); + + // Now for post meta + preg_match_all('|(.*?)|is', $post, $postmeta); + $postmeta = $postmeta[1]; + if ( $postmeta) { foreach ($postmeta as $p) { + $key = $this->get_tag( $p, 'wp:meta_key' ); + $value = $this->get_tag( $p, 'wp:meta_value' ); + $value = stripslashes($value); // add_post_meta() will escape. + + $this->process_post_meta($post_id, $key, $value); + + } } + + do_action('import_post_added', $post_id); + print "
  • \n"; + } + + function process_post_meta($post_id, $key, $value) { + // the filter can return false to skip a particular metadata key + $_key = apply_filters('import_post_meta_key', $key); + if ( $_key ) { + add_post_meta( $post_id, $_key, $value ); + do_action('import_post_meta', $post_id, $_key, $value); + } + } + + function process_attachment($postdata, $remote_url) { + if ($this->fetch_attachments and $remote_url) { + printf( __('Importing attachment %s... '), htmlspecialchars($remote_url) ); + + // If the URL is absolute, but does not contain http, upload it assuming the base_site_url variable + if ( preg_match('/^\/[\w\W]+$/', $remote_url) ) + $remote_url = rtrim($this->base_url,'/').$remote_url; + + $upload = $this->fetch_remote_file($postdata, $remote_url); + if ( is_wp_error($upload) ) { + printf( __('Remote file error: %s'), htmlspecialchars($upload->get_error_message()) ); + return $upload; + } + else { + print '('.size_format(filesize($upload['file'])).')'; + } + + if ( $info = wp_check_filetype($upload['file']) ) { + $postdata['post_mime_type'] = $info['type']; + } + else { + print __('Invalid file type'); + return; + } + + $postdata['guid'] = $upload['url']; + + // as per wp-admin/includes/upload.php + $post_id = wp_insert_attachment($postdata, $upload['file']); + wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) ); + + // remap the thumbnail url. this isn't perfect because we're just guessing the original url. + if ( preg_match('@^image/@', $info['type']) && $thumb_url = wp_get_attachment_thumb_url($post_id) ) { + $parts = pathinfo($remote_url); + $ext = $parts['extension']; + $name = basename($parts['basename'], ".{$ext}"); + $this->url_remap[$parts['dirname'] . '/' . $name . '.thumbnail.' . $ext] = $thumb_url; + } + + return $post_id; + } + else { + printf( __('Skipping attachment %s'), htmlspecialchars($remote_url) ); + } + } + + function fetch_remote_file($post, $url) { + $upload = wp_upload_dir($post['post_date']); + + // extract the file name and extension from the url + $file_name = basename($url); + + // get placeholder file in the upload dir with a unique sanitized filename + $upload = wp_upload_bits( $file_name, 0, '', $post['post_date']); + if ( $upload['error'] ) { + echo $upload['error']; + return new WP_Error( 'upload_dir_error', $upload['error'] ); + } + + // fetch the remote url and write it to the placeholder file + $headers = wp_get_http($url, $upload['file']); + + //Request failed + if ( ! $headers ) { + @unlink($upload['file']); + return new WP_Error( 'import_file_error', __('Remote server did not respond') ); + } + + // make sure the fetch was successful + if ( $headers['response'] != '200' ) { + @unlink($upload['file']); + return new WP_Error( 'import_file_error', sprintf(__('Remote file returned error response %1$d %2$s'), $headers['response'], get_status_header_desc($headers['response']) ) ); + } + elseif ( isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length'] ) { + @unlink($upload['file']); + return new WP_Error( 'import_file_error', __('Remote file is incorrect size') ); + } + + $max_size = $this->max_attachment_size(); + if ( !empty($max_size) and filesize($upload['file']) > $max_size ) { + @unlink($upload['file']); + return new WP_Error( 'import_file_error', sprintf(__('Remote file is too large, limit is %s', size_format($max_size))) ); + } + + // keep track of the old and new urls so we can substitute them later + $this->url_remap[$url] = $upload['url']; + // if the remote url is redirected somewhere else, keep track of the destination too + if ( $headers['x-final-location'] != $url ) + $this->url_remap[$headers['x-final-location']] = $upload['url']; + + return $upload; + + } + + // sort by strlen, longest string first + function cmpr_strlen($a, $b) { + return strlen($b) - strlen($a); + } + + // update url references in post bodies to point to the new local files + function backfill_attachment_urls() { + + // make sure we do the longest urls first, in case one is a substring of another + uksort($this->url_remap, array(&$this, 'cmpr_strlen')); + + global $wpdb; + foreach ($this->url_remap as $from_url => $to_url) { + // remap urls in post_content + $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, '%s', '%s')", $from_url, $to_url) ); + // remap enclosure urls + $result = $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, '%s', '%s') WHERE meta_key='enclosure'", $from_url, $to_url) ); + } + } + + // update the post_parent of orphans now that we know the local id's of all parents + function backfill_parents() { + global $wpdb; + + foreach ($this->orphans as $child_id => $parent_id) { + $local_child_id = $this->post_ids_processed[$child_id]; + $local_parent_id = $this->post_ids_processed[$parent_id]; + if ($local_child_id and $local_parent_id) { + $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_parent = %d WHERE ID = %d", $local_parent_id, $local_child_id)); + } + } + } + + function is_valid_meta_key($key) { + // skip _wp_attached_file metadata since we'll regenerate it from scratch + if ( $key == '_wp_attached_file' ) + return false; + return $key; + } + + // give the user the option of creating new users to represent authors in the import file? + function allow_create_users() { + return apply_filters('import_allow_create_users', true); + } + + // give the user the option of downloading and importing attached files + function allow_fetch_attachments() { + return apply_filters('import_allow_fetch_attachments', true); + } + + function max_attachment_size() { + // can be overridden with a filter - 0 means no limit + return apply_filters('import_attachment_size_limit', 0); + } + + function import_start() { + wp_defer_term_counting(true); + wp_defer_comment_counting(true); + do_action('import_start'); + } + + function import_end() { + do_action('import_end'); + + // clear the caches after backfilling + foreach ($this->post_ids_processed as $post_id) + clean_post_cache($post_id); + + wp_defer_term_counting(false); + wp_defer_comment_counting(false); + } + + function import($id, $fetch_attachments = false) { + $this->id = (int) $id; + $this->fetch_attachments = ($this->allow_fetch_attachments() && (bool) $fetch_attachments); + + add_filter('import_post_meta_key', array($this, 'is_valid_meta_key')); + $file = get_attached_file($this->id); + $this->import_file($file); + } + + function import_file($file) { + $this->file = $file; + + $this->import_start(); + $this->get_authors_from_post(); + wp_suspend_cache_invalidation(true); + $this->get_entries(); + $this->process_categories(); + $this->process_tags(); + $result = $this->process_posts(); + wp_suspend_cache_invalidation(false); + $this->backfill_parents(); + $this->backfill_attachment_urls(); + $this->import_end(); + + if ( is_wp_error( $result ) ) + return $result; + } + + function handle_upload() { + $file = wp_import_handle_upload(); + if ( isset($file['error']) ) { + echo '

    '.__('Sorry, there has been an error.').'

    '; + echo '

    ' . $file['error'] . '

    '; + return false; + } + $this->file = $file['file']; + $this->id = (int) $file['id']; + return true; + } + + function dispatch() { + if (empty ($_GET['step'])) + $step = 0; + else + $step = (int) $_GET['step']; + + $this->header(); + switch ($step) { + case 0 : + $this->greet(); + break; + case 1 : + check_admin_referer('import-upload'); + if ( $this->handle_upload() ) + $this->select_authors(); + break; + case 2: + check_admin_referer('import-wordpress'); + $result = $this->import( $_GET['id'], $_POST['attachments'] ); + if ( is_wp_error( $result ) ) + echo $result->get_error_message(); + break; + } + $this->footer(); + } + + function WP_Import() { + // Nothing. + } +} + +/** + * Register WordPress Importer + * + * @since unknown + * @var WP_Import + * @name $wp_import + */ +$wp_import = new WP_Import(); + +register_importer('wordpress', 'WordPress', __('Import posts, pages, comments, custom fields, categories, and tags from a WordPress export file.'), array ($wp_import, 'dispatch')); + +?> diff --git a/wp-admin/import/wp-cat2tag.php b/wp-admin/import/wp-cat2tag.php new file mode 100644 index 0000000..b4312b6 --- /dev/null +++ b/wp-admin/import/wp-cat2tag.php @@ -0,0 +1,472 @@ +'; + if ( ! current_user_can('manage_categories') ) { + echo '
    '; + echo '

    ' . __('Cheatin’ uh?') . '

    '; + echo '
    '; + } else { ?> +

    +

    +'; + } + + function populate_cats() { + + $categories = get_categories('get=all'); + foreach ( $categories as $category ) { + $this->all_categories[] = $category; + if ( is_term( $category->slug, 'post_tag' ) ) + $this->hybrids_ids[] = $category->term_id; + } + } + + function populate_tags() { + + $tags = get_terms( array('post_tag'), 'get=all' ); + foreach ( $tags as $tag ) { + $this->all_tags[] = $tag; + if ( is_term( $tag->slug, 'category' ) ) + $this->hybrids_ids[] = $tag->term_id; + } + } + + function categories_tab() { + $this->populate_cats(); + $cat_num = count($this->all_categories); + + echo '
    '; + + if ( $cat_num > 0 ) { + screen_icon(); + echo '

    ' . sprintf( _n( 'Convert Category to Tag.', 'Convert Categories (%d) to Tags.', $cat_num ), $cat_num ) . '

    '; + echo '
    '; + echo '

    ' . __('Hey there. Here you can selectively convert existing categories to tags. To get started, check the categories you wish to be converted, then click the Convert button.') . '

    '; + echo '

    ' . __('Keep in mind that if you convert a category with child categories, the children become top-level orphans.') . '

    '; + + $this->categories_form(); + } else { + echo '

    '.__('You have no categories to convert!').'

    '; + } + } + + function categories_form() { ?> + + + +
    +

    +

    +
      + +all_categories as $category) { + $category = sanitize_term( $category, 'category', 'display' ); + + if ( (int) $category->parent == 0 ) { ?> + +
    • term_id), $this->hybrids_ids ) ) + echo ' * '; + + if ( isset($hier[$category->term_id]) ) + $this->_category_children($category, $hier); ?>
    • + +
    + +hybrids_ids) ) + echo '

    ' . __('* This category is also a tag. Converting it will add that tag to all posts that are currently in the category.') . '

    '; ?> + +

    +
    + +populate_tags(); + $tags_num = count($this->all_tags); + + echo '
    '; + + if ( $tags_num > 0 ) { + screen_icon(); + echo '

    ' . sprintf( _n( 'Convert Tag to Category.', 'Convert Tags (%d) to Categories.', $tags_num ), $tags_num ) . '

    '; + echo '
    '; + echo '

    ' . __('Here you can selectively convert existing tags to categories. To get started, check the tags you wish to be converted, then click the Convert button.') . '

    '; + echo '

    ' . __('The newly created categories will still be associated with the same posts.') . '

    '; + + $this->tags_form(); + } else { + echo '

    '.__('You have no tags to convert!').'

    '; + } + } + + function tags_form() { ?> + + + +
    +

    +

    +
      + +all_tags as $tag ) { ?> +
    • term_id), $this->hybrids_ids ) ) echo ' * '; ?>
    • + + +
    + +hybrids_ids) ) + echo '

    ' . __('* This tag is also a category. When converted, all posts associated with the tag will also be in the category.') . '

    '; ?> + +

    +
    + + + +
      +term_id] as $child_id) { + $child =& get_category($child_id); ?> +
    • term_id), $this->hybrids_ids ) ) + echo ' * '; + + if ( isset($hier[$child->term_id]) ) + $this->_category_children($child, $hier); ?>
    • + +
    categories_to_convert)) { ?> +
    +

    try again.'), 'admin.php?import=wp-cat2tag'); ?>

    +
    +categories_to_convert) ) + $this->categories_to_convert = $_POST['cats_to_convert']; + + $hier = _get_term_hierarchy('category'); + $hybrid_cats = $clear_parents = $parents = false; + $clean_term_cache = $clean_cat_cache = array(); + $default_cat = get_option('default_category'); + + echo '
      '; + + foreach ( (array) $this->categories_to_convert as $cat_id) { + $cat_id = (int) $cat_id; + + if ( ! $this->_category_exists($cat_id) ) { + echo '
    • ' . sprintf( __('Category %s doesn’t exist!'), $cat_id ) . "
    • \n"; + } else { + $category =& get_category($cat_id); + echo '
    • ' . sprintf(__('Converting category %s ... '), $category->name); + + // If the category is the default, leave category in place and create tag. + if ( $default_cat == $category->term_id ) { + + if ( ! ($id = is_term( $category->slug, 'post_tag' ) ) ) + $id = wp_insert_term($category->name, 'post_tag', array('slug' => $category->slug)); + + $id = $id['term_taxonomy_id']; + $posts = get_objects_in_term($category->term_id, 'category'); + $term_order = 0; + + foreach ( $posts as $post ) { + $values[] = $wpdb->prepare( "(%d, %d, %d)", $post, $id, $term_order); + clean_post_cache($post); + } + + if ( $values ) { + $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)"); + + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET count = %d WHERE term_id = %d AND taxonomy = 'post_tag'", $category->count, $category->term_id) ); + } + + echo __('Converted successfully.') . "
    • \n"; + continue; + } + + // if tag already exists, add it to all posts in the category + if ( $tag_ttid = $wpdb->get_var( $wpdb->prepare("SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id = %d AND taxonomy = 'post_tag'", $category->term_id) ) ) { + $objects_ids = get_objects_in_term($category->term_id, 'category'); + $tag_ttid = (int) $tag_ttid; + $term_order = 0; + + foreach ( $objects_ids as $object_id ) + $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tag_ttid, $term_order); + + if ( $values ) { + $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)"); + + $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tag_ttid) ); + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET count = %d WHERE term_id = %d AND taxonomy = 'post_tag'", $count, $category->term_id) ); + } + echo __('Tag added to all posts in this category.') . " *\n"; + + $hybrid_cats = true; + $clean_term_cache[] = $category->term_id; + $clean_cat_cache[] = $category->term_id; + + continue; + } + + $tt_ids = $wpdb->get_col( $wpdb->prepare("SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id = %d AND taxonomy = 'category'", $category->term_id) ); + if ( $tt_ids ) { + $posts = $wpdb->get_col("SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id IN (" . join(',', $tt_ids) . ") GROUP BY object_id"); + foreach ( (array) $posts as $post ) + clean_post_cache($post); + } + + // Change the category to a tag. + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET taxonomy = 'post_tag' WHERE term_id = %d AND taxonomy = 'category'", $category->term_id) ); + + // Set all parents to 0 (root-level) if their parent was the converted tag + $parents = $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET parent = 0 WHERE parent = %d AND taxonomy = 'category'", $category->term_id) ); + + if ( $parents ) $clear_parents = true; + $clean_cat_cache[] = $category->term_id; + echo __('Converted successfully.') . "\n"; + } + } + echo '
    '; + + if ( ! empty($clean_term_cache) ) { + $clean_term_cache = array_unique(array_values($clean_term_cache)); + clean_term_cache($clean_term_cache, 'post_tag'); + } + + if ( ! empty($clean_cat_cache) ) { + $clean_cat_cache = array_unique(array_values($clean_cat_cache)); + clean_term_cache($clean_cat_cache, 'category'); + } + + if ( $clear_parents ) delete_option('category_children'); + + if ( $hybrid_cats ) + echo '

    ' . sprintf( __('* This category is also a tag. The converter has added that tag to all posts currently in the category. If you want to remove it, please confirm that all tags were added successfully, then delete it from the Manage Categories page.'), 'categories.php') . '

    '; + echo '

    ' . sprintf( __('We’re all done here, but you can always convert more.'), 'admin.php?import=wp-cat2tag' ) . '

    '; + } + + function convert_tags() { + global $wpdb; + + if ( (!isset($_POST['tags_to_convert']) || !is_array($_POST['tags_to_convert'])) && empty($this->tags_to_convert)) { + echo '
    '; + echo '

    ' . sprintf(__('Uh, oh. Something didn’t work. Please try again.'), 'admin.php?import=wp-cat2tag&step=3') . '

    '; + echo '
    '; + return; + } + + if ( empty($this->tags_to_convert) ) + $this->tags_to_convert = $_POST['tags_to_convert']; + + $hybrid_tags = $clear_parents = false; + $clean_cat_cache = $clean_term_cache = array(); + $default_cat = get_option('default_category'); + echo '
      '; + + foreach ( (array) $this->tags_to_convert as $tag_id) { + $tag_id = (int) $tag_id; + + if ( $tag = get_term( $tag_id, 'post_tag' ) ) { + printf('
    • ' . __('Converting tag %s ... '), $tag->name); + + if ( $cat_ttid = $wpdb->get_var( $wpdb->prepare("SELECT term_taxonomy_id FROM $wpdb->term_taxonomy WHERE term_id = %d AND taxonomy = 'category'", $tag->term_id) ) ) { + $objects_ids = get_objects_in_term($tag->term_id, 'post_tag'); + $cat_ttid = (int) $cat_ttid; + $term_order = 0; + + foreach ( $objects_ids as $object_id ) { + $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $cat_ttid, $term_order); + clean_post_cache($object_id); + } + + if ( $values ) { + $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)"); + + if ( $default_cat != $tag->term_id ) { + $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tag->term_id) ); + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET count = %d WHERE term_id = %d AND taxonomy = 'category'", $count, $tag->term_id) ); + } + } + + $hybrid_tags = true; + $clean_term_cache[] = $tag->term_id; + $clean_cat_cache[] = $tag->term_id; + echo __('All posts were added to the category with the same name.') . " *
    • \n"; + + continue; + } + + // Change the tag to a category. + $parent = $wpdb->get_var( $wpdb->prepare("SELECT parent FROM $wpdb->term_taxonomy WHERE term_id = %d AND taxonomy = 'post_tag'", $tag->term_id) ); + if ( 0 == $parent || (0 < (int) $parent && $this->_category_exists($parent)) ) { + $reset_parent = ''; + $clear_parents = true; + } else + $reset_parent = ", parent = '0'"; + + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->term_taxonomy SET taxonomy = 'category' $reset_parent WHERE term_id = %d AND taxonomy = 'post_tag'", $tag->term_id) ); + + $clean_term_cache[] = $tag->term_id; + $clean_cat_cache[] = $cat['term_id']; + echo __('Converted successfully.') . "\n"; + + } else { + printf( '
    • ' . __('Tag #%s doesn’t exist!') . "
    • \n", $tag_id ); + } + } + + if ( ! empty($clean_term_cache) ) { + $clean_term_cache = array_unique(array_values($clean_term_cache)); + clean_term_cache($clean_term_cache, 'post_tag'); + } + + if ( ! empty($clean_cat_cache) ) { + $clean_cat_cache = array_unique(array_values($clean_cat_cache)); + clean_term_cache($clean_term_cache, 'category'); + } + + if ( $clear_parents ) delete_option('category_children'); + + echo '
    '; + if ( $hybrid_tags ) + echo '

    ' . sprintf( __('* This tag is also a category. The converter has added all posts from it to the category. If you want to remove it, please confirm that all posts were added successfully, then delete it from the Manage Tags page.'), 'edit-tags.php') . '

    '; + echo '

    ' . sprintf( __('We’re all done here, but you can always convert more.'), 'admin.php?import=wp-cat2tag&step=3' ) . '

    '; + } + + function init() { + + $step = (isset($_GET['step'])) ? (int) $_GET['step'] : 1; + + $this->header(); + + if ( current_user_can('manage_categories') ) { + + switch ($step) { + case 1 : + $this->categories_tab(); + break; + + case 2 : + check_admin_referer('import-cat2tag'); + $this->convert_categories(); + break; + + case 3 : + $this->tags_tab(); + break; + + case 4 : + check_admin_referer('import-cat2tag'); + $this->convert_tags(); + break; + } + } + + $this->footer(); + } + + function WP_Categories_to_Tags() { + // Do nothing. + } +} + +$wp_cat2tag_importer = new WP_Categories_to_Tags(); + +register_importer('wp-cat2tag', __('Categories and Tags Converter'), __('Convert existing categories to tags or tags to categories, selectively.'), array(&$wp_cat2tag_importer, 'init')); + +?> diff --git a/wp-admin/includes/admin.php b/wp-admin/includes/admin.php new file mode 100644 index 0000000..a75a199 --- /dev/null +++ b/wp-admin/includes/admin.php @@ -0,0 +1,54 @@ + \ No newline at end of file diff --git a/wp-admin/includes/bookmark.php b/wp-admin/includes/bookmark.php new file mode 100644 index 0000000..64621fd --- /dev/null +++ b/wp-admin/includes/bookmark.php @@ -0,0 +1,273 @@ +link_url = esc_url( $_GET['linkurl']); + else + $link->link_url = ''; + + if ( isset( $_GET['name'] ) ) + $link->link_name = esc_attr( $_GET['name']); + else + $link->link_name = ''; + + $link->link_visible = 'Y'; + + return $link; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $link_id + * @return unknown + */ +function wp_delete_link( $link_id ) { + global $wpdb; + + do_action( 'delete_link', $link_id ); + + wp_delete_object_term_relationships( $link_id, 'link_category' ); + + $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->links WHERE link_id = %d", $link_id ) ); + + do_action( 'deleted_link', $link_id ); + + clean_bookmark_cache( $link_id ); + + return true; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $link_id + * @return unknown + */ +function wp_get_link_cats( $link_id = 0 ) { + + $cats = wp_get_object_terms( $link_id, 'link_category', 'fields=ids' ); + + return array_unique( $cats ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $link_id + * @return unknown + */ +function get_link_to_edit( $link_id ) { + return get_bookmark( $link_id, OBJECT, 'edit' ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $linkdata + * @return unknown + */ +function wp_insert_link( $linkdata, $wp_error = false ) { + global $wpdb, $current_user; + + $defaults = array( 'link_id' => 0, 'link_name' => '', 'link_url' => '', 'link_rating' => 0 ); + + $linkdata = wp_parse_args( $linkdata, $defaults ); + $linkdata = sanitize_bookmark( $linkdata, 'db' ); + + extract( stripslashes_deep( $linkdata ), EXTR_SKIP ); + + $update = false; + + if ( !empty( $link_id ) ) + $update = true; + + if ( trim( $link_name ) == '' ) { + if ( trim( $link_url ) != '' ) { + $link_name = $link_url; + } else { + return 0; + } + } + + if ( trim( $link_url ) == '' ) + return 0; + + if ( empty( $link_rating ) ) + $link_rating = 0; + + if ( empty( $link_image ) ) + $link_image = ''; + + if ( empty( $link_target ) ) + $link_target = ''; + + if ( empty( $link_visible ) ) + $link_visible = 'Y'; + + if ( empty( $link_owner ) ) + $link_owner = $current_user->id; + + if ( empty( $link_notes ) ) + $link_notes = ''; + + if ( empty( $link_description ) ) + $link_description = ''; + + if ( empty( $link_rss ) ) + $link_rss = ''; + + if ( empty( $link_rel ) ) + $link_rel = ''; + + // Make sure we set a valid category + if ( ! isset( $link_category ) ||0 == count( $link_category ) || !is_array( $link_category ) ) { + $link_category = array( get_option( 'default_link_category' ) ); + } + + if ( $update ) { + if ( false === $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->links SET link_url = %s, + link_name = %s, link_image = %s, link_target = %s, + link_visible = %s, link_description = %s, link_rating = %s, + link_rel = %s, link_notes = %s, link_rss = %s + WHERE link_id = %s", $link_url, $link_name, $link_image, $link_target, $link_visible, $link_description, $link_rating, $link_rel, $link_notes, $link_rss, $link_id ) ) ) { + if ( $wp_error ) + return new WP_Error( 'db_update_error', __( 'Could not update link in the database' ), $wpdb->last_error ); + else + return 0; + } + } else { + if ( false === $wpdb->query( $wpdb->prepare( "INSERT INTO $wpdb->links (link_url, link_name, link_image, link_target, link_description, link_visible, link_owner, link_rating, link_rel, link_notes, link_rss) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", + $link_url,$link_name, $link_image, $link_target, $link_description, $link_visible, $link_owner, $link_rating, $link_rel, $link_notes, $link_rss ) ) ) { + if ( $wp_error ) + return new WP_Error( 'db_insert_error', __( 'Could not insert link into the database' ), $wpdb->last_error ); + else + return 0; + } + $link_id = (int) $wpdb->insert_id; + } + + wp_set_link_cats( $link_id, $link_category ); + + if ( $update ) + do_action( 'edit_link', $link_id ); + else + do_action( 'add_link', $link_id ); + + clean_bookmark_cache( $link_id ); + + return $link_id; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $link_id + * @param unknown_type $link_categories + */ +function wp_set_link_cats( $link_id = 0, $link_categories = array() ) { + // If $link_categories isn't already an array, make it one: + if ( !is_array( $link_categories ) || 0 == count( $link_categories ) ) + $link_categories = array( get_option( 'default_link_category' ) ); + + $link_categories = array_map( 'intval', $link_categories ); + $link_categories = array_unique( $link_categories ); + + wp_set_object_terms( $link_id, $link_categories, 'link_category' ); + + clean_bookmark_cache( $link_id ); +} // wp_set_link_cats() + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $linkdata + * @return unknown + */ +function wp_update_link( $linkdata ) { + $link_id = (int) $linkdata['link_id']; + + $link = get_link( $link_id, ARRAY_A ); + + // Escape data pulled from DB. + $link = add_magic_quotes( $link ); + + // Passed link category list overwrites existing category list if not empty. + if ( isset( $linkdata['link_category'] ) && is_array( $linkdata['link_category'] ) + && 0 != count( $linkdata['link_category'] ) ) + $link_cats = $linkdata['link_category']; + else + $link_cats = $link['link_category']; + + // Merge old and new fields with new fields overwriting old ones. + $linkdata = array_merge( $link, $linkdata ); + $linkdata['link_category'] = $link_cats; + + return wp_insert_link( $linkdata ); +} + +?> diff --git a/wp-admin/includes/class-ftp-pure.php b/wp-admin/includes/class-ftp-pure.php new file mode 100644 index 0000000..c947f44 --- /dev/null +++ b/wp-admin/includes/class-ftp-pure.php @@ -0,0 +1,190 @@ +__construct($verb, $le); + } + + function __construct($verb=FALSE, $le=FALSE) { + parent::__construct(false, $verb, $le); + } + +// +// +// + + function _settimeout($sock) { + if(!@stream_set_timeout($sock, $this->_timeout)) { + $this->PushError('_settimeout','socket set send timeout'); + $this->_quit(); + return FALSE; + } + return TRUE; + } + + function _connect($host, $port) { + $this->SendMSG("Creating socket"); + $sock = @fsockopen($host, $port, $errno, $errstr, $this->_timeout); + if (!$sock) { + $this->PushError('_connect','socket connect failed', $errstr." (".$errno.")"); + return FALSE; + } + $this->_connected=true; + return $sock; + } + + function _readmsg($fnction="_readmsg"){ + if(!$this->_connected) { + $this->PushError($fnction, 'Connect first'); + return FALSE; + } + $result=true; + $this->_message=""; + $this->_code=0; + $go=true; + do { + $tmp=@fgets($this->_ftp_control_sock, 512); + if($tmp===false) { + $go=$result=false; + $this->PushError($fnction,'Read failed'); + } else { + $this->_message.=$tmp; + if(preg_match("/^([0-9]{3})(-(.*[".CRLF."]{1,2})+\\1)? [^".CRLF."]+[".CRLF."]{1,2}$/", $this->_message, $regs)) $go=false; + } + } while($go); + if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF; + $this->_code=(int)$regs[1]; + return $result; + } + + function _exec($cmd, $fnction="_exec") { + if(!$this->_ready) { + $this->PushError($fnction,'Connect first'); + return FALSE; + } + if($this->LocalEcho) echo "PUT > ",$cmd,CRLF; + $status=@fputs($this->_ftp_control_sock, $cmd.CRLF); + if($status===false) { + $this->PushError($fnction,'socket write failed'); + return FALSE; + } + $this->_lastaction=time(); + if(!$this->_readmsg($fnction)) return FALSE; + return TRUE; + } + + function _data_prepare($mode=FTP_ASCII) { + if(!$this->_settype($mode)) return FALSE; + if($this->_passive) { + if(!$this->_exec("PASV", "pasv")) { + $this->_data_close(); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + return FALSE; + } + $ip_port = explode(",", ereg_replace("^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*".CRLF."$", "\\1", $this->_message)); + $this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3]; + $this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]); + $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); + $this->_ftp_data_sock=@fsockopen($this->_datahost, $this->_dataport, $errno, $errstr, $this->_timeout); + if(!$this->_ftp_data_sock) { + $this->PushError("_data_prepare","fsockopen fails", $errstr." (".$errno.")"); + $this->_data_close(); + return FALSE; + } + else $this->_ftp_data_sock; + } else { + $this->SendMSG("Only passive connections available!"); + return FALSE; + } + return TRUE; + } + + function _data_read($mode=FTP_ASCII, $fp=NULL) { + if(is_resource($fp)) $out=0; + else $out=""; + if(!$this->_passive) { + $this->SendMSG("Only passive connections available!"); + return FALSE; + } + while (!feof($this->_ftp_data_sock)) { + $block=fread($this->_ftp_data_sock, $this->_ftp_buff_size); + if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block); + if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block)); + else $out.=$block; + } + return $out; + } + + function _data_write($mode=FTP_ASCII, $fp=NULL) { + if(is_resource($fp)) $out=0; + else $out=""; + if(!$this->_passive) { + $this->SendMSG("Only passive connections available!"); + return FALSE; + } + if(is_resource($fp)) { + while(!feof($fp)) { + $block=fread($fp, $this->_ftp_buff_size); + if(!$this->_data_write_block($mode, $block)) return false; + } + } elseif(!$this->_data_write_block($mode, $fp)) return false; + return TRUE; + } + + function _data_write_block($mode, $block) { + if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block); + do { + if(($t=@fwrite($this->_ftp_data_sock, $block))===FALSE) { + $this->PushError("_data_write","Can't write to socket"); + return FALSE; + } + $block=substr($block, $t); + } while(!empty($block)); + return true; + } + + function _data_close() { + @fclose($this->_ftp_data_sock); + $this->SendMSG("Disconnected data from remote host"); + return TRUE; + } + + function _quit($force=FALSE) { + if($this->_connected or $force) { + @fclose($this->_ftp_control_sock); + $this->_connected=false; + $this->SendMSG("Socket closed"); + } + } +} + +?> diff --git a/wp-admin/includes/class-ftp-sockets.php b/wp-admin/includes/class-ftp-sockets.php new file mode 100644 index 0000000..4026dd0 --- /dev/null +++ b/wp-admin/includes/class-ftp-sockets.php @@ -0,0 +1,250 @@ +__construct($verb, $le); + } + + function __construct($verb=FALSE, $le=FALSE) { + parent::__construct(true, $verb, $le); + } + +// +// +// + + function _settimeout($sock) { + if(!@socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) { + $this->PushError('_connect','socket set receive timeout',socket_strerror(socket_last_error($sock))); + @socket_close($sock); + return FALSE; + } + if(!@socket_set_option($sock, SOL_SOCKET , SO_SNDTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) { + $this->PushError('_connect','socket set send timeout',socket_strerror(socket_last_error($sock))); + @socket_close($sock); + return FALSE; + } + return true; + } + + function _connect($host, $port) { + $this->SendMSG("Creating socket"); + if(!($sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { + $this->PushError('_connect','socket create failed',socket_strerror(socket_last_error($sock))); + return FALSE; + } + if(!$this->_settimeout($sock)) return FALSE; + $this->SendMSG("Connecting to \"".$host.":".$port."\""); + if (!($res = @socket_connect($sock, $host, $port))) { + $this->PushError('_connect','socket connect failed',socket_strerror(socket_last_error($sock))); + @socket_close($sock); + return FALSE; + } + $this->_connected=true; + return $sock; + } + + function _readmsg($fnction="_readmsg"){ + if(!$this->_connected) { + $this->PushError($fnction,'Connect first'); + return FALSE; + } + $result=true; + $this->_message=""; + $this->_code=0; + $go=true; + do { + $tmp=@socket_read($this->_ftp_control_sock, 4096, PHP_BINARY_READ); + if($tmp===false) { + $go=$result=false; + $this->PushError($fnction,'Read failed', socket_strerror(socket_last_error($this->_ftp_control_sock))); + } else { + $this->_message.=$tmp; + $go = !preg_match("/^([0-9]{3})(-.+\\1)? [^".CRLF."]+".CRLF."$/Us", $this->_message, $regs); + } + } while($go); + if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF; + $this->_code=(int)$regs[1]; + return $result; + } + + function _exec($cmd, $fnction="_exec") { + if(!$this->_ready) { + $this->PushError($fnction,'Connect first'); + return FALSE; + } + if($this->LocalEcho) echo "PUT > ",$cmd,CRLF; + $status=@socket_write($this->_ftp_control_sock, $cmd.CRLF); + if($status===false) { + $this->PushError($fnction,'socket write failed', socket_strerror(socket_last_error($this->stream))); + return FALSE; + } + $this->_lastaction=time(); + if(!$this->_readmsg($fnction)) return FALSE; + return TRUE; + } + + function _data_prepare($mode=FTP_ASCII) { + if(!$this->_settype($mode)) return FALSE; + $this->SendMSG("Creating data socket"); + $this->_ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + if ($this->_ftp_data_sock < 0) { + $this->PushError('_data_prepare','socket create failed',socket_strerror(socket_last_error($this->_ftp_data_sock))); + return FALSE; + } + if(!$this->_settimeout($this->_ftp_data_sock)) { + $this->_data_close(); + return FALSE; + } + if($this->_passive) { + if(!$this->_exec("PASV", "pasv")) { + $this->_data_close(); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + return FALSE; + } + $ip_port = explode(",", ereg_replace("^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*".CRLF."$", "\\1", $this->_message)); + $this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3]; + $this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]); + $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); + if(!@socket_connect($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) { + $this->PushError("_data_prepare","socket_connect", socket_strerror(socket_last_error($this->_ftp_data_sock))); + $this->_data_close(); + return FALSE; + } + else $this->_ftp_temp_sock=$this->_ftp_data_sock; + } else { + if(!@socket_getsockname($this->_ftp_control_sock, $addr, $port)) { + $this->PushError("_data_prepare","can't get control socket information", socket_strerror(socket_last_error($this->_ftp_control_sock))); + $this->_data_close(); + return FALSE; + } + if(!@socket_bind($this->_ftp_data_sock,$addr)){ + $this->PushError("_data_prepare","can't bind data socket", socket_strerror(socket_last_error($this->_ftp_data_sock))); + $this->_data_close(); + return FALSE; + } + if(!@socket_listen($this->_ftp_data_sock)) { + $this->PushError("_data_prepare","can't listen data socket", socket_strerror(socket_last_error($this->_ftp_data_sock))); + $this->_data_close(); + return FALSE; + } + if(!@socket_getsockname($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) { + $this->PushError("_data_prepare","can't get data socket information", socket_strerror(socket_last_error($this->_ftp_data_sock))); + $this->_data_close(); + return FALSE; + } + if(!$this->_exec('PORT '.str_replace('.',',',$this->_datahost.'.'.($this->_dataport>>8).'.'.($this->_dataport&0x00FF)), "_port")) { + $this->_data_close(); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + return FALSE; + } + } + return TRUE; + } + + function _data_read($mode=FTP_ASCII, $fp=NULL) { + $NewLine=$this->_eol_code[$this->OS_local]; + if(is_resource($fp)) $out=0; + else $out=""; + if(!$this->_passive) { + $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); + $this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock); + if($this->_ftp_temp_sock===FALSE) { + $this->PushError("_data_read","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock))); + $this->_data_close(); + return FALSE; + } + } + + while(($block=@socket_read($this->_ftp_temp_sock, $this->_ftp_buff_size, PHP_BINARY_READ))!==false) { + if($block==="") break; + if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block); + if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block)); + else $out.=$block; + } + return $out; + } + + function _data_write($mode=FTP_ASCII, $fp=NULL) { + $NewLine=$this->_eol_code[$this->OS_local]; + if(is_resource($fp)) $out=0; + else $out=""; + if(!$this->_passive) { + $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); + $this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock); + if($this->_ftp_temp_sock===FALSE) { + $this->PushError("_data_write","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock))); + $this->_data_close(); + return false; + } + } + if(is_resource($fp)) { + while(!feof($fp)) { + $block=fread($fp, $this->_ftp_buff_size); + if(!$this->_data_write_block($mode, $block)) return false; + } + } elseif(!$this->_data_write_block($mode, $fp)) return false; + return true; + } + + function _data_write_block($mode, $block) { + if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block); + do { + if(($t=@socket_write($this->_ftp_temp_sock, $block))===FALSE) { + $this->PushError("_data_write","socket_write", socket_strerror(socket_last_error($this->_ftp_temp_sock))); + $this->_data_close(); + return FALSE; + } + $block=substr($block, $t); + } while(!empty($block)); + return true; + } + + function _data_close() { + @socket_close($this->_ftp_temp_sock); + @socket_close($this->_ftp_data_sock); + $this->SendMSG("Disconnected data from remote host"); + return TRUE; + } + + function _quit() { + if($this->_connected) { + @socket_close($this->_ftp_control_sock); + $this->_connected=false; + $this->SendMSG("Socket closed"); + } + } +} +?> diff --git a/wp-admin/includes/class-ftp.php b/wp-admin/includes/class-ftp.php new file mode 100644 index 0000000..0bf25e9 --- /dev/null +++ b/wp-admin/includes/class-ftp.php @@ -0,0 +1,903 @@ +__construct($port_mode); + } + + function __construct($port_mode=FALSE, $verb=FALSE, $le=FALSE) { + $this->LocalEcho=$le; + $this->Verbose=$verb; + $this->_lastaction=NULL; + $this->_error_array=array(); + $this->_eol_code=array(FTP_OS_Unix=>"\n", FTP_OS_Mac=>"\r", FTP_OS_Windows=>"\r\n"); + $this->AuthorizedTransferMode=array(FTP_AUTOASCII, FTP_ASCII, FTP_BINARY); + $this->OS_FullName=array(FTP_OS_Unix => 'UNIX', FTP_OS_Windows => 'WINDOWS', FTP_OS_Mac => 'MACOS'); + $this->AutoAsciiExt=array("ASP","BAT","C","CPP","CSS","CSV","JS","H","HTM","HTML","SHTML","INI","LOG","PHP3","PHTML","PL","PERL","SH","SQL","TXT"); + $this->_port_available=($port_mode==TRUE); + $this->SendMSG("Staring FTP client class".($this->_port_available?"":" without PORT mode support")); + $this->_connected=FALSE; + $this->_ready=FALSE; + $this->_can_restore=FALSE; + $this->_code=0; + $this->_message=""; + $this->_ftp_buff_size=4096; + $this->_curtype=NULL; + $this->SetUmask(0022); + $this->SetType(FTP_AUTOASCII); + $this->SetTimeout(30); + $this->Passive(!$this->_port_available); + $this->_login="anonymous"; + $this->_password="anon@ftp.com"; + $this->_features=array(); + $this->OS_local=FTP_OS_Unix; + $this->OS_remote=FTP_OS_Unix; + $this->features=array(); + if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $this->OS_local=FTP_OS_Windows; + elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'MAC') $this->OS_local=FTP_OS_Mac; + } + +// +// +// + + function parselisting($line) { + $is_windows = ($this->OS_remote == FTP_OS_Windows); + if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)/",$line,$lucifer)) { + $b = array(); + if ($lucifer[3]<70) { $lucifer[3]+=2000; } else { $lucifer[3]+=1900; } // 4digit year fix + $b['isdir'] = ($lucifer[7]==""); + if ( $b['isdir'] ) + $b['type'] = 'd'; + else + $b['type'] = 'f'; + $b['size'] = $lucifer[7]; + $b['month'] = $lucifer[1]; + $b['day'] = $lucifer[2]; + $b['year'] = $lucifer[3]; + $b['hour'] = $lucifer[4]; + $b['minute'] = $lucifer[5]; + $b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]); + $b['am/pm'] = $lucifer[6]; + $b['name'] = $lucifer[8]; + } else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) { + //echo $line."\n"; + $lcount=count($lucifer); + if ($lcount<8) return ''; + $b = array(); + $b['isdir'] = $lucifer[0]{0} === "d"; + $b['islink'] = $lucifer[0]{0} === "l"; + if ( $b['isdir'] ) + $b['type'] = 'd'; + elseif ( $b['islink'] ) + $b['type'] = 'l'; + else + $b['type'] = 'f'; + $b['perms'] = $lucifer[0]; + $b['number'] = $lucifer[1]; + $b['owner'] = $lucifer[2]; + $b['group'] = $lucifer[3]; + $b['size'] = $lucifer[4]; + if ($lcount==8) { + sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']); + sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']); + $b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']); + $b['name'] = $lucifer[7]; + } else { + $b['month'] = $lucifer[5]; + $b['day'] = $lucifer[6]; + if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) { + $b['year'] = date("Y"); + $b['hour'] = $l2[1]; + $b['minute'] = $l2[2]; + } else { + $b['year'] = $lucifer[7]; + $b['hour'] = 0; + $b['minute'] = 0; + } + $b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute'])); + $b['name'] = $lucifer[8]; + } + } + + return $b; + } + + function SendMSG($message = "", $crlf=true) { + if ($this->Verbose) { + echo $message.($crlf?CRLF:""); + flush(); + } + return TRUE; + } + + function SetType($mode=FTP_AUTOASCII) { + if(!in_array($mode, $this->AuthorizedTransferMode)) { + $this->SendMSG("Wrong type"); + return FALSE; + } + $this->_type=$mode; + $this->SendMSG("Transfer type: ".($this->_type==FTP_BINARY?"binary":($this->_type==FTP_ASCII?"ASCII":"auto ASCII") ) ); + return TRUE; + } + + function _settype($mode=FTP_ASCII) { + if($this->_ready) { + if($mode==FTP_BINARY) { + if($this->_curtype!=FTP_BINARY) { + if(!$this->_exec("TYPE I", "SetType")) return FALSE; + $this->_curtype=FTP_BINARY; + } + } elseif($this->_curtype!=FTP_ASCII) { + if(!$this->_exec("TYPE A", "SetType")) return FALSE; + $this->_curtype=FTP_ASCII; + } + } else return FALSE; + return TRUE; + } + + function Passive($pasv=NULL) { + if(is_null($pasv)) $this->_passive=!$this->_passive; + else $this->_passive=$pasv; + if(!$this->_port_available and !$this->_passive) { + $this->SendMSG("Only passive connections available!"); + $this->_passive=TRUE; + return FALSE; + } + $this->SendMSG("Passive mode ".($this->_passive?"on":"off")); + return TRUE; + } + + function SetServer($host, $port=21, $reconnect=true) { + if(!is_long($port)) { + $this->verbose=true; + $this->SendMSG("Incorrect port syntax"); + return FALSE; + } else { + $ip=@gethostbyname($host); + $dns=@gethostbyaddr($host); + if(!$ip) $ip=$host; + if(!$dns) $dns=$host; + if(ip2long($ip) === -1) { + $this->SendMSG("Wrong host name/address \"".$host."\""); + return FALSE; + } + $this->_host=$ip; + $this->_fullhost=$dns; + $this->_port=$port; + $this->_dataport=$port-1; + } + $this->SendMSG("Host \"".$this->_fullhost."(".$this->_host."):".$this->_port."\""); + if($reconnect){ + if($this->_connected) { + $this->SendMSG("Reconnecting"); + if(!$this->quit(FTP_FORCE)) return FALSE; + if(!$this->connect()) return FALSE; + } + } + return TRUE; + } + + function SetUmask($umask=0022) { + $this->_umask=$umask; + umask($this->_umask); + $this->SendMSG("UMASK 0".decoct($this->_umask)); + return TRUE; + } + + function SetTimeout($timeout=30) { + $this->_timeout=$timeout; + $this->SendMSG("Timeout ".$this->_timeout); + if($this->_connected) + if(!$this->_settimeout($this->_ftp_control_sock)) return FALSE; + return TRUE; + } + + function connect($server=NULL) { + if(!empty($server)) { + if(!$this->SetServer($server)) return false; + } + if($this->_ready) return true; + $this->SendMsg('Local OS : '.$this->OS_FullName[$this->OS_local]); + if(!($this->_ftp_control_sock = $this->_connect($this->_host, $this->_port))) { + $this->SendMSG("Error : Cannot connect to remote host \"".$this->_fullhost." :".$this->_port."\""); + return FALSE; + } + $this->SendMSG("Connected to remote host \"".$this->_fullhost.":".$this->_port."\". Waiting for greeting."); + do { + if(!$this->_readmsg()) return FALSE; + if(!$this->_checkCode()) return FALSE; + $this->_lastaction=time(); + } while($this->_code<200); + $this->_ready=true; + $syst=$this->systype(); + if(!$syst) $this->SendMSG("Can't detect remote OS"); + else { + if(preg_match("/win|dos|novell/i", $syst[0])) $this->OS_remote=FTP_OS_Windows; + elseif(preg_match("/os/i", $syst[0])) $this->OS_remote=FTP_OS_Mac; + elseif(preg_match("/(li|u)nix/i", $syst[0])) $this->OS_remote=FTP_OS_Unix; + else $this->OS_remote=FTP_OS_Mac; + $this->SendMSG("Remote OS: ".$this->OS_FullName[$this->OS_remote]); + } + if(!$this->features()) $this->SendMSG("Can't get features list. All supported - disabled"); + else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features))); + return TRUE; + } + + function quit($force=false) { + if($this->_ready) { + if(!$this->_exec("QUIT") and !$force) return FALSE; + if(!$this->_checkCode() and !$force) return FALSE; + $this->_ready=false; + $this->SendMSG("Session finished"); + } + $this->_quit(); + return TRUE; + } + + function login($user=NULL, $pass=NULL) { + if(!is_null($user)) $this->_login=$user; + else $this->_login="anonymous"; + if(!is_null($pass)) $this->_password=$pass; + else $this->_password="anon@anon.com"; + if(!$this->_exec("USER ".$this->_login, "login")) return FALSE; + if(!$this->_checkCode()) return FALSE; + if($this->_code!=230) { + if(!$this->_exec((($this->_code==331)?"PASS ":"ACCT ").$this->_password, "login")) return FALSE; + if(!$this->_checkCode()) return FALSE; + } + $this->SendMSG("Authentication succeeded"); + if(empty($this->_features)) { + if(!$this->features()) $this->SendMSG("Can't get features list. All supported - disabled"); + else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features))); + } + return TRUE; + } + + function pwd() { + if(!$this->_exec("PWD", "pwd")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return ereg_replace("^[0-9]{3} \"(.+)\".+", "\\1", $this->_message); + } + + function cdup() { + if(!$this->_exec("CDUP", "cdup")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return true; + } + + function chdir($pathname) { + if(!$this->_exec("CWD ".$pathname, "chdir")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return TRUE; + } + + function rmdir($pathname) { + if(!$this->_exec("RMD ".$pathname, "rmdir")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return TRUE; + } + + function mkdir($pathname) { + if(!$this->_exec("MKD ".$pathname, "mkdir")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return TRUE; + } + + function rename($from, $to) { + if(!$this->_exec("RNFR ".$from, "rename")) return FALSE; + if(!$this->_checkCode()) return FALSE; + if($this->_code==350) { + if(!$this->_exec("RNTO ".$to, "rename")) return FALSE; + if(!$this->_checkCode()) return FALSE; + } else return FALSE; + return TRUE; + } + + function filesize($pathname) { + if(!isset($this->_features["SIZE"])) { + $this->PushError("filesize", "not supported by server"); + return FALSE; + } + if(!$this->_exec("SIZE ".$pathname, "filesize")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return ereg_replace("^[0-9]{3} ([0-9]+)".CRLF, "\\1", $this->_message); + } + + function abort() { + if(!$this->_exec("ABOR", "abort")) return FALSE; + if(!$this->_checkCode()) { + if($this->_code!=426) return FALSE; + if(!$this->_readmsg("abort")) return FALSE; + if(!$this->_checkCode()) return FALSE; + } + return true; + } + + function mdtm($pathname) { + if(!isset($this->_features["MDTM"])) { + $this->PushError("mdtm", "not supported by server"); + return FALSE; + } + if(!$this->_exec("MDTM ".$pathname, "mdtm")) return FALSE; + if(!$this->_checkCode()) return FALSE; + $mdtm = ereg_replace("^[0-9]{3} ([0-9]+)".CRLF, "\\1", $this->_message); + $date = sscanf($mdtm, "%4d%2d%2d%2d%2d%2d"); + $timestamp = mktime($date[3], $date[4], $date[5], $date[1], $date[2], $date[0]); + return $timestamp; + } + + function systype() { + if(!$this->_exec("SYST", "systype")) return FALSE; + if(!$this->_checkCode()) return FALSE; + $DATA = explode(" ", $this->_message); + return array($DATA[1], $DATA[3]); + } + + function delete($pathname) { + if(!$this->_exec("DELE ".$pathname, "delete")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return TRUE; + } + + function site($command, $fnction="site") { + if(!$this->_exec("SITE ".$command, $fnction)) return FALSE; + if(!$this->_checkCode()) return FALSE; + return TRUE; + } + + function chmod($pathname, $mode) { + if(!$this->site( sprintf('CHMOD %o %s', $mode, $pathname), "chmod")) return FALSE; + return TRUE; + } + + function restore($from) { + if(!isset($this->_features["REST"])) { + $this->PushError("restore", "not supported by server"); + return FALSE; + } + if($this->_curtype!=FTP_BINARY) { + $this->PushError("restore", "can't restore in ASCII mode"); + return FALSE; + } + if(!$this->_exec("REST ".$from, "resore")) return FALSE; + if(!$this->_checkCode()) return FALSE; + return TRUE; + } + + function features() { + if(!$this->_exec("FEAT", "features")) return FALSE; + if(!$this->_checkCode()) return FALSE; + $f=preg_split("/[".CRLF."]+/", preg_replace("/[0-9]{3}[ -].*[".CRLF."]+/", "", $this->_message), -1, PREG_SPLIT_NO_EMPTY); + $this->_features=array(); + foreach($f as $k=>$v) { + $v=explode(" ", trim($v)); + $this->_features[array_shift($v)]=$v;; + } + return true; + } + + function rawlist($pathname="", $arg="") { + return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "LIST", "rawlist"); + } + + function nlist($pathname="") { + return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "NLST", "nlist"); + } + + function is_exists($pathname) { + return $this->file_exists($pathname); + } + + function file_exists($pathname) { + $exists=true; + if(!$this->_exec("RNFR ".$pathname, "rename")) $exists=FALSE; + else { + if(!$this->_checkCode()) $exists=FALSE; + $this->abort(); + } + if($exists) $this->SendMSG("Remote file ".$pathname." exists"); + else $this->SendMSG("Remote file ".$pathname." does not exist"); + return $exists; + } + + function fget($fp, $remotefile,$rest=0) { + if($this->_can_restore and $rest!=0) fseek($fp, $rest); + $pi=pathinfo($remotefile); + if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; + else $mode=FTP_BINARY; + if(!$this->_data_prepare($mode)) { + return FALSE; + } + if($this->_can_restore and $rest!=0) $this->restore($rest); + if(!$this->_exec("RETR ".$remotefile, "get")) { + $this->_data_close(); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + return FALSE; + } + $out=$this->_data_read($mode, $fp); + $this->_data_close(); + if(!$this->_readmsg()) return FALSE; + if(!$this->_checkCode()) return FALSE; + return $out; + } + + function get($remotefile, $localfile=NULL, $rest=0) { + if(is_null($localfile)) $localfile=$remotefile; + if (@file_exists($localfile)) $this->SendMSG("Warning : local file will be overwritten"); + $fp = @fopen($localfile, "w"); + if (!$fp) { + $this->PushError("get","can't open local file", "Cannot create \"".$localfile."\""); + return FALSE; + } + if($this->_can_restore and $rest!=0) fseek($fp, $rest); + $pi=pathinfo($remotefile); + if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; + else $mode=FTP_BINARY; + if(!$this->_data_prepare($mode)) { + fclose($fp); + return FALSE; + } + if($this->_can_restore and $rest!=0) $this->restore($rest); + if(!$this->_exec("RETR ".$remotefile, "get")) { + $this->_data_close(); + fclose($fp); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + fclose($fp); + return FALSE; + } + $out=$this->_data_read($mode, $fp); + fclose($fp); + $this->_data_close(); + if(!$this->_readmsg()) return FALSE; + if(!$this->_checkCode()) return FALSE; + return $out; + } + + function fput($remotefile, $fp) { + if($this->_can_restore and $rest!=0) fseek($fp, $rest); + $pi=pathinfo($remotefile); + if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; + else $mode=FTP_BINARY; + if(!$this->_data_prepare($mode)) { + return FALSE; + } + if($this->_can_restore and $rest!=0) $this->restore($rest); + if(!$this->_exec("STOR ".$remotefile, "put")) { + $this->_data_close(); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + return FALSE; + } + $ret=$this->_data_write($mode, $fp); + $this->_data_close(); + if(!$this->_readmsg()) return FALSE; + if(!$this->_checkCode()) return FALSE; + return $ret; + } + + function put($localfile, $remotefile=NULL, $rest=0) { + if(is_null($remotefile)) $remotefile=$localfile; + if (!file_exists($localfile)) { + $this->PushError("put","can't open local file", "No such file or directory \"".$localfile."\""); + return FALSE; + } + $fp = @fopen($localfile, "r"); + + if (!$fp) { + $this->PushError("put","can't open local file", "Cannot read file \"".$localfile."\""); + return FALSE; + } + if($this->_can_restore and $rest!=0) fseek($fp, $rest); + $pi=pathinfo($localfile); + if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII; + else $mode=FTP_BINARY; + if(!$this->_data_prepare($mode)) { + fclose($fp); + return FALSE; + } + if($this->_can_restore and $rest!=0) $this->restore($rest); + if(!$this->_exec("STOR ".$remotefile, "put")) { + $this->_data_close(); + fclose($fp); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + fclose($fp); + return FALSE; + } + $ret=$this->_data_write($mode, $fp); + fclose($fp); + $this->_data_close(); + if(!$this->_readmsg()) return FALSE; + if(!$this->_checkCode()) return FALSE; + return $ret; + } + + function mput($local=".", $remote=NULL, $continious=false) { + $local=realpath($local); + if(!@file_exists($local)) { + $this->PushError("mput","can't open local folder", "Cannot stat folder \"".$local."\""); + return FALSE; + } + if(!is_dir($local)) return $this->put($local, $remote); + if(empty($remote)) $remote="."; + elseif(!$this->file_exists($remote) and !$this->mkdir($remote)) return FALSE; + if($handle = opendir($local)) { + $list=array(); + while (false !== ($file = readdir($handle))) { + if ($file != "." && $file != "..") $list[]=$file; + } + closedir($handle); + } else { + $this->PushError("mput","can't open local folder", "Cannot read folder \"".$local."\""); + return FALSE; + } + if(empty($list)) return TRUE; + $ret=true; + foreach($list as $el) { + if(is_dir($local."/".$el)) $t=$this->mput($local."/".$el, $remote."/".$el); + else $t=$this->put($local."/".$el, $remote."/".$el); + if(!$t) { + $ret=FALSE; + if(!$continious) break; + } + } + return $ret; + + } + + function mget($remote, $local=".", $continious=false) { + $list=$this->rawlist($remote, "-lA"); + if($list===false) { + $this->PushError("mget","can't read remote folder list", "Can't read remote folder \"".$remote."\" contents"); + return FALSE; + } + if(empty($list)) return true; + if(!@file_exists($local)) { + if(!@mkdir($local)) { + $this->PushError("mget","can't create local folder", "Cannot create folder \"".$local."\""); + return FALSE; + } + } + foreach($list as $k=>$v) { + $list[$k]=$this->parselisting($v); + if($list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]); + } + $ret=true; + foreach($list as $el) { + if($el["type"]=="d") { + if(!$this->mget($remote."/".$el["name"], $local."/".$el["name"], $continious)) { + $this->PushError("mget", "can't copy folder", "Can't copy remote folder \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\""); + $ret=false; + if(!$continious) break; + } + } else { + if(!$this->get($remote."/".$el["name"], $local."/".$el["name"])) { + $this->PushError("mget", "can't copy file", "Can't copy remote file \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\""); + $ret=false; + if(!$continious) break; + } + } + @chmod($local."/".$el["name"], $el["perms"]); + $t=strtotime($el["date"]); + if($t!==-1 and $t!==false) @touch($local."/".$el["name"], $t); + } + return $ret; + } + + function mdel($remote, $continious=false) { + $list=$this->rawlist($remote, "-la"); + if($list===false) { + $this->PushError("mdel","can't read remote folder list", "Can't read remote folder \"".$remote."\" contents"); + return false; + } + + foreach($list as $k=>$v) { + $list[$k]=$this->parselisting($v); + if($list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]); + } + $ret=true; + + foreach($list as $el) { + if ( empty($el) ) + continue; + + if($el["type"]=="d") { + if(!$this->mdel($remote."/".$el["name"], $continious)) { + $ret=false; + if(!$continious) break; + } + } else { + if (!$this->delete($remote."/".$el["name"])) { + $this->PushError("mdel", "can't delete file", "Can't delete remote file \"".$remote."/".$el["name"]."\""); + $ret=false; + if(!$continious) break; + } + } + } + + if(!$this->rmdir($remote)) { + $this->PushError("mdel", "can't delete folder", "Can't delete remote folder \"".$remote."/".$el["name"]."\""); + $ret=false; + } + return $ret; + } + + function mmkdir($dir, $mode = 0777) { + if(empty($dir)) return FALSE; + if($this->is_exists($dir) or $dir == "/" ) return TRUE; + if(!$this->mmkdir(dirname($dir), $mode)) return false; + $r=$this->mkdir($dir, $mode); + $this->chmod($dir,$mode); + return $r; + } + + function glob($pattern, $handle=NULL) { + $path=$output=null; + if(PHP_OS=='WIN32') $slash='\\'; + else $slash='/'; + $lastpos=strrpos($pattern,$slash); + if(!($lastpos===false)) { + $path=substr($pattern,0,-$lastpos-1); + $pattern=substr($pattern,$lastpos); + } else $path=getcwd(); + if(is_array($handle) and !empty($handle)) { + while($dir=each($handle)) { + if($this->glob_pattern_match($pattern,$dir)) + $output[]=$dir; + } + } else { + $handle=@opendir($path); + if($handle===false) return false; + while($dir=readdir($handle)) { + if($this->glob_pattern_match($pattern,$dir)) + $output[]=$dir; + } + closedir($handle); + } + if(is_array($output)) return $output; + return false; + } + + function glob_pattern_match($pattern,$string) { + $out=null; + $chunks=explode(';',$pattern); + foreach($chunks as $pattern) { + $escape=array('$','^','.','{','}','(',')','[',']','|'); + while(strpos($pattern,'**')!==false) + $pattern=str_replace('**','*',$pattern); + foreach($escape as $probe) + $pattern=str_replace($probe,"\\$probe",$pattern); + $pattern=str_replace('?*','*', + str_replace('*?','*', + str_replace('*',".*", + str_replace('?','.{1,1}',$pattern)))); + $out[]=$pattern; + } + if(count($out)==1) return($this->glob_regexp("^$out[0]$",$string)); + else { + foreach($out as $tester) + if($this->my_regexp("^$tester$",$string)) return true; + } + return false; + } + + function glob_regexp($pattern,$probe) { + $sensitive=(PHP_OS!='WIN32'); + return ($sensitive? + ereg($pattern,$probe): + eregi($pattern,$probe) + ); + } + + function dirlist($remote) { + $list=$this->rawlist($remote, "-la"); + if($list===false) { + $this->PushError("dirlist","can't read remote folder list", "Can't read remote folder \"".$remote."\" contents"); + return false; + } + + $dirlist = array(); + foreach($list as $k=>$v) { + $entry=$this->parselisting($v); + if ( empty($entry) ) + continue; + + if($entry["name"]=="." or $entry["name"]=="..") + continue; + + $dirlist[$entry['name']] = $entry; + } + + return $dirlist; + } +// +// +// + function _checkCode() { + return ($this->_code<400 and $this->_code>0); + } + + function _list($arg="", $cmd="LIST", $fnction="_list") { + if(!$this->_data_prepare()) return false; + if(!$this->_exec($cmd.$arg, $fnction)) { + $this->_data_close(); + return FALSE; + } + if(!$this->_checkCode()) { + $this->_data_close(); + return FALSE; + } + $out=""; + if($this->_code<200) { + $out=$this->_data_read(); + $this->_data_close(); + if(!$this->_readmsg()) return FALSE; + if(!$this->_checkCode()) return FALSE; + if($out === FALSE ) return FALSE; + $out=preg_split("/[".CRLF."]+/", $out, -1, PREG_SPLIT_NO_EMPTY); +// $this->SendMSG(implode($this->_eol_code[$this->OS_local], $out)); + } + return $out; + } + +// +// +// +// Gnre une erreur pour traitement externe la classe + function PushError($fctname,$msg,$desc=false){ + $error=array(); + $error['time']=time(); + $error['fctname']=$fctname; + $error['msg']=$msg; + $error['desc']=$desc; + if($desc) $tmp=' ('.$desc.')'; else $tmp=''; + $this->SendMSG($fctname.': '.$msg.$tmp); + return(array_push($this->_error_array,$error)); + } + +// Rcupre une erreur externe + function PopError(){ + if(count($this->_error_array)) return(array_pop($this->_error_array)); + else return(false); + } +} + +$mod_sockets=TRUE; +if (!extension_loaded('sockets')) { + $prefix = (PHP_SHLIB_SUFFIX == 'dll') ? 'php_' : ''; + if(!@dl($prefix . 'sockets.' . PHP_SHLIB_SUFFIX)) $mod_sockets=FALSE; +} + +require_once "class-ftp-".($mod_sockets?"sockets":"pure").".php"; +?> diff --git a/wp-admin/includes/class-pclzip.php b/wp-admin/includes/class-pclzip.php new file mode 100644 index 0000000..082442d --- /dev/null +++ b/wp-admin/includes/class-pclzip.php @@ -0,0 +1,6285 @@ +zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 1); + return; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function create($p_filelist) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::create', "filelist='$p_filelist', ..."); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options detected"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Invalid number / type of arguments"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Ignore an empty filename"); + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_result_list); + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function add($p_filelist) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::add', "filelist='$p_filelist', ..."); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options detected"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_result_list); + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + function listContent() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::listContent', ""); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) + { + unset($p_list); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function extract() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extract", ""); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'"); + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + function extractByIndex($p_index) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::extractByIndex", "index='$p_index', ..."); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Variable list of options"); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Option PCLZIP_OPT_EXTRACT_AS_STRING not set."); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Option PCLZIP_OPT_EXTRACT_AS_STRING set."); + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Static synopsis"); + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return 0; + } + } + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "index='$p_index', path='$v_path', remove_path='$v_remove_path', remove_all_path='".($v_remove_path?'true':'false')."'"); + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function delete() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::delete", ""); + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "$v_size arguments passed to the method"); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + } + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0, PclZip::errorInfo()); + return(0); + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_list); + return $v_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + function deleteByIndex($p_index) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::deleteByIndex", "index='$p_index'"); + + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $p_list); + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + function properties() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::properties", ""); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; + + // ----- Look if file exists + if (@is_file($this->zipname)) + { + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), 0); + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_prop); + return $v_prop; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + function duplicate($p_archive) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::duplicate", ""); + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The parameter is valid PclZip object '".$p_archive->zipname."'"); + + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); + } + + // ----- Look if the $p_archive is a string (so a filename) + else if (is_string($p_archive)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The parameter is a filename '$p_archive'"); + + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + function merge($p_archive_to_add) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::merge", ""); + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, 0); + return(0); + } + + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The parameter is valid PclZip object"); + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); + } + + // ----- Look if the $p_archive_to_add is a string (so a filename) + else if (is_string($p_archive_to_add)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The parameter is a filename"); + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorCode() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); + } + else { + return($this->error_code); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorName($p_with_code=false) + { + $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } + else { + $v_value = 'NoName'; + } + + if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); + } + else { + return($v_value); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorInfo($p_full=false) + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); + } + else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); + } + else { + return($this->error_string." [code ".$this->error_code."]"); + } + } + } + // -------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------- +// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** +// ***** ***** +// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** +// -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + function privCheckFormat($p_level=0) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFormat", ""); + $v_result = true; + + // ----- Reset the file system cache + clearstatcache(); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo()); + return(false); + } + + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, false, PclZip::errorInfo()); + return(false); + } + + // ----- Check the magic code + // TBC + + // ----- Check the central header + // TBC + + // ----- Check each file header + // TBC + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privParseOptions", ""); + $v_result=1; + + // ----- Read the options + $i=0; + while ($i<$p_size) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Looking for table index $i, option = '".PclZipUtilOptionText($p_options_list[$i])."(".$p_options_list[$i].")'"); + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH : + case PCLZIP_OPT_REMOVE_PATH : + case PCLZIP_OPT_ADD_PATH : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_THRESHOLD : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i+1]; + if ((!is_integer($v_value)) || ($v_value<0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value*1048576; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_ON : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + break; + + case PCLZIP_OPT_TEMP_FILE_OFF : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if ( is_string($p_options_list[$i+1]) + && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." set with an empty value is ignored."); + } + break; + + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG : + case PCLZIP_OPT_BY_PREG : + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT : + case PCLZIP_OPT_ADD_COMMENT : + case PCLZIP_OPT_PREPEND_COMMENT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, + "Missing parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, + "Wrong parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is a string '".$p_options_list[$i+1]."'"); + + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } + else if (is_integer($p_options_list[$i+1])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an integer '".$p_options_list[$i+1]."'"); + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Index value is an array"); + $v_work_list = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($p_options_list[$i])." = '".$v_result_list[$p_options_list[$i]]."'"); + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT : + case PCLZIP_CB_POST_EXTRACT : + case PCLZIP_CB_PRE_ADD : + case PCLZIP_CB_POST_ADD : + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "call-back ".PclZipUtilOptionText($p_options_list[$i])." = '".$v_function_name."'"); + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '" + .$p_options_list[$i]."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Next options + $i++; + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")"); + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + } + } + + // ----- Look for default values + if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3,"Calculate auto threshold"); + + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOptionDefaultThreshold() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privOptionDefaultThreshold(&$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privOptionDefaultThreshold", ""); + $v_result=1; + + if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3,"Create an auto-threshold for use of temporay files"); + // ----- Get 'memory_limit' configuration value + $v_memory_limit = ini_get('memory_limit'); + $v_memory_limit = trim($v_memory_limit); + $last = strtolower(substr($v_memory_limit, -1)); + + if($last == 'g') + //$v_memory_limit = $v_memory_limit*1024*1024*1024; + $v_memory_limit = $v_memory_limit*1073741824; + if($last == 'm') + //$v_memory_limit = $v_memory_limit*1024*1024; + $v_memory_limit = $v_memory_limit*1048576; + if($last == 'k') + $v_memory_limit = $v_memory_limit*1024; + + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3,"Current memory usage : ".memory_get_usage(TRUE)." bytes"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3,"Threshold value is : ".$p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]." bytes"); + + // ----- Sanity check : No threshold if value lower than 1M + if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3,"Unset the threshold (value ".$p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD].") because under 1Mo sanity check)"); + unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privFileDescrParseAtt", ""); + $v_result=1; + + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + break; + + case PCLZIP_ATT_FILE_NEW_SHORT_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + break; + + case PCLZIP_ATT_FILE_NEW_FULL_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + break; + + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['comment'] = $v_value; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + break; + + case PCLZIP_ATT_FILE_MTIME : + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + $p_filedescr['mtime'] = $v_value; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + break; + + case PCLZIP_ATT_FILE_CONTENT : + $p_filedescr['content'] = $v_value; + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "".PclZipUtilOptionText($v_key)." = '".$v_value."'"); + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '".$v_key."'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Detect a mandatory option : ".PclZipUtilOptionText($key)."(".$key.")"); + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + } + } + + // end foreach + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // This method look for each item of the list to see if its a file, a folder + // or a string to be added as file. For any other type of files (link, other) + // just ignore the item. + // Then prepare the information that will be stored for that file. + // When its a folder, expand the folder with all the files that are in that + // folder (recursively). + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privFileDescrExpand", ""); + $v_result=1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i=0; $iprivCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Looking for '".$v_item_handler."' in the directory"); + + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if ($v_descr['stored_filename'] != $v_descr['filename']) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; + } + else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to open dir '".$v_descr['filename']."' in read mode. Skipped."); + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Concat the resulting list + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Merging result list (size '".sizeof($v_result_list)."') with dirlist (size '".sizeof($v_dirlist_descr)."')"); + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "merged result list is size '".sizeof($v_result_list)."'"); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Nothing in this folder to expand."); + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCreate", "list"); + $v_result=1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAdd", "list"); + $v_result=1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive does not exist, or is empty, create it."); + + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "New offset of central dir : $v_offset"); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = $v_central_dir['comment']; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privOpenFd($p_mode) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privOpenFd", 'mode='.$p_mode); + $v_result=1; + + // ----- Look if already open + if ($this->zip_fd != 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Open file in '.$p_mode.' mode'); + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privCloseFd() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCloseFd", ""); + $v_result=1; + + if ($this->zip_fd != 0) + @fclose($this->zip_fd); + $this->zip_fd = 0; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- +// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddList", "list"); + $v_result=1; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Create the Central Dir files header + for ($i=0,$v_count=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFileList", "filedescr_list"); + $v_result=1; + $v_header = array(); + + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Before add, list have ".$v_nb." elements"); + + // ----- Loop on the files + for ($j=0; ($jprivAddFile($p_filedescr_list[$j], $v_header, + $p_options); + if ($v_result != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "After add, list have ".$v_nb." elements"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFile($p_filedescr, &$p_header, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFile", "filename='".$p_filedescr['filename']."'"); + $v_result=1; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'Stored filename is NOT the same "'.$v_stored_filename.'"'); + } + else { + $v_stored_filename = $p_filedescr['stored_filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'Stored filename is the same'); + } + */ + + // ----- Set the file properties + clearstatcache(); + $p_header['version'] = 20; + $p_header['version_extracted'] = 10; + $p_header['flag'] = 0; + $p_header['compression'] = 0; + $p_header['crc'] = 0; + $p_header['compressed_size'] = 0; + $p_header['filename_len'] = strlen($p_filename); + $p_header['extra_len'] = 0; + $p_header['disk'] = 0; + $p_header['internal'] = 0; + $p_header['offset'] = 0; + $p_header['filename'] = $p_filename; +// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; + $p_header['stored_filename'] = $p_filedescr['stored_filename']; + $p_header['extra'] = ''; + $p_header['status'] = 'ok'; + $p_header['index'] = -1; + + // ----- Look for regular file + if ($p_filedescr['type']=='file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for regular folder + else if ($p_filedescr['type']=='folder') { + $p_header['external'] = 0x00000010; + $p_header['mtime'] = filemtime($p_filename); + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for virtual file + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = strlen($p_filedescr['content']); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header external extension '".sprintf("0x%X",$p_header['external'])."'"); + + // ----- Look for filetime + if (isset($p_filedescr['mtime'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3,"Overload mtime value with :'".$p_filedescr['mtime']."'"); + $p_header['mtime'] = $p_filedescr['mtime']; + } + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['mtime'] = time(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Virtual file : use current time '".$p_header['mtime']."' for mtime value."); + } + else { + $p_header['mtime'] = filemtime($p_filename); + } + + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } + else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } + + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_ADD]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } + + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New stored filename is '".$p_header['stored_filename']."'"); + } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { + + // ----- Look for a file + if ($p_filedescr['type'] == 'file') { + // ----- Look for using temporary file to zip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { + $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Use "in memory" zip algo + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"In memory compression."); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"Current memory usage : ".memory_get_usage(TRUE)." bytes"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"Current memory peak : ".memory_get_peak_usage(TRUE)." bytes"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a file"); + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"Memory usage after reading file : ".memory_get_usage(TRUE)." bytes"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"Memory peak after reading file : ".memory_get_peak_usage(TRUE)." bytes"); + + // ----- Close the file + @fclose($v_file); + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be compressed"); + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will be compressed"); + // ----- Compress the content + $v_content = @gzdeflate($v_content); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"Memory usage after gzdeflate : ".memory_get_usage(TRUE)." bytes"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2,"Memory peak after gzdeflate : ".memory_get_peak_usage(TRUE)." bytes"); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + + } + + } + + // ----- Look for a virtual file (a file from string) + else if ($p_filedescr['type'] == 'virtual_file') { + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Add by string"); + $v_content = $p_filedescr['content']; + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be compressed"); + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will be compressed"); + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } + + // ----- Look for a directory + else if ($p_filedescr['type'] == 'folder') { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a folder"); + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) + { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + } + } + + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_ADD]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privAddFileUsingTempFile", "filename='".$p_filedescr['filename']."'"); + $v_result=PCLZIP_ERR_NO_ERROR; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "'".$p_filename."' is a file"); + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Creates a compressed temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = filesize($p_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read ".$v_read_size." bytes"); + $v_buffer = @fread($v_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @gzputs($v_file_compressed, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file); + @gzclose($v_file_compressed); + + // ----- Check the minimum file size + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "gzip file size ".filesize($v_gzip_temp_name)); + if (filesize($v_gzip_temp_name) < 18) { + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the compressed attributes + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the gzip file header + $v_binary_data = @fread($v_file_compressed, 10); + $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); + + // ----- Check some parameters + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[id1]='.bin2hex($v_data_header['id1'])); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[id2]='.bin2hex($v_data_header['id2'])); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[cm]='.bin2hex($v_data_header['cm'])); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[flag]='.bin2hex($v_data_header['flag'])); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[mtime]='.$v_data_header['mtime']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[xfl]='.bin2hex($v_data_header['xfl'])); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, '$v_data_header[os]='.bin2hex($v_data_header['os'])); + $v_data_header['os'] = bin2hex($v_data_header['os']); + + // ----- Read the gzip file footer + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File position after header ".ftell($v_file_compressed)); + @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File position at beginning of footer ".ftell($v_file_compressed)); + $v_binary_data = @fread($v_file_compressed, 8); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File position after footer ".ftell($v_file_compressed)); + $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); + + // ----- Set the attributes + $p_header['compression'] = ord($v_data_header['cm']); + //$p_header['mtime'] = $v_data_header['mtime']; + $p_header['crc'] = $v_data_footer['crc']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Compressed size ".(filesize($v_gzip_temp_name)-18)); + $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Add the compressed data + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) + { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + fseek($v_file_compressed, 10); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File position before reading compressed data ".ftell($v_file_compressed)); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, ' '.$p_header['compressed_size'].' bytes to read'); + $v_size = $p_header['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read ".$v_read_size." bytes"); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Unlink the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCalculateStoredFilename(&$p_filedescr, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCalculateStoredFilename", "filename='".$p_filedescr['filename']."'"); + $v_result=1; + + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } + else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } + else { + $p_remove_dir = ''; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Remove path ='".$p_remove_dir."'"); + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + else { + $p_remove_all_dir = 0; + } + + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Changing full name of '".$p_filename."' for '".$v_stored_filename."'"); + } + + // ----- Look for path and/or short name change + else { + + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Changing short name of '".$p_filename."' for '".$v_stored_filename."'"); + } + else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Remove all path selected change '".$p_filename."' for '".$v_stored_filename."'"); + } + // ----- Look for partial path remove + else if ($p_remove_dir != "") { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Partial path to remove"); + if (substr($p_remove_dir, -1) != '/') + $p_remove_dir .= "/"; + + if ( (substr($p_filename, 0, 2) == "./") + || (substr($p_remove_dir, 0, 2) == "./")) { + + if ( (substr($p_filename, 0, 2) == "./") + && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ( (substr($p_filename, 0, 2) != "./") + && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, + $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Path to remove is the current folder"); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Remove path '$p_remove_dir' in file '$v_stored_filename'"); + $v_stored_filename = substr($v_stored_filename, + strlen($p_remove_dir)); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Result is '$v_stored_filename'"); + } + } + } + + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); + + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") + $v_stored_filename = $p_add_dir.$v_stored_filename; + else + $v_stored_filename = $p_add_dir."/".$v_stored_filename; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Add path '$p_add_dir' in file '$p_filename' = '$v_stored_filename'"); + } + } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Stored filename will be '".$p_filedescr['stored_filename']."', strlen ".strlen($p_filedescr['stored_filename'])); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteFileHeader", 'file="'.$p_header['filename'].'", stored as "'.$p_header['stored_filename'].'"'); + $v_result=1; + + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'File offset of the header :'.$p_header['offset']); + + // ----- Transform UNIX mtime to DOS format mdate/mtime + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, + $p_header['version_extracted'], $p_header['flag'], + $p_header['compression'], $v_mtime, $v_mdate, + $p_header['crc'], $p_header['compressed_size'], + $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len']); + + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteCentralFileHeader", 'file="'.$p_header['filename'].'", stored as "'.$p_header['stored_filename'].'"'); + $v_result=1; + + // TBC + //for(reset($p_header); $key = key($p_header); next($p_header)) { + // //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "header[$key] = ".$p_header[$key]); + //} + + // ----- Transform UNIX mtime to DOS format mdate/mtime + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment size : \''.$p_header['comment_len'].'\''); + + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, + $p_header['version'], $p_header['version_extracted'], + $p_header['flag'], $p_header['compression'], + $v_mtime, $v_mdate, $p_header['crc'], + $p_header['compressed_size'], $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len'], $p_header['comment_len'], + $p_header['disk'], $p_header['internal'], + $p_header['external'], $p_header['offset']); + + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) + { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privWriteCentralHeader", 'nb_entries='.$p_nb_entries.', size='.$p_size.', offset='.$p_offset.', comment="'.$p_comment.'"'); + $v_result=1; + + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, + $p_nb_entries, $p_size, + $p_offset, strlen($p_comment)); + + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); + + // ----- Write the variable fields + if (strlen($p_comment) != 0) + { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privList() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privList(&$p_list) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privList", "list"); + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of Central Dir + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Offset : ".$v_central_dir['offset']."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position in file : ".ftell($this->zip_fd)."'"); + + // ----- Read each entry + for ($i=0; $i<$v_central_dir['entries']; $i++) + { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + $v_header['index'] = $i; + + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privConvertHeader2FileInfo($p_header, &$p_info) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privConvertHeader2FileInfo", "Filename='".$p_header['filename']."'"); + $v_result=1; + + // ----- Get the interesting attributes + $v_temp_path = PclZipUtilPathReduction($p_header['filename']); + $p_info['filename'] = $v_temp_path; + $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); + $p_info['stored_filename'] = $v_temp_path; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privExtractByRule", "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'"); + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check the path + if ( ($p_path == "") + || ( (substr($p_path, 0, 1) != "/") + && (substr($p_path, 0, 3) != "../") + && (substr($p_path,1,2)!=":/"))) + $p_path = "./".$p_path; + + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) + { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'"); + $p_path = substr($p_path, 0, strlen($p_path)-1); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]"); + } + } + + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) + { + $p_remove_path .= '/'; + } + $p_remove_path_size = strlen($p_remove_path); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result = $this->privOpenFd('rb')) != 1) + { + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + + // ----- Read each entry + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry : '$i'"); + + // ----- Read next Central dir entry + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position before rewind : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'"); + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path"); + $v_extract = true; + } + } + // ----- Look for a filename + elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one."); + $v_extract = true; + } + } + } + + // ----- Look for extract by ereg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'"); + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_extract = true; + } + } + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'"); + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_extract = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'"); + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range"); + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop"); + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop"); + break; + } + } + } + + // ----- Look for no rule, which means extract all the archive + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with no rule (extract all)"); + $v_extract = true; + } + + // ----- Check compression method + if ( ($v_extract) + && ( ($v_header['compression'] != 8) + && ($v_header['compression'] != 0))) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported compression method (".$v_header['compression'].")"); + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, + "Filename '".$v_header['stored_filename']."' is " + ."compressed by an unsupported compression " + ."method (".$v_header['compression'].") "); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unsupported file encryption"); + $v_header['status'] = 'unsupported_encryption'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, + "Unsupported encryption for " + ." filename '".$v_header['stored_filename'] + ."'"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "No need for extract"); + $v_result = $this->privConvertHeader2FileInfo($v_header, + $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file '".$v_header['filename']."', index '$i'"); + + // ----- Go to the file position + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_header['offset'])) + { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for extraction in standard output + elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) + && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for normal extraction + else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, + $p_path, $p_remove_path, + $p_remove_all_path, + $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result1); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } + + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFile', "path='$p_path', remove_path='$p_remove_path', remove_all_path='".($p_remove_all_path?'true':'false')."'"); + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'"); + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The entry is a folder : need to be filtered"); + + $p_entry['status'] = "filtered"; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "All path is removed"); + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); + } + + // ----- Look for path to remove + else if ($p_remove_path != "") + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Look for some path to remove"); + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The folder is the same as the removed path '".$p_entry['filename']."'"); + + // ----- Change the file status + $p_entry['status'] = "filtered"; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '".$p_entry['filename']."'"); + + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Resulting file is '".$p_entry['filename']."'"); + } + } + + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; + } + + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Check the extract directory restriction"); + $v_inclusion + = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], + $p_entry['filename']); + if ($v_inclusion == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_EXTRACT_DIR_RESTRICTION is selected, file is outside restriction"); + + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, + "Filename '".$p_entry['filename']."' is " + ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'"); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'"); + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$p_entry['filename']."' already exists"); + + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is a directory"); + + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, + "Filename '".$p_entry['filename']."' is " + ."already used by an existing directory"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + // ----- Look if file is write protected + else if (!is_writeable($p_entry['filename'])) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is write protected"); + + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Filename '".$p_entry['filename']."' exists " + ."and is write protected"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Look if the extracted file is older + else if (filemtime($p_entry['filename']) > $p_entry['mtime']) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is newer (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")"); + // ----- Change the file status + if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) + && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_REPLACE_NEWER is selected, file will be replaced"); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File will not be replaced"); + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "PCLZIP_OPT_STOP_ON_ERROR is selected, extraction will be stopped"); + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Newer version of '".$p_entry['filename']."' exists " + ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Existing file '".$p_entry['filename']."' is older than the extrated one - will be replaced by the extracted one (".date("l dS of F Y h:i:s A", filemtime($p_entry['filename'])).") than the extracted file (".date("l dS of F Y h:i:s A", $p_entry['mtime']).")"); + } + } + + // ----- Check the directory availability and create it if necessary + else { + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) + $v_dir_to_check = $p_entry['filename']; + else if (!strstr($p_entry['filename'], "/")) + $v_dir_to_check = ""; + else + $v_dir_to_check = dirname($p_entry['filename']); + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '".$p_entry['filename']."'"); + + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; + + // ----- Return + ////--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + //return $v_result; + $v_result = 1; + } + } + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file"); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode"); + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read '".$p_entry['size']."' bytes"); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read $v_read_size bytes"); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + + + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (Compression method ".$p_entry['compression'].")"); + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File is encrypted"); + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + + // ----- Look for using temporary file to unzip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Look for extract in memory + else { + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read '".$p_entry['compressed_size']."' compressed bytes"); + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === FALSE) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to inflate compressed file"); + + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode"); + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + + } + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "chmod option activated '".$p_options[PCLZIP_OPT_SET_CHMOD]."'"); + + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done"); + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileUsingTempFile(&$p_entry, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileUsingTempFile', "filename='".$p_entry['filename']."'"); + $v_result=1; + + // ----- Creates a temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Start extraction of '".$p_entry['filename']."'"); + + // ----- Write gz file format header + $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); + @fwrite($v_dest_file, $v_binary_data, 10); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Compressed Size :".$v_size.""); + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read ".$v_read_size." bytes"); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Write gz file format footer + $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); + @fwrite($v_dest_file, $v_binary_data, 8); + + // ----- Close the temporary file + @fclose($v_dest_file); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Error while opening '".$p_entry['filename']."' in write binary mode"); + $p_entry['status'] = "write_error"; + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the temporary gz file + if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, 'File size is '.filesize($v_gzip_temp_name)); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes"); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size :".$v_size.""); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Read ".$v_read_size." bytes"); + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + @fclose($v_dest_file); + @gzclose($v_src_file); + + // ----- Delete the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileInOutput(&$p_entry, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileInOutput', ""); + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'"); + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A pre-callback '".$p_options[PCLZIP_CB_PRE_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "New filename is '".$p_entry['filename']."'"); + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '".$p_entry['filename']."', size '$v_header[size]'"); + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes"); + + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Reading '".$p_entry['size']."' bytes"); + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done"); + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "A post-callback '".$p_options[PCLZIP_CB_POST_EXTRACT]."()') is defined for the extraction"); + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + + // ----- Look for abort result + if ($v_result == 2) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "User callback abort the extraction"); + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileAsString(&$p_entry, &$p_string) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privExtractFileAsString', "p_entry['filename']='".$p_entry['filename']."'"); + $v_result=1; + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found file '".$v_header['filename']."', size '".$v_header['size']."'"); + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting file in string (with path) '".$p_entry['filename']."', size '$v_header[size]'"); + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file +// if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting an un-compressed file"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Reading '".$p_entry['size']."' bytes"); + + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extracting a compressed file (compression method '".$p_entry['compression']."')"); + + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === FALSE) { + // TBC + } + } + + // ----- Trace + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Extraction done"); + } + else { + // TBC : error : can not extract a folder in a string + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadFileHeader", ""); + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'"); + $v_data = unpack('Vid', $v_binary_data); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'"); + + // ----- Check signature + if ($v_data['id'] != 0x04034b50) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid File header"); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the values + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header : '".$v_binary_data."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Header (Hex) : '".bin2hex($v_binary_data)."'"); + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + + // ----- Get filename + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "File name length : ".$v_data['filename_len']); + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename : \''.$p_header['filename'].'\''); + + // ----- Get extra_fields + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extra field length : ".$v_data['extra_len']); + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } + else { + $p_header['extra'] = ''; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Extra field : \''.bin2hex($p_header['extra']).'\''); + + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : ('.$p_header['version_extracted'].') \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\''); + $p_header['compression'] = $v_data['compression']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compression method : \''.$p_header['compression'].'\''); + $p_header['size'] = $v_data['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_header['size'].'\''); + $p_header['compressed_size'] = $v_data['compressed_size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_header['compressed_size'].'\''); + $p_header['crc'] = $v_data['crc']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\''); + $p_header['flag'] = $v_data['flag']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Flag : \''.$p_header['flag'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Flag bit 11 (from right) : \''.($p_header['flag']&0x0400).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Flag bit 11 (from left) : \''.($p_header['flag']&0x0020).'\''); + $p_header['filename_len'] = $v_data['filename_len']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Filename_len : \''.$p_header['filename_len'].'\''); + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + else + { + $p_header['mtime'] = time(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + + // TBC + //for(reset($v_data); $key = key($v_data); next($v_data)) { + // //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Attribut[$key] = ".$v_data[$key]); + //} + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set the status field + $p_header['status'] = "ok"; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadCentralFileHeader(&$p_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadCentralFileHeader", ""); + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary data is : '".sprintf("%08x", $v_binary_data)."'"); + $v_data = unpack('Vid', $v_binary_data); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'"); + + // ----- Check signature + if ($v_data['id'] != 0x02014b50) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid Central Dir File signature"); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the values + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header : '".$v_binary_data."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Header (Hex) : '".bin2hex($v_binary_data)."'"); + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + + // ----- Get filename + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "File name length : ".$p_header['filename_len']); + if ($p_header['filename_len'] != 0) + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + else + $p_header['filename'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Filename : \''.$p_header['filename'].'\''); + + // ----- Get extra + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Extra length : ".$p_header['extra_len']); + if ($p_header['extra_len'] != 0) + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + else + $p_header['extra'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Extra : \''.$p_header['extra'].'\''); + + // ----- Get comment + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Comment length : ".$p_header['comment_len']); + if ($p_header['comment_len'] != 0) + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + else + $p_header['comment'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Comment : \''.$p_header['comment'].'\''); + + // ----- Extract properties + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version : \''.($p_header['version']/10).'.'.($p_header['version']%10).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Version need to extract : \''.($p_header['version_extracted']/10).'.'.($p_header['version_extracted']%10).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Size : \''.$p_header['size'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Compressed Size : \''.$p_header['compressed_size'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'CRC : \''.sprintf("0x%X", $p_header['crc']).'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Flag : \''.$p_header['flag'].'\''); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Offset : \''.$p_header['offset'].'\''); + + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + else + { + $p_header['mtime'] = time(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Date is actual : \''.date("d/m/y H:i:s", $p_header['mtime']).'\''); + } + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set default status to ok + $p_header['status'] = 'ok'; + + // ----- Look if it is a directory + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Internal (Hex) : '".sprintf("Ox%04X", $p_header['internal'])."'"); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "External (Hex) : '".sprintf("Ox%04X", $p_header['external'])."' (".(($p_header['external']&0x00000010)==0x00000010?'is a folder':'is a file').')'); + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Force folder external : \''.sprintf("Ox%04X", $p_header['external']).'\''); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Header of filename : \''.$p_header['filename'].'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privCheckFileHeaders", ""); + $v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename" : TBC To Be Completed'); + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "version_extracted" : TBC To Be Completed'); + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "flag" : TBC To Be Completed'); + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "compression" : TBC To Be Completed'); + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "mtime" : TBC To Be Completed'); + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Bad check "filename_len" : TBC To Be Completed'); + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Purpose bit flag bit 3 set !'); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'File size, compression size and crc found in central header'); + $p_local_header['size'] = $p_central_header['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size : \''.$p_local_header['size'].'\''); + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Compressed Size : \''.$p_local_header['compressed_size'].'\''); + $p_local_header['crc'] = $p_central_header['crc']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'CRC : \''.sprintf("0x%X", $p_local_header['crc']).'\''); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadEndCentralDir(&$p_central_dir) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privReadEndCentralDir", ""); + $v_result=1; + + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Size of the file :$v_size"); + @fseek($this->zip_fd, $v_size); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position at end of zip file : \''.ftell($this->zip_fd).'\''); + if (@ftell($this->zip_fd) != $v_size) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Look for central dir with no comment'); + @fseek($this->zip_fd, $v_size-22); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after min central position : \''.ftell($this->zip_fd).'\''); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Binary data is : '".sprintf("%08x", $v_binary_data)."'"); + $v_data = @unpack('Vid', $v_binary_data); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Binary signature is : '".sprintf("0x%08x", $v_data['id'])."'"); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Found central dir at the default position."); + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); + } + + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Start extended search of end central dir'); + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) + $v_maximum_size = $v_size; + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Position after max central position : \''.ftell($this->zip_fd).'\''); + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) + { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + // $v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, 'Found End Central Dir signature at position : \''.ftell($this->zip_fd).'\''); + $v_pos++; + break; + } + + $v_pos++; + } + + // ----- Look if not found end of central dir + if ($v_pos == $v_size) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Unable to find End of Central Dir Record signature"); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Extract the values + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record : '".$v_binary_data."'"); + ////--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Central Dir Record (Hex) : '".bin2hex($v_binary_data)."'"); + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + + // ----- Check the global size + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Comment length : ".$v_data['comment_size']); + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "The central dir is not at the end of the archive. Some trailing bytes exists after the archive."); + + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, + 'The central dir is not at the end of the archive.' + .' Some trailing bytes exists after the archive.'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + } + + // ----- Get comment + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment size : \''.$v_data['comment_size'].'\''); + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } + else + $p_central_dir['comment'] = ''; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Comment : \''.$p_central_dir['comment'].'\''); + + $p_central_dir['entries'] = $v_data['entries']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries : \''.$p_central_dir['entries'].'\''); + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Nb of entries for this disk : \''.$p_central_dir['disk_entries'].'\''); + $p_central_dir['offset'] = $v_data['offset']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Offset of Central Dir : \''.$p_central_dir['offset'].'\''); + $p_central_dir['size'] = $v_data['size']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Size of Central Dir : \''.$p_central_dir['size'].'\''); + $p_central_dir['disk'] = $v_data['disk']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Disk number : \''.$p_central_dir['disk'].'\''); + $p_central_dir['disk_start'] = $v_data['disk_start']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, 'Start disk number : \''.$p_central_dir['disk_start'].'\''); + + // TBC + //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + // //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "central_dir[$key] = ".$p_central_dir[$key]); + //} + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDeleteByRule(&$p_result_list, &$p_options) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDeleteByRule", ""); + $v_result=1; + $v_list_detail = array(); + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in file : ".ftell($this->zip_fd)."'"); + + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position before rewind : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Read next file header entry (index '$i')"); + + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename (index '$i') : '".$v_header_list[$v_nb_extracted]['stored_filename']."'"); + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByName'"); + + // ----- Look if the filename is in the list + for ($j=0; ($j strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The directory is in the file path"); + $v_found = true; + } + elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ + && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The entry is the searched directory"); + $v_found = true; + } + } + // ----- Look for a filename + elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "The file is the right one."); + $v_found = true; + } + } + } + + // ----- Look for extract by ereg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract by ereg '".$p_options[PCLZIP_OPT_BY_EREG]."'"); + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_found = true; + } + } + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByEreg'"); + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Filename match the regular expression"); + $v_found = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Extract with rule 'ByIndex'"); + + // ----- Look if the index is in the list + for ($j=$j_start; ($j=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Found as part of an index range"); + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Do not look this index range for next loop"); + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Index range is greater than index, stop loop"); + break; + } + } + } + else { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "No argument mean remove all file"); + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_header_list[$v_nb_extracted]['stored_filename']."', index '$i' need to be deleted"); + unset($v_header_list[$v_nb_extracted]); + } + else + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 2, "File '".$v_header_list[$v_nb_extracted]['stored_filename']."', index '$i' will not be deleted"); + $v_nb_extracted++; + } + } + + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); + + // ----- Open the temporary zip file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary write mode"); + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look which file need to be kept + for ($i=0; $izip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after rewind : ".ftell($this->zip_fd)."'"); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position after fseek : ".ftell($this->zip_fd)."'"); + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, + $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Offset for this file is '".$v_header_list[$i]['offset']."'"); + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "New offset of central dir : $v_offset"); + + // ----- Re-Create the Central Dir files header + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Creates the new central directory"); + for ($i=0; $iprivWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Creates the central directory footer"); + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + } + + // ----- Remove every files : reset the file + else if ($v_central_dir['entries'] != 0) { + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + $this->privCloseFd(); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + function privDirCheck($p_dir, $p_is_dir=false) + { + $v_result = 1; + + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDirCheck", "entry='$p_dir', is_dir='".($p_is_dir?"true":"false")."'"); + + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1)=='/')) + { + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Looking for entry '$p_dir'"); + + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) + { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, "'$p_dir' is a directory"); + return 1; + } + + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Parent directory is '$p_parent_dir'"); + + // ----- Just a check + if ($p_parent_dir != $p_dir) + { + // ----- Look for parent directory + if ($p_parent_dir != "") + { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) + { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + } + } + + // ----- Create the directory + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Create directory '$p_dir'"); + if (!@mkdir($p_dir, 0777)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result, "Directory '$p_dir' created"); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privMerge(&$p_archive_to_add) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privMerge", "archive='".$p_archive_to_add->zipname."'"); + $v_result=1; + + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive to add does not exist. End of merge."); + + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look if the archive exists + if (!is_file($this->zipname)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive does not exist, duplicate the archive_to_add."); + + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in zip : ".ftell($this->zip_fd)."'"); + @rewind($this->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in zip : ".ftell($this->zip_fd)."'"); + + // ----- Open the archive_to_add file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open archive_to_add in binary read mode"); + if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) + { + $this->privCloseFd(); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Go to beginning of File + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in archive_to_add : ".ftell($p_archive_to_add->zip_fd)."'"); + @rewind($p_archive_to_add->zip_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Position in archive_to_add : ".ftell($p_archive_to_add->zip_fd)."'"); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "New offset of central dir : $v_offset"); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd)-$v_offset; + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDuplicate($p_archive_filename) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZip::privDuplicate", "archive_filename='$p_archive_filename'"); + $v_result=1; + + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Archive to duplicate does not exist. End of duplicate."); + + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the zip file + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_result=$this->privOpenFd('wb')) != 1) + { + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Open the temporary file in write mode + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode"); + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) + { + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, PclZip::errorCode(), PclZip::errorInfo()); + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Read $v_read_size bytes"); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorLog($p_error_code=0, $p_error_string='') + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } + else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorReset() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } + else { + $this->error_code = 0; + $this->error_string = ''; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDisableMagicQuotes() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privDisableMagicQuotes', ""); + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote already disabled"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Current magic_quotes_runtime status is '".($this->magic_quotes_status==0?'disable':'enable')."'"); + + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Disable magic_quotes"); + @set_magic_quotes_runtime(0); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privSwapBackMagicQuotes() + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, 'PclZip::privSwapBackMagicQuotes', ""); + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Functions *et_magic_quotes_runtime are not supported"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "magic_quote not modified"); + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Enable back magic_quotes"); + @set_magic_quotes_runtime($this->magic_quotes_status); + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + } + // End of class + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathReduction() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilPathReduction($p_dir) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathReduction", "dir='$p_dir'"); + $v_result = ""; + + // ----- Look for not empty path + if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } + else if ($v_list[$i] == "..") { + $v_skip++; + } + else if ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 3, "Invalid path is unchanged"); + $v_skip = 0; + } + } + // ----- Last '/' i.e. indicates a directory + else if ($i == (sizeof($v_list)-1)) { + $v_result = $v_list[$i]; + } + // ----- Double '/' inside the path + else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } + else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } + else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathInclusion() + // Description : + // This function indicates if the path $p_path is under the $p_dir tree. Or, + // said in an other way, if the file or sub-dir $p_path is inside the dir + // $p_dir. + // The function indicates also if the path is exactly the same as the dir. + // This function supports path with duplicated '/' like '//', but does not + // support '.' or '..' statements. + // Parameters : + // Return Values : + // 0 if $p_path is not inside directory $p_dir + // 1 if $p_path is inside directory $p_dir + // 2 if $p_path is exactly the same as $p_dir + // -------------------------------------------------------------------------------- + function PclZipUtilPathInclusion($p_dir, $p_path) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilPathInclusion", "dir='$p_dir', path='$p_path'"); + $v_result = 1; + + // ----- Look for path beginning by ./ + if ( ($p_dir == '.') + || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_dir '".$p_dir."'"); + } + if ( ($p_path == '.') + || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Replacing ./ by full path in p_path '".$p_path."'"); + } + + // ----- Explode dir and path by directory separator + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); + $v_list_path_size = sizeof($v_list_path); + + // ----- Study directories paths + $i = 0; + $j = 0; + while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Working on dir($i)='".$v_list_dir[$i]."' and path($j)='".$v_list_path[$j]."'"); + + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Items ($i,$j) are different"); + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; + } + + // ----- Look if everything seems to be the same + if ($v_result) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Look for tie break"); + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Looking on dir($i)='".($i < $v_list_dir_size?$v_list_dir[$i]:'')."' and path($j)='".($j < $v_list_path_size?$v_list_path[$j]:'')."'"); + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } + else if ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilCopyBlock() + // Description : + // Parameters : + // $p_mode : read/write compression mode + // 0 : src & dest normal + // 1 : src gzip, dest normal + // 2 : src normal, dest gzip + // 3 : src & dest gzip + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilCopyBlock", "size=$p_size, mode=$p_mode"); + $v_result = 1; + + if ($p_mode==0) + { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Src offset before read :".(@ftell($p_src))); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Dest offset before write :".(@ftell($p_dest))); + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Src offset after read :".(@ftell($p_src))); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Dest offset after write :".(@ftell($p_dest))); + } + else if ($p_mode==1) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==2) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==3) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 4, "Read $v_read_size bytes"); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilRename() + // Description : + // This function tries to do a simple rename() function. If it fails, it + // tries to copy the $p_src file in a new $p_dest file and then unlink the + // first one. + // Parameters : + // $p_src : Old filename + // $p_dest : New filename + // Return Values : + // 1 on success, 0 on failure. + // -------------------------------------------------------------------------------- + function PclZipUtilRename($p_src, $p_dest) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilRename", "source=$p_src, destination=$p_dest"); + $v_result = 1; + + // ----- Try to rename the files + if (!@rename($p_src, $p_dest)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to rename file, try copy+unlink"); + + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to copy file"); + $v_result = 0; + } + else if (!@unlink($p_src)) { + //--(MAGIC-PclTrace)--//PclTraceFctMessage(__FILE__, __LINE__, 5, "Fail to unlink old filename"); + $v_result = 0; + } + } + + // ----- Return + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilOptionText() + // Description : + // Translate option value in text. Mainly for debug purpose. + // Parameters : + // $p_option : the option value. + // Return Values : + // The option text value. + // -------------------------------------------------------------------------------- + function PclZipUtilOptionText($p_option) + { + //--(MAGIC-PclTrace)--//PclTraceFctStart(__FILE__, __LINE__, "PclZipUtilOptionText", "option='".$p_option."'"); + + $v_list = get_defined_constants(); + for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if (( ($v_prefix == 'PCLZIP_OPT') + || ($v_prefix == 'PCLZIP_CB_') + || ($v_prefix == 'PCLZIP_ATT')) + && ($v_list[$v_key] == $p_option)) { + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_key); + return $v_key; + } + } + + $v_result = 'Unknown'; + + //--(MAGIC-PclTrace)--//PclTraceFctEnd(__FILE__, __LINE__, $v_result); + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilTranslateWinPath() + // Description : + // Translate windows path by replacing '\' by '/' and optionally removing + // drive letter. + // Parameters : + // $p_path : path to translate. + // $p_remove_disk_letter : true | false + // Return Values : + // The path translated. + // -------------------------------------------------------------------------------- + function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) + { + if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } + } + return $p_path; + } + // -------------------------------------------------------------------------------- + + +?> diff --git a/wp-admin/includes/class-wp-filesystem-base.php b/wp-admin/includes/class-wp-filesystem-base.php new file mode 100644 index 0000000..2569a86 --- /dev/null +++ b/wp-admin/includes/class-wp-filesystem-base.php @@ -0,0 +1,320 @@ +find_folder(ABSPATH); + //Perhaps the FTP folder is rooted at the WordPress install, Check for wp-includes folder in root, Could have some false positives, but rare. + if ( ! $folder && $this->is_dir('/wp-includes') ) + $folder = '/'; + return $folder; + } + /** + * Returns the path on the remote filesystem of WP_CONTENT_DIR + * + * @since 2.7 + * @access public + * @return string The location of the remote path. + */ + function wp_content_dir() { + return $this->find_folder(WP_CONTENT_DIR); + } + /** + * Returns the path on the remote filesystem of WP_PLUGIN_DIR + * + * @since 2.7 + * @access public + * + * @return string The location of the remote path. + */ + function wp_plugins_dir() { + return $this->find_folder(WP_PLUGIN_DIR); + } + /** + * Returns the path on the remote filesystem of the Themes Directory + * + * @since 2.7 + * @access public + * + * @return string The location of the remote path. + */ + function wp_themes_dir() { + return $this->wp_content_dir() . '/themes'; + } + + /** + * Locates a folder on the remote filesystem. + * + * Deprecated; use WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir() methods instead. + * + * @since 2.5 + * @deprecated 2.7 + * @access public + * + * @param string $base The folder to start searching from + * @param bool $echo True to display debug information + * @return string The location of the remote path. + */ + function find_base_dir($base = '.', $echo = false) { + _deprecated_function(__FUNCTION__, '2.7', 'WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir()' ); + $this->verbose = $echo; + return $this->abspath(); + } + /** + * Locates a folder on the remote filesystem. + * + * Deprecated; use WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir() methods instead. + * + * @since 2.5 + * @deprecated 2.7 + * @access public + * + * @param string $base The folder to start searching from + * @param bool $echo True to display debug information + * @return string The location of the remote path. + */ + function get_base_dir($base = '.', $echo = false) { + _deprecated_function(__FUNCTION__, '2.7', 'WP_Filesystem::abspath() or WP_Filesystem::wp_*_dir()' ); + $this->verbose = $echo; + return $this->abspath(); + } + + /** + * Locates a folder on the remote filesystem. + * + * Assumes that on Windows systems, Stripping off the Drive letter is OK + * Sanitizes \\ to / in windows filepaths. + * + * @since 2.7 + * @access public + * + * @param string $folder the folder to locate + * @return string The location of the remote path. + */ + function find_folder($folder) { + + if ( strpos($this->method, 'ftp') !== false ) { + $constant_overrides = array( 'FTP_BASE' => ABSPATH, 'FTP_CONTENT_DIR' => WP_CONTENT_DIR, 'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR ); + foreach ( $constant_overrides as $constant => $dir ) + if ( defined($constant) && $folder === $dir ) + return trailingslashit(constant($constant)); + } elseif ( 'direct' == $this->method ) { + return trailingslashit($folder); + } + + $folder = preg_replace('|^([a-z]{1}):|i', '', $folder); //Strip out windows driveletter if its there. + $folder = str_replace('\\', '/', $folder); //Windows path sanitiation + + if ( isset($this->cache[ $folder ] ) ) + return $this->cache[ $folder ]; + + if ( $this->exists($folder) ) { //Folder exists at that absolute path. + $folder = trailingslashit($folder); + $this->cache[ $folder ] = $folder; + return $folder; + } + if( $return = $this->search_for_folder($folder) ) + $this->cache[ $folder ] = $return; + return $return; + } + + /** + * Locates a folder on the remote filesystem. + * + * Expects Windows sanitized path + * + * @since 2.7 + * @access private + * + * @param string $folder the folder to locate + * @param string $base the folder to start searching from + * @param bool $loop if the function has recursed, Internal use only + * @return string The location of the remote path. + */ + function search_for_folder($folder, $base = '.', $loop = false ) { + if ( empty( $base ) || '.' == $base ) + $base = trailingslashit($this->cwd()); + + $folder = untrailingslashit($folder); + + $folder_parts = explode('/', $folder); + $last_path = $folder_parts[ count($folder_parts) - 1 ]; + + $files = $this->dirlist( $base ); + + foreach ( $folder_parts as $key ) { + if ( $key == $last_path ) + continue; //We want this to be caught by the next code block. + + //Working from /home/ to /user/ to /wordpress/ see if that file exists within the current folder, + // If its found, change into it and follow through looking for it. + // If it cant find WordPress down that route, it'll continue onto the next folder level, and see if that matches, and so on. + // If it reaches the end, and still cant find it, it'll return false for the entire function. + if ( isset($files[ $key ]) ){ + //Lets try that folder: + $newdir = trailingslashit(path_join($base, $key)); + if ( $this->verbose ) + printf( __('Changing to %s') . '
    ', $newdir ); + if ( $ret = $this->search_for_folder( $folder, $newdir, $loop) ) + return $ret; + } + } + + //Only check this as a last resort, to prevent locating the incorrect install. All above proceeedures will fail quickly if this is the right branch to take. + if (isset( $files[ $last_path ] ) ) { + if ( $this->verbose ) + printf( __('Found %s') . '
    ', $base . $last_path ); + return trailingslashit($base . $last_path); + } + if ( $loop ) + return false;//Prevent tihs function looping again. + //As an extra last resort, Change back to / if the folder wasnt found. This comes into effect when the CWD is /home/user/ but WP is at /var/www/.... mainly dedicated setups. + return $this->search_for_folder($folder, '/', true); + + } + + /** + * Returns the *nix style file permissions for a file + * + * From the PHP documentation page for fileperms() + * + * @link http://docs.php.net/fileperms + * @since 2.5 + * @access public + * + * @param string $file string filename + * @return int octal representation of permissions + */ + function gethchmod($file){ + $perms = $this->getchmod($file); + if (($perms & 0xC000) == 0xC000) // Socket + $info = 's'; + elseif (($perms & 0xA000) == 0xA000) // Symbolic Link + $info = 'l'; + elseif (($perms & 0x8000) == 0x8000) // Regular + $info = '-'; + elseif (($perms & 0x6000) == 0x6000) // Block special + $info = 'b'; + elseif (($perms & 0x4000) == 0x4000) // Directory + $info = 'd'; + elseif (($perms & 0x2000) == 0x2000) // Character special + $info = 'c'; + elseif (($perms & 0x1000) == 0x1000)// FIFO pipe + $info = 'p'; + else // Unknown + $info = 'u'; + + // Owner + $info .= (($perms & 0x0100) ? 'r' : '-'); + $info .= (($perms & 0x0080) ? 'w' : '-'); + $info .= (($perms & 0x0040) ? + (($perms & 0x0800) ? 's' : 'x' ) : + (($perms & 0x0800) ? 'S' : '-')); + + // Group + $info .= (($perms & 0x0020) ? 'r' : '-'); + $info .= (($perms & 0x0010) ? 'w' : '-'); + $info .= (($perms & 0x0008) ? + (($perms & 0x0400) ? 's' : 'x' ) : + (($perms & 0x0400) ? 'S' : '-')); + + // World + $info .= (($perms & 0x0004) ? 'r' : '-'); + $info .= (($perms & 0x0002) ? 'w' : '-'); + $info .= (($perms & 0x0001) ? + (($perms & 0x0200) ? 't' : 'x' ) : + (($perms & 0x0200) ? 'T' : '-')); + return $info; + } + + /** + * Converts *nix style file permissions to a octal number. + * + * Converts '-rw-r--r--' to 0644 + * From "info at rvgate dot nl"'s comment on the PHP documentation for chmod() + * + * @link http://docs.php.net/manual/en/function.chmod.php#49614 + * @since 2.5 + * @access public + * + * @param string $mode string *nix style file permission + * @return int octal representation + */ + function getnumchmodfromh($mode) { + $realmode = ''; + $legal = array('', 'w', 'r', 'x', '-'); + $attarray = preg_split('//', $mode); + + for($i=0; $i < count($attarray); $i++) + if($key = array_search($attarray[$i], $legal)) + $realmode .= $legal[$key]; + + $mode = str_pad($realmode, 9, '-'); + $trans = array('-'=>'0', 'r'=>'4', 'w'=>'2', 'x'=>'1'); + $mode = strtr($mode,$trans); + + $newmode = ''; + $newmode .= $mode[0] + $mode[1] + $mode[2]; + $newmode .= $mode[3] + $mode[4] + $mode[5]; + $newmode .= $mode[6] + $mode[7] + $mode[8]; + return $newmode; + } + + /** + * Determines if the string provided contains binary characters. + * + * @since 2.7 + * @access private + * + * @param string $text String to test against + * @return bool true if string is binary, false otherwise + */ + function is_binary( $text ) { + return (bool) preg_match('|[^\x20-\x7E]|', $text); //chr(32)..chr(127) + } +} + +?> diff --git a/wp-admin/includes/class-wp-filesystem-direct.php b/wp-admin/includes/class-wp-filesystem-direct.php new file mode 100644 index 0000000..03a7977 --- /dev/null +++ b/wp-admin/includes/class-wp-filesystem-direct.php @@ -0,0 +1,283 @@ +method = 'direct'; + $this->errors = new WP_Error(); + } + function connect() { + return true; + } + function setDefaultPermissions($perm) { + $this->permission = $perm; + } + function get_contents($file) { + return @file_get_contents($file); + } + function get_contents_array($file) { + return @file($file); + } + function put_contents($file, $contents, $mode = false, $type = '') { + if ( ! ($fp = @fopen($file, 'w' . $type)) ) + return false; + @fwrite($fp, $contents); + @fclose($fp); + $this->chmod($file,$mode); + return true; + } + function cwd() { + return @getcwd(); + } + function chdir($dir) { + return @chdir($dir); + } + function chgrp($file, $group, $recursive = false) { + if ( ! $this->exists($file) ) + return false; + if ( ! $recursive ) + return @chgrp($file, $group); + if ( ! $this->is_dir($file) ) + return @chgrp($file, $group); + //Is a directory, and we want recursive + $file = trailingslashit($file); + $filelist = $this->dirlist($file); + foreach ($filelist as $filename) + $this->chgrp($file . $filename, $group, $recursive); + + return true; + } + function chmod($file, $mode = false, $recursive = false) { + if ( ! $this->exists($file) ) + return false; + + if ( ! $mode ) { + if ( $this->permission ) + $mode = $this->permission; + elseif ( $this->is_file($file) ) + $mode = FS_CHMOD_FILE; + elseif ( $this->is_dir($file) ) + $mode = FS_CHMOD_DIR; + else + return false; + } + + if ( ! $recursive ) + return @chmod($file, $mode); + if ( ! $this->is_dir($file) ) + return @chmod($file, $mode); + //Is a directory, and we want recursive + $file = trailingslashit($file); + $filelist = $this->dirlist($file); + foreach ($filelist as $filename) + $this->chmod($file . $filename, $mode, $recursive); + + return true; + } + function chown($file, $owner, $recursive = false) { + if ( ! $this->exists($file) ) + return false; + if ( ! $recursive ) + return @chown($file, $owner); + if ( ! $this->is_dir($file) ) + return @chown($file, $owner); + //Is a directory, and we want recursive + $filelist = $this->dirlist($file); + foreach ($filelist as $filename){ + $this->chown($file . '/' . $filename, $owner, $recursive); + } + return true; + } + function owner($file) { + $owneruid = @fileowner($file); + if ( ! $owneruid ) + return false; + if ( ! function_exists('posix_getpwuid') ) + return $owneruid; + $ownerarray = posix_getpwuid($owneruid); + return $ownerarray['name']; + } + function getchmod($file) { + return substr(decoct(@fileperms($file)),3); + } + function group($file) { + $gid = @filegroup($file); + if ( ! $gid ) + return false; + if ( ! function_exists('posix_getgrgid') ) + return $gid; + $grouparray = posix_getgrgid($gid); + return $grouparray['name']; + } + + function copy($source, $destination, $overwrite = false) { + if ( ! $overwrite && $this->exists($destination) ) + return false; + return copy($source, $destination); + } + + function move($source, $destination, $overwrite = false) { + //Possible to use rename()? + if ( $this->copy($source, $destination, $overwrite) && $this->exists($destination) ){ + $this->delete($source); + return true; + } else { + return false; + } + } + + function delete($file, $recursive = false) { + if ( empty($file) ) //Some filesystems report this as /, which can cause non-expected recursive deletion of all files in the filesystem. + return false; + $file = str_replace('\\', '/', $file); //for win32, occasional problems deleteing files otherwise + + if ( $this->is_file($file) ) + return @unlink($file); + if ( ! $recursive && $this->is_dir($file) ) + return @rmdir($file); + + //At this point its a folder, and we're in recursive mode + $file = trailingslashit($file); + $filelist = $this->dirlist($file, true); + + $retval = true; + if ( is_array($filelist) ) //false if no files, So check first. + foreach ($filelist as $filename => $fileinfo) + if ( ! $this->delete($file . $filename, $recursive) ) + $retval = false; + + if ( file_exists($file) && ! @rmdir($file) ) + $retval = false; + return $retval; + } + + function exists($file) { + return @file_exists($file); + } + + function is_file($file) { + return @is_file($file); + } + + function is_dir($path) { + return @is_dir($path); + } + + function is_readable($file) { + return @is_readable($file); + } + + function is_writable($file) { + return @is_writable($file); + } + + function atime($file) { + return @fileatime($file); + } + + function mtime($file) { + return @filemtime($file); + } + function size($file) { + return @filesize($file); + } + + function touch($file, $time = 0, $atime = 0){ + if ($time == 0) + $time = time(); + if ($atime == 0) + $atime = time(); + return @touch($file, $time, $atime); + } + + function mkdir($path, $chmod = false, $chown = false, $chgrp = false){ + if ( ! @mkdir($path) ) + return false; + $this->chmod($path, $chmod); + if ( $chown ) + $this->chown($path, $chown); + if ( $chgrp ) + $this->chgrp($path, $chgrp); + return true; + } + + function rmdir($path, $recursive = false) { + //Currently unused and untested, Use delete() instead. + if ( ! $recursive ) + return @rmdir($path); + //recursive: + $filelist = $this->dirlist($path); + foreach ($filelist as $filename => $det) { + if ( '/' == substr($filename, -1, 1) ) + $this->rmdir($path . '/' . $filename, $recursive); + @rmdir($filename); + } + return @rmdir($path); + } + + function dirlist($path, $incdot = false, $recursive = false) { + if ( $this->is_file($path) ) { + $limitFile = basename($path); + $path = dirname($path); + } else { + $limitFile = false; + } + if ( ! $this->is_dir($path) ) + return false; + + $ret = array(); + $dir = @dir($path); + if ( ! $dir ) + return false; + while (false !== ($entry = $dir->read()) ) { + $struc = array(); + $struc['name'] = $entry; + + if ( '.' == $struc['name'] || '..' == $struc['name'] ) + continue; //Do not care about these folders. + if ( '.' == $struc['name'][0] && !$incdot) + continue; + if ( $limitFile && $struc['name'] != $limitFile) + continue; + + $struc['perms'] = $this->gethchmod($path.'/'.$entry); + $struc['permsn'] = $this->getnumchmodfromh($struc['perms']); + $struc['number'] = false; + $struc['owner'] = $this->owner($path.'/'.$entry); + $struc['group'] = $this->group($path.'/'.$entry); + $struc['size'] = $this->size($path.'/'.$entry); + $struc['lastmodunix']= $this->mtime($path.'/'.$entry); + $struc['lastmod'] = date('M j',$struc['lastmodunix']); + $struc['time'] = date('h:i:s',$struc['lastmodunix']); + $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f'; + + if ( 'd' == $struc['type'] ) { + if ( $recursive ) + $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive); + else + $struc['files'] = array(); + } + + $ret[ $struc['name'] ] = $struc; + } + $dir->close(); + unset($dir); + return $ret; + } +} +?> diff --git a/wp-admin/includes/class-wp-filesystem-ftpext.php b/wp-admin/includes/class-wp-filesystem-ftpext.php new file mode 100644 index 0000000..24611c9 --- /dev/null +++ b/wp-admin/includes/class-wp-filesystem-ftpext.php @@ -0,0 +1,378 @@ +method = 'ftpext'; + $this->errors = new WP_Error(); + + //Check if possible to use ftp functions. + if ( ! extension_loaded('ftp') ) { + $this->errors->add('no_ftp_ext', __('The ftp PHP extension is not available')); + return false; + } + + // Set defaults: + if ( empty($opt['port']) ) + $this->options['port'] = 21; + else + $this->options['port'] = $opt['port']; + + if ( empty($opt['hostname']) ) + $this->errors->add('empty_hostname', __('FTP hostname is required')); + else + $this->options['hostname'] = $opt['hostname']; + + if ( isset($opt['base']) && ! empty($opt['base']) ) + $this->wp_base = $opt['base']; + + // Check if the options provided are OK. + if ( empty($opt['username']) ) + $this->errors->add('empty_username', __('FTP username is required')); + else + $this->options['username'] = $opt['username']; + + if ( empty($opt['password']) ) + $this->errors->add('empty_password', __('FTP password is required')); + else + $this->options['password'] = $opt['password']; + + $this->options['ssl'] = false; + if ( isset($opt['connection_type']) && 'ftps' == $opt['connection_type'] ) + $this->options['ssl'] = true; + } + + function connect() { + if ( isset($this->options['ssl']) && $this->options['ssl'] && function_exists('ftp_ssl_connect') ) + $this->link = @ftp_ssl_connect($this->options['hostname'], $this->options['port'], $this->timeout); + else + $this->link = @ftp_connect($this->options['hostname'], $this->options['port'], $this->timeout); + + if ( ! $this->link ) { + $this->errors->add('connect', sprintf(__('Failed to connect to FTP Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); + return false; + } + + if ( ! @ftp_login($this->link,$this->options['username'], $this->options['password']) ) { + $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username'])); + return false; + } + + //Set the Connection to use Passive FTP + @ftp_pasv( $this->link, true ); + + return true; + } + + function setDefaultPermissions($perm) { + $this->permission = $perm; + } + + function get_contents($file, $type = '', $resumepos = 0 ){ + if( empty($type) ) + $type = FTP_BINARY; + + $temp = tmpfile(); + if ( ! $temp ) + return false; + + if( ! @ftp_fget($this->link, $temp, $file, $type, $resumepos) ) + return false; + + fseek($temp, 0); //Skip back to the start of the file being written to + $contents = ''; + + while ( ! feof($temp) ) + $contents .= fread($temp, 8192); + + fclose($temp); + return $contents; + } + function get_contents_array($file) { + return explode("\n", $this->get_contents($file)); + } + function put_contents($file, $contents, $type = '' ) { + if( empty($type) ) + $type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII; + + $temp = tmpfile(); + if ( ! $temp ) + return false; + + fwrite($temp, $contents); + fseek($temp, 0); //Skip back to the start of the file being written to + + $ret = @ftp_fput($this->link, $file, $temp, $type); + + fclose($temp); + return $ret; + } + function cwd() { + $cwd = @ftp_pwd($this->link); + if( $cwd ) + $cwd = trailingslashit($cwd); + return $cwd; + } + function chdir($dir) { + return @ftp_chdir($dir); + } + function chgrp($file, $group, $recursive = false ) { + return false; + } + function chmod($file, $mode = false, $recursive = false) { + if( ! $mode ) + $mode = $this->permission; + if( ! $mode ) + return false; + if ( ! $this->exists($file) && ! $this->is_dir($file) ) + return false; + if ( ! $recursive || ! $this->is_dir($file) ) { + if ( ! function_exists('ftp_chmod') ) + return @ftp_site($this->link, sprintf('CHMOD %o %s', $mode, $file)); + return @ftp_chmod($this->link, $mode, $file); + } + //Is a directory, and we want recursive + $filelist = $this->dirlist($file); + foreach($filelist as $filename){ + $this->chmod($file . '/' . $filename, $mode, $recursive); + } + return true; + } + function chown($file, $owner, $recursive = false ) { + return false; + } + function owner($file) { + $dir = $this->dirlist($file); + return $dir[$file]['owner']; + } + function getchmod($file) { + $dir = $this->dirlist($file); + return $dir[$file]['permsn']; + } + function group($file) { + $dir = $this->dirlist($file); + return $dir[$file]['group']; + } + function copy($source, $destination, $overwrite = false ) { + if( ! $overwrite && $this->exists($destination) ) + return false; + $content = $this->get_contents($source); + if( false === $content) + return false; + return $this->put_contents($destination, $content); + } + function move($source, $destination, $overwrite = false) { + return ftp_rename($this->link, $source, $destination); + } + + function delete($file, $recursive = false ) { + if ( empty($file) ) + return false; + if ( $this->is_file($file) ) + return @ftp_delete($this->link, $file); + if ( !$recursive ) + return @ftp_rmdir($this->link, $file); + + $filelist = $this->dirlist( trailingslashit($file) ); + if ( !empty($filelist) ) + foreach ( $filelist as $delete_file ) + $this->delete( trailingslashit($file) . $delete_file['name'], $recursive); + return @ftp_rmdir($this->link, $file); + } + + function exists($file) { + $list = @ftp_rawlist($this->link, $file, false); + return !empty($list); //empty list = no file, so invert. + } + function is_file($file) { + return $this->exists($file) && !$this->is_dir($file); + } + function is_dir($path) { + $cwd = $this->cwd(); + $result = @ftp_chdir($this->link, trailingslashit($path) ); + if( $result && $path == $this->cwd() || $this->cwd() != $cwd ) { + @ftp_chdir($this->link, $cwd); + return true; + } + return false; + } + function is_readable($file) { + //Get dir list, Check if the file is readable by the current user?? + return true; + } + function is_writable($file) { + //Get dir list, Check if the file is writable by the current user?? + return true; + } + function atime($file) { + return false; + } + function mtime($file) { + return ftp_mdtm($this->link, $file); + } + function size($file) { + return ftp_size($this->link, $file); + } + function touch($file, $time = 0, $atime = 0) { + return false; + } + function mkdir($path, $chmod = false, $chown = false, $chgrp = false) { + if( !ftp_mkdir($this->link, $path) ) + return false; + if( $chmod ) + $this->chmod($path, $chmod); + if( $chown ) + $this->chown($path, $chown); + if( $chgrp ) + $this->chgrp($path, $chgrp); + return true; + } + function rmdir($path, $recursive = false) { + return $this->delete($path, $recursive); + } + + function parselisting($line) { + static $is_windows; + if ( is_null($is_windows) ) + $is_windows = strpos( strtolower(ftp_systype($this->link)), 'win') !== false; + + if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)/", $line, $lucifer)) { + $b = array(); + if ($lucifer[3]<70) { $lucifer[3] +=2000; } else { $lucifer[3]+=1900; } // 4digit year fix + $b['isdir'] = ($lucifer[7]==""); + if ( $b['isdir'] ) + $b['type'] = 'd'; + else + $b['type'] = 'f'; + $b['size'] = $lucifer[7]; + $b['month'] = $lucifer[1]; + $b['day'] = $lucifer[2]; + $b['year'] = $lucifer[3]; + $b['hour'] = $lucifer[4]; + $b['minute'] = $lucifer[5]; + $b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]); + $b['am/pm'] = $lucifer[6]; + $b['name'] = $lucifer[8]; + } else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) { + //echo $line."\n"; + $lcount=count($lucifer); + if ($lcount<8) return ''; + $b = array(); + $b['isdir'] = $lucifer[0]{0} === "d"; + $b['islink'] = $lucifer[0]{0} === "l"; + if ( $b['isdir'] ) + $b['type'] = 'd'; + elseif ( $b['islink'] ) + $b['type'] = 'l'; + else + $b['type'] = 'f'; + $b['perms'] = $lucifer[0]; + $b['number'] = $lucifer[1]; + $b['owner'] = $lucifer[2]; + $b['group'] = $lucifer[3]; + $b['size'] = $lucifer[4]; + if ($lcount==8) { + sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']); + sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']); + $b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']); + $b['name'] = $lucifer[7]; + } else { + $b['month'] = $lucifer[5]; + $b['day'] = $lucifer[6]; + if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) { + $b['year'] = date("Y"); + $b['hour'] = $l2[1]; + $b['minute'] = $l2[2]; + } else { + $b['year'] = $lucifer[7]; + $b['hour'] = 0; + $b['minute'] = 0; + } + $b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute'])); + $b['name'] = $lucifer[8]; + } + } + + return $b; + } + + function dirlist($path = '.', $incdot = false, $recursive = false) { + if( $this->is_file($path) ) { + $limitFile = basename($path); + $path = dirname($path) . '/'; + } else { + $limitFile = false; + } + + $list = @ftp_rawlist($this->link, '-a ' . $path, false); + + if ( $list === false ) + return false; + + $dirlist = array(); + foreach ( $list as $k => $v ) { + $entry = $this->parselisting($v); + if ( empty($entry) ) + continue; + + if ( '.' == $entry["name"] || '..' == $entry["name"] ) + continue; + + $dirlist[ $entry['name'] ] = $entry; + } + + if ( ! $dirlist ) + return false; + if ( empty($dirlist) ) + return array(); + + $ret = array(); + foreach ( $dirlist as $struc ) { + + if ( 'd' == $struc['type'] ) { + $struc['files'] = array(); + + if ( $incdot ){ + //We're including the doted starts + if( '.' != $struc['name'] && '..' != $struc['name'] ){ //Ok, It isnt a special folder + if ($recursive) + $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive); + } + } else { //No dots + if ($recursive) + $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive); + } + } + //File + $ret[$struc['name']] = $struc; + } + return $ret; + } + + function __destruct(){ + if( $this->link ) + ftp_close($this->link); + } +} + +?> diff --git a/wp-admin/includes/class-wp-filesystem-ftpsockets.php b/wp-admin/includes/class-wp-filesystem-ftpsockets.php new file mode 100644 index 0000000..759eaa8 --- /dev/null +++ b/wp-admin/includes/class-wp-filesystem-ftpsockets.php @@ -0,0 +1,327 @@ +method = 'ftpsockets'; + $this->errors = new WP_Error(); + + //Check if possible to use ftp functions. + if( ! @include_once ABSPATH . 'wp-admin/includes/class-ftp.php' ) + return false; + $this->ftp = new ftp(); + + //Set defaults: + if ( empty($opt['port']) ) + $this->options['port'] = 21; + else + $this->options['port'] = $opt['port']; + + if ( empty($opt['hostname']) ) + $this->errors->add('empty_hostname', __('FTP hostname is required')); + else + $this->options['hostname'] = $opt['hostname']; + + if ( isset($opt['base']) && ! empty($opt['base']) ) + $this->wp_base = $opt['base']; + + // Check if the options provided are OK. + if ( empty ($opt['username']) ) + $this->errors->add('empty_username', __('FTP username is required')); + else + $this->options['username'] = $opt['username']; + + if ( empty ($opt['password']) ) + $this->errors->add('empty_password', __('FTP password is required')); + else + $this->options['password'] = $opt['password']; + } + + function connect() { + if ( ! $this->ftp ) + return false; + + //$this->ftp->Verbose = true; + + if ( ! $this->ftp->SetServer($this->options['hostname'], $this->options['port']) ) { + $this->errors->add('connect', sprintf(__('Failed to connect to FTP Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); + return false; + } + if ( ! $this->ftp->connect() ) { + $this->errors->add('connect', sprintf(__('Failed to connect to FTP Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); + return false; + } + + if ( ! $this->ftp->login($this->options['username'], $this->options['password']) ) { + $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username'])); + return false; + } + + $this->ftp->SetType(FTP_AUTOASCII); + $this->ftp->Passive(true); + return true; + } + + function setDefaultPermissions($perm) { + $this->permission = $perm; + } + + function get_contents($file, $type = '', $resumepos = 0) { + if( ! $this->exists($file) ) + return false; + + if( empty($type) ) + $type = FTP_AUTOASCII; + $this->ftp->SetType($type); + + $temp = wp_tempnam( $file ); + + if ( ! $temphandle = fopen($temp, 'w+') ) + return false; + + if ( ! $this->ftp->fget($temphandle, $file) ) { + fclose($temphandle); + unlink($temp); + return ''; //Blank document, File does exist, Its just blank. + } + + fseek($temphandle, 0); //Skip back to the start of the file being written to + $contents = ''; + + while ( ! feof($temphandle) ) + $contents .= fread($temphandle, 8192); + + fclose($temphandle); + unlink($temp); + return $contents; + } + + function get_contents_array($file) { + return explode("\n", $this->get_contents($file) ); + } + + function put_contents($file, $contents, $type = '' ) { + if( empty($type) ) + $type = $this->is_binary($contents) ? FTP_BINARY : FTP_ASCII; + + $this->ftp->SetType($type); + + $temp = wp_tempnam( $file ); + if ( ! $temphandle = fopen($temp, 'w+') ){ + unlink($temp); + return false; + } + + fwrite($temphandle, $contents); + fseek($temphandle, 0); //Skip back to the start of the file being written to + + $ret = $this->ftp->fput($file, $temphandle); + + fclose($temphandle); + unlink($temp); + return $ret; + } + + function cwd() { + $cwd = $this->ftp->pwd(); + if( $cwd ) + $cwd = trailingslashit($cwd); + return $cwd; + } + + function chdir($file) { + return $this->ftp->chdir($file); + } + + function chgrp($file, $group, $recursive = false ) { + return false; + } + + function chmod($file, $mode = false, $recursive = false ) { + if( ! $mode ) + $mode = $this->permission; + if( ! $mode ) + return false; + //if( ! $this->exists($file) ) + // return false; + if( ! $recursive || ! $this->is_dir($file) ) { + return $this->ftp->chmod($file,$mode); + } + //Is a directory, and we want recursive + $filelist = $this->dirlist($file); + foreach($filelist as $filename){ + $this->chmod($file . '/' . $filename, $mode, $recursive); + } + return true; + } + + function chown($file, $owner, $recursive = false ) { + return false; + } + + function owner($file) { + $dir = $this->dirlist($file); + return $dir[$file]['owner']; + } + + function getchmod($file) { + $dir = $this->dirlist($file); + return $dir[$file]['permsn']; + } + + function group($file) { + $dir = $this->dirlist($file); + return $dir[$file]['group']; + } + + function copy($source, $destination, $overwrite = false ) { + if( ! $overwrite && $this->exists($destination) ) + return false; + + $content = $this->get_contents($source); + if ( false === $content ) + return false; + + return $this->put_contents($destination, $content); + } + + function move($source, $destination, $overwrite = false ) { + return $this->ftp->rename($source, $destination); + } + + function delete($file, $recursive = false ) { + if ( empty($file) ) + return false; + if ( $this->is_file($file) ) + return $this->ftp->delete($file); + if ( !$recursive ) + return $this->ftp->rmdir($file); + + return $this->ftp->mdel($file); + } + + function exists($file) { + return $this->ftp->is_exists($file); + } + + function is_file($file) { + return $this->is_dir($file) ? false : true; + } + + function is_dir($path) { + $cwd = $this->cwd(); + if ( $this->chdir($path) ) { + $this->chdir($cwd); + return true; + } + return false; + } + + function is_readable($file) { + //Get dir list, Check if the file is writable by the current user?? + return true; + } + + function is_writable($file) { + //Get dir list, Check if the file is writable by the current user?? + return true; + } + + function atime($file) { + return false; + } + + function mtime($file) { + return $this->ftp->mdtm($file); + } + + function size($file) { + return $this->ftp->filesize($file); + } + + function touch($file, $time = 0, $atime = 0 ) { + return false; + } + + function mkdir($path, $chmod = false, $chown = false, $chgrp = false ) { + if( ! $this->ftp->mkdir($path) ) + return false; + if( $chmod ) + $this->chmod($path, $chmod); + if( $chown ) + $this->chown($path, $chown); + if( $chgrp ) + $this->chgrp($path, $chgrp); + return true; + } + + function rmdir($path, $recursive = false ) { + if( ! $recursive ) + return $this->ftp->rmdir($path); + + return $this->ftp->mdel($path); + } + + function dirlist($path = '.', $incdot = false, $recursive = false ) { + if( $this->is_file($path) ) { + $limitFile = basename($path); + $path = dirname($path) . '/'; + } else { + $limitFile = false; + } + + $list = $this->ftp->dirlist($path); + if( ! $list ) + return false; + if( empty($list) ) + return array(); + + $ret = array(); + foreach ( $list as $struc ) { + + if ( 'd' == $struc['type'] ) { + $struc['files'] = array(); + + if ( $incdot ){ + //We're including the doted starts + if( '.' != $struc['name'] && '..' != $struc['name'] ){ //Ok, It isnt a special folder + if ($recursive) + $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive); + } + } else { //No dots + if ($recursive) + $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive); + } + } + //File + $ret[$struc['name']] = $struc; + } + return $ret; + } + + function __destruct() { + $this->ftp->quit(); + } +} + +?> diff --git a/wp-admin/includes/class-wp-filesystem-ssh2.php b/wp-admin/includes/class-wp-filesystem-ssh2.php new file mode 100644 index 0000000..89763df --- /dev/null +++ b/wp-admin/includes/class-wp-filesystem-ssh2.php @@ -0,0 +1,383 @@ +method = 'ssh2'; + $this->errors = new WP_Error(); + + //Check if possible to use ssh2 functions. + if ( ! extension_loaded('ssh2') ) { + $this->errors->add('no_ssh2_ext', __('The ssh2 PHP extension is not available')); + return false; + } + if ( !function_exists('stream_get_contents') ) { + $this->errors->add('ssh2_php_requirement', __('The ssh2 PHP extension is available, however, we require the PHP5 function stream_get_contents()')); + return false; + } + + // Set defaults: + if ( empty($opt['port']) ) + $this->options['port'] = 22; + else + $this->options['port'] = $opt['port']; + + if ( empty($opt['hostname']) ) + $this->errors->add('empty_hostname', __('SSH2 hostname is required')); + else + $this->options['hostname'] = $opt['hostname']; + + if ( isset($opt['base']) && ! empty($opt['base']) ) + $this->wp_base = $opt['base']; + + // Check if the options provided are OK. + if ( !empty ($opt['public_key']) && !empty ($opt['private_key']) ) { + $this->options['public_key'] = $opt['public_key']; + $this->options['private_key'] = $opt['private_key']; + + $this->options['hostkey'] = array('hostkey' => 'ssh-rsa'); + + $this->keys = true; + } elseif ( empty ($opt['username']) ) { + $this->errors->add('empty_username', __('SSH2 username is required')); + } + + if ( !empty($opt['username']) ) + $this->options['username'] = $opt['username']; + + if ( empty ($opt['password']) ) { + if ( !$this->keys ) //password can be blank if we are using keys + $this->errors->add('empty_password', __('SSH2 password is required')); + } else { + $this->options['password'] = $opt['password']; + } + + } + + function connect() { + if ( ! $this->keys ) { + $this->link = @ssh2_connect($this->options['hostname'], $this->options['port']); + } else { + $this->link = @ssh2_connect($this->options['hostname'], $this->options['port'], $this->options['hostkey']); + } + + if ( ! $this->link ) { + $this->errors->add('connect', sprintf(__('Failed to connect to SSH2 Server %1$s:%2$s'), $this->options['hostname'], $this->options['port'])); + return false; + } + + if ( !$this->keys ) { + if ( ! @ssh2_auth_password($this->link, $this->options['username'], $this->options['password']) ) { + $this->errors->add('auth', sprintf(__('Username/Password incorrect for %s'), $this->options['username'])); + return false; + } + } else { + if ( ! @ssh2_auth_pubkey_file($this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) { + $this->errors->add('auth', sprintf(__('Public and Private keys incorrect for %s'), $this->options['username'])); + return false; + } + } + + $this->sftp_link = ssh2_sftp($this->link); + + return true; + } + + function run_command( $command, $returnbool = false) { + + if ( ! $this->link ) + return false; + + if ( ! ($stream = ssh2_exec($this->link, $command)) ) { + $this->errors->add('command', sprintf(__('Unable to perform command: %s'), $command)); + } else { + stream_set_blocking( $stream, true ); + stream_set_timeout( $stream, $this->timeout ); + $data = stream_get_contents( $stream ); + fclose( $stream ); + + if ( $returnbool ) + return ( $data === false ) ? false : '' != trim($data); + else + return $data; + } + return false; + } + + function setDefaultPermissions($perm) { + $this->debug("setDefaultPermissions();"); + if ( $perm ) + $this->permission = $perm; + } + + function get_contents($file, $type = '', $resumepos = 0 ) { + $file = ltrim($file, '/'); + return file_get_contents('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function get_contents_array($file) { + $file = ltrim($file, '/'); + return file('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function put_contents($file, $contents, $type = '' ) { + $file = ltrim($file, '/'); + return file_put_contents('ssh2.sftp://' . $this->sftp_link . '/' . $file, $contents); + } + + function cwd() { + $cwd = $this->run_command('pwd'); + if( $cwd ) + $cwd = trailingslashit($cwd); + return $cwd; + } + + function chdir($dir) { + return $this->run_command('cd ' . $dir, true); + } + + function chgrp($file, $group, $recursive = false ) { + if ( ! $this->exists($file) ) + return false; + if ( ! $recursive || ! $this->is_dir($file) ) + return $this->run_command(sprintf('chgrp %o %s', $mode, escapeshellarg($file)), true); + return $this->run_command(sprintf('chgrp -R %o %s', $mode, escapeshellarg($file)), true); + } + + function chmod($file, $mode = false, $recursive = false) { + if( ! $mode ) + $mode = $this->permission; + if( ! $mode ) + return false; + if ( ! $this->exists($file) ) + return false; + if ( ! $recursive || ! $this->is_dir($file) ) + return $this->run_command(sprintf('chmod %o %s', $mode, escapeshellarg($file)), true); + return $this->run_command(sprintf('chmod -R %o %s', $mode, escapeshellarg($file)), true); + } + + function chown($file, $owner, $recursive = false ) { + if ( ! $this->exists($file) ) + return false; + if ( ! $recursive || ! $this->is_dir($file) ) + return $this->run_command(sprintf('chown %o %s', $mode, escapeshellarg($file)), true); + return $this->run_command(sprintf('chown -R %o %s', $mode, escapeshellarg($file)), true); + } + + function owner($file) { + $owneruid = @fileowner('ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/')); + if ( ! $owneruid ) + return false; + if ( ! function_exists('posix_getpwuid') ) + return $owneruid; + $ownerarray = posix_getpwuid($owneruid); + return $ownerarray['name']; + } + + function getchmod($file) { + return substr(decoct(@fileperms( 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/') )),3); + } + + function group($file) { + $gid = @filegroup('ssh2.sftp://' . $this->sftp_link . '/' . ltrim($file, '/')); + if ( ! $gid ) + return false; + if ( ! function_exists('posix_getgrgid') ) + return $gid; + $grouparray = posix_getgrgid($gid); + return $grouparray['name']; + } + + function copy($source, $destination, $overwrite = false ) { + if( ! $overwrite && $this->exists($destination) ) + return false; + $content = $this->get_contents($source); + if( false === $content) + return false; + return $this->put_contents($destination, $content); + } + + function move($source, $destination, $overwrite = false) { + return @ssh2_sftp_rename($this->link, $source, $destination); + } + + function delete($file, $recursive = false) { + if ( $this->is_file($file) ) + return ssh2_sftp_unlink($this->sftp_link, $file); + if ( ! $recursive ) + return ssh2_sftp_rmdir($this->sftp_link, $file); + $filelist = $this->dirlist($file); + if ( is_array($filelist) ) { + foreach ( $filelist as $filename => $fileinfo) { + $this->delete($file . '/' . $filename, $recursive); + } + } + return ssh2_sftp_rmdir($this->sftp_link, $file); + } + + function exists($file) { + $file = ltrim($file, '/'); + return file_exists('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function is_file($file) { + $file = ltrim($file, '/'); + return is_file('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function is_dir($path) { + $path = ltrim($path, '/'); + return is_dir('ssh2.sftp://' . $this->sftp_link . '/' . $path); + } + + function is_readable($file) { + $file = ltrim($file, '/'); + return is_readable('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function is_writable($file) { + $file = ltrim($file, '/'); + return is_writable('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function atime($file) { + $file = ltrim($file, '/'); + return fileatime('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function mtime($file) { + $file = ltrim($file, '/'); + return filemtime('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function size($file) { + $file = ltrim($file, '/'); + return filesize('ssh2.sftp://' . $this->sftp_link . '/' . $file); + } + + function touch($file, $time = 0, $atime = 0) { + //Not implmented. + } + + function mkdir($path, $chmod = null, $chown = false, $chgrp = false) { + $path = untrailingslashit($path); + $chmod = !empty($chmod) ? $chmod : $this->permission; + if ( ! ssh2_sftp_mkdir($this->sftp_link, $path, $chmod, true) ) + return false; + if ( $chown ) + $this->chown($path, $chown); + if ( $chgrp ) + $this->chgrp($path, $chgrp); + return true; + } + + function rmdir($path, $recursive = false) { + return $this->delete($path, $recursive); + } + + function dirlist($path, $incdot = false, $recursive = false) { + if ( $this->is_file($path) ) { + $limitFile = basename($path); + $path = dirname($path); + } else { + $limitFile = false; + } + if ( ! $this->is_dir($path) ) + return false; + + $ret = array(); + $dir = @dir('ssh2.sftp://' . $this->sftp_link .'/' . ltrim($path, '/') ); + if ( ! $dir ) + return false; + while (false !== ($entry = $dir->read()) ) { + $struc = array(); + $struc['name'] = $entry; + + if ( '.' == $struc['name'] || '..' == $struc['name'] ) + continue; //Do not care about these folders. + if ( '.' == $struc['name'][0] && !$incdot) + continue; + if ( $limitFile && $struc['name'] != $limitFile) + continue; + + $struc['perms'] = $this->gethchmod($path.'/'.$entry); + $struc['permsn'] = $this->getnumchmodfromh($struc['perms']); + $struc['number'] = false; + $struc['owner'] = $this->owner($path.'/'.$entry); + $struc['group'] = $this->group($path.'/'.$entry); + $struc['size'] = $this->size($path.'/'.$entry); + $struc['lastmodunix']= $this->mtime($path.'/'.$entry); + $struc['lastmod'] = date('M j',$struc['lastmodunix']); + $struc['time'] = date('h:i:s',$struc['lastmodunix']); + $struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f'; + + if ( 'd' == $struc['type'] ) { + if ( $recursive ) + $struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive); + else + $struc['files'] = array(); + } + + $ret[ $struc['name'] ] = $struc; + } + $dir->close(); + unset($dir); + return $ret; + } +} diff --git a/wp-admin/includes/class-wp-upgrader.php b/wp-admin/includes/class-wp-upgrader.php new file mode 100644 index 0000000..76b11fe --- /dev/null +++ b/wp-admin/includes/class-wp-upgrader.php @@ -0,0 +1,1059 @@ +__construct($skin); + } + function __construct($skin = null) { + if ( null == $skin ) + $this->skin = new WP_Upgrader_Skin(); + else + $this->skin = $skin; + } + + function init() { + $this->skin->set_upgrader($this); + $this->generic_strings(); + } + + function generic_strings() { + $this->strings['bad_request'] = __('Invalid Data provided.'); + $this->strings['fs_unavailable'] = __('Could not access filesystem.'); + $this->strings['fs_error'] = __('Filesystem error'); + $this->strings['fs_no_root_dir'] = __('Unable to locate WordPress Root directory.'); + $this->strings['fs_no_content_dir'] = __('Unable to locate WordPress Content directory (wp-content).'); + $this->strings['fs_no_plugins_dir'] = __('Unable to locate WordPress Plugin directory.'); + $this->strings['fs_no_themes_dir'] = __('Unable to locate WordPress Theme directory.'); + $this->strings['fs_no_folder'] = __('Unable to locate needed folder (%s).'); + + $this->strings['download_failed'] = __('Download failed.'); + $this->strings['installing_package'] = __('Installing the latest version.'); + $this->strings['folder_exists'] = __('Destination folder already exists.'); + $this->strings['mkdir_failed'] = __('Could not create directory.'); + $this->strings['bad_package'] = __('Incompatible Archive'); + + $this->strings['maintenance_start'] = __('Enabling Maintenance mode.'); + $this->strings['maintenance_end'] = __('Disabling Maintenance mode.'); + } + + function fs_connect( $directories = array() ) { + global $wp_filesystem; + + if ( false === ($credentials = $this->skin->request_filesystem_credentials()) ) + return false; + + if ( ! WP_Filesystem($credentials) ) { + $error = true; + if ( is_object($wp_filesystem) && $wp_filesystem->errors->get_error_code() ) + $error = $wp_filesystem->errors; + $this->skin->request_filesystem_credentials($error); //Failed to connect, Error and request again + return false; + } + + if ( ! is_object($wp_filesystem) ) + return new WP_Error('fs_unavailable', $this->strings['fs_unavailable'] ); + + if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) + return new WP_Error('fs_error', $this->strings['fs_error'], $wp_filesystem->errors); + + foreach ( (array)$directories as $dir ) { + if ( ABSPATH == $dir && ! $wp_filesystem->abspath() ) + return new WP_Error('fs_no_root_dir', $this->strings['fs_no_root_dir']); + + elseif ( WP_CONTENT_DIR == $dir && ! $wp_filesystem->wp_content_dir() ) + return new WP_Error('fs_no_content_dir', $this->strings['fs_no_content_dir']); + + elseif ( WP_PLUGIN_DIR == $dir && ! $wp_filesystem->wp_plugins_dir() ) + return new WP_Error('fs_no_plugins_dir', $this->strings['fs_no_plugins_dir']); + + elseif ( WP_CONTENT_DIR . '/themes' == $dir && ! $wp_filesystem->find_folder(WP_CONTENT_DIR . '/themes') ) + return new WP_Error('fs_no_themes_dir', $this->strings['fs_no_themes_dir']); + + elseif ( ! $wp_filesystem->find_folder($dir) ) + return new WP_Error('fs_no_folder', sprintf($strings['fs_no_folder'], $dir)); + } + return true; + } //end fs_connect(); + + function download_package($package) { + + if ( ! preg_match('!^(http|https|ftp)://!i', $package) && file_exists($package) ) //Local file or remote? + return $package; //must be a local file.. + + if ( empty($package) ) + return new WP_Error('no_package', $this->strings['no_package']); + + $this->skin->feedback('downloading_package', $package); + + $download_file = download_url($package); + + if ( is_wp_error($download_file) ) + return new WP_Error('download_failed', $this->strings['download_failed'], $download_file->get_error_message()); + + return $download_file; + } + + function unpack_package($package, $delete_package = true) { + global $wp_filesystem; + + $this->skin->feedback('unpack_package'); + + $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/'; + + //Clean up contents of upgrade directory beforehand. + $upgrade_files = $wp_filesystem->dirlist($upgrade_folder); + if ( !empty($upgrade_files) ) { + foreach ( $upgrade_files as $file ) + $wp_filesystem->delete($upgrade_folder . $file['name'], true); + } + + //We need a working directory + $working_dir = $upgrade_folder . basename($package, '.zip'); + + // Clean up working directory + if ( $wp_filesystem->is_dir($working_dir) ) + $wp_filesystem->delete($working_dir, true); + + // Unzip package to working directory + $result = unzip_file($package, $working_dir); //TODO optimizations, Copy when Move/Rename would suffice? + + // Once extracted, delete the package if required. + if ( $delete_package ) + unlink($package); + + if ( is_wp_error($result) ) { + $wp_filesystem->delete($working_dir, true); + return $result; + } + + return $working_dir; + } + + function install_package($args = array()) { + global $wp_filesystem; + $defaults = array( 'source' => '', 'destination' => '', //Please always pass these + 'clear_destination' => false, 'clear_working' => false, + 'hook_extra' => array()); + + $args = wp_parse_args($args, $defaults); + extract($args); + + @set_time_limit( 300 ); + + if ( empty($source) || empty($destination) ) + return new WP_Error('bad_request', $this->strings['bad_request']); + + $this->skin->feedback('installing_package'); + + $res = apply_filters('upgrader_pre_install', true, $hook_extra); + if ( is_wp_error($res) ) + return $res; + + //Retain the Original source and destinations + $remote_source = $source; + $local_destination = $destination; + + $source_files = array_keys( $wp_filesystem->dirlist($remote_source) ); + $remote_destination = $wp_filesystem->find_folder($local_destination); + + //Locate which directory to copy to the new folder, This is based on the actual folder holding the files. + if ( 1 == count($source_files) && $wp_filesystem->is_dir( trailingslashit($source) . $source_files[0] . '/') ) //Only one folder? Then we want its contents. + $source = trailingslashit($source) . trailingslashit($source_files[0]); + elseif ( count($source_files) == 0 ) + return new WP_Error('bad_package', $this->strings['bad_package']); //There are no files? + //else //Its only a single file, The upgrader will use the foldername of this file as the destination folder. foldername is based on zip filename. + + //Hook ability to change the source file location.. + $source = apply_filters('upgrader_source_selection', $source, $remote_source, $this); + if ( is_wp_error($source) ) + return $source; + + //Has the source location changed? If so, we need a new source_files list. + if ( $source !== $remote_source ) + $source_files = array_keys( $wp_filesystem->dirlist($source) ); + + //Protection against deleting files in any important base directories. + if ( in_array( $destination, array(ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes') ) ) { + $remote_destination = trailingslashit($remote_destination) . trailingslashit(basename($source)); + $destination = trailingslashit($destination) . trailingslashit(basename($source)); + } + + //If we're not clearing the destination folder, and something exists there allready, Bail. + if ( ! $clear_destination && $wp_filesystem->exists($remote_destination) ) { + $wp_filesystem->delete($remote_source, true); //Clear out the source files. + return new WP_Error('folder_exists', $this->strings['folder_exists'], $remote_destination ); + } else if ( $clear_destination ) { + //We're going to clear the destination if theres something there + $this->skin->feedback('remove_old'); + + $removed = true; + if ( $wp_filesystem->exists($remote_destination) ) + $removed = $wp_filesystem->delete($remote_destination, true); + + $removed = apply_filters('upgrader_clear_destination', $removed, $local_destination, $remote_destination, $hook_extra); + + if ( is_wp_error($removed) ) + return $removed; + else if ( ! $removed ) + return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']); + } + + //Create destination if needed + if ( !$wp_filesystem->exists($remote_destination) ) + if ( !$wp_filesystem->mkdir($remote_destination, FS_CHMOD_DIR) ) + return new WP_Error('mkdir_failed', $this->strings['mkdir_failed'], $remote_destination); + + // Copy new version of item into place. + $result = copy_dir($source, $remote_destination); + if ( is_wp_error($result) ) { + if ( $clear_working ) + $wp_filesystem->delete($remote_source, true); + return $result; + } + + //Clear the Working folder? + if ( $clear_working ) + $wp_filesystem->delete($remote_source, true); + + $destination_name = basename( str_replace($local_destination, '', $destination) ); + if ( '.' == $destination_name ) + $destination_name = ''; + + $this->result = compact('local_source', 'source', 'source_name', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination', 'delete_source_dir'); + + $res = apply_filters('upgrader_post_install', true, $hook_extra, $this->result); + if ( is_wp_error($res) ) { + $this->result = $res; + return $res; + } + + //Bombard the calling function will all the info which we've just used. + return $this->result; + } + + function run($options) { + + $defaults = array( 'package' => '', //Please always pass this. + 'destination' => '', //And this + 'clear_destination' => false, + 'clear_working' => true, + 'hook_extra' => array() //Pass any extra $hook_extra args here, this will be passed to any hooked filters. + ); + + $options = wp_parse_args($options, $defaults); + extract($options); + + //Connect to the Filesystem first. + $res = $this->fs_connect( array(WP_CONTENT_DIR, $destination) ); + if ( ! $res ) //Mainly for non-connected filesystem. + return false; + + if ( is_wp_error($res) ) { + $this->skin->error($res); + return $res; + } + + $this->skin->header(); + $this->skin->before(); + + //Download the package (Note, This just returns the filename of the file if the package is a local file) + $download = $this->download_package( $package ); + if ( is_wp_error($download) ) { + $this->skin->error($download); + return $download; + } + + //Unzip's the file into a temporary directory + $working_dir = $this->unpack_package( $download ); + if ( is_wp_error($working_dir) ) { + $this->skin->error($working_dir); + return $working_dir; + } + + //With the given options, this installs it to the destination directory. + $result = $this->install_package( array( + 'source' => $working_dir, + 'destination' => $destination, + 'clear_destination' => $clear_destination, + 'clear_working' => $clear_working, + 'hook_extra' => $hook_extra + ) ); + $this->skin->set_result($result); + if ( is_wp_error($result) ) { + $this->skin->error($result); + $this->skin->feedback('process_failed'); + } else { + //Install Suceeded + $this->skin->feedback('process_success'); + } + $this->skin->after(); + $this->skin->footer(); + return $result; + } + + function maintenance_mode($enable = false) { + global $wp_filesystem; + $file = $wp_filesystem->abspath() . '.maintenance'; + if ( $enable ) { + $this->skin->feedback('maintenance_start'); + // Create maintenance file to signal that we are upgrading + $maintenance_string = ''; + $wp_filesystem->delete($file); + $wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE); + } else if ( !$enable && $wp_filesystem->exists($file) ) { + $this->skin->feedback('maintenance_end'); + $wp_filesystem->delete($file); + } + } + +} + +/** + * Plugin Upgrader class for WordPress Plugins, It is designed to upgrade/install plugins from a local zip, remote zip URL, or uploaded zip file. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Plugin_Upgrader extends WP_Upgrader { + + var $result; + + function upgrade_strings() { + $this->strings['up_to_date'] = __('The plugin is at the latest version.'); + $this->strings['no_package'] = __('Upgrade package not available.'); + $this->strings['downloading_package'] = __('Downloading update from %s.'); + $this->strings['unpack_package'] = __('Unpacking the update.'); + $this->strings['deactivate_plugin'] = __('Deactivating the plugin.'); + $this->strings['remove_old'] = __('Removing the old version of the plugin.'); + $this->strings['remove_old_failed'] = __('Could not remove the old plugin.'); + $this->strings['process_failed'] = __('Plugin upgrade Failed.'); + $this->strings['process_success'] = __('Plugin upgraded successfully.'); + } + + function install_strings() { + $this->strings['no_package'] = __('Install package not available.'); + $this->strings['downloading_package'] = __('Downloading install package from %s.'); + $this->strings['unpack_package'] = __('Unpacking the package.'); + $this->strings['installing_package'] = __('Installing the plugin.'); + $this->strings['process_failed'] = __('Plugin Install Failed.'); + $this->strings['process_success'] = __('Plugin Installed successfully.'); + } + + function install($package) { + + $this->init(); + $this->install_strings(); + + $this->run(array( + 'package' => $package, + 'destination' => WP_PLUGIN_DIR, + 'clear_destination' => false, //Do not overwrite files. + 'clear_working' => true, + 'hook_extra' => array() + )); + + // Force refresh of plugin update information + delete_transient('update_plugins'); + + } + + function upgrade($plugin) { + + $this->init(); + $this->upgrade_strings(); + + $current = get_transient( 'update_plugins' ); + if ( !isset( $current->response[ $plugin ] ) ) { + $this->skin->set_result(false); + $this->skin->error('up_to_date'); + $this->skin->after(); + return false; + } + + // Get the URL to the zip file + $r = $current->response[ $plugin ]; + + add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2); + add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4); + //'source_selection' => array(&$this, 'source_selection'), //theres a track ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins. + + $this->run(array( + 'package' => $r->package, + 'destination' => WP_PLUGIN_DIR, + 'clear_destination' => true, + 'clear_working' => true, + 'hook_extra' => array( + 'plugin' => $plugin + ) + )); + + //Cleanup our hooks, incase something else does a upgrade on this connection. + remove_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade')); + remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin')); + + if ( ! $this->result || is_wp_error($this->result) ) + return $this->result; + + // Force refresh of plugin update information + delete_transient('update_plugins'); + } + + //return plugin info. + function plugin_info() { + if ( ! is_array($this->result) ) + return false; + if ( empty($this->result['destination_name']) ) + return false; + + $plugin = get_plugins('/' . $this->result['destination_name']); //Ensure to pass with leading slash + if ( empty($plugin) ) + return false; + + $pluginfiles = array_keys($plugin); //Assume the requested plugin is the first in the list + + return $this->result['destination_name'] . '/' . $pluginfiles[0]; + } + + //Hooked to pre_install + function deactivate_plugin_before_upgrade($return, $plugin) { + + if ( is_wp_error($return) ) //Bypass. + return $return; + + $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : ''; + if ( empty($plugin) ) + return new WP_Error('bad_request', $this->strings['bad_request']); + + if ( is_plugin_active($plugin) ) { + $this->skin->feedback('deactivate_plugin'); + //Deactivate the plugin silently, Prevent deactivation hooks from running. + deactivate_plugins($plugin, true); + } + } + + //Hooked to upgrade_clear_destination + function delete_old_plugin($removed, $local_destination, $remote_destination, $plugin) { + global $wp_filesystem; + + if ( is_wp_error($removed) ) + return $removed; //Pass errors through. + + $plugin = isset($plugin['plugin']) ? $plugin['plugin'] : ''; + if ( empty($plugin) ) + return new WP_Error('bad_request', $this->strings['bad_request']); + + $plugins_dir = $wp_filesystem->wp_plugins_dir(); + $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin) ); + + if ( ! $wp_filesystem->exists($this_plugin_dir) ) //If its already vanished. + return $removed; + + // If plugin is in its own directory, recursively delete the directory. + if ( strpos($plugin, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory seperator AND that its not the root plugin folder + $deleted = $wp_filesystem->delete($this_plugin_dir, true); + else + $deleted = $wp_filesystem->delete($plugins_dir . $plugin); + + if ( ! $deleted ) + return new WP_Error('remove_old_failed', $this->strings['remove_old_failed']); + + return $removed; + } +} + +/** + * Theme Upgrader class for WordPress Themes, It is designed to upgrade/install themes from a local zip, remote zip URL, or uploaded zip file. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Theme_Upgrader extends WP_Upgrader { + + var $result; + + function upgrade_strings() { + $this->strings['up_to_date'] = __('The theme is at the latest version.'); + $this->strings['no_package'] = __('Upgrade package not available.'); + $this->strings['downloading_package'] = __('Downloading update from %s.'); + $this->strings['unpack_package'] = __('Unpacking the update.'); + $this->strings['remove_old'] = __('Removing the old version of the theme.'); + $this->strings['remove_old_failed'] = __('Could not remove the old theme.'); + $this->strings['process_failed'] = __('Theme upgrade Failed.'); + $this->strings['process_success'] = __('Theme upgraded successfully.'); + } + + function install_strings() { + $this->strings['no_package'] = __('Install package not available.'); + $this->strings['downloading_package'] = __('Downloading install package from %s.'); + $this->strings['unpack_package'] = __('Unpacking the package.'); + $this->strings['installing_package'] = __('Installing the theme.'); + $this->strings['process_failed'] = __('Theme Install Failed.'); + $this->strings['process_success'] = __('Theme Installed successfully.'); + } + + function install($package) { + + $this->init(); + $this->install_strings(); + + $options = array( + 'package' => $package, + 'destination' => WP_CONTENT_DIR . '/themes', + 'clear_destination' => false, //Do not overwrite files. + 'clear_working' => true + ); + + $this->run($options); + + if ( ! $this->result || is_wp_error($this->result) ) + return $this->result; + + // Force refresh of theme update information + delete_transient('update_themes'); + + if ( empty($result['destination_name']) ) + return false; + else + return $result['destination_name']; + } + + function upgrade($theme) { + + $this->init(); + $this->upgrade_strings(); + + // Is an update available? + $current = get_transient( 'update_themes' ); + if ( !isset( $current->response[ $theme ] ) ) { + $this->skin->set_result(false); + $this->skin->error('up_to_date'); + $this->skin->after(); + return false; + } + + $r = $current->response[ $theme ]; + + add_filter('upgrader_pre_install', array(&$this, 'current_before'), 10, 2); + add_filter('upgrader_post_install', array(&$this, 'current_after'), 10, 2); + add_filter('upgrader_clear_destination', array(&$this, 'delete_old_theme'), 10, 4); + + $options = array( + 'package' => $r['package'], + 'destination' => WP_CONTENT_DIR . '/themes', + 'clear_destination' => true, + 'clear_working' => true, + 'hook_extra' => array( + 'theme' => $theme + ) + ); + + $this->run($options); + + if ( ! $this->result || is_wp_error($this->result) ) + return $this->result; + + // Force refresh of theme update information + delete_transient('update_themes'); + + return true; + } + + function current_before($return, $theme) { + + if ( is_wp_error($return) ) + return $return; + + $theme = isset($theme['theme']) ? $theme['theme'] : ''; + + if ( $theme != get_stylesheet() ) //If not current + return $return; + //Change to maintainence mode now. + $this->maintenance_mode(true); + + return $return; + } + function current_after($return, $theme) { + if ( is_wp_error($return) ) + return $return; + + $theme = isset($theme['theme']) ? $theme['theme'] : ''; + + if ( $theme != get_stylesheet() ) //If not current + return $return; + + //Ensure stylesheet name hasnt changed after the upgrade: + if ( $theme == get_stylesheet() && $theme != $this->result['destination_name'] ) { + $theme_info = $this->theme_info(); + $stylesheet = $this->result['destination_name']; + $template = !empty($theme_info['Template']) ? $theme_info['Template'] : $stylesheet; + switch_theme($template, $stylesheet, true); + } + + //Time to remove maintainence mode + $this->maintenance_mode(false); + return $return; + } + + function delete_old_theme($removed, $local_destination, $remote_destination, $theme) { + global $wp_filesystem; + + $theme = isset($theme['theme']) ? $theme['theme'] : ''; + + if ( is_wp_error($removed) || empty($theme) ) + return $removed; //Pass errors through. + + $themes_dir = $wp_filesystem->wp_themes_dir(); + if ( $wp_filesystem->exists( trailingslashit($themes_dir) . $theme ) ) + if ( ! $wp_filesystem->delete( trailingslashit($themes_dir) . $theme, true ) ) + return false; + return true; + } + + function theme_info() { + if ( empty($this->result['destination_name']) ) + return false; + return get_theme_data(WP_CONTENT_DIR . '/themes/' . $this->result['destination_name'] . '/style.css'); + } + +} + +/** + * Core Upgrader class for WordPress. It allows for WordPress to upgrade itself in combiantion with the wp-admin/includes/update-core.php file + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Core_Upgrader extends WP_Upgrader { + + function upgrade_strings() { + $this->strings['up_to_date'] = __('WordPress is at the latest version.'); + $this->strings['no_package'] = __('Upgrade package not available.'); + $this->strings['downloading_package'] = __('Downloading update from %s.'); + $this->strings['unpack_package'] = __('Unpacking the update.'); + $this->strings['copy_failed'] = __('Could not copy files.'); + } + + function upgrade($current) { + global $wp_filesystem; + + $this->init(); + $this->upgrade_strings(); + + if ( !empty($feedback) ) + add_filter('update_feedback', $feedback); + + // Is an update available? + if ( !isset( $current->response ) || $current->response == 'latest' ) + return new WP_Error('up_to_date', $this->strings['up_to_date']); + + $res = $this->fs_connect( array(ABSPATH, WP_CONTENT_DIR) ); + if ( is_wp_error($res) ) + return $res; + + $wp_dir = trailingslashit($wp_filesystem->abspath()); + + $download = $this->download_package( $current->package ); + if ( is_wp_error($download) ) + return $download; + + $working_dir = $this->unpack_package( $download ); + if ( is_wp_error($working_dir) ) + return $working_dir; + + // Copy update-core.php from the new version into place. + if ( !$wp_filesystem->copy($working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true) ) { + $wp_filesystem->delete($working_dir, true); + return new WP_Error('copy_failed', $this->strings['copy_failed']); + } + $wp_filesystem->chmod($wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE); + + require(ABSPATH . 'wp-admin/includes/update-core.php'); + + return update_core($working_dir, $wp_dir); + } + +} + +/** + * Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class WP_Upgrader_Skin { + + var $upgrader; + var $done_header = false; + + function WP_Upgrader_Skin($args = array()) { + return $this->__construct($args); + } + function __construct($args = array()) { + $defaults = array( 'url' => '', 'nonce' => '', 'title' => '', 'context' => false ); + $this->options = wp_parse_args($args, $defaults); + } + + function set_upgrader(&$upgrader) { + if ( is_object($upgrader) ) + $this->upgrader =& $upgrader; + } + function set_result($result) { + $this->result = $result; + } + + function request_filesystem_credentials($error = false) { + $url = $this->options['url']; + $context = $this->options['context']; + if ( !empty($this->options['nonce']) ) + $url = wp_nonce_url($url, $this->options['nonce']); + return request_filesystem_credentials($url, '', $error, $context); //Possible to bring inline, Leaving as is for now. + } + + function header() { + if ( $this->done_header ) + return; + $this->done_header = true; + echo '
    '; + echo screen_icon(); + echo '

    ' . $this->options['title'] . '

    '; + } + function footer() { + echo '
    '; + } + + function error($errors) { + if ( ! $this->done_header ) + $this->header(); + if ( is_string($errors) ) { + $this->feedback($errors); + } elseif ( is_wp_error($errors) && $errors->get_error_code() ) { + foreach ( $errors->get_error_messages() as $message ) { + if ( $errors->get_error_data() ) + $this->feedback($message . ' ' . $errors->get_error_data() ); + else + $this->feedback($message); + } + } + } + + function feedback($string) { + if ( isset( $this->upgrader->strings[$string] ) ) + $string = $this->upgrader->strings[$string]; + + if ( strpos($string, '%') !== false ) { + $args = func_get_args(); + $args = array_splice($args, 1); + if ( !empty($args) ) + $string = vsprintf($string, $args); + } + if ( empty($string) ) + return; + show_message($string); + } + function before() {} + function after() {} + +} + +/** + * Plugin Upgrader Skin for WordPress Plugin Upgrades. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Plugin_Upgrader_Skin extends WP_Upgrader_Skin { + var $plugin = ''; + var $plugin_active = false; + + function Plugin_Upgrader_Skin($args = array()) { + return $this->__construct($args); + } + + function __construct($args = array()) { + $defaults = array( 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => __('Upgrade Plugin') ); + $args = wp_parse_args($args, $defaults); + + $this->plugin = $args['plugin']; + + $this->plugin_active = is_plugin_active($this->plugin); + + parent::__construct($args); + } + + function after() { + $this->plugin = $this->upgrader->plugin_info(); + if( !empty($this->plugin) && !is_wp_error($this->result) && $this->plugin_active ){ + show_message(__('Attempting reactivation of the plugin')); + echo ''; + } + $update_actions = array( + 'activate_plugin' => '' . __('Activate Plugin') . '', + 'plugins_page' => '' . __('Return to Plugins page') . '' + ); + if ( $this->plugin_active ) + unset( $update_actions['activate_plugin'] ); + if ( ! $this->result || is_wp_error($this->result) ) + unset( $update_actions['activate_plugin'] ); + + $update_actions = apply_filters('update_plugin_complete_actions', $update_actions, $this->plugin); + if ( ! empty($update_actions) ) + $this->feedback('' . __('Actions:') . ' ' . implode(' | ', (array)$update_actions)); + } +} + +/** + * Plugin Installer Skin for WordPress Plugin Installer. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Plugin_Installer_Skin extends WP_Upgrader_Skin { + var $api; + var $type; + + function Plugin_Installer_Skin($args = array()) { + return $this->__construct($args); + } + + function __construct($args = array()) { + $defaults = array( 'type' => 'web', 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => '' ); + $args = wp_parse_args($args, $defaults); + + $this->type = $args['type']; + $this->api = isset($args['api']) ? $args['api'] : array(); + + parent::__construct($args); + } + + function before() { + if ( !empty($this->api) ) + $this->upgrader->strings['process_success'] = sprintf( __('Successfully installed the plugin %s %s.'), $this->api->name, $this->api->version); + } + + function after() { + + $plugin_file = $this->upgrader->plugin_info(); + + $install_actions = array( + 'activate_plugin' => '' . __('Activate Plugin') . '', + ); + + if ( $this->type == 'web' ) + $install_actions['plugins_page'] = '' . __('Return to Plugin Installer') . ''; + else + $install_actions['plugins_page'] = '' . __('Return to Plugins page') . ''; + + + if ( ! $this->result || is_wp_error($this->result) ) + unset( $install_actions['activate_plugin'] ); + + $install_actions = apply_filters('install_plugin_complete_actions', $install_actions, $this->api, $plugin_file); + if ( ! empty($install_actions) ) + $this->feedback('' . __('Actions:') . ' ' . implode(' | ', (array)$install_actions)); + } +} + +/** + * Theme Installer Skin for the WordPress Theme Installer. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Theme_Installer_Skin extends WP_Upgrader_Skin { + var $api; + var $type; + + function Theme_Installer_Skin($args = array()) { + return $this->__construct($args); + } + + function __construct($args = array()) { + $defaults = array( 'type' => 'web', 'url' => '', 'theme' => '', 'nonce' => '', 'title' => '' ); + $args = wp_parse_args($args, $defaults); + + $this->type = $args['type']; + $this->api = isset($args['api']) ? $args['api'] : array(); + + parent::__construct($args); + } + + function before() { + if ( !empty($this->api) ) { + /* translators: 1: theme name, 2: version */ + $this->upgrader->strings['process_success'] = sprintf( __('Successfully installed the theme %1$s %2$s.'), $this->api->name, $this->api->version); + } + } + + function after() { + if ( empty($this->upgrader->result['destination_name']) ) + return; + + $theme_info = $this->upgrader->theme_info(); + if ( empty($theme_info) ) + return; + $name = $theme_info['Name']; + $stylesheet = $this->upgrader->result['destination_name']; + $template = !empty($theme_info['Template']) ? $theme_info['Template'] : $stylesheet; + + $preview_link = htmlspecialchars( add_query_arg( array('preview' => 1, 'template' => $template, 'stylesheet' => $stylesheet, 'TB_iframe' => 'true' ), trailingslashit(esc_url(get_option('home'))) ) ); + $activate_link = wp_nonce_url("themes.php?action=activate&template=" . urlencode($template) . "&stylesheet=" . urlencode($stylesheet), 'switch-theme_' . $template); + + $install_actions = array( + 'preview' => '' . __('Preview') . '', + 'activate' => '' . __('Activate') . '' + ); + + if ( $this->type == 'web' ) + $install_actions['themes_page'] = '' . __('Return to Theme Installer') . ''; + else + $install_actions['themes_page'] = '' . __('Return to Themes page') . ''; + + if ( ! $this->result || is_wp_error($this->result) ) + unset( $install_actions['activate'], $install_actions['preview'] ); + + $install_actions = apply_filters('install_theme_complete_actions', $install_actions, $this->api, $stylesheet, $theme_info); + if ( ! empty($install_actions) ) + $this->feedback('' . __('Actions:') . ' ' . implode(' | ', (array)$install_actions)); + } +} + +/** + * Theme Upgrader Skin for WordPress Theme Upgrades. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class Theme_Upgrader_Skin extends WP_Upgrader_Skin { + var $theme = ''; + + function Theme_Upgrader_Skin($args = array()) { + return $this->__construct($args); + } + + function __construct($args = array()) { + $defaults = array( 'url' => '', 'theme' => '', 'nonce' => '', 'title' => __('Upgrade Theme') ); + $args = wp_parse_args($args, $defaults); + + $this->theme = $args['theme']; + + parent::__construct($args); + } + + function after() { + + if ( !empty($this->upgrader->result['destination_name']) && + ($theme_info = $this->upgrader->theme_info()) && + !empty($theme_info) ) { + + $name = $theme_info['Name']; + $stylesheet = $this->upgrader->result['destination_name']; + $template = !empty($theme_info['Template']) ? $theme_info['Template'] : $stylesheet; + + $preview_link = htmlspecialchars( add_query_arg( array('preview' => 1, 'template' => $template, 'stylesheet' => $stylesheet, 'TB_iframe' => 'true' ), trailingslashit(esc_url(get_option('home'))) ) ); + $activate_link = wp_nonce_url("themes.php?action=activate&template=" . urlencode($template) . "&stylesheet=" . urlencode($stylesheet), 'switch-theme_' . $template); + + $update_actions = array( + 'preview' => '' . __('Preview') . '', + 'activate' => '' . __('Activate') . '', + ); + if ( ( ! $this->result || is_wp_error($this->result) ) || $stylesheet == get_stylesheet() ) + unset($update_actions['preview'], $update_actions['activate']); + } + + $update_actions['themes_page'] = '' . __('Return to Themes page') . ''; + + $update_actions = apply_filters('update_theme_complete_actions', $update_actions, $this->theme); + if ( ! empty($update_actions) ) + $this->feedback('' . __('Actions:') . ' ' . implode(' | ', (array)$update_actions)); + } +} + +/** + * Upgrade Skin helper for File uploads. This class handles the upload process and passes it as if its a local file to the Upgrade/Installer functions. + * + * @TODO More Detailed docs, for methods as well. + * + * @package WordPress + * @subpackage Upgrader + * @since 2.8.0 + */ +class File_Upload_Upgrader { + var $package; + var $filename; + + function File_Upload_Upgrader($form, $urlholder) { + return $this->__construct($form, $urlholder); + } + function __construct($form, $urlholder) { + if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) ) + wp_die($uploads['error']); + + if ( empty($_FILES[$form]['name']) && empty($_GET[$urlholder]) ) + wp_die(__('Please select a file')); + + if ( !empty($_FILES) ) + $this->filename = $_FILES[$form]['name']; + else if ( isset($_GET[$urlholder]) ) + $this->filename = $_GET[$urlholder]; + + //Handle a newly uploaded file, Else assume its already been uploaded + if ( !empty($_FILES) ) { + $this->filename = wp_unique_filename( $uploads['basedir'], $this->filename ); + $this->package = $uploads['basedir'] . '/' . $this->filename; + + // Move the file to the uploads dir + if ( false === @ move_uploaded_file( $_FILES[$form]['tmp_name'], $this->package) ) + wp_die( sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'])); + } else { + $this->package = $uploads['basedir'] . '/' . $this->filename; + } + } +} diff --git a/wp-admin/includes/comment.php b/wp-admin/includes/comment.php new file mode 100644 index 0000000..26f2556 --- /dev/null +++ b/wp-admin/includes/comment.php @@ -0,0 +1,167 @@ +get_var( $wpdb->prepare("SELECT comment_post_ID FROM $wpdb->comments + WHERE comment_author = %s AND comment_date = %s", $comment_author, $comment_date) ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function edit_comment() { + + $comment_post_ID = (int) $_POST['comment_post_ID']; + + if (!current_user_can( 'edit_post', $comment_post_ID )) + wp_die( __('You are not allowed to edit comments on this post, so you cannot edit this comment.' )); + + $_POST['comment_author'] = $_POST['newcomment_author']; + $_POST['comment_author_email'] = $_POST['newcomment_author_email']; + $_POST['comment_author_url'] = $_POST['newcomment_author_url']; + $_POST['comment_approved'] = $_POST['comment_status']; + $_POST['comment_content'] = $_POST['content']; + $_POST['comment_ID'] = (int) $_POST['comment_ID']; + + foreach ( array ('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) { + if ( !empty( $_POST['hidden_' . $timeunit] ) && $_POST['hidden_' . $timeunit] != $_POST[$timeunit] ) { + $_POST['edit_date'] = '1'; + break; + } + } + + if (!empty ( $_POST['edit_date'] ) ) { + $aa = $_POST['aa']; + $mm = $_POST['mm']; + $jj = $_POST['jj']; + $hh = $_POST['hh']; + $mn = $_POST['mn']; + $ss = $_POST['ss']; + $jj = ($jj > 31 ) ? 31 : $jj; + $hh = ($hh > 23 ) ? $hh -24 : $hh; + $mn = ($mn > 59 ) ? $mn -60 : $mn; + $ss = ($ss > 59 ) ? $ss -60 : $ss; + $_POST['comment_date'] = "$aa-$mm-$jj $hh:$mn:$ss"; + } + + wp_update_comment( $_POST); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $id + * @return unknown + */ +function get_comment_to_edit( $id ) { + if ( !$comment = get_comment($id) ) + return false; + + $comment->comment_ID = (int) $comment->comment_ID; + $comment->comment_post_ID = (int) $comment->comment_post_ID; + + $comment->comment_content = format_to_edit( $comment->comment_content ); + $comment->comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content); + + $comment->comment_author = format_to_edit( $comment->comment_author ); + $comment->comment_author_email = format_to_edit( $comment->comment_author_email ); + $comment->comment_author_url = format_to_edit( $comment->comment_author_url ); + $comment->comment_author_url = esc_url($comment->comment_author_url); + + return $comment; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * @uses $wpdb + * + * @param int $post_id Post ID + * @return unknown + */ +function get_pending_comments_num( $post_id ) { + global $wpdb; + + $single = false; + if ( !is_array($post_id) ) { + $post_id = (array) $post_id; + $single = true; + } + $post_id = array_map('intval', $post_id); + $post_id = "'" . implode("', '", $post_id) . "'"; + + $pending = $wpdb->get_results( "SELECT comment_post_ID, COUNT(comment_ID) as num_comments FROM $wpdb->comments WHERE comment_post_ID IN ( $post_id ) AND comment_approved = '0' GROUP BY comment_post_ID", ARRAY_N ); + + if ( empty($pending) ) + return 0; + + if ( $single ) + return $pending[0][1]; + + $pending_keyed = array(); + foreach ( $pending as $pend ) + $pending_keyed[$pend[0]] = $pend[1]; + + return $pending_keyed; +} + +/** + * Add avatars to relevant places in admin, or try to. + * + * @since unknown + * @uses $comment + * + * @param string $name User name. + * @return string Avatar with Admin name. + */ +function floated_admin_avatar( $name ) { + global $comment; + + $id = $avatar = false; + if ( $comment->comment_author_email ) + $id = $comment->comment_author_email; + if ( $comment->user_id ) + $id = $comment->user_id; + + if ( $id ) + $avatar = get_avatar( $id, 32 ); + + return "$avatar $name"; +} + +function enqueue_comment_hotkeys_js() { + if ( 'true' == get_user_option( 'comment_shortcuts' ) ) + wp_enqueue_script( 'jquery-table-hotkeys' ); +} + +if ( is_admin() && isset($pagenow) && ('edit-comments.php' == $pagenow || 'edit.php' == $pagenow) ) { + if ( get_option('show_avatars') ) + add_filter( 'comment_author', 'floated_admin_avatar' ); +} + +?> diff --git a/wp-admin/includes/continents-cities.php b/wp-admin/includes/continents-cities.php new file mode 100644 index 0000000..0ebc4f3 --- /dev/null +++ b/wp-admin/includes/continents-cities.php @@ -0,0 +1,493 @@ + get_option('home'), + 'link' => apply_filters( 'dashboard_incoming_links_link', 'http://blogsearch.google.com/blogsearch?hl=en&scoring=d&partner=wordpress&q=link:' . trailingslashit( get_option('home') ) ), + 'url' => isset($widget_options['dashboard_incoming_links']['url']) ? apply_filters( 'dashboard_incoming_links_feed', $widget_options['dashboard_incoming_links']['url'] ) : apply_filters( 'dashboard_incoming_links_feed', 'http://blogsearch.google.com/blogsearch_feeds?hl=en&scoring=d&ie=utf-8&num=20&output=rss&partner=wordpress&q=link:' . trailingslashit( get_option('home') ) ), + 'items' => isset($widget_options['dashboard_incoming_links']['items']) ? $widget_options['dashboard_incoming_links']['items'] : 10, + 'show_date' => isset($widget_options['dashboard_incoming_links']['show_date']) ? $widget_options['dashboard_incoming_links']['show_date'] : false + ); + } + wp_add_dashboard_widget( 'dashboard_incoming_links', __( 'Incoming Links' ), 'wp_dashboard_incoming_links', 'wp_dashboard_incoming_links_control' ); + + // WP Plugins Widget + if ( current_user_can( 'activate_plugins' ) ) + wp_add_dashboard_widget( 'dashboard_plugins', __( 'Plugins' ), 'wp_dashboard_plugins' ); + + // QuickPress Widget + if ( current_user_can('edit_posts') ) + wp_add_dashboard_widget( 'dashboard_quick_press', __( 'QuickPress' ), 'wp_dashboard_quick_press' ); + + // Recent Drafts + if ( current_user_can('edit_posts') ) + wp_add_dashboard_widget( 'dashboard_recent_drafts', __('Recent Drafts'), 'wp_dashboard_recent_drafts' ); + + // Primary feed (Dev Blog) Widget + if ( !isset( $widget_options['dashboard_primary'] ) ) { + $update = true; + $widget_options['dashboard_primary'] = array( + 'link' => apply_filters( 'dashboard_primary_link', __( 'http://wordpress.org/development/' ) ), + 'url' => apply_filters( 'dashboard_primary_feed', __( 'http://wordpress.org/development/feed/' ) ), + 'title' => apply_filters( 'dashboard_primary_title', __( 'WordPress Development Blog' ) ), + 'items' => 2, + 'show_summary' => 1, + 'show_author' => 0, + 'show_date' => 1 + ); + } + wp_add_dashboard_widget( 'dashboard_primary', $widget_options['dashboard_primary']['title'], 'wp_dashboard_primary', 'wp_dashboard_primary_control' ); + + // Secondary Feed (Planet) Widget + if ( !isset( $widget_options['dashboard_secondary'] ) ) { + $update = true; + $widget_options['dashboard_secondary'] = array( + 'link' => apply_filters( 'dashboard_secondary_link', __( 'http://planet.wordpress.org/' ) ), + 'url' => apply_filters( 'dashboard_secondary_feed', __( 'http://planet.wordpress.org/feed/' ) ), + 'title' => apply_filters( 'dashboard_secondary_title', __( 'Other WordPress News' ) ), + 'items' => 5 + ); + } + wp_add_dashboard_widget( 'dashboard_secondary', $widget_options['dashboard_secondary']['title'], 'wp_dashboard_secondary', 'wp_dashboard_secondary_control' ); + + // Hook to register new widgets + do_action( 'wp_dashboard_setup' ); + + // Filter widget order + $dashboard_widgets = apply_filters( 'wp_dashboard_widgets', array() ); + + foreach ( $dashboard_widgets as $widget_id ) { + $name = empty( $wp_registered_widgets[$widget_id]['all_link'] ) ? $wp_registered_widgets[$widget_id]['name'] : $wp_registered_widgets[$widget_id]['name'] . " " . __('View all') . ''; + wp_add_dashboard_widget( $widget_id, $name, $wp_registered_widgets[$widget_id]['callback'], $wp_registered_widget_controls[$widget_id]['callback'] ); + } + + if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget_id']) ) { + ob_start(); // hack - but the same hack wp-admin/widgets.php uses + wp_dashboard_trigger_widget_control( $_POST['widget_id'] ); + ob_end_clean(); + wp_redirect( remove_query_arg( 'edit' ) ); + exit; + } + + if ( $update ) + update_option( 'dashboard_widget_options', $widget_options ); + + do_action('do_meta_boxes', 'dashboard', 'normal', ''); + do_action('do_meta_boxes', 'dashboard', 'side', ''); +} + +function wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback = null ) { + global $wp_dashboard_control_callbacks; + if ( $control_callback && current_user_can( 'edit_dashboard' ) && is_callable( $control_callback ) ) { + $wp_dashboard_control_callbacks[$widget_id] = $control_callback; + if ( isset( $_GET['edit'] ) && $widget_id == $_GET['edit'] ) { + list($url) = explode( '#', add_query_arg( 'edit', false ), 2 ); + $widget_name .= ' ' . __( 'Cancel' ) . ''; + add_meta_box( $widget_id, $widget_name, '_wp_dashboard_control_callback', 'dashboard', 'normal', 'core' ); + return; + } + list($url) = explode( '#', add_query_arg( 'edit', $widget_id ), 2 ); + $widget_name .= ' ' . __( 'Configure' ) . ''; + } + $side_widgets = array('dashboard_quick_press', 'dashboard_recent_drafts', 'dashboard_primary', 'dashboard_secondary'); + $location = 'normal'; + if ( in_array($widget_id, $side_widgets) ) + $location = 'side'; + add_meta_box( $widget_id, $widget_name , $callback, 'dashboard', $location, 'core' ); +} + +function _wp_dashboard_control_callback( $dashboard, $meta_box ) { + echo '
    '; + wp_dashboard_trigger_widget_control( $meta_box['id'] ); + echo "

    "; + + echo '
    '; +} + +/** + * Displays the dashboard. + * + * @since unknown + */ +function wp_dashboard() { + global $screen_layout_columns; + + $hide2 = $hide3 = $hide4 = ''; + switch ( $screen_layout_columns ) { + case 4: + $width = 'width:24.5%;'; + break; + case 3: + $width = 'width:32.67%;'; + $hide4 = 'display:none;'; + break; + case 2: + $width = 'width:49%;'; + $hide3 = $hide4 = 'display:none;'; + break; + default: + $width = 'width:98%;'; + $hide2 = $hide3 = $hide4 = 'display:none;'; + } +?> +
    +\n"; + do_meta_boxes( 'dashboard', 'normal', '' ); + + echo "\t
    \n"; + do_meta_boxes( 'dashboard', 'side', '' ); + + echo "\t
    \n"; + do_meta_boxes( 'dashboard', 'column3', '' ); + + echo "\t
    \n"; + do_meta_boxes( 'dashboard', 'column4', '' ); +?> +
    + +
    +

    + +

    +
    + +' . __('At a Glance') . '

    '; + echo "\n\t".'
    '."\n\t".''; + echo "\n\t".''; + + // Posts + $num = number_format_i18n( $num_posts->publish ); + $text = _n( 'Post', 'Posts', intval($num_posts->publish) ); + if ( current_user_can( 'edit_posts' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + /* TODO: Show status breakdown on hover + if ( $can_edit_pages && !empty($num_pages->publish) ) { // how many pages is not exposed in feeds. Don't show if !current_user_can + $post_type_texts[] = ''.sprintf( _n( '%s page', '%s pages', $num_pages->publish ), number_format_i18n( $num_pages->publish ) ).''; + } + if ( $can_edit_posts && !empty($num_posts->draft) ) { + $post_type_texts[] = ''.sprintf( _n( '%s draft', '%s drafts', $num_posts->draft ), number_format_i18n( $num_posts->draft ) ).''; + } + if ( $can_edit_posts && !empty($num_posts->future) ) { + $post_type_texts[] = ''.sprintf( _n( '%s scheduled post', '%s scheduled posts', $num_posts->future ), number_format_i18n( $num_posts->future ) ).''; + } + if ( current_user_can('publish_posts') && !empty($num_posts->pending) ) { + $pending_text = sprintf( _n( 'There is %2$s post pending your review.', 'There are %2$s posts pending your review.', $num_posts->pending ), 'edit.php?post_status=pending', number_format_i18n( $num_posts->pending ) ); + } else { + $pending_text = ''; + } + */ + + // Total Comments + $num = number_format_i18n($num_comm->total_comments); + $text = _n( 'Comment', 'Comments', $num_comm->total_comments ); + if ( current_user_can( 'moderate_comments' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + echo ''; + + // Pages + $num = number_format_i18n( $num_pages->publish ); + $text = _n( 'Page', 'Pages', $num_pages->publish ); + if ( current_user_can( 'edit_pages' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + // Approved Comments + $num = number_format_i18n($num_comm->approved); + $text = _nc( 'Approved|Right Now', 'Approved', $num_comm->approved ); + if ( current_user_can( 'moderate_comments' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + echo "\n\t"; + + // Categories + $num = number_format_i18n( $num_cats ); + $text = _n( 'Category', 'Categories', $num_cats ); + if ( current_user_can( 'manage_categories' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + // Pending Comments + $num = number_format_i18n($num_comm->moderated); + $text = _n( 'Pending', 'Pending', $num_comm->moderated ); + if ( current_user_can( 'moderate_comments' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + echo "\n\t"; + + // Tags + $num = number_format_i18n( $num_tags ); + $text = _n( 'Tag', 'Tags', $num_tags ); + if ( current_user_can( 'manage_categories' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + // Spam Comments + $num = number_format_i18n($num_comm->spam); + $text = _n( 'Spam', 'Spam', $num_comm->spam ); + if ( current_user_can( 'moderate_comments' ) ) { + $num = "$num"; + $text = "$text"; + } + echo ''; + echo ''; + + echo ""; + do_action('right_now_table_end'); + echo "\n\t
    ' . $num . '' . $text . '' . $num . '' . $text . '
    ' . $num . '' . $text . '' . $num . '' . $text . '
    ' . $num . '' . $text . '' . $num . '' . $text . '
    ' . $num . '' . $text . '' . $num . '' . $text . '
    \n\t
    "; + + echo "\n\t".'
    '; + $ct = current_theme_info(); + + echo "\n\t

    "; + if ( !empty($wp_registered_sidebars) ) { + $sidebars_widgets = wp_get_sidebars_widgets(); + $num_widgets = 0; + foreach ( (array) $sidebars_widgets as $k => $v ) { + if ( 'wp_inactive_widgets' == $k ) + continue; + if ( is_array($v) ) + $num_widgets = $num_widgets + count($v); + } + $num = number_format_i18n( $num_widgets ); + + if ( current_user_can( 'switch_themes' ) ) { + echo '' . __('Change Theme') . ''; + printf(_n('Theme %1$s with %2$s Widget', 'Theme %1$s with %2$s Widgets', $num_widgets), $ct->title, $num); + } else { + printf(_n('Theme %1$s with %2$s Widget', 'Theme %1$s with %2$s Widgets', $num_widgets), $ct->title, $num); + } + } else { + if ( current_user_can( 'switch_themes' ) ) { + echo '' . __('Change Theme') . ''; + printf('Theme %1$s', $ct->title); + } else { + printf('Theme %1$s', $ct->title); + } + } + echo '

    '; + + update_right_now_message(); + + echo "\n\t".'
    '; + do_action( 'rightnow_end' ); + do_action( 'activity_box_end' ); +} + +function wp_dashboard_quick_press() { + $drafts = false; + if ( 'post' === strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['action'] ) && 0 === strpos( $_POST['action'], 'post-quickpress' ) && (int) $_POST['post_ID'] ) { + $view = get_permalink( $_POST['post_ID'] ); + $edit = esc_url( get_edit_post_link( $_POST['post_ID'] ) ); + if ( 'post-quickpress-publish' == $_POST['action'] ) { + if ( current_user_can('publish_posts') ) + printf( '

    ' . __( 'Post Published. View post | Edit post' ) . '

    ', esc_url( $view ), $edit ); + else + printf( '

    ' . __( 'Post submitted. Preview post | Edit post' ) . '

    ', esc_url( add_query_arg( 'preview', 1, $view ) ), $edit ); + } else { + printf( '

    ' . __( 'Draft Saved. Preview post | Edit post' ) . '

    ', esc_url( add_query_arg( 'preview', 1, $view ) ), $edit ); + $drafts_query = new WP_Query( array( + 'post_type' => 'post', + 'post_status' => 'draft', + 'author' => $GLOBALS['current_user']->ID, + 'posts_per_page' => 1, + 'orderby' => 'modified', + 'order' => 'DESC' + ) ); + + if ( $drafts_query->posts ) + $drafts =& $drafts_query->posts; + } + printf('

    ' . __('You can also try %s, easy blogging from anywhere on the Web.') . '

    ', '' . __('Press This') . '' ); + $_REQUEST = array(); // hack for get_default_post_to_edit() + } + + $post = get_default_post_to_edit(); +?> + +
    +

    +
    + +
    + + +
    + +
    + + +

    +
    + +
    + + + +

    +
    + +
    + +

    + + + + + + + + + + +
    +

    + +
    + + 'post', + 'post_status' => 'draft', + 'author' => $GLOBALS['current_user']->ID, + 'posts_per_page' => 5, + 'orderby' => 'modified', + 'order' => 'DESC' + ) ); + $drafts =& $drafts_query->posts; + } + + if ( $drafts && is_array( $drafts ) ) { + $list = array(); + foreach ( $drafts as $draft ) { + $url = get_edit_post_link( $draft->ID ); + $title = _draft_or_post_title( $draft->ID ); + $item = "

    $title " . get_the_time( get_option( 'date_format' ), $draft ) . '

    '; + if ( $the_content = preg_split( '#\s#', strip_tags( $draft->post_content ), 11, PREG_SPLIT_NO_EMPTY ) ) + $item .= '

    ' . join( ' ', array_slice( $the_content, 0, 10 ) ) . ( 10 < count( $the_content ) ? '…' : '' ) . '

    '; + $list[] = $item; + } +?> +
      +
    • \n
    • ", $list ); ?>
    • +
    +

    +get_results( "SELECT * FROM $wpdb->comments ORDER BY comment_date_gmt DESC LIMIT $start, 50" ) ) { + + foreach ( $possible as $comment ) { + if ( count( $comments ) >= 5 ) + break; + if ( in_array( $comment->comment_approved, $allowed_states ) ) + $comments[] = $comment; + } + + $start = $start + 50; + } + + if ( $comments ) : +?> + +
    + + +
    + + +

    + + +

    + +comment_post_ID ); + $comment_post_title = strip_tags(get_the_title( $comment->comment_post_ID )); + $comment_post_link = "$comment_post_title"; + $comment_link = '#'; + + $delete_url = esc_url( wp_nonce_url( "comment.php?action=deletecomment&p=$comment->comment_post_ID&c=$comment->comment_ID", "delete-comment_$comment->comment_ID" ) ); + $approve_url = esc_url( wp_nonce_url( "comment.php?action=approvecomment&p=$comment->comment_post_ID&c=$comment->comment_ID", "approve-comment_$comment->comment_ID" ) ); + $unapprove_url = esc_url( wp_nonce_url( "comment.php?action=unapprovecomment&p=$comment->comment_post_ID&c=$comment->comment_ID", "unapprove-comment_$comment->comment_ID" ) ); + $spam_url = esc_url( wp_nonce_url( "comment.php?action=deletecomment&dt=spam&p=$comment->comment_post_ID&c=$comment->comment_ID", "delete-comment_$comment->comment_ID" ) ); + + $actions = array(); + + $actions_string = ''; + if ( current_user_can('edit_post', $comment->comment_post_ID) ) { + $actions['approve'] = "" . __( 'Approve' ) . ''; + $actions['unapprove'] = "" . __( 'Unapprove' ) . ''; + $actions['edit'] = "". __('Edit') . ''; + //$actions['quickedit'] = '' . __('Quick Edit') . ''; + $actions['reply'] = '' . __('Reply') . ''; + $actions['spam'] = "" . /* translators: mark as spam link */ _x( 'Spam', 'verb' ) . ''; + $actions['delete'] = "" . __('Delete') . ''; + + $actions = apply_filters( 'comment_row_actions', $actions, $comment ); + + $i = 0; + foreach ( $actions as $action => $link ) { + ++$i; + ( ( ('approve' == $action || 'unapprove' == $action) && 2 === $i ) || 1 === $i ) ? $sep = '' : $sep = ' | '; + + // Reply and quickedit need a hide-if-no-js span + if ( 'reply' == $action || 'quickedit' == $action ) + $action .= ' hide-if-no-js'; + + $actions_string .= "$sep$link"; + } + } + +?> + +
    comment_ID) ) ); ?>> + comment_type || 'comment' == $comment->comment_type ) : ?> + + + +
    +

    ' . get_comment_author_link() . '', $comment_post_link." ".$comment_link, ' ' . __( '[Pending]' ) . '' ); ?>

    + + comment_type ) : + case 'pingback' : + $type = __( 'Pingback' ); + break; + case 'trackback' : + $type = __( 'Trackback' ); + break; + default : + $type = ucwords( $comment->comment_type ); + endswitch; + $type = esc_html( $type ); + ?> +
    + +

    $type", $comment_post_link ); ?>

    +

    + + +

    +

    + + +
    +
    +' . __( 'Loading…' ) . '

    ' . __('This widget requires JavaScript.') . '

    '; +} + +/** + * Display incoming links dashboard widget content. + * + * @since unknown + */ +function wp_dashboard_incoming_links_output() { + $widgets = get_option( 'dashboard_widget_options' ); + @extract( @$widgets['dashboard_incoming_links'], EXTR_SKIP ); + $rss = fetch_feed( $url ); + + if ( is_wp_error($rss) ) { + if ( is_admin() || current_user_can('manage_options') ) { + echo '

    '; + printf(__('RSS Error: %s'), $rss->get_error_message()); + echo '

    '; + } + return; + } + + if ( !$rss->get_item_quantity() ) { + echo '

    ' . __('This dashboard widget queries Google Blog Search so that when another blog links to your site it will show up here. It has found no incoming links… yet. It’s okay — there is no rush.') . "

    \n"; + return; + } + + echo "
      \n"; + + if ( !isset($items) ) + $items = 10; + + foreach ( $rss->get_items(0, $items) as $item ) { + $publisher = ''; + $site_link = ''; + $link = ''; + $content = ''; + $date = ''; + $link = esc_url( strip_tags( $item->get_link() ) ); + + $author = $item->get_author(); + if ( $author ) { + $site_link = esc_url( strip_tags( $author->get_link() ) ); + + if ( !$publisher = esc_html( strip_tags( $author->get_name() ) ) ) + $publisher = __( 'Somebody' ); + } else { + $publisher = __( 'Somebody' ); + } + if ( $site_link ) + $publisher = "$publisher"; + else + $publisher = "$publisher"; + + $content = $item->get_content(); + $content = wp_html_excerpt($content, 50) . ' ...'; + + if ( $link ) + /* translators: incoming links feed, %1$s is other person, %3$s is content */ + $text = __( '%1$s linked here saying, "%3$s"' ); + else + /* translators: incoming links feed, %1$s is other person, %3$s is content */ + $text = __( '%1$s linked here saying, "%3$s"' ); + + if ( $show_date ) { + if ( $show_author || $show_summary ) + /* translators: incoming links feed, %4$s is the date */ + $text .= ' ' . __( 'on %4$s' ); + $date = esc_html( strip_tags( $item->get_date() ) ); + $date = strtotime( $date ); + $date = gmdate( get_option( 'date_format' ), $date ); + } + + echo "\t
    • " . sprintf( $text, $publisher, $link, $content, $date ) . "
    • \n"; + } + + echo "
    \n"; + +} + +function wp_dashboard_incoming_links_control() { + wp_dashboard_rss_control( 'dashboard_incoming_links', array( 'title' => false, 'show_summary' => false, 'show_author' => false ) ); +} + +function wp_dashboard_primary() { + echo '

    ' . __( 'Loading…' ) . '

    ' . __('This widget requires JavaScript.') . '

    '; +} + +function wp_dashboard_primary_control() { + wp_dashboard_rss_control( 'dashboard_primary' ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param int $widget_id + */ +function wp_dashboard_rss_output( $widget_id ) { + $widgets = get_option( 'dashboard_widget_options' ); + echo "
    "; + wp_widget_rss_output( $widgets[$widget_id] ); + echo "
    "; +} + +function wp_dashboard_secondary() { + echo '

    ' . __( 'Loading…' ) . '

    ' . __('This widget requires JavaScript.') . '

    '; +} + +function wp_dashboard_secondary_control() { + wp_dashboard_rss_control( 'dashboard_secondary' ); +} + +/** + * Display secondary dashboard RSS widget feed. + * + * @since unknown + * + * @return unknown + */ +function wp_dashboard_secondary_output() { + $widgets = get_option( 'dashboard_widget_options' ); + @extract( @$widgets['dashboard_secondary'], EXTR_SKIP ); + $rss = @fetch_feed( $url ); + + if ( is_wp_error($rss) ) { + if ( is_admin() || current_user_can('manage_options') ) { + echo '

    '; + printf(__('RSS Error: %s'), $rss->get_error_message()); + echo '

    '; + } + } elseif ( !$rss->get_item_quantity() ) { + return false; + } else { + echo '
    '; + wp_widget_rss_output( $rss, $widgets['dashboard_secondary'] ); + echo '
    '; + } +} + +function wp_dashboard_plugins() { + echo '

    ' . __( 'Loading…' ) . '

    ' . __('This widget requires JavaScript.') . '

    '; +} + +/** + * Display plugins most popular, newest plugins, and recently updated widget text. + * + * @since unknown + */ +function wp_dashboard_plugins_output() { + $popular = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/popular/' ); + $new = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/new/' ); + $updated = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/updated/' ); + + if ( false === $plugin_slugs = get_transient( 'plugin_slugs' ) ) { + $plugin_slugs = array_keys( get_plugins() ); + set_transient( 'plugin_slugs', $plugin_slugs, 86400 ); + } + + foreach ( array( 'popular' => __('Most Popular'), 'new' => __('Newest Plugins'), 'updated' => __('Recently Updated') ) as $feed => $label ) { + if ( is_wp_error($$feed) || !$$feed->get_item_quantity() ) + continue; + + $items = $$feed->get_items(0, 5); + + // Pick a random, non-installed plugin + while ( true ) { + // Abort this foreach loop iteration if there's no plugins left of this type + if ( 0 == count($items) ) + continue 2; + + $item_key = array_rand($items); + $item = $items[$item_key]; + + list($link, $frag) = explode( '#', $item->get_link() ); + + $link = esc_url($link); + if ( preg_match( '|/([^/]+?)/?$|', $link, $matches ) ) + $slug = $matches[1]; + else { + unset( $items[$item_key] ); + continue; + } + + // Is this random plugin's slug already installed? If so, try again. + reset( $plugin_slugs ); + foreach ( $plugin_slugs as $plugin_slug ) { + if ( $slug == substr( $plugin_slug, 0, strlen( $slug ) ) ) { + unset( $items[$item_key] ); + continue 2; + } + } + + // If we get to this point, then the random plugin isn't installed and we can stop the while(). + break; + } + + // Eliminate some common badly formed plugin descriptions + while ( ( null !== $item_key = array_rand($items) ) && false !== strpos( $items[$item_key]->get_description(), 'Plugin Name:' ) ) + unset($items[$item_key]); + + if ( !isset($items[$item_key]) ) + continue; + + // current bbPress feed item titles are: user on "topic title" + if ( preg_match( '/"(.*)"/s', $item->get_title(), $matches ) ) + $title = $matches[1]; + else // but let's make it forward compatible if things change + $title = $item->get_title(); + $title = esc_html( $title ); + + $description = esc_html( strip_tags(@html_entity_decode($item->get_description(), ENT_QUOTES, get_option('blog_charset'))) ); + + $ilink = wp_nonce_url('plugin-install.php?tab=plugin-information&plugin=' . $slug, 'install-plugin_' . $slug) . + '&TB_iframe=true&width=600&height=800'; + + echo "

    $label

    \n"; + echo "
    $title
     (" . __( 'Install' ) . ")\n"; + echo "

    $description

    \n"; + } +} + +/** + * Checks to see if all of the feed url in $check_urls are cached. + * + * If $check_urls is empty, look for the rss feed url found in the dashboard + * widget optios of $widget_id. If cached, call $callback, a function that + * echoes out output for this widget. If not cache, echo a "Loading..." stub + * which is later replaced by AJAX call (see top of /wp-admin/index.php) + * + * @since unknown + * + * @param int $widget_id + * @param callback $callback + * @param array $check_urls RSS feeds + * @return bool False on failure. True on success. + */ +function wp_dashboard_cached_rss_widget( $widget_id, $callback, $check_urls = array() ) { + $loading = '

    ' . __( 'Loading…' ) . '

    '; + + if ( empty($check_urls) ) { + $widgets = get_option( 'dashboard_widget_options' ); + if ( empty($widgets[$widget_id]['url']) ) { + echo $loading; + return false; + } + $check_urls = array( $widgets[$widget_id]['url'] ); + } + + include_once ABSPATH . WPINC . '/class-feed.php'; + foreach ( $check_urls as $check_url ) { + $cache = new WP_Feed_Cache_Transient('', md5($check_url), ''); + if ( ! $cache->load() ) { + echo $loading; + return false; + } + } + + if ( $callback && is_callable( $callback ) ) { + $args = array_slice( func_get_args(), 2 ); + array_unshift( $args, $widget_id ); + call_user_func_array( $callback, $args ); + } + + return true; +} + +/* Dashboard Widgets Controls */ + +// Calls widget_control callback +/** + * Calls widget control callback. + * + * @since unknown + * + * @param int $widget_control_id Registered Widget ID. + */ +function wp_dashboard_trigger_widget_control( $widget_control_id = false ) { + global $wp_dashboard_control_callbacks; + + if ( is_scalar($widget_control_id) && $widget_control_id && isset($wp_dashboard_control_callbacks[$widget_control_id]) && is_callable($wp_dashboard_control_callbacks[$widget_control_id]) ) { + call_user_func( $wp_dashboard_control_callbacks[$widget_control_id], '', array( 'id' => $widget_control_id, 'callback' => $wp_dashboard_control_callbacks[$widget_control_id] ) ); + } +} + +/** + * The RSS dashboard widget control. + * + * Sets up $args to be used as input to wp_widget_rss_form(). Handles POST data + * from RSS-type widgets. + * + * @since unknown + * + * @param string widget_id + * @param array form_inputs + */ +function wp_dashboard_rss_control( $widget_id, $form_inputs = array() ) { + if ( !$widget_options = get_option( 'dashboard_widget_options' ) ) + $widget_options = array(); + + if ( !isset($widget_options[$widget_id]) ) + $widget_options[$widget_id] = array(); + + $number = 1; // Hack to use wp_widget_rss_form() + $widget_options[$widget_id]['number'] = $number; + + if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget-rss'][$number]) ) { + $_POST['widget-rss'][$number] = stripslashes_deep( $_POST['widget-rss'][$number] ); + $widget_options[$widget_id] = wp_widget_rss_process( $_POST['widget-rss'][$number] ); + // title is optional. If black, fill it if possible + if ( !$widget_options[$widget_id]['title'] && isset($_POST['widget-rss'][$number]['title']) ) { + $rss = fetch_feed($widget_options[$widget_id]['url']); + if ( ! is_wp_error($rss) ) + $widget_options[$widget_id]['title'] = htmlentities(strip_tags($rss->get_title())); + else + $widget_options[$widget_id]['title'] = htmlentities(__('Unknown Feed')); + } + update_option( 'dashboard_widget_options', $widget_options ); + } + + wp_widget_rss_form( $widget_options[$widget_id], $form_inputs ); +} + +/** + * Empty function usable by plugins to output empty dashboard widget (to be populated later by JS). + */ +function wp_dashboard_empty() {} + +?> diff --git a/wp-admin/includes/export.php b/wp-admin/includes/export.php new file mode 100644 index 0000000..641e173 --- /dev/null +++ b/wp-admin/includes/export.php @@ -0,0 +1,334 @@ +prepare(" WHERE post_author = %d ", $author_id); +} + +// grab a snapshot of post IDs, just in case it changes during the export +$post_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts $where ORDER BY post_date_gmt ASC"); + +$categories = (array) get_categories('get=all'); +$tags = (array) get_tags('get=all'); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $categories + */ +function wxr_missing_parents($categories) { + if ( !is_array($categories) || empty($categories) ) + return array(); + + foreach ( $categories as $category ) + $parents[$category->term_id] = $category->parent; + + $parents = array_unique(array_diff($parents, array_keys($parents))); + + if ( $zero = array_search('0', $parents) ) + unset($parents[$zero]); + + return $parents; +} + +while ( $parents = wxr_missing_parents($categories) ) { + $found_parents = get_categories("include=" . join(', ', $parents)); + if ( is_array($found_parents) && count($found_parents) ) + $categories = array_merge($categories, $found_parents); + else + break; +} + +// Put them in order to be inserted with no child going before its parent +$pass = 0; +$passes = 1000 + count($categories); +while ( ( $cat = array_shift($categories) ) && ++$pass < $passes ) { + if ( $cat->parent == 0 || isset($cats[$cat->parent]) ) { + $cats[$cat->term_id] = $cat; + } else { + $categories[] = $cat; + } +} +unset($categories); + +/** + * Place string in CDATA tag. + * + * @since unknown + * + * @param string $str String to place in XML CDATA tag. + */ +function wxr_cdata($str) { + if ( seems_utf8($str) == false ) + $str = utf8_encode($str); + + // $str = ent2ncr(esc_html($str)); + + $str = ""; + + return $str; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return string Site URL. + */ +function wxr_site_url() { + global $current_site; + + // mu: the base url + if ( isset($current_site->domain) ) { + return 'http://'.$current_site->domain.$current_site->path; + } + // wp: the blog url + else { + return get_bloginfo_rss('url'); + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param object $c Category Object + */ +function wxr_cat_name($c) { + if ( empty($c->name) ) + return; + + echo '' . wxr_cdata($c->name) . ''; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param object $c Category Object + */ +function wxr_category_description($c) { + if ( empty($c->description) ) + return; + + echo '' . wxr_cdata($c->description) . ''; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param object $t Tag Object + */ +function wxr_tag_name($t) { + if ( empty($t->name) ) + return; + + echo '' . wxr_cdata($t->name) . ''; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param object $t Tag Object + */ +function wxr_tag_description($t) { + if ( empty($t->description) ) + return; + + echo '' . wxr_cdata($t->description) . ''; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function wxr_post_taxonomy() { + $categories = get_the_category(); + $tags = get_the_tags(); + $the_list = ''; + $filter = 'rss'; + + if ( !empty($categories) ) foreach ( (array) $categories as $category ) { + $cat_name = sanitize_term_field('name', $category->name, $category->term_id, 'category', $filter); + // for backwards compatibility + $the_list .= "\n\t\t\n"; + // forwards compatibility: use a unique identifier for each cat to avoid clashes + // http://trac.wordpress.org/ticket/5447 + $the_list .= "\n\t\tslug}\">\n"; + } + + if ( !empty($tags) ) foreach ( (array) $tags as $tag ) { + $tag_name = sanitize_term_field('name', $tag->name, $tag->term_id, 'post_tag', $filter); + $the_list .= "\n\t\t\n"; + // forwards compatibility as above + $the_list .= "\n\t\tslug}\">\n"; + } + + echo $the_list; +} + +echo '\n"; + +?> + + + + + + + + + + + + + + + + + + + + + <?php bloginfo_rss('name'); ?> + + + + http://wordpress.org/?v= + + + + + + slug; ?>parent ? $cats[$c->parent]->name : ''; ?> + + + slug; ?> + + + in_the_loop = true; // Fake being in the loop. + // fetch 20 posts at a time rather than loading the entire table into memory + while ( $next_posts = array_splice($post_ids, 0, 20) ) { + $where = "WHERE ID IN (".join(',', $next_posts).")"; + $posts = $wpdb->get_results("SELECT * FROM $wpdb->posts $where ORDER BY post_date_gmt ASC"); + foreach ($posts as $post) { + // Don't export revisions. They bloat the export. + if ( 'revision' == $post->post_type ) + continue; + setup_postdata($post); ?> + +<?php echo apply_filters('the_title_rss', $post->post_title); ?> + + + + + + + +post_content) ); ?> +post_excerpt) ); ?> +ID; ?> +post_date; ?> +post_date_gmt; ?> +comment_status; ?> +ping_status; ?> +post_name; ?> +post_status; ?> +post_parent; ?> +menu_order; ?> +post_type; ?> +post_password; ?> +post_type == 'attachment') { ?> +ID); ?> + +get_results( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID) ); +if ( $postmeta ) { +?> + + +meta_key; ?> +meta_value; ?> + + + +get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d", $post->ID) ); +if ( $comments ) { foreach ( $comments as $c ) { ?> + +comment_ID; ?> +comment_author); ?> +comment_author_email; ?> +comment_author_url; ?> +comment_author_IP; ?> +comment_date; ?> +comment_date_gmt; ?> +comment_content) ?> +comment_approved; ?> +comment_type; ?> +comment_parent; ?> +user_id; ?> + + + + + + + diff --git a/wp-admin/includes/file.php b/wp-admin/includes/file.php new file mode 100644 index 0000000..5cd7a45 --- /dev/null +++ b/wp-admin/includes/file.php @@ -0,0 +1,807 @@ + __( 'Main Index Template' ), + 'style.css' => __( 'Stylesheet' ), + 'rtl.css' => __( 'RTL Stylesheet' ), + 'comments.php' => __( 'Comments' ), + 'comments-popup.php' => __( 'Popup Comments' ), + 'footer.php' => __( 'Footer' ), + 'header.php' => __( 'Header' ), + 'sidebar.php' => __( 'Sidebar' ), + 'archive.php' => __( 'Archives' ), + 'category.php' => __( 'Category Template' ), + 'page.php' => __( 'Page Template' ), + 'search.php' => __( 'Search Results' ), + 'searchform.php' => __( 'Search Form' ), + 'single.php' => __( 'Single Post' ), + '404.php' => __( '404 Template' ), + 'link.php' => __( 'Links Template' ), + 'functions.php' => __( 'Theme Functions' ), + 'attachment.php' => __( 'Attachment Template' ), + 'image.php' => __('Image Attachment Template'), + 'video.php' => __('Video Attachment Template'), + 'audio.php' => __('Audio Attachment Template'), + 'application.php' => __('Application Attachment Template'), + 'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ), + '.htaccess' => __( '.htaccess (for rewrite rules )' ), + // Deprecated files + 'wp-layout.css' => __( 'Stylesheet' ), 'wp-comments.php' => __( 'Comments Template' ), 'wp-comments-popup.php' => __( 'Popup Comments Template' )); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file + * @return unknown + */ +function get_file_description( $file ) { + global $wp_file_descriptions; + + if ( isset( $wp_file_descriptions[basename( $file )] ) ) { + return $wp_file_descriptions[basename( $file )]; + } + elseif ( file_exists( WP_CONTENT_DIR . $file ) && is_file( WP_CONTENT_DIR . $file ) ) { + $template_data = implode( '', file( WP_CONTENT_DIR . $file ) ); + if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name )) + return _cleanup_header_comment($name[1]) . ' Page Template'; + } + + return basename( $file ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function get_home_path() { + $home = get_option( 'home' ); + $siteurl = get_option( 'siteurl' ); + if ( $home != '' && $home != $siteurl ) { + $wp_path_rel_to_home = str_replace($home, '', $siteurl); /* $siteurl - $home */ + $pos = strpos($_SERVER["SCRIPT_FILENAME"], $wp_path_rel_to_home); + $home_path = substr($_SERVER["SCRIPT_FILENAME"], 0, $pos); + $home_path = trailingslashit( $home_path ); + } else { + $home_path = ABSPATH; + } + + return $home_path; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file + * @return unknown + */ +function get_real_file_to_edit( $file ) { + if ('index.php' == $file || '.htaccess' == $file ) { + $real_file = get_home_path() . $file; + } else { + $real_file = WP_CONTENT_DIR . $file; + } + + return $real_file; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param string $folder Optional. Full path to folder + * @param int $levels Optional. Levels of folders to follow, Default: 100 (PHP Loop limit). + * @return bool|array + */ +function list_files( $folder = '', $levels = 100 ) { + if( empty($folder) ) + return false; + + if( ! $levels ) + return false; + + $files = array(); + if ( $dir = @opendir( $folder ) ) { + while (($file = readdir( $dir ) ) !== false ) { + if ( in_array($file, array('.', '..') ) ) + continue; + if ( is_dir( $folder . '/' . $file ) ) { + $files2 = list_files( $folder . '/' . $file, $levels - 1); + if( $files2 ) + $files = array_merge($files, $files2 ); + else + $files[] = $folder . '/' . $file . '/'; + } else { + $files[] = $folder . '/' . $file; + } + } + } + @closedir( $dir ); + return $files; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function get_temp_dir() { + if ( defined('WP_TEMP_DIR') ) + return trailingslashit(WP_TEMP_DIR); + + $temp = WP_CONTENT_DIR . '/'; + if ( is_dir($temp) && is_writable($temp) ) + return $temp; + + if ( function_exists('sys_get_temp_dir') ) + return trailingslashit(sys_get_temp_dir()); + + return '/tmp/'; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $filename + * @param unknown_type $dir + * @return unknown + */ +function wp_tempnam($filename = '', $dir = ''){ + if ( empty($dir) ) + $dir = get_temp_dir(); + $filename = basename($filename); + if ( empty($filename) ) + $filename = time(); + + $filename = $dir . wp_unique_filename($dir, $filename); + touch($filename); + return $filename; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file + * @param unknown_type $allowed_files + * @return unknown + */ +function validate_file_to_edit( $file, $allowed_files = '' ) { + $file = stripslashes( $file ); + + $code = validate_file( $file, $allowed_files ); + + if (!$code ) + return $file; + + switch ( $code ) { + case 1 : + wp_die( __('Sorry, can’t edit files with “..” in the name. If you are trying to edit a file in your WordPress home directory, you can just type the name of the file in.' )); + + case 2 : + wp_die( __('Sorry, can’t call files with their real path.' )); + + case 3 : + wp_die( __('Sorry, that file cannot be edited.' )); + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param array $file Reference to a single element of $_FILES. Call the function once for each uploaded file. + * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ). + * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ). + */ +function wp_handle_upload( &$file, $overrides = false, $time = null ) { + // The default error handler. + if (! function_exists( 'wp_handle_upload_error' ) ) { + function wp_handle_upload_error( &$file, $message ) { + return array( 'error'=>$message ); + } + } + + // You may define your own function and pass the name in $overrides['upload_error_handler'] + $upload_error_handler = 'wp_handle_upload_error'; + + // You may define your own function and pass the name in $overrides['unique_filename_callback'] + $unique_filename_callback = null; + + // $_POST['action'] must be set and its value must equal $overrides['action'] or this: + $action = 'wp_handle_upload'; + + // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error']. + $upload_error_strings = array( false, + __( "The uploaded file exceeds the upload_max_filesize directive in php.ini." ), + __( "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." ), + __( "The uploaded file was only partially uploaded." ), + __( "No file was uploaded." ), + '', + __( "Missing a temporary folder." ), + __( "Failed to write file to disk." ), + __( "File upload stopped by extension." )); + + // All tests are on by default. Most can be turned off by $override[{test_name}] = false; + $test_form = true; + $test_size = true; + + // If you override this, you must provide $ext and $type!!!! + $test_type = true; + $mimes = false; + + // Install user overrides. Did we mention that this voids your warranty? + if ( is_array( $overrides ) ) + extract( $overrides, EXTR_OVERWRITE ); + + // A correct form post will pass this test. + if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) ) + return $upload_error_handler( $file, __( 'Invalid form submission.' )); + + // A successful upload will pass this test. It makes no sense to override this one. + if ( $file['error'] > 0 ) + return $upload_error_handler( $file, $upload_error_strings[$file['error']] ); + + // A non-empty file will pass this test. + if ( $test_size && !($file['size'] > 0 ) ) + return $upload_error_handler( $file, __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.' )); + + // A properly uploaded file will pass this test. There should be no reason to override this one. + if (! @ is_uploaded_file( $file['tmp_name'] ) ) + return $upload_error_handler( $file, __( 'Specified file failed upload test.' )); + + // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter. + if ( $test_type ) { + $wp_filetype = wp_check_filetype( $file['name'], $mimes ); + + extract( $wp_filetype ); + + if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) + return $upload_error_handler( $file, __( 'File type does not meet security guidelines. Try another.' )); + + if ( !$ext ) + $ext = ltrim(strrchr($file['name'], '.'), '.'); + + if ( !$type ) + $type = $file['type']; + } else { + $type = ''; + } + + // A writable uploads dir will pass this test. Again, there's no point overriding this one. + if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) ) + return $upload_error_handler( $file, $uploads['error'] ); + + $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback ); + + // Move the file to the uploads dir + $new_file = $uploads['path'] . "/$filename"; + if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) ) { + return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) ); + } + + // Set correct file permissions + $stat = stat( dirname( $new_file )); + $perms = $stat['mode'] & 0000666; + @ chmod( $new_file, $perms ); + + // Compute the URL + $url = $uploads['url'] . "/$filename"; + + return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) ); +} + +/** + * {@internal Missing Short Description}} + * + * Pass this function an array similar to that of a $_FILES POST array. + * + * @since unknown + * + * @param unknown_type $file + * @param unknown_type $overrides + * @return unknown + */ +function wp_handle_sideload( &$file, $overrides = false ) { + // The default error handler. + if (! function_exists( 'wp_handle_upload_error' ) ) { + function wp_handle_upload_error( &$file, $message ) { + return array( 'error'=>$message ); + } + } + + // You may define your own function and pass the name in $overrides['upload_error_handler'] + $upload_error_handler = 'wp_handle_upload_error'; + + // You may define your own function and pass the name in $overrides['unique_filename_callback'] + $unique_filename_callback = null; + + // $_POST['action'] must be set and its value must equal $overrides['action'] or this: + $action = 'wp_handle_sideload'; + + // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error']. + $upload_error_strings = array( false, + __( "The uploaded file exceeds the upload_max_filesize directive in php.ini." ), + __( "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." ), + __( "The uploaded file was only partially uploaded." ), + __( "No file was uploaded." ), + '', + __( "Missing a temporary folder." ), + __( "Failed to write file to disk." ), + __( "File upload stopped by extension." )); + + // All tests are on by default. Most can be turned off by $override[{test_name}] = false; + $test_form = true; + $test_size = true; + + // If you override this, you must provide $ext and $type!!!! + $test_type = true; + $mimes = false; + + // Install user overrides. Did we mention that this voids your warranty? + if ( is_array( $overrides ) ) + extract( $overrides, EXTR_OVERWRITE ); + + // A correct form post will pass this test. + if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) ) + return $upload_error_handler( $file, __( 'Invalid form submission.' )); + + // A successful upload will pass this test. It makes no sense to override this one. + if ( $file['error'] > 0 ) + return $upload_error_handler( $file, $upload_error_strings[$file['error']] ); + + // A non-empty file will pass this test. + if ( $test_size && !(filesize($file['tmp_name']) > 0 ) ) + return $upload_error_handler( $file, __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.' )); + + // A properly uploaded file will pass this test. There should be no reason to override this one. + if (! @ is_file( $file['tmp_name'] ) ) + return $upload_error_handler( $file, __( 'Specified file does not exist.' )); + + // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter. + if ( $test_type ) { + $wp_filetype = wp_check_filetype( $file['name'], $mimes ); + + extract( $wp_filetype ); + + if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) + return $upload_error_handler( $file, __( 'File type does not meet security guidelines. Try another.' )); + + if ( !$ext ) + $ext = ltrim(strrchr($file['name'], '.'), '.'); + + if ( !$type ) + $type = $file['type']; + } + + // A writable uploads dir will pass this test. Again, there's no point overriding this one. + if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) ) + return $upload_error_handler( $file, $uploads['error'] ); + + $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback ); + + // Strip the query strings. + $filename = str_replace('?','-', $filename); + $filename = str_replace('&','-', $filename); + + // Move the file to the uploads dir + $new_file = $uploads['path'] . "/$filename"; + if ( false === @ rename( $file['tmp_name'], $new_file ) ) { + return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) ); + } + + // Set correct file permissions + $stat = stat( dirname( $new_file )); + $perms = $stat['mode'] & 0000666; + @ chmod( $new_file, $perms ); + + // Compute the URL + $url = $uploads['url'] . "/$filename"; + + $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) ); + + return $return; +} + +/** + * Downloads a url to a local file using the Snoopy HTTP Class. + * + * @since unknown + * @todo Transition over to using the new HTTP Request API (jacob). + * + * @param string $url the URL of the file to download + * @return mixed WP_Error on failure, string Filename on success. + */ +function download_url( $url ) { + //WARNING: The file is not automatically deleted, The script must unlink() the file. + if ( ! $url ) + return new WP_Error('http_no_url', __('Invalid URL Provided')); + + $tmpfname = wp_tempnam($url); + if ( ! $tmpfname ) + return new WP_Error('http_no_file', __('Could not create Temporary file')); + + $handle = @fopen($tmpfname, 'wb'); + if ( ! $handle ) + return new WP_Error('http_no_file', __('Could not create Temporary file')); + + $response = wp_remote_get($url, array('timeout' => 60)); + + if ( is_wp_error($response) ) { + fclose($handle); + unlink($tmpfname); + return $response; + } + + if ( $response['response']['code'] != '200' ){ + fclose($handle); + unlink($tmpfname); + return new WP_Error('http_404', trim($response['response']['message'])); + } + + fwrite($handle, $response['body']); + fclose($handle); + + return $tmpfname; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file + * @param unknown_type $to + * @return unknown + */ +function unzip_file($file, $to) { + global $wp_filesystem; + + if ( ! $wp_filesystem || !is_object($wp_filesystem) ) + return new WP_Error('fs_unavailable', __('Could not access filesystem.')); + + // Unzip uses a lot of memory + @ini_set('memory_limit', '256M'); + + $fs =& $wp_filesystem; + + require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php'); + + $archive = new PclZip($file); + + // Is the archive valid? + if ( false == ($archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING)) ) + return new WP_Error('incompatible_archive', __('Incompatible archive'), $archive->errorInfo(true)); + + if ( 0 == count($archive_files) ) + return new WP_Error('empty_archive', __('Empty archive')); + + $path = explode('/', untrailingslashit($to)); + for ( $i = count($path); $i > 0; $i-- ) { //>0 = first element is empty allways for paths starting with '/' + $tmppath = implode('/', array_slice($path, 0, $i) ); + if ( $fs->is_dir($tmppath) ) { //Found the highest folder that exists, Create from here(ie +1) + for ( $i = $i + 1; $i <= count($path); $i++ ) { + $tmppath = implode('/', array_slice($path, 0, $i) ); + if ( ! $fs->mkdir($tmppath, FS_CHMOD_DIR) ) + return new WP_Error('mkdir_failed', __('Could not create directory'), $tmppath); + } + break; //Exit main for loop + } + } + + $to = trailingslashit($to); + foreach ($archive_files as $file) { + $path = $file['folder'] ? $file['filename'] : dirname($file['filename']); + $path = explode('/', $path); + for ( $i = count($path); $i >= 0; $i-- ) { //>=0 as the first element contains data + if ( empty($path[$i]) ) + continue; + $tmppath = $to . implode('/', array_slice($path, 0, $i) ); + if ( $fs->is_dir($tmppath) ) {//Found the highest folder that exists, Create from here + for ( $i = $i + 1; $i <= count($path); $i++ ) { //< count() no file component please. + $tmppath = $to . implode('/', array_slice($path, 0, $i) ); + if ( ! $fs->is_dir($tmppath) && ! $fs->mkdir($tmppath, FS_CHMOD_DIR) ) + return new WP_Error('mkdir_failed', __('Could not create directory'), $tmppath); + } + break; //Exit main for loop + } + } + + // We've made sure the folders are there, so let's extract the file now: + if ( ! $file['folder'] ) { + if ( !$fs->put_contents( $to . $file['filename'], $file['content']) ) + return new WP_Error('copy_failed', __('Could not copy file'), $to . $file['filename']); + $fs->chmod($to . $file['filename'], FS_CHMOD_FILE); + } + } + return true; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $from + * @param unknown_type $to + * @return unknown + */ +function copy_dir($from, $to) { + global $wp_filesystem; + + $dirlist = $wp_filesystem->dirlist($from); + + $from = trailingslashit($from); + $to = trailingslashit($to); + + foreach ( (array) $dirlist as $filename => $fileinfo ) { + if ( 'f' == $fileinfo['type'] ) { + if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true) ) { + // If copy failed, chmod file to 0644 and try again. + $wp_filesystem->chmod($to . $filename, 0644); + if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true) ) + return new WP_Error('copy_failed', __('Could not copy file'), $to . $filename); + } + $wp_filesystem->chmod($to . $filename, FS_CHMOD_FILE); + } elseif ( 'd' == $fileinfo['type'] ) { + if ( !$wp_filesystem->is_dir($to . $filename) ) { + if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) ) + return new WP_Error('mkdir_failed', __('Could not create directory'), $to . $filename); + } + $result = copy_dir($from . $filename, $to . $filename); + if ( is_wp_error($result) ) + return $result; + } + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $args + * @return unknown + */ +function WP_Filesystem( $args = false, $context = false ) { + global $wp_filesystem; + + require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'); + + $method = get_filesystem_method($args, $context); + + if ( ! $method ) + return false; + + if ( ! class_exists("WP_Filesystem_$method") ) { + $abstraction_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method); + if( ! file_exists($abstraction_file) ) + return; + + require_once($abstraction_file); + } + $method = "WP_Filesystem_$method"; + + $wp_filesystem = new $method($args); + + if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) + return false; + + if ( !$wp_filesystem->connect() ) + return false; //There was an erorr connecting to the server. + + // Set the permission constants if not already set. + if ( ! defined('FS_CHMOD_DIR') ) + define('FS_CHMOD_DIR', 0755 ); + if ( ! defined('FS_CHMOD_FILE') ) + define('FS_CHMOD_FILE', 0644 ); + + return true; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $args + * @param string $context Full path to the directory that is tested for being writable. + * @return unknown + */ +function get_filesystem_method($args = array(), $context = false) { + $method = defined('FS_METHOD') ? FS_METHOD : false; //Please ensure that this is either 'direct', 'ssh', 'ftpext' or 'ftpsockets' + + if( ! $method && function_exists('getmyuid') && function_exists('fileowner') ){ + if ( !$context ) + $context = WP_CONTENT_DIR; + $context = trailingslashit($context); + $temp_file_name = $context . '.write-test-' . time(); + $temp_handle = @fopen($temp_file_name, 'w'); + if ( $temp_handle ) { + if ( getmyuid() == fileowner($temp_file_name) ) + $method = 'direct'; + @fclose($temp_handle); + unlink($temp_file_name); + } + } + + if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') && function_exists('stream_get_contents') ) $method = 'ssh2'; + if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext'; + if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread + return apply_filters('filesystem_method', $method, $args); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $form_post + * @param unknown_type $type + * @param unknown_type $error + * @return unknown + */ +function request_filesystem_credentials($form_post, $type = '', $error = false, $context = false) { + $req_cred = apply_filters('request_filesystem_credentials', '', $form_post, $type, $error, $context); + if ( '' !== $req_cred ) + return $req_cred; + + if ( empty($type) ) + $type = get_filesystem_method(array(), $context); + + if ( 'direct' == $type ) + return true; + + $credentials = get_option('ftp_credentials', array( 'hostname' => '', 'username' => '')); + + // If defined, set it to that, Else, If POST'd, set it to that, If not, Set it to whatever it previously was(saved details in option) + $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? $_POST['hostname'] : $credentials['hostname']); + $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? $_POST['username'] : $credentials['username']); + $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? $_POST['password'] : ''); + + // Check to see if we are setting the public/private keys for ssh + $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? $_POST['public_key'] : ''); + $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? $_POST['private_key'] : ''); + + //sanitize the hostname, Some people might pass in odd-data: + $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off + + if ( strpos($credentials['hostname'], ':') ) + list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2); + else + unset($credentials['port']); + + if ( defined('FTP_SSH') || (defined('FS_METHOD') && 'ssh' == FS_METHOD) ) + $credentials['connection_type'] = 'ssh'; + else if ( defined('FTP_SSL') && 'ftpext' == $type ) //Only the FTP Extension understands SSL + $credentials['connection_type'] = 'ftps'; + else if ( !empty($_POST['connection_type']) ) + $credentials['connection_type'] = $_POST['connection_type']; + else if ( !isset($credentials['connection_type']) ) //All else fails (And its not defaulted to something else saved), Default to FTP + $credentials['connection_type'] = 'ftp'; + + if ( ! $error && + ( + ( !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) || + ( 'ssh' == $credentials['connection_type'] && !empty($credentials['public_key']) && !empty($credentials['private_key']) ) + ) ) { + $stored_credentials = $credentials; + if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code. + $stored_credentials['hostname'] .= ':' . $stored_credentials['port']; + + unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']); + update_option('ftp_credentials', $stored_credentials); + return $credentials; + } + $hostname = ''; + $username = ''; + $password = ''; + $connection_type = ''; + if ( !empty($credentials) ) + extract($credentials, EXTR_OVERWRITE); + if ( $error ) { + $error_string = __('Error: There was an error connecting to the server, Please verify the settings are correct.'); + if ( is_wp_error($error) ) + $error_string = $error->get_error_message(); + echo '

    ' . $error_string . '

    '; + } +?> + +
    +
    + +

    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    " size="40" />
    size="40" />
    size="40" />
    +
    +
    + +

    size="40" />
    size="40" /> +
    +
    + + +
    + + +
    + +
    +
    + + + + + + + +

    + +

    +
    +
    + diff --git a/wp-admin/includes/image.php b/wp-admin/includes/image.php new file mode 100644 index 0000000..c0632ac --- /dev/null +++ b/wp-admin/includes/image.php @@ -0,0 +1,330 @@ + 0, + 'credit' => '', + 'camera' => '', + 'caption' => '', + 'created_timestamp' => 0, + 'copyright' => '', + 'focal_length' => 0, + 'iso' => 0, + 'shutter_speed' => 0, + 'title' => '', + ); + + // read iptc first, since it might contain data not available in exif such + // as caption, description etc + if ( is_callable('iptcparse') ) { + getimagesize($file, $info); + if ( !empty($info['APP13']) ) { + $iptc = iptcparse($info['APP13']); + if ( !empty($iptc['2#110'][0]) ) // credit + $meta['credit'] = utf8_encode(trim($iptc['2#110'][0])); + elseif ( !empty($iptc['2#080'][0]) ) // byline + $meta['credit'] = utf8_encode(trim($iptc['2#080'][0])); + if ( !empty($iptc['2#055'][0]) and !empty($iptc['2#060'][0]) ) // created date and time + $meta['created_timestamp'] = strtotime($iptc['2#055'][0] . ' ' . $iptc['2#060'][0]); + if ( !empty($iptc['2#120'][0]) ) // caption + $meta['caption'] = utf8_encode(trim($iptc['2#120'][0])); + if ( !empty($iptc['2#116'][0]) ) // copyright + $meta['copyright'] = utf8_encode(trim($iptc['2#116'][0])); + if ( !empty($iptc['2#005'][0]) ) // title + $meta['title'] = utf8_encode(trim($iptc['2#005'][0])); + } + } + + // fetch additional info from exif if available + if ( is_callable('exif_read_data') && in_array($sourceImageType, apply_filters('wp_read_image_metadata_types', array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM)) ) ) { + $exif = @exif_read_data( $file ); + if (!empty($exif['FNumber'])) + $meta['aperture'] = round( wp_exif_frac2dec( $exif['FNumber'] ), 2 ); + if (!empty($exif['Model'])) + $meta['camera'] = trim( $exif['Model'] ); + if (!empty($exif['DateTimeDigitized'])) + $meta['created_timestamp'] = wp_exif_date2ts($exif['DateTimeDigitized']); + if (!empty($exif['FocalLength'])) + $meta['focal_length'] = wp_exif_frac2dec( $exif['FocalLength'] ); + if (!empty($exif['ISOSpeedRatings'])) + $meta['iso'] = $exif['ISOSpeedRatings']; + if (!empty($exif['ExposureTime'])) + $meta['shutter_speed'] = wp_exif_frac2dec( $exif['ExposureTime'] ); + } + + return apply_filters( 'wp_read_image_metadata', $meta, $file, $sourceImageType ); + +} + +/** + * Validate that file is an image. + * + * @since 2.5.0 + * + * @param string $path File path to test if valid image. + * @return bool True if valid image, false if not valid image. + */ +function file_is_valid_image($path) { + $size = @getimagesize($path); + return !empty($size); +} + +/** + * Validate that file is suitable for displaying within a web page. + * + * @since 2.5.0 + * @uses apply_filters() Calls 'file_is_displayable_image' on $result and $path. + * + * @param string $path File path to test. + * @return bool True if suitable, false if not suitable. + */ +function file_is_displayable_image($path) { + $info = @getimagesize($path); + if ( empty($info) ) + $result = false; + elseif ( !in_array($info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG)) ) // only gif, jpeg and png images can reliably be displayed + $result = false; + else + $result = true; + + return apply_filters('file_is_displayable_image', $result, $path); +} + +?> diff --git a/wp-admin/includes/import.php b/wp-admin/includes/import.php new file mode 100644 index 0000000..820ee54 --- /dev/null +++ b/wp-admin/includes/import.php @@ -0,0 +1,87 @@ + false, 'test_type' => false ); + $_FILES['import']['name'] .= '.txt'; + $file = wp_handle_upload( $_FILES['import'], $overrides ); + + if ( isset( $file['error'] ) ) + return $file; + + $url = $file['url']; + $type = $file['type']; + $file = addslashes( $file['file'] ); + $filename = basename( $file ); + + // Construct the object array + $object = array( 'post_title' => $filename, + 'post_content' => $url, + 'post_mime_type' => $type, + 'guid' => $url + ); + + // Save the data + $id = wp_insert_attachment( $object, $file ); + + return array( 'file' => $file, 'id' => $id ); +} + +?> diff --git a/wp-admin/includes/manifest.php b/wp-admin/includes/manifest.php new file mode 100644 index 0000000..6b763df --- /dev/null +++ b/wp-admin/includes/manifest.php @@ -0,0 +1,208 @@ + __('From Computer'), // handler action suffix => tab text + 'type_url' => __('From URL'), + 'gallery' => __('Gallery'), + 'library' => __('Media Library') + ); + + return apply_filters('media_upload_tabs', $_default_tabs); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $tabs + * @return unknown + */ +function update_gallery_tab($tabs) { + global $wpdb; + + if ( !isset($_REQUEST['post_id']) ) { + unset($tabs['gallery']); + return $tabs; + } + + if ( intval($_REQUEST['post_id']) ) + $attachments = intval($wpdb->get_var($wpdb->prepare("SELECT count(*) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $_REQUEST['post_id']))); + + if ( empty($attachments) ) { + unset($tabs['gallery']); + return $tabs; + } + + $tabs['gallery'] = sprintf(__('Gallery (%s)'), "$attachments"); + + return $tabs; +} +add_filter('media_upload_tabs', 'update_gallery_tab'); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function the_media_upload_tabs() { + global $redir_tab; + $tabs = media_upload_tabs(); + + if ( !empty($tabs) ) { + echo "
      \n"; + if ( isset($redir_tab) && array_key_exists($redir_tab, $tabs) ) + $current = $redir_tab; + elseif ( isset($_GET['tab']) && array_key_exists($_GET['tab'], $tabs) ) + $current = $_GET['tab']; + else + $current = apply_filters('media_upload_default_tab', 'type'); + + foreach ( $tabs as $callback => $text ) { + $class = ''; + if ( $current == $callback ) + $class = " class='current'"; + $href = add_query_arg(array('tab'=>$callback, 's'=>false, 'paged'=>false, 'post_mime_type'=>false, 'm'=>false)); + $link = "$text"; + echo "\t
    • $link
    • \n"; + } + echo "
    \n"; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $id + * @param unknown_type $alt + * @param unknown_type $title + * @param unknown_type $align + * @param unknown_type $url + * @param unknown_type $rel + * @param unknown_type $size + * @return unknown + */ +function get_image_send_to_editor($id, $alt, $title, $align, $url='', $rel = false, $size='medium') { + + $htmlalt = ( empty($alt) ) ? $title : $alt; + + $html = get_image_tag($id, $htmlalt, $title, $align, $size); + + $rel = $rel ? ' rel="attachment wp-att-' . esc_attr($id).'"' : ''; + + if ( $url ) + $html = '$html"; + + $html = apply_filters( 'image_send_to_editor', $html, $id, $alt, $title, $align, $url, $size ); + + return $html; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $html + * @param unknown_type $id + * @param unknown_type $alt + * @param unknown_type $title + * @param unknown_type $align + * @param unknown_type $url + * @param unknown_type $size + * @return unknown + */ +function image_add_caption( $html, $id, $alt, $title, $align, $url, $size ) { + + if ( empty($alt) || apply_filters( 'disable_captions', '' ) ) + return $html; + + $id = ( 0 < (int) $id ) ? 'attachment_' . $id : ''; + + preg_match( '/width="([0-9]+)/', $html, $matches ); + if ( ! isset($matches[1]) ) + return $html; + + $width = $matches[1]; + + $html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html ); + if ( empty($align) ) + $align = 'none'; + + $alt = ! empty($alt) ? addslashes($alt) : ''; + + $shcode = '[caption id="' . $id . '" align="align' . $align + . '" width="' . $width . '" caption="' . $alt . '"]' . $html . '[/caption]'; + + return apply_filters( 'image_add_caption_shortcode', $shcode, $html ); +} +add_filter( 'image_send_to_editor', 'image_add_caption', 20, 7 ); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $html + */ +function media_send_to_editor($html) { +?> + + false); + + $time = current_time('mysql'); + if ( $post = get_post($post_id) ) { + if ( substr( $post->post_date, 0, 4 ) > 0 ) + $time = $post->post_date; + } + + $name = $_FILES[$file_id]['name']; + $file = wp_handle_upload($_FILES[$file_id], $overrides, $time); + + if ( isset($file['error']) ) + return new WP_Error( 'upload_error', $file['error'] ); + + $name_parts = pathinfo($name); + $name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) ); + + $url = $file['url']; + $type = $file['type']; + $file = $file['file']; + $title = $name; + $content = ''; + + // use image exif/iptc data for title and caption defaults if possible + if ( $image_meta = @wp_read_image_metadata($file) ) { + if ( trim($image_meta['title']) ) + $title = $image_meta['title']; + if ( trim($image_meta['caption']) ) + $content = $image_meta['caption']; + } + + // Construct the attachment array + $attachment = array_merge( array( + 'post_mime_type' => $type, + 'guid' => $url, + 'post_parent' => $post_id, + 'post_title' => $title, + 'post_content' => $content, + ), $post_data ); + + // Save the data + $id = wp_insert_attachment($attachment, $file, $post_id); + if ( !is_wp_error($id) ) { + wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); + } + + return $id; + +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file_array + * @param unknown_type $post_id + * @param unknown_type $desc + * @param unknown_type $post_data + * @return unknown + */ +function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) { + $overrides = array('test_form'=>false); + $file = wp_handle_sideload($file_array, $overrides); + + if ( isset($file['error']) ) + return new WP_Error( 'upload_error', $file['error'] ); + + $url = $file['url']; + $type = $file['type']; + $file = $file['file']; + $title = preg_replace('/\.[^.]+$/', '', basename($file)); + $content = ''; + + // use image exif/iptc data for title and caption defaults if possible + if ( $image_meta = @wp_read_image_metadata($file) ) { + if ( trim($image_meta['title']) ) + $title = $image_meta['title']; + if ( trim($image_meta['caption']) ) + $content = $image_meta['caption']; + } + + $title = @$desc; + + // Construct the attachment array + $attachment = array_merge( array( + 'post_mime_type' => $type, + 'guid' => $url, + 'post_parent' => $post_id, + 'post_title' => $title, + 'post_content' => $content, + ), $post_data ); + + // Save the data + $id = wp_insert_attachment($attachment, $file, $post_id); + if ( !is_wp_error($id) ) { + wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); + return $url; + } + return $id; +} + +/** + * {@internal Missing Short Description}} + * + * Wrap iframe content (produced by $content_func) in a doctype, html head/body + * etc any additional function args will be passed to content_func. + * + * @since unknown + * + * @param unknown_type $content_func + */ +function wp_iframe($content_func /* ... */) { +?> + + > + + +<?php bloginfo('name') ?> › <?php _e('Uploads'); ?> — <?php _e('WordPress'); ?> + + + + +> + + + + +$image_title + $video_title + $audio_title + $media_title + +EOF; + printf($context, $out); +} +add_action( 'media_buttons', 'media_buttons' ); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_form_handler() { + check_admin_referer('media-form'); + + $errors = null; + + if ( isset($_POST['send']) ) { + $keys = array_keys($_POST['send']); + $send_id = (int) array_shift($keys); + } + + if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) { + $post = $_post = get_post($attachment_id, ARRAY_A); + if ( isset($attachment['post_content']) ) + $post['post_content'] = $attachment['post_content']; + if ( isset($attachment['post_title']) ) + $post['post_title'] = $attachment['post_title']; + if ( isset($attachment['post_excerpt']) ) + $post['post_excerpt'] = $attachment['post_excerpt']; + if ( isset($attachment['menu_order']) ) + $post['menu_order'] = $attachment['menu_order']; + + if ( isset($send_id) && $attachment_id == $send_id ) { + if ( isset($attachment['post_parent']) ) + $post['post_parent'] = $attachment['post_parent']; + } + + $post = apply_filters('attachment_fields_to_save', $post, $attachment); + + if ( isset($post['errors']) ) { + $errors[$attachment_id] = $post['errors']; + unset($post['errors']); + } + + if ( $post != $_post ) + wp_update_post($post); + + foreach ( get_attachment_taxonomies($post) as $t ) + if ( isset($attachment[$t]) ) + wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false); + } + + if ( isset($_POST['insert-gallery']) || isset($_POST['update-gallery']) ) { ?> + + $html"; + } + + $html = apply_filters('media_send_to_editor', $html, $send_id, $attachment); + return media_send_to_editor($html); + } + + return $errors; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_image() { + $errors = array(); + $id = 0; + + if ( isset($_POST['html-upload']) && !empty($_FILES) ) { + // Upload File button was clicked + $id = media_handle_upload('async-upload', $_REQUEST['post_id']); + unset($_FILES); + if ( is_wp_error($id) ) { + $errors['upload_error'] = $id; + $id = false; + } + } + + if ( !empty($_POST['insertonlybutton']) ) { + $src = $_POST['insertonly']['src']; + if ( !empty($src) && !strpos($src, '://') ) + $src = "http://$src"; + $alt = esc_attr($_POST['insertonly']['alt']); + if ( isset($_POST['insertonly']['align']) ) { + $align = esc_attr($_POST['insertonly']['align']); + $class = " class='align$align'"; + } + if ( !empty($src) ) + $html = "$alt"; + $html = apply_filters('image_send_to_editor_url', $html, $src, $alt, $align); + return media_send_to_editor($html); + } + + if ( !empty($_POST) ) { + $return = media_upload_form_handler(); + + if ( is_string($return) ) + return $return; + if ( is_array($return) ) + $errors = $return; + } + + if ( isset($_POST['save']) ) { + $errors['upload_notice'] = __('Saved.'); + return media_upload_gallery(); + } + + if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) + return wp_iframe( 'media_upload_type_url_form', 'image', $errors, $id ); + + return wp_iframe( 'media_upload_type_form', 'image', $errors, $id ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file + * @param unknown_type $post_id + * @param unknown_type $desc + * @return unknown + */ +function media_sideload_image($file, $post_id, $desc = null) { + if (!empty($file) ) { + $file_array['name'] = basename($file); + $tmp = download_url($file); + $file_array['tmp_name'] = $tmp; + $desc = @$desc; + + if ( is_wp_error($tmp) ) { + @unlink($file_array['tmp_name']); + $file_array['tmp_name'] = ''; + } + + $id = media_handle_sideload($file_array, $post_id, $desc); + $src = $id; + + if ( is_wp_error($id) ) { + @unlink($file_array['tmp_name']); + return $id; + } + } + + if ( !empty($src) ) { + $alt = @$desc; + $html = "$alt"; + return $html; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_audio() { + $errors = array(); + $id = 0; + + if ( isset($_POST['html-upload']) && !empty($_FILES) ) { + // Upload File button was clicked + $id = media_handle_upload('async-upload', $_REQUEST['post_id']); + unset($_FILES); + if ( is_wp_error($id) ) { + $errors['upload_error'] = $id; + $id = false; + } + } + + if ( !empty($_POST['insertonlybutton']) ) { + $href = $_POST['insertonly']['href']; + if ( !empty($href) && !strpos($href, '://') ) + $href = "http://$href"; + $title = esc_attr($_POST['insertonly']['title']); + if ( empty($title) ) + $title = basename($href); + if ( !empty($title) && !empty($href) ) + $html = "$title"; + $html = apply_filters('audio_send_to_editor_url', $html, $href, $title); + return media_send_to_editor($html); + } + + if ( !empty($_POST) ) { + $return = media_upload_form_handler(); + + if ( is_string($return) ) + return $return; + if ( is_array($return) ) + $errors = $return; + } + + if ( isset($_POST['save']) ) { + $errors['upload_notice'] = __('Saved.'); + return media_upload_gallery(); + } + + if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) + return wp_iframe( 'media_upload_type_url_form', 'audio', $errors, $id ); + + return wp_iframe( 'media_upload_type_form', 'audio', $errors, $id ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_video() { + $errors = array(); + $id = 0; + + if ( isset($_POST['html-upload']) && !empty($_FILES) ) { + // Upload File button was clicked + $id = media_handle_upload('async-upload', $_REQUEST['post_id']); + unset($_FILES); + if ( is_wp_error($id) ) { + $errors['upload_error'] = $id; + $id = false; + } + } + + if ( !empty($_POST['insertonlybutton']) ) { + $href = $_POST['insertonly']['href']; + if ( !empty($href) && !strpos($href, '://') ) + $href = "http://$href"; + $title = esc_attr($_POST['insertonly']['title']); + if ( empty($title) ) + $title = basename($href); + if ( !empty($title) && !empty($href) ) + $html = "$title"; + $html = apply_filters('video_send_to_editor_url', $html, $href, $title); + return media_send_to_editor($html); + } + + if ( !empty($_POST) ) { + $return = media_upload_form_handler(); + + if ( is_string($return) ) + return $return; + if ( is_array($return) ) + $errors = $return; + } + + if ( isset($_POST['save']) ) { + $errors['upload_notice'] = __('Saved.'); + return media_upload_gallery(); + } + + if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) + return wp_iframe( 'media_upload_type_url_form', 'video', $errors, $id ); + + return wp_iframe( 'media_upload_type_form', 'video', $errors, $id ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_file() { + $errors = array(); + $id = 0; + + if ( isset($_POST['html-upload']) && !empty($_FILES) ) { + // Upload File button was clicked + $id = media_handle_upload('async-upload', $_REQUEST['post_id']); + unset($_FILES); + if ( is_wp_error($id) ) { + $errors['upload_error'] = $id; + $id = false; + } + } + + if ( !empty($_POST['insertonlybutton']) ) { + $href = $_POST['insertonly']['href']; + if ( !empty($href) && !strpos($href, '://') ) + $href = "http://$href"; + $title = esc_attr($_POST['insertonly']['title']); + if ( empty($title) ) + $title = basename($href); + if ( !empty($title) && !empty($href) ) + $html = "$title"; + $html = apply_filters('file_send_to_editor_url', $html, $href, $title); + return media_send_to_editor($html); + } + + if ( !empty($_POST) ) { + $return = media_upload_form_handler(); + + if ( is_string($return) ) + return $return; + if ( is_array($return) ) + $errors = $return; + } + + if ( isset($_POST['save']) ) { + $errors['upload_notice'] = __('Saved.'); + return media_upload_gallery(); + } + + if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' ) + return wp_iframe( 'media_upload_type_url_form', 'file', $errors, $id ); + + return wp_iframe( 'media_upload_type_form', 'file', $errors, $id ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_gallery() { + $errors = array(); + + if ( !empty($_POST) ) { + $return = media_upload_form_handler(); + + if ( is_string($return) ) + return $return; + if ( is_array($return) ) + $errors = $return; + } + + wp_enqueue_script('admin-gallery'); + return wp_iframe( 'media_upload_gallery_form', $errors ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function media_upload_library() { + $errors = array(); + if ( !empty($_POST) ) { + $return = media_upload_form_handler(); + + if ( is_string($return) ) + return $return; + if ( is_array($return) ) + $errors = $return; + } + + return wp_iframe( 'media_upload_library_form', $errors ); +} + +/** + * Retrieve HTML for the image alignment radio buttons with the specified one checked. + * + * @since unknown + * + * @param unknown_type $post + * @param unknown_type $checked + * @return unknown + */ +function image_align_input_fields( $post, $checked = '' ) { + + $alignments = array('none' => __('None'), 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right')); + if ( !array_key_exists( (string) $checked, $alignments ) ) + $checked = 'none'; + + $out = array(); + foreach ($alignments as $name => $label) { + $name = esc_attr($name); + $out[] = ""; + } + return join("\n", $out); +} + +/** + * Retrieve HTML for the size radio buttons with the specified one checked. + * + * @since unknown + * + * @param unknown_type $post + * @param unknown_type $checked + * @return unknown + */ +function image_size_input_fields( $post, $checked = '' ) { + + // get a list of the actual pixel dimensions of each possible intermediate version of this image + $size_names = array('thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full size')); + + foreach ( $size_names as $size => $name ) { + $downsize = image_downsize($post->ID, $size); + + // is this size selectable? + $enabled = ( $downsize[3] || 'full' == $size ); + $css_id = "image-size-{$size}-{$post->ID}"; + // if this size is the default but that's not available, don't select it + if ( $checked && !$enabled ) + $checked = ''; + // if $checked was not specified, default to the first available size that's bigger than a thumbnail + if ( !$checked && $enabled && 'thumbnail' != $size ) + $checked = $size; + + $html = "
    "; + + $html .= ""; + // only show the dimensions if that choice is available + if ( $enabled ) + $html .= " "; + + $html .= '
    '; + + $out[] = $html; + } + + return array( + 'label' => __('Size'), + 'input' => 'html', + 'html' => join("\n", $out), + ); +} + +/** + * Retrieve HTML for the Link URL buttons with the default link type as specified. + * + * @since unknown + * + * @param unknown_type $post + * @param unknown_type $url_type + * @return unknown + */ +function image_link_input_fields($post, $url_type='') { + + $file = wp_get_attachment_url($post->ID); + $link = get_attachment_link($post->ID); + + $url = ''; + if ( $url_type == 'file' ) + $url = $file; + elseif ( $url_type == 'post' ) + $url = $link; + + return "
    + + + +"; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $form_fields + * @param unknown_type $post + * @return unknown + */ +function image_attachment_fields_to_edit($form_fields, $post) { + if ( substr($post->post_mime_type, 0, 5) == 'image' ) { + $form_fields['post_title']['required'] = true; + $file = wp_get_attachment_url($post->ID); + + $form_fields['image_url']['value'] = $file; + + $form_fields['post_excerpt']['label'] = __('Caption'); + $form_fields['post_excerpt']['helps'][] = __('Also used as alternate text for the image'); + + $form_fields['post_content']['label'] = __('Description'); + + $form_fields['align'] = array( + 'label' => __('Alignment'), + 'input' => 'html', + 'html' => image_align_input_fields($post, get_option('image_default_align')), + ); + + $form_fields['image-size'] = image_size_input_fields($post, get_option('image_default_size')); + } + return $form_fields; +} + +add_filter('attachment_fields_to_edit', 'image_attachment_fields_to_edit', 10, 2); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $form_fields + * @param unknown_type $post + * @return unknown + */ +function media_single_attachment_fields_to_edit( $form_fields, $post ) { + unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']); + return $form_fields; +} + +function media_post_single_attachment_fields_to_edit( $form_fields, $post ) { + unset($form_fields['image_url']); + return $form_fields; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post + * @param unknown_type $attachment + * @return unknown + */ +function image_attachment_fields_to_save($post, $attachment) { + if ( substr($post['post_mime_type'], 0, 5) == 'image' ) { + if ( strlen(trim($post['post_title'])) == 0 ) { + $post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid'])); + $post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.'); + } + } + + return $post; +} + +add_filter('attachment_fields_to_save', 'image_attachment_fields_to_save', 10, 2); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $html + * @param unknown_type $attachment_id + * @param unknown_type $attachment + * @return unknown + */ +function image_media_send_to_editor($html, $attachment_id, $attachment) { + $post =& get_post($attachment_id); + if ( substr($post->post_mime_type, 0, 5) == 'image' ) { + $url = $attachment['url']; + + if ( isset($attachment['align']) ) + $align = $attachment['align']; + else + $align = 'none'; + + if ( !empty($attachment['image-size']) ) + $size = $attachment['image-size']; + else + $size = 'medium'; + + $rel = ( $url == get_attachment_link($attachment_id) ); + + return get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size); + } + + return $html; +} + +add_filter('media_send_to_editor', 'image_media_send_to_editor', 10, 3); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post + * @param unknown_type $errors + * @return unknown + */ +function get_attachment_fields_to_edit($post, $errors = null) { + if ( is_int($post) ) + $post =& get_post($post); + if ( is_array($post) ) + $post = (object) $post; + + $image_url = wp_get_attachment_url($post->ID); + + $edit_post = sanitize_post($post, 'edit'); + + $form_fields = array( + 'post_title' => array( + 'label' => __('Title'), + 'value' => $edit_post->post_title, + ), + 'post_excerpt' => array( + 'label' => __('Caption'), + 'value' => $edit_post->post_excerpt, + ), + 'post_content' => array( + 'label' => __('Description'), + 'value' => $edit_post->post_content, + 'input' => 'textarea', + ), + 'url' => array( + 'label' => __('Link URL'), + 'input' => 'html', + 'html' => image_link_input_fields($post, get_option('image_default_link_type')), + 'helps' => __('Enter a link URL or click above for presets.'), + ), + 'menu_order' => array( + 'label' => __('Order'), + 'value' => $edit_post->menu_order + ), + 'image_url' => array( + 'label' => __('File URL'), + 'input' => 'html', + 'html' => "
    ", + 'value' => isset($edit_post->post_url) ? $edit_post->post_url : '', + 'helps' => __('Location of the uploaded file.'), + ) + ); + + foreach ( get_attachment_taxonomies($post) as $taxonomy ) { + $t = (array) get_taxonomy($taxonomy); + if ( empty($t['label']) ) + $t['label'] = $taxonomy; + if ( empty($t['args']) ) + $t['args'] = array(); + + $terms = get_object_term_cache($post->ID, $taxonomy); + if ( empty($terms) ) + $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']); + + $values = array(); + + foreach ( $terms as $term ) + $values[] = $term->name; + $t['value'] = join(', ', $values); + + $form_fields[$taxonomy] = $t; + } + + // Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default + // The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing ) + $form_fields = array_merge_recursive($form_fields, (array) $errors); + + $form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post); + + return $form_fields; +} + +/** + * Retrieve HTML for media items of post gallery. + * + * The HTML markup retrieved will be created for the progress of SWF Upload + * component. Will also create link for showing and hiding the form to modify + * the image attachment. + * + * @since unknown + * + * @param int $post_id Optional. Post ID. + * @param array $errors Errors for attachment, if any. + * @return string + */ +function get_media_items( $post_id, $errors ) { + if ( $post_id ) { + $post = get_post($post_id); + if ( $post && $post->post_type == 'attachment' ) + $attachments = array($post->ID => $post); + else + $attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') ); + } else { + if ( is_array($GLOBALS['wp_the_query']->posts) ) + foreach ( $GLOBALS['wp_the_query']->posts as $attachment ) + $attachments[$attachment->ID] = $attachment; + } + + $output = ''; + foreach ( (array) $attachments as $id => $attachment ) + if ( $item = get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) ) + $output .= "\n
    $item\n
    "; + + return $output; +} + +/** + * Retrieve HTML form for modifying the image attachment. + * + * @since unknown + * + * @param int $attachment_id Attachment ID for modification. + * @param string|array $args Optional. Override defaults. + * @return string HTML form for attachment. + */ +function get_media_item( $attachment_id, $args = null ) { + global $redir_tab; + + $default_args = array( 'errors' => null, 'send' => true, 'delete' => true, 'toggle' => true, 'show_title' => true ); + $args = wp_parse_args( $args, $default_args ); + extract( $args, EXTR_SKIP ); + + global $post_mime_types; + if ( ( $attachment_id = intval($attachment_id) ) && $thumb_url = get_attachment_icon_src( $attachment_id ) ) + $thumb_url = $thumb_url[0]; + else + return false; + + $toggle_on = __('Show'); + $toggle_off = __('Hide'); + + $post = get_post($attachment_id); + + $filename = basename($post->guid); + $title = esc_attr($post->post_title); + + if ( $_tags = get_the_tags($attachment_id) ) { + foreach ( $_tags as $tag ) + $tags[] = $tag->name; + $tags = esc_attr(join(', ', $tags)); + } + + $type = ''; + if ( isset($post_mime_types) ) { + $keys = array_keys(wp_match_mime_types(array_keys($post_mime_types), $post->post_mime_type)); + $type = array_shift($keys); + $type = ""; + } + + $form_fields = get_attachment_fields_to_edit($post, $errors); + + if ( $toggle ) { + $class = empty($errors) ? 'startclosed' : 'startopen'; + $toggle_links = " + $toggle_on + $toggle_off"; + } else { + $class = 'form-table'; + $toggle_links = ''; + } + + $display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case + $display_title = $show_title ? "
    " . wp_html_excerpt($display_title, 60) . "
    " : ''; + + $gallery = ( (isset($_REQUEST['tab']) && 'gallery' == $_REQUEST['tab']) || (isset($redir_tab) && 'gallery' == $redir_tab) ) ? true : false; + $order = ''; + + foreach ( $form_fields as $key => $val ) { + if ( 'menu_order' == $key ) { + if ( $gallery ) + $order = ''; + else + $order = ''; + + unset($form_fields['menu_order']); + break; + } + } + + $item = " + $type + $toggle_links + $order + $display_title + + + + + + + + + + + \n"; + + $defaults = array( + 'input' => 'text', + 'required' => false, + 'value' => '', + 'extra_rows' => array(), + ); + + $delete_href = wp_nonce_url("post.php?action=delete-post&post=$attachment_id", 'delete-post_' . $attachment_id); + if ( $send ) + $send = ""; + if ( $delete ) + $delete = "" . __('Delete') . ""; + if ( ( $send || $delete ) && !isset($form_fields['buttons']) ) + $form_fields['buttons'] = array('tr' => "\t\t\n"); + + $hidden_fields = array(); + + foreach ( $form_fields as $id => $field ) { + if ( $id{0} == '_' ) + continue; + + if ( !empty($field['tr']) ) { + $item .= $field['tr']; + continue; + } + + $field = array_merge($defaults, $field); + $name = "attachments[$attachment_id][$id]"; + + if ( $field['input'] == 'hidden' ) { + $hidden_fields[$name] = $field['value']; + continue; + } + + $required = $field['required'] ? '*' : ''; + $aria_required = $field['required'] ? " aria-required='true' " : ''; + $class = $id; + $class .= $field['required'] ? ' form-required' : ''; + + $item .= "\t\t\n\t\t\t\n\t\t\t\n\t\t\n"; + + $extra_rows = array(); + + if ( !empty($field['errors']) ) + foreach ( array_unique((array) $field['errors']) as $error ) + $extra_rows['error'][] = $error; + + if ( !empty($field['extra_rows']) ) + foreach ( $field['extra_rows'] as $class => $rows ) + foreach ( (array) $rows as $html ) + $extra_rows[$class][] = $html; + + foreach ( $extra_rows as $class => $rows ) + foreach ( $rows as $html ) + $item .= "\t\t\n"; + } + + if ( !empty($form_fields['_final']) ) + $item .= "\t\t\n"; + $item .= "\t\n"; + $item .= "\t
    $filename
    $post->post_mime_type
    " . mysql2date($post->post_date, get_option('time_format')) . "
    " . apply_filters('media_meta', '', $post) . "
    $send $delete +
    " . sprintf(__("You are about to delete %s."), $filename) . " " . __('Continue') . " + " . __('Cancel') . "
    "; + if ( !empty($field[$field['input']]) ) + $item .= $field[$field['input']]; + elseif ( $field['input'] == 'textarea' ) { + $item .= ""; + } else { + $item .= ""; + } + if ( !empty($field['helps']) ) + $item .= "

    " . join( "

    \n

    ", array_unique((array) $field['helps']) ) . '

    '; + $item .= "
    $html
    {$form_fields['_final']}
    \n"; + + foreach ( $hidden_fields as $name => $value ) + $item .= "\t\n"; + + if ( $post->post_parent < 1 && isset($_REQUEST['post_id']) ) { + $parent = (int) $_REQUEST['post_id']; + $parent_name = "attachments[$attachment_id][post_parent]"; + + $item .= "\t\n"; + } + + return $item; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function media_upload_header() { + ?> + +
    + +
    + + +
    + + + +
    +
    + + get_error_message(); ?> + +
    + + + + + + +
    + + +
    + +
    + +
    + +

    +
    + + +
    + +

    + + +

    +
    + +

    + + +
    + + + +
    + + + +

    + + + + +
    +'.esc_html($id->get_error_message()).'
    '; + exit; + } +} +?> +
    +

    + +

    + + + + + + + + +

    + + + +
    +
    + +
    +
    + + + + +
    + + + + + + + | + | + +
    + + + +
    + + + + + + + +
      + $reals ) + foreach ( $reals as $real ) + if ( isset($num_posts[$_type]) ) + $num_posts[$_type] += $_num_posts[$real]; + else + $num_posts[$_type] = $_num_posts[$real]; +// If available type specified by media button clicked, filter by that type +if ( empty($_GET['post_mime_type']) && !empty($num_posts[$type]) ) { + $_GET['post_mime_type'] = $type; + list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query(); +} +if ( empty($_GET['post_mime_type']) || $_GET['post_mime_type'] == 'all' ) + $class = ' class="current"'; +else + $class = ''; +$type_links[] = "
    • 'all', 'paged'=>false, 'm'=>false))) . "'$class>".__('All Types').""; +foreach ( $post_mime_types as $mime_type => $label ) { + $class = ''; + + if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) ) + continue; + + if ( isset($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) ) + $class = ' class="current"'; + + $type_links[] = "
    • $mime_type, 'paged'=>false))) . "'$class>" . sprintf(_n($label[2][0], $label[2][1], $num_posts[$mime_type]), "" . number_format_i18n( $num_posts[$mime_type] ) . '') . ''; +} +echo implode(' |
    • ', $type_links) . ''; +unset($type_links); +?> +
    + +
    + + add_query_arg( 'paged', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil($wp_query->found_posts / 10), + 'current' => $_GET['paged'] +)); + +if ( $page_links ) + echo "
    $page_links
    "; +?> + +
    +posts WHERE post_type = 'attachment' ORDER BY post_date DESC"; + +$arc_result = $wpdb->get_results( $arc_query ); + +$month_count = count($arc_result); + +if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) { ?> + + + + + +
    + +
    +
    +
    + +
    + + + + + + +
    + + +
    +

    + + +

    +
    + + + + + required + + + + + + + + * + +

    + + + + + + + +

    ' . $alt_help . '

    + + + +

    + + + + + + + + + + + + + + + + +
    + + + +

    ' . __('Enter a link URL or click above for presets.') . '

    + + + + + + + + + +'; + +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function type_url_form_audio() { + return ' + + + + + + + + + + + + + + +
    + + * +
    + + * +
    ' . __('Link text, e.g. “Still Alive by Jonathan Coulton”') . '
    + +
    +'; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function type_url_form_video() { + return ' + + + + + + + + + + + + + + +
    + + * +
    + + * +
    ' . __('Link text, e.g. “Lucy on YouTube“') . '
    + +
    +'; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function type_url_form_file() { + return ' + + + + + + + + + + + + + + +
    + + * +
    + + * +
    ' . __('Link text, e.g. “Ransom Demands (PDF)”') . '
    + +
    +'; +} + +/** + * {@internal Missing Short Description}} + * + * Support a GET parameter for disabling the flash uploader. + * + * @since unknown + * + * @param unknown_type $flash + * @return unknown + */ +function media_upload_use_flash($flash) { + if ( array_key_exists('flash', $_REQUEST) ) + $flash = !empty($_REQUEST['flash']); + return $flash; +} + +add_filter('flash_uploader', 'media_upload_use_flash'); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function media_upload_flash_bypass() { + echo '

    '; + printf( __('You are using the Flash uploader. Problems? Try the Browser uploader instead.'), esc_url(add_query_arg('flash', 0)) ); + echo '

    '; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function media_upload_html_bypass($flash = true) { + echo '

    '; + _e('You are using the Browser uploader.'); + if ( $flash ) { + // the user manually selected the browser uploader, so let them switch back to Flash + echo ' '; + printf( __('Try the Flash uploader instead.'), esc_url(add_query_arg('flash', 1)) ); + } + echo "

    \n"; +} + +add_action('post-flash-upload-ui', 'media_upload_flash_bypass'); +add_action('post-html-upload-ui', 'media_upload_html_bypass'); + +/** + * {@internal Missing Short Description}} + * + * Make sure the GET parameter sticks when we submit a form. + * + * @since unknown + * + * @param unknown_type $url + * @return unknown + */ +function media_upload_bypass_url($url) { + if ( array_key_exists('flash', $_REQUEST) ) + $url = add_query_arg('flash', intval($_REQUEST['flash'])); + return $url; +} + +add_filter('media_upload_form_url', 'media_upload_bypass_url'); + +add_filter('async_upload_image', 'get_media_item', 10, 2); +add_filter('async_upload_audio', 'get_media_item', 10, 2); +add_filter('async_upload_video', 'get_media_item', 10, 2); +add_filter('async_upload_file', 'get_media_item', 10, 2); + +add_action('media_upload_image', 'media_upload_image'); +add_action('media_upload_audio', 'media_upload_audio'); +add_action('media_upload_video', 'media_upload_video'); +add_action('media_upload_file', 'media_upload_file'); + +add_filter('media_upload_gallery', 'media_upload_gallery'); + +add_filter('media_upload_library', 'media_upload_library'); + +?> diff --git a/wp-admin/includes/misc.php b/wp-admin/includes/misc.php new file mode 100644 index 0000000..356c6b0 --- /dev/null +++ b/wp-admin/includes/misc.php @@ -0,0 +1,641 @@ + $markerline ) { + if (strpos($markerline, '# BEGIN ' . $marker) !== false) + $state = false; + if ( $state ) { + if ( $n + 1 < count( $markerdata ) ) + fwrite( $f, "{$markerline}\n" ); + else + fwrite( $f, "{$markerline}" ); + } + if (strpos($markerline, '# END ' . $marker) !== false) { + fwrite( $f, "# BEGIN {$marker}\n" ); + if ( is_array( $insertion )) + foreach ( $insertion as $insertline ) + fwrite( $f, "{$insertline}\n" ); + fwrite( $f, "# END {$marker}\n" ); + $state = true; + $foundit = true; + } + } + } + if (!$foundit) { + fwrite( $f, "\n# BEGIN {$marker}\n" ); + foreach ( $insertion as $insertline ) + fwrite( $f, "{$insertline}\n" ); + fwrite( $f, "# END {$marker}\n" ); + } + fclose( $f ); + return true; + } else { + return false; + } +} + +/** + * Updates the htaccess file with the current rules if it is writable. + * + * Always writes to the file if it exists and is writable to ensure that we + * blank out old rules. + * + * @since unknown + */ +function save_mod_rewrite_rules() { + global $wp_rewrite; + + $home_path = get_home_path(); + $htaccess_file = $home_path.'.htaccess'; + + // If the file doesn't already exists check for write access to the directory and whether of not we have some rules. + // else check for write access to the file. + if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) { + if ( got_mod_rewrite() ) { + $rules = explode( "\n", $wp_rewrite->mod_rewrite_rules() ); + return insert_with_markers( $htaccess_file, 'WordPress', $rules ); + } + } + + return false; +} + +/** + * Updates the IIS web.config file with the current rules if it is writable. + * If the permalinks do not require rewrite rules then the rules are deleted from the web.config file. + * + * @since 2.8.0 + * + * @return bool True if web.config was updated successfully + */ +function iis7_save_url_rewrite_rules(){ + global $wp_rewrite; + + $home_path = get_home_path(); + $web_config_file = $home_path . 'web.config'; + + // Using win_is_writable() instead of is_writable() because of a bug in Windows PHP + if ( ( ! file_exists($web_config_file) && win_is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks() ) || win_is_writable($web_config_file) ) { + if ( iis7_supports_permalinks() ) { + $rule = $wp_rewrite->iis7_url_rewrite_rules(); + if ( ! empty($rule) ) { + return iis7_add_rewrite_rule($web_config_file, $rule); + } else { + return iis7_delete_rewrite_rule($web_config_file); + } + } + } + return false; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $file + */ +function update_recently_edited( $file ) { + $oldfiles = (array ) get_option( 'recently_edited' ); + if ( $oldfiles ) { + $oldfiles = array_reverse( $oldfiles ); + $oldfiles[] = $file; + $oldfiles = array_reverse( $oldfiles ); + $oldfiles = array_unique( $oldfiles ); + if ( 5 < count( $oldfiles )) + array_pop( $oldfiles ); + } else { + $oldfiles[] = $file; + } + update_option( 'recently_edited', $oldfiles ); +} + +/** + * If siteurl or home changed, flush rewrite rules. + * + * @since unknown + * + * @param unknown_type $old_value + * @param unknown_type $value + */ +function update_home_siteurl( $old_value, $value ) { + global $wp_rewrite; + + if ( defined( "WP_INSTALLING" ) ) + return; + + // If home changed, write rewrite rules to new location. + $wp_rewrite->flush_rules(); +} + +add_action( 'update_option_home', 'update_home_siteurl', 10, 2 ); +add_action( 'update_option_siteurl', 'update_home_siteurl', 10, 2 ); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $url + * @return unknown + */ +function url_shorten( $url ) { + $short_url = str_replace( 'http://', '', stripslashes( $url )); + $short_url = str_replace( 'www.', '', $short_url ); + if ('/' == substr( $short_url, -1 )) + $short_url = substr( $short_url, 0, -1 ); + if ( strlen( $short_url ) > 35 ) + $short_url = substr( $short_url, 0, 32 ).'...'; + return $short_url; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $vars + */ +function wp_reset_vars( $vars ) { + for ( $i=0; $iget_error_data() ) + $message = $message->get_error_message() . ': ' . $message->get_error_data(); + else + $message = $message->get_error_message(); + } + echo "

    $message

    \n"; +} + +function wp_doc_link_parse( $content ) { + if ( !is_string( $content ) || empty( $content ) ) + return array(); + + if ( !function_exists('token_get_all') ) + return array(); + + $tokens = token_get_all( $content ); + $functions = array(); + $ignore_functions = array(); + for ( $t = 0, $count = count( $tokens ); $t < $count; $t++ ) { + if ( !is_array( $tokens[$t] ) ) continue; + if ( T_STRING == $tokens[$t][0] && ( '(' == $tokens[ $t + 1 ] || '(' == $tokens[ $t + 2 ] ) ) { + // If it's a function or class defined locally, there's not going to be any docs available + if ( ( isset( $tokens[ $t - 2 ][1] ) && in_array( $tokens[ $t - 2 ][1], array( 'function', 'class' ) ) ) || ( isset( $tokens[ $t - 2 ][0] ) && T_OBJECT_OPERATOR == $tokens[ $t - 1 ][0] ) ) { + $ignore_functions[] = $tokens[$t][1]; + } + // Add this to our stack of unique references + $functions[] = $tokens[$t][1]; + } + } + + $functions = array_unique( $functions ); + sort( $functions ); + $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions ); + $ignore_functions = array_unique( $ignore_functions ); + + $out = array(); + foreach ( $functions as $function ) { + if ( in_array( $function, $ignore_functions ) ) + continue; + $out[] = $function; + } + + return $out; +} + +/** + * Determines the language to use for CodePress syntax highlighting, + * based only on a filename. + * + * @since 2.8 + * + * @param string $filename The name of the file to be highlighting +**/ +function codepress_get_lang( $filename ) { + $codepress_supported_langs = apply_filters( 'codepress_supported_langs', + array( '.css' => 'css', + '.js' => 'javascript', + '.php' => 'php', + '.html' => 'html', + '.htm' => 'html', + '.txt' => 'text' + ) ); + $extension = substr( $filename, strrpos( $filename, '.' ) ); + if ( $extension && array_key_exists( $extension, $codepress_supported_langs ) ) + return $codepress_supported_langs[$extension]; + + return 'generic'; +} + +/** + * Adds Javascript required to make CodePress work on the theme/plugin editors. + * + * This code is attached to the action admin_print_footer_scripts. + * + * @since 2.8 +**/ +function codepress_footer_js() { + // Script-loader breaks CP's automatic path-detection, thus CodePress.path + // CP edits in an iframe, so we need to grab content back into normal form + ?> + 999 ) + return; + break; + default: + $value = apply_filters('set-screen-option', false, $option, $value); + if ( false === $value ) + return; + break; + } + + update_usermeta($user->ID, $option, $value); + wp_redirect( remove_query_arg( array('pagenum', 'apage', 'paged'), wp_get_referer() ) ); + exit; + } +} + +function wp_menu_unfold() { + if ( isset($_GET['unfoldmenu']) ) { + delete_user_setting('mfold'); + wp_redirect( remove_query_arg( 'unfoldmenu', stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; + } +} + +/** + * Check if IIS 7 supports pretty permalinks + * + * @since 2.8.0 + * + * @return bool + */ +function iis7_supports_permalinks() { + global $is_iis7; + + $supports_permalinks = false; + if ( $is_iis7 ) { + /* First we check if the DOMDocument class exists. If it does not exist, + * which is the case for PHP 4.X, then we cannot easily update the xml configuration file, + * hence we just bail out and tell user that pretty permalinks cannot be used. + * This is not a big issue because PHP 4.X is going to be depricated and for IIS it + * is recommended to use PHP 5.X NTS. + * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When + * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'. + * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs + * via ISAPI then pretty permalinks will not work. + */ + $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' ); + } + + return apply_filters('iis7_supports_permalinks', $supports_permalinks); +} + +/** + * Check if rewrite rule for WordPress already exists in the IIS 7 configuration file + * + * @since 2.8.0 + * + * @return bool + * @param string $filename The file path to the configuration file + */ +function iis7_rewrite_rule_exists($filename) { + if ( ! file_exists($filename) ) + return false; + if ( ! class_exists('DOMDocument') ) + return false; + + $doc = new DOMDocument(); + if ( $doc->load($filename) === false ) + return false; + $xpath = new DOMXPath($doc); + $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[@name=\'wordpress\']'); + if ( $rules->length == 0 ) + return false; + else + return true; +} + +/** + * Delete WordPress rewrite rule from web.config file if it exists there + * + * @since 2.8.0 + * + * @param string $filename Name of the configuration file + * @return bool + */ +function iis7_delete_rewrite_rule($filename) { + // If configuration file does not exist then rules also do not exist so there is nothing to delete + if ( ! file_exists($filename) ) + return true; + + if ( ! class_exists('DOMDocument') ) + return false; + + $doc = new DOMDocument(); + $doc->preserveWhiteSpace = false; + + if ( $doc -> load($filename) === false ) + return false; + $xpath = new DOMXPath($doc); + $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[@name=\'wordpress\']'); + if ( $rules->length > 0 ) { + $child = $rules->item(0); + $parent = $child->parentNode; + $parent->removeChild($child); + $doc->formatOutput = true; + saveDomDocument($doc, $filename); + } + return true; +} + +/** + * Add WordPress rewrite rule to the IIS 7 configuration file. + * + * @since 2.8.0 + * + * @param string $filename The file path to the configuration file + * @param string $rewrite_rule The XML fragment with URL Rewrite rule + * @return bool + */ +function iis7_add_rewrite_rule($filename, $rewrite_rule) { + if ( ! class_exists('DOMDocument') ) + return false; + + // If configuration file does not exist then we create one. + if ( ! file_exists($filename) ) { + $fp = fopen( $filename, 'w'); + fwrite($fp, ''); + fclose($fp); + } + + $doc = new DOMDocument(); + $doc->preserveWhiteSpace = false; + + if ( $doc->load($filename) === false ) + return false; + + $xpath = new DOMXPath($doc); + + // First check if the rule already exists as in that case there is no need to re-add it + $wordpress_rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[@name=\'wordpress\']'); + if ( $wordpress_rules->length > 0 ) + return true; + + // Check the XPath to the rewrite rule and create XML nodes if they do not exist + $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite/rules'); + if ( $xmlnodes->length > 0 ) { + $rules_node = $xmlnodes->item(0); + } else { + $rules_node = $doc->createElement('rules'); + + $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite'); + if ( $xmlnodes->length > 0 ) { + $rewrite_node = $xmlnodes->item(0); + $rewrite_node->appendChild($rules_node); + } else { + $rewrite_node = $doc->createElement('rewrite'); + $rewrite_node->appendChild($rules_node); + + $xmlnodes = $xpath->query('/configuration/system.webServer'); + if ( $xmlnodes->length > 0 ) { + $system_webServer_node = $xmlnodes->item(0); + $system_webServer_node->appendChild($rewrite_node); + } else { + $system_webServer_node = $doc->createElement('system.webServer'); + $system_webServer_node->appendChild($rewrite_node); + + $xmlnodes = $xpath->query('/configuration'); + if ( $xmlnodes->length > 0 ) { + $config_node = $xmlnodes->item(0); + $config_node->appendChild($system_webServer_node); + } else { + $config_node = $doc->createElement('configuration'); + $doc->appendChild($config_node); + $config_node->appendChild($system_webServer_node); + } + } + } + } + + $rule_fragment = $doc->createDocumentFragment(); + $rule_fragment->appendXML($rewrite_rule); + $rules_node->appendChild($rule_fragment); + + $doc->formatOutput = true; + saveDomDocument($doc, $filename); + + return true; +} + +/** + * Saves the XML document into a file + * + * @since 2.8.0 + * + * @param DOMDocument $doc + * @param string $filename + */ +function saveDomDocument($doc, $filename) { + $config = $doc->saveXML(); + $config = preg_replace("/([^\r])\n/", "$1\r\n", $config); + $fp = fopen($filename, 'w'); + fwrite($fp, $config); + fclose($fp); +} + +/** + * Workaround for Windows bug in is_writable() function + * + * @since 2.8.0 + * + * @param object $path + * @return bool + */ +function win_is_writable($path) { + /* will work in despite of Windows ACLs bug + * NOTE: use a trailing slash for folders!!! + * see http://bugs.php.net/bug.php?id=27609 + * see http://bugs.php.net/bug.php?id=30931 + */ + + if ( $path{strlen($path)-1} == '/' ) // recursively return a temporary file path + return win_is_writable($path . uniqid(mt_rand()) . '.tmp'); + else if ( is_dir($path) ) + return win_is_writable($path . '/' . uniqid(mt_rand()) . '.tmp'); + // check tmp file for read/write capabilities + $rm = file_exists($path); + $f = @fopen($path, 'a'); + if ($f===false) + return false; + fclose($f); + if ( ! $rm ) + unlink($path); + return true; +} +?> diff --git a/wp-admin/includes/plugin-install.php b/wp-admin/includes/plugin-install.php new file mode 100644 index 0000000..f81ecc8 --- /dev/null +++ b/wp-admin/includes/plugin-install.php @@ -0,0 +1,562 @@ +per_page) ) + $args->per_page = 24; + + $args = apply_filters('plugins_api_args', $args, $action); //NOTE: Ensure that an object is returned via this filter. + $res = apply_filters('plugins_api', false, $action, $args); //NOTE: Allows a plugin to completely override the builtin WordPress.org API. + + if ( ! $res ) { + $request = wp_remote_post('http://api.wordpress.org/plugins/info/1.0/', array( 'body' => array('action' => $action, 'request' => serialize($args))) ); + if ( is_wp_error($request) ) { + $res = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.

    Try again'), $request->get_error_message() ); + } else { + $res = unserialize($request['body']); + if ( ! $res ) + $res = new WP_Error('plugins_api_failed', __('An unknown error occurred'), $request['body']); + } + } elseif ( !is_wp_error($res) ) { + $res->external = true; + } + + return apply_filters('plugins_api_result', $res, $action, $args); +} + +/** + * Retrieve popular WordPress plugin tags. + * + * @since 2.7.0 + * + * @param array $args + * @return array + */ +function install_popular_tags( $args = array() ) { + if ( ! ($cache = wp_cache_get('popular_tags', 'api')) && ! ($cache = get_option('wporg_popular_tags')) ) + add_option('wporg_popular_tags', array(), '', 'no'); ///No autoload. + + if ( $cache && $cache->timeout + 3 * 60 * 60 > time() ) + return $cache->cached; + + $tags = plugins_api('hot_tags', $args); + + if ( is_wp_error($tags) ) + return $tags; + + $cache = (object) array('timeout' => time(), 'cached' => $tags); + + update_option('wporg_popular_tags', $cache); + wp_cache_set('popular_tags', $cache, 'api'); + + return $tags; +} +add_action('install_plugins_search', 'install_search', 10, 1); + +/** + * Display search results and display as tag cloud. + * + * @since 2.7.0 + * + * @param string $page + */ +function install_search($page) { + $type = isset($_REQUEST['type']) ? stripslashes( $_REQUEST['type'] ) : ''; + $term = isset($_REQUEST['s']) ? stripslashes( $_REQUEST['s'] ) : ''; + + $args = array(); + + switch( $type ){ + case 'tag': + $args['tag'] = sanitize_title_with_dashes($term); + break; + case 'term': + $args['search'] = $term; + break; + case 'author': + $args['author'] = $term; + break; + } + + $args['page'] = $page; + + $api = plugins_api('query_plugins', $args); + + if ( is_wp_error($api) ) + wp_die($api); + + add_action('install_plugins_table_header', 'install_search_form'); + + display_plugins_table($api->plugins, $api->info['page'], $api->info['pages']); + + return; +} + +add_action('install_plugins_dashboard', 'install_dashboard'); +function install_dashboard() { + ?> +

    WordPress Plugin Directory or upload a plugin in .zip format via this page.') ?>

    + +

    +

    + + +

    +

    + esc_url( admin_url('plugin-install.php?tab=search&type=tag&s=' . urlencode($tag['name'])) ), + 'name' => $tag['name'], + 'id' => sanitize_title_with_dashes($tag['name']), + 'count' => $tag['count'] ); + echo '
    '; +} + +/** + * Display search form for searching plugins. + * + * @since 2.7.0 + */ +function install_search_form(){ + $type = isset($_REQUEST['type']) ? stripslashes( $_REQUEST['type'] ) : ''; + $term = isset($_REQUEST['s']) ? stripslashes( $_REQUEST['s'] ) : ''; + + ?>
    + + + + +
    'featured', 'page' => $page); + $api = plugins_api('query_plugins', $args); + if ( is_wp_error($api) ) + wp_die($api); + display_plugins_table($api->plugins, $api->info['page'], $api->info['pages']); +} + +add_action('install_plugins_popular', 'install_popular', 10, 1); +/** + * Display popular plugins. + * + * @since 2.7.0 + * + * @param string $page + */ +function install_popular($page = 1) { + $args = array('browse' => 'popular', 'page' => $page); + $api = plugins_api('query_plugins', $args); + display_plugins_table($api->plugins, $api->info['page'], $api->info['pages']); +} + +add_action('install_plugins_upload', 'install_plugins_upload', 10, 1); +/** + * Upload from zip + * @since 2.8.0 + * + * @param string $page + */ +function install_plugins_upload( $page = 1 ) { +?> +

    +

    +
    + + + + +
    + 'new', 'page' => $page); + $api = plugins_api('query_plugins', $args); + if ( is_wp_error($api) ) + wp_die($api); + display_plugins_table($api->plugins, $api->info['page'], $api->info['pages']); +} +add_action('install_plugins_updated', 'install_updated', 10, 1); + + +/** + * Display recently updated plugins. + * + * @since 2.7.0 + * + * @param string $page + */ +function install_updated($page = 1) { + $args = array('browse' => 'updated', 'page' => $page); + $api = plugins_api('query_plugins', $args); + display_plugins_table($api->plugins, $api->info['page'], $api->info['pages']); +} + +/** + * Display plugin content based on plugin list. + * + * @since 2.7.0 + * + * @param array $plugins List of plugins. + * @param string $page + * @param int $totalpages Number of pages. + */ +function display_plugins_table($plugins, $page = 1, $totalpages = 1){ + $type = isset($_REQUEST['type']) ? stripslashes( $_REQUEST['type'] ) : ''; + $term = isset($_REQUEST['s']) ? stripslashes( $_REQUEST['s'] ) : ''; + + $plugins_allowedtags = array('a' => array('href' => array(),'title' => array(), 'target' => array()), + 'abbr' => array('title' => array()),'acronym' => array('title' => array()), + 'code' => array(), 'pre' => array(), 'em' => array(),'strong' => array(), + 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array()); + +?> +
    +
    + +
    + add_query_arg('paged', '%#%', $url), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => $totalpages, + 'current' => $page + )); + + if ( $page_links ) + echo "\t\t
    $page_links
    "; +?> +
    +
    + + + + + + + + + + + + + + + + + + + + + + + '; + + foreach( (array) $plugins as $plugin ){ + if ( is_object($plugin) ) + $plugin = (array) $plugin; + + $title = wp_kses($plugin['name'], $plugins_allowedtags); + //Limit description to 400char, and remove any HTML. + $description = strip_tags($plugin['description']); + if ( strlen($description) > 400 ) + $description = mb_substr($description, 0, 400) . '…'; + //remove any trailing entities + $description = preg_replace('/&[^;\s]{0,6}$/', '', $description); + //strip leading/trailing & multiple consecutive lines + $description = trim($description); + $description = preg_replace("|(\r?\n)+|", "\n", $description); + //\n =>
    + $description = nl2br($description); + $version = wp_kses($plugin['version'], $plugins_allowedtags); + + $name = strip_tags($title . ' ' . $version); + + $author = $plugin['author']; + if( ! empty($plugin['author']) ) + $author = ' ' . sprintf( __('By %s'), $author ) . '.'; + + $author = wp_kses($author, $plugins_allowedtags); + + if( isset($plugin['homepage']) ) + $title = '' . $title . ''; + + $action_links = array(); + $action_links[] = '' . __('Install') . ''; + + $action_links = apply_filters('plugin_install_action_links', $action_links, $plugin); + ?> + + + + + + + + + +
    ', __('No plugins match your request.'), '
    +
    +
    +
    <?php _e('5 stars') ?>
    +
    <?php _e('4 stars') ?>
    +
    <?php _e('3 stars') ?>
    +
    <?php _e('2 stars') ?>
    +
    <?php _e('1 star') ?>
    +
    +
    + +
    + $page_links
    "; ?> +
    + + + stripslashes( $_REQUEST['plugin'] ) )); + + if ( is_wp_error($api) ) + wp_die($api); + + $plugins_allowedtags = array('a' => array('href' => array(), 'title' => array(), 'target' => array()), + 'abbr' => array('title' => array()), 'acronym' => array('title' => array()), + 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), + 'div' => array(), 'p' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), + 'h1' => array(), 'h2' => array(), 'h3' => array(), 'h4' => array(), 'h5' => array(), 'h6' => array(), + 'img' => array('src' => array(), 'class' => array(), 'alt' => array())); + //Sanitize HTML + foreach ( (array)$api->sections as $section_name => $content ) + $api->sections[$section_name] = wp_kses($content, $plugins_allowedtags); + foreach ( array('version', 'author', 'requires', 'tested', 'homepage', 'downloaded', 'slug') as $key ) + $api->$key = wp_kses($api->$key, $plugins_allowedtags); + + $section = isset($_REQUEST['section']) ? stripslashes( $_REQUEST['section'] ) : 'description'; //Default to the Description tab, Do not translate, API returns English. + if( empty($section) || ! isset($api->sections[ $section ]) ) + $section = array_shift( $section_titles = array_keys((array)$api->sections) ); + + iframe_header( __('Plugin Install') ); + echo "
    \n"; + echo "
      \n"; + foreach ( (array)$api->sections as $section_name => $content ) { + + $title = $section_name; + $title = ucwords(str_replace('_', ' ', $title)); + + $class = ( $section_name == $section ) ? ' class="current"' : ''; + $href = add_query_arg( array('tab' => $tab, 'section' => $section_name) ); + $href = esc_url($href); + $san_title = esc_attr(sanitize_title_with_dashes($title)); + echo "\t
    • $title
    • \n"; + } + echo "
    \n"; + echo "
    \n"; + ?> +
    + download_link) ) : ?> +

    + response as $file => $plugin ) { + if ( $plugin->slug === $api->slug ) { + $type = 'update_available'; + $update_file = $file; + break; + } + } + } + if ( 'install' == $type && is_dir( WP_PLUGIN_DIR . '/' . $api->slug ) ) { + $installed_plugin = get_plugins('/' . $api->slug); + if ( ! empty($installed_plugin) ) { + $key = array_shift( $key = array_keys($installed_plugin) ); //Use the first plugin regardless of the name, Could have issues for multiple-plugins in one directory if they share different version numbers + if ( version_compare($api->version, $installed_plugin[ $key ]['Version'], '=') ){ + $type = 'latest_installed'; + } elseif ( version_compare($api->version, $installed_plugin[ $key ]['Version'], '<') ) { + $type = 'newer_installed'; + $newer_version = $installed_plugin[ $key ]['Version']; + } else { + //If the above update check failed, Then that probably means that the update checker has out-of-date information, force a refresh + delete_transient('update_plugins'); + $update_file = $api->slug . '/' . $key; //This code branch only deals with a plugin which is in a folder the same name as its slug, Doesnt support plugins which have 'non-standard' names + $type = 'update_available'; + } + } + } + + switch ( $type ) : + default: + case 'install': + if ( current_user_can('install_plugins') ) : + ?> +

    + +

    +
      +version) ) : ?> +
    • version ?>
    • +author) ) : ?> +
    • author, '_blank') ?>
    • +last_updated) ) : ?> +
    • last_updated)) ) ?>
    • +requires) ) : ?> +
    • requires) ?>
    • +tested) ) : ?> +
    • tested ?>
    • +downloaded) ) : ?> +
    • downloaded), number_format_i18n($api->downloaded)) ?>
    • +slug) && empty($api->external) ) : ?> +
    • +homepage) ) : ?> +
    • + +
    + rating) ) : ?> +

    +
    +
    +
    <?php _e('5 stars') ?>
    +
    <?php _e('4 stars') ?>
    +
    <?php _e('3 stars') ?>
    +
    <?php _e('2 stars') ?>
    +
    <?php _e('1 star') ?>
    +
    + num_ratings), number_format_i18n($api->num_ratings)); ?> + +
    +
    + tested) && version_compare( substr($GLOBALS['wp_version'], 0, strlen($api->tested)), $api->tested, '>') ) + echo '

    ' . __('Warning: This plugin has not been tested with your current version of WordPress.') . '

    '; + + else if ( !empty($api->requires) && version_compare( substr($GLOBALS['wp_version'], 0, strlen($api->requires)), $api->requires, '<') ) + echo '

    ' . __('Warning: This plugin has not been marked as compatible with your version of WordPress.') . '

    '; + + foreach ( (array)$api->sections as $section_name => $content ) { + $title = $section_name; + $title[0] = strtoupper($title[0]); + $title = str_replace('_', ' ', $title); + + $content = links_add_base_url($content, 'http://wordpress.org/extend/plugins/' . $api->slug . '/'); + $content = links_add_target($content, '_blank'); + + $san_title = esc_attr(sanitize_title_with_dashes($title)); + + $display = ( $section_name == $section ) ? 'block' : 'none'; + + echo "\t
    \n"; + echo "\t\t

    $title

    "; + echo $content; + echo "\t
    \n"; + } + echo "
    \n"; + + iframe_footer(); + exit; +} diff --git a/wp-admin/includes/plugin.php b/wp-admin/includes/plugin.php new file mode 100644 index 0000000..88a95dd --- /dev/null +++ b/wp-admin/includes/plugin.php @@ -0,0 +1,1151 @@ + + * /* + * Plugin Name: Name of Plugin + * Plugin URI: Link to plugin information + * Description: Plugin Description + * Author: Plugin author's name + * Author URI: Link to the author's web site + * Version: Must be set in the plugin for WordPress 2.3+ + * Text Domain: Optional. Unique identifier, should be same as the one used in + * plugin_text_domain() + * Domain Path: Optional. Only useful if the translations are located in a + * folder above the plugin's base path. For example, if .mo files are + * located in the locale folder then Domain Path will be "/locale/" and + * must have the first slash. Defaults to the base folder the plugin is + * located in. + * * / # Remove the space to close comment + * + * + * Plugin data returned array contains the following: + * 'Name' - Name of the plugin, must be unique. + * 'Title' - Title of the plugin and the link to the plugin's web site. + * 'Description' - Description of what the plugin does and/or notes + * from the author. + * 'Author' - The author's name + * 'AuthorURI' - The authors web site address. + * 'Version' - The plugin version number. + * 'PluginURI' - Plugin web site address. + * 'TextDomain' - Plugin's text domain for localization. + * 'DomainPath' - Plugin's relative directory path to .mo files. + * + * Some users have issues with opening large files and manipulating the contents + * for want is usually the first 1kiB or 2kiB. This function stops pulling in + * the plugin contents when it has all of the required plugin data. + * + * The first 8kiB of the file will be pulled in and if the plugin data is not + * within that first 8kiB, then the plugin author should correct their plugin + * and move the plugin data headers to the top. + * + * The plugin file is assumed to have permissions to allow for scripts to read + * the file. This is not checked however and the file is only opened for + * reading. + * + * @link http://trac.wordpress.org/ticket/5651 Previous Optimizations. + * @link http://trac.wordpress.org/ticket/7372 Further and better Optimizations. + * @since 1.5.0 + * + * @param string $plugin_file Path to the plugin file + * @param bool $markup If the returned data should have HTML markup applied + * @param bool $translate If the returned data should be translated + * @return array See above for description. + */ +function get_plugin_data( $plugin_file, $markup = true, $translate = true ) { + // We don't need to write to the file, so just open for reading. + $fp = fopen($plugin_file, 'r'); + + // Pull only the first 8kiB of the file in. + $plugin_data = fread( $fp, 8192 ); + + // PHP will close file handle, but we are good citizens. + fclose($fp); + + preg_match( '|Plugin Name:(.*)$|mi', $plugin_data, $name ); + preg_match( '|Plugin URI:(.*)$|mi', $plugin_data, $uri ); + preg_match( '|Version:(.*)|i', $plugin_data, $version ); + preg_match( '|Description:(.*)$|mi', $plugin_data, $description ); + preg_match( '|Author:(.*)$|mi', $plugin_data, $author_name ); + preg_match( '|Author URI:(.*)$|mi', $plugin_data, $author_uri ); + preg_match( '|Text Domain:(.*)$|mi', $plugin_data, $text_domain ); + preg_match( '|Domain Path:(.*)$|mi', $plugin_data, $domain_path ); + + foreach ( array( 'name', 'uri', 'version', 'description', 'author_name', 'author_uri', 'text_domain', 'domain_path' ) as $field ) { + if ( !empty( ${$field} ) ) + ${$field} = _cleanup_header_comment(${$field}[1]); + else + ${$field} = ''; + } + + $plugin_data = array( + 'Name' => $name, 'Title' => $name, 'PluginURI' => $uri, 'Description' => $description, + 'Author' => $author_name, 'AuthorURI' => $author_uri, 'Version' => $version, + 'TextDomain' => $text_domain, 'DomainPath' => $domain_path + ); + if ( $markup || $translate ) + $plugin_data = _get_plugin_data_markup_translate($plugin_file, $plugin_data, $markup, $translate); + + return $plugin_data; +} + +function _get_plugin_data_markup_translate($plugin_file, $plugin_data, $markup = true, $translate = true) { + + //Translate fields + if( $translate && ! empty($plugin_data['TextDomain']) ) { + if( ! empty( $plugin_data['DomainPath'] ) ) + load_plugin_textdomain($plugin_data['TextDomain'], dirname($plugin_file). $plugin_data['DomainPath']); + else + load_plugin_textdomain($plugin_data['TextDomain'], dirname($plugin_file)); + + foreach ( array('Name', 'PluginURI', 'Description', 'Author', 'AuthorURI', 'Version') as $field ) + $plugin_data[ $field ] = translate($plugin_data[ $field ], $plugin_data['TextDomain']); + } + + //Apply Markup + if ( $markup ) { + if ( ! empty($plugin_data['PluginURI']) && ! empty($plugin_data['Name']) ) + $plugin_data['Title'] = '' . $plugin_data['Name'] . ''; + else + $plugin_data['Title'] = $plugin_data['Name']; + + if ( ! empty($plugin_data['AuthorURI']) && ! empty($plugin_data['Author']) ) + $plugin_data['Author'] = '' . $plugin_data['Author'] . ''; + + $plugin_data['Description'] = wptexturize( $plugin_data['Description'] ); + if( ! empty($plugin_data['Author']) ) + $plugin_data['Description'] .= ' ' . sprintf( __('By %s'), $plugin_data['Author'] ) . '.'; + } + + $plugins_allowedtags = array('a' => array('href' => array(),'title' => array()),'abbr' => array('title' => array()),'acronym' => array('title' => array()),'code' => array(),'em' => array(),'strong' => array()); + + // Sanitize all displayed data + $plugin_data['Title'] = wp_kses($plugin_data['Title'], $plugins_allowedtags); + $plugin_data['Version'] = wp_kses($plugin_data['Version'], $plugins_allowedtags); + $plugin_data['Description'] = wp_kses($plugin_data['Description'], $plugins_allowedtags); + $plugin_data['Author'] = wp_kses($plugin_data['Author'], $plugins_allowedtags); + + return $plugin_data; +} + +/** + * Get a list of a plugin's files. + * + * @since 2.8.0 + * + * @param string $plugin Plugin ID + * @return array List of files relative to the plugin root. + */ +function get_plugin_files($plugin) { + $plugin_file = WP_PLUGIN_DIR . '/' . $plugin; + $dir = dirname($plugin_file); + $plugin_files = array($plugin); + if ( is_dir($dir) && $dir != WP_PLUGIN_DIR ) { + $plugins_dir = @ opendir( $dir ); + if ( $plugins_dir ) { + while (($file = readdir( $plugins_dir ) ) !== false ) { + if ( substr($file, 0, 1) == '.' ) + continue; + if ( is_dir( $dir . '/' . $file ) ) { + $plugins_subdir = @ opendir( $dir . '/' . $file ); + if ( $plugins_subdir ) { + while (($subfile = readdir( $plugins_subdir ) ) !== false ) { + if ( substr($subfile, 0, 1) == '.' ) + continue; + $plugin_files[] = plugin_basename("$dir/$file/$subfile"); + } + @closedir( $plugins_subdir ); + } + } else { + if ( plugin_basename("$dir/$file") != $plugin ) + $plugin_files[] = plugin_basename("$dir/$file"); + } + } + @closedir( $plugins_dir ); + } + } + + return $plugin_files; +} + +/** + * Check the plugins directory and retrieve all plugin files with plugin data. + * + * WordPress only supports plugin files in the base plugins directory + * (wp-content/plugins) and in one directory above the plugins directory + * (wp-content/plugins/my-plugin). The file it looks for has the plugin data and + * must be found in those two locations. It is recommended that do keep your + * plugin files in directories. + * + * The file with the plugin data is the file that will be included and therefore + * needs to have the main execution for the plugin. This does not mean + * everything must be contained in the file and it is recommended that the file + * be split for maintainability. Keep everything in one file for extreme + * optimization purposes. + * + * @since unknown + * + * @param string $plugin_folder Optional. Relative path to single plugin folder. + * @return array Key is the plugin file path and the value is an array of the plugin data. + */ +function get_plugins($plugin_folder = '') { + + if ( ! $cache_plugins = wp_cache_get('plugins', 'plugins') ) + $cache_plugins = array(); + + if ( isset($cache_plugins[ $plugin_folder ]) ) + return $cache_plugins[ $plugin_folder ]; + + $wp_plugins = array (); + $plugin_root = WP_PLUGIN_DIR; + if( !empty($plugin_folder) ) + $plugin_root .= $plugin_folder; + + // Files in wp-content/plugins directory + $plugins_dir = @ opendir( $plugin_root); + $plugin_files = array(); + if ( $plugins_dir ) { + while (($file = readdir( $plugins_dir ) ) !== false ) { + if ( substr($file, 0, 1) == '.' ) + continue; + if ( is_dir( $plugin_root.'/'.$file ) ) { + $plugins_subdir = @ opendir( $plugin_root.'/'.$file ); + if ( $plugins_subdir ) { + while (($subfile = readdir( $plugins_subdir ) ) !== false ) { + if ( substr($subfile, 0, 1) == '.' ) + continue; + if ( substr($subfile, -4) == '.php' ) + $plugin_files[] = "$file/$subfile"; + } + } + } else { + if ( substr($file, -4) == '.php' ) + $plugin_files[] = $file; + } + } + } + @closedir( $plugins_dir ); + @closedir( $plugins_subdir ); + + if ( !$plugins_dir || empty($plugin_files) ) + return $wp_plugins; + + foreach ( $plugin_files as $plugin_file ) { + if ( !is_readable( "$plugin_root/$plugin_file" ) ) + continue; + + $plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false ); //Do not apply markup/translate as it'll be cached. + + if ( empty ( $plugin_data['Name'] ) ) + continue; + + $wp_plugins[plugin_basename( $plugin_file )] = $plugin_data; + } + + uasort( $wp_plugins, create_function( '$a, $b', 'return strnatcasecmp( $a["Name"], $b["Name"] );' )); + + $cache_plugins[ $plugin_folder ] = $wp_plugins; + wp_cache_set('plugins', $cache_plugins, 'plugins'); + + return $wp_plugins; +} + +/** + * Check whether the plugin is active by checking the active_plugins list. + * + * @since 2.5.0 + * + * @param string $plugin Base plugin path from plugins directory. + * @return bool True, if in the active plugins list. False, not in the list. + */ +function is_plugin_active($plugin) { + return in_array($plugin, get_option('active_plugins')); +} + +/** + * Attempts activation of plugin in a "sandbox" and redirects on success. + * + * A plugin that is already activated will not attempt to be activated again. + * + * The way it works is by setting the redirection to the error before trying to + * include the plugin file. If the plugin fails, then the redirection will not + * be overwritten with the success message. Also, the options will not be + * updated and the activation hook will not be called on plugin error. + * + * It should be noted that in no way the below code will actually prevent errors + * within the file. The code should not be used elsewhere to replicate the + * "sandbox", which uses redirection to work. + * {@source 13 1} + * + * If any errors are found or text is outputted, then it will be captured to + * ensure that the success redirection will update the error redirection. + * + * @since unknown + * + * @param string $plugin Plugin path to main plugin file with plugin data. + * @param string $redirect Optional. URL to redirect to. + * @return WP_Error|null WP_Error on invalid file or null on success. + */ +function activate_plugin($plugin, $redirect = '') { + $current = get_option('active_plugins'); + $plugin = plugin_basename(trim($plugin)); + + $valid = validate_plugin($plugin); + if ( is_wp_error($valid) ) + return $valid; + + if ( !in_array($plugin, $current) ) { + if ( !empty($redirect) ) + wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); // we'll override this later if the plugin can be included without fatal error + ob_start(); + @include(WP_PLUGIN_DIR . '/' . $plugin); + $current[] = $plugin; + sort($current); + update_option('active_plugins', $current); + do_action('activate_' . $plugin); + ob_end_clean(); + } + + return null; +} + +/** + * Deactivate a single plugin or multiple plugins. + * + * The deactivation hook is disabled by the plugin upgrader by using the $silent + * parameter. + * + * @since unknown + * + * @param string|array $plugins Single plugin or list of plugins to deactivate. + * @param bool $silent Optional, default is false. Prevent calling deactivate hook. + */ +function deactivate_plugins($plugins, $silent= false) { + $current = get_option('active_plugins'); + + if ( !is_array($plugins) ) + $plugins = array($plugins); + + foreach ( $plugins as $plugin ) { + $plugin = plugin_basename($plugin); + if( ! is_plugin_active($plugin) ) + continue; + array_splice($current, array_search( $plugin, $current), 1 ); // Fixed Array-fu! + if ( ! $silent ) //Used by Plugin updater to internally deactivate plugin, however, not to notify plugins of the fact to prevent plugin output. + do_action('deactivate_' . trim( $plugin )); + } + + update_option('active_plugins', $current); +} + +/** + * Activate multiple plugins. + * + * When WP_Error is returned, it does not mean that one of the plugins had + * errors. It means that one or more of the plugins file path was invalid. + * + * The execution will be halted as soon as one of the plugins has an error. + * + * @since unknown + * + * @param string|array $plugins + * @param string $redirect Redirect to page after successful activation. + * @return bool|WP_Error True when finished or WP_Error if there were errors during a plugin activation. + */ +function activate_plugins($plugins, $redirect = '') { + if ( !is_array($plugins) ) + $plugins = array($plugins); + + $errors = array(); + foreach ( (array) $plugins as $plugin ) { + if ( !empty($redirect) ) + $redirect = add_query_arg('plugin', $plugin, $redirect); + $result = activate_plugin($plugin, $redirect); + if ( is_wp_error($result) ) + $errors[$plugin] = $result; + } + + if ( !empty($errors) ) + return new WP_Error('plugins_invalid', __('One of the plugins is invalid.'), $errors); + + return true; +} + +/** + * Remove directory and files of a plugin for a single or list of plugin(s). + * + * If the plugins parameter list is empty, false will be returned. True when + * completed. + * + * @since unknown + * + * @param array $plugins List of plugin + * @param string $redirect Redirect to page when complete. + * @return mixed + */ +function delete_plugins($plugins, $redirect = '' ) { + global $wp_filesystem; + + if( empty($plugins) ) + return false; + + $checked = array(); + foreach( $plugins as $plugin ) + $checked[] = 'checked[]=' . $plugin; + + ob_start(); + $url = wp_nonce_url('plugins.php?action=delete-selected&verify-delete=1&' . implode('&', $checked), 'bulk-manage-plugins'); + if ( false === ($credentials = request_filesystem_credentials($url)) ) { + $data = ob_get_contents(); + ob_end_clean(); + if( ! empty($data) ){ + include_once( ABSPATH . 'wp-admin/admin-header.php'); + echo $data; + include( ABSPATH . 'wp-admin/admin-footer.php'); + exit; + } + return; + } + + if ( ! WP_Filesystem($credentials) ) { + request_filesystem_credentials($url, '', true); //Failed to connect, Error and request again + $data = ob_get_contents(); + ob_end_clean(); + if( ! empty($data) ){ + include_once( ABSPATH . 'wp-admin/admin-header.php'); + echo $data; + include( ABSPATH . 'wp-admin/admin-footer.php'); + exit; + } + return; + } + + if ( ! is_object($wp_filesystem) ) + return new WP_Error('fs_unavailable', __('Could not access filesystem.')); + + if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) + return new WP_Error('fs_error', __('Filesystem error'), $wp_filesystem->errors); + + //Get the base plugin folder + $plugins_dir = $wp_filesystem->wp_plugins_dir(); + if ( empty($plugins_dir) ) + return new WP_Error('fs_no_plugins_dir', __('Unable to locate WordPress Plugin directory.')); + + $plugins_dir = trailingslashit( $plugins_dir ); + + $errors = array(); + + foreach( $plugins as $plugin_file ) { + // Run Uninstall hook + if ( is_uninstallable_plugin( $plugin_file ) ) + uninstall_plugin($plugin_file); + + $this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin_file) ); + // If plugin is in its own directory, recursively delete the directory. + if ( strpos($plugin_file, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory seperator AND that its not the root plugin folder + $deleted = $wp_filesystem->delete($this_plugin_dir, true); + else + $deleted = $wp_filesystem->delete($plugins_dir . $plugin_file); + + if ( ! $deleted ) + $errors[] = $plugin_file; + } + + if ( ! empty($errors) ) + return new WP_Error('could_not_remove_plugin', sprintf(__('Could not fully remove the plugin(s) %s'), implode(', ', $errors)) ); + + // Force refresh of plugin update information + if ( $current = get_transient('update_plugins') ) { + unset( $current->response[ $plugin_file ] ); + set_transient('update_plugins', $current); + } + + return true; +} + +function validate_active_plugins() { + $check_plugins = get_option('active_plugins'); + + // Sanity check. If the active plugin list is not an array, make it an + // empty array. + if ( !is_array($check_plugins) ) { + update_option('active_plugins', array()); + return; + } + + //Invalid is any plugin that is deactivated due to error. + $invalid = array(); + + // If a plugin file does not exist, remove it from the list of active + // plugins. + foreach ( $check_plugins as $check_plugin ) { + $result = validate_plugin($check_plugin); + if ( is_wp_error( $result ) ) { + $invalid[$check_plugin] = $result; + deactivate_plugins( $check_plugin, true); + } + } + return $invalid; +} + +/** + * Validate the plugin path. + * + * Checks that the file exists and {@link validate_file() is valid file}. + * + * @since unknown + * + * @param string $plugin Plugin Path + * @return WP_Error|int 0 on success, WP_Error on failure. + */ +function validate_plugin($plugin) { + if ( validate_file($plugin) ) + return new WP_Error('plugin_invalid', __('Invalid plugin path.')); + if ( ! file_exists(WP_PLUGIN_DIR . '/' . $plugin) ) + return new WP_Error('plugin_not_found', __('Plugin file does not exist.')); + + $installed_plugins = get_plugins(); + if ( ! isset($installed_plugins[$plugin]) ) + return new WP_Error('no_plugin_header', __('The plugin does not have a valid header.')); + return 0; +} + +/** + * Whether the plugin can be uninstalled. + * + * @since 2.7.0 + * + * @param string $plugin Plugin path to check. + * @return bool Whether plugin can be uninstalled. + */ +function is_uninstallable_plugin($plugin) { + $file = plugin_basename($plugin); + + $uninstallable_plugins = (array) get_option('uninstall_plugins'); + if ( isset( $uninstallable_plugins[$file] ) || file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) ) + return true; + + return false; +} + +/** + * Uninstall a single plugin. + * + * Calls the uninstall hook, if it is available. + * + * @since 2.7.0 + * + * @param string $plugin Relative plugin path from Plugin Directory. + */ +function uninstall_plugin($plugin) { + $file = plugin_basename($plugin); + + $uninstallable_plugins = (array) get_option('uninstall_plugins'); + if ( file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) ) { + if ( isset( $uninstallable_plugins[$file] ) ) { + unset($uninstallable_plugins[$file]); + update_option('uninstall_plugins', $uninstallable_plugins); + } + unset($uninstallable_plugins); + + define('WP_UNINSTALL_PLUGIN', $file); + include WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php'; + + return true; + } + + if ( isset( $uninstallable_plugins[$file] ) ) { + $callable = $uninstallable_plugins[$file]; + unset($uninstallable_plugins[$file]); + update_option('uninstall_plugins', $uninstallable_plugins); + unset($uninstallable_plugins); + + include WP_PLUGIN_DIR . '/' . $file; + + add_action( 'uninstall_' . $file, $callable ); + do_action( 'uninstall_' . $file ); + } +} + +// +// Menu +// + +function add_menu_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '' ) { + global $menu, $admin_page_hooks, $_registered_pages; + + $file = plugin_basename( $file ); + + $admin_page_hooks[$file] = sanitize_title( $menu_title ); + + $hookname = get_plugin_page_hookname( $file, '' ); + if (!empty ( $function ) && !empty ( $hookname )) + add_action( $hookname, $function ); + + if ( empty($icon_url) ) + $icon_url = 'images/generic.png'; + elseif ( is_ssl() && 0 === strpos($icon_url, 'http://') ) + $icon_url = 'https://' . substr($icon_url, 7); + + $menu[] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url ); + + $_registered_pages[$hookname] = true; + + return $hookname; +} + +function add_object_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '') { + global $menu, $admin_page_hooks, $_wp_last_object_menu, $_registered_pages; + + $file = plugin_basename( $file ); + + $admin_page_hooks[$file] = sanitize_title( $menu_title ); + + $hookname = get_plugin_page_hookname( $file, '' ); + if (!empty ( $function ) && !empty ( $hookname )) + add_action( $hookname, $function ); + + if ( empty($icon_url) ) + $icon_url = 'images/generic.png'; + + $_wp_last_object_menu++; + + $menu[$_wp_last_object_menu] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url ); + + $_registered_pages[$hookname] = true; + + return $hookname; +} + +function add_utility_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '') { + global $menu, $admin_page_hooks, $_wp_last_utility_menu, $_registered_pages; + + $file = plugin_basename( $file ); + + $admin_page_hooks[$file] = sanitize_title( $menu_title ); + + $hookname = get_plugin_page_hookname( $file, '' ); + if (!empty ( $function ) && !empty ( $hookname )) + add_action( $hookname, $function ); + + if ( empty($icon_url) ) + $icon_url = 'images/generic.png'; + elseif ( is_ssl() && 0 === strpos($icon_url, 'http://') ) + $icon_url = 'https://' . substr($icon_url, 7); + + $_wp_last_utility_menu++; + + $menu[$_wp_last_utility_menu] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url ); + + $_registered_pages[$hookname] = true; + + return $hookname; +} + +function add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function = '' ) { + global $submenu; + global $menu; + global $_wp_real_parent_file; + global $_wp_submenu_nopriv; + global $_registered_pages; + + $file = plugin_basename( $file ); + + $parent = plugin_basename( $parent); + if ( isset( $_wp_real_parent_file[$parent] ) ) + $parent = $_wp_real_parent_file[$parent]; + + if ( !current_user_can( $access_level ) ) { + $_wp_submenu_nopriv[$parent][$file] = true; + return false; + } + + // If the parent doesn't already have a submenu, add a link to the parent + // as the first item in the submenu. If the submenu file is the same as the + // parent file someone is trying to link back to the parent manually. In + // this case, don't automatically add a link back to avoid duplication. + if (!isset( $submenu[$parent] ) && $file != $parent ) { + foreach ( (array)$menu as $parent_menu ) { + if ( $parent_menu[2] == $parent && current_user_can( $parent_menu[1] ) ) + $submenu[$parent][] = $parent_menu; + } + } + + $submenu[$parent][] = array ( $menu_title, $access_level, $file, $page_title ); + + $hookname = get_plugin_page_hookname( $file, $parent); + if (!empty ( $function ) && !empty ( $hookname )) + add_action( $hookname, $function ); + + $_registered_pages[$hookname] = true; + // backwards-compatibility for plugins using add_management page. See wp-admin/admin.php for redirect from edit.php to tools.php + if ( 'tools.php' == $parent ) + $_registered_pages[get_plugin_page_hookname( $file, 'edit.php')] = true; + + return $hookname; +} + +/** + * Add sub menu page to the tools main menu. + * + * @param string $page_title + * @param unknown_type $menu_title + * @param unknown_type $access_level + * @param unknown_type $file + * @param unknown_type $function + * @return unknown + */ +function add_management_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'tools.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_options_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'options-general.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_theme_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'themes.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_users_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + if ( current_user_can('edit_users') ) + $parent = 'users.php'; + else + $parent = 'profile.php'; + return add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_dashboard_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'index.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_posts_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'edit.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_media_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'upload.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_links_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'link-manager.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_pages_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'edit-pages.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +function add_comments_page( $page_title, $menu_title, $access_level, $file, $function = '' ) { + return add_submenu_page( 'edit-comments.php', $page_title, $menu_title, $access_level, $file, $function ); +} + +// +// Pluggable Menu Support -- Private +// + +function get_admin_page_parent( $parent = '' ) { + global $parent_file; + global $menu; + global $submenu; + global $pagenow; + global $plugin_page; + global $_wp_real_parent_file; + global $_wp_menu_nopriv; + global $_wp_submenu_nopriv; + + if ( !empty ( $parent ) && 'admin.php' != $parent ) { + if ( isset( $_wp_real_parent_file[$parent] ) ) + $parent = $_wp_real_parent_file[$parent]; + return $parent; + } +/* + if ( !empty ( $parent_file ) ) { + if ( isset( $_wp_real_parent_file[$parent_file] ) ) + $parent_file = $_wp_real_parent_file[$parent_file]; + + return $parent_file; + } +*/ + + if ( $pagenow == 'admin.php' && isset( $plugin_page ) ) { + foreach ( (array)$menu as $parent_menu ) { + if ( $parent_menu[2] == $plugin_page ) { + $parent_file = $plugin_page; + if ( isset( $_wp_real_parent_file[$parent_file] ) ) + $parent_file = $_wp_real_parent_file[$parent_file]; + return $parent_file; + } + } + if ( isset( $_wp_menu_nopriv[$plugin_page] ) ) { + $parent_file = $plugin_page; + if ( isset( $_wp_real_parent_file[$parent_file] ) ) + $parent_file = $_wp_real_parent_file[$parent_file]; + return $parent_file; + } + } + + if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) ) { + $parent_file = $pagenow; + if ( isset( $_wp_real_parent_file[$parent_file] ) ) + $parent_file = $_wp_real_parent_file[$parent_file]; + return $parent_file; + } + + foreach (array_keys( (array)$submenu ) as $parent) { + foreach ( $submenu[$parent] as $submenu_array ) { + if ( isset( $_wp_real_parent_file[$parent] ) ) + $parent = $_wp_real_parent_file[$parent]; + if ( $submenu_array[2] == $pagenow ) { + $parent_file = $parent; + return $parent; + } else + if ( isset( $plugin_page ) && ($plugin_page == $submenu_array[2] ) ) { + $parent_file = $parent; + return $parent; + } + } + } + + if ( empty($parent_file) ) + $parent_file = ''; + return ''; +} + +function get_admin_page_title() { + global $title; + global $menu; + global $submenu; + global $pagenow; + global $plugin_page; + + if ( isset( $title ) && !empty ( $title ) ) { + return $title; + } + + $hook = get_plugin_page_hook( $plugin_page, $pagenow ); + + $parent = $parent1 = get_admin_page_parent(); + + if ( empty ( $parent) ) { + foreach ( (array)$menu as $menu_array ) { + if ( isset( $menu_array[3] ) ) { + if ( $menu_array[2] == $pagenow ) { + $title = $menu_array[3]; + return $menu_array[3]; + } else + if ( isset( $plugin_page ) && ($plugin_page == $menu_array[2] ) && ($hook == $menu_array[3] ) ) { + $title = $menu_array[3]; + return $menu_array[3]; + } + } else { + $title = $menu_array[0]; + return $title; + } + } + } else { + foreach (array_keys( $submenu ) as $parent) { + foreach ( $submenu[$parent] as $submenu_array ) { + if ( isset( $plugin_page ) && + ($plugin_page == $submenu_array[2] ) && + (($parent == $pagenow ) || ($parent == $plugin_page ) || ($plugin_page == $hook ) || (($pagenow == 'admin.php' ) && ($parent1 != $submenu_array[2] ) ) ) + ) { + $title = $submenu_array[3]; + return $submenu_array[3]; + } + + if ( $submenu_array[2] != $pagenow || isset( $_GET['page'] ) ) // not the current page + continue; + + if ( isset( $submenu_array[3] ) ) { + $title = $submenu_array[3]; + return $submenu_array[3]; + } else { + $title = $submenu_array[0]; + return $title; + } + } + } + if ( !isset($title) || empty ( $title ) ) { + foreach ( $menu as $menu_array ) { + if ( isset( $plugin_page ) && + ($plugin_page == $menu_array[2] ) && + ($pagenow == 'admin.php' ) && + ($parent1 == $menu_array[2] ) ) + { + $title = $menu_array[3]; + return $menu_array[3]; + } + } + } + } + + return $title; +} + +function get_plugin_page_hook( $plugin_page, $parent_page ) { + $hook = get_plugin_page_hookname( $plugin_page, $parent_page ); + if ( has_action($hook) ) + return $hook; + else + return null; +} + +function get_plugin_page_hookname( $plugin_page, $parent_page ) { + global $admin_page_hooks; + + $parent = get_admin_page_parent( $parent_page ); + + $page_type = 'admin'; + if ( empty ( $parent_page ) || 'admin.php' == $parent_page || isset( $admin_page_hooks[$plugin_page] ) ) { + if ( isset( $admin_page_hooks[$plugin_page] ) ) + $page_type = 'toplevel'; + else + if ( isset( $admin_page_hooks[$parent] )) + $page_type = $admin_page_hooks[$parent]; + } else if ( isset( $admin_page_hooks[$parent] ) ) { + $page_type = $admin_page_hooks[$parent]; + } + + $plugin_name = preg_replace( '!\.php!', '', $plugin_page ); + + return $page_type.'_page_'.$plugin_name; +} + +function user_can_access_admin_page() { + global $pagenow; + global $menu; + global $submenu; + global $_wp_menu_nopriv; + global $_wp_submenu_nopriv; + global $plugin_page; + global $_registered_pages; + + $parent = get_admin_page_parent(); + + if ( !isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$pagenow] ) ) + return false; + + if ( isset( $plugin_page ) ) { + if ( isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) ) + return false; + + $hookname = get_plugin_page_hookname($plugin_page, $parent); + if ( !isset($_registered_pages[$hookname]) ) + return false; + } + + if ( empty( $parent) ) { + if ( isset( $_wp_menu_nopriv[$pagenow] ) ) + return false; + if ( isset( $_wp_submenu_nopriv[$pagenow][$pagenow] ) ) + return false; + if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) ) + return false; + if ( isset( $plugin_page ) && isset( $_wp_menu_nopriv[$plugin_page] ) ) + return false; + foreach (array_keys( $_wp_submenu_nopriv ) as $key ) { + if ( isset( $_wp_submenu_nopriv[$key][$pagenow] ) ) + return false; + if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$key][$plugin_page] ) ) + return false; + } + return true; + } + + if ( isset( $plugin_page ) && ( $plugin_page == $parent ) && isset( $_wp_menu_nopriv[$plugin_page] ) ) + return false; + + if ( isset( $submenu[$parent] ) ) { + foreach ( $submenu[$parent] as $submenu_array ) { + if ( isset( $plugin_page ) && ( $submenu_array[2] == $plugin_page ) ) { + if ( current_user_can( $submenu_array[1] )) + return true; + else + return false; + } else if ( $submenu_array[2] == $pagenow ) { + if ( current_user_can( $submenu_array[1] )) + return true; + else + return false; + } + } + } + + foreach ( $menu as $menu_array ) { + if ( $menu_array[2] == $parent) { + if ( current_user_can( $menu_array[1] )) + return true; + else + return false; + } + } + + return true; +} + +/* Whitelist functions */ + +/** + * Register a setting and its sanitization callback + * + * @since 2.7.0 + * + * @param string $option_group A settings group name. Can be anything. + * @param string $option_name The name of an option to sanitize and save. + * @param unknown_type $sanitize_callback A callback function that sanitizes the option's value. + * @return unknown + */ +function register_setting($option_group, $option_name, $sanitize_callback = '') { + return add_option_update_handler($option_group, $option_name, $sanitize_callback); +} + +/** + * Unregister a setting + * + * @since 2.7.0 + * + * @param unknown_type $option_group + * @param unknown_type $option_name + * @param unknown_type $sanitize_callback + * @return unknown + */ +function unregister_setting($option_group, $option_name, $sanitize_callback = '') { + return remove_option_update_handler($option_group, $option_name, $sanitize_callback); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $option_group + * @param unknown_type $option_name + * @param unknown_type $sanitize_callback + */ +function add_option_update_handler($option_group, $option_name, $sanitize_callback = '') { + global $new_whitelist_options; + $new_whitelist_options[ $option_group ][] = $option_name; + if ( $sanitize_callback != '' ) + add_filter( "sanitize_option_{$option_name}", $sanitize_callback ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $option_group + * @param unknown_type $option_name + * @param unknown_type $sanitize_callback + */ +function remove_option_update_handler($option_group, $option_name, $sanitize_callback = '') { + global $new_whitelist_options; + $pos = array_search( $option_name, (array) $new_whitelist_options ); + if ( $pos !== false ) + unset( $new_whitelist_options[ $option_group ][ $pos ] ); + if ( $sanitize_callback != '' ) + remove_filter( "sanitize_option_{$option_name}", $sanitize_callback ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $options + * @return unknown + */ +function option_update_filter( $options ) { + global $new_whitelist_options; + + if ( is_array( $new_whitelist_options ) ) + $options = add_option_whitelist( $new_whitelist_options, $options ); + + return $options; +} +add_filter( 'whitelist_options', 'option_update_filter' ); + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $new_options + * @param unknown_type $options + * @return unknown + */ +function add_option_whitelist( $new_options, $options = '' ) { + if( $options == '' ) { + global $whitelist_options; + } else { + $whitelist_options = $options; + } + foreach( $new_options as $page => $keys ) { + foreach( $keys as $key ) { + if ( !isset($whitelist_options[ $page ]) || !is_array($whitelist_options[ $page ]) ) { + $whitelist_options[ $page ] = array(); + $whitelist_options[ $page ][] = $key; + } else { + $pos = array_search( $key, $whitelist_options[ $page ] ); + if ( $pos === false ) + $whitelist_options[ $page ][] = $key; + } + } + } + return $whitelist_options; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $del_options + * @param unknown_type $options + * @return unknown + */ +function remove_option_whitelist( $del_options, $options = '' ) { + if( $options == '' ) { + global $whitelist_options; + } else { + $whitelist_options = $options; + } + foreach( $del_options as $page => $keys ) { + foreach( $keys as $key ) { + if ( isset($whitelist_options[ $page ]) && is_array($whitelist_options[ $page ]) ) { + $pos = array_search( $key, $whitelist_options[ $page ] ); + if( $pos !== false ) + unset( $whitelist_options[ $page ][ $pos ] ); + } + } + } + return $whitelist_options; +} + +/** + * Output nonce, action, and option_page fields for a settings page. + * + * @since 2.7.0 + * + * @param string $option_group A settings group name. This should match the group name used in register_setting(). + */ +function settings_fields($option_group) { + echo ""; + echo ''; + wp_nonce_field("$option_group-options"); +} + +?> diff --git a/wp-admin/includes/post.php b/wp-admin/includes/post.php new file mode 100644 index 0000000..c7acf91 --- /dev/null +++ b/wp-admin/includes/post.php @@ -0,0 +1,1404 @@ + 31 ) ? 31 : $jj; + $jj = ($jj <= 0 ) ? date('j') : $jj; + $hh = ($hh > 23 ) ? $hh -24 : $hh; + $mn = ($mn > 59 ) ? $mn -60 : $mn; + $ss = ($ss > 59 ) ? $ss -60 : $ss; + $post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss ); + $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] ); + } + + return $post_data; +} + +/** + * Update an existing post with values provided in $_POST. + * + * @since unknown + * + * @param array $post_data Optional. + * @return int Post ID. + */ +function edit_post( $post_data = null ) { + + if ( empty($post_data) ) + $post_data = &$_POST; + + $post_ID = (int) $post_data['post_ID']; + + if ( 'page' == $post_data['post_type'] ) { + if ( !current_user_can( 'edit_page', $post_ID ) ) + wp_die( __('You are not allowed to edit this page.' )); + } else { + if ( !current_user_can( 'edit_post', $post_ID ) ) + wp_die( __('You are not allowed to edit this post.' )); + } + + // Autosave shouldn't save too soon after a real save + if ( 'autosave' == $post_data['action'] ) { + $post =& get_post( $post_ID ); + $now = time(); + $then = strtotime($post->post_date_gmt . ' +0000'); + $delta = AUTOSAVE_INTERVAL / 2; + if ( ($now - $then) < $delta ) + return $post_ID; + } + + $post_data = _wp_translate_postdata( true, $post_data ); + if ( is_wp_error($post_data) ) + wp_die( $post_data->get_error_message() ); + + if ( isset($post_data['visibility']) ) { + switch ( $post_data['visibility'] ) { + case 'public' : + $post_data['post_password'] = ''; + break; + case 'password' : + unset( $post_data['sticky'] ); + break; + case 'private' : + $post_data['post_status'] = 'private'; + $post_data['post_password'] = ''; + unset( $post_data['sticky'] ); + break; + } + } + + // Meta Stuff + if ( isset($post_data['meta']) && $post_data['meta'] ) { + foreach ( $post_data['meta'] as $key => $value ) + update_meta( $key, $value['key'], $value['value'] ); + } + + if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) { + foreach ( $post_data['deletemeta'] as $key => $value ) + delete_meta( $key ); + } + + add_meta( $post_ID ); + + wp_update_post( $post_data ); + + // Reunite any orphaned attachments with their parent + if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) ) + $draft_ids = array(); + if ( $draft_temp_id = (int) array_search( $post_ID, $draft_ids ) ) + _relocate_children( $draft_temp_id, $post_ID ); + + // Now that we have an ID we can fix any attachment anchor hrefs + _fix_attachment_links( $post_ID ); + + wp_set_post_lock( $post_ID, $GLOBALS['current_user']->ID ); + + if ( current_user_can( 'edit_others_posts' ) ) { + if ( !empty($post_data['sticky']) ) + stick_post($post_ID); + else + unstick_post($post_ID); + } + + return $post_ID; +} + +/** + * {@internal Missing Short Description}} + * + * Updates all bulk edited posts/pages, adding (but not removing) tags and + * categories. Skips pages when they would be their own parent or child. + * + * @since unknown + * + * @return array + */ +function bulk_edit_posts( $post_data = null ) { + global $wpdb; + + if ( empty($post_data) ) + $post_data = &$_POST; + + if ( isset($post_data['post_type']) && 'page' == $post_data['post_type'] ) { + if ( ! current_user_can( 'edit_pages' ) ) + wp_die( __('You are not allowed to edit pages.') ); + } else { + if ( ! current_user_can( 'edit_posts' ) ) + wp_die( __('You are not allowed to edit posts.') ); + } + + $post_IDs = array_map( 'intval', (array) $post_data['post'] ); + + $reset = array( 'post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tags_input', 'post_category', 'sticky' ); + foreach ( $reset as $field ) { + if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) ) + unset($post_data[$field]); + } + + if ( isset($post_data['post_category']) ) { + if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) ) + $new_cats = array_map( absint, $post_data['post_category'] ); + else + unset($post_data['post_category']); + } + + if ( isset($post_data['tags_input']) ) { + $new_tags = preg_replace( '/\s*,\s*/', ',', rtrim( trim($post_data['tags_input']), ' ,' ) ); + $new_tags = explode(',', $new_tags); + } + + if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) { + $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'"); + $children = array(); + + for ( $i = 0; $i < 50 && $parent > 0; $i++ ) { + $children[] = $parent; + + foreach ( $pages as $page ) { + if ( $page->ID == $parent ) { + $parent = $page->post_parent; + break; + } + } + } + } + + $updated = $skipped = $locked = array(); + foreach ( $post_IDs as $post_ID ) { + + if ( isset($children) && in_array($post_ID, $children) ) { + $skipped[] = $post_ID; + continue; + } + + if ( wp_check_post_lock( $post_ID ) ) { + $locked[] = $post_ID; + continue; + } + + if ( isset($new_cats) ) { + $cats = (array) wp_get_post_categories($post_ID); + $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) ); + } + + if ( isset($new_tags) ) { + $tags = wp_get_post_tags($post_ID, array('fields' => 'names')); + $post_data['tags_input'] = array_unique( array_merge($tags, $new_tags) ); + } + + $post_data['ID'] = $post_ID; + $updated[] = wp_update_post( $post_data ); + + if ( current_user_can( 'edit_others_posts' ) && isset( $post_data['sticky'] ) ) { + if ( 'sticky' == $post_data['sticky'] ) + stick_post( $post_ID ); + else + unstick_post( $post_ID ); + } + + } + + return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked ); +} + +/** + * Default post information to use when populating the "Write Post" form. + * + * @since unknown + * + * @return unknown + */ +function get_default_post_to_edit() { + if ( !empty( $_REQUEST['post_title'] ) ) + $post_title = esc_html( stripslashes( $_REQUEST['post_title'] )); + else if ( !empty( $_REQUEST['popuptitle'] ) ) { + $post_title = esc_html( stripslashes( $_REQUEST['popuptitle'] )); + $post_title = funky_javascript_fix( $post_title ); + } else { + $post_title = ''; + } + + $post_content = ''; + if ( !empty( $_REQUEST['content'] ) ) + $post_content = esc_html( stripslashes( $_REQUEST['content'] )); + else if ( !empty( $post_title ) ) { + $text = esc_html( stripslashes( urldecode( $_REQUEST['text'] ) ) ); + $text = funky_javascript_fix( $text); + $popupurl = esc_url($_REQUEST['popupurl']); + $post_content = ''.$post_title.''."\n$text"; + } + + if ( !empty( $_REQUEST['excerpt'] ) ) + $post_excerpt = esc_html( stripslashes( $_REQUEST['excerpt'] )); + else + $post_excerpt = ''; + + $post->ID = 0; + $post->post_name = ''; + $post->post_author = ''; + $post->post_date = ''; + $post->post_date_gmt = ''; + $post->post_password = ''; + $post->post_status = 'draft'; + $post->post_type = 'post'; + $post->to_ping = ''; + $post->pinged = ''; + $post->comment_status = get_option( 'default_comment_status' ); + $post->ping_status = get_option( 'default_ping_status' ); + $post->post_pingback = get_option( 'default_pingback_flag' ); + $post->post_category = get_option( 'default_category' ); + $post->post_content = apply_filters( 'default_content', $post_content); + $post->post_title = apply_filters( 'default_title', $post_title ); + $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt); + $post->page_template = 'default'; + $post->post_parent = 0; + $post->menu_order = 0; + + return $post; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function get_default_page_to_edit() { + $page = get_default_post_to_edit(); + $page->post_type = 'page'; + return $page; +} + +/** + * Get an existing post and format it for editing. + * + * @since unknown + * + * @param unknown_type $id + * @return unknown + */ +function get_post_to_edit( $id ) { + + $post = get_post( $id, OBJECT, 'edit' ); + + if ( $post->post_type == 'page' ) + $post->page_template = get_post_meta( $id, '_wp_page_template', true ); + + return $post; +} + +/** + * Determine if a post exists based on title, content, and date + * + * @since unknown + * + * @param string $title Post title + * @param string $content Optional post content + * @param string $date Optional post date + * @return int Post ID if post exists, 0 otherwise. + */ +function post_exists($title, $content = '', $date = '') { + global $wpdb; + + $post_title = stripslashes( sanitize_post_field( 'post_title', $title, 0, 'db' ) ); + $post_content = stripslashes( sanitize_post_field( 'post_content', $content, 0, 'db' ) ); + $post_date = stripslashes( sanitize_post_field( 'post_date', $date, 0, 'db' ) ); + + $query = "SELECT ID FROM $wpdb->posts WHERE 1=1"; + $args = array(); + + if ( !empty ( $date ) ) { + $query .= ' AND post_date = %s'; + $args[] = $post_date; + } + + if ( !empty ( $title ) ) { + $query .= ' AND post_title = %s'; + $args[] = $post_title; + } + + if ( !empty ( $content ) ) { + $query .= 'AND post_content = %s'; + $args[] = $post_content; + } + + if ( !empty ( $args ) ) + return $wpdb->get_var( $wpdb->prepare($query, $args) ); + + return 0; +} + +/** + * Creates a new post from the "Write Post" form using $_POST information. + * + * @since unknown + * + * @return unknown + */ +function wp_write_post() { + global $user_ID; + + if ( 'page' == $_POST['post_type'] ) { + if ( !current_user_can( 'edit_pages' ) ) + return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this blog.' ) ); + } else { + if ( !current_user_can( 'edit_posts' ) ) + return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this blog.' ) ); + } + + + // Check for autosave collisions + $temp_id = false; + if ( isset($_POST['temp_ID']) ) { + $temp_id = (int) $_POST['temp_ID']; + if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) ) + $draft_ids = array(); + foreach ( $draft_ids as $temp => $real ) + if ( time() + $temp > 86400 ) // 1 day: $temp is equal to -1 * time( then ) + unset($draft_ids[$temp]); + + if ( isset($draft_ids[$temp_id]) ) { // Edit, don't write + $_POST['post_ID'] = $draft_ids[$temp_id]; + unset($_POST['temp_ID']); + update_user_option( $user_ID, 'autosave_draft_ids', $draft_ids ); + return edit_post(); + } + } + + $translated = _wp_translate_postdata( false ); + if ( is_wp_error($translated) ) + return $translated; + + if ( isset($_POST['visibility']) ) { + switch ( $_POST['visibility'] ) { + case 'public' : + $_POST['post_password'] = ''; + break; + case 'password' : + unset( $_POST['sticky'] ); + break; + case 'private' : + $_POST['post_status'] = 'private'; + $_POST['post_password'] = ''; + unset( $_POST['sticky'] ); + break; + } + } + + // Create the post. + $post_ID = wp_insert_post( $_POST ); + if ( is_wp_error( $post_ID ) ) + return $post_ID; + + if ( empty($post_ID) ) + return 0; + + add_meta( $post_ID ); + + // Reunite any orphaned attachments with their parent + if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) ) + $draft_ids = array(); + if ( $draft_temp_id = (int) array_search( $post_ID, $draft_ids ) ) + _relocate_children( $draft_temp_id, $post_ID ); + if ( $temp_id && $temp_id != $draft_temp_id ) + _relocate_children( $temp_id, $post_ID ); + + // Update autosave collision detection + if ( $temp_id ) { + $draft_ids[$temp_id] = $post_ID; + update_user_option( $user_ID, 'autosave_draft_ids', $draft_ids ); + } + + // Now that we have an ID we can fix any attachment anchor hrefs + _fix_attachment_links( $post_ID ); + + wp_set_post_lock( $post_ID, $GLOBALS['current_user']->ID ); + + return $post_ID; +} + +/** + * Calls wp_write_post() and handles the errors. + * + * @since unknown + * + * @return unknown + */ +function write_post() { + $result = wp_write_post(); + if( is_wp_error( $result ) ) + wp_die( $result->get_error_message() ); + else + return $result; +} + +// +// Post Meta +// + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post_ID + * @return unknown + */ +function add_meta( $post_ID ) { + global $wpdb; + $post_ID = (int) $post_ID; + + $protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' ); + + $metakeyselect = isset($_POST['metakeyselect']) ? stripslashes( trim( $_POST['metakeyselect'] ) ) : ''; + $metakeyinput = isset($_POST['metakeyinput']) ? stripslashes( trim( $_POST['metakeyinput'] ) ) : ''; + $metavalue = isset($_POST['metavalue']) ? maybe_serialize( stripslashes( trim( $_POST['metavalue'] ) ) ) : ''; + + if ( ('0' === $metavalue || !empty ( $metavalue ) ) && ((('#NONE#' != $metakeyselect) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput) ) ) { + // We have a key/value pair. If both the select and the + // input for the key have data, the input takes precedence: + + if ('#NONE#' != $metakeyselect) + $metakey = $metakeyselect; + + if ( $metakeyinput) + $metakey = $metakeyinput; // default + + if ( in_array($metakey, $protected) ) + return false; + + wp_cache_delete($post_ID, 'post_meta'); + + $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value ) VALUES (%s, %s, %s)", $post_ID, $metakey, $metavalue) ); + return $wpdb->insert_id; + } + return false; +} // add_meta + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $mid + * @return unknown + */ +function delete_meta( $mid ) { + global $wpdb; + $mid = (int) $mid; + + $post_id = $wpdb->get_var( $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_id = %d", $mid) ); + wp_cache_delete($post_id, 'post_meta'); + + return $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_id = %d", $mid) ); +} + +/** + * Get a list of previously defined keys. + * + * @since unknown + * + * @return unknown + */ +function get_meta_keys() { + global $wpdb; + + $keys = $wpdb->get_col( " + SELECT meta_key + FROM $wpdb->postmeta + GROUP BY meta_key + ORDER BY meta_key" ); + + return $keys; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $mid + * @return unknown + */ +function get_post_meta_by_id( $mid ) { + global $wpdb; + $mid = (int) $mid; + + $meta = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_id = %d", $mid) ); + if ( is_serialized_string( $meta->meta_value ) ) + $meta->meta_value = maybe_unserialize( $meta->meta_value ); + return $meta; +} + +/** + * {@internal Missing Short Description}} + * + * Some postmeta stuff. + * + * @since unknown + * + * @param unknown_type $postid + * @return unknown + */ +function has_meta( $postid ) { + global $wpdb; + + return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id + FROM $wpdb->postmeta WHERE post_id = %d + ORDER BY meta_key,meta_id", $postid), ARRAY_A ); + +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $meta_id + * @param unknown_type $meta_key + * @param unknown_type $meta_value + * @return unknown + */ +function update_meta( $meta_id, $meta_key, $meta_value ) { + global $wpdb; + + $protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' ); + + if ( in_array($meta_key, $protected) ) + return false; + + if ( '' === trim( $meta_value ) ) + return false; + + $post_id = $wpdb->get_var( $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_id = %d", $meta_id) ); + wp_cache_delete($post_id, 'post_meta'); + + $meta_value = maybe_serialize( stripslashes( $meta_value ) ); + $meta_id = (int) $meta_id; + + $data = compact( 'meta_key', 'meta_value' ); + $where = compact( 'meta_id' ); + + return $wpdb->update( $wpdb->postmeta, $data, $where ); +} + +// +// Private +// + +/** + * Replace hrefs of attachment anchors with up-to-date permalinks. + * + * @since unknown + * @access private + * + * @param unknown_type $post_ID + * @return unknown + */ +function _fix_attachment_links( $post_ID ) { + + $post = & get_post( $post_ID, ARRAY_A ); + + $search = "#]+rel=('|\")[^'\"]*attachment[^>]*>#ie"; + + // See if we have any rel="attachment" links + if ( 0 == preg_match_all( $search, $post['post_content'], $anchor_matches, PREG_PATTERN_ORDER ) ) + return; + + $i = 0; + $search = "#[\s]+rel=(\"|')(.*?)wp-att-(\d+)\\1#i"; + foreach ( $anchor_matches[0] as $anchor ) { + if ( 0 == preg_match( $search, $anchor, $id_matches ) ) + continue; + + $id = (int) $id_matches[3]; + + // While we have the attachment ID, let's adopt any orphans. + $attachment = & get_post( $id, ARRAY_A ); + if ( ! empty( $attachment) && ! is_object( get_post( $attachment['post_parent'] ) ) ) { + $attachment['post_parent'] = $post_ID; + // Escape data pulled from DB. + $attachment = add_magic_quotes( $attachment); + wp_update_post( $attachment); + } + + $post_search[$i] = $anchor; + $post_replace[$i] = preg_replace( "#href=(\"|')[^'\"]*\\1#e", "stripslashes( 'href=\\1' ).get_attachment_link( $id ).stripslashes( '\\1' )", $anchor ); + ++$i; + } + + $post['post_content'] = str_replace( $post_search, $post_replace, $post['post_content'] ); + + // Escape data pulled from DB. + $post = add_magic_quotes( $post); + + return wp_update_post( $post); +} + +/** + * Move child posts to a new parent. + * + * @since unknown + * @access private + * + * @param unknown_type $old_ID + * @param unknown_type $new_ID + * @return unknown + */ +function _relocate_children( $old_ID, $new_ID ) { + global $wpdb; + $old_ID = (int) $old_ID; + $new_ID = (int) $new_ID; + return $wpdb->update($wpdb->posts, array('post_parent' => $new_ID), array('post_parent' => $old_ID) ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $type + * @return unknown + */ +function get_available_post_statuses($type = 'post') { + $stati = wp_count_posts($type); + + return array_keys(get_object_vars($stati)); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $q + * @return unknown + */ +function wp_edit_posts_query( $q = false ) { + if ( false === $q ) + $q = $_GET; + $q['m'] = isset($q['m']) ? (int) $q['m'] : 0; + $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0; + $post_stati = array( // array( adj, noun ) + 'publish' => array(_x('Published', 'post'), __('Published posts'), _n_noop('Published (%s)', 'Published (%s)')), + 'future' => array(_x('Scheduled', 'post'), __('Scheduled posts'), _n_noop('Scheduled (%s)', 'Scheduled (%s)')), + 'pending' => array(_x('Pending Review', 'post'), __('Pending posts'), _n_noop('Pending Review (%s)', 'Pending Review (%s)')), + 'draft' => array(_x('Draft', 'post'), _x('Drafts', 'manage posts header'), _n_noop('Draft (%s)', 'Drafts (%s)')), + 'private' => array(_x('Private', 'post'), __('Private posts'), _n_noop('Private (%s)', 'Private (%s)')), + ); + + $post_stati = apply_filters('post_stati', $post_stati); + + $avail_post_stati = get_available_post_statuses('post'); + + $post_status_q = ''; + if ( isset($q['post_status']) && in_array( $q['post_status'], array_keys($post_stati) ) ) { + $post_status_q = '&post_status=' . $q['post_status']; + $post_status_q .= '&perm=readable'; + } + + if ( isset($q['post_status']) && 'pending' === $q['post_status'] ) { + $order = 'ASC'; + $orderby = 'modified'; + } elseif ( isset($q['post_status']) && 'draft' === $q['post_status'] ) { + $order = 'DESC'; + $orderby = 'modified'; + } else { + $order = 'DESC'; + $orderby = 'date'; + } + + $posts_per_page = get_user_option('edit_per_page'); + if ( empty($posts_per_page) ) + $posts_per_page = 15; + $posts_per_page = apply_filters('edit_posts_per_page', $posts_per_page); + + wp("post_type=post&$post_status_q&posts_per_page=$posts_per_page&order=$order&orderby=$orderby"); + + return array($post_stati, $avail_post_stati); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $type + * @return unknown + */ +function get_available_post_mime_types($type = 'attachment') { + global $wpdb; + + $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type)); + return $types; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $q + * @return unknown + */ +function wp_edit_attachments_query( $q = false ) { + if ( false === $q ) + $q = $_GET; + + $q['m'] = isset( $q['m'] ) ? (int) $q['m'] : 0; + $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0; + $q['post_type'] = 'attachment'; + $q['post_status'] = 'any'; + $media_per_page = get_user_option('upload_per_page'); + if ( empty($media_per_page) ) + $media_per_page = 20; + $q['posts_per_page'] = $media_per_page; + $post_mime_types = array( // array( adj, noun ) + 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image (%s)', 'Images (%s)')), + 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio (%s)', 'Audio (%s)')), + 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video (%s)', 'Video (%s)')), + ); + $post_mime_types = apply_filters('post_mime_types', $post_mime_types); + + $avail_post_mime_types = get_available_post_mime_types('attachment'); + + if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) ) + unset($q['post_mime_type']); + + wp($q); + + return array($post_mime_types, $avail_post_mime_types); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $id + * @param unknown_type $page + * @return unknown + */ +function postbox_classes( $id, $page ) { + if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) + return ''; + $current_user = wp_get_current_user(); + if ( $closed = get_user_option('closedpostboxes_'.$page, 0, false ) ) { + if ( !is_array( $closed ) ) return ''; + return in_array( $id, $closed )? 'closed' : ''; + } else { + return ''; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $id + * @param unknown_type $title + * @param unknown_type $name + * @return unknown + */ +function get_sample_permalink($id, $title=null, $name = null) { + $post = &get_post($id); + if (!$post->ID) { + return array('', ''); + } + $original_status = $post->post_status; + $original_date = $post->post_date; + $original_name = $post->post_name; + + // Hack: get_permalink would return ugly permalink for + // drafts, so we will fake, that our post is published + if (in_array($post->post_status, array('draft', 'pending'))) { + $post->post_status = 'publish'; + $post->post_name = sanitize_title($post->post_name? $post->post_name : $post->post_title, $post->ID); + } + + $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent); + + // If the user wants to set a new name -- override the current one + // Note: if empty name is supplied -- use the title instead, see #6072 + if (!is_null($name)) { + $post->post_name = sanitize_title($name? $name : $title, $post->ID); + } + + $post->filter = 'sample'; + + $permalink = get_permalink($post, true); + + // Handle page hierarchy + if ( 'page' == $post->post_type ) { + $uri = get_page_uri($post->ID); + $uri = untrailingslashit($uri); + $uri = strrev( stristr( strrev( $uri ), '/' ) ); + $uri = untrailingslashit($uri); + if ( !empty($uri) ) + $uri .='/'; + $permalink = str_replace('%pagename%', "${uri}%pagename%", $permalink); + } + + $permalink = array($permalink, apply_filters('editable_slug', $post->post_name)); + $post->post_status = $original_status; + $post->post_date = $original_date; + $post->post_name = $original_name; + unset($post->filter); + + return $permalink; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $id + * @param unknown_type $new_title + * @param unknown_type $new_slug + * @return unknown + */ +function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) { + $post = &get_post($id); + list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug); + if ( 'publish' == $post->post_status ) + $view_post = 'post' == $post->post_type ? __('View Post') : __('View Page'); + + if ( false === strpos($permalink, '%postname%') && false === strpos($permalink, '%pagename%') ) { + $return = '' . __('Permalink:') . "\n" . '' . $permalink . "\n"; + if ( current_user_can( 'manage_options' ) ) + $return .= '' . __('Change Permalinks') . "\n"; + if ( isset($view_post) ) + $return .= "$view_post\n"; + + return $return; + } + + $title = __('Click to edit this part of the permalink'); + if (function_exists('mb_strlen')) { + if (mb_strlen($post_name) > 30) { + $post_name_abridged = mb_substr($post_name, 0, 14). '…' . mb_substr($post_name, -14); + } else { + $post_name_abridged = $post_name; + } + } else { + if (strlen($post_name) > 30) { + $post_name_abridged = substr($post_name, 0, 14). '…' . substr($post_name, -14); + } else { + $post_name_abridged = $post_name; + } + } + + $post_name_html = '' . $post_name_abridged . ''; + $display_link = str_replace(array('%pagename%','%postname%'), $post_name_html, $permalink); + $view_link = str_replace(array('%pagename%','%postname%'), $post_name, $permalink); + $return = '' . __('Permalink:') . "\n" . '' . $display_link . "\n"; + $return .= '' . __('Edit') . "\n"; + $return .= '' . $post_name . "\n"; + if ( isset($view_post) ) + $return .= "$view_post\n"; + + return $return; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post_id + * @return bool|int False: not locked or locked by current user. Int: user ID of user with lock. + */ +function wp_check_post_lock( $post_id ) { + global $current_user; + + if ( !$post = get_post( $post_id ) ) + return false; + + $lock = get_post_meta( $post->ID, '_edit_lock', true ); + $last = get_post_meta( $post->ID, '_edit_last', true ); + + $time_window = apply_filters( 'wp_check_post_lock_window', AUTOSAVE_INTERVAL * 2 ); + + if ( $lock && $lock > time() - $time_window && $last != $current_user->ID ) + return $last; + return false; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post_id + * @return unknown + */ +function wp_set_post_lock( $post_id ) { + global $current_user; + if ( !$post = get_post( $post_id ) ) + return false; + if ( !$current_user || !$current_user->ID ) + return false; + + $now = time(); + + if ( !add_post_meta( $post->ID, '_edit_lock', $now, true ) ) + update_post_meta( $post->ID, '_edit_lock', $now ); + if ( !add_post_meta( $post->ID, '_edit_last', $current_user->ID, true ) ) + update_post_meta( $post->ID, '_edit_last', $current_user->ID ); +} + +/** + * Creates autosave data for the specified post from $_POST data. + * + * @package WordPress + * @subpackage Post_Revisions + * @since 2.6.0 + * + * @uses _wp_translate_postdata() + * @uses _wp_post_revision_fields() + */ +function wp_create_post_autosave( $post_id ) { + $translated = _wp_translate_postdata( true ); + if ( is_wp_error( $translated ) ) + return $translated; + + // Only store one autosave. If there is already an autosave, overwrite it. + if ( $old_autosave = wp_get_post_autosave( $post_id ) ) { + $new_autosave = _wp_post_revision_fields( $_POST, true ); + $new_autosave['ID'] = $old_autosave->ID; + return wp_update_post( $new_autosave ); + } + + // _wp_put_post_revision() expects unescaped. + $_POST = stripslashes_deep($_POST); + + // Otherwise create the new autosave as a special post revision + return _wp_put_post_revision( $_POST, true ); +} + +/** + * Save draft or manually autosave for showing preview. + * + * @package WordPress + * @since 2.7 + * + * @uses wp_write_post() + * @uses edit_post() + * @uses get_post() + * @uses current_user_can() + * @uses wp_create_post_autosave() + * + * @return str URL to redirect to show the preview + */ +function post_preview() { + + $post_ID = (int) $_POST['post_ID']; + if ( $post_ID < 1 ) + wp_die( __('Preview not available. Please save as a draft first.') ); + + if ( isset($_POST['catslist']) ) + $_POST['post_category'] = explode(",", $_POST['catslist']); + + if ( isset($_POST['tags_input']) ) + $_POST['tags_input'] = explode(",", $_POST['tags_input']); + + if ( $_POST['post_type'] == 'page' || empty($_POST['post_category']) ) + unset($_POST['post_category']); + + $_POST['ID'] = $post_ID; + $post = get_post($post_ID); + + if ( 'page' == $post->post_type ) { + if ( !current_user_can('edit_page', $post_ID) ) + wp_die(__('You are not allowed to edit this page.')); + } else { + if ( !current_user_can('edit_post', $post_ID) ) + wp_die(__('You are not allowed to edit this post.')); + } + + if ( 'draft' == $post->post_status ) { + $id = edit_post(); + } else { // Non drafts are not overwritten. The autosave is stored in a special post revision. + $id = wp_create_post_autosave( $post->ID ); + if ( ! is_wp_error($id) ) + $id = $post->ID; + } + + if ( is_wp_error($id) ) + wp_die( $id->get_error_message() ); + + if ( $_POST['post_status'] == 'draft' ) { + $url = add_query_arg( 'preview', 'true', get_permalink($id) ); + } else { + $nonce = wp_create_nonce('post_preview_' . $id); + $url = add_query_arg( array( 'preview' => 'true', 'preview_id' => $id, 'preview_nonce' => $nonce ), get_permalink($id) ); + } + + return $url; +} + +/** + * Adds the TinyMCE editor used on the Write and Edit screens. + * + * @package WordPress + * @since 2.7 + * + * TinyMCE is loaded separately from other Javascript by using wp-tinymce.php. It outputs concatenated + * and optionaly pre-compressed version of the core and all default plugins. Additional plugins are loaded + * directly by TinyMCE using non-blocking method. Custom plugins can be refreshed by adding a query string + * to the URL when queueing them with the mce_external_plugins filter. + * + * @param bool $teeny optional Output a trimmed down version used in Press This. + */ +function wp_tiny_mce( $teeny = false ) { + global $concatenate_scripts, $compress_scripts, $tinymce_version; + + if ( ! user_can_richedit() ) + return; + + $baseurl = includes_url('js/tinymce'); + + $mce_locale = ( '' == get_locale() ) ? 'en' : strtolower( substr(get_locale(), 0, 2) ); // only ISO 639-1 + + /* + The following filter allows localization scripts to change the languages displayed in the spellchecker's drop-down menu. + By default it uses Google's spellchecker API, but can be configured to use PSpell/ASpell if installed on the server. + The + sign marks the default language. More information: + http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker + */ + $mce_spellchecker_languages = apply_filters('mce_spellchecker_languages', '+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv'); + + if ( $teeny ) { + $plugins = apply_filters( 'teeny_mce_plugins', array('safari', 'inlinepopups', 'media', 'autosave', 'fullscreen') ); + $ext_plugins = ''; + } else { + $plugins = array( 'safari', 'inlinepopups', 'spellchecker', 'paste', 'wordpress', 'media', 'fullscreen', 'wpeditimage', 'wpgallery', 'tabfocus' ); + + /* + The following filter takes an associative array of external plugins for TinyMCE in the form 'plugin_name' => 'url'. + It adds the plugin's name to TinyMCE's plugins init and the call to PluginManager to load the plugin. + The url should be absolute and should include the js file name to be loaded. Example: + array( 'myplugin' => 'http://my-site.com/wp-content/plugins/myfolder/mce_plugin.js' ) + If the plugin uses a button, it should be added with one of the "$mce_buttons" filters. + */ + $mce_external_plugins = apply_filters('mce_external_plugins', array()); + + $ext_plugins = ''; + if ( ! empty($mce_external_plugins) ) { + + /* + The following filter loads external language files for TinyMCE plugins. + It takes an associative array 'plugin_name' => 'path', where path is the + include path to the file. The language file should follow the same format as + /tinymce/langs/wp-langs.php and should define a variable $strings that + holds all translated strings. + When this filter is not used, the function will try to load {mce_locale}.js. + If that is not found, en.js will be tried next. + */ + $mce_external_languages = apply_filters('mce_external_languages', array()); + + $loaded_langs = array(); + $strings = ''; + + if ( ! empty($mce_external_languages) ) { + foreach ( $mce_external_languages as $name => $path ) { + if ( @is_file($path) && @is_readable($path) ) { + include_once($path); + $ext_plugins .= $strings . "\n"; + $loaded_langs[] = $name; + } + } + } + + foreach ( $mce_external_plugins as $name => $url ) { + + if ( is_ssl() ) $url = str_replace('http://', 'https://', $url); + + $plugins[] = '-' . $name; + + $plugurl = dirname($url); + $strings = $str1 = $str2 = ''; + if ( ! in_array($name, $loaded_langs) ) { + $path = str_replace( WP_PLUGIN_URL, '', $plugurl ); + $path = WP_PLUGIN_DIR . $path . '/langs/'; + + if ( function_exists('realpath') ) + $path = trailingslashit( realpath($path) ); + + if ( @is_file($path . $mce_locale . '.js') ) + $strings .= @file_get_contents($path . $mce_locale . '.js') . "\n"; + + if ( @is_file($path . $mce_locale . '_dlg.js') ) + $strings .= @file_get_contents($path . $mce_locale . '_dlg.js') . "\n"; + + if ( 'en' != $mce_locale && empty($strings) ) { + if ( @is_file($path . 'en.js') ) { + $str1 = @file_get_contents($path . 'en.js'); + $strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str1, 1 ) . "\n"; + } + + if ( @is_file($path . 'en_dlg.js') ) { + $str2 = @file_get_contents($path . 'en_dlg.js'); + $strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str2, 1 ) . "\n"; + } + } + + if ( ! empty($strings) ) + $ext_plugins .= "\n" . $strings . "\n"; + } + + $ext_plugins .= 'tinyMCEPreInit.load_ext("' . $plugurl . '", "' . $mce_locale . '");' . "\n"; + $ext_plugins .= 'tinymce.PluginManager.load("' . $name . '", "' . $url . '");' . "\n"; + } + } + } + + $plugins = implode($plugins, ','); + + if ( $teeny ) { + $mce_buttons = apply_filters( 'teeny_mce_buttons', array('bold, italic, underline, blockquote, separator, strikethrough, bullist, numlist,justifyleft, justifycenter, justifyright, undo, redo, link, unlink, fullscreen') ); + $mce_buttons = implode($mce_buttons, ','); + $mce_buttons_2 = $mce_buttons_3 = $mce_buttons_4 = ''; + } else { + $mce_buttons = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', '|', 'bullist', 'numlist', 'blockquote', '|', 'justifyleft', 'justifycenter', 'justifyright', '|', 'link', 'unlink', 'wp_more', '|', 'spellchecker', 'fullscreen', 'wp_adv' )); + $mce_buttons = implode($mce_buttons, ','); + + $mce_buttons_2 = apply_filters('mce_buttons_2', array('formatselect', 'underline', 'justifyfull', 'forecolor', '|', 'pastetext', 'pasteword', 'removeformat', '|', 'media', 'charmap', '|', 'outdent', 'indent', '|', 'undo', 'redo', 'wp_help' )); + $mce_buttons_2 = implode($mce_buttons_2, ','); + + $mce_buttons_3 = apply_filters('mce_buttons_3', array()); + $mce_buttons_3 = implode($mce_buttons_3, ','); + + $mce_buttons_4 = apply_filters('mce_buttons_4', array()); + $mce_buttons_4 = implode($mce_buttons_4, ','); + } + $no_captions = ( apply_filters( 'disable_captions', '' ) ) ? true : false; + + // TinyMCE init settings + $initArray = array ( + 'mode' => 'specific_textareas', + 'editor_selector' => 'theEditor', + 'width' => '100%', + 'theme' => 'advanced', + 'skin' => 'wp_theme', + 'theme_advanced_buttons1' => "$mce_buttons", + 'theme_advanced_buttons2' => "$mce_buttons_2", + 'theme_advanced_buttons3' => "$mce_buttons_3", + 'theme_advanced_buttons4' => "$mce_buttons_4", + 'language' => "$mce_locale", + 'spellchecker_languages' => "$mce_spellchecker_languages", + 'theme_advanced_toolbar_location' => 'top', + 'theme_advanced_toolbar_align' => 'left', + 'theme_advanced_statusbar_location' => 'bottom', + 'theme_advanced_resizing' => true, + 'theme_advanced_resize_horizontal' => false, + 'dialog_type' => 'modal', + 'relative_urls' => false, + 'remove_script_host' => false, + 'convert_urls' => false, + 'apply_source_formatting' => false, + 'remove_linebreaks' => true, + 'gecko_spellcheck' => true, + 'entities' => '38,amp,60,lt,62,gt', + 'accessibility_focus' => true, + 'tabfocus_elements' => 'major-publishing-actions', + 'media_strict' => false, + 'save_callback' => 'switchEditors.saveCallback', + 'wpeditimage_disable_captions' => $no_captions, + 'plugins' => "$plugins" + ); + + $mce_css = trim(apply_filters('mce_css', ''), ' ,'); + + if ( ! empty($mce_css) ) + $initArray['content_css'] = "$mce_css"; + + // For people who really REALLY know what they're doing with TinyMCE + // You can modify initArray to add, remove, change elements of the config before tinyMCE.init + // Setting "valid_elements", "invalid_elements" and "extended_valid_elements" can be done through "tiny_mce_before_init". + // Best is to use the default cleanup by not specifying valid_elements, as TinyMCE contains full set of XHTML 1.0. + if ( $teeny ) { + $initArray = apply_filters('teeny_mce_before_init', $initArray); + } else { + $initArray = apply_filters('tiny_mce_before_init', $initArray); + } + + if ( empty($initArray['theme_advanced_buttons3']) && !empty($initArray['theme_advanced_buttons4']) ) { + $initArray['theme_advanced_buttons3'] = $initArray['theme_advanced_buttons4']; + $initArray['theme_advanced_buttons4'] = ''; + } + + if ( ! isset($concatenate_scripts) ) + script_concat_settings(); + + $language = $initArray['language']; + $zip = $compress_scripts ? 1 : 0; + + /** + * Deprecated + * + * The tiny_mce_version filter is not needed since external plugins are loaded directly by TinyMCE. + * These plugins can be refreshed by appending query string to the URL passed to mce_external_plugins filter. + * If the plugin has a popup dialog, a query string can be added to the button action that opens it (in the plugin's code). + */ + $version = apply_filters('tiny_mce_version', ''); + $version = 'ver=' . $tinymce_version . $version; + + if ( 'en' != $language ) + include_once(ABSPATH . WPINC . '/js/tinymce/langs/wp-langs.php'); + + $mce_options = ''; + foreach ( $initArray as $k => $v ) + $mce_options .= $k . ':"' . $v . '", '; + + $mce_options = rtrim( trim($mce_options), '\n\r,' ); ?> + + + +\n"; + else + echo "\n"; + + if ( 'en' != $language && isset($lang) ) + echo "\n"; + else + echo "\n"; +?> + + +has_cap( 'collation' ) ) { + if ( ! empty($wpdb->charset) ) + $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; + if ( ! empty($wpdb->collate) ) + $charset_collate .= " COLLATE $wpdb->collate"; +} + +/** Create WordPress database tables SQL */ +$wp_queries = "CREATE TABLE $wpdb->terms ( + term_id bigint(20) unsigned NOT NULL auto_increment, + name varchar(200) NOT NULL default '', + slug varchar(200) NOT NULL default '', + term_group bigint(10) NOT NULL default 0, + PRIMARY KEY (term_id), + UNIQUE KEY slug (slug), + KEY name (name) +) $charset_collate; +CREATE TABLE $wpdb->term_taxonomy ( + term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, + term_id bigint(20) unsigned NOT NULL default 0, + taxonomy varchar(32) NOT NULL default '', + description longtext NOT NULL, + parent bigint(20) unsigned NOT NULL default 0, + count bigint(20) NOT NULL default 0, + PRIMARY KEY (term_taxonomy_id), + UNIQUE KEY term_id_taxonomy (term_id,taxonomy), + KEY taxonomy (taxonomy) +) $charset_collate; +CREATE TABLE $wpdb->term_relationships ( + object_id bigint(20) unsigned NOT NULL default 0, + term_taxonomy_id bigint(20) unsigned NOT NULL default 0, + term_order int(11) NOT NULL default 0, + PRIMARY KEY (object_id,term_taxonomy_id), + KEY term_taxonomy_id (term_taxonomy_id) +) $charset_collate; +CREATE TABLE $wpdb->comments ( + comment_ID bigint(20) unsigned NOT NULL auto_increment, + comment_post_ID bigint(20) unsigned NOT NULL default '0', + comment_author tinytext NOT NULL, + comment_author_email varchar(100) NOT NULL default '', + comment_author_url varchar(200) NOT NULL default '', + comment_author_IP varchar(100) NOT NULL default '', + comment_date datetime NOT NULL default '0000-00-00 00:00:00', + comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', + comment_content text NOT NULL, + comment_karma int(11) NOT NULL default '0', + comment_approved varchar(20) NOT NULL default '1', + comment_agent varchar(255) NOT NULL default '', + comment_type varchar(20) NOT NULL default '', + comment_parent bigint(20) unsigned NOT NULL default '0', + user_id bigint(20) unsigned NOT NULL default '0', + PRIMARY KEY (comment_ID), + KEY comment_approved (comment_approved), + KEY comment_post_ID (comment_post_ID), + KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), + KEY comment_date_gmt (comment_date_gmt) +) $charset_collate; +CREATE TABLE $wpdb->links ( + link_id bigint(20) unsigned NOT NULL auto_increment, + link_url varchar(255) NOT NULL default '', + link_name varchar(255) NOT NULL default '', + link_image varchar(255) NOT NULL default '', + link_target varchar(25) NOT NULL default '', + link_description varchar(255) NOT NULL default '', + link_visible varchar(20) NOT NULL default 'Y', + link_owner bigint(20) unsigned NOT NULL default '1', + link_rating int(11) NOT NULL default '0', + link_updated datetime NOT NULL default '0000-00-00 00:00:00', + link_rel varchar(255) NOT NULL default '', + link_notes mediumtext NOT NULL, + link_rss varchar(255) NOT NULL default '', + PRIMARY KEY (link_id), + KEY link_visible (link_visible) +) $charset_collate; +CREATE TABLE $wpdb->options ( + option_id bigint(20) unsigned NOT NULL auto_increment, + blog_id int(11) NOT NULL default '0', + option_name varchar(64) NOT NULL default '', + option_value longtext NOT NULL, + autoload varchar(20) NOT NULL default 'yes', + PRIMARY KEY (option_id,blog_id,option_name), + KEY option_name (option_name) +) $charset_collate; +CREATE TABLE $wpdb->postmeta ( + meta_id bigint(20) unsigned NOT NULL auto_increment, + post_id bigint(20) unsigned NOT NULL default '0', + meta_key varchar(255) default NULL, + meta_value longtext, + PRIMARY KEY (meta_id), + KEY post_id (post_id), + KEY meta_key (meta_key) +) $charset_collate; +CREATE TABLE $wpdb->posts ( + ID bigint(20) unsigned NOT NULL auto_increment, + post_author bigint(20) unsigned NOT NULL default '0', + post_date datetime NOT NULL default '0000-00-00 00:00:00', + post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', + post_content longtext NOT NULL, + post_title text NOT NULL, + post_excerpt text NOT NULL, + post_status varchar(20) NOT NULL default 'publish', + comment_status varchar(20) NOT NULL default 'open', + ping_status varchar(20) NOT NULL default 'open', + post_password varchar(20) NOT NULL default '', + post_name varchar(200) NOT NULL default '', + to_ping text NOT NULL, + pinged text NOT NULL, + post_modified datetime NOT NULL default '0000-00-00 00:00:00', + post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', + post_content_filtered text NOT NULL, + post_parent bigint(20) unsigned NOT NULL default '0', + guid varchar(255) NOT NULL default '', + menu_order int(11) NOT NULL default '0', + post_type varchar(20) NOT NULL default 'post', + post_mime_type varchar(100) NOT NULL default '', + comment_count bigint(20) NOT NULL default '0', + PRIMARY KEY (ID), + KEY post_name (post_name), + KEY type_status_date (post_type,post_status,post_date,ID), + KEY post_parent (post_parent) +) $charset_collate; +CREATE TABLE $wpdb->users ( + ID bigint(20) unsigned NOT NULL auto_increment, + user_login varchar(60) NOT NULL default '', + user_pass varchar(64) NOT NULL default '', + user_nicename varchar(50) NOT NULL default '', + user_email varchar(100) NOT NULL default '', + user_url varchar(100) NOT NULL default '', + user_registered datetime NOT NULL default '0000-00-00 00:00:00', + user_activation_key varchar(60) NOT NULL default '', + user_status int(11) NOT NULL default '0', + display_name varchar(250) NOT NULL default '', + PRIMARY KEY (ID), + KEY user_login_key (user_login), + KEY user_nicename (user_nicename) +) $charset_collate; +CREATE TABLE $wpdb->usermeta ( + umeta_id bigint(20) unsigned NOT NULL auto_increment, + user_id bigint(20) unsigned NOT NULL default '0', + meta_key varchar(255) default NULL, + meta_value longtext, + PRIMARY KEY (umeta_id), + KEY user_id (user_id), + KEY meta_key (meta_key) +) $charset_collate;"; + +/** + * Create WordPress options and set the default values. + * + * @since 1.5.0 + * @uses $wpdb + * @uses $wp_db_version + */ +function populate_options() { + global $wpdb, $wp_db_version; + + $guessurl = wp_guess_url(); + + do_action('populate_options'); + + if ( ini_get('safe_mode') ) { + // Safe mode screws up mkdir(), so we must use a flat structure. + $uploads_use_yearmonth_folders = 0; + $upload_path = WP_CONTENT_DIR; + } else { + $uploads_use_yearmonth_folders = 1; + $upload_path = WP_CONTENT_DIR . '/uploads'; + } + + $options = array( + 'siteurl' => $guessurl, + 'blogname' => __('My Blog'), + 'blogdescription' => __('Just another WordPress weblog'), + 'users_can_register' => 0, + 'admin_email' => 'you@example.com', + 'start_of_week' => 1, + 'use_balanceTags' => 0, + 'use_smilies' => 1, + 'require_name_email' => 1, + 'comments_notify' => 1, + 'posts_per_rss' => 10, + 'rss_excerpt_length' => 50, + 'rss_use_excerpt' => 0, + 'mailserver_url' => 'mail.example.com', + 'mailserver_login' => 'login@example.com', + 'mailserver_pass' => 'password', + 'mailserver_port' => 110, + 'default_category' => 1, + 'default_comment_status' => 'open', + 'default_ping_status' => 'open', + 'default_pingback_flag' => 1, + 'default_post_edit_rows' => 10, + 'posts_per_page' => 10, + /* translators: default date format, see http://php.net/date */ + 'date_format' => __('F j, Y'), + /* translators: default time format, see http://php.net/date */ + 'time_format' => __('g:i a'), + /* translators: links last updated date format, see http://php.net/date */ + 'links_updated_date_format' => __('F j, Y g:i a'), + 'links_recently_updated_prepend' => '', + 'links_recently_updated_append' => '', + 'links_recently_updated_time' => 120, + 'comment_moderation' => 0, + 'moderation_notify' => 1, + 'permalink_structure' => '', + 'gzipcompression' => 0, + 'hack_file' => 0, + 'blog_charset' => 'UTF-8', + 'moderation_keys' => '', + 'active_plugins' => array(), + 'home' => $guessurl, + 'category_base' => '', + 'ping_sites' => 'http://rpc.pingomatic.com/', + 'advanced_edit' => 0, + 'comment_max_links' => 2, + 'gmt_offset' => date('Z') / 3600, + + // 1.5 + 'default_email_category' => 1, + 'recently_edited' => '', + 'use_linksupdate' => 0, + 'template' => 'default', + 'stylesheet' => 'default', + 'comment_whitelist' => 1, + 'blacklist_keys' => '', + 'comment_registration' => 0, + 'rss_language' => 'en', + 'html_type' => 'text/html', + + // 1.5.1 + 'use_trackback' => 0, + + // 2.0 + 'default_role' => 'subscriber', + 'db_version' => $wp_db_version, + + // 2.0.1 + 'uploads_use_yearmonth_folders' => $uploads_use_yearmonth_folders, + 'upload_path' => $upload_path, + + // 2.0.3 + 'secret' => wp_generate_password(64), + + // 2.1 + 'blog_public' => '1', + 'default_link_category' => 2, + 'show_on_front' => 'posts', + + // 2.2 + 'tag_base' => '', + + // 2.5 + 'show_avatars' => '1', + 'avatar_rating' => 'G', + 'upload_url_path' => '', + 'thumbnail_size_w' => 150, + 'thumbnail_size_h' => 150, + 'thumbnail_crop' => 1, + 'medium_size_w' => 300, + 'medium_size_h' => 300, + + // 2.6 + 'avatar_default' => 'mystery', + 'enable_app' => 0, + 'enable_xmlrpc' => 0, + + // 2.7 + 'large_size_w' => 1024, + 'large_size_h' => 1024, + 'image_default_link_type' => 'file', + 'image_default_size' => '', + 'image_default_align' => '', + 'close_comments_for_old_posts' => 0, + 'close_comments_days_old' => 14, + 'thread_comments' => 0, + 'thread_comments_depth' => 5, + 'page_comments' => 1, + 'comments_per_page' => 50, + 'default_comments_page' => 'newest', + 'comment_order' => 'asc', + 'sticky_posts' => array(), + 'widget_categories' => array(), + 'widget_text' => array(), + 'widget_rss' => array(), + + // 2.8 + 'timezone_string' => '' + ); + + // Set autoload to no for these options + $fat_options = array( 'moderation_keys', 'recently_edited', 'blacklist_keys' ); + + $existing_options = $wpdb->get_col("SELECT option_name FROM $wpdb->options"); + + $insert = ''; + foreach ( $options as $option => $value ) { + if ( in_array($option, $existing_options) ) + continue; + if ( in_array($option, $fat_options) ) + $autoload = 'no'; + else + $autoload = 'yes'; + + $option = $wpdb->escape($option); + if ( is_array($value) ) + $value = serialize($value); + $value = $wpdb->escape($value); + if ( !empty($insert) ) + $insert .= ', '; + $insert .= "('$option', '$value', '$autoload')"; + } + + if ( !empty($insert) ) + $wpdb->query("INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES " . $insert); + + // in case it is set, but blank, update "home" + if ( !__get_option('home') ) update_option('home', $guessurl); + + // Delete unused options + $unusedoptions = array ('blodotgsping_url', 'bodyterminator', 'emailtestonly', 'phoneemail_separator', 'smilies_directory', 'subjectprefix', 'use_bbcode', 'use_blodotgsping', 'use_phoneemail', 'use_quicktags', 'use_weblogsping', 'weblogs_cache_file', 'use_preview', 'use_htmltrans', 'smilies_directory', 'fileupload_allowedusers', 'use_phoneemail', 'default_post_status', 'default_post_category', 'archive_mode', 'time_difference', 'links_minadminlevel', 'links_use_adminlevels', 'links_rating_type', 'links_rating_char', 'links_rating_ignore_zero', 'links_rating_single_image', 'links_rating_image0', 'links_rating_image1', 'links_rating_image2', 'links_rating_image3', 'links_rating_image4', 'links_rating_image5', 'links_rating_image6', 'links_rating_image7', 'links_rating_image8', 'links_rating_image9', 'weblogs_cacheminutes', 'comment_allowed_tags', 'search_engine_friendly_urls', 'default_geourl_lat', 'default_geourl_lon', 'use_default_geourl', 'weblogs_xml_url', 'new_users_can_blog', '_wpnonce', '_wp_http_referer', 'Update', 'action', 'rich_editing', 'autosave_interval', 'deactivated_plugins', 'can_compress_scripts', + 'page_uris', 'rewrite_rules', 'update_core', 'update_plugins', 'update_themes', 'doing_cron', 'random_seed'); + foreach ($unusedoptions as $option) + delete_option($option); +} + +/** + * Execute WordPress role creation for the various WordPress versions. + * + * @since 2.0.0 + */ +function populate_roles() { + populate_roles_160(); + populate_roles_210(); + populate_roles_230(); + populate_roles_250(); + populate_roles_260(); + populate_roles_270(); + populate_roles_280(); +} + +/** + * Create the roles for WordPress 2.0 + * + * @since 2.0.0 + */ +function populate_roles_160() { + // Add roles + + // Dummy gettext calls to get strings in the catalog. + /* translators: user role */ + _x('Administrator', 'User role'); + /* translators: user role */ + _x('Editor', 'User role'); + /* translators: user role */ + _x('Author', 'User role'); + /* translators: user role */ + _x('Contributor', 'User role'); + /* translators: user role */ + _x('Subscriber', 'User role'); + + add_role('administrator', 'Administrator'); + add_role('editor', 'Editor'); + add_role('author', 'Author'); + add_role('contributor', 'Contributor'); + add_role('subscriber', 'Subscriber'); + + // Add caps for Administrator role + $role =& get_role('administrator'); + $role->add_cap('switch_themes'); + $role->add_cap('edit_themes'); + $role->add_cap('activate_plugins'); + $role->add_cap('edit_plugins'); + $role->add_cap('edit_users'); + $role->add_cap('edit_files'); + $role->add_cap('manage_options'); + $role->add_cap('moderate_comments'); + $role->add_cap('manage_categories'); + $role->add_cap('manage_links'); + $role->add_cap('upload_files'); + $role->add_cap('import'); + $role->add_cap('unfiltered_html'); + $role->add_cap('edit_posts'); + $role->add_cap('edit_others_posts'); + $role->add_cap('edit_published_posts'); + $role->add_cap('publish_posts'); + $role->add_cap('edit_pages'); + $role->add_cap('read'); + $role->add_cap('level_10'); + $role->add_cap('level_9'); + $role->add_cap('level_8'); + $role->add_cap('level_7'); + $role->add_cap('level_6'); + $role->add_cap('level_5'); + $role->add_cap('level_4'); + $role->add_cap('level_3'); + $role->add_cap('level_2'); + $role->add_cap('level_1'); + $role->add_cap('level_0'); + + // Add caps for Editor role + $role =& get_role('editor'); + $role->add_cap('moderate_comments'); + $role->add_cap('manage_categories'); + $role->add_cap('manage_links'); + $role->add_cap('upload_files'); + $role->add_cap('unfiltered_html'); + $role->add_cap('edit_posts'); + $role->add_cap('edit_others_posts'); + $role->add_cap('edit_published_posts'); + $role->add_cap('publish_posts'); + $role->add_cap('edit_pages'); + $role->add_cap('read'); + $role->add_cap('level_7'); + $role->add_cap('level_6'); + $role->add_cap('level_5'); + $role->add_cap('level_4'); + $role->add_cap('level_3'); + $role->add_cap('level_2'); + $role->add_cap('level_1'); + $role->add_cap('level_0'); + + // Add caps for Author role + $role =& get_role('author'); + $role->add_cap('upload_files'); + $role->add_cap('edit_posts'); + $role->add_cap('edit_published_posts'); + $role->add_cap('publish_posts'); + $role->add_cap('read'); + $role->add_cap('level_2'); + $role->add_cap('level_1'); + $role->add_cap('level_0'); + + // Add caps for Contributor role + $role =& get_role('contributor'); + $role->add_cap('edit_posts'); + $role->add_cap('read'); + $role->add_cap('level_1'); + $role->add_cap('level_0'); + + // Add caps for Subscriber role + $role =& get_role('subscriber'); + $role->add_cap('read'); + $role->add_cap('level_0'); +} + +/** + * Create and modify WordPress roles for WordPress 2.1. + * + * @since 2.1.0 + */ +function populate_roles_210() { + $roles = array('administrator', 'editor'); + foreach ($roles as $role) { + $role =& get_role($role); + if ( empty($role) ) + continue; + + $role->add_cap('edit_others_pages'); + $role->add_cap('edit_published_pages'); + $role->add_cap('publish_pages'); + $role->add_cap('delete_pages'); + $role->add_cap('delete_others_pages'); + $role->add_cap('delete_published_pages'); + $role->add_cap('delete_posts'); + $role->add_cap('delete_others_posts'); + $role->add_cap('delete_published_posts'); + $role->add_cap('delete_private_posts'); + $role->add_cap('edit_private_posts'); + $role->add_cap('read_private_posts'); + $role->add_cap('delete_private_pages'); + $role->add_cap('edit_private_pages'); + $role->add_cap('read_private_pages'); + } + + $role =& get_role('administrator'); + if ( ! empty($role) ) { + $role->add_cap('delete_users'); + $role->add_cap('create_users'); + } + + $role =& get_role('author'); + if ( ! empty($role) ) { + $role->add_cap('delete_posts'); + $role->add_cap('delete_published_posts'); + } + + $role =& get_role('contributor'); + if ( ! empty($role) ) { + $role->add_cap('delete_posts'); + } +} + +/** + * Create and modify WordPress roles for WordPress 2.3. + * + * @since 2.3.0 + */ +function populate_roles_230() { + $role =& get_role( 'administrator' ); + + if ( !empty( $role ) ) { + $role->add_cap( 'unfiltered_upload' ); + } +} + +/** + * Create and modify WordPress roles for WordPress 2.5. + * + * @since 2.5.0 + */ +function populate_roles_250() { + $role =& get_role( 'administrator' ); + + if ( !empty( $role ) ) { + $role->add_cap( 'edit_dashboard' ); + } +} + +/** + * Create and modify WordPress roles for WordPress 2.6. + * + * @since 2.6.0 + */ +function populate_roles_260() { + $role =& get_role( 'administrator' ); + + if ( !empty( $role ) ) { + $role->add_cap( 'update_plugins' ); + $role->add_cap( 'delete_plugins' ); + } +} + +/** + * Create and modify WordPress roles for WordPress 2.7. + * + * @since 2.7.0 + */ +function populate_roles_270() { + $role =& get_role( 'administrator' ); + + if ( !empty( $role ) ) { + $role->add_cap( 'install_plugins' ); + $role->add_cap( 'update_themes' ); + } +} + +/** + * Create and modify WordPress roles for WordPress 2.8. + * + * @since 2.8.0 + */ +function populate_roles_280() { + $role =& get_role( 'administrator' ); + + if ( !empty( $role ) ) { + $role->add_cap( 'install_themes' ); + } +} + +?> diff --git a/wp-admin/includes/taxonomy.php b/wp-admin/includes/taxonomy.php new file mode 100644 index 0000000..5f104d6 --- /dev/null +++ b/wp-admin/includes/taxonomy.php @@ -0,0 +1,268 @@ + $cat_name, 'category_parent' => $parent) ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $categories + * @param unknown_type $post_id + * @return unknown + */ +function wp_create_categories($categories, $post_id = '') { + $cat_ids = array (); + foreach ($categories as $category) { + if ($id = category_exists($category)) + $cat_ids[] = $id; + else + if ($id = wp_create_category($category)) + $cat_ids[] = $id; + } + + if ($post_id) + wp_set_post_categories($post_id, $cat_ids); + + return $cat_ids; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $cat_ID + * @return unknown + */ +function wp_delete_category($cat_ID) { + $cat_ID = (int) $cat_ID; + $default = get_option('default_category'); + + // Don't delete the default cat + if ( $cat_ID == $default ) + return 0; + + return wp_delete_term($cat_ID, 'category', array('default' => $default)); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $catarr + * @param unknown_type $wp_error + * @return unknown + */ +function wp_insert_category($catarr, $wp_error = false) { + $cat_defaults = array('cat_ID' => 0, 'cat_name' => '', 'category_description' => '', 'category_nicename' => '', 'category_parent' => ''); + $catarr = wp_parse_args($catarr, $cat_defaults); + extract($catarr, EXTR_SKIP); + + if ( trim( $cat_name ) == '' ) { + if ( ! $wp_error ) + return 0; + else + return new WP_Error( 'cat_name', __('You did not enter a category name.') ); + } + + $cat_ID = (int) $cat_ID; + + // Are we updating or creating? + if ( !empty ($cat_ID) ) + $update = true; + else + $update = false; + + $name = $cat_name; + $description = $category_description; + $slug = $category_nicename; + $parent = $category_parent; + + $parent = (int) $parent; + if ( $parent < 0 ) + $parent = 0; + + if ( empty($parent) || !category_exists( $parent ) || ($cat_ID && cat_is_ancestor_of($cat_ID, $parent) ) ) + $parent = 0; + + $args = compact('name', 'slug', 'parent', 'description'); + + if ( $update ) + $cat_ID = wp_update_term($cat_ID, 'category', $args); + else + $cat_ID = wp_insert_term($cat_name, 'category', $args); + + if ( is_wp_error($cat_ID) ) { + if ( $wp_error ) + return $cat_ID; + else + return 0; + } + + return $cat_ID['term_id']; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $catarr + * @return unknown + */ +function wp_update_category($catarr) { + $cat_ID = (int) $catarr['cat_ID']; + + if ( isset($catarr['category_parent']) && ($cat_ID == $catarr['category_parent']) ) + return false; + + // First, get all of the original fields + $category = get_category($cat_ID, ARRAY_A); + + // Escape data pulled from DB. + $category = add_magic_quotes($category); + + // Merge old and new fields with new fields overwriting old ones. + $catarr = array_merge($category, $catarr); + + return wp_insert_category($catarr); +} + +// +// Tags +// + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post_id + * @return unknown + */ +function get_tags_to_edit( $post_id, $taxonomy = 'post_tag' ) { + return get_terms_to_edit( $post_id, $taxonomy); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post_id + * @return unknown + */ +function get_terms_to_edit( $post_id, $taxonomy = 'post_tag' ) { + $post_id = (int) $post_id; + if ( !$post_id ) + return false; + + $tags = wp_get_post_terms($post_id, $taxonomy, array()); + + if ( !$tags ) + return false; + + if ( is_wp_error($tags) ) + return $tags; + + foreach ( $tags as $tag ) + $tag_names[] = $tag->name; + $tags_to_edit = join( ',', $tag_names ); + $tags_to_edit = esc_attr( $tags_to_edit ); + $tags_to_edit = apply_filters( 'terms_to_edit', $tags_to_edit, $taxonomy ); + + return $tags_to_edit; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $tag_name + * @return unknown + */ +function tag_exists($tag_name) { + return is_term($tag_name, 'post_tag'); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $tag_name + * @return unknown + */ +function wp_create_tag($tag_name) { + return wp_create_term( $tag_name, 'post_tag'); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $tag_name + * @return unknown + */ +function wp_create_term($tag_name, $taxonomy = 'post_tag') { + if ( $id = is_term($tag_name, $taxonomy) ) + return $id; + + return wp_insert_term($tag_name, $taxonomy); +} diff --git a/wp-admin/includes/template.php b/wp-admin/includes/template.php new file mode 100644 index 0000000..b47e079 --- /dev/null +++ b/wp-admin/includes/template.php @@ -0,0 +1,3751 @@ + 0); + if ( !empty($_GET['s']) ) + $args['search'] = $_GET['s']; + + $categories = get_categories( $args ); + + if ( empty($categories) ) + return false; + } + + $children = _get_term_hierarchy('category'); + + _cat_rows( $parent, $level, $categories, $children, $page, $per_page, $count ); + +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $categories + * @param unknown_type $count + * @param unknown_type $parent + * @param unknown_type $level + * @param unknown_type $page + * @param unknown_type $per_page + * @return unknown + */ +function _cat_rows( $parent = 0, $level = 0, $categories, &$children, $page = 1, $per_page = 20, &$count ) { + + $start = ($page - 1) * $per_page; + $end = $start + $per_page; + ob_start(); + + foreach ( $categories as $key => $category ) { + if ( $count >= $end ) + break; + + if ( $category->parent != $parent && empty($_GET['s']) ) + continue; + + // If the page starts in a subtree, print the parents. + if ( $count == $start && $category->parent > 0 ) { + + $my_parents = array(); + $p = $category->parent; + while ( $p ) { + $my_parent = get_category( $p ); + $my_parents[] = $my_parent; + if ( $my_parent->parent == 0 ) + break; + $p = $my_parent->parent; + } + + $num_parents = count($my_parents); + while( $my_parent = array_pop($my_parents) ) { + echo "\t" . _cat_row( $my_parent, $level - $num_parents ); + $num_parents--; + } + } + + if ( $count >= $start ) + echo "\t" . _cat_row( $category, $level ); + + unset( $categories[ $key ] ); + + $count++; + + if ( isset($children[$category->term_id]) ) + _cat_rows( $category->term_id, $level + 1, $categories, $children, $page, $per_page, $count ); + } + + $output = ob_get_contents(); + ob_end_clean(); + + echo $output; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $category + * @param unknown_type $level + * @param unknown_type $name_override + * @return unknown + */ +function _cat_row( $category, $level, $name_override = false ) { + static $row_class = ''; + + $category = get_category( $category, OBJECT, 'display' ); + + $default_cat_id = (int) get_option( 'default_category' ); + $pad = str_repeat( '— ', max(0, $level) ); + $name = ( $name_override ? $name_override : $pad . ' ' . $category->name ); + $edit_link = "categories.php?action=edit&cat_ID=$category->term_id"; + if ( current_user_can( 'manage_categories' ) ) { + $edit = "name)) . "'>" . esc_attr( $name ) . '
    '; + $actions = array(); + $actions['edit'] = '' . __('Edit') . ''; + $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; + if ( $default_cat_id != $category->term_id ) + $actions['delete'] = "term_id) . "'>" . __('Delete') . ""; + $actions = apply_filters('cat_row_actions', $actions, $category); + $action_count = count($actions); + $i = 0; + $edit .= '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + $edit .= "$link$sep"; + } + $edit .= '
    '; + } else { + $edit = $name; + } + + $row_class = 'alternate' == $row_class ? '' : 'alternate'; + $qe_data = get_category_to_edit($category->term_id); + + $category->count = number_format_i18n( $category->count ); + $posts_count = ( $category->count > 0 ) ? "$category->count" : $category->count; + $output = ""; + + $columns = get_column_headers('categories'); + $hidden = get_hidden_columns('categories'); + foreach ( $columns as $column_name => $column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + case 'cb': + $output .= ""; + if ( $default_cat_id != $category->term_id ) { + $output .= ""; + } else { + $output .= " "; + } + $output .= ''; + break; + case 'name': + $output .= "$edit"; + $output .= ''; + break; + case 'description': + $output .= "$category->description"; + break; + case 'slug': + $output .= "$category->slug"; + break; + case 'posts': + $attributes = 'class="posts column-posts num"' . $style; + $output .= "$posts_count\n"; + break; + default: + $output .= ""; + $output .= apply_filters('manage_categories_custom_column', '', $column_name, $category->term_id); + $output .= ""; + } + } + $output .= ''; + + return $output; +} + +/** + * {@internal Missing Short Description}} + * + * @since 2.7 + * + * Outputs the HTML for the hidden table rows used in Categories, Link Caregories and Tags quick edit. + * + * @param string $type "tag", "category" or "link-category" + * @return + */ +function inline_edit_term_row($type) { + + if ( ! current_user_can( 'manage_categories' ) ) + return; + + $is_tag = $type == 'edit-tags'; + $columns = get_column_headers($type); + $hidden = array_intersect( array_keys( $columns ), array_filter( get_hidden_columns($type) ) ); + $col_count = count($columns) - count($hidden); + ?> + +
    + +
    +name ); + $edit_link = "link-category.php?action=edit&cat_ID=$category->term_id"; + if ( current_user_can( 'manage_categories' ) ) { + $edit = "name)) . "'>$name
    "; + $actions = array(); + $actions['edit'] = '' . __('Edit') . ''; + $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; + if ( $default_cat_id != $category->term_id ) + $actions['delete'] = "term_id) . "'>" . __('Delete') . ""; + $actions = apply_filters('link_cat_row_actions', $actions, $category); + $action_count = count($actions); + $i = 0; + $edit .= '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + $edit .= "$link$sep"; + } + $edit .= '
    '; + } else { + $edit = $name; + } + + $row_class = 'alternate' == $row_class ? '' : 'alternate'; + $qe_data = get_term_to_edit($category->term_id, 'link_category'); + + $category->count = number_format_i18n( $category->count ); + $count = ( $category->count > 0 ) ? "$category->count" : $category->count; + $output = ""; + $columns = get_column_headers('edit-link-categories'); + $hidden = get_hidden_columns('edit-link-categories'); + foreach ( $columns as $column_name => $column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + case 'cb': + $output .= ""; + if ( absint( get_option( 'default_link_category' ) ) != $category->term_id ) { + $output .= ""; + } else { + $output .= " "; + } + $output .= ""; + break; + case 'name': + $output .= "$edit"; + $output .= ''; + break; + case 'description': + $output .= "$category->description"; + break; + case 'slug': + $output .= "$category->slug"; + break; + case 'links': + $attributes = 'class="links column-links num"' . $style; + $output .= "$count"; + break; + default: + $output .= ""; + $output .= apply_filters('manage_link_categories_custom_column', '', $column_name, $category->term_id); + $output .= ""; + } + } + $output .= ''; + + return $output; +} + +/** + * Outputs the html checked attribute. + * + * Compares the first two arguments and if identical marks as checked + * + * @since 2.8 + * + * @param any $checked One of the values to compare + * @param any $current (true) The other value to compare if not just true + * @param bool $echo Whether or not to echo or just return the string + */ +function checked( $checked, $current = true, $echo = true) { + return __checked_selected_helper( $checked, $current, $echo, 'checked' ); +} + +/** + * Outputs the html selected attribute. + * + * Compares the first two arguments and if identical marks as selected + * + * @since 2.8 + * + * @param any selected One of the values to compare + * @param any $current (true) The other value to compare if not just true + * @param bool $echo Whether or not to echo or just return the string + */ +function selected( $selected, $current = true, $echo = true) { + return __checked_selected_helper( $selected, $current, $echo, 'selected' ); +} + +/** + * Private helper function for checked and selected. + * + * Compares the first two arguments and if identical marks as $type + * + * @since 2.8 + * @access private + * + * @param any $helper One of the values to compare + * @param any $current (true) The other value to compare if not just true + * @param bool $echo Whether or not to echo or just return the string + * @param string $type The type of checked|selected we are doing. + */ +function __checked_selected_helper( $helper, $current, $echo, $type) { + if ( $helper == $current) + $result = " $type='$type'"; + else + $result = ''; + + if ($echo) + echo $result; + + return $result; +} + +// +// Category Checklists +// + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * @deprecated Use {@link wp_link_category_checklist()} + * @see wp_link_category_checklist() + * + * @param unknown_type $default + * @param unknown_type $parent + * @param unknown_type $popular_ids + */ +function dropdown_categories( $default = 0, $parent = 0, $popular_ids = array() ) { + global $post_ID; + wp_category_checklist($post_ID); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +class Walker_Category_Checklist extends Walker { + var $tree_type = 'category'; + var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); //TODO: decouple this + + function start_lvl(&$output, $depth, $args) { + $indent = str_repeat("\t", $depth); + $output .= "$indent
      \n"; + } + + function end_lvl(&$output, $depth, $args) { + $indent = str_repeat("\t", $depth); + $output .= "$indent
    \n"; + } + + function start_el(&$output, $category, $depth, $args) { + extract($args); + + $class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : ''; + $output .= "\n
  • " . ''; + } + + function end_el(&$output, $category, $depth, $args) { + $output .= "
  • \n"; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $post_id + * @param unknown_type $descendants_and_self + * @param unknown_type $selected_cats + * @param unknown_type $popular_cats + */ +function wp_category_checklist( $post_id = 0, $descendants_and_self = 0, $selected_cats = false, $popular_cats = false, $walker = null ) { + if ( empty($walker) || !is_a($walker, 'Walker') ) + $walker = new Walker_Category_Checklist; + + $descendants_and_self = (int) $descendants_and_self; + + $args = array(); + + if ( is_array( $selected_cats ) ) + $args['selected_cats'] = $selected_cats; + elseif ( $post_id ) + $args['selected_cats'] = wp_get_post_categories($post_id); + else + $args['selected_cats'] = array(); + + if ( is_array( $popular_cats ) ) + $args['popular_cats'] = $popular_cats; + else + $args['popular_cats'] = get_terms( 'category', array( 'fields' => 'ids', 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false ) ); + + if ( $descendants_and_self ) { + $categories = get_categories( "child_of=$descendants_and_self&hierarchical=0&hide_empty=0" ); + $self = get_category( $descendants_and_self ); + array_unshift( $categories, $self ); + } else { + $categories = get_categories('get=all'); + } + + // Post process $categories rather than adding an exclude to the get_terms() query to keep the query the same across all posts (for any query cache) + $checked_categories = array(); + $keys = array_keys( $categories ); + + foreach( $keys as $k ) { + if ( in_array( $categories[$k]->term_id, $args['selected_cats'] ) ) { + $checked_categories[] = $categories[$k]; + unset( $categories[$k] ); + } + } + + // Put checked cats on top + echo call_user_func_array(array(&$walker, 'walk'), array($checked_categories, 0, $args)); + // Then the rest of them + echo call_user_func_array(array(&$walker, 'walk'), array($categories, 0, $args)); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $taxonomy + * @param unknown_type $default + * @param unknown_type $number + * @param unknown_type $echo + * @return unknown + */ +function wp_popular_terms_checklist( $taxonomy, $default = 0, $number = 10, $echo = true ) { + global $post_ID; + if ( $post_ID ) + $checked_categories = wp_get_post_categories($post_ID); + else + $checked_categories = array(); + $categories = get_terms( $taxonomy, array( 'orderby' => 'count', 'order' => 'DESC', 'number' => $number, 'hierarchical' => false ) ); + + $popular_ids = array(); + foreach ( (array) $categories as $category ) { + $popular_ids[] = $category->term_id; + if ( !$echo ) // hack for AJAX use + continue; + $id = "popular-category-$category->term_id"; + ?> + + + + term_id; + $name = esc_html( apply_filters('the_category', $category->name)); + $checked = in_array( $cat_id, $checked_categories ); + echo '"; + } +} + +// Tag stuff + +// Returns a single tag row (see tag_rows below) +// Note: this is also used in admin-ajax.php! +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $tag + * @param unknown_type $class + * @return unknown + */ +function _tag_row( $tag, $class = '', $taxonomy = 'post_tag' ) { + $count = number_format_i18n( $tag->count ); + $tagsel = ($taxonomy == 'post_tag' ? 'tag' : $taxonomy); + $count = ( $count > 0 ) ? "$count" : $count; + + $name = apply_filters( 'term_name', $tag->name ); + $qe_data = get_term($tag->term_id, $taxonomy, object, 'edit'); + $edit_link = "edit-tags.php?action=edit&taxonomy=$taxonomy&tag_ID=$tag->term_id"; + $out = ''; + $out .= ''; + $columns = get_column_headers('edit-tags'); + $hidden = get_hidden_columns('edit-tags'); + foreach ( $columns as $column_name => $column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + case 'cb': + $out .= ' '; + break; + case 'name': + $out .= '' . $name . '
    '; + $actions = array(); + $actions['edit'] = '' . __('Edit') . ''; + $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; + $actions['delete'] = "term_id) . "'>" . __('Delete') . ""; + $actions = apply_filters('tag_row_actions', $actions, $tag); + $action_count = count($actions); + $i = 0; + $out .= '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + $out .= "$link$sep"; + } + $out .= '
    '; + $out .= ''; + break; + case 'description': + $out .= "$tag->description"; + break; + case 'slug': + $out .= "$tag->slug"; + break; + case 'posts': + $attributes = 'class="posts column-posts num"' . $style; + $out .= "$count"; + break; + default: + $out .= ""; + $out .= apply_filters("manage_${taxonomy}_custom_column", '', $column_name, $tag->term_id); + $out .= ""; + } + } + + $out .= ''; + + return $out; +} + +// Outputs appropriate rows for the Nth page of the Tag Management screen, +// assuming M tags displayed at a time on the page +// Returns the number of tags displayed +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + * @param unknown_type $pagesize + * @param unknown_type $searchterms + * @return unknown + */ +function tag_rows( $page = 1, $pagesize = 20, $searchterms = '', $taxonomy = 'post_tag' ) { + + // Get a page worth of tags + $start = ($page - 1) * $pagesize; + + $args = array('offset' => $start, 'number' => $pagesize, 'hide_empty' => 0); + + if ( !empty( $searchterms ) ) { + $args['search'] = $searchterms; + } + + $tags = get_terms( $taxonomy, $args ); + + // convert it to table rows + $out = ''; + $count = 0; + foreach( $tags as $tag ) + $out .= _tag_row( $tag, ++$count % 2 ? ' class="iedit alternate"' : ' class="iedit"', $taxonomy ); + + // filter and send to screen + echo $out; + return $count; +} + +// define the columns to display, the syntax is 'internal name' => 'display name' +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function wp_manage_posts_columns() { + $posts_columns = array(); + $posts_columns['cb'] = ''; + /* translators: manage posts column name */ + $posts_columns['title'] = _x('Post', 'column name'); + $posts_columns['author'] = __('Author'); + $posts_columns['categories'] = __('Categories'); + $posts_columns['tags'] = __('Tags'); + if ( !isset($_GET['post_status']) || !in_array($_GET['post_status'], array('pending', 'draft', 'future')) ) + $posts_columns['comments'] = '
    Comments
    '; + $posts_columns['date'] = __('Date'); + $posts_columns = apply_filters('manage_posts_columns', $posts_columns); + + return $posts_columns; +} + +// define the columns to display, the syntax is 'internal name' => 'display name' +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function wp_manage_media_columns() { + $posts_columns = array(); + $posts_columns['cb'] = ''; + $posts_columns['icon'] = ''; + /* translators: column name */ + $posts_columns['media'] = _x('File', 'column name'); + $posts_columns['author'] = __('Author'); + //$posts_columns['tags'] = _x('Tags', 'column name'); + /* translators: column name */ + $posts_columns['parent'] = _x('Attached to', 'column name'); + $posts_columns['comments'] = '
    Comments
    '; + //$posts_columns['comments'] = __('Comments'); + /* translators: column name */ + $posts_columns['date'] = _x('Date', 'column name'); + $posts_columns = apply_filters('manage_media_columns', $posts_columns); + + return $posts_columns; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function wp_manage_pages_columns() { + $posts_columns = array(); + $posts_columns['cb'] = ''; + $posts_columns['title'] = __('Title'); + $posts_columns['author'] = __('Author'); + $post_status = 'all'; + if ( !empty($_GET['post_status']) ) + $post_status = $_GET['post_status']; + if ( !in_array($post_status, array('pending', 'draft', 'future')) ) + $posts_columns['comments'] = '
    '; + $posts_columns['date'] = __('Date'); + $posts_columns = apply_filters('manage_pages_columns', $posts_columns); + + return $posts_columns; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + * @return unknown + */ +function get_column_headers($page) { + global $_wp_column_headers; + + if ( !isset($_wp_column_headers) ) + $_wp_column_headers = array(); + + // Store in static to avoid running filters on each call + if ( isset($_wp_column_headers[$page]) ) + return $_wp_column_headers[$page]; + + switch ($page) { + case 'edit': + $_wp_column_headers[$page] = wp_manage_posts_columns(); + break; + case 'edit-pages': + $_wp_column_headers[$page] = wp_manage_pages_columns(); + break; + case 'edit-comments': + $_wp_column_headers[$page] = array( + 'cb' => '', + 'author' => __('Author'), + /* translators: column name */ + 'comment' => _x('Comment', 'column name'), + //'date' => __('Submitted'), + 'response' => __('In Response To') + ); + + break; + case 'link-manager': + $_wp_column_headers[$page] = array( + 'cb' => '', + 'name' => __('Name'), + 'url' => __('URL'), + 'categories' => __('Categories'), + 'rel' => __('Relationship'), + 'visible' => __('Visible'), + 'rating' => __('Rating') + ); + + break; + case 'upload': + $_wp_column_headers[$page] = wp_manage_media_columns(); + break; + case 'categories': + $_wp_column_headers[$page] = array( + 'cb' => '', + 'name' => __('Name'), + 'description' => __('Description'), + 'slug' => __('Slug'), + 'posts' => __('Posts') + ); + + break; + case 'edit-link-categories': + $_wp_column_headers[$page] = array( + 'cb' => '', + 'name' => __('Name'), + 'description' => __('Description'), + 'slug' => __('Slug'), + 'links' => __('Links') + ); + + break; + case 'edit-tags': + $_wp_column_headers[$page] = array( + 'cb' => '', + 'name' => __('Name'), + 'description' => __('Description'), + 'slug' => __('Slug'), + 'posts' => __('Posts') + ); + + break; + case 'users': + $_wp_column_headers[$page] = array( + 'cb' => '', + 'username' => __('Username'), + 'name' => __('Name'), + 'email' => __('E-mail'), + 'role' => __('Role'), + 'posts' => __('Posts') + ); + break; + default : + $_wp_column_headers[$page] = array(); + } + + $_wp_column_headers[$page] = apply_filters('manage_' . $page . '_columns', $_wp_column_headers[$page]); + return $_wp_column_headers[$page]; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $type + * @param unknown_type $id + */ +function print_column_headers( $type, $id = true ) { + $type = str_replace('.php', '', $type); + $columns = get_column_headers( $type ); + $hidden = get_hidden_columns($type); + $styles = array(); +// $styles['tag']['posts'] = 'width: 90px;'; +// $styles['link-category']['links'] = 'width: 90px;'; +// $styles['category']['posts'] = 'width: 90px;'; +// $styles['link']['visible'] = 'text-align: center;'; + + foreach ( $columns as $column_key => $column_display_name ) { + $class = ' class="manage-column'; + + $class .= " column-$column_key"; + + if ( 'cb' == $column_key ) + $class .= ' check-column'; + elseif ( in_array($column_key, array('posts', 'comments', 'links')) ) + $class .= ' num'; + + $class .= '"'; + + $style = ''; + if ( in_array($column_key, $hidden) ) + $style = 'display:none;'; + + if ( isset($styles[$type]) && isset($styles[$type][$column_key]) ) + $style .= ' ' . $styles[$type][$column_key]; + $style = ' style="' . $style . '"'; +?> + > + true, 'date' => true, 'title' => true, 'categories' => true, 'tags' => true, 'comments' => true, 'author' => true ); + +?> + +
    + + + " style="display: none"> + +
    + +
    +

    + + + +
    +
    +
    + + + + + + + + + + + + + +
    + +
    +
    + +id, true, $type ); // TODO: ROLE SYSTEM + if ( $authors && count( $authors ) > 1 ) : + $users_opt = array('include' => $authors, 'name' => 'post_author', 'class'=> 'authors', 'multi' => 1); + if ( $bulk ) + $users_opt['show_option_none'] = __('- No Change -'); +?> + + + + + + +
    + + + + + + +
    + + + +
    + + + +
    + + + + +
      + +
    +
    + + + +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + + +
    + + + + +
    + + + + + + + + + + + + + + + + +
    + +
    + + $column_display_name ) { + if ( isset( $core_columns[$column_name] ) ) + continue; + do_action( $bulk ? 'bulk_edit_custom_box' : 'quick_edit_custom_box', $column_name, $type); + } +?> +

    + + + + + + + + +
    +

    +
    +post_type, $post->ID) ) + return; + + $title = esc_attr($post->post_title); + + echo ' +'; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $posts + */ +function post_rows( $posts = array() ) { + global $wp_query, $post, $mode; + + add_filter('the_title','esc_html'); + + // Create array of post IDs. + $post_ids = array(); + + if ( empty($posts) ) + $posts = &$wp_query->posts; + + foreach ( $posts as $a_post ) + $post_ids[] = $a_post->ID; + + $comment_pending_count = get_pending_comments_num($post_ids); + if ( empty($comment_pending_count) ) + $comment_pending_count = array(); + + foreach ( $posts as $post ) { + if ( empty($comment_pending_count[$post->ID]) ) + $comment_pending_count[$post->ID] = 0; + + _post_row($post, $comment_pending_count[$post->ID], $mode); + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $a_post + * @param unknown_type $pending_comments + * @param unknown_type $mode + */ +function _post_row($a_post, $pending_comments, $mode) { + global $post; + static $rowclass; + + $global_post = $post; + $post = $a_post; + setup_postdata($post); + + $rowclass = 'alternate' == $rowclass ? '' : 'alternate'; + global $current_user; + $post_owner = ( $current_user->ID == $post->post_author ? 'self' : 'other' ); + $edit_link = get_edit_post_link( $post->ID ); + $title = _draft_or_post_title(); +?> + post_status ); ?> iedit' valign="top"> +$column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + + case 'cb': + ?> + ID ) ) { ?> + post_date && 'date' == $column_name ) { + $t_time = $h_time = __('Unpublished'); + $time_diff = 0; + } else { + $t_time = get_the_time(__('Y/m/d g:i:s A')); + $m_time = $post->post_date; + $time = get_post_time('G', true, $post); + + $time_diff = time() - $time; + + if ( $time_diff > 0 && $time_diff < 24*60*60 ) + $h_time = sprintf( __('%s ago'), human_time_diff( $time ) ); + else + $h_time = mysql2date(__('Y/m/d'), $m_time); + } + + echo ''; + if ( 'excerpt' == $mode ) + echo apply_filters('post_date_column_time', $t_time, $post, $column_name, $mode); + else + echo '' . apply_filters('post_date_column_time', $h_time, $post, $column_name, $mode) . ''; + echo '
    '; + if ( 'publish' == $post->post_status ) { + _e('Published'); + } elseif ( 'future' == $post->post_status ) { + if ( $time_diff > 0 ) + echo '' . __('Missed schedule') . ''; + else + _e('Scheduled'); + } else { + _e('Last Modified'); + } + echo ''; + break; + + case 'title': + $attributes = 'class="post-title column-title"' . $style; + ?> + >ID ) ) { ?> + ID) ) { + $actions['edit'] = '' . __('Edit') . ''; + $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; + } + if ( current_user_can('delete_post', $post->ID) ) { + $actions['delete'] = "ID) . "' onclick=\"if ( confirm('" . esc_js(sprintf( ('draft' == $post->post_status) ? __("You are about to delete this draft '%s'\n 'Cancel' to stop, 'OK' to delete.") : __("You are about to delete this post '%s'\n 'Cancel' to stop, 'OK' to delete."), $post->post_title )) . "') ) { return true;}return false;\">" . __('Delete') . ""; + } + if ( in_array($post->post_status, array('pending', 'draft')) ) { + if ( current_user_can('edit_post', $post->ID) ) + $actions['view'] = '' . __('Preview') . ''; + } else { + $actions['view'] = '' . __('View') . ''; + } + $actions = apply_filters('post_row_actions', $actions, $post); + $action_count = count($actions); + $i = 0; + echo '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + echo "$link$sep"; + } + echo '
    '; + + get_inline_data($post); + ?> + + + >slug'> " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'category', 'display')) . ""; + echo join( ', ', $out ); + } else { + _e('Uncategorized'); + } + ?> + + >ID); + if ( !empty( $tags ) ) { + $out = array(); + foreach ( $tags as $c ) + $out[] = " " . esc_html(sanitize_term_field('name', $c->name, $c->term_id, 'post_tag', 'display')) . ""; + echo join( ', ', $out ); + } else { + _e('No Tags'); + } + ?> + + >
    + '; + comments_number("" . /* translators: comment count link */ _x('0', 'comment count') . '', "" . /* translators: comment count link */ _x('1', 'comment count') . '', "" . /* translators: comment count link: % will be substituted by comment count */ _x('%', 'comment count') . ''); + if ( $pending_comments ) + echo ''; + ?> +
    + + > + + + + ID) ) { echo "" . __('Edit') . ""; } ?> + + ID) ) { echo "ID) . "' class='delete'>" . __('Delete') . ""; } ?> + + >ID); ?> + + +post_parent > 0 ) { + //sent level 0 by accident, by default, or because we don't know the actual level + $find_main_page = (int)$page->post_parent; + while ( $find_main_page > 0 ) { + $parent = get_page($find_main_page); + + if ( is_null($parent) ) + break; + + $level++; + $find_main_page = (int)$parent->post_parent; + + if ( !isset($parent_name) ) + $parent_name = $parent->post_title; + } + } + + $page->post_title = esc_html( $page->post_title ); + $pad = str_repeat( '— ', $level ); + $id = (int) $page->ID; + $rowclass = 'alternate' == $rowclass ? '' : 'alternate'; + $posts_columns = get_column_headers('edit-pages'); + $hidden = get_hidden_columns('edit-pages'); + $title = _draft_or_post_title(); +?> + +$column_display_name) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + + case 'cb': + ?> + + post_date && 'date' == $column_name ) { + $t_time = $h_time = __('Unpublished'); + $time_diff = 0; + } else { + $t_time = get_the_time(__('Y/m/d g:i:s A')); + $m_time = $page->post_date; + $time = get_post_time('G', true); + + $time_diff = time() - $time; + + if ( $time_diff > 0 && $time_diff < 24*60*60 ) + $h_time = sprintf( __('%s ago'), human_time_diff( $time ) ); + else + $h_time = mysql2date(__('Y/m/d'), $m_time); + } + echo ''; + echo '' . apply_filters('post_date_column_time', $h_time, $page, $column_name, '') . ''; + echo '
    '; + if ( 'publish' == $page->post_status ) { + _e('Published'); + } elseif ( 'future' == $page->post_status ) { + if ( $time_diff > 0 ) + echo '' . __('Missed schedule') . ''; + else + _e('Scheduled'); + } else { + _e('Last Modified'); + } + echo ''; + break; + case 'title': + $attributes = 'class="post-title page-title column-title"' . $style; + $edit_link = get_edit_post_link( $page->ID ); + ?> + >ID ) ) { ?> + ID) ) { + $actions['edit'] = '' . __('Edit') . ''; + $actions['inline'] = '' . __('Quick Edit') . ''; + } + if ( current_user_can('delete_page', $page->ID) ) { + $actions['delete'] = "ID) . "' onclick=\"if ( confirm('" . esc_js(sprintf( ('draft' == $page->post_status) ? __("You are about to delete this draft '%s'\n 'Cancel' to stop, 'OK' to delete.") : __("You are about to delete this page '%s'\n 'Cancel' to stop, 'OK' to delete."), $page->post_title )) . "') ) { return true;}return false;\">" . __('Delete') . ""; + } + if ( in_array($post->post_status, array('pending', 'draft')) ) { + if ( current_user_can('edit_page', $page->ID) ) + $actions['view'] = '' . __('Preview') . ''; + } else { + $actions['view'] = '' . __('View') . ''; + } + $actions = apply_filters('page_row_actions', $actions, $page); + $action_count = count($actions); + + $i = 0; + echo '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + echo "$link$sep"; + } + echo '
    '; + + get_inline_data($post); + echo ''; + break; + + case 'comments': + ?> + >
    + ID ); + $pending_phrase = sprintf( __('%s pending'), number_format( $left ) ); + if ( $left ) + echo ''; + comments_number("" . /* translators: comment count link */ _x('0', 'comment count') . '', "" . /* translators: comment count link */ _x('1', 'comment count') . '', "" . /* translators: comment count link: % will be substituted by comment count */ _x('%', 'comment count') . ''); + if ( $left ) + echo ''; + ?> +
    + + > + + > + + + + + 'menu_order') ); + + if ( ! $pages ) + return false; + } + + /* + * arrange pages into two parts: top level pages and children_pages + * children_pages is two dimensional array, eg. + * children_pages[10][] contains all sub-pages whose parent is 10. + * It only takes O(N) to arrange this and it takes O(1) for subsequent lookup operations + * If searching, ignore hierarchy and treat everything as top level + */ + if ( empty($_GET['s']) ) { + + $top_level_pages = array(); + $children_pages = array(); + + foreach ( $pages as $page ) { + + // catch and repair bad pages + if ( $page->post_parent == $page->ID ) { + $page->post_parent = 0; + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_parent = '0' WHERE ID = %d", $page->ID) ); + clean_page_cache( $page->ID ); + } + + if ( 0 == $page->post_parent ) + $top_level_pages[] = $page; + else + $children_pages[ $page->post_parent ][] = $page; + } + + $pages = &$top_level_pages; + } + + $count = 0; + $start = ($pagenum - 1) * $per_page; + $end = $start + $per_page; + + foreach ( $pages as $page ) { + if ( $count >= $end ) + break; + + if ( $count >= $start ) + echo "\t" . display_page_row( $page, $level ); + + $count++; + + if ( isset($children_pages) ) + _page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page ); + } + + // if it is the last pagenum and there are orphaned pages, display them with paging as well + if ( isset($children_pages) && $count < $end ){ + foreach( $children_pages as $orphans ){ + foreach ( $orphans as $op ) { + if ( $count >= $end ) + break; + if ( $count >= $start ) + echo "\t" . display_page_row( $op, 0 ); + $count++; + } + } + } +} + +/* + * Given a top level page ID, display the nested hierarchy of sub-pages + * together with paging support + */ +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $children_pages + * @param unknown_type $count + * @param unknown_type $parent + * @param unknown_type $level + * @param unknown_type $pagenum + * @param unknown_type $per_page + */ +function _page_rows( &$children_pages, &$count, $parent, $level, $pagenum, $per_page ) { + + if ( ! isset( $children_pages[$parent] ) ) + return; + + $start = ($pagenum - 1) * $per_page; + $end = $start + $per_page; + + foreach ( $children_pages[$parent] as $page ) { + + if ( $count >= $end ) + break; + + // If the page starts in a subtree, print the parents. + if ( $count == $start && $page->post_parent > 0 ) { + $my_parents = array(); + $my_parent = $page->post_parent; + while ( $my_parent) { + $my_parent = get_post($my_parent); + $my_parents[] = $my_parent; + if ( !$my_parent->post_parent ) + break; + $my_parent = $my_parent->post_parent; + } + $num_parents = count($my_parents); + while( $my_parent = array_pop($my_parents) ) { + echo "\t" . display_page_row( $my_parent, $level - $num_parents ); + $num_parents--; + } + } + + if ( $count >= $start ) + echo "\t" . display_page_row( $page, $level ); + + $count++; + + _page_rows( $children_pages, $count, $page->ID, $level + 1, $pagenum, $per_page ); + } + + unset( $children_pages[$parent] ); //required in order to keep track of orphans +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $user_object + * @param unknown_type $style + * @param unknown_type $role + * @return unknown + */ +function user_row( $user_object, $style = '', $role = '' ) { + global $wp_roles; + + $current_user = wp_get_current_user(); + + if ( !( is_object( $user_object) && is_a( $user_object, 'WP_User' ) ) ) + $user_object = new WP_User( (int) $user_object ); + $email = $user_object->user_email; + $url = $user_object->user_url; + $short_url = str_replace( 'http://', '', $url ); + $short_url = str_replace( 'www.', '', $short_url ); + if ('/' == substr( $short_url, -1 )) + $short_url = substr( $short_url, 0, -1 ); + if ( strlen( $short_url ) > 35 ) + $short_url = substr( $short_url, 0, 32 ).'...'; + $numposts = get_usernumposts( $user_object->ID ); + $checkbox = ''; + // Check if the user for this row is editable + if ( current_user_can( 'edit_user', $user_object->ID ) ) { + // Set up the user editing link + // TODO: make profile/user-edit determination a seperate function + if ($current_user->ID == $user_object->ID) { + $edit_link = 'profile.php'; + } else { + $edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( esc_url( stripslashes( $_SERVER['REQUEST_URI'] ) ) ), "user-edit.php?user_id=$user_object->ID" ) ); + } + $edit = "$user_object->user_login
    "; + + // Set up the hover actions for this user + $actions = array(); + $actions['edit'] = '' . __('Edit') . ''; + if ( $current_user->ID != $user_object->ID ) + $actions['delete'] = "" . __('Delete') . ""; + $actions = apply_filters('user_row_actions', $actions, $user_object); + $action_count = count($actions); + $i = 0; + $edit .= '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + $edit .= "$link$sep"; + } + $edit .= '
    '; + + // Set up the checkbox (because the user is editable, otherwise its empty) + $checkbox = ""; + + } else { + $edit = '' . $user_object->user_login . ''; + } + $role_name = isset($wp_roles->role_names[$role]) ? translate_user_role($wp_roles->role_names[$role] ) : __('None'); + $r = ""; + $columns = get_column_headers('users'); + $hidden = get_hidden_columns('users'); + $avatar = get_avatar( $user_object->ID, 32 ); + foreach ( $columns as $column_name => $column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + case 'cb': + $r .= "$checkbox"; + break; + case 'username': + $r .= "$avatar $edit"; + break; + case 'name': + $r .= "$user_object->first_name $user_object->last_name"; + break; + case 'email': + $r .= "$email"; + break; + case 'role': + $r .= "$role_name"; + break; + case 'posts': + $attributes = 'class="posts column-posts num"' . $style; + $r .= ""; + if ( $numposts > 0 ) { + $r .= ""; + $r .= $numposts; + $r .= ''; + } else { + $r .= 0; + } + $r .= ""; + break; + default: + $r .= ""; + $r .= apply_filters('manage_users_custom_column', '', $column_name, $user_object->ID); + $r .= ""; + } + } + $r .= ''; + + return $r; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $status + * @param unknown_type $s + * @param unknown_type $start + * @param unknown_type $num + * @param unknown_type $post + * @param unknown_type $type + * @return unknown + */ +function _wp_get_comment_list( $status = '', $s = false, $start, $num, $post = 0, $type = '' ) { + global $wpdb; + + $start = abs( (int) $start ); + $num = (int) $num; + $post = (int) $post; + $count = wp_count_comments(); + $index = ''; + + if ( 'moderated' == $status ) { + $approved = "comment_approved = '0'"; + $total = $count->moderated; + } elseif ( 'approved' == $status ) { + $approved = "comment_approved = '1'"; + $total = $count->approved; + } elseif ( 'spam' == $status ) { + $approved = "comment_approved = 'spam'"; + $total = $count->spam; + } else { + $approved = "( comment_approved = '0' OR comment_approved = '1' )"; + $total = $count->moderated + $count->approved; + $index = 'USE INDEX (comment_date_gmt)'; + } + + if ( $post ) { + $total = ''; + $post = " AND comment_post_ID = '$post'"; + $orderby = "ORDER BY comment_date_gmt ASC LIMIT $start, $num"; + } else { + $post = ''; + $orderby = "ORDER BY comment_date_gmt DESC LIMIT $start, $num"; + } + + if ( 'comment' == $type ) + $typesql = "AND comment_type = ''"; + elseif ( 'pingback' == $type ) + $typesql = "AND comment_type = 'pingback'"; + elseif ( 'trackback' == $type ) + $typesql = "AND comment_type = 'trackback'"; + elseif ( 'pings' == $type ) + $typesql = "AND ( comment_type = 'pingback' OR comment_type = 'trackback' )"; + else + $typesql = ''; + + if ( !empty($type) ) + $total = ''; + + if ( $s ) { + $total = ''; + $s = $wpdb->escape($s); + $query = "FROM $wpdb->comments WHERE + (comment_author LIKE '%$s%' OR + comment_author_email LIKE '%$s%' OR + comment_author_url LIKE ('%$s%') OR + comment_author_IP LIKE ('%$s%') OR + comment_content LIKE ('%$s%') ) AND + $approved + $typesql"; + } else { + $query = "FROM $wpdb->comments $index WHERE $approved $post $typesql"; + } + + $comments = $wpdb->get_results("SELECT * $query $orderby"); + if ( '' === $total ) + $total = $wpdb->get_var("SELECT COUNT(comment_ID) $query"); + + update_comment_cache($comments); + + return array($comments, $total); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $comment_id + * @param unknown_type $mode + * @param unknown_type $comment_status + * @param unknown_type $checkbox + */ +function _wp_comment_row( $comment_id, $mode, $comment_status, $checkbox = true, $from_ajax = false ) { + global $comment, $post, $_comment_pending_count; + $comment = get_comment( $comment_id ); + $post = get_post($comment->comment_post_ID); + $the_comment_status = wp_get_comment_status($comment->comment_ID); + $user_can = current_user_can('edit_post', $post->ID); + + $author_url = get_comment_author_url(); + if ( 'http://' == $author_url ) + $author_url = ''; + $author_url_display = preg_replace('|http://(www\.)?|i', '', $author_url); + if ( strlen($author_url_display) > 50 ) + $author_url_display = substr($author_url_display, 0, 49) . '...'; + + $ptime = date('G', strtotime( $comment->comment_date ) ); + if ( ( abs(time() - $ptime) ) < 86400 ) + $ptime = sprintf( __('%s ago'), human_time_diff( $ptime ) ); + else + $ptime = mysql2date(__('Y/m/d \a\t g:i A'), $comment->comment_date ); + + $delete_url = esc_url( wp_nonce_url( "comment.php?action=deletecomment&p=$post->ID&c=$comment->comment_ID", "delete-comment_$comment->comment_ID" ) ); + $approve_url = esc_url( wp_nonce_url( "comment.php?action=approvecomment&p=$post->ID&c=$comment->comment_ID", "approve-comment_$comment->comment_ID" ) ); + $unapprove_url = esc_url( wp_nonce_url( "comment.php?action=unapprovecomment&p=$post->ID&c=$comment->comment_ID", "unapprove-comment_$comment->comment_ID" ) ); + $spam_url = esc_url( wp_nonce_url( "comment.php?action=deletecomment&dt=spam&p=$post->ID&c=$comment->comment_ID", "delete-comment_$comment->comment_ID" ) ); + + echo ""; + $columns = get_column_headers('edit-comments'); + $hidden = get_hidden_columns('edit-comments'); + foreach ( $columns as $column_name => $column_display_name ) { + $class = "class=\"$column_name column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch ($column_name) { + case 'cb': + if ( !$checkbox ) break; + echo ''; + if ( $user_can ) echo ""; + echo ''; + break; + case 'comment': + echo ""; + echo '
    '; + printf(__('Submitted on %2$s at %3$s'), get_comment_link($comment->comment_ID), get_comment_date(__('Y/m/d')), get_comment_date(__('g:ia'))); + echo '
    '; + comment_text(); ?> + + comment_ID:unapproved:e7e7d3:e7e7d3:new=approved vim-a' title='" . __( 'Approve this comment' ) . "'>" . __( 'Approve' ) . ''; + $actions['unapprove'] = "" . __( 'Unapprove' ) . ''; + if ( $comment_status && 'all' != $comment_status ) { // not looking at all comments + if ( 'approved' == $the_comment_status ) { + $actions['unapprove'] = "" . __( 'Unapprove' ) . ''; + unset($actions['approve']); + } else { + $actions['approve'] = "" . __( 'Approve' ) . ''; + unset($actions['unapprove']); + } + } + if ( 'spam' != $the_comment_status ) + $actions['spam'] = "" . /* translators: mark as spam link */ _x( 'Spam', 'verb' ) . ''; + $actions['delete'] = "" . __('Delete') . ''; + $actions['edit'] = "". __('Edit') . ''; + $actions['quickedit'] = '' . __('Quick Edit') . ''; + if ( 'spam' != $the_comment_status ) + $actions['reply'] = '' . __('Reply') . ''; + + $actions = apply_filters( 'comment_row_actions', $actions, $comment ); + + $i = 0; + echo '
    '; + foreach ( $actions as $action => $link ) { + ++$i; + ( ( ('approve' == $action || 'unapprove' == $action) && 2 === $i ) || 1 === $i ) ? $sep = '' : $sep = ' | '; + + // Reply and quickedit need a hide-if-no-js span when not added with ajax + if ( ('reply' == $action || 'quickedit' == $action) && ! $from_ajax ) + $action .= ' hide-if-no-js'; + + echo "$sep$link"; + } + echo '
    '; + } + + echo ''; + break; + case 'author': + echo ""; comment_author(); echo '
    '; + if ( !empty($author_url) ) + echo "$author_url_display
    "; + if ( $user_can ) { + if ( !empty($comment->comment_author_email) ) { + comment_author_email_link(); + echo '
    '; + } + echo ''; + comment_author_IP(); + echo ''; + } //current_user_can + echo ''; + break; + case 'date': + echo "" . get_comment_date(__('Y/m/d \a\t g:ia')) . ''; + break; + case 'response': + if ( 'single' !== $mode ) { + if ( isset( $_comment_pending_count[$post->ID] ) ) { + $pending_comments = absint( $_comment_pending_count[$post->ID] ); + } else { + $_comment_pending_count_temp = (array) get_pending_comments_num( array( $post->ID ) ); + $pending_comments = $_comment_pending_count[$post->ID] = $_comment_pending_count_temp[$post->ID]; + } + if ( $user_can ) { + $post_link = ""; + $post_link .= get_the_title($post->ID) . ''; + } else { + $post_link = get_the_title($post->ID); + } + echo "\n"; + echo ''; + if ( 'attachment' == $post->post_type && ( $thumb = wp_get_attachment_image( $post->ID, array(80, 60), true ) ) ) + echo $thumb; + echo ''; + } + break; + default: + echo "\n"; + do_action( 'manage_comments_custom_column', $column_name, $comment->comment_ID ); + echo "\n"; + break; + } + } + echo "\n"; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $position + * @param unknown_type $checkbox + * @param unknown_type $mode + */ +function wp_comment_reply($position = '1', $checkbox = false, $mode = 'single', $table_row = true) { + global $current_user; + + // allow plugin to replace the popup content + $content = apply_filters( 'wp_comment_reply', '', array('position' => $position, 'checkbox' => $checkbox, 'mode' => $mode) ); + + if ( ! empty($content) ) { + echo $content; + return; + } + + $columns = get_column_headers('edit-comments'); + $hidden = array_intersect( array_keys( $columns ), array_filter( get_hidden_columns('edit-comments') ) ); + $col_count = count($columns) - count($hidden); + +?> +
    + +
    + +
    + + + +
    + 0) ); + + if ( $categories ) { + foreach ( $categories as $category ) { + if ( $currentcat != $category->term_id && $parent == $category->parent) { + $pad = str_repeat( '– ', $level ); + $category->name = esc_html( $category->name ); + echo "\n\t"; + wp_dropdown_cats( $currentcat, $currentparent, $category->term_id, $level +1, $categories ); + } + } + } else { + return false; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $meta + */ +function list_meta( $meta ) { + // Exit if no meta + if ( ! $meta ) { + echo ' + + + + + + + + + + +'; //TBODY needed for list-manipulation JS + return; + } + $count = 0; +?> + + + + + + + + + + +
    + + $entry['meta_id'] = (int) $entry['meta_id']; + + $delete_nonce = wp_create_nonce( 'delete-meta_' . $entry['meta_id'] ); + + $r .= "\n\t"; + $r .= "\n\t\t"; + + $r .= "\n\t\t
    "; + $r .= "\n\t\t
    "; + $r .= wp_nonce_field( 'change-meta', '_ajax_nonce', false, false ); + $r .= ""; + + $r .= "\n\t\t\n\t"; + return $r; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function meta_form() { + global $wpdb; + $limit = (int) apply_filters( 'postmeta_form_limit', 30 ); + $keys = $wpdb->get_col( " + SELECT meta_key + FROM $wpdb->postmeta + GROUP BY meta_key + HAVING meta_key NOT LIKE '\_%' + ORDER BY LOWER(meta_key) + LIMIT $limit" ); + if ( $keys ) + natcasesort($keys); +?> +

    + + + + + + + + + + + + + + + + +
    + + + + + + + + + +
    + + +
    +post_status, array('draft', 'pending') ) && (!$post->post_date_gmt || '0000-00-00 00:00:00' == $post->post_date_gmt ) ) ? false : true; + + $tab_index_attribute = ''; + if ( (int) $tab_index > 0 ) + $tab_index_attribute = " tabindex=\"$tab_index\""; + + // echo '
    '; + + $time_adj = time() + (get_option( 'gmt_offset' ) * 3600 ); + $post_date = ($for_post) ? $post->post_date : $comment->comment_date; + $jj = ($edit) ? mysql2date( 'd', $post_date, false ) : gmdate( 'd', $time_adj ); + $mm = ($edit) ? mysql2date( 'm', $post_date, false ) : gmdate( 'm', $time_adj ); + $aa = ($edit) ? mysql2date( 'Y', $post_date, false ) : gmdate( 'Y', $time_adj ); + $hh = ($edit) ? mysql2date( 'H', $post_date, false ) : gmdate( 'H', $time_adj ); + $mn = ($edit) ? mysql2date( 'i', $post_date, false ) : gmdate( 'i', $time_adj ); + $ss = ($edit) ? mysql2date( 's', $post_date, false ) : gmdate( 's', $time_adj ); + + $cur_jj = gmdate( 'd', $time_adj ); + $cur_mm = gmdate( 'm', $time_adj ); + $cur_aa = gmdate( 'Y', $time_adj ); + $cur_hh = gmdate( 'H', $time_adj ); + $cur_mn = gmdate( 'i', $time_adj ); + + $month = "'; + + $day = ''; + $year = ''; + $hour = ''; + $minute = ''; + /* translators: 1: month input, 2: day input, 3: year input, 4: hour input, 5: minute input */ + printf(__('%1$s%2$s, %3$s @ %4$s : %5$s'), $month, $day, $year, $hour, $minute); + + echo ''; + + if ( $multi ) return; + + echo "\n\n"; + foreach ( array('mm', 'jj', 'aa', 'hh', 'mn') as $timeunit ) { + echo '' . "\n"; + $cur_timeunit = 'cur_' . $timeunit; + echo '' . "\n"; + } +?> + +

    + + +

    +$template"; + endforeach; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $default + * @param unknown_type $parent + * @param unknown_type $level + * @return unknown + */ +function parent_dropdown( $default = 0, $parent = 0, $level = 0 ) { + global $wpdb, $post_ID; + $items = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' ORDER BY menu_order", $parent) ); + + if ( $items ) { + foreach ( $items as $item ) { + // A page cannot be its own parent. + if (!empty ( $post_ID ) ) { + if ( $item->ID == $post_ID ) { + continue; + } + } + $pad = str_repeat( ' ', $level * 3 ); + if ( $item->ID == $default) + $current = ' selected="selected"'; + else + $current = ''; + + echo "\n\t"; + parent_dropdown( $default, $item->ID, $level +1 ); + } + } else { + return false; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function browse_happy() { + $getit = __( 'WordPress recommends a better browser' ); + echo ' +
    Browse Happy
    +'; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $id + * @return unknown + */ +function the_attachment_links( $id = false ) { + $id = (int) $id; + $post = & get_post( $id ); + + if ( $post->post_type != 'attachment' ) + return false; + + $icon = get_attachment_icon( $post->ID ); + $attachment_data = wp_get_attachment_metadata( $id ); + $thumb = isset( $attachment_data['thumb'] ); +?> + + html elements for role selectors based on $wp_roles + * + * @package WordPress + * @subpackage Administration + * @since 2.1 + * + * @uses $wp_roles + * @param string $default slug for the role that should be already selected + */ +function wp_dropdown_roles( $selected = false ) { + global $wp_roles; + $p = ''; + $r = ''; + + $editable_roles = get_editable_roles(); + + foreach( $editable_roles as $role => $details ) { + $name = translate_user_role($details['name'] ); + if ( $selected == $role ) // Make default first in list + $p = "\n\t"; + else + $r .= "\n\t"; + } + echo $p . $r; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $size + * @return unknown + */ +function wp_convert_hr_to_bytes( $size ) { + $size = strtolower($size); + $bytes = (int) $size; + if ( strpos($size, 'k') !== false ) + $bytes = intval($size) * 1024; + elseif ( strpos($size, 'm') !== false ) + $bytes = intval($size) * 1024 * 1024; + elseif ( strpos($size, 'g') !== false ) + $bytes = intval($size) * 1024 * 1024 * 1024; + return $bytes; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $bytes + * @return unknown + */ +function wp_convert_bytes_to_hr( $bytes ) { + $units = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' ); + $log = log( $bytes, 1024 ); + $power = (int) $log; + $size = pow(1024, $log - $power); + return $size . $units[$power]; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function wp_max_upload_size() { + $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) ); + $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) ); + $bytes = apply_filters( 'upload_size_limit', min($u_bytes, $p_bytes), $u_bytes, $p_bytes ); + return $bytes; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $action + */ +function wp_import_upload_form( $action ) { + $bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() ); + $size = wp_convert_bytes_to_hr( $bytes ); + $upload_dir = wp_upload_dir(); + if ( ! empty( $upload_dir['error'] ) ) : + ?>

    +

    +
    +

    + + () + + + +

    +

    + +

    +
    +post_name); // just in case + if ( strlen($name) ) + echo ''; +} + +/** + * Add a meta box to an edit form. + * + * @since 2.5.0 + * + * @param string $id String for use in the 'id' attribute of tags. + * @param string $title Title of the meta box. + * @param string $callback Function that fills the box with the desired content. The function should echo its output. + * @param string $page The type of edit page on which to show the box (post, page, link). + * @param string $context The context within the page where the boxes should show ('normal', 'advanced'). + * @param string $priority The priority within the context where the boxes should show ('high', 'low'). + */ +function add_meta_box($id, $title, $callback, $page, $context = 'advanced', $priority = 'default', $callback_args=null) { + global $wp_meta_boxes; + + if ( !isset($wp_meta_boxes) ) + $wp_meta_boxes = array(); + if ( !isset($wp_meta_boxes[$page]) ) + $wp_meta_boxes[$page] = array(); + if ( !isset($wp_meta_boxes[$page][$context]) ) + $wp_meta_boxes[$page][$context] = array(); + + foreach ( array_keys($wp_meta_boxes[$page]) as $a_context ) { + foreach ( array('high', 'core', 'default', 'low') as $a_priority ) { + if ( !isset($wp_meta_boxes[$page][$a_context][$a_priority][$id]) ) + continue; + + // If a core box was previously added or removed by a plugin, don't add. + if ( 'core' == $priority ) { + // If core box previously deleted, don't add + if ( false === $wp_meta_boxes[$page][$a_context][$a_priority][$id] ) + return; + // If box was added with default priority, give it core priority to maintain sort order + if ( 'default' == $a_priority ) { + $wp_meta_boxes[$page][$a_context]['core'][$id] = $wp_meta_boxes[$page][$a_context]['default'][$id]; + unset($wp_meta_boxes[$page][$a_context]['default'][$id]); + } + return; + } + // If no priority given and id already present, use existing priority + if ( empty($priority) ) { + $priority = $a_priority; + // else if we're adding to the sorted priortiy, we don't know the title or callback. Glab them from the previously added context/priority. + } elseif ( 'sorted' == $priority ) { + $title = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['title']; + $callback = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['callback']; + $callback_args = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['args']; + } + // An id can be in only one priority and one context + if ( $priority != $a_priority || $context != $a_context ) + unset($wp_meta_boxes[$page][$a_context][$a_priority][$id]); + } + } + + if ( empty($priority) ) + $priority = 'low'; + + if ( !isset($wp_meta_boxes[$page][$context][$priority]) ) + $wp_meta_boxes[$page][$context][$priority] = array(); + + $wp_meta_boxes[$page][$context][$priority][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $callback_args); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + * @param unknown_type $context + * @param unknown_type $object + * @return int number of meta_boxes + */ +function do_meta_boxes($page, $context, $object) { + global $wp_meta_boxes; + static $already_sorted = false; + + //do_action('do_meta_boxes', $page, $context, $object); + + $hidden = get_hidden_meta_boxes($page); + + echo "
    \n"; + + $i = 0; + do { + // Grab the ones the user has manually sorted. Pull them out of their previous context/priority and into the one the user chose + if ( !$already_sorted && $sorted = get_user_option( "meta-box-order_$page", 0, false ) ) { + foreach ( $sorted as $box_context => $ids ) + foreach ( explode(',', $ids) as $id ) + if ( $id ) + add_meta_box( $id, null, null, $page, $box_context, 'sorted' ); + } + $already_sorted = true; + + if ( !isset($wp_meta_boxes) || !isset($wp_meta_boxes[$page]) || !isset($wp_meta_boxes[$page][$context]) ) + break; + + foreach ( array('high', 'sorted', 'core', 'default', 'low') as $priority ) { + if ( isset($wp_meta_boxes[$page][$context][$priority]) ) { + foreach ( (array) $wp_meta_boxes[$page][$context][$priority] as $box ) { + if ( false == $box || ! $box['title'] ) + continue; + $i++; + $style = ''; + if ( in_array($box['id'], $hidden) ) + $style = 'style="display:none;"'; + echo '
    ' . "\n"; + echo '

    '; + echo "

    {$box['title']}

    \n"; + echo '
    ' . "\n"; + call_user_func($box['callback'], $object, $box); + echo "
    \n"; + echo "
    \n"; + } + } + } + } while(0); + + echo "
    "; + + return $i; + +} + +/** + * Remove a meta box from an edit form. + * + * @since 2.6.0 + * + * @param string $id String for use in the 'id' attribute of tags. + * @param string $page The type of edit page on which to show the box (post, page, link). + * @param string $context The context within the page where the boxes should show ('normal', 'advanced'). + */ +function remove_meta_box($id, $page, $context) { + global $wp_meta_boxes; + + if ( !isset($wp_meta_boxes) ) + $wp_meta_boxes = array(); + if ( !isset($wp_meta_boxes[$page]) ) + $wp_meta_boxes[$page] = array(); + if ( !isset($wp_meta_boxes[$page][$context]) ) + $wp_meta_boxes[$page][$context] = array(); + + foreach ( array('high', 'core', 'default', 'low') as $priority ) + $wp_meta_boxes[$page][$context][$priority][$id] = false; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + */ +function meta_box_prefs($page) { + global $wp_meta_boxes; + + if ( empty($wp_meta_boxes[$page]) ) + return; + + $hidden = get_hidden_meta_boxes($page); + + foreach ( array_keys($wp_meta_boxes[$page]) as $context ) { + foreach ( array_keys($wp_meta_boxes[$page][$context]) as $priority ) { + foreach ( $wp_meta_boxes[$page][$context][$priority] as $box ) { + if ( false == $box || ! $box['title'] ) + continue; + // Submit box cannot be hidden + if ( 'submitdiv' == $box['id'] || 'linksubmitdiv' == $box['id'] ) + continue; + $box_id = $box['id']; + echo '\n"; + } + } + } +} + +function get_hidden_meta_boxes($page) { + $hidden = (array) get_user_option( "meta-box-hidden_$page", 0, false ); + + // Hide slug boxes by default + if ( empty($hidden[0]) ) { + if ( 'page' == $page ) + $hidden = array('pageslugdiv'); + elseif ( 'post' == $page ) + $hidden = array('slugdiv'); + } + + return $hidden; +} + +/** + * Add a new section to a settings page. + * + * @since 2.7.0 + * + * @param string $id String for use in the 'id' attribute of tags. + * @param string $title Title of the section. + * @param string $callback Function that fills the section with the desired content. The function should echo its output. + * @param string $page The type of settings page on which to show the section (general, reading, writing, ...). + */ +function add_settings_section($id, $title, $callback, $page) { + global $wp_settings_sections; + + if ( !isset($wp_settings_sections) ) + $wp_settings_sections = array(); + if ( !isset($wp_settings_sections[$page]) ) + $wp_settings_sections[$page] = array(); + if ( !isset($wp_settings_sections[$page][$id]) ) + $wp_settings_sections[$page][$id] = array(); + + $wp_settings_sections[$page][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback); +} + +/** + * Add a new field to a settings page. + * + * @since 2.7.0 + * + * @param string $id String for use in the 'id' attribute of tags. + * @param string $title Title of the field. + * @param string $callback Function that fills the field with the desired content. The function should echo its output. + * @param string $page The type of settings page on which to show the field (general, reading, writing, ...). + * @param string $section The section of the settingss page in which to show the box (default, ...). + * @param array $args Additional arguments + */ +function add_settings_field($id, $title, $callback, $page, $section = 'default', $args = array()) { + global $wp_settings_fields; + + if ( !isset($wp_settings_fields) ) + $wp_settings_fields = array(); + if ( !isset($wp_settings_fields[$page]) ) + $wp_settings_fields[$page] = array(); + if ( !isset($wp_settings_fields[$page][$section]) ) + $wp_settings_fields[$page][$section] = array(); + + $wp_settings_fields[$page][$section][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $args); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + */ +function do_settings_sections($page) { + global $wp_settings_sections, $wp_settings_fields; + + if ( !isset($wp_settings_sections) || !isset($wp_settings_sections[$page]) ) + return; + + foreach ( (array) $wp_settings_sections[$page] as $section ) { + echo "

    {$section['title']}

    \n"; + call_user_func($section['callback'], $section); + if ( !isset($wp_settings_fields) || !isset($wp_settings_fields[$page]) || !isset($wp_settings_fields[$page][$section['id']]) ) + continue; + echo ''; + do_settings_fields($page, $section['id']); + echo '
    '; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + * @param unknown_type $section + */ +function do_settings_fields($page, $section) { + global $wp_settings_fields; + + if ( !isset($wp_settings_fields) || !isset($wp_settings_fields[$page]) || !isset($wp_settings_fields[$page][$section]) ) + return; + + foreach ( (array) $wp_settings_fields[$page][$section] as $field ) { + echo ''; + if ( !empty($field['args']['label_for']) ) + echo ''; + else + echo '' . $field['title'] . ''; + echo ''; + call_user_func($field['callback']); + echo ''; + echo ''; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $page + */ +function manage_columns_prefs($page) { + $columns = get_column_headers($page); + + $hidden = get_hidden_columns($page); + + foreach ( $columns as $column => $title ) { + // Can't hide these + if ( 'cb' == $column || 'title' == $column || 'name' == $column || 'username' == $column || 'media' == $column || 'comment' == $column ) + continue; + if ( empty($title) ) + continue; + + if ( 'comments' == $column ) + $title = __('Comments'); + $id = "$column-hide"; + echo '\n"; + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param unknown_type $found_action + */ +function find_posts_div($found_action = '') { +?> + +post_password ) ) echo esc_attr( $post->post_password ); +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + */ +function favorite_actions( $screen = null ) { + switch ( $screen ) { + case 'post-new.php': + $default_action = array('edit.php' => array(__('Edit Posts'), 'edit_posts')); + break; + case 'edit-pages.php': + $default_action = array('page-new.php' => array(__('New Page'), 'edit_pages')); + break; + case 'page-new.php': + $default_action = array('edit-pages.php' => array(__('Edit Pages'), 'edit_pages')); + break; + case 'upload.php': + $default_action = array('media-new.php' => array(__('New Media'), 'upload_files')); + break; + case 'media-new.php': + $default_action = array('upload.php' => array(__('Edit Media'), 'upload_files')); + break; + case 'link-manager.php': + $default_action = array('link-add.php' => array(__('New Link'), 'manage_links')); + break; + case 'link-add.php': + $default_action = array('link-manager.php' => array(__('Edit Links'), 'manage_links')); + break; + case 'users.php': + $default_action = array('user-new.php' => array(__('New User'), 'create_users')); + break; + case 'user-new.php': + $default_action = array('users.php' => array(__('Edit Users'), 'edit_users')); + break; + case 'plugins.php': + $default_action = array('plugin-install.php' => array(__('Install Plugins'), 'install_plugins')); + break; + case 'plugin-install.php': + $default_action = array('plugins.php' => array(__('Manage Plugins'), 'activate_plugins')); + break; + case 'themes.php': + $default_action = array('theme-install.php' => array(__('Install Themes'), 'install_themes')); + break; + case 'theme-install.php': + $default_action = array('themes.php' => array(__('Manage Themes'), 'switch_themes')); + break; + default: + $default_action = array('post-new.php' => array(__('New Post'), 'edit_posts')); + break; + } + + $actions = array( + 'post-new.php' => array(__('New Post'), 'edit_posts'), + 'edit.php?post_status=draft' => array(__('Drafts'), 'edit_posts'), + 'page-new.php' => array(__('New Page'), 'edit_pages'), + 'media-new.php' => array(__('Upload'), 'upload_files'), + 'edit-comments.php' => array(__('Comments'), 'moderate_comments') + ); + + $default_key = array_keys($default_action); + $default_key = $default_key[0]; + if ( isset($actions[$default_key]) ) + unset($actions[$default_key]); + $actions = array_merge($default_action, $actions); + $actions = apply_filters('favorite_actions', $actions); + + $allowed_actions = array(); + foreach ( $actions as $action => $data ) { + if ( current_user_can($data[1]) ) + $allowed_actions[$action] = $data[0]; + } + + if ( empty($allowed_actions) ) + return; + + $first = array_keys($allowed_actions); + $first = $first[0]; + echo '
    '; + echo '

    '; + echo '
    '; + + array_shift($allowed_actions); + + foreach ( $allowed_actions as $action => $label) { + echo "\n"; + } + echo "
    \n"; +} + +/** + * Get the post title. + * + * The post title is fetched and if it is blank then a default string is + * returned. + * + * @since 2.7.0 + * @param int $id The post id. If not supplied the global $post is used. + * + */ +function _draft_or_post_title($post_id = 0) +{ + $title = get_the_title($post_id); + if ( empty($title) ) + $title = __('(no title)'); + return $title; +} + +/** + * Display the search query. + * + * A simple wrapper to display the "s" parameter in a GET URI. This function + * should only be used when {@link the_search_query()} cannot. + * + * @uses attr + * @since 2.7.0 + * + */ +function _admin_search_query() { + echo isset($_GET['s']) ? esc_attr( stripslashes( $_GET['s'] ) ) : ''; +} + +/** + * Generic Iframe header for use with Thickbox + * + * @since 2.7.0 + * @param string $title Title of the Iframe page. + * @param bool $limit_styles Limit styles to colour-related styles only (unless others are enqueued). + * + */ +function iframe_header( $title = '', $limit_styles = false ) { +?> + > + + +<?php bloginfo('name') ?> › <?php echo $title ?> — <?php _e('WordPress'); ?> + + + + +> + + + + + +post_password) ) + $post_states[] = __('Password protected'); + if ( 'private' == $post->post_status && 'private' != $post_status ) + $post_states[] = __('Private'); + if ( 'draft' == $post->post_status && 'draft' != $post_status ) + $post_states[] = __('Draft'); + if ( 'pending' == $post->post_status && 'pending' != $post_status ) + /* translators: post state */ + $post_states[] = _x('Pending', 'post state'); + if ( is_sticky($post->ID) ) + $post_states[] = __('Sticky'); + + $post_states = apply_filters( 'display_post_states', $post_states ); + + if ( ! empty($post_states) ) { + $state_count = count($post_states); + $i = 0; + echo ' - '; + foreach ( $post_states as $state ) { + ++$i; + ( $i == $state_count ) ? $sep = '' : $sep = ', '; + echo "$state$sep"; + } + } +} + +function screen_meta($screen) { + global $wp_meta_boxes, $_wp_contextual_help; + + $screen = str_replace('.php', '', $screen); + $screen = str_replace('-new', '', $screen); + $screen = str_replace('-add', '', $screen); + $screen = apply_filters('screen_meta_screen', $screen); + + $column_screens = get_column_headers($screen); + $meta_screens = array('index' => 'dashboard'); + + if ( isset($meta_screens[$screen]) ) + $screen = $meta_screens[$screen]; + $show_screen = false; + $show_on_screen = false; + if ( !empty($wp_meta_boxes[$screen]) || !empty($column_screens) ) { + $show_screen = true; + $show_on_screen = true; + } + + $screen_options = screen_options($screen); + if ( $screen_options ) + $show_screen = true; + + if ( !isset($_wp_contextual_help) ) + $_wp_contextual_help = array(); + + $settings = ''; + + switch ( $screen ) { + case 'post': + if ( !isset($_wp_contextual_help['post']) ) { + $help = drag_drop_help(); + $help .= '

    ' . __('Writing Posts') . '

    '; + $_wp_contextual_help['post'] = $help; + } + break; + case 'page': + if ( !isset($_wp_contextual_help['page']) ) { + $help = drag_drop_help(); + $_wp_contextual_help['page'] = $help; + } + break; + case 'dashboard': + if ( !isset($_wp_contextual_help['dashboard']) ) { + $help = '

    ' . __('The modules on this screen can be arranged in several columns. You can select the number of columns from the Screen Options tab.') . "

    \n"; + $help .= drag_drop_help(); + $_wp_contextual_help['dashboard'] = $help; + } + break; + case 'link': + if ( !isset($_wp_contextual_help['link']) ) { + $help = drag_drop_help(); + $_wp_contextual_help['link'] = $help; + } + break; + case 'options-general': + if ( !isset($_wp_contextual_help['options-general']) ) + $_wp_contextual_help['options-general'] = __('General Settings'); + break; + case 'theme-install': + case 'plugin-install': + if ( ( !isset($_GET['tab']) || 'dashboard' == $_GET['tab'] ) && !isset($_wp_contextual_help[$screen]) ) { + $help = plugins_search_help(); + $_wp_contextual_help[$screen] = $help; + } + break; + case 'widgets': + if ( !isset($_wp_contextual_help['widgets']) ) { + $help = widgets_help(); + $_wp_contextual_help['widgets'] = $help; + } + $settings = '

    ' . __('Enable accessibility mode') . '' . __('Disable accessibility mode') . "

    \n"; + $show_screen = true; + break; + } +?> +
    + + + + + + + +
    +' . __('Most of the modules on this screen can be moved. If you hover your mouse over the title bar of a module you’ll notice the 4 arrow cursor appears to let you know it is movable. Click on it, hold down the mouse button and start dragging the module to a new location. As you drag the module, notice the dotted gray box that also moves. This box indicates where the module will be placed when you release the mouse button.') . '

    +

    ' . __('The same modules can be expanded and collapsed by clicking once on their title bar and also completely hidden from the Screen Options tab.') . '

    +'; +} + +function plugins_search_help() { + return ' +

    ' . __('Search help') . '

    ' . + '

    ' . __('You may search based on 3 criteria:') . '
    ' . + __('Term: Searches theme names and descriptions for the specified term.') . '
    ' . + __('Tag: Searches for themes tagged as such.') . '
    ' . + __('Author: Searches for themes created by the Author, or which the Author contributed to.') . '

    +'; +} + +function widgets_help() { + return ' +

    ' . __('Widgets are added and arranged by simple drag ’n’ drop. If you hover your mouse over the titlebar of a widget, you’ll see a 4-arrow cursor which indicates that the widget is movable. Click on the titlebar, hold down the mouse button and drag the widget to a sidebar. As you drag, you’ll see a dotted box that also moves. This box shows where the widget will go once you drop it.') . '

    +

    ' . __('To remove a widget from a sidebar, drag it back to Available Widgets or click on the arrow on its titlebar to reveal its settings, and then click Remove.') . '

    +

    ' . __('To remove a widget from a sidebar and keep its configuration, drag it to Inactive Widgets.') . '

    +

    ' . __('The Inactive Widgets area stores widgets that are configured but not curently used. If you change themes and the new theme has fewer sidebars than the old, all extra widgets will be stored to Inactive Widgets automatically.') . '

    +'; +} + +function screen_layout($screen) { + global $screen_layout_columns; + + $columns = array('dashboard' => 4, 'post' => 2, 'page' => 2, 'link' => 2); + $columns = apply_filters('screen_layout_columns', $columns, $screen); + + if ( !isset($columns[$screen]) ) { + $screen_layout_columns = 0; + return ''; + } + + $screen_layout_columns = get_user_option("screen_layout_$screen"); + $num = $columns[$screen]; + + if ( ! $screen_layout_columns ) + $screen_layout_columns = 2; + + $i = 1; + $return = '
    ' . __('Screen Layout') . "
    \n
    " . __('Number of Columns:') . "\n"; + while ( $i <= $num ) { + $return .= "\n"; + ++$i; + } + $return .= "
    \n"; + return $return; +} + +function screen_options($screen) { + switch ( $screen ) { + case 'edit': + $per_page_label = __('Posts per page:'); + break; + case 'edit-pages': + $per_page_label = __('Pages per page:'); + break; + case 'edit-comments': + $per_page_label = __('Comments per page:'); + break; + case 'upload': + $per_page_label = __('Media items per page:'); + break; + case 'categories': + $per_page_label = __('Categories per page:'); + break; + case 'edit-tags': + $per_page_label = __('Tags per page:'); + break; + case 'plugins': + $per_page_label = __('Plugins per page:'); + break; + default: + return ''; + } + + $option = str_replace('-', '_', "${screen}_per_page"); + $per_page = get_user_option($option); + if ( empty($per_page) ) { + if ( 'plugins' == $screen ) + $per_page = 999; + else + $per_page = 20; + } + + $return = '
    ' . __('Options') . "
    \n"; + $return .= "
    \n"; + if ( !empty($per_page_label) ) + $return .= " \n"; + $return .= ""; + $return .= ""; + $return .= "
    \n"; + return $return; +} + +function screen_icon($name = '') { + global $parent_file, $hook_suffix; + + if ( empty($name) ) { + if ( isset($parent_file) && !empty($parent_file) ) + $name = substr($parent_file, 0, -4); + else + $name = str_replace(array('.php', '-new', '-add'), '', $hook_suffix); + } +?> +

    + + + diff --git a/wp-admin/includes/theme-install.php b/wp-admin/includes/theme-install.php new file mode 100644 index 0000000..d704d67 --- /dev/null +++ b/wp-admin/includes/theme-install.php @@ -0,0 +1,547 @@ + array('href' => array(), 'title' => array(), 'target' => array()), + 'abbr' => array('title' => array()), 'acronym' => array('title' => array()), + 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), + 'div' => array(), 'p' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), + 'h1' => array(), 'h2' => array(), 'h3' => array(), 'h4' => array(), 'h5' => array(), 'h6' => array(), + 'img' => array('src' => array(), 'class' => array(), 'alt' => array()) +); + +$theme_field_defaults = array( 'description' => true, 'sections' => false, 'tested' => true, 'requires' => true, + 'rating' => true, 'downloaded' => true, 'downloadlink' => true, 'last_updated' => true, 'homepage' => true, + 'tags' => true, 'num_ratings' => true +); + + +/** + * Retrieve theme installer pages from WordPress Themes API. + * + * It is possible for a theme to override the Themes API result with three + * filters. Assume this is for themes, which can extend on the Theme Info to + * offer more choices. This is very powerful and must be used with care, when + * overridding the filters. + * + * The first filter, 'themes_api_args', is for the args and gives the action as + * the second parameter. The hook for 'themes_api_args' must ensure that an + * object is returned. + * + * The second filter, 'themes_api', is the result that would be returned. + * + * @since 2.8.0 + * + * @param string $action + * @param array|object $args Optional. Arguments to serialize for the Theme Info API. + * @return mixed + */ +function themes_api($action, $args = null) { + + if ( is_array($args) ) + $args = (object)$args; + + if ( !isset($args->per_page) ) + $args->per_page = 24; + + $args = apply_filters('themes_api_args', $args, $action); //NOTE: Ensure that an object is returned via this filter. + $res = apply_filters('themes_api', false, $action, $args); //NOTE: Allows a theme to completely override the builtin WordPress.org API. + + if ( ! $res ) { + $request = wp_remote_post('http://api.wordpress.org/themes/info/1.0/', array( 'body' => array('action' => $action, 'request' => serialize($args))) ); + if ( is_wp_error($request) ) { + $res = new WP_Error('themes_api_failed', __('An Unexpected HTTP Error occured during the API request.

    Try again'), $request->get_error_message() ); + } else { + $res = unserialize($request['body']); + if ( ! $res ) + $res = new WP_Error('themes_api_failed', __('An unknown error occured'), $request['body']); + } + } + //var_dump(array($args, $res)); + return apply_filters('themes_api_result', $res, $action, $args); +} + +/** + * Retrieve list of WordPress theme features (aka theme tags) + * + * @since 2.8.0 + * + * @return array + */ +function install_themes_feature_list( ) { + if ( !$cache = get_transient( 'wporg_theme_feature_list' ) ) + set_transient( 'wporg_theme_feature_list', array( ), 10800); + + if ( $cache ) + return $cache; + + $feature_list = themes_api( 'feature_list', array( ) ); + if ( is_wp_error( $feature_list ) ) + return $features; + + set_transient( 'wporg_theme_feature_list', $feature_list, 10800 ); + + return $feature_list; +} + +add_action('install_themes_search', 'install_theme_search', 10, 1); +/** + * Display theme search results + * + * @since 2.8.0 + * + * @param string $page + */ +function install_theme_search($page) { + global $theme_field_defaults; + + $type = isset($_REQUEST['type']) ? stripslashes( $_REQUEST['type'] ) : ''; + $term = isset($_REQUEST['s']) ? stripslashes( $_REQUEST['s'] ) : ''; + + $args = array(); + + switch( $type ){ + case 'tag': + $terms = explode(',', $term); + $terms = array_map('trim', $terms); + $terms = array_map('sanitize_title_with_dashes', $terms); + $args['tag'] = $terms; + break; + case 'term': + $args['search'] = $term; + break; + case 'author': + $args['author'] = $term; + break; + } + + $args['page'] = $page; + $args['fields'] = $theme_field_defaults; + + if ( !empty( $_POST['features'] ) ) { + $terms = $_POST['features']; + $terms = array_map( 'trim', $terms ); + $terms = array_map( 'sanitize_title_with_dashes', $terms ); + $args['tag'] = $terms; + $_REQUEST['s'] = implode( ',', $terms ); + $_REQUEST['type'] = 'tag'; + } + + $api = themes_api('query_themes', $args); + + if ( is_wp_error($api) ) + wp_die($api); + + add_action('install_themes_table_header', 'install_theme_search_form'); + + display_themes($api->themes, $api->info['page'], $api->info['pages']); +} + +/** + * Display search form for searching themes. + * + * @since 2.8.0 + */ +function install_theme_search_form() { + $type = isset( $_REQUEST['type'] ) ? stripslashes( $_REQUEST['type'] ) : ''; + $term = isset( $_REQUEST['s'] ) ? stripslashes( $_REQUEST['s'] ) : ''; + ?> +

    + +
    + + + +
    + +

    +
    +

    + '; + $trans = array ('Colors' => __('Colors'), 'black' => __('Black'), 'blue' => __('Blue'), 'brown' => __('Brown'), + 'green' => __('Green'), 'orange' => __('Orange'), 'pink' => __('Pink'), 'purple' => __('Purple'), 'red' => __('Red'), + 'silver' => __('Silver'), 'tan' => __('Tan'), 'white' => __('White'), 'yellow' => __('Yellow'), 'dark' => __('Dark'), + 'light' => __('Light'), 'Columns' => __('Columns'), 'one-column' => __('One Column'), 'two-columns' => __('Two Columns'), + 'three-columns' => __('Three Columns'), 'four-columns' => __('Four Columns'), 'left-sidebar' => __('Left Sidebar'), + 'right-sidebar' => __('Right Sidebar'), 'Width' => __('Width'), 'fixed-width' => __('Fixed Width'), 'flexible-width' => __('Flexible Width'), + 'Features' => __('Features'), 'custom-colors' => __('Custom Colors'), 'custom-header' => __('Custom Header'), 'theme-options' => __('Theme Options'), + 'threaded-comments' => __('Threaded Comments'), 'sticky-post' => __('Sticky Post'), 'microformats' => __('Microformats'), + 'Subject' => __('Subject'), 'holiday' => __('Holiday'), 'photoblogging' => __('Photoblogging'), 'seasonal' => __('Seasonal'), + ); + + foreach ( (array) $feature_list as $feature_name => $features ) { + if ( isset($trans[$feature_name]) ) + $feature_name = $trans[$feature_name]; + $feature_name = esc_html( $feature_name ); + echo '
    ' . $feature_name . '
    '; + + echo '
      '; + foreach ( $features as $feature ) { + $feature_name = $feature; + if ( isset($trans[$feature]) ) + $feature_name = $trans[$feature]; + $feature_name = esc_html( $feature_name ); + $feature = esc_attr($feature); +?> + +
    1. + + +
    2. + + +
    +
    + + + +
    +

    +
    + 'featured', 'page' => $page, 'fields' => $theme_field_defaults); + $api = themes_api('query_themes', $args); + if ( is_wp_error($api) ) + wp_die($api); + display_themes($api->themes, $api->info['page'], $api->info['pages']); +} + +add_action('install_themes_new', 'install_themes_new', 10, 1); +/** + * Display new themes/ + * + * @since 2.8.0 + * + * @param string $page + */ +function install_themes_new($page = 1) { + global $theme_field_defaults; + $args = array('browse' => 'new', 'page' => $page, 'fields' => $theme_field_defaults); + $api = themes_api('query_themes', $args); + if ( is_wp_error($api) ) + wp_die($api); + display_themes($api->themes, $api->info['page'], $api->info['pages']); +} + +add_action('install_themes_updated', 'install_themes_updated', 10, 1); +/** + * Display recently updated themes. + * + * @since 2.8.0 + * + * @param string $page + */ +function install_themes_updated($page = 1) { + global $theme_field_defaults; + $args = array('browse' => 'updated', 'page' => $page, 'fields' => $theme_field_defaults); + $api = themes_api('query_themes', $args); + display_themes($api->themes, $api->info['page'], $api->info['pages']); +} + +add_action('install_themes_upload', 'install_themes_upload', 10, 1); +function install_themes_upload($page = 1) { +?> +

    +

    +
    + + + +
    + name, $themes_allowedtags); + $desc = wp_kses($theme->description, $themes_allowedtags); + //if ( strlen($desc) > 30 ) + // $desc = substr($desc, 0, 15) . '...' . substr($desc, -15) . ''; + + $preview_link = $theme->preview_url . '?TB_iframe=true&width=600&height=400'; + if ( !is_array($actions) ) { + $actions = array(); + $actions[] = '' . __('Install') . ''; + $actions[] = '' . __('Preview') . ''; + $actions = apply_filters('theme_install_action_links', $actions, $theme); + } + + $actions = implode ( ' | ', $actions ); + ?> +'> + + +

    + +

    + + +
    +

    version, $themes_allowedtags) ?>

    +

    author, $themes_allowedtags) ?>

    +last_updated) ) : ?> +

    last_updated)) ) ?>

    +requires) ) : ?> +

    requires) ?>

    +tested) ) : ?> +

    tested ?>

    +downloaded) ) : ?> +

    downloaded), number_format_i18n($theme->downloaded)) ?>

    + +
    +
    +
    <?php _e('5 stars') ?>
    +
    <?php _e('4 stars') ?>
    +
    <?php _e('3 stars') ?>
    +
    <?php _e('2 stars') ?>
    +
    <?php _e('1 star') ?>
    +
    +
    + string 'Magazine Basic' (length=14) + public 'slug' => string 'magazine-basic' (length=14) + public 'version' => string '1.1' (length=3) + public 'author' => string 'tinkerpriest' (length=12) + public 'preview_url' => string 'http://wp-themes.com/?magazine-basic' (length=36) + public 'screenshot_url' => string 'http://wp-themes.com/wp-content/themes/magazine-basic/screenshot.png' (length=68) + public 'rating' => float 80 + public 'num_ratings' => int 1 + public 'homepage' => string 'http://wordpress.org/extend/themes/magazine-basic' (length=49) + public 'description' => string 'A basic magazine style layout with a fully customizable layout through a backend interface. Designed by c.bavota of Tinker Priest Media.' (length=214) + public 'download_link' => string 'http://wordpress.org/extend/themes/download/magazine-basic.1.1.zip' (length=66) + */ +} + +/** + * Display theme content based on theme list. + * + * @since 2.8.0 + * + * @param array $themes List of themes. + * @param string $page + * @param int $totalpages Number of pages. + */ +function display_themes($themes, $page = 1, $totalpages = 1) { + global $themes_allowedtags; + + $type = isset($_REQUEST['type']) ? stripslashes( $_REQUEST['type'] ) : ''; + $term = isset($_REQUEST['s']) ? stripslashes( $_REQUEST['s'] ) : ''; + ?> +
    +
    + add_query_arg('paged', '%#%', $url), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => $totalpages, + 'current' => $page + )); + + if ( $page_links ) + echo "\t\t
    $page_links
    "; + ?> +
    +
    + + + $cols ) { + ?> + + $theme_index ) { + $class = array('available-theme'); + if ( $row == 1 ) $class[] = 'top'; + if ( $col == 1 ) $class[] = 'left'; + if ( $row == $rows ) $class[] = 'bottom'; + if ( $col == 3 ) $class[] = 'right'; + ?> + + + + +
    + +
    $page_links
    "; ?>
    + + + stripslashes( $_REQUEST['theme'] ) )); + + if ( is_wp_error($api) ) + wp_die($api); + + // Sanitize HTML + foreach ( (array)$api->sections as $section_name => $content ) + $api->sections[$section_name] = wp_kses($content, $themes_allowedtags); + foreach ( array('version', 'author', 'requires', 'tested', 'homepage', 'downloaded', 'slug') as $key ) + $api->$key = wp_kses($api->$key, $themes_allowedtags); + + iframe_header( __('Theme Install') ); + + if ( empty($api->download_link) ) { + echo '

    ' . __('Error: This theme is currently not available. Please try again later.') . '

    '; + iframe_footer(); + exit; + } + + if ( !empty($api->tested) && version_compare($GLOBALS['wp_version'], $api->tested, '>') ) + echo '

    ' . __('Warning: This theme has not been tested with your current version of WordPress.') . '

    '; + else if ( !empty($api->requires) && version_compare($GLOBALS['wp_version'], $api->requires, '<') ) + echo '

    ' . __('Warning: This theme has not been marked as compatible with your version of WordPress.') . '

    '; + + // Default to a "new" theme + $type = 'install'; + // Check to see if this theme is known to be installed, and has an update awaiting it. + $update_themes = get_transient('update_themes'); + if ( is_object($update_themes) && isset($update_themes->response) ) { + foreach ( (array)$update_themes->response as $theme_slug => $theme_info ) { + if ( $theme_slug === $api->slug ) { + $type = 'update_available'; + $update_file = $theme_slug; + break; + } + } + } + + $themes = get_themes(); + foreach ( $themes as $this_theme ) { + if ( is_array($this_theme) && $this_theme['Stylesheet'] == $api->slug ) { + if ( $this_theme['Version'] == $api->version ) { + $type = 'latest_installed'; + } elseif ( $this_theme['Version'] > $api->version ) { + $type = 'newer_installed'; + $newer_version = $this_theme['Version']; + } + break; + } + } +?> + +
    + +

    name; ?>

    +

    author); ?>

    +

    version); ?>

    + +' . __('Cancel') . ' '; + +switch ( $type ) { +default: +case 'install': + if ( current_user_can('install_themes') ) : + $buttons .= '' . __('Install Now') . ''; + endif; + break; +case 'update_available': + if ( current_user_can('update_themes') ) : + $buttons .= '' . __('Install Update Now') . ''; + endif; + break; +case 'newer_installed': + if ( current_user_can('install_themes') || current_user_can('update_themes') ) : + ?>

    +
    +
    + +

    + +
    +

    + +name = $current_theme; + $ct->title = $themes[$current_theme]['Title']; + $ct->version = $themes[$current_theme]['Version']; + $ct->parent_theme = $themes[$current_theme]['Parent Theme']; + $ct->template_dir = $themes[$current_theme]['Template Dir']; + $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir']; + $ct->template = $themes[$current_theme]['Template']; + $ct->stylesheet = $themes[$current_theme]['Stylesheet']; + $ct->screenshot = $themes[$current_theme]['Screenshot']; + $ct->description = $themes[$current_theme]['Description']; + $ct->author = $themes[$current_theme]['Author']; + $ct->tags = $themes[$current_theme]['Tags']; + return $ct; +} + +/** + * Remove a theme + * + * @since 2.8.0 + * + * @param string $template Template directory of the theme to delete + * @return mixed + */ +function delete_theme($template) { + global $wp_filesystem; + + if ( empty($template) ) + return false; + + ob_start(); + $url = wp_nonce_url('themes.php?action=delete&template=' . $template, 'delete-theme_' . $template); + if ( false === ($credentials = request_filesystem_credentials($url)) ) { + $data = ob_get_contents(); + ob_end_clean(); + if ( ! empty($data) ){ + include_once( ABSPATH . 'wp-admin/admin-header.php'); + echo $data; + include( ABSPATH . 'wp-admin/admin-footer.php'); + exit; + } + return; + } + + if ( ! WP_Filesystem($credentials) ) { + request_filesystem_credentials($url, '', true); // Failed to connect, Error and request again + $data = ob_get_contents(); + ob_end_clean(); + if( ! empty($data) ){ + include_once( ABSPATH . 'wp-admin/admin-header.php'); + echo $data; + include( ABSPATH . 'wp-admin/admin-footer.php'); + exit; + } + return; + } + + + if ( ! is_object($wp_filesystem) ) + return new WP_Error('fs_unavailable', __('Could not access filesystem.')); + + if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() ) + return new WP_Error('fs_error', __('Filesystem error'), $wp_filesystem->errors); + + //Get the base plugin folder + $themes_dir = $wp_filesystem->wp_themes_dir(); + if ( empty($themes_dir) ) + return new WP_Error('fs_no_themes_dir', __('Unable to locate WordPress theme directory.')); + + $themes_dir = trailingslashit( $themes_dir ); + + $errors = array(); + + $theme_dir = trailingslashit($themes_dir . $template); + $deleted = $wp_filesystem->delete($theme_dir, true); + + if ( ! $deleted ) + return new WP_Error('could_not_remove_theme', sprintf(__('Could not fully remove the theme %s'), $template) ); + + // Force refresh of theme update information + delete_transient('update_themes'); + + return true; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function get_broken_themes() { + global $wp_broken_themes; + + get_themes(); + return $wp_broken_themes; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @return unknown + */ +function get_page_templates() { + $themes = get_themes(); + $theme = get_current_theme(); + $templates = $themes[$theme]['Template Files']; + $page_templates = array (); + + if ( is_array( $templates ) ) { + foreach ( $templates as $template ) { + $template_data = implode( '', file( WP_CONTENT_DIR.$template )); + + $name = ''; + if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) + $name = _cleanup_header_comment($name[1]); + + if ( !empty( $name ) ) { + $page_templates[trim( $name )] = basename( $template ); + } + } + } + + return $page_templates; +} + +?> diff --git a/wp-admin/includes/update-core.php b/wp-admin/includes/update-core.php new file mode 100644 index 0000000..5abee75 --- /dev/null +++ b/wp-admin/includes/update-core.php @@ -0,0 +1,262 @@ +exists($from . '/wordpress/wp-settings.php') || !$wp_filesystem->exists($from . '/wordpress/wp-admin/admin.php') || + !$wp_filesystem->exists($from . '/wordpress/wp-includes/functions.php') ) { + $wp_filesystem->delete($from, true); + return new WP_Error('insane_distro', __('The update could not be unpacked') ); + } + + apply_filters('update_feedback', __('Installing the latest version')); + + // Create maintenance file to signal that we are upgrading + $maintenance_string = ''; + $maintenance_file = $to . '.maintenance'; + $wp_filesystem->delete($maintenance_file); + $wp_filesystem->put_contents($maintenance_file, $maintenance_string, FS_CHMOD_FILE); + + // Copy new versions of WP files into place. + $result = copy_dir($from . '/wordpress', $to); + if ( is_wp_error($result) ) { + $wp_filesystem->delete($maintenance_file); + $wp_filesystem->delete($from, true); + return $result; + } + + // Remove old files + foreach ( $_old_files as $old_file ) { + $old_file = $to . $old_file; + if ( !$wp_filesystem->exists($old_file) ) + continue; + $wp_filesystem->delete($old_file, true); + } + + // Upgrade DB with separate request + apply_filters('update_feedback', __('Upgrading database')); + $db_upgrade_url = admin_url('upgrade.php?step=upgrade_db'); + wp_remote_post($db_upgrade_url, array('timeout' => 60)); + + // Remove working directory + $wp_filesystem->delete($from, true); + + // Force refresh of update information + if ( function_exists('delete_transient') ) + delete_transient('update_core'); + else + delete_option('update_core'); + + // Remove maintenance file, we're done. + $wp_filesystem->delete($maintenance_file); +} + +?> diff --git a/wp-admin/includes/update.php b/wp-admin/includes/update.php new file mode 100644 index 0000000..0db0882 --- /dev/null +++ b/wp-admin/includes/update.php @@ -0,0 +1,220 @@ + 'latest'); + return $updates[0]; +} + +/** + * Get available core updates + * + * @param array $options Set $options['dismissed'] to true to show dismissed upgrades too, + * set $options['available'] to false to skip not-dimissed updates. + * @return array Array of the update objects + */ +function get_core_updates( $options = array() ) { + $options = array_merge( array('available' => true, 'dismissed' => false ), $options ); + $dismissed = get_option( 'dismissed_update_core' ); + if ( !is_array( $dismissed ) ) $dismissed = array(); + $from_api = get_transient( 'update_core' ); + if ( empty($from_api) ) + return false; + if ( !isset( $from_api->updates ) || !is_array( $from_api->updates ) ) return false; + $updates = $from_api->updates; + if ( !is_array( $updates ) ) return false; + $result = array(); + foreach($updates as $update) { + if ( array_key_exists( $update->current.'|'.$update->locale, $dismissed ) ) { + if ( $options['dismissed'] ) { + $update->dismissed = true; + $result[]= $update; + } + } else { + if ( $options['available'] ) { + $update->dismissed = false; + $result[]= $update; + } + } + } + return $result; +} + +function dismiss_core_update( $update ) { + $dismissed = get_option( 'dismissed_update_core' ); + $dismissed[ $update->current.'|'.$update->locale ] = true; + return update_option( 'dismissed_update_core', $dismissed ); +} + +function undismiss_core_update( $version, $locale ) { + $dismissed = get_option( 'dismissed_update_core' ); + $key = $version.'|'.$locale; + if ( !isset( $dismissed[$key] ) ) return false; + unset( $dismissed[$key] ); + return update_option( 'dismissed_update_core', $dismissed ); +} + +function find_core_update( $version, $locale ) { + $from_api = get_transient( 'update_core' ); + if ( !is_array( $from_api->updates ) ) return false; + $updates = $from_api->updates; + foreach($updates as $update) { + if ( $update->current == $version && $update->locale == $locale ) + return $update; + } + return false; +} + +function core_update_footer( $msg = '' ) { + if ( !current_user_can('manage_options') ) + return sprintf( __( 'Version %s' ), $GLOBALS['wp_version'] ); + + $cur = get_preferred_from_update_core(); + if ( ! isset( $cur->current ) ) + $cur->current = ''; + + if ( ! isset( $cur->url ) ) + $cur->url = ''; + + if ( ! isset( $cur->response ) ) + $cur->response = ''; + + switch ( $cur->response ) { + case 'development' : + return sprintf( __( 'You are using a development version (%1$s). Cool! Please stay updated.' ), $GLOBALS['wp_version'], 'update-core.php'); + break; + + case 'upgrade' : + if ( current_user_can('manage_options') ) { + return sprintf( ''.__( 'Get Version %2$s' ).'', 'update-core.php', $cur->current); + break; + } + + case 'latest' : + default : + return sprintf( __( 'Version %s' ), $GLOBALS['wp_version'] ); + break; + } +} +add_filter( 'update_footer', 'core_update_footer' ); + +function update_nag() { + global $pagenow; + + if ( 'update-core.php' == $pagenow ) + return; + + $cur = get_preferred_from_update_core(); + + if ( ! isset( $cur->response ) || $cur->response != 'upgrade' ) + return false; + + if ( current_user_can('manage_options') ) + $msg = sprintf( __('WordPress %1$s is available! Please update now.'), $cur->current, 'update-core.php' ); + else + $msg = sprintf( __('WordPress %1$s is available! Please notify the site administrator.'), $cur->current ); + + echo "
    $msg
    "; +} +add_action( 'admin_notices', 'update_nag', 3 ); + +// Called directly from dashboard +function update_right_now_message() { + $cur = get_preferred_from_update_core(); + + $msg = sprintf( __('You are using WordPress %s.'), $GLOBALS['wp_version'] ); + if ( isset( $cur->response ) && $cur->response == 'upgrade' && current_user_can('manage_options') ) + $msg .= " " . sprintf( __('Update to %s'), $cur->current ? $cur->current : __( 'Latest' ) ) . ''; + + echo "$msg"; +} + +function wp_plugin_update_row( $file, $plugin_data ) { + $current = get_transient( 'update_plugins' ); + if ( !isset( $current->response[ $file ] ) ) + return false; + + $r = $current->response[ $file ]; + + $plugins_allowedtags = array('a' => array('href' => array(),'title' => array()),'abbr' => array('title' => array()),'acronym' => array('title' => array()),'code' => array(),'em' => array(),'strong' => array()); + $plugin_name = wp_kses( $plugin_data['Name'], $plugins_allowedtags ); + + $details_url = admin_url('plugin-install.php?tab=plugin-information&plugin=' . $r->slug . '&TB_iframe=true&width=600&height=800'); + + echo '
    '; + if ( ! current_user_can('update_plugins') ) + printf( __('There is a new version of %1$s available. View version %4$s Details.'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version ); + else if ( empty($r->package) ) + printf( __('There is a new version of %1$s available. View version %4$s Details automatic upgrade unavailable for this plugin.'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version ); + else + printf( __('There is a new version of %1$s available. View version %4$s Details or upgrade automatically.'), $plugin_name, esc_url($details_url), esc_attr($plugin_name), $r->new_version, wp_nonce_url('update.php?action=upgrade-plugin&plugin=' . $file, 'upgrade-plugin_' . $file) ); + + do_action( "in_plugin_update_message-$file", $plugin_data, $r ); + + echo '
    '; +} +add_action( 'after_plugin_row', 'wp_plugin_update_row', 10, 2 ); + +function wp_update_plugin($plugin, $feedback = '') { + + if ( !empty($feedback) ) + add_filter('update_feedback', $feedback); + + include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; + $upgrader = new Plugin_Upgrader(); + return $upgrader->upgrade($plugin); +} + +function wp_update_theme($theme, $feedback = '') { + + if ( !empty($feedback) ) + add_filter('update_feedback', $feedback); + + include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; + $upgrader = new Theme_Upgrader(); + return $upgrader->upgrade($theme); +} + + +function wp_update_core($current, $feedback = '') { + + if ( !empty($feedback) ) + add_filter('update_feedback', $feedback); + + include ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; + $upgrader = new Core_Upgrader(); + return $upgrader->upgrade($current); + +} + +function maintenance_nag() { + global $upgrading; + if ( ! isset( $upgrading ) ) + return false; + + if ( current_user_can('manage_options') ) + $msg = sprintf( __('An automated WordPress update has failed to complete - please attempt the update again now.'), 'update-core.php' ); + else + $msg = __('An automated WordPress update has failed to complete! Please notify the site administrator.'); + + echo "
    $msg
    "; +} +add_action( 'admin_notices', 'maintenance_nag' ); + +?> diff --git a/wp-admin/includes/upgrade.php b/wp-admin/includes/upgrade.php new file mode 100644 index 0000000..a4d5aba --- /dev/null +++ b/wp-admin/includes/upgrade.php @@ -0,0 +1,1659 @@ +Note that password carefully! It is a random password that was generated just for you.'); + $user_id = wp_create_user($user_name, $random_password, $user_email); + update_usermeta($user_id, 'default_password_nag', true); + } else { + $random_password = ''; + $message = __('User already exists. Password inherited.'); + } + + $user = new WP_User($user_id); + $user->set_role('administrator'); + + wp_install_defaults($user_id); + + $wp_rewrite->flush_rules(); + + wp_new_blog_notification($blog_title, $guessurl, $user_id, $random_password); + + wp_cache_flush(); + + return array('url' => $guessurl, 'user_id' => $user_id, 'password' => $random_password, 'password_message' => $message); +} +endif; + +if ( !function_exists('wp_install_defaults') ) : +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param int $user_id User ID. + */ +function wp_install_defaults($user_id) { + global $wpdb; + + // Default category + $cat_name = __('Uncategorized'); + /* translators: Default category slug */ + $cat_slug = sanitize_title(_x('Uncategorized', 'Default category slug')); + + $wpdb->insert( $wpdb->terms, array('name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) ); + $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => '1', 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1)); + + // Default link category + $cat_name = __('Blogroll'); + /* translators: Default link category slug */ + $cat_slug = sanitize_title(_x('Blogroll', 'Default link category slug')); + + $wpdb->insert( $wpdb->terms, array('name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) ); + $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => '2', 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 7)); + + // Now drop in some default links + $default_links = array(); + $default_links[] = array( 'link_url' => 'http://codex.wordpress.org/', + 'link_name' => 'Documentation', + 'link_rss' => '', + 'link_notes' => ''); + + $default_links[] = array( 'link_url' => 'http://wordpress.org/development/', + 'link_name' => 'Development Blog', + 'link_rss' => 'http://wordpress.org/development/feed/', + 'link_notes' => ''); + + $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/ideas/', + 'link_name' => 'Suggest Ideas', + 'link_rss' => '', + 'link_notes' =>''); + + $default_links[] = array( 'link_url' => 'http://wordpress.org/support/', + 'link_name' => 'Support Forum', + 'link_rss' => '', + 'link_notes' =>''); + + $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/plugins/', + 'link_name' => 'Plugins', + 'link_rss' => '', + 'link_notes' =>''); + + $default_links[] = array( 'link_url' => 'http://wordpress.org/extend/themes/', + 'link_name' => 'Themes', + 'link_rss' => '', + 'link_notes' =>''); + + $default_links[] = array( 'link_url' => 'http://planet.wordpress.org/', + 'link_name' => 'WordPress Planet', + 'link_rss' => '', + 'link_notes' =>''); + + foreach ( $default_links as $link ) { + $wpdb->insert( $wpdb->links, $link); + $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => 2, 'object_id' => $wpdb->insert_id) ); + } + + // First post + $now = date('Y-m-d H:i:s'); + $now_gmt = gmdate('Y-m-d H:i:s'); + $first_post_guid = get_option('home') . '/?p=1'; + + $wpdb->insert( $wpdb->posts, array( + 'post_author' => $user_id, + 'post_date' => $now, + 'post_date_gmt' => $now_gmt, + 'post_content' => __('Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!'), + 'post_excerpt' => '', + 'post_title' => __('Hello world!'), + /* translators: Default post slug */ + 'post_name' => _x('hello-world', 'Default post slug'), + 'post_modified' => $now, + 'post_modified_gmt' => $now_gmt, + 'guid' => $first_post_guid, + 'comment_count' => 1, + 'to_ping' => '', + 'pinged' => '', + 'post_content_filtered' => '' + )); + $wpdb->insert( $wpdb->term_relationships, array('term_taxonomy_id' => 1, 'object_id' => 1) ); + + // Default comment + $wpdb->insert( $wpdb->comments, array( + 'comment_post_ID' => 1, + 'comment_author' => __('Mr WordPress'), + 'comment_author_email' => '', + 'comment_author_url' => 'http://wordpress.org/', + 'comment_date' => $now, + 'comment_date_gmt' => $now_gmt, + 'comment_content' => __('Hi, this is a comment.
    To delete a comment, just log in and view the post's comments. There you will have the option to edit or delete them.') + )); + // First Page + $first_post_guid = get_option('home') . '/?page_id=2'; + $wpdb->insert( $wpdb->posts, array( + 'post_author' => $user_id, + 'post_date' => $now, + 'post_date_gmt' => $now_gmt, + 'post_content' => __('This is an example of a WordPress page, you could edit this to put information about yourself or your site so readers know where you are coming from. You can create as many pages like this one or sub-pages as you like and manage all of your content inside of WordPress.'), + 'post_excerpt' => '', + 'post_title' => __('About'), + /* translators: Default page slug */ + 'post_name' => _x('about', 'Default page slug'), + 'post_modified' => $now, + 'post_modified_gmt' => $now_gmt, + 'guid' => $first_post_guid, + 'post_type' => 'page', + 'to_ping' => '', + 'pinged' => '', + 'post_content_filtered' => '' + )); +} +endif; + +if ( !function_exists('wp_new_blog_notification') ) : +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param string $blog_title Blog title. + * @param string $blog_url Blog url. + * @param int $user_id User ID. + * @param string $password User's Password. + */ +function wp_new_blog_notification($blog_title, $blog_url, $user_id, $password) { + $user = new WP_User($user_id); + $email = $user->user_email; + $name = $user->user_login; + $message = sprintf(__("Your new WordPress blog has been successfully set up at: + +%1\$s + +You can log in to the administrator account with the following information: + +Username: %2\$s +Password: %3\$s + +We hope you enjoy your new blog. Thanks! + +--The WordPress Team +http://wordpress.org/ +"), $blog_url, $name, $password); + + @wp_mail($email, __('New WordPress Blog'), $message); +} +endif; + +if ( !function_exists('wp_upgrade') ) : +/** + * Run WordPress Upgrade functions. + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @return null + */ +function wp_upgrade() { + global $wp_current_db_version, $wp_db_version; + + $wp_current_db_version = __get_option('db_version'); + + // We are up-to-date. Nothing to do. + if ( $wp_db_version == $wp_current_db_version ) + return; + + if( ! is_blog_installed() ) + return; + + wp_check_mysql_version(); + wp_cache_flush(); + make_db_current_silent(); + upgrade_all(); + wp_cache_flush(); +} +endif; + +/** + * Functions to be called in install and upgrade scripts. + * + * {@internal Missing Long Description}} + * + * @since unknown + */ +function upgrade_all() { + global $wp_current_db_version, $wp_db_version, $wp_rewrite; + $wp_current_db_version = __get_option('db_version'); + + // We are up-to-date. Nothing to do. + if ( $wp_db_version == $wp_current_db_version ) + return; + + // If the version is not set in the DB, try to guess the version. + if ( empty($wp_current_db_version) ) { + $wp_current_db_version = 0; + + // If the template option exists, we have 1.5. + $template = __get_option('template'); + if ( !empty($template) ) + $wp_current_db_version = 2541; + } + + if ( $wp_current_db_version < 6039 ) + upgrade_230_options_table(); + + populate_options(); + + if ( $wp_current_db_version < 2541 ) { + upgrade_100(); + upgrade_101(); + upgrade_110(); + upgrade_130(); + } + + if ( $wp_current_db_version < 3308 ) + upgrade_160(); + + if ( $wp_current_db_version < 4772 ) + upgrade_210(); + + if ( $wp_current_db_version < 4351 ) + upgrade_old_slugs(); + + if ( $wp_current_db_version < 5539 ) + upgrade_230(); + + if ( $wp_current_db_version < 6124 ) + upgrade_230_old_tables(); + + if ( $wp_current_db_version < 7499 ) + upgrade_250(); + + if ( $wp_current_db_version < 7796 ) + upgrade_251(); + + if ( $wp_current_db_version < 7935 ) + upgrade_252(); + + if ( $wp_current_db_version < 8201 ) + upgrade_260(); + + if ( $wp_current_db_version < 8989 ) + upgrade_270(); + + if ( $wp_current_db_version < 10360 ) + upgrade_280(); + + maybe_disable_automattic_widgets(); + + update_option( 'db_version', $wp_db_version ); + update_option( 'db_upgraded', true ); +} + +/** + * Execute changes made in WordPress 1.0. + * + * @since 1.0.0 + */ +function upgrade_100() { + global $wpdb; + + // Get the title and ID of every post, post_name to check if it already has a value + $posts = $wpdb->get_results("SELECT ID, post_title, post_name FROM $wpdb->posts WHERE post_name = ''"); + if ($posts) { + foreach($posts as $post) { + if ('' == $post->post_name) { + $newtitle = sanitize_title($post->post_title); + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_name = %s WHERE ID = %d", $newtitle, $post->ID) ); + } + } + } + + $categories = $wpdb->get_results("SELECT cat_ID, cat_name, category_nicename FROM $wpdb->categories"); + foreach ($categories as $category) { + if ('' == $category->category_nicename) { + $newtitle = sanitize_title($category->cat_name); + $wpdb>update( $wpdb->categories, array('category_nicename' => $newtitle), array('cat_ID' => $category->cat_ID) ); + } + } + + $wpdb->query("UPDATE $wpdb->options SET option_value = REPLACE(option_value, 'wp-links/links-images/', 'wp-images/links/') + WHERE option_name LIKE 'links_rating_image%' + AND option_value LIKE 'wp-links/links-images/%'"); + + $done_ids = $wpdb->get_results("SELECT DISTINCT post_id FROM $wpdb->post2cat"); + if ($done_ids) : + foreach ($done_ids as $done_id) : + $done_posts[] = $done_id->post_id; + endforeach; + $catwhere = ' AND ID NOT IN (' . implode(',', $done_posts) . ')'; + else: + $catwhere = ''; + endif; + + $allposts = $wpdb->get_results("SELECT ID, post_category FROM $wpdb->posts WHERE post_category != '0' $catwhere"); + if ($allposts) : + foreach ($allposts as $post) { + // Check to see if it's already been imported + $cat = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->post2cat WHERE post_id = %d AND category_id = %d", $post->ID, $post->post_category) ); + if (!$cat && 0 != $post->post_category) { // If there's no result + $wpdb->insert( $wpdb->post2cat, array('post_id' => $post->ID, 'category_id' => $post->post_category) ); + } + } + endif; +} + +/** + * Execute changes made in WordPress 1.0.1. + * + * @since 1.0.1 + */ +function upgrade_101() { + global $wpdb; + + // Clean up indices, add a few + add_clean_index($wpdb->posts, 'post_name'); + add_clean_index($wpdb->posts, 'post_status'); + add_clean_index($wpdb->categories, 'category_nicename'); + add_clean_index($wpdb->comments, 'comment_approved'); + add_clean_index($wpdb->comments, 'comment_post_ID'); + add_clean_index($wpdb->links , 'link_category'); + add_clean_index($wpdb->links , 'link_visible'); +} + +/** + * Execute changes made in WordPress 1.2. + * + * @since 1.2.0 + */ +function upgrade_110() { + global $wpdb; + + // Set user_nicename. + $users = $wpdb->get_results("SELECT ID, user_nickname, user_nicename FROM $wpdb->users"); + foreach ($users as $user) { + if ('' == $user->user_nicename) { + $newname = sanitize_title($user->user_nickname); + $wpdb->update( $wpdb->users, array('user_nicename' => $newname), array('ID' => $user->ID) ); + } + } + + $users = $wpdb->get_results("SELECT ID, user_pass from $wpdb->users"); + foreach ($users as $row) { + if (!preg_match('/^[A-Fa-f0-9]{32}$/', $row->user_pass)) { + $wpdb->update( $wpdb->users, array('user_pass' => md5($row->user_pass)), array('ID' => $row->ID) ); + } + } + + // Get the GMT offset, we'll use that later on + $all_options = get_alloptions_110(); + + $time_difference = $all_options->time_difference; + + $server_time = time()+date('Z'); + $weblogger_time = $server_time + $time_difference*3600; + $gmt_time = time(); + + $diff_gmt_server = ($gmt_time - $server_time) / 3600; + $diff_weblogger_server = ($weblogger_time - $server_time) / 3600; + $diff_gmt_weblogger = $diff_gmt_server - $diff_weblogger_server; + $gmt_offset = -$diff_gmt_weblogger; + + // Add a gmt_offset option, with value $gmt_offset + add_option('gmt_offset', $gmt_offset); + + // Check if we already set the GMT fields (if we did, then + // MAX(post_date_gmt) can't be '0000-00-00 00:00:00' + // I just slapped myself silly for not thinking about it earlier + $got_gmt_fields = ($wpdb->get_var("SELECT MAX(post_date_gmt) FROM $wpdb->posts") == '0000-00-00 00:00:00') ? false : true; + + if (!$got_gmt_fields) { + + // Add or substract time to all dates, to get GMT dates + $add_hours = intval($diff_gmt_weblogger); + $add_minutes = intval(60 * ($diff_gmt_weblogger - $add_hours)); + $wpdb->query("UPDATE $wpdb->posts SET post_date_gmt = DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"); + $wpdb->query("UPDATE $wpdb->posts SET post_modified = post_date"); + $wpdb->query("UPDATE $wpdb->posts SET post_modified_gmt = DATE_ADD(post_modified, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE) WHERE post_modified != '0000-00-00 00:00:00'"); + $wpdb->query("UPDATE $wpdb->comments SET comment_date_gmt = DATE_ADD(comment_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"); + $wpdb->query("UPDATE $wpdb->users SET user_registered = DATE_ADD(user_registered, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"); + } + +} + +/** + * Execute changes made in WordPress 1.5. + * + * @since 1.5.0 + */ +function upgrade_130() { + global $wpdb; + + // Remove extraneous backslashes. + $posts = $wpdb->get_results("SELECT ID, post_title, post_content, post_excerpt, guid, post_date, post_name, post_status, post_author FROM $wpdb->posts"); + if ($posts) { + foreach($posts as $post) { + $post_content = addslashes(deslash($post->post_content)); + $post_title = addslashes(deslash($post->post_title)); + $post_excerpt = addslashes(deslash($post->post_excerpt)); + if ( empty($post->guid) ) + $guid = get_permalink($post->ID); + else + $guid = $post->guid; + + $wpdb->update( $wpdb->posts, compact('post_title', 'post_content', 'post_excerpt', 'guid'), array('ID' => $post->ID) ); + + } + } + + // Remove extraneous backslashes. + $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_content FROM $wpdb->comments"); + if ($comments) { + foreach($comments as $comment) { + $comment_content = deslash($comment->comment_content); + $comment_author = deslash($comment->comment_author); + + $wpdb->update($wpdb->comments, compact('comment_content', 'comment_author'), array('comment_ID' => $comment->comment_ID) ); + } + } + + // Remove extraneous backslashes. + $links = $wpdb->get_results("SELECT link_id, link_name, link_description FROM $wpdb->links"); + if ($links) { + foreach($links as $link) { + $link_name = deslash($link->link_name); + $link_description = deslash($link->link_description); + + $wpdb->update( $wpdb->links, compact('link_name', 'link_description'), array('link_id' => $link->link_id) ); + } + } + + $active_plugins = __get_option('active_plugins'); + + // If plugins are not stored in an array, they're stored in the old + // newline separated format. Convert to new format. + if ( !is_array( $active_plugins ) ) { + $active_plugins = explode("\n", trim($active_plugins)); + update_option('active_plugins', $active_plugins); + } + + // Obsolete tables + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optionvalues'); + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiontypes'); + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroups'); + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'optiongroup_options'); + + // Update comments table to use comment_type + $wpdb->query("UPDATE $wpdb->comments SET comment_type='trackback', comment_content = REPLACE(comment_content, '', '') WHERE comment_content LIKE '%'"); + $wpdb->query("UPDATE $wpdb->comments SET comment_type='pingback', comment_content = REPLACE(comment_content, '', '') WHERE comment_content LIKE '%'"); + + // Some versions have multiple duplicate option_name rows with the same values + $options = $wpdb->get_results("SELECT option_name, COUNT(option_name) AS dupes FROM `$wpdb->options` GROUP BY option_name"); + foreach ( $options as $option ) { + if ( 1 != $option->dupes ) { // Could this be done in the query? + $limit = $option->dupes - 1; + $dupe_ids = $wpdb->get_col( $wpdb->prepare("SELECT option_id FROM $wpdb->options WHERE option_name = %s LIMIT %d", $option->option_name, $limit) ); + $dupe_ids = join($dupe_ids, ','); + $wpdb->query("DELETE FROM $wpdb->options WHERE option_id IN ($dupe_ids)"); + } + } + + make_site_theme(); +} + +/** + * Execute changes made in WordPress 2.0. + * + * @since 2.0.0 + */ +function upgrade_160() { + global $wpdb, $wp_current_db_version; + + populate_roles_160(); + + $users = $wpdb->get_results("SELECT * FROM $wpdb->users"); + foreach ( $users as $user ) : + if ( !empty( $user->user_firstname ) ) + update_usermeta( $user->ID, 'first_name', $wpdb->escape($user->user_firstname) ); + if ( !empty( $user->user_lastname ) ) + update_usermeta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) ); + if ( !empty( $user->user_nickname ) ) + update_usermeta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) ); + if ( !empty( $user->user_level ) ) + update_usermeta( $user->ID, $wpdb->prefix . 'user_level', $user->user_level ); + if ( !empty( $user->user_icq ) ) + update_usermeta( $user->ID, 'icq', $wpdb->escape($user->user_icq) ); + if ( !empty( $user->user_aim ) ) + update_usermeta( $user->ID, 'aim', $wpdb->escape($user->user_aim) ); + if ( !empty( $user->user_msn ) ) + update_usermeta( $user->ID, 'msn', $wpdb->escape($user->user_msn) ); + if ( !empty( $user->user_yim ) ) + update_usermeta( $user->ID, 'yim', $wpdb->escape($user->user_icq) ); + if ( !empty( $user->user_description ) ) + update_usermeta( $user->ID, 'description', $wpdb->escape($user->user_description) ); + + if ( isset( $user->user_idmode ) ): + $idmode = $user->user_idmode; + if ($idmode == 'nickname') $id = $user->user_nickname; + if ($idmode == 'login') $id = $user->user_login; + if ($idmode == 'firstname') $id = $user->user_firstname; + if ($idmode == 'lastname') $id = $user->user_lastname; + if ($idmode == 'namefl') $id = $user->user_firstname.' '.$user->user_lastname; + if ($idmode == 'namelf') $id = $user->user_lastname.' '.$user->user_firstname; + if (!$idmode) $id = $user->user_nickname; + $wpdb->update( $wpdb->users, array('display_name' => $id), array('ID' => $user->ID) ); + endif; + + // FIXME: RESET_CAPS is temporary code to reset roles and caps if flag is set. + $caps = get_usermeta( $user->ID, $wpdb->prefix . 'capabilities'); + if ( empty($caps) || defined('RESET_CAPS') ) { + $level = get_usermeta($user->ID, $wpdb->prefix . 'user_level'); + $role = translate_level_to_role($level); + update_usermeta( $user->ID, $wpdb->prefix . 'capabilities', array($role => true) ); + } + + endforeach; + $old_user_fields = array( 'user_firstname', 'user_lastname', 'user_icq', 'user_aim', 'user_msn', 'user_yim', 'user_idmode', 'user_ip', 'user_domain', 'user_browser', 'user_description', 'user_nickname', 'user_level' ); + $wpdb->hide_errors(); + foreach ( $old_user_fields as $old ) + $wpdb->query("ALTER TABLE $wpdb->users DROP $old"); + $wpdb->show_errors(); + + // populate comment_count field of posts table + $comments = $wpdb->get_results( "SELECT comment_post_ID, COUNT(*) as c FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID" ); + if( is_array( $comments ) ) + foreach ($comments as $comment) + $wpdb->update( $wpdb->posts, array('comment_count' => $comment->c), array('ID' => $comment->comment_post_ID) ); + + // Some alpha versions used a post status of object instead of attachment and put + // the mime type in post_type instead of post_mime_type. + if ( $wp_current_db_version > 2541 && $wp_current_db_version <= 3091 ) { + $objects = $wpdb->get_results("SELECT ID, post_type FROM $wpdb->posts WHERE post_status = 'object'"); + foreach ($objects as $object) { + $wpdb->update( $wpdb->posts, array( 'post_status' => 'attachment', + 'post_mime_type' => $object->post_type, + 'post_type' => ''), + array( 'ID' => $object->ID ) ); + + $meta = get_post_meta($object->ID, 'imagedata', true); + if ( ! empty($meta['file']) ) + update_attached_file( $object->ID, $meta['file'] ); + } + } +} + +/** + * Execute changes made in WordPress 2.1. + * + * @since 2.1.0 + */ +function upgrade_210() { + global $wpdb, $wp_current_db_version; + + if ( $wp_current_db_version < 3506 ) { + // Update status and type. + $posts = $wpdb->get_results("SELECT ID, post_status FROM $wpdb->posts"); + + if ( ! empty($posts) ) foreach ($posts as $post) { + $status = $post->post_status; + $type = 'post'; + + if ( 'static' == $status ) { + $status = 'publish'; + $type = 'page'; + } else if ( 'attachment' == $status ) { + $status = 'inherit'; + $type = 'attachment'; + } + + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_status = %s, post_type = %s WHERE ID = %d", $status, $type, $post->ID) ); + } + } + + if ( $wp_current_db_version < 3845 ) { + populate_roles_210(); + } + + if ( $wp_current_db_version < 3531 ) { + // Give future posts a post_status of future. + $now = gmdate('Y-m-d H:i:59'); + $wpdb->query ("UPDATE $wpdb->posts SET post_status = 'future' WHERE post_status = 'publish' AND post_date_gmt > '$now'"); + + $posts = $wpdb->get_results("SELECT ID, post_date FROM $wpdb->posts WHERE post_status ='future'"); + if ( !empty($posts) ) + foreach ( $posts as $post ) + wp_schedule_single_event(mysql2date('U', $post->post_date, false), 'publish_future_post', array($post->ID)); + } +} + +/** + * Execute changes made in WordPress 2.3. + * + * @since 2.3.0 + */ +function upgrade_230() { + global $wp_current_db_version, $wpdb; + + if ( $wp_current_db_version < 5200 ) { + populate_roles_230(); + } + + // Convert categories to terms. + $tt_ids = array(); + $have_tags = false; + $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_ID"); + foreach ($categories as $category) { + $term_id = (int) $category->cat_ID; + $name = $category->cat_name; + $description = $category->category_description; + $slug = $category->category_nicename; + $parent = $category->category_parent; + $term_group = 0; + + // Associate terms with the same slug in a term group and make slugs unique. + if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) { + $term_group = $exists[0]->term_group; + $id = $exists[0]->term_id; + $num = 2; + do { + $alt_slug = $slug . "-$num"; + $num++; + $slug_check = $wpdb->get_var( $wpdb->prepare("SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug) ); + } while ( $slug_check ); + + $slug = $alt_slug; + + if ( empty( $term_group ) ) { + $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms GROUP BY term_group") + 1; + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->terms SET term_group = %d WHERE term_id = %d", $term_group, $id) ); + } + } + + $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->terms (term_id, name, slug, term_group) VALUES + (%d, %s, %s, %d)", $term_id, $name, $slug, $term_group) ); + + $count = 0; + if ( !empty($category->category_count) ) { + $count = (int) $category->category_count; + $taxonomy = 'category'; + $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) ); + $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; + } + + if ( !empty($category->link_count) ) { + $count = (int) $category->link_count; + $taxonomy = 'link_category'; + $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->term_taxonomy (term_id, taxonomy, description, parent, count) VALUES ( %d, %s, %s, %d, %d)", $term_id, $taxonomy, $description, $parent, $count) ); + $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; + } + + if ( !empty($category->tag_count) ) { + $have_tags = true; + $count = (int) $category->tag_count; + $taxonomy = 'post_tag'; + $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') ); + $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; + } + + if ( empty($count) ) { + $count = 0; + $taxonomy = 'category'; + $wpdb->insert( $wpdb->term_taxonomy, compact('term_id', 'taxonomy', 'description', 'parent', 'count') ); + $tt_ids[$term_id][$taxonomy] = (int) $wpdb->insert_id; + } + } + + $select = 'post_id, category_id'; + if ( $have_tags ) + $select .= ', rel_type'; + + $posts = $wpdb->get_results("SELECT $select FROM $wpdb->post2cat GROUP BY post_id, category_id"); + foreach ( $posts as $post ) { + $post_id = (int) $post->post_id; + $term_id = (int) $post->category_id; + $taxonomy = 'category'; + if ( !empty($post->rel_type) && 'tag' == $post->rel_type) + $taxonomy = 'tag'; + $tt_id = $tt_ids[$term_id][$taxonomy]; + if ( empty($tt_id) ) + continue; + + $wpdb->insert( $wpdb->term_relationships, array('object_id' => $post_id, 'term_taxonomy_id' => $tt_id) ); + } + + // < 3570 we used linkcategories. >= 3570 we used categories and link2cat. + if ( $wp_current_db_version < 3570 ) { + // Create link_category terms for link categories. Create a map of link cat IDs + // to link_category terms. + $link_cat_id_map = array(); + $default_link_cat = 0; + $tt_ids = array(); + $link_cats = $wpdb->get_results("SELECT cat_id, cat_name FROM " . $wpdb->prefix . 'linkcategories'); + foreach ( $link_cats as $category) { + $cat_id = (int) $category->cat_id; + $term_id = 0; + $name = $wpdb->escape($category->cat_name); + $slug = sanitize_title($name); + $term_group = 0; + + // Associate terms with the same slug in a term group and make slugs unique. + if ( $exists = $wpdb->get_results( $wpdb->prepare("SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $slug) ) ) { + $term_group = $exists[0]->term_group; + $term_id = $exists[0]->term_id; + } + + if ( empty($term_id) ) { + $wpdb->insert( $wpdb->terms, compact('name', 'slug', 'term_group') ); + $term_id = (int) $wpdb->insert_id; + } + + $link_cat_id_map[$cat_id] = $term_id; + $default_link_cat = $term_id; + + $wpdb->insert( $wpdb->term_taxonomy, array('term_id' => $term_id, 'taxonomy' => 'link_category', 'description' => '', 'parent' => 0, 'count' => 0) ); + $tt_ids[$term_id] = (int) $wpdb->insert_id; + } + + // Associate links to cats. + $links = $wpdb->get_results("SELECT link_id, link_category FROM $wpdb->links"); + if ( !empty($links) ) foreach ( $links as $link ) { + if ( 0 == $link->link_category ) + continue; + if ( ! isset($link_cat_id_map[$link->link_category]) ) + continue; + $term_id = $link_cat_id_map[$link->link_category]; + $tt_id = $tt_ids[$term_id]; + if ( empty($tt_id) ) + continue; + + $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link->link_id, 'term_taxonomy_id' => $tt_id) ); + } + + // Set default to the last category we grabbed during the upgrade loop. + update_option('default_link_category', $default_link_cat); + } else { + $links = $wpdb->get_results("SELECT link_id, category_id FROM $wpdb->link2cat GROUP BY link_id, category_id"); + foreach ( $links as $link ) { + $link_id = (int) $link->link_id; + $term_id = (int) $link->category_id; + $taxonomy = 'link_category'; + $tt_id = $tt_ids[$term_id][$taxonomy]; + if ( empty($tt_id) ) + continue; + $wpdb->insert( $wpdb->term_relationships, array('object_id' => $link_id, 'term_taxonomy_id' => $tt_id) ); + } + } + + if ( $wp_current_db_version < 4772 ) { + // Obsolete linkcategories table + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'linkcategories'); + } + + // Recalculate all counts + $terms = $wpdb->get_results("SELECT term_taxonomy_id, taxonomy FROM $wpdb->term_taxonomy"); + foreach ( (array) $terms as $term ) { + if ( ('post_tag' == $term->taxonomy) || ('category' == $term->taxonomy) ) + $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term->term_taxonomy_id) ); + else + $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term->term_taxonomy_id) ); + $wpdb->update( $wpdb->term_taxonomy, array('count' => $count), array('term_taxonomy_id' => $term->term_taxonomy_id) ); + } +} + +/** + * Remove old options from the database. + * + * @since 2.3.0 + */ +function upgrade_230_options_table() { + global $wpdb; + $old_options_fields = array( 'option_can_override', 'option_type', 'option_width', 'option_height', 'option_description', 'option_admin_level' ); + $wpdb->hide_errors(); + foreach ( $old_options_fields as $old ) + $wpdb->query("ALTER TABLE $wpdb->options DROP $old"); + $wpdb->show_errors(); +} + +/** + * Remove old categories, link2cat, and post2cat database tables. + * + * @since 2.3.0 + */ +function upgrade_230_old_tables() { + global $wpdb; + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'categories'); + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'link2cat'); + $wpdb->query('DROP TABLE IF EXISTS ' . $wpdb->prefix . 'post2cat'); +} + +/** + * Upgrade old slugs made in version 2.2. + * + * @since 2.2.0 + */ +function upgrade_old_slugs() { + // upgrade people who were using the Redirect Old Slugs plugin + global $wpdb; + $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '_wp_old_slug' WHERE meta_key = 'old_slug'"); +} + +/** + * Execute changes made in WordPress 2.5.0. + * + * @since 2.5.0 + */ +function upgrade_250() { + global $wp_current_db_version; + + if ( $wp_current_db_version < 6689 ) { + populate_roles_250(); + } + +} + +/** + * Execute changes made in WordPress 2.5.1. + * + * @since 2.5.1 + */ +function upgrade_251() { + global $wp_current_db_version; + + // Make the secret longer + update_option('secret', wp_generate_password(64)); +} + +/** + * Execute changes made in WordPress 2.5.2. + * + * @since 2.5.2 + */ +function upgrade_252() { + global $wpdb; + + $wpdb->query("UPDATE $wpdb->users SET user_activation_key = ''"); +} + +/** + * Execute changes made in WordPress 2.6. + * + * @since 2.6.0 + */ +function upgrade_260() { + global $wp_current_db_version; + + if ( $wp_current_db_version < 8000 ) + populate_roles_260(); + + if ( $wp_current_db_version < 8201 ) { + update_option('enable_app', 1); + update_option('enable_xmlrpc', 1); + } +} + +/** + * Execute changes made in WordPress 2.7. + * + * @since 2.7.0 + */ +function upgrade_270() { + global $wpdb, $wp_current_db_version; + + if ( $wp_current_db_version < 8980 ) + populate_roles_270(); + + // Update post_date for unpublished posts with empty timestamp + if ( $wp_current_db_version < 8921 ) + $wpdb->query( "UPDATE $wpdb->posts SET post_date = post_modified WHERE post_date = '0000-00-00 00:00:00'" ); +} + +/** + * Execute changes made in WordPress 2.8. + * + * @since 2.8.0 + */ +function upgrade_280() { + global $wp_current_db_version; + + if ( $wp_current_db_version < 10360 ) + populate_roles_280(); +} + + +// The functions we use to actually do stuff + +// General + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param string $table_name Database table name to create. + * @param string $create_ddl SQL statement to create table. + * @return bool If table already exists or was created by function. + */ +function maybe_create_table($table_name, $create_ddl) { + global $wpdb; + if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name ) + return true; + //didn't find it try to create it. + $q = $wpdb->query($create_ddl); + // we cannot directly tell that whether this succeeded! + if ( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") == $table_name ) + return true; + return false; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param string $table Database table name. + * @param string $index Index name to drop. + * @return bool True, when finished. + */ +function drop_index($table, $index) { + global $wpdb; + $wpdb->hide_errors(); + $wpdb->query("ALTER TABLE `$table` DROP INDEX `$index`"); + // Now we need to take out all the extra ones we may have created + for ($i = 0; $i < 25; $i++) { + $wpdb->query("ALTER TABLE `$table` DROP INDEX `{$index}_$i`"); + } + $wpdb->show_errors(); + return true; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param string $table Database table name. + * @param string $index Database table index column. + * @return bool True, when done with execution. + */ +function add_clean_index($table, $index) { + global $wpdb; + drop_index($table, $index); + $wpdb->query("ALTER TABLE `$table` ADD INDEX ( `$index` )"); + return true; +} + +/** + ** maybe_add_column() + ** Add column to db table if it doesn't exist. + ** Returns: true if already exists or on successful completion + ** false on error + */ +function maybe_add_column($table_name, $column_name, $create_ddl) { + global $wpdb, $debug; + foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { + if ($debug) echo("checking $column == $column_name
    "); + if ($column == $column_name) { + return true; + } + } + //didn't find it try to create it. + $q = $wpdb->query($create_ddl); + // we cannot directly tell that whether this succeeded! + foreach ($wpdb->get_col("DESC $table_name", 0) as $column ) { + if ($column == $column_name) { + return true; + } + } + return false; +} + +/** + * Retrieve all options as it was for 1.2. + * + * @since 1.2.0 + * + * @return array List of options. + */ +function get_alloptions_110() { + global $wpdb; + if ($options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options")) { + foreach ($options as $option) { + // "When trying to design a foolproof system, + // never underestimate the ingenuity of the fools :)" -- Dougal + if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value); + if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value); + if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value); + $all_options->{$option->option_name} = stripslashes($option->option_value); + } + } + return $all_options; +} + +/** + * Version of get_option that is private to install/upgrade. + * + * @since unknown + * @access private + * + * @param string $setting Option name. + * @return mixed + */ +function __get_option($setting) { + global $wpdb; + + if ( $setting == 'home' && defined( 'WP_HOME' ) ) { + return preg_replace( '|/+$|', '', constant( 'WP_HOME' ) ); + } + + if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) { + return preg_replace( '|/+$|', '', constant( 'WP_SITEURL' ) ); + } + + $option = $wpdb->get_var( $wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s", $setting) ); + + if ( 'home' == $setting && '' == $option ) + return __get_option('siteurl'); + + if ( 'siteurl' == $setting || 'home' == $setting || 'category_base' == $setting ) + $option = preg_replace('|/+$|', '', $option); + + @ $kellogs = unserialize($option); + if ($kellogs !== FALSE) + return $kellogs; + else + return $option; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param string $content + * @return string + */ +function deslash($content) { + // Note: \\\ inside a regex denotes a single backslash. + + // Replace one or more backslashes followed by a single quote with + // a single quote. + $content = preg_replace("/\\\+'/", "'", $content); + + // Replace one or more backslashes followed by a double quote with + // a double quote. + $content = preg_replace('/\\\+"/', '"', $content); + + // Replace one or more backslashes with one backslash. + $content = preg_replace("/\\\+/", "\\", $content); + + return $content; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param unknown_type $queries + * @param unknown_type $execute + * @return unknown + */ +function dbDelta($queries, $execute = true) { + global $wpdb; + + // Separate individual queries into an array + if( !is_array($queries) ) { + $queries = explode( ';', $queries ); + if('' == $queries[count($queries) - 1]) array_pop($queries); + } + + $cqueries = array(); // Creation Queries + $iqueries = array(); // Insertion Queries + $for_update = array(); + + // Create a tablename index for an array ($cqueries) of queries + foreach($queries as $qry) { + if(preg_match("|CREATE TABLE ([^ ]*)|", $qry, $matches)) { + $cqueries[trim( strtolower($matches[1]), '`' )] = $qry; + $for_update[$matches[1]] = 'Created table '.$matches[1]; + } + else if(preg_match("|CREATE DATABASE ([^ ]*)|", $qry, $matches)) { + array_unshift($cqueries, $qry); + } + else if(preg_match("|INSERT INTO ([^ ]*)|", $qry, $matches)) { + $iqueries[] = $qry; + } + else if(preg_match("|UPDATE ([^ ]*)|", $qry, $matches)) { + $iqueries[] = $qry; + } + else { + // Unrecognized query type + } + } + + // Check to see which tables and fields exist + if($tables = $wpdb->get_col('SHOW TABLES;')) { + // For every table in the database + foreach($tables as $table) { + // If a table query exists for the database table... + if( array_key_exists(strtolower($table), $cqueries) ) { + // Clear the field and index arrays + unset($cfields); + unset($indices); + // Get all of the field names in the query from between the parens + preg_match("|\((.*)\)|ms", $cqueries[strtolower($table)], $match2); + $qryline = trim($match2[1]); + + // Separate field lines into an array + $flds = explode("\n", $qryline); + + //echo "
    \n".print_r(strtolower($table), true).":\n".print_r($cqueries, true)."

    "; + + // For every field line specified in the query + foreach($flds as $fld) { + // Extract the field name + preg_match("|^([^ ]*)|", trim($fld), $fvals); + $fieldname = trim( $fvals[1], '`' ); + + // Verify the found field name + $validfield = true; + switch(strtolower($fieldname)) + { + case '': + case 'primary': + case 'index': + case 'fulltext': + case 'unique': + case 'key': + $validfield = false; + $indices[] = trim(trim($fld), ", \n"); + break; + } + $fld = trim($fld); + + // If it's a valid field, add it to the field array + if($validfield) { + $cfields[strtolower($fieldname)] = trim($fld, ", \n"); + } + } + + // Fetch the table column structure from the database + $tablefields = $wpdb->get_results("DESCRIBE {$table};"); + + // For every field in the table + foreach($tablefields as $tablefield) { + // If the table field exists in the field array... + if(array_key_exists(strtolower($tablefield->Field), $cfields)) { + // Get the field type from the query + preg_match("|".$tablefield->Field." ([^ ]*( unsigned)?)|i", $cfields[strtolower($tablefield->Field)], $matches); + $fieldtype = $matches[1]; + + // Is actual field type different from the field type in query? + if($tablefield->Type != $fieldtype) { + // Add a query to change the column type + $cqueries[] = "ALTER TABLE {$table} CHANGE COLUMN {$tablefield->Field} " . $cfields[strtolower($tablefield->Field)]; + $for_update[$table.'.'.$tablefield->Field] = "Changed type of {$table}.{$tablefield->Field} from {$tablefield->Type} to {$fieldtype}"; + } + + // Get the default value from the array + //echo "{$cfields[strtolower($tablefield->Field)]}
    "; + if(preg_match("| DEFAULT '(.*)'|i", $cfields[strtolower($tablefield->Field)], $matches)) { + $default_value = $matches[1]; + if($tablefield->Default != $default_value) + { + // Add a query to change the column's default value + $cqueries[] = "ALTER TABLE {$table} ALTER COLUMN {$tablefield->Field} SET DEFAULT '{$default_value}'"; + $for_update[$table.'.'.$tablefield->Field] = "Changed default value of {$table}.{$tablefield->Field} from {$tablefield->Default} to {$default_value}"; + } + } + + // Remove the field from the array (so it's not added) + unset($cfields[strtolower($tablefield->Field)]); + } + else { + // This field exists in the table, but not in the creation queries? + } + } + + // For every remaining field specified for the table + foreach($cfields as $fieldname => $fielddef) { + // Push a query line into $cqueries that adds the field to that table + $cqueries[] = "ALTER TABLE {$table} ADD COLUMN $fielddef"; + $for_update[$table.'.'.$fieldname] = 'Added column '.$table.'.'.$fieldname; + } + + // Index stuff goes here + // Fetch the table index structure from the database + $tableindices = $wpdb->get_results("SHOW INDEX FROM {$table};"); + + if($tableindices) { + // Clear the index array + unset($index_ary); + + // For every index in the table + foreach($tableindices as $tableindex) { + // Add the index to the index data array + $keyname = $tableindex->Key_name; + $index_ary[$keyname]['columns'][] = array('fieldname' => $tableindex->Column_name, 'subpart' => $tableindex->Sub_part); + $index_ary[$keyname]['unique'] = ($tableindex->Non_unique == 0)?true:false; + } + + // For each actual index in the index array + foreach($index_ary as $index_name => $index_data) { + // Build a create string to compare to the query + $index_string = ''; + if($index_name == 'PRIMARY') { + $index_string .= 'PRIMARY '; + } + else if($index_data['unique']) { + $index_string .= 'UNIQUE '; + } + $index_string .= 'KEY '; + if($index_name != 'PRIMARY') { + $index_string .= $index_name; + } + $index_columns = ''; + // For each column in the index + foreach($index_data['columns'] as $column_data) { + if($index_columns != '') $index_columns .= ','; + // Add the field to the column list string + $index_columns .= $column_data['fieldname']; + if($column_data['subpart'] != '') { + $index_columns .= '('.$column_data['subpart'].')'; + } + } + // Add the column list to the index create string + $index_string .= ' ('.$index_columns.')'; + if(!(($aindex = array_search($index_string, $indices)) === false)) { + unset($indices[$aindex]); + //echo "
    {$table}:
    Found index:".$index_string."
    \n"; + } + //else echo "
    {$table}:
    Did not find index:".$index_string."
    ".print_r($indices, true)."
    \n"; + } + } + + // For every remaining index specified for the table + foreach ( (array) $indices as $index ) { + // Push a query line into $cqueries that adds the index to that table + $cqueries[] = "ALTER TABLE {$table} ADD $index"; + $for_update[$table.'.'.$fieldname] = 'Added index '.$table.' '.$index; + } + + // Remove the original table creation query from processing + unset($cqueries[strtolower($table)]); + unset($for_update[strtolower($table)]); + } else { + // This table exists in the database, but not in the creation queries? + } + } + } + + $allqueries = array_merge($cqueries, $iqueries); + if($execute) { + foreach($allqueries as $query) { + //echo "
    ".print_r($query, true)."
    \n"; + $wpdb->query($query); + } + } + + return $for_update; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + */ +function make_db_current() { + global $wp_queries; + + $alterations = dbDelta($wp_queries); + echo "
      \n"; + foreach($alterations as $alteration) echo "
    1. $alteration
    2. \n"; + echo "
    \n"; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + */ +function make_db_current_silent() { + global $wp_queries; + + $alterations = dbDelta($wp_queries); +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param unknown_type $theme_name + * @param unknown_type $template + * @return unknown + */ +function make_site_theme_from_oldschool($theme_name, $template) { + $home_path = get_home_path(); + $site_dir = WP_CONTENT_DIR . "/themes/$template"; + + if (! file_exists("$home_path/index.php")) + return false; + + // Copy files from the old locations to the site theme. + // TODO: This does not copy arbitarary include dependencies. Only the + // standard WP files are copied. + $files = array('index.php' => 'index.php', 'wp-layout.css' => 'style.css', 'wp-comments.php' => 'comments.php', 'wp-comments-popup.php' => 'comments-popup.php'); + + foreach ($files as $oldfile => $newfile) { + if ($oldfile == 'index.php') + $oldpath = $home_path; + else + $oldpath = ABSPATH; + + if ($oldfile == 'index.php') { // Check to make sure it's not a new index + $index = implode('', file("$oldpath/$oldfile")); + if (strpos($index, 'WP_USE_THEMES') !== false) { + if (! @copy(WP_CONTENT_DIR . '/themes/default/index.php', "$site_dir/$newfile")) + return false; + continue; // Don't copy anything + } + } + + if (! @copy("$oldpath/$oldfile", "$site_dir/$newfile")) + return false; + + chmod("$site_dir/$newfile", 0777); + + // Update the blog header include in each file. + $lines = explode("\n", implode('', file("$site_dir/$newfile"))); + if ($lines) { + $f = fopen("$site_dir/$newfile", 'w'); + + foreach ($lines as $line) { + if (preg_match('/require.*wp-blog-header/', $line)) + $line = '//' . $line; + + // Update stylesheet references. + $line = str_replace("/wp-layout.css", "", $line); + + // Update comments template inclusion. + $line = str_replace("", "", $line); + + fwrite($f, "{$line}\n"); + } + fclose($f); + } + } + + // Add a theme header. + $header = "/*\nTheme Name: $theme_name\nTheme URI: " . __get_option('siteurl') . "\nDescription: A theme automatically created by the upgrade.\nVersion: 1.0\nAuthor: Moi\n*/\n"; + + $stylelines = file_get_contents("$site_dir/style.css"); + if ($stylelines) { + $f = fopen("$site_dir/style.css", 'w'); + + fwrite($f, $header); + fwrite($f, $stylelines); + fclose($f); + } + + return true; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param unknown_type $theme_name + * @param unknown_type $template + * @return unknown + */ +function make_site_theme_from_default($theme_name, $template) { + $site_dir = WP_CONTENT_DIR . "/themes/$template"; + $default_dir = WP_CONTENT_DIR . '/themes/default'; + + // Copy files from the default theme to the site theme. + //$files = array('index.php', 'comments.php', 'comments-popup.php', 'footer.php', 'header.php', 'sidebar.php', 'style.css'); + + $theme_dir = @ opendir("$default_dir"); + if ($theme_dir) { + while(($theme_file = readdir( $theme_dir )) !== false) { + if (is_dir("$default_dir/$theme_file")) + continue; + if (! @copy("$default_dir/$theme_file", "$site_dir/$theme_file")) + return; + chmod("$site_dir/$theme_file", 0777); + } + } + @closedir($theme_dir); + + // Rewrite the theme header. + $stylelines = explode("\n", implode('', file("$site_dir/style.css"))); + if ($stylelines) { + $f = fopen("$site_dir/style.css", 'w'); + + foreach ($stylelines as $line) { + if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name; + elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url'); + elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.'; + elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1'; + elseif (strpos($line, 'Author:') !== false) $line = 'Author: You'; + fwrite($f, $line . "\n"); + } + fclose($f); + } + + // Copy the images. + umask(0); + if (! mkdir("$site_dir/images", 0777)) { + return false; + } + + $images_dir = @ opendir("$default_dir/images"); + if ($images_dir) { + while(($image = readdir($images_dir)) !== false) { + if (is_dir("$default_dir/images/$image")) + continue; + if (! @copy("$default_dir/images/$image", "$site_dir/images/$image")) + return; + chmod("$site_dir/images/$image", 0777); + } + } + @closedir($images_dir); +} + +// Create a site theme from the default theme. +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @return unknown + */ +function make_site_theme() { + // Name the theme after the blog. + $theme_name = __get_option('blogname'); + $template = sanitize_title($theme_name); + $site_dir = WP_CONTENT_DIR . "/themes/$template"; + + // If the theme already exists, nothing to do. + if ( is_dir($site_dir)) { + return false; + } + + // We must be able to write to the themes dir. + if (! is_writable(WP_CONTENT_DIR . "/themes")) { + return false; + } + + umask(0); + if (! mkdir($site_dir, 0777)) { + return false; + } + + if (file_exists(ABSPATH . 'wp-layout.css')) { + if (! make_site_theme_from_oldschool($theme_name, $template)) { + // TODO: rm -rf the site theme directory. + return false; + } + } else { + if (! make_site_theme_from_default($theme_name, $template)) + // TODO: rm -rf the site theme directory. + return false; + } + + // Make the new site theme active. + $current_template = __get_option('template'); + if ($current_template == 'default') { + update_option('template', $template); + update_option('stylesheet', $template); + } + return $template; +} + +/** + * Translate user level to user role name. + * + * @since unknown + * + * @param int $level User level. + * @return string User role name. + */ +function translate_level_to_role($level) { + switch ($level) { + case 10: + case 9: + case 8: + return 'administrator'; + case 7: + case 6: + case 5: + return 'editor'; + case 4: + case 3: + case 2: + return 'author'; + case 1: + return 'contributor'; + case 0: + return 'subscriber'; + } +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + */ +function wp_check_mysql_version() { + global $wpdb; + $result = $wpdb->check_database_version(); + if ( is_wp_error( $result ) ) + die( $result->get_error_message() ); +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + */ +function maybe_disable_automattic_widgets() { + $plugins = __get_option( 'active_plugins' ); + + foreach ( (array) $plugins as $plugin ) { + if ( basename( $plugin ) == 'widgets.php' ) { + array_splice( $plugins, array_search( $plugin, $plugins ), 1 ); + update_option( 'active_plugins', $plugins ); + break; + } + } +} + +?> diff --git a/wp-admin/includes/user.php b/wp-admin/includes/user.php new file mode 100644 index 0000000..8c6bf2b --- /dev/null +++ b/wp-admin/includes/user.php @@ -0,0 +1,838 @@ +id || $wp_roles->role_objects[$_POST['role']]->has_cap( 'edit_users' ) ) { + // If the new role isn't editable by the logged-in user die with error + $editable_roles = get_editable_roles(); + if (!$editable_roles[$_POST['role']]) + wp_die(__('You can’t give users that role.')); + + $user = new WP_User( $user_id ); + $user->set_role( $_POST['role'] ); + } + } + } else { + add_action( 'user_register', 'add_user' ); // See above + return edit_user(); + } +} + +/** + * Edit user settings based on contents of $_POST + * + * Used on user-edit.php and profile.php to manage and process user options, passwords etc. + * + * @since 2.0 + * + * @param int $user_id Optional. User ID. + * @return int user id of the updated user + */ +function edit_user( $user_id = 0 ) { + global $current_user, $wp_roles, $wpdb; + if ( $user_id != 0 ) { + $update = true; + $user->ID = (int) $user_id; + $userdata = get_userdata( $user_id ); + $user->user_login = $wpdb->escape( $userdata->user_login ); + } else { + $update = false; + $user = ''; + } + + if ( isset( $_POST['user_login'] )) + $user->user_login = esc_html( trim( $_POST['user_login'] )); + + $pass1 = $pass2 = ''; + if ( isset( $_POST['pass1'] )) + $pass1 = $_POST['pass1']; + if ( isset( $_POST['pass2'] )) + $pass2 = $_POST['pass2']; + + if ( isset( $_POST['role'] ) && current_user_can( 'edit_users' ) ) { + + // Don't let anyone with 'edit_users' (admins) edit their own role to something without it. + if( $user_id != $current_user->id || $wp_roles->role_objects[$_POST['role']]->has_cap( 'edit_users' )) + $user->role = $_POST['role']; + + // If the new role isn't editable by the logged-in user die with error + $editable_roles = get_editable_roles(); + if (!$editable_roles[$_POST['role']]) + wp_die(__('You can’t give users that role.')); + } + + if ( isset( $_POST['email'] )) + $user->user_email = esc_html( trim( $_POST['email'] )); + if ( isset( $_POST['url'] ) ) { + if ( empty ( $_POST['url'] ) || $_POST['url'] == 'http://' ) { + $user->user_url = ''; + } else { + $user->user_url = esc_url( trim( $_POST['url'] )); + $user->user_url = preg_match('/^(https?|ftps?|mailto|news|irc|gopher|nntp|feed|telnet):/is', $user->user_url) ? $user->user_url : 'http://'.$user->user_url; + } + } + if ( isset( $_POST['first_name'] )) + $user->first_name = esc_html( trim( $_POST['first_name'] )); + if ( isset( $_POST['last_name'] )) + $user->last_name = esc_html( trim( $_POST['last_name'] )); + if ( isset( $_POST['nickname'] )) + $user->nickname = esc_html( trim( $_POST['nickname'] )); + if ( isset( $_POST['display_name'] )) + $user->display_name = esc_html( trim( $_POST['display_name'] )); + if ( isset( $_POST['description'] )) + $user->description = trim( $_POST['description'] ); + if ( isset( $_POST['jabber'] )) + $user->jabber = esc_html( trim( $_POST['jabber'] )); + if ( isset( $_POST['aim'] )) + $user->aim = esc_html( trim( $_POST['aim'] )); + if ( isset( $_POST['yim'] )) + $user->yim = esc_html( trim( $_POST['yim'] )); + if ( !$update ) + $user->rich_editing = 'true'; // Default to true for new users. + else if ( isset( $_POST['rich_editing'] ) ) + $user->rich_editing = $_POST['rich_editing']; + else + $user->rich_editing = 'true'; + + $user->comment_shortcuts = isset( $_POST['comment_shortcuts'] )? $_POST['comment_shortcuts'] : ''; + + $user->use_ssl = 0; + if ( !empty($_POST['use_ssl']) ) + $user->use_ssl = 1; + + if ( !$update ) + $user->admin_color = 'fresh'; // Default to fresh for new users. + else if ( isset( $_POST['admin_color'] ) ) + $user->admin_color = $_POST['admin_color']; + else + $user->admin_color = 'fresh'; + + $errors = new WP_Error(); + + /* checking that username has been typed */ + if ( $user->user_login == '' ) + $errors->add( 'user_login', __( 'ERROR: Please enter a username.' )); + + /* checking the password has been typed twice */ + do_action_ref_array( 'check_passwords', array ( $user->user_login, & $pass1, & $pass2 )); + + if ( $update ) { + if ( empty($pass1) && !empty($pass2) ) + $errors->add( 'pass', __( 'ERROR: You entered your new password only once.' ), array( 'form-field' => 'pass1' ) ); + elseif ( !empty($pass1) && empty($pass2) ) + $errors->add( 'pass', __( 'ERROR: You entered your new password only once.' ), array( 'form-field' => 'pass2' ) ); + } else { + if ( empty($pass1) ) + $errors->add( 'pass', __( 'ERROR: Please enter your password.' ), array( 'form-field' => 'pass1' ) ); + elseif ( empty($pass2) ) + $errors->add( 'pass', __( 'ERROR: Please enter your password twice.' ), array( 'form-field' => 'pass2' ) ); + } + + /* Check for "\" in password */ + if ( false !== strpos( stripslashes($pass1), "\\" ) ) + $errors->add( 'pass', __( 'ERROR: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) ); + + /* checking the password has been typed twice the same */ + if ( $pass1 != $pass2 ) + $errors->add( 'pass', __( 'ERROR: Please enter the same password in the two password fields.' ), array( 'form-field' => 'pass1' ) ); + + if (!empty ( $pass1 )) + $user->user_pass = $pass1; + + if ( !$update && !validate_username( $user->user_login ) ) + $errors->add( 'user_login', __( 'ERROR: This username is invalid. Please enter a valid username.' )); + + if (!$update && username_exists( $user->user_login )) + $errors->add( 'user_login', __( 'ERROR: This username is already registered. Please choose another one.' )); + + /* checking e-mail address */ + if ( empty ( $user->user_email ) ) { + $errors->add( 'empty_email', __( 'ERROR: Please enter an e-mail address.' ), array( 'form-field' => 'email' ) ); + } elseif (!is_email( $user->user_email ) ) { + $errors->add( 'invalid_email', __( 'ERROR: The e-mail address isn’t correct.' ), array( 'form-field' => 'email' ) ); + } elseif ( ( $owner_id = email_exists($user->user_email) ) && $owner_id != $user->ID ) { + $errors->add( 'email_exists', __('ERROR: This email is already registered, please choose another one.'), array( 'form-field' => 'email' ) ); + } + + // Allow plugins to return there own errors. + do_action_ref_array('user_profile_update_errors', array ( &$errors, $update, &$user ) ); + + if ( $errors->get_error_codes() ) + return $errors; + + if ( $update ) { + $user_id = wp_update_user( get_object_vars( $user )); + } else { + $user_id = wp_insert_user( get_object_vars( $user )); + wp_new_user_notification( $user_id, isset($_POST['send_password']) ? $pass1 : '' ); + } + return $user_id; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @return array List of user IDs. + */ +function get_author_user_ids() { + global $wpdb; + $level_key = $wpdb->prefix . 'user_level'; + return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value != '0'", $level_key) ); +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param int $user_id User ID. + * @return array|bool List of editable authors. False if no editable users. + */ +function get_editable_authors( $user_id ) { + global $wpdb; + + $editable = get_editable_user_ids( $user_id ); + + if( !$editable ) { + return false; + } else { + $editable = join(',', $editable); + $authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" ); + } + + return apply_filters('get_editable_authors', $authors); +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @param int $user_id User ID. + * @param bool $exclude_zeros Optional, default is true. Whether to exclude zeros. + * @return unknown + */ +function get_editable_user_ids( $user_id, $exclude_zeros = true, $post_type = 'post' ) { + global $wpdb; + + $user = new WP_User( $user_id ); + + if ( ! $user->has_cap("edit_others_{$post_type}s") ) { + if ( $user->has_cap("edit_{$post_type}s") || $exclude_zeros == false ) + return array($user->id); + else + return array(); + } + + $level_key = $wpdb->prefix . 'user_level'; + + $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s", $level_key); + if ( $exclude_zeros ) + $query .= " AND meta_value != '0'"; + + return $wpdb->get_col( $query ); +} + +/** + * Fetch a filtered list of user roles that the current user is + * allowed to edit. + * + * Simple function who's main purpose is to allow filtering of the + * list of roles in the $wp_roles object so that plugins can remove + * innappropriate ones depending on the situation or user making edits. + * Specifically because without filtering anyone with the edit_users + * capability can edit others to be administrators, even if they are + * only editors or authors. This filter allows admins to delegate + * user management. + * + * @since 2.8 + * + * @return unknown + */ +function get_editable_roles() { + global $wp_roles; + + $all_roles = $wp_roles->roles; + $editable_roles = apply_filters('editable_roles', $all_roles); + + return $editable_roles; +} + +/** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * + * @return unknown + */ +function get_nonauthor_user_ids() { + global $wpdb; + $level_key = $wpdb->prefix . 'user_level'; + + return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) ); +} + +/** + * Retrieve editable posts from other users. + * + * @since unknown + * + * @param int $user_id User ID to not retrieve posts from. + * @param string $type Optional, defaults to 'any'. Post type to retrieve, can be 'draft' or 'pending'. + * @return array List of posts from others. + */ +function get_others_unpublished_posts($user_id, $type='any') { + global $wpdb; + + $editable = get_editable_user_ids( $user_id ); + + if ( in_array($type, array('draft', 'pending')) ) + $type_sql = " post_status = '$type' "; + else + $type_sql = " ( post_status = 'draft' OR post_status = 'pending' ) "; + + $dir = ( 'pending' == $type ) ? 'ASC' : 'DESC'; + + if( !$editable ) { + $other_unpubs = ''; + } else { + $editable = join(',', $editable); + $other_unpubs = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title, post_author FROM $wpdb->posts WHERE post_type = 'post' AND $type_sql AND post_author IN ($editable) AND post_author != %d ORDER BY post_modified $dir", $user_id) ); + } + + return apply_filters('get_others_drafts', $other_unpubs); +} + +/** + * Retrieve drafts from other users. + * + * @since unknown + * + * @param int $user_id User ID. + * @return array List of drafts from other users. + */ +function get_others_drafts($user_id) { + return get_others_unpublished_posts($user_id, 'draft'); +} + +/** + * Retrieve pending review posts from other users. + * + * @since unknown + * + * @param int $user_id User ID. + * @return array List of posts with pending review post type from other users. + */ +function get_others_pending($user_id) { + return get_others_unpublished_posts($user_id, 'pending'); +} + +/** + * Retrieve user data and filter it. + * + * @since unknown + * + * @param int $user_id User ID. + * @return object WP_User object with user data. + */ +function get_user_to_edit( $user_id ) { + $user = new WP_User( $user_id ); + $user->user_login = esc_attr($user->user_login); + $user->user_email = esc_attr($user->user_email); + $user->user_url = esc_url($user->user_url); + $user->first_name = esc_attr($user->first_name); + $user->last_name = esc_attr($user->last_name); + $user->display_name = esc_attr($user->display_name); + $user->nickname = esc_attr($user->nickname); + $user->aim = isset( $user->aim ) && !empty( $user->aim ) ? esc_attr($user->aim) : ''; + $user->yim = isset( $user->yim ) && !empty( $user->yim ) ? esc_attr($user->yim) : ''; + $user->jabber = isset( $user->jabber ) && !empty( $user->jabber ) ? esc_attr($user->jabber) : ''; + $user->description = isset( $user->description ) && !empty( $user->description ) ? esc_html($user->description) : ''; + + return $user; +} + +/** + * Retrieve the user's drafts. + * + * @since unknown + * + * @param int $user_id User ID. + * @return array + */ +function get_users_drafts( $user_id ) { + global $wpdb; + $query = $wpdb->prepare("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id); + $query = apply_filters('get_users_drafts', $query); + return $wpdb->get_results( $query ); +} + +/** + * Remove user and optionally reassign posts and links to another user. + * + * If the $reassign parameter is not assigned to an User ID, then all posts will + * be deleted of that user. The action 'delete_user' that is passed the User ID + * being deleted will be run after the posts are either reassigned or deleted. + * The user meta will also be deleted that are for that User ID. + * + * @since unknown + * + * @param int $id User ID. + * @param int $reassign Optional. Reassign posts and links to new User ID. + * @return bool True when finished. + */ +function wp_delete_user($id, $reassign = 'novalue') { + global $wpdb; + + $id = (int) $id; + $user = new WP_User($id); + + // allow for transaction statement + do_action('delete_user', $id); + + if ($reassign == 'novalue') { + $post_ids = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id) ); + + if ($post_ids) { + foreach ($post_ids as $post_id) + wp_delete_post($post_id); + } + + // Clean links + $link_ids = $wpdb->get_col( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id) ); + + if ( $link_ids ) { + foreach ( $link_ids as $link_id ) + wp_delete_link($link_id); + } + + } else { + $reassign = (int) $reassign; + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $id) ); + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $id) ); + } + + // FINALLY, delete user + + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d", $id) ); + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->users WHERE ID = %d", $id) ); + + wp_cache_delete($id, 'users'); + wp_cache_delete($user->user_login, 'userlogins'); + wp_cache_delete($user->user_email, 'useremail'); + wp_cache_delete($user->user_nicename, 'userslugs'); + + // allow for commit transaction + do_action('deleted_user', $id); + + return true; +} + +/** + * Remove all capabilities from user. + * + * @since unknown + * + * @param int $id User ID. + */ +function wp_revoke_user($id) { + $id = (int) $id; + + $user = new WP_User($id); + $user->remove_all_caps(); +} + +if ( !class_exists('WP_User_Search') ) : +/** + * WordPress User Search class. + * + * @since unknown + * @author Mark Jaquith + */ +class WP_User_Search { + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $results; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $search_term; + + /** + * Page number. + * + * @since unknown + * @access private + * @var int + */ + var $page; + + /** + * Role name that users have. + * + * @since unknown + * @access private + * @var string + */ + var $role; + + /** + * Raw page number. + * + * @since unknown + * @access private + * @var int|bool + */ + var $raw_page; + + /** + * Amount of users to display per page. + * + * @since unknown + * @access public + * @var int + */ + var $users_per_page = 50; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $first_user; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var int + */ + var $last_user; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $query_limit; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $query_sort; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $query_from_where; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var int + */ + var $total_users_for_query = 0; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var bool + */ + var $too_many_total_users = false; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $search_errors; + + /** + * {@internal Missing Description}} + * + * @since unknown + * @access private + * @var unknown_type + */ + var $paging_text; + + /** + * PHP4 Constructor - Sets up the object properties. + * + * @since unknown + * + * @param string $search_term Search terms string. + * @param int $page Optional. Page ID. + * @param string $role Role name. + * @return WP_User_Search + */ + function WP_User_Search ($search_term = '', $page = '', $role = '') { + $this->search_term = $search_term; + $this->raw_page = ( '' == $page ) ? false : (int) $page; + $this->page = (int) ( '' == $page ) ? 1 : $page; + $this->role = $role; + + $this->prepare_query(); + $this->query(); + $this->prepare_vars_for_template_usage(); + $this->do_paging(); + } + + /** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * @access public + */ + function prepare_query() { + global $wpdb; + $this->first_user = ($this->page - 1) * $this->users_per_page; + $this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page); + $this->query_sort = ' ORDER BY user_login'; + $search_sql = ''; + if ( $this->search_term ) { + $searches = array(); + $search_sql = 'AND ('; + foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col ) + $searches[] = $col . " LIKE '%$this->search_term%'"; + $search_sql .= implode(' OR ', $searches); + $search_sql .= ')'; + } + + $this->query_from_where = "FROM $wpdb->users"; + if ( $this->role ) + $this->query_from_where .= $wpdb->prepare(" INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%'); + else + $this->query_from_where .= " WHERE 1=1"; + $this->query_from_where .= " $search_sql"; + + } + + /** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * @access public + */ + function query() { + global $wpdb; + $this->results = $wpdb->get_col('SELECT ID ' . $this->query_from_where . $this->query_sort . $this->query_limit); + + if ( $this->results ) + $this->total_users_for_query = $wpdb->get_var('SELECT COUNT(ID) ' . $this->query_from_where); // no limit + else + $this->search_errors = new WP_Error('no_matching_users_found', __('No matching users were found!')); + } + + /** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * @access public + */ + function prepare_vars_for_template_usage() { + $this->search_term = stripslashes($this->search_term); // done with DB, from now on we want slashes gone + } + + /** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * @access public + */ + function do_paging() { + if ( $this->total_users_for_query > $this->users_per_page ) { // have to page the results + $args = array(); + if( ! empty($this->search_term) ) + $args['usersearch'] = urlencode($this->search_term); + if( ! empty($this->role) ) + $args['role'] = urlencode($this->role); + + $this->paging_text = paginate_links( array( + 'total' => ceil($this->total_users_for_query / $this->users_per_page), + 'current' => $this->page, + 'base' => 'users.php?%_%', + 'format' => 'userspage=%#%', + 'add_args' => $args + ) ); + if ( $this->paging_text ) { + $this->paging_text = sprintf( '' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ), + number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ), + number_format_i18n( $this->total_users_for_query ), + $this->paging_text + ); + } + } + } + + /** + * {@internal Missing Short Description}} + * + * {@internal Missing Long Description}} + * + * @since unknown + * @access public + * + * @return unknown + */ + function get_results() { + return (array) $this->results; + } + + /** + * Displaying paging text. + * + * @see do_paging() Builds paging text. + * + * @since unknown + * @access public + */ + function page_links() { + echo $this->paging_text; + } + + /** + * Whether paging is enabled. + * + * @see do_paging() Builds paging text. + * + * @since unknown + * @access public + * + * @return bool + */ + function results_are_paged() { + if ( $this->paging_text ) + return true; + return false; + } + + /** + * Whether there are search terms. + * + * @since unknown + * @access public + * + * @return bool + */ + function is_search() { + if ( $this->search_term ) + return true; + return false; + } +} +endif; + +add_action('admin_init', 'default_password_nag_handler'); +function default_password_nag_handler($errors = false) { + global $user_ID; + if ( ! get_usermeta($user_ID, 'default_password_nag') ) //Short circuit it. + return; + + //get_user_setting = JS saved UI setting. else no-js-falback code. + if ( 'hide' == get_user_setting('default_password_nag') || isset($_GET['default_password_nag']) && '0' == $_GET['default_password_nag'] ) { + delete_user_setting('default_password_nag'); + update_usermeta($user_ID, 'default_password_nag', false); + } +} + +add_action('profile_update', 'default_password_nag_edit_user', 10, 2); +function default_password_nag_edit_user($user_ID, $old_data) { + global $user_ID; + if ( ! get_usermeta($user_ID, 'default_password_nag') ) //Short circuit it. + return; + + $new_data = get_userdata($user_ID); + + if ( $new_data->user_pass != $old_data->user_pass ) { //Remove the nag if the password has been changed. + delete_user_setting('default_password_nag'); + update_usermeta($user_ID, 'default_password_nag', false); + } +} + +add_action('admin_notices', 'default_password_nag'); +function default_password_nag() { + global $user_ID; + if ( ! get_usermeta($user_ID, 'default_password_nag') ) + return; + + echo '

    '; + printf(__("Notice: you're using the auto-generated password for your account. Would you like to change it to something you'll remember easier?
    + Yes, Take me to my profile page | No Thanks, Do not remind me again."), admin_url('profile.php') . '#password', '?default_password_nag=0'); + echo '

    '; +} + +?> diff --git a/wp-admin/includes/widgets.php b/wp-admin/includes/widgets.php new file mode 100644 index 0000000..d6d930d --- /dev/null +++ b/wp-admin/includes/widgets.php @@ -0,0 +1,210 @@ + $widget['id'], 'widget_name' => $widget['name'], '_display' => 'template' ); + + if ( isset($wp_registered_widget_controls[$widget['id']]['id_base']) && isset($widget['params'][0]['number']) ) { + $id_base = $wp_registered_widget_controls[$widget['id']]['id_base']; + $args['_temp_id'] = "$id_base-__i__"; + $args['_multi_num'] = next_widget_id_number($id_base); + $args['_add'] = 'multi'; + } else { + $args['_add'] = 'single'; + if ( $sidebar ) + $args['_hide'] = '1'; + } + + $args = wp_list_widget_controls_dynamic_sidebar( array( 0 => $args, 1 => $widget['params'][0] ) ); + call_user_func_array( 'wp_widget_control', $args ); + } +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param string $sidebar + */ +function wp_list_widget_controls( $sidebar ) { + add_filter( 'dynamic_sidebar_params', 'wp_list_widget_controls_dynamic_sidebar' ); + + echo "\t
    \n"; + dynamic_sidebar( $sidebar ); + echo "\t
    \n"; +} + +/** + * {@internal Missing Short Description}} + * + * @since unknown + * + * @param array $params + * @return array + */ +function wp_list_widget_controls_dynamic_sidebar( $params ) { + global $wp_registered_widgets; + static $i = 0; + $i++; + + $widget_id = $params[0]['widget_id']; + $id = isset($params[0]['_temp_id']) ? $params[0]['_temp_id'] : $widget_id; + $hidden = isset($params[0]['_hide']) ? ' style="display:none;"' : ''; + + $params[0]['before_widget'] = "
    "; + $params[0]['after_widget'] = "
    "; + $params[0]['before_title'] = "%BEG_OF_TITLE%"; // deprecated + $params[0]['after_title'] = "%END_OF_TITLE%"; // deprecated + if ( is_callable( $wp_registered_widgets[$widget_id]['callback'] ) ) { + $wp_registered_widgets[$widget_id]['_callback'] = $wp_registered_widgets[$widget_id]['callback']; + $wp_registered_widgets[$widget_id]['callback'] = 'wp_widget_control'; + } + + return $params; +} + +function next_widget_id_number($id_base) { + global $wp_registered_widgets; + $number = 1; + + foreach ( $wp_registered_widgets as $widget_id => $widget ) { + if ( preg_match( '/' . $id_base . '-([0-9]+)$/', $widget_id, $matches ) ) + $number = max($number, $matches[1]); + } + $number++; + + return $number; +} + +/** + * Meta widget used to display the control form for a widget. + * + * Called from dynamic_sidebar(). + * + * @since unknown + * + * @param array $sidebar_args + * @return array + */ +function wp_widget_control( $sidebar_args ) { + global $wp_registered_widgets, $wp_registered_widget_controls, $sidebars_widgets; + + $widget_id = $sidebar_args['widget_id']; + $sidebar_id = isset($sidebar_args['id']) ? $sidebar_args['id'] : false; + $key = $sidebar_id ? array_search( $widget_id, $sidebars_widgets[$sidebar_id] ) : '-1'; // position of widget in sidebar + $control = isset($wp_registered_widget_controls[$widget_id]) ? $wp_registered_widget_controls[$widget_id] : array(); + $widget = $wp_registered_widgets[$widget_id]; + + $id_format = $widget['id']; + $widget_number = isset($control['params'][0]['number']) ? $control['params'][0]['number'] : ''; + $id_base = isset($control['id_base']) ? $control['id_base'] : $widget_id; + $multi_number = isset($sidebar_args['_multi_num']) ? $sidebar_args['_multi_num'] : ''; + $add_new = isset($sidebar_args['_add']) ? $sidebar_args['_add'] : ''; + + $query_arg = array( 'editwidget' => $widget['id'] ); + if ( $add_new ) { + $query_arg['addnew'] = 1; + if ( $multi_number ) { + $query_arg['num'] = $multi_number; + $query_arg['base'] = $id_base; + } + } else { + $query_arg['sidebar'] = $sidebar_id; + $query_arg['key'] = $key; + } + + // We aren't showing a widget control, we're outputing a template for a mult-widget control + if ( isset($sidebar_args['_display']) && 'template' == $sidebar_args['_display'] && $widget_number ) { + // number == -1 implies a template where id numbers are replaced by a generic '__i__' + $control['params'][0]['number'] = -1; + // with id_base widget id's are constructed like {$id_base}-{$id_number} + if ( isset($control['id_base']) ) + $id_format = $control['id_base'] . '-__i__'; + } + + $wp_registered_widgets[$widget_id]['callback'] = $wp_registered_widgets[$widget_id]['_callback']; + unset($wp_registered_widgets[$widget_id]['_callback']); + + $widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) ); + $has_form = 'noform'; + + echo $sidebar_args['before_widget']; ?> +
    +
    + + +
    +

    +
    + +
    +
    +
    +" . __('There are no options for this widget.') . "

    \n"; ?> +
    + + + + + + + + +
    +
    + | + +
    +
    + + +
    +
    +
    +
    +
    + +
    + +
    + \ No newline at end of file diff --git a/wp-admin/index.php b/wp-admin/index.php new file mode 100644 index 0000000..a88b1bc --- /dev/null +++ b/wp-admin/index.php @@ -0,0 +1,44 @@ + + +
    + +

    + +
    + + + +
    +
    + +
    + + diff --git a/wp-admin/install-helper.php b/wp-admin/install-helper.php new file mode 100644 index 0000000..cddbc26 --- /dev/null +++ b/wp-admin/install-helper.php @@ -0,0 +1,225 @@ + + * check_column('wp_links', 'link_description', 'mediumtext'); + * if (check_column($wpdb->comments, 'comment_author', 'tinytext')) + * echo "ok\n"; + * + * $error_count = 0; + * $tablename = $wpdb->links; + * // check the column + * if (!check_column($wpdb->links, 'link_description', 'varchar(255)')) { + * $ddl = "ALTER TABLE $wpdb->links MODIFY COLUMN link_description varchar(255) NOT NULL DEFAULT '' "; + * $q = $wpdb->query($ddl); + * } + * + * if (check_column($wpdb->links, 'link_description', 'varchar(255)')) { + * $res .= $tablename . ' - ok
    '; + * } else { + * $res .= 'There was a problem with ' . $tablename . '
    '; + * ++$error_count; + * } + * + * + * @package WordPress + * @subpackage Plugin + */ + +/** + * @global bool $wp_only_load_config + * @name $wp_only_load_config + * @var bool + * @since unknown + */ +$wp_only_load_config = true; + +/** Load WordPress Bootstrap */ +require_once(dirname(dirname(__FILE__)).'/wp-load.php'); + +/** + * Turn debugging on or off. + * @global bool|int $debug + * @name $debug + * @var bool|int + * @since unknown + */ +$debug = 0; + +if ( ! function_exists('maybe_create_table') ) : +/** + * Create database table, if it doesn't already exist. + * + * @since unknown + * @package WordPress + * @subpackage Plugin + * @uses $wpdb + * + * @param string $table_name Database table name. + * @param string $create_ddl Create database table SQL. + * @return bool False on error, true if already exists or success. + */ +function maybe_create_table($table_name, $create_ddl) { + global $wpdb; + foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) { + if ($table == $table_name) { + return true; + } + } + //didn't find it try to create it. + $wpdb->query($create_ddl); + // we cannot directly tell that whether this succeeded! + foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) { + if ($table == $table_name) { + return true; + } + } + return false; +} +endif; + +if ( ! function_exists('maybe_add_column') ) : +/** + * Add column to database table, if column doesn't already exist in table. + * + * @since unknown + * @package WordPress + * @subpackage Plugin + * @uses $wpdb + * @uses $debug + * + * @param string $table_name Database table name + * @param string $column_name Table column name + * @param string $create_ddl SQL to add column to table. + * @return bool False on failure. True, if already exists or was successful. + */ +function maybe_add_column($table_name, $column_name, $create_ddl) { + global $wpdb, $debug; + foreach ($wpdb->get_col("DESC $table_name",0) as $column ) { + if ($debug) echo("checking $column == $column_name
    "); + + if ($column == $column_name) { + return true; + } + } + //didn't find it try to create it. + $wpdb->query($create_ddl); + // we cannot directly tell that whether this succeeded! + foreach ($wpdb->get_col("DESC $table_name",0) as $column ) { + if ($column == $column_name) { + return true; + } + } + return false; +} +endif; + +/** + * Drop column from database table, if it exists. + * + * @since unknown + * @package WordPress + * @subpackage Plugin + * @uses $wpdb + * + * @param string $table_name Table name + * @param string $column_name Column name + * @param string $drop_ddl SQL statement to drop column. + * @return bool False on failure, true on success or doesn't exist. + */ +function maybe_drop_column($table_name, $column_name, $drop_ddl) { + global $wpdb; + foreach ($wpdb->get_col("DESC $table_name",0) as $column ) { + if ($column == $column_name) { + //found it try to drop it. + $wpdb->query($drop_ddl); + // we cannot directly tell that whether this succeeded! + foreach ($wpdb->get_col("DESC $table_name",0) as $column ) { + if ($column == $column_name) { + return false; + } + } + } + } + // else didn't find it + return true; +} + +/** + * Check column matches criteria. + * + * Uses the SQL DESC for retrieving the table info for the column. It will help + * understand the parameters, if you do more research on what column information + * is returned by the SQL statement. Pass in null to skip checking that + * criteria. + * + * Column names returned from DESC table are case sensitive and are listed: + * Field + * Type + * Null + * Key + * Default + * Extra + * + * @since unknown + * @package WordPress + * @subpackage Plugin + * + * @param string $table_name Table name + * @param string $col_name Column name + * @param string $col_type Column type + * @param bool $is_null Optional. Check is null. + * @param mixed $key Optional. Key info. + * @param mixed $default Optional. Default value. + * @param mixed $extra Optional. Extra value. + * @return bool True, if matches. False, if not matching. + */ +function check_column($table_name, $col_name, $col_type, $is_null = null, $key = null, $default = null, $extra = null) { + global $wpdb, $debug; + $diffs = 0; + $results = $wpdb->get_results("DESC $table_name"); + + foreach ($results as $row ) { + if ($debug > 1) print_r($row); + + if ($row->Field == $col_name) { + // got our column, check the params + if ($debug) echo ("checking $row->Type against $col_type\n"); + if (($col_type != null) && ($row->Type != $col_type)) { + ++$diffs; + } + if (($is_null != null) && ($row->Null != $is_null)) { + ++$diffs; + } + if (($key != null) && ($row->Key != $key)) { + ++$diffs; + } + if (($default != null) && ($row->Default != $default)) { + ++$diffs; + } + if (($extra != null) && ($row->Extra != $extra)) { + ++$diffs; + } + if ($diffs > 0) { + if ($debug) echo ("diffs = $diffs returning false\n"); + return false; + } + return true; + } // end if found our column + } + return false; +} + +?> diff --git a/wp-admin/install.php b/wp-admin/install.php new file mode 100644 index 0000000..a9579ff --- /dev/null +++ b/wp-admin/install.php @@ -0,0 +1,150 @@ + + +> + + + <?php _e('WordPress › Installation'); ?> + + + +

    WordPress

    + + +

    ERROR: %s'), $error); ?>

    + +
    + + + + + + + + + + + +

    + +
    +

    +
    +'.__('Already Installed').'

    '.__('You appear to have already installed WordPress. To reinstall please clear your old database tables first.').'

    ');} + +switch($step) { + case 0: + case 1: // in case people are directly linking to this + display_header(); +?> +

    +

    ReadMe documentation at your leisure. Otherwise, just fill in the information below and you’ll be on your way to using the most extendable and powerful personal publishing platform in the world.'), '../readme.html'); ?>

    + + +

    +

    + + + +error) ) + wp_die($wpdb->error->get_error_message()); + + display_header(); + // Fill in the data we gathered + $weblog_title = isset($_POST['weblog_title']) ? stripslashes($_POST['weblog_title']) : ''; + $admin_email = isset($_POST['admin_email']) ? stripslashes($_POST['admin_email']) : ''; + $public = isset($_POST['blog_public']) ? (int) $_POST['blog_public'] : 0; + // check e-mail address + $error = false; + if (empty($admin_email)) { + // TODO: poka-yoke + display_setup_form( __('you must provide an e-mail address.') ); + $error = true; + } else if (!is_email($admin_email)) { + // TODO: poka-yoke + display_setup_form( __('that isn’t a valid e-mail address. E-mail addresses look like: username@example.com') ); + $error = true; + } + + if ( $error === false ) { + $wpdb->show_errors(); + $result = wp_install($weblog_title, 'admin', $admin_email, $public); + extract($result, EXTR_SKIP); +?> + +

    + +

    + + + + + + + + + + +
    admin
    '. $password .'
    '; + } + echo '

    '. $password_message .'

    '; ?>
    + +

    + + + + + diff --git a/wp-admin/js/cat.dev.js b/wp-admin/js/cat.dev.js new file mode 100644 index 0000000..cbc2900 --- /dev/null +++ b/wp-admin/js/cat.dev.js @@ -0,0 +1,5 @@ +jQuery(document).ready( function($) { + var myConfirm = function() { return '' !== $('#newcat').val(); }; + $('#jaxcat').prepend('' + catL10n.how + ''); + $('#categorychecklist').wpList( { alt: '', response: 'cat-ajax-response', confirm: myConfirm } ); +} ); diff --git a/wp-admin/js/cat.js b/wp-admin/js/cat.js new file mode 100644 index 0000000..deee8c4 --- /dev/null +++ b/wp-admin/js/cat.js @@ -0,0 +1 @@ +jQuery(document).ready(function(b){var a=function(){return""!==b("#newcat").val()};b("#jaxcat").prepend(''+catL10n.how+'');b("#categorychecklist").wpList({alt:"",response:"cat-ajax-response",confirm:a})}); \ No newline at end of file diff --git a/wp-admin/js/categories.dev.js b/wp-admin/js/categories.dev.js new file mode 100644 index 0000000..dd96954 --- /dev/null +++ b/wp-admin/js/categories.dev.js @@ -0,0 +1,42 @@ +jQuery(document).ready(function($) { + var options = false, addAfter, addAfter2, delBefore, delAfter; + if ( document.forms['addcat'].category_parent ) + options = document.forms['addcat'].category_parent.options; + + addAfter = function( r, settings ) { + var name, id; + + name = $("" + $('name', r).text() + "").html(); + id = $('cat', r).attr('id'); + options[options.length] = new Option(name, id); + + addAfter2( r, settings ); + } + + addAfter2 = function( x, r ) { + var t = $(r.parsed.responses[0].data); + if ( t.length == 1 ) + inlineEditTax.addEvents($(t.id)); + } + + delAfter = function( r, settings ) { + var id = $('cat', r).attr('id'), o; + for ( o = 0; o < options.length; o++ ) + if ( id == options[o].value ) + options[o] = null; + } + + delBefore = function(s) { + if ( 'undefined' != showNotice ) + return showNotice.warn() ? s : false; + + return s; + } + + if ( options ) + $('#the-list').wpList( { addAfter: addAfter, delBefore: delBefore, delAfter: delAfter } ); + else + $('#the-list').wpList({ addAfter: addAfter2, delBefore: delBefore }); + + $('.delete a[class^="delete"]').click(function(){return false;}); +}); diff --git a/wp-admin/js/categories.js b/wp-admin/js/categories.js new file mode 100644 index 0000000..43f60ca --- /dev/null +++ b/wp-admin/js/categories.js @@ -0,0 +1 @@ +jQuery(document).ready(function(d){var b=false,f,e,c,a;if(document.forms.addcat.category_parent){b=document.forms.addcat.category_parent.options}f=function(i,h){var g,j;g=d(""+d("name",i).text()+"").html();j=d("cat",i).attr("id");b[b.length]=new Option(g,j);e(i,h)};e=function(g,i){var h=d(i.parsed.responses[0].data);if(h.length==1){inlineEditTax.addEvents(d(h.id))}};a=function(h,g){var j=d("cat",h).attr("id"),i;for(i=0;i' + + $( '#mm option[value=' + $('#mm').val() + ']' ).text() + ' ' + + $('#jj').val() + ', ' + + $('#aa').val() + ' @ ' + + $('#hh').val() + ':' + + $('#mn').val() + ' ' + ); + return false; + }); +}); \ No newline at end of file diff --git a/wp-admin/js/comment.js b/wp-admin/js/comment.js new file mode 100644 index 0000000..ac65c92 --- /dev/null +++ b/wp-admin/js/comment.js @@ -0,0 +1 @@ +jQuery(document).ready(function(b){var a=b("#timestamp").html();b(".edit-timestamp").click(function(){if(b("#timestampdiv").is(":hidden")){b("#timestampdiv").slideDown("normal");b(".edit-timestamp").hide()}return false});b(".cancel-timestamp").click(function(){b("#timestampdiv").slideUp("normal");b("#mm").val(b("#hidden_mm").val());b("#jj").val(b("#hidden_jj").val());b("#aa").val(b("#hidden_aa").val());b("#hh").val(b("#hidden_hh").val());b("#mn").val(b("#hidden_mn").val());b("#timestamp").html(a);b(".edit-timestamp").show();return false});b(".save-timestamp").click(function(){b("#timestampdiv").slideUp("normal");b(".edit-timestamp").show();b("#timestamp").html(commentL10n.submittedOn+" "+b("#mm option[value="+b("#mm").val()+"]").text()+" "+b("#jj").val()+", "+b("#aa").val()+" @ "+b("#hh").val()+":"+b("#mn").val()+" ");return false})}); \ No newline at end of file diff --git a/wp-admin/js/common.dev.js b/wp-admin/js/common.dev.js new file mode 100644 index 0000000..4a54c59 --- /dev/null +++ b/wp-admin/js/common.dev.js @@ -0,0 +1,267 @@ +var showNotice, adminMenu, columns; +(function($){ +// sidebar admin menu +adminMenu = { + + init : function() { + $('#adminmenu div.wp-menu-toggle').each( function() { + if ( $(this).siblings('.wp-submenu').length ) + $(this).click(function(){ adminMenu.toggle( $(this).siblings('.wp-submenu') ); }); + else + $(this).hide(); + }); + + this.favorites(); + + $('a.separator').click(function(){ + if ( $('body').hasClass('folded') ) { + adminMenu.fold(1); + deleteUserSetting( 'mfold' ); + } else { + adminMenu.fold(); + setUserSetting( 'mfold', 'f' ); + } + return false; + }); + + if ( $('body').hasClass('folded') ) { + this.fold(); + } + this.restoreMenuState(); + }, + + restoreMenuState : function() { + $('#adminmenu li.wp-has-submenu').each(function(i, e) { + var v = getUserSetting( 'm'+i ); + if ( $(e).hasClass('wp-has-current-submenu') ) return true; // leave the current parent open + + if ( 'o' == v ) $(e).addClass('wp-menu-open'); + else if ( 'c' == v ) $(e).removeClass('wp-menu-open'); + }); + }, + + toggle : function(el) { + + el['slideToggle'](150, function(){el.css('display','');}).parent().toggleClass( 'wp-menu-open' ); + + $('#adminmenu li.wp-has-submenu').each(function(i, e) { + var v = $(e).hasClass('wp-menu-open') ? 'o' : 'c'; + setUserSetting( 'm'+i, v ); + }); + + return false; + }, + + fold : function(off) { + if (off) { + $('body').removeClass('folded'); + $('#adminmenu li.wp-has-submenu').unbind(); + } else { + $('body').addClass('folded'); + $('#adminmenu li.wp-has-submenu').hoverIntent({ + over: function(e){ + var m, b, h, o, f; + m = $(this).find('.wp-submenu'); + b = m.parent().offset().top + m.height() + 1; // Bottom offset of the menu + h = $('#wpwrap').height(); // Height of the entire page + o = 60 + b - h; + f = $(window).height() + $('body').scrollTop() - 15; // The fold + if (f < (b - o)) { + o = b - f; + } + if (o > 1) { + m.css({'marginTop':'-'+o+'px'}); + } else if ( m.css('marginTop') ) { + m.css({'marginTop':''}); + } + m.addClass('sub-open'); + }, + out: function(){ $(this).find('.wp-submenu').removeClass('sub-open').css({'marginTop':''}); }, + timeout: 220, + sensitivity: 8, + interval: 100 + }); + + } + }, + + favorites : function() { + $('#favorite-inside').width($('#favorite-actions').width()-4); + $('#favorite-toggle, #favorite-inside').bind( 'mouseenter', function(){$('#favorite-inside').removeClass('slideUp').addClass('slideDown'); setTimeout(function(){if ( $('#favorite-inside').hasClass('slideDown') ) { $('#favorite-inside').slideDown(100); $('#favorite-first').addClass('slide-down'); }}, 200) } ); + + $('#favorite-toggle, #favorite-inside').bind( 'mouseleave', function(){$('#favorite-inside').removeClass('slideDown').addClass('slideUp'); setTimeout(function(){if ( $('#favorite-inside').hasClass('slideUp') ) { $('#favorite-inside').slideUp(100, function(){ $('#favorite-first').removeClass('slide-down'); } ); }}, 300) } ); + } +}; + +$(document).ready(function(){adminMenu.init();}); + +// show/hide/save table columns +columns = { + init : function() { + $('.hide-column-tog').click( function() { + var column = $(this).val(), show = $(this).attr('checked'); + if ( show ) { + $('.column-' + column).show(); + } else { + $('.column-' + column).hide(); + } + columns.save_manage_columns_state(); + } ); + }, + + save_manage_columns_state : function() { + var hidden = $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(','); + $.post(ajaxurl, { + action: 'hidden-columns', + hidden: hidden, + screenoptionnonce: $('#screenoptionnonce').val(), + page: pagenow + }); + } +} + +$(document).ready(function(){columns.init();}); + +})(jQuery); + +// stub for doing better warnings +showNotice = { + warn : function() { + var msg = commonL10n.warnDelete || ''; + if ( confirm(msg) ) { + return true; + } + + return false; + }, + + note : function(text) { + alert(text); + } +}; + +jQuery(document).ready( function($) { + var lastClicked = false, checks, first, last, checked; + + // pulse + $('.fade').animate( { backgroundColor: '#ffffe0' }, 300).animate( { backgroundColor: '#fffbcc' }, 300).animate( { backgroundColor: '#ffffe0' }, 300).animate( { backgroundColor: '#fffbcc' }, 300); + + // Move .updated and .error alert boxes + $('div.wrap h2 ~ div.updated, div.wrap h2 ~ div.error').addClass('below-h2'); + $('div.updated, div.error').not('.below-h2').insertAfter('div.wrap h2:first'); + + // show warnings + $('#doaction, #doaction2').click(function(){ + if ( $('select[name="action"]').val() == 'delete' || $('select[name="action2"]').val() == 'delete' ) { + return showNotice.warn(); + } + }); + + // screen settings tab + $('#show-settings-link').click(function () { + if ( ! $('#screen-options-wrap').hasClass('screen-options-open') ) { + $('#contextual-help-link-wrap').css('visibility', 'hidden'); + } + $('#screen-options-wrap').slideToggle('fast', function(){ + if ( $(this).hasClass('screen-options-open') ) { + $('#show-settings-link').css({'backgroundImage':'url("images/screen-options-right.gif")'}); + $('#contextual-help-link-wrap').css('visibility', ''); + $(this).removeClass('screen-options-open'); + } else { + $('#show-settings-link').css({'backgroundImage':'url("images/screen-options-right-up.gif")'}); + $(this).addClass('screen-options-open'); + } + }); + return false; + }); + + // help tab + $('#contextual-help-link').click(function () { + if ( ! $('#contextual-help-wrap').hasClass('contextual-help-open') ) { + $('#screen-options-link-wrap').css('visibility', 'hidden'); + } + $('#contextual-help-wrap').slideToggle('fast', function(){ + if ( $(this).hasClass('contextual-help-open') ) { + $('#contextual-help-link').css({'backgroundImage':'url("images/screen-options-right.gif")'}); + $('#screen-options-link-wrap').css('visibility', ''); + $(this).removeClass('contextual-help-open'); + } else { + $('#contextual-help-link').css({'backgroundImage':'url("images/screen-options-right-up.gif")'}); + $(this).addClass('contextual-help-open'); + } + }); + return false; + }); + $('#contextual-help-link-wrap, #screen-options-link-wrap').show(); + + // check all checkboxes + $( 'table:visible tbody .check-column :checkbox' ).click( function(e) { + if ( 'undefined' == e.shiftKey ) { return true; } + if ( e.shiftKey ) { + if ( !lastClicked ) { return true; } + checks = $( lastClicked ).parents( 'form:first' ).find( ':checkbox' ); + first = checks.index( lastClicked ); + last = checks.index( this ); + checked = $(this).attr('checked'); + if ( 0 < first && 0 < last && first != last ) { + checks.slice( first, last ).attr( 'checked', function(){ + if ( $(this).parents('tr').is(':visible') ) + return checked ? 'checked' : ''; + + return ''; + }); + } + } + lastClicked = this; + return true; + } ); + $( 'thead :checkbox, tfoot :checkbox' ).click( function(e) { + var c = $(this).attr('checked'), kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard, toggle = e.shiftKey || kbtoggle; + + + $(this).parents( 'form:first' ).find( 'table tbody:visible' ).find( '.check-column :checkbox' ).attr( 'checked', function() { + if ( $(this).parents('tr').is(':hidden') ) + return ''; + if ( toggle ) + return $(this).attr( 'checked' ) ? '' : 'checked'; + else if (c) + return 'checked'; + return ''; + }); + $(this).parents( 'form:first' ).find( 'table thead:visible, table tfoot:visible').find( '.check-column :checkbox' ).attr( 'checked', function() { + if ( toggle ) + return ''; + else if (c) + return 'checked'; + return ''; + }); + }); + $('#default-password-nag-no').click( function() { + setUserSetting('default_password_nag', 'hide'); + $('div.default-password-nag').hide(); + return false; + }); + + +}); + +jQuery(document).ready( function($){ + var turboNag = $('.turbo-nag'); + + if ( !turboNag.length || ('undefined' != typeof(google) && google.gears) ) + return; + + if ( 'undefined' != typeof GearsFactory ) { + return; + } else { + try { + if ( ( 'undefined' != typeof window.ActiveXObject && ActiveXObject('Gears.Factory') ) || + ( 'undefined' != typeof navigator.mimeTypes && navigator.mimeTypes['application/x-googlegears'] ) ) { + return; + } + } catch(e){} + } + + turboNag.show(); + +}); diff --git a/wp-admin/js/common.js b/wp-admin/js/common.js new file mode 100644 index 0000000..299b576 --- /dev/null +++ b/wp-admin/js/common.js @@ -0,0 +1 @@ +var showNotice,adminMenu,columns;(function(a){adminMenu={init:function(){a("#adminmenu div.wp-menu-toggle").each(function(){if(a(this).siblings(".wp-submenu").length){a(this).click(function(){adminMenu.toggle(a(this).siblings(".wp-submenu"))})}else{a(this).hide()}});this.favorites();a("a.separator").click(function(){if(a("body").hasClass("folded")){adminMenu.fold(1);deleteUserSetting("mfold")}else{adminMenu.fold();setUserSetting("mfold","f")}return false});if(a("body").hasClass("folded")){this.fold()}this.restoreMenuState()},restoreMenuState:function(){a("#adminmenu li.wp-has-submenu").each(function(c,d){var b=getUserSetting("m"+c);if(a(d).hasClass("wp-has-current-submenu")){return true}if("o"==b){a(d).addClass("wp-menu-open")}else{if("c"==b){a(d).removeClass("wp-menu-open")}}})},toggle:function(b){b.slideToggle(150,function(){b.css("display","")}).parent().toggleClass("wp-menu-open");a("#adminmenu li.wp-has-submenu").each(function(d,f){var c=a(f).hasClass("wp-menu-open")?"o":"c";setUserSetting("m"+d,c)});return false},fold:function(b){if(b){a("body").removeClass("folded");a("#adminmenu li.wp-has-submenu").unbind()}else{a("body").addClass("folded");a("#adminmenu li.wp-has-submenu").hoverIntent({over:function(j){var d,c,g,k,i;d=a(this).find(".wp-submenu");c=d.parent().offset().top+d.height()+1;g=a("#wpwrap").height();k=60+c-g;i=a(window).height()+a("body").scrollTop()-15;if(i<(c-k)){k=c-i}if(k>1){d.css({marginTop:"-"+k+"px"})}else{if(d.css("marginTop")){d.css({marginTop:""})}}d.addClass("sub-open")},out:function(){a(this).find(".wp-submenu").removeClass("sub-open").css({marginTop:""})},timeout:220,sensitivity:8,interval:100})}},favorites:function(){a("#favorite-inside").width(a("#favorite-actions").width()-4);a("#favorite-toggle, #favorite-inside").bind("mouseenter",function(){a("#favorite-inside").removeClass("slideUp").addClass("slideDown");setTimeout(function(){if(a("#favorite-inside").hasClass("slideDown")){a("#favorite-inside").slideDown(100);a("#favorite-first").addClass("slide-down")}},200)});a("#favorite-toggle, #favorite-inside").bind("mouseleave",function(){a("#favorite-inside").removeClass("slideDown").addClass("slideUp");setTimeout(function(){if(a("#favorite-inside").hasClass("slideUp")){a("#favorite-inside").slideUp(100,function(){a("#favorite-first").removeClass("slide-down")})}},300)})}};a(document).ready(function(){adminMenu.init()});columns={init:function(){a(".hide-column-tog").click(function(){var c=a(this).val(),b=a(this).attr("checked");if(b){a(".column-"+c).show()}else{a(".column-"+c).hide()}columns.save_manage_columns_state()})},save_manage_columns_state:function(){var b=a(".manage-column").filter(":hidden").map(function(){return this.id}).get().join(",");a.post(ajaxurl,{action:"hidden-columns",hidden:b,screenoptionnonce:a("#screenoptionnonce").val(),page:pagenow})}};a(document).ready(function(){columns.init()})})(jQuery);showNotice={warn:function(){var a=commonL10n.warnDelete||"";if(confirm(a)){return true}return false},note:function(a){alert(a)}};jQuery(document).ready(function(d){var f=false,a,e,c,b;d(".fade").animate({backgroundColor:"#ffffe0"},300).animate({backgroundColor:"#fffbcc"},300).animate({backgroundColor:"#ffffe0"},300).animate({backgroundColor:"#fffbcc"},300);d("div.wrap h2 ~ div.updated, div.wrap h2 ~ div.error").addClass("below-h2");d("div.updated, div.error").not(".below-h2").insertAfter("div.wrap h2:first");d("#doaction, #doaction2").click(function(){if(d('select[name="action"]').val()=="delete"||d('select[name="action2"]').val()=="delete"){return showNotice.warn()}});d("#show-settings-link").click(function(){if(!d("#screen-options-wrap").hasClass("screen-options-open")){d("#contextual-help-link-wrap").css("visibility","hidden")}d("#screen-options-wrap").slideToggle("fast",function(){if(d(this).hasClass("screen-options-open")){d("#show-settings-link").css({backgroundImage:'url("images/screen-options-right.gif")'});d("#contextual-help-link-wrap").css("visibility","");d(this).removeClass("screen-options-open")}else{d("#show-settings-link").css({backgroundImage:'url("images/screen-options-right-up.gif")'});d(this).addClass("screen-options-open")}});return false});d("#contextual-help-link").click(function(){if(!d("#contextual-help-wrap").hasClass("contextual-help-open")){d("#screen-options-link-wrap").css("visibility","hidden")}d("#contextual-help-wrap").slideToggle("fast",function(){if(d(this).hasClass("contextual-help-open")){d("#contextual-help-link").css({backgroundImage:'url("images/screen-options-right.gif")'});d("#screen-options-link-wrap").css("visibility","");d(this).removeClass("contextual-help-open")}else{d("#contextual-help-link").css({backgroundImage:'url("images/screen-options-right-up.gif")'});d(this).addClass("contextual-help-open")}});return false});d("#contextual-help-link-wrap, #screen-options-link-wrap").show();d("table:visible tbody .check-column :checkbox").click(function(g){if("undefined"==g.shiftKey){return true}if(g.shiftKey){if(!f){return true}a=d(f).parents("form:first").find(":checkbox");e=a.index(f);c=a.index(this);b=d(this).attr("checked");if(0' ); + $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr('disabled','disabled'); + + if ( 'post' == act.val() ) { + act.val( 'post-quickpress-publish' ); + } + + $('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() { + $('#dashboard_quick_press h3 img').remove(); + $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr('disabled',''); + $('#dashboard_quick_press ul').find('li').each( function() { + $('#dashboard_recent_drafts ul').prepend( this ); + } ).end().remove(); + tb_init('a.thickbox'); + quickPressLoad(); + } ); + return false; + } ); + + $('#publish').click( function() { act.val( 'post-quickpress-publish' ); } ); + + }; + quickPressLoad(); + +} ); diff --git a/wp-admin/js/dashboard.js b/wp-admin/js/dashboard.js new file mode 100644 index 0000000..c988618 --- /dev/null +++ b/wp-admin/js/dashboard.js @@ -0,0 +1 @@ +var ajaxWidgets,ajaxPopulateWidgets,quickPressLoad;jQuery(document).ready(function(a){ajaxWidgets=["dashboard_incoming_links","dashboard_primary","dashboard_secondary","dashboard_plugins"];ajaxPopulateWidgets=function(b){show=function(g,c){var f,d=a("#"+g+" div.inside:visible").find(".widget-loading");if(d.length){f=d.parent();setTimeout(function(){f.load("index-extra.php?jax="+g,"",function(){f.hide().slideDown("normal",function(){a(this).css("display","");if("dashboard_plugins"==g&&a.isFunction(tb_init)){tb_init("#dashboard_plugins a.thickbox")}})})},c*500)}};if(b){b=b.toString();if(a.inArray(b,ajaxWidgets)!=-1){show(b,0)}}else{a.each(ajaxWidgets,function(c){show(this,c)})}};ajaxPopulateWidgets();postboxes.add_postbox_toggles("dashboard",{pbshow:ajaxPopulateWidgets});quickPressLoad=function(){var b=a("#quickpost-action"),c;c=a("#quick-press").submit(function(){a("#dashboard_quick_press h3").append('');a('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr("disabled","disabled");if("post"==b.val()){b.val("post-quickpress-publish")}a("#dashboard_quick_press div.inside").load(c.attr("action"),c.serializeArray(),function(){a("#dashboard_quick_press h3 img").remove();a('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr("disabled","");a("#dashboard_quick_press ul").find("li").each(function(){a("#dashboard_recent_drafts ul").prepend(this)}).end().remove();tb_init("a.thickbox");quickPressLoad()});return false});a("#publish").click(function(){b.val("post-quickpress-publish")})};quickPressLoad()}); \ No newline at end of file diff --git a/wp-admin/js/edit-comments.dev.js b/wp-admin/js/edit-comments.dev.js new file mode 100644 index 0000000..6600e14 --- /dev/null +++ b/wp-admin/js/edit-comments.dev.js @@ -0,0 +1,391 @@ +var theList, theExtraList, toggleWithKeyboard = false; +(function($) { + +setCommentsList = function() { + var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter; + + totalInput = $('#comments-form .tablenav :input[name="_total"]'); + perPageInput = $('#comments-form .tablenav :input[name="_per_page"]'); + pageInput = $('#comments-form .tablenav :input[name="_page"]'); + + dimAfter = function( r, settings ) { + var c = $('#' + settings.element); + + if ( c.is('.unapproved') ) + c.find('div.comment_status').html('0') + else + c.find('div.comment_status').html('1') + + $('span.pending-count').each( function() { + var a = $(this), n; + n = a.html().replace(/[ ,.]+/g, ''); + n = parseInt(n,10); + if ( isNaN(n) ) return; + n = n + ( $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1 ); + if ( n < 0 ) { n = 0; } + a.parents('#awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0'); + n = n.toString(); + if ( n.length > 3 ) + n = n.substr(0, n.length-3)+' '+n.substr(-3); + a.html(n); + }); + }; + + // Send current total, page, per_page and url + delBefore = function( settings ) { + settings.data._total = totalInput.val(); + settings.data._per_page = perPageInput.val(); + settings.data._page = pageInput.val(); + settings.data._url = document.location.href; + + if ( 'undefined' != showNotice && settings.data.action && settings.data.action == 'delete-comment' && !settings.data.spam ) + return showNotice.warn() ? settings : false; + + return settings; + }; + + /* Updates the current total (as displayed visibly) + */ + updateTotalCount = function( total, time, setConfidentTime ) { + if ( time < lastConfidentTime ) { + return; + } + totalInput.val( total.toString() ); + if ( setConfidentTime ) { + lastConfidentTime = time; + } + $('span.total-type-count').each( function() { + var a = $(this), n; + n = totalInput.val().toString(); + if ( n.length > 3 ) + n = n.substr(0, n.length-3)+' '+n.substr(-3); + a.html(n); + }); + + }; + + // In admin-ajax.php, we send back the unix time stamp instead of 1 on success + delAfter = function( r, settings ) { + $('span.pending-count').each( function() { + var a = $(this), n; + n = a.html().replace(/[ ,.]+/g, ''); + n = parseInt(n,10); + if ( isNaN(n) ) return; + if ( $('#' + settings.element).is('.unapproved') ) { // we deleted a formerly unapproved comment + n = n - 1; + } else if ( $(settings.target).parents( 'span.unapprove' ).size() ) { // we "deleted" an approved comment from the approved list by clicking "Unapprove" + n = n + 1; + } + if ( n < 0 ) { n = 0; } + a.parents('#awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0'); + n = n.toString(); + if ( n.length > 3 ) + n = n.substr(0, n.length-3)+' '+n.substr(-3); + a.html(n); + }); + + $('span.spam-count').each( function() { + var a = $(this), n; + n = a.html().replace(/[ ,.]+/g, ''); + n = parseInt(n,10); + if ( isNaN(n) ) return; + if ( $(settings.target).parents( 'span.spam' ).size() ) { // we marked a comment as spam + n = n + 1; + } else if ( $('#' + settings.element).is('.spam') ) { // we approved or deleted a comment marked as spam + n = n - 1; + } + if ( n < 0 ) { n = 0; } + n = n.toString(); + if ( n.length > 3 ) + n = n.substr(0, n.length-3)+' '+n.substr(-3); + a.html(n); + }); + + + // XML response + if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) { + // Set the total to the known good value (even if this value is a little old, newer values should only be a few less, and so shouldn't mess up the page links) + updateTotalCount( settings.parsed.responses[0].supplemental.total, settings.parsed.responses[0].supplemental.time, true ); + if ( $.trim( settings.parsed.responses[0].supplemental.pageLinks ) ) { + $('.tablenav-pages').find( '.page-numbers' ).remove().end().append( $( settings.parsed.responses[0].supplemental.pageLinks ) ); + } else if ( 'undefined' != typeof settings.parsed.responses[0].supplemental.pageLinks ) { + $('.tablenav-pages').find( '.page-numbers' ).remove(); + } + } else { + // Decrement the total + var total = parseInt( totalInput.val(), 10 ); + if ( total-- < 0 ) + total = 0; + updateTotalCount( total, r, false ); + } + + if ( theExtraList.size() == 0 || theExtraList.children().size() == 0 ) { + return; + } + + theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() ); + $('#get-extra-comments').submit(); + }; + + theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } ); + theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } ); + +}; + +commentReply = { + + init : function() { + var row = $('#replyrow'); + + $('a.cancel', row).click(function() { return commentReply.revert(); }); + $('a.save', row).click(function() { return commentReply.send(); }); + $('input#author, input#author-email, input#author-url', row).keypress(function(e){ + if ( e.which == 13 ) { + commentReply.send(); + e.preventDefault(); + return false; + } + }); + + // add events + $('#the-comment-list .column-comment > p').dblclick(function(){ + commentReply.toggle($(this).parent()); + }); + + $('#doaction, #doaction2, #post-query-submit').click(function(e){ + if ( $('#the-comment-list #replyrow').length > 0 ) + commentReply.close(); + }); + + this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || ''; + + }, + + addEvents : function(r) { + r.each(function() { + $(this).find('.column-comment > p').dblclick(function(){ + commentReply.toggle($(this).parent()); + }); + }); + }, + + toggle : function(el) { + if ( $(el).css('display') != 'none' ) + $(el).find('a.vim-q').click(); + }, + + revert : function() { + + if ( $('#the-comment-list #replyrow').length < 1 ) + return false; + + $('#replyrow').fadeOut('fast', function(){ + commentReply.close(); + }); + + return false; + }, + + close : function() { + $(this.o).fadeIn('fast').css('backgroundColor', ''); + $('#com-reply').append( $('#replyrow') ); + $('#replycontent').val(''); + $('#edithead input').val(''); + $('#replysubmit .error').html('').hide(); + $('#replysubmit .waiting').hide(); + if ( $.browser.msie ) + $('#replycontainer, #replycontent').css('height', '120px'); + else + $('#replycontainer').resizable('destroy').css('height', '120px'); + }, + + open : function(id, p, a) { + var t = this, editRow, act, h; + t.close(); + t.o = '#comment-'+id; + + $('#replyrow td').attr('colspan', $('.widefat thead th:visible').length); + editRow = $('#replyrow'), rowData = $('#inline-'+id); + act = t.act = (a == 'edit') ? 'edit-comment' : 'replyto-comment'; + + $('#action', editRow).val(act); + $('#comment_post_ID', editRow).val(p); + $('#comment_ID', editRow).val(id); + + if ( a == 'edit' ) { + $('#author', editRow).val( $('div.author', rowData).text() ); + $('#author-email', editRow).val( $('div.author-email', rowData).text() ); + $('#author-url', editRow).val( $('div.author-url', rowData).text() ); + $('#status', editRow).val( $('div.comment_status', rowData).text() ); + $('#replycontent', editRow).val( $('textarea.comment', rowData).val() ); + $('#edithead, #savebtn', editRow).show(); + $('#replyhead, #replybtn', editRow).hide(); + + h = $(t.o).height(); + if ( h > 220 ) + if ( $.browser.msie ) + $('#replycontainer, #replycontent', editRow).height(h-105); + else + $('#replycontainer', editRow).height(h-105); + + $(t.o).after(editRow.hide()).fadeOut('fast', function(){ + $('#replyrow').fadeIn('fast'); + }); + } else { + $('#edithead, #savebtn', editRow).hide(); + $('#replyhead, #replybtn', editRow).show(); + $(t.o).after(editRow); + $('#replyrow').hide().fadeIn('fast'); + } + + if ( ! $.browser.msie ) + $('#replycontainer').resizable({ + handles : 's', + axis : 'y', + minHeight : 80, + stop : function() { + $('#replycontainer').width('auto'); + } + }); + + setTimeout(function() { + var rtop, rbottom, scrollTop, vp, scrollBottom; + + rtop = $('#replyrow').offset().top; + rbottom = rtop + $('#replyrow').height(); + scrollTop = window.pageYOffset || document.documentElement.scrollTop; + vp = document.documentElement.clientHeight || self.innerHeight || 0; + scrollBottom = scrollTop + vp; + + if ( scrollBottom - 20 < rbottom ) + window.scroll(0, rbottom - vp + 35); + else if ( rtop - 20 < scrollTop ) + window.scroll(0, rtop - 35); + + $('#replycontent').focus().keyup(function(e){ + if (e.which == 27) commentReply.revert(); // close on Escape + }); + }, 600); + + return false; + }, + + send : function() { + var post = {}; + + $('#replysubmit .waiting').show(); + + $('#replyrow input').each(function() { + post[ $(this).attr('name') ] = $(this).val(); + }); + + post.content = $('#replycontent').val(); + post.id = post.comment_post_ID; + post.comments_listing = this.comments_listing; + + $.ajax({ + type : 'POST', + url : wpListL10n.url, + data : post, + success : function(x) { commentReply.show(x); }, + error : function(r) { commentReply.error(r); } + }); + + return false; + }, + + show : function(xml) { + var r, c, id, bg; + + if ( typeof(xml) == 'string' ) { + this.error({'responseText': xml}); + return false; + } + + r = wpAjax.parseAjaxResponse(xml); + if ( r.errors ) { + this.error({'responseText': wpAjax.broken}); + return false; + } + + if ( 'edit-comment' == this.act ) + $(this.o).remove(); + + r = r.responses[0]; + c = r.data; + + $(c).hide() + $('#replyrow').after(c); + + this.o = id = '#comment-'+r.id; + this.revert(); + this.addEvents($(id)); + bg = $(id).hasClass('unapproved') ? '#ffffe0' : '#fff'; + + $(id) + .animate( { 'backgroundColor':'#CCEEBB' }, 600 ) + .animate( { 'backgroundColor': bg }, 600 ); + + $.fn.wpList.process($(id)) + }, + + error : function(r) { + var er = r.statusText; + + $('#replysubmit .waiting').hide(); + + if ( r.responseText ) + er = r.responseText.replace( /<.[^<>]*?>/g, '' ); + + if ( er ) + $('#replysubmit .error').html(er).show(); + + } +}; + +$(document).ready(function(){ + var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk; + + setCommentsList(); + commentReply.init(); + $('span.delete a.delete').click(function(){return false;}); + + if ( typeof QTags != 'undefined' ) + ed_reply = new QTags('ed_reply', 'replycontent', 'replycontainer', 'more'); + + if ( typeof $.table_hotkeys != 'undefined' ) { + make_hotkeys_redirect = function(which) { + return function() { + var first_last, l; + + first_last = 'next' == which? 'first' : 'last'; + l = $('.'+which+'.page-numbers'); + if (l.length) + window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1'; + } + }; + edit_comment = function(event, current_row) { + window.location = $('span.edit a', current_row).attr('href'); + }; + toggle_all = function() { + toggleWithKeyboard = true; + $('#comments-form thead #cb input:checkbox').click().attr('checked', ''); + toggleWithKeyboard = false; + } + make_bulk = function(value) { + return function(event, _) { + $('option[value='+value+']').attr('selected', 'selected'); + $('form#comments-form')[0].submit(); + } + }; + $.table_hotkeys($('table.widefat'),['a', 'u', 's', 'd', 'r', 'q', ['e', edit_comment], + ['shift+a', make_bulk('approve')], ['shift+s', make_bulk('markspam')], + ['shift+d', make_bulk('delete')], ['shift+x', toggle_all], + ['shift+u', make_bulk('unapprove')]], + {highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last, + prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next')} + ); + } +}); + +})(jQuery); diff --git a/wp-admin/js/edit-comments.js b/wp-admin/js/edit-comments.js new file mode 100644 index 0000000..e6ab98b --- /dev/null +++ b/wp-admin/js/edit-comments.js @@ -0,0 +1 @@ +var theList,theExtraList,toggleWithKeyboard=false;(function(a){setCommentsList=function(){var g,i,h,f=0,c,e,d,b;g=a('#comments-form .tablenav :input[name="_total"]');i=a('#comments-form .tablenav :input[name="_per_page"]');h=a('#comments-form .tablenav :input[name="_page"]');c=function(k,j){var l=a("#"+j.element);if(l.is(".unapproved")){l.find("div.comment_status").html("0")}else{l.find("div.comment_status").html("1")}a("span.pending-count").each(function(){var m=a(this),o;o=m.html().replace(/[ ,.]+/g,"");o=parseInt(o,10);if(isNaN(o)){return}o=o+(a("#"+j.element).is("."+j.dimClass)?1:-1);if(o<0){o=0}m.parents("#awaiting-mod")[0==o?"addClass":"removeClass"]("count-0");o=o.toString();if(o.length>3){o=o.substr(0,o.length-3)+" "+o.substr(-3)}m.html(o)})};e=function(j){j.data._total=g.val();j.data._per_page=i.val();j.data._page=h.val();j.data._url=document.location.href;if("undefined"!=showNotice&&j.data.action&&j.data.action=="delete-comment"&&!j.data.spam){return showNotice.warn()?j:false}return j};d=function(j,k,l){if(k3){o=o.substr(0,o.length-3)+" "+o.substr(-3)}m.html(o)})};b=function(l,j){a("span.pending-count").each(function(){var m=a(this),o;o=m.html().replace(/[ ,.]+/g,"");o=parseInt(o,10);if(isNaN(o)){return}if(a("#"+j.element).is(".unapproved")){o=o-1}else{if(a(j.target).parents("span.unapprove").size()){o=o+1}}if(o<0){o=0}m.parents("#awaiting-mod")[0==o?"addClass":"removeClass"]("count-0");o=o.toString();if(o.length>3){o=o.substr(0,o.length-3)+" "+o.substr(-3)}m.html(o)});a("span.spam-count").each(function(){var m=a(this),o;o=m.html().replace(/[ ,.]+/g,"");o=parseInt(o,10);if(isNaN(o)){return}if(a(j.target).parents("span.spam").size()){o=o+1}else{if(a("#"+j.element).is(".spam")){o=o-1}}if(o<0){o=0}o=o.toString();if(o.length>3){o=o.substr(0,o.length-3)+" "+o.substr(-3)}m.html(o)});if(("object"==typeof l)&&f p").dblclick(function(){commentReply.toggle(a(this).parent())});a("#doaction, #doaction2, #post-query-submit").click(function(c){if(a("#the-comment-list #replyrow").length>0){commentReply.close()}});this.comments_listing=a('#comments-form > input[name="comment_status"]').val()||""},addEvents:function(b){b.each(function(){a(this).find(".column-comment > p").dblclick(function(){commentReply.toggle(a(this).parent())})})},toggle:function(b){if(a(b).css("display")!="none"){a(b).find("a.vim-q").click()}},revert:function(){if(a("#the-comment-list #replyrow").length<1){return false}a("#replyrow").fadeOut("fast",function(){commentReply.close()});return false},close:function(){a(this.o).fadeIn("fast").css("backgroundColor","");a("#com-reply").append(a("#replyrow"));a("#replycontent").val("");a("#edithead input").val("");a("#replysubmit .error").html("").hide();a("#replysubmit .waiting").hide();if(a.browser.msie){a("#replycontainer, #replycontent").css("height","120px")}else{a("#replycontainer").resizable("destroy").css("height","120px")}},open:function(i,g,c){var e=this,d,b,f;e.close();e.o="#comment-"+i;a("#replyrow td").attr("colspan",a(".widefat thead th:visible").length);d=a("#replyrow"),rowData=a("#inline-"+i);b=e.act=(c=="edit")?"edit-comment":"replyto-comment";a("#action",d).val(b);a("#comment_post_ID",d).val(g);a("#comment_ID",d).val(i);if(c=="edit"){a("#author",d).val(a("div.author",rowData).text());a("#author-email",d).val(a("div.author-email",rowData).text());a("#author-url",d).val(a("div.author-url",rowData).text());a("#status",d).val(a("div.comment_status",rowData).text());a("#replycontent",d).val(a("textarea.comment",rowData).val());a("#edithead, #savebtn",d).show();a("#replyhead, #replybtn",d).hide();f=a(e.o).height();if(f>220){if(a.browser.msie){a("#replycontainer, #replycontent",d).height(f-105)}else{a("#replycontainer",d).height(f-105)}}a(e.o).after(d.hide()).fadeOut("fast",function(){a("#replyrow").fadeIn("fast")})}else{a("#edithead, #savebtn",d).hide();a("#replyhead, #replybtn",d).show();a(e.o).after(d);a("#replyrow").hide().fadeIn("fast")}if(!a.browser.msie){a("#replycontainer").resizable({handles:"s",axis:"y",minHeight:80,stop:function(){a("#replycontainer").width("auto")}})}setTimeout(function(){var l,j,m,h,k;l=a("#replyrow").offset().top;j=l+a("#replyrow").height();m=window.pageYOffset||document.documentElement.scrollTop;h=document.documentElement.clientHeight||self.innerHeight||0;k=m+h;if(k-20]*?>/g,"")}if(c){a("#replysubmit .error").html(c).show()}}};a(document).ready(function(){var e,b,c,d;setCommentsList();commentReply.init();a("span.delete a.delete").click(function(){return false});if(typeof QTags!="undefined"){ed_reply=new QTags("ed_reply","replycontent","replycontainer","more")}if(typeof a.table_hotkeys!="undefined"){e=function(f){return function(){var h,g;h="next"==f?"first":"last";g=a("."+f+".page-numbers");if(g.length){window.location=g[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g,"")+"&hotkeys_highlight_"+h+"=1"}}};b=function(g,f){window.location=a("span.edit a",f).attr("href")};c=function(){toggleWithKeyboard=true;a("#comments-form thead #cb input:checkbox").click().attr("checked","");toggleWithKeyboard=false};d=function(f){return function(h,g){a("option[value="+f+"]").attr("selected","selected");a("form#comments-form")[0].submit()}};a.table_hotkeys(a("table.widefat"),["a","u","s","d","r","q",["e",b],["shift+a",d("approve")],["shift+s",d("markspam")],["shift+d",d("delete")],["shift+x",c],["shift+u",d("unapprove")]],{highlight_first:adminCommentsL10n.hotkeys_highlight_first,highlight_last:adminCommentsL10n.hotkeys_highlight_last,prev_page_link_cb:e("prev"),next_page_link_cb:e("next")})}})})(jQuery); \ No newline at end of file diff --git a/wp-admin/js/editor.dev.js b/wp-admin/js/editor.dev.js new file mode 100644 index 0000000..17c0192 --- /dev/null +++ b/wp-admin/js/editor.dev.js @@ -0,0 +1,179 @@ + +jQuery(document).ready(function($){ + var h = wpCookies.getHash('TinyMCE_content_size'); + + if ( getUserSetting( 'editor' ) == 'html' ) { + if ( h ) + $('#content').css('height', h.ch - 15 + 'px'); + } else { + $('#content').css('color', 'white'); + $('#quicktags').hide(); + } +}); + +var switchEditors = { + + mode : '', + + I : function(e) { + return document.getElementById(e); + }, + + edInit : function() { + }, + + saveCallback : function(el, content, body) { + + if ( tinyMCE.activeEditor.isHidden() ) + content = this.I(el).value; + else + content = this.pre_wpautop(content); + + return content; + }, + + pre_wpautop : function(content) { + var blocklist1, blocklist2; + + // Protect pre|script tags + content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) { + a = a.replace(/
    [\r\n]*/g, ''); + return a.replace(/<\/?p( [^>]*)?>[\r\n]*/g, ''); + }); + + // Pretty it up for the source editor + blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tr|th|td|div|h[1-6]|p'; + content = content.replace(new RegExp('\\s*\\s*', 'mg'), '\n'); + content = content.replace(new RegExp('\\s*<(('+blocklist1+')[^>]*)>', 'mg'), '\n<$1>'); + + // Mark

    if it has any attributes. + content = content.replace(new RegExp('(

    ]+>.*?)

    ', 'mg'), '$1'); + + // Sepatate
    containing

    + content = content.replace(new RegExp(']*)>\\s*

    ', 'mgi'), '\n\n'); + + // Remove

    and
    + content = content.replace(new RegExp('\\s*

    ', 'mgi'), ''); + content = content.replace(new RegExp('\\s*

    \\s*', 'mgi'), '\n\n'); + content = content.replace(new RegExp('\\n\\s*\\n', 'mgi'), '\n\n'); + content = content.replace(new RegExp('\\s*
    \\s*', 'gi'), '\n'); + + // Fix some block element newline issues + content = content.replace(new RegExp('\\s*\\s*', 'mg'), '
    \n'); + content = content.replace(new RegExp('\\s*\\[caption([^\\[]+)\\[/caption\\]\\s*', 'gi'), '\n\n[caption$1[/caption]\n\n'); + content = content.replace(new RegExp('caption\\]\\n\\n+\\[caption', 'g'), 'caption]\n\n[caption'); + + blocklist2 = 'blockquote|ul|ol|li|table|thead|tr|th|td|h[1-6]|pre'; + content = content.replace(new RegExp('\\s*<(('+blocklist2+') ?[^>]*)\\s*>', 'mg'), '\n<$1>'); + content = content.replace(new RegExp('\\s*\\s*', 'mg'), '\n'); + content = content.replace(new RegExp(']*)>', 'g'), '\t'); + + if ( content.indexOf('/g, function(a){ + return a.replace(/[\r\n]+/g, ''); + }); + } + + // Unmark special paragraph closing tags + content = content.replace(new RegExp('', 'g'), '

    \n'); + content = content.replace(new RegExp('\\s*(

    ]+>.*

    )', 'mg'), '\n$1'); + + // Trim whitespace + content = content.replace(new RegExp('^\\s*', ''), ''); + content = content.replace(new RegExp('[\\s\\u00a0]*$', ''), ''); + + // put back the line breaks in pre|script + content = content.replace(//g, '\n'); + + // Hope. + return content; + }, + + go : function(id, mode) { + id = id || 'content'; + mode = mode || this.mode || ''; + + var ed, qt = this.I('quicktags'), H = this.I('edButtonHTML'), P = this.I('edButtonPreview'), ta = this.I(id); + + try { ed = tinyMCE.get(id); } + catch(e) { ed = false; } + + if ( 'tinymce' == mode ) { + if ( ed && ! ed.isHidden() ) + return false; + + setUserSetting( 'editor', 'tinymce' ); + this.mode = 'html'; + + P.className = 'active'; + H.className = ''; + edCloseAllTags(); // :-( + qt.style.display = 'none'; + + ta.value = this.wpautop(ta.value); + + if ( ed ) { + ed.show(); + } else { + try{tinyMCE.execCommand("mceAddControl", false, id);} + catch(e){} + } + } else { + setUserSetting( 'editor', 'html' ); + ta.style.color = '#000'; + this.mode = 'tinymce'; + H.className = 'active'; + P.className = ''; + + if ( ed && !ed.isHidden() ) { + ta.style.height = ed.getContentAreaContainer().offsetHeight + 24 + 'px'; + ed.hide(); + } + + qt.style.display = 'block'; + } + return false; + }, + + wpautop : function(pee) { + var blocklist = 'table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6]'; + + if ( pee.indexOf('/g, function(a){ + return a.replace(/[\r\n]+/g, ''); + }); + } + + pee = pee.replace(/<[^<>]+>/g, function(a){ + return a.replace(/[\r\n]+/g, ' '); + }); + + pee = pee + "\n\n"; + pee = pee.replace(new RegExp('
    \\s*
    ', 'gi'), "\n\n"); + pee = pee.replace(new RegExp('(<(?:'+blocklist+')[^>]*>)', 'gi'), "\n$1"); + pee = pee.replace(new RegExp('()', 'gi'), "$1\n\n"); + pee = pee.replace(new RegExp("\\r\\n|\\r", 'g'), "\n"); + pee = pee.replace(new RegExp("\\n\\s*\\n+", 'g'), "\n\n"); + pee = pee.replace(new RegExp('([\\s\\S]+?)\\n\\n', 'mg'), "

    $1

    \n"); + pee = pee.replace(new RegExp('

    \\s*?

    ', 'gi'), ''); + pee = pee.replace(new RegExp('

    \\s*(]*>)\\s*

    ', 'gi'), "$1"); + pee = pee.replace(new RegExp("

    (", 'gi'), "$1"); + pee = pee.replace(new RegExp('

    \\s*]*)>', 'gi'), "

    "); + pee = pee.replace(new RegExp('\\s*

    ', 'gi'), '

    '); + pee = pee.replace(new RegExp('

    \\s*(]*>)', 'gi'), "$1"); + pee = pee.replace(new RegExp('(]*>)\\s*

    ', 'gi'), "$1"); + pee = pee.replace(new RegExp('\\s*\\n', 'gi'), "
    \n"); + pee = pee.replace(new RegExp('(]*>)\\s*
    ', 'gi'), "$1"); + pee = pee.replace(new RegExp('
    (\\s*)', 'gi'), '$1'); + pee = pee.replace(new RegExp('(?:

    |
    )*\\s*\\[caption([^\\[]+)\\[/caption\\]\\s*(?:

    |
    )*', 'gi'), '[caption$1[/caption]'); + + // Fix the pre|script tags + pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) { + a = a.replace(/
    [\r\n]*/g, '\n'); + return a.replace(/<\/?p( [^>]*)?>[\r\n]*/g, '\n'); + }); + + return pee; + } +}; diff --git a/wp-admin/js/editor.js b/wp-admin/js/editor.js new file mode 100644 index 0000000..f3e5415 --- /dev/null +++ b/wp-admin/js/editor.js @@ -0,0 +1 @@ +jQuery(document).ready(function(b){var a=wpCookies.getHash("TinyMCE_content_size");if(getUserSetting("editor")=="html"){if(a){b("#content").css("height",a.ch-15+"px")}}else{b("#content").css("color","white");b("#quicktags").hide()}});var switchEditors={mode:"",I:function(a){return document.getElementById(a)},edInit:function(){},saveCallback:function(b,c,a){if(tinyMCE.activeEditor.isHidden()){c=this.I(b).value}else{c=this.pre_wpautop(c)}return c},pre_wpautop:function(b){var c,a;b=b.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g,function(d){d=d.replace(/
    [\r\n]*/g,"");return d.replace(/<\/?p( [^>]*)?>[\r\n]*/g,"")});c="blockquote|ul|ol|li|table|thead|tbody|tr|th|td|div|h[1-6]|p";b=b.replace(new RegExp("\\s*\\s*","mg"),"\n");b=b.replace(new RegExp("\\s*<(("+c+")[^>]*)>","mg"),"\n<$1>");b=b.replace(new RegExp("(

    ]+>.*?)

    ","mg"),"$1");b=b.replace(new RegExp("]*)>\\s*

    ","mgi"),"\n\n");b=b.replace(new RegExp("\\s*

    ","mgi"),"");b=b.replace(new RegExp("\\s*

    \\s*","mgi"),"\n\n");b=b.replace(new RegExp("\\n\\s*\\n","mgi"),"\n\n");b=b.replace(new RegExp("\\s*
    \\s*","gi"),"\n");b=b.replace(new RegExp("\\s*\\s*","mg"),"\n");b=b.replace(new RegExp("\\s*\\[caption([^\\[]+)\\[/caption\\]\\s*","gi"),"\n\n[caption$1[/caption]\n\n");b=b.replace(new RegExp("caption\\]\\n\\n+\\[caption","g"),"caption]\n\n[caption");a="blockquote|ul|ol|li|table|thead|tr|th|td|h[1-6]|pre";b=b.replace(new RegExp("\\s*<(("+a+") ?[^>]*)\\s*>","mg"),"\n<$1>");b=b.replace(new RegExp("\\s*\\s*","mg"),"\n");b=b.replace(new RegExp("]*)>","g"),"\t");if(b.indexOf("/g,function(d){return d.replace(/[\r\n]+/g,"")})}b=b.replace(new RegExp("","g"),"

    \n");b=b.replace(new RegExp("\\s*(

    ]+>.*

    )","mg"),"\n$1");b=b.replace(new RegExp("^\\s*",""),"");b=b.replace(new RegExp("[\\s\\u00a0]*$",""),"");b=b.replace(//g,"\n");return b},go:function(i,g){i=i||"content";g=g||this.mode||"";var b,h=this.I("quicktags"),c=this.I("edButtonHTML"),d=this.I("edButtonPreview"),a=this.I(i);try{b=tinyMCE.get(i)}catch(f){b=false}if("tinymce"==g){if(b&&!b.isHidden()){return false}setUserSetting("editor","tinymce");this.mode="html";d.className="active";c.className="";edCloseAllTags();h.style.display="none";a.value=this.wpautop(a.value);if(b){b.show()}else{try{tinyMCE.execCommand("mceAddControl",false,i)}catch(f){}}}else{setUserSetting("editor","html");a.style.color="#000";this.mode="tinymce";c.className="active";d.className="";if(b&&!b.isHidden()){a.style.height=b.getContentAreaContainer().offsetHeight+24+"px";b.hide()}h.style.display="block"}return false},wpautop:function(a){var b="table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6]";if(a.indexOf("/g,function(c){return c.replace(/[\r\n]+/g,"")})}a=a.replace(/<[^<>]+>/g,function(c){return c.replace(/[\r\n]+/g," ")});a=a+"\n\n";a=a.replace(new RegExp("
    \\s*
    ","gi"),"\n\n");a=a.replace(new RegExp("(<(?:"+b+")[^>]*>)","gi"),"\n$1");a=a.replace(new RegExp("()","gi"),"$1\n\n");a=a.replace(new RegExp("\\r\\n|\\r","g"),"\n");a=a.replace(new RegExp("\\n\\s*\\n+","g"),"\n\n");a=a.replace(new RegExp("([\\s\\S]+?)\\n\\n","mg"),"

    $1

    \n");a=a.replace(new RegExp("

    \\s*?

    ","gi"),"");a=a.replace(new RegExp("

    \\s*(]*>)\\s*

    ","gi"),"$1");a=a.replace(new RegExp("

    (","gi"),"$1");a=a.replace(new RegExp("

    \\s*]*)>","gi"),"

    ");a=a.replace(new RegExp("\\s*

    ","gi"),"

    ");a=a.replace(new RegExp("

    \\s*(]*>)","gi"),"$1");a=a.replace(new RegExp("(]*>)\\s*

    ","gi"),"$1");a=a.replace(new RegExp("\\s*\\n","gi"),"
    \n");a=a.replace(new RegExp("(]*>)\\s*
    ","gi"),"$1");a=a.replace(new RegExp("
    (\\s*)","gi"),"$1");a=a.replace(new RegExp("(?:

    |
    )*\\s*\\[caption([^\\[]+)\\[/caption\\]\\s*(?:

    |
    )*","gi"),"[caption$1[/caption]");a=a.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g,function(c){c=c.replace(/
    [\r\n]*/g,"\n");return c.replace(/<\/?p( [^>]*)?>[\r\n]*/g,"\n")});return a}}; \ No newline at end of file diff --git a/wp-admin/js/farbtastic.js b/wp-admin/js/farbtastic.js new file mode 100644 index 0000000..9399d0c --- /dev/null +++ b/wp-admin/js/farbtastic.js @@ -0,0 +1,333 @@ +// $Id: farbtastic.js,v 1.2 2007/01/08 22:53:01 unconed Exp $ +// Farbtastic 1.2 + +var farbtastic_click = false; + +jQuery.fn.farbtastic = function (callback) { + jQuery.farbtastic(this, callback); + return this; +}; + +jQuery.farbtastic = function (container, callback) { + var container = jQuery(container).get(0); + return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); +} + +jQuery._farbtastic = function (container, callback) { + // Store farbtastic object + var fb = this; + + // Insert markup + jQuery(container).html('
    '); + var e = jQuery('.farbtastic', container); + fb.wheel = jQuery('.wheel', container).get(0); + // Dimensions + fb.radius = 84; + fb.square = 100; + fb.width = 194; + + // Fix background PNGs in IE6 + if (navigator.appVersion.match(/MSIE [0-6]\./)) { + jQuery('*', e).each(function () { + if (this.currentStyle.backgroundImage != 'none') { + var image = this.currentStyle.backgroundImage; + image = this.currentStyle.backgroundImage.substring(5, image.length - 2); + jQuery(this).css({ + 'backgroundImage': 'none', + 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" + }); + } + }); + } + + /** + * Link to the given element(s) or callback. + */ + fb.linkTo = function (callback) { + // Unbind previous nodes + if (typeof fb.callback == 'object') { + jQuery(fb.callback).unbind('keyup', fb.updateValue); + } + + // Reset color + fb.color = null; + + // Bind callback or elements + if (typeof callback == 'function') { + fb.callback = callback; + } + else if (typeof callback == 'object' || typeof callback == 'string') { + fb.callback = jQuery(callback); + fb.callback.bind('keyup', fb.updateValue); + if (fb.callback.get(0).value) { + fb.setColor(fb.callback.get(0).value); + } + } + return this; + } + fb.updateValue = function (event) { + if (this.value && this.value != fb.color) { + fb.setColor(this.value); + } + } + + /** + * Change color with HTML syntax #123456 + */ + fb.setColor = function (color) { + var unpack = fb.unpack(color); + if (fb.color != color && unpack) { + fb.color = color; + fb.rgb = unpack; + fb.hsl = fb.RGBToHSL(fb.rgb); + fb.updateDisplay(); + } + return this; + } + + /** + * Change color with HSL triplet [0..1, 0..1, 0..1] + */ + fb.setHSL = function (hsl) { + fb.hsl = hsl; + fb.rgb = fb.HSLToRGB(hsl); + fb.color = fb.pack(fb.rgb); + fb.updateDisplay(); + return this; + } + + ///////////////////////////////////////////////////// + + /** + * Retrieve the coordinates of the given event relative to the center + * of the widget. + */ + fb.widgetCoords = function (event) { + var x, y; + var el = event.target || event.srcElement; + var reference = fb.wheel; + + if (typeof event.offsetX != 'undefined') { + // Use offset coordinates and find common offsetParent + var pos = { x: event.offsetX, y: event.offsetY }; + + // Send the coordinates upwards through the offsetParent chain. + var e = el; + while (e) { + e.mouseX = pos.x; + e.mouseY = pos.y; + pos.x += e.offsetLeft; + pos.y += e.offsetTop; + e = e.offsetParent; + } + + // Look for the coordinates starting from the wheel widget. + var e = reference; + var offset = { x: 0, y: 0 } + while (e) { + if (typeof e.mouseX != 'undefined') { + x = e.mouseX - offset.x; + y = e.mouseY - offset.y; + break; + } + offset.x += e.offsetLeft; + offset.y += e.offsetTop; + e = e.offsetParent; + } + + // Reset stored coordinates + e = el; + while (e) { + e.mouseX = undefined; + e.mouseY = undefined; + e = e.offsetParent; + } + } + else { + // Use absolute coordinates + var pos = fb.absolutePosition(reference); + x = (event.pageX || 0*(event.clientX + jQuery('html').get(0).scrollLeft)) - pos.x; + y = (event.pageY || 0*(event.clientY + jQuery('html').get(0).scrollTop)) - pos.y; + } + // Subtract distance to middle + return { x: x - fb.width / 2, y: y - fb.width / 2 }; + } + + /** + * Mousedown handler + */ + fb.mousedown = function (event) { + farbtastic_click = true; + // Capture mouse + if (!document.dragging) { + jQuery(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); + document.dragging = true; + } + + // Check which area is being dragged + var pos = fb.widgetCoords(event); + fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; + + // Process + fb.mousemove(event); + return false; + } + + /** + * Mousemove handler + */ + fb.mousemove = function (event) { + // Get coordinates relative to color picker center + var pos = fb.widgetCoords(event); + + // Set new HSL parameters + if (fb.circleDrag) { + var hue = Math.atan2(pos.x, -pos.y) / 6.28; + if (hue < 0) hue += 1; + fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); + } + else { + var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); + var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); + fb.setHSL([fb.hsl[0], sat, lum]); + } + return false; + } + + /** + * Mouseup handler + */ + fb.mouseup = function () { + // Uncapture mouse + farbtastic_click = false; + jQuery(document).unbind('mousemove', fb.mousemove); + jQuery(document).unbind('mouseup', fb.mouseup); + document.dragging = false; + } + + /** + * Update the markers and styles + */ + fb.updateDisplay = function () { + // Markers + var angle = fb.hsl[0] * 6.28; + jQuery('.h-marker', e).css({ + left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', + top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' + }); + + jQuery('.sl-marker', e).css({ + left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', + top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' + }); + + // Saturation/Luminance gradient + jQuery('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); + + // Linked elements or callback + if (typeof fb.callback == 'object') { + // Set background/foreground color + jQuery(fb.callback).css({ + backgroundColor: fb.color, + color: fb.hsl[2] > 0.5 ? '#000' : '#fff' + }); + + // Change linked value + jQuery(fb.callback).each(function() { + if (this.value && this.value != fb.color) { + this.value = fb.color; + } + }); + } + else if (typeof fb.callback == 'function') { + fb.callback.call(fb, fb.color); + } + } + + /** + * Get absolute position of element + */ + fb.absolutePosition = function (el) { + var r = { x: el.offsetLeft, y: el.offsetTop }; + // Resolve relative to offsetParent + if (el.offsetParent) { + var tmp = fb.absolutePosition(el.offsetParent); + r.x += tmp.x; + r.y += tmp.y; + } + return r; + }; + + /* Various color utility functions */ + fb.pack = function (rgb) { + var r = Math.round(rgb[0] * 255); + var g = Math.round(rgb[1] * 255); + var b = Math.round(rgb[2] * 255); + return '#' + (r < 16 ? '0' : '') + r.toString(16) + + (g < 16 ? '0' : '') + g.toString(16) + + (b < 16 ? '0' : '') + b.toString(16); + } + + fb.unpack = function (color) { + if (color.length == 7) { + return [parseInt('0x' + color.substring(1, 3)) / 255, + parseInt('0x' + color.substring(3, 5)) / 255, + parseInt('0x' + color.substring(5, 7)) / 255]; + } + else if (color.length == 4) { + return [parseInt('0x' + color.substring(1, 2)) / 15, + parseInt('0x' + color.substring(2, 3)) / 15, + parseInt('0x' + color.substring(3, 4)) / 15]; + } + } + + fb.HSLToRGB = function (hsl) { + var m1, m2, r, g, b; + var h = hsl[0], s = hsl[1], l = hsl[2]; + m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; + m1 = l * 2 - m2; + return [this.hueToRGB(m1, m2, h+0.33333), + this.hueToRGB(m1, m2, h), + this.hueToRGB(m1, m2, h-0.33333)]; + } + + fb.hueToRGB = function (m1, m2, h) { + h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); + if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; + if (h * 2 < 1) return m2; + if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; + return m1; + } + + fb.RGBToHSL = function (rgb) { + var min, max, delta, h, s, l; + var r = rgb[0], g = rgb[1], b = rgb[2]; + min = Math.min(r, Math.min(g, b)); + max = Math.max(r, Math.max(g, b)); + delta = max - min; + l = (min + max) / 2; + s = 0; + if (l > 0 && l < 1) { + s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); + } + h = 0; + if (delta > 0) { + if (max == r && max != g) h += (g - b) / delta; + if (max == g && max != b) h += (2 + (b - r) / delta); + if (max == b && max != r) h += (4 + (r - g) / delta); + h /= 6; + } + return [h, s, l]; + } + + // Install mousedown handler (the others are set on the document on-demand) + jQuery('*', e).mousedown(fb.mousedown); + + // Init color + fb.setColor('#000000'); + + // Set linked elements/callback + if (callback) { + fb.linkTo(callback); + } +} \ No newline at end of file diff --git a/wp-admin/js/gallery.dev.js b/wp-admin/js/gallery.dev.js new file mode 100644 index 0000000..a7f1661 --- /dev/null +++ b/wp-admin/js/gallery.dev.js @@ -0,0 +1,204 @@ +jQuery(document).ready(function($) { + var gallerySortable, gallerySortableInit, w, desc = false; + + gallerySortableInit = function() { + gallerySortable = $('#media-items').sortable( { + items: '.media-item', + placeholder: 'sorthelper', + axis: 'y', + distance: 2, + stop: function(e, ui) { + // When an update has occurred, adjust the order for each item + var all = $('#media-items').sortable('toArray'), len = all.length; + $.each(all, function(i, id) { + var order = desc ? (len - i) : (1 + i); + $('#' + id + ' .menu_order input').val(order); + }); + } + } ); + } + + sortIt = function() { + var all = $('.menu_order_input'), len = all.length; + all.each(function(i){ + var order = desc ? (len - i) : (1 + i); + $(this).val(order); + }); + } + + clearAll = function(c) { + c = c || 0; + $('.menu_order_input').each(function(){ + if ( this.value == '0' || c ) this.value = ''; + }); + } + + $('#asc').click(function(){desc = false; sortIt(); return false;}); + $('#desc').click(function(){desc = true; sortIt(); return false;}); + $('#clear').click(function(){clearAll(1); return false;}); + $('#showall').click(function(){ + $('#sort-buttons span a').toggle(); + $('a.describe-toggle-on').hide(); + $('a.describe-toggle-off, table.slidetoggle').show(); + return false; + }); + $('#hideall').click(function(){ + $('#sort-buttons span a').toggle(); + $('a.describe-toggle-on').show(); + $('a.describe-toggle-off, table.slidetoggle').hide(); + return false; + }); + + // initialize sortable + gallerySortableInit(); + clearAll(); + + if ( $('#media-items>*').length > 1 ) { + w = wpgallery.getWin(); + + $('#save-all, #gallery-settings').show(); + if ( typeof w.tinyMCE != 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) { + wpgallery.mcemode = true; + wpgallery.init(); + } else { + $('#insert-gallery').show(); + } + } +}); + +jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup + +/* gallery settings */ +var tinymce = null, tinyMCE, wpgallery; + +wpgallery = { + mcemode : false, + editor : {}, + dom : {}, + is_update : false, + el : {}, + + I : function(e) { + return document.getElementById(e); + }, + + init: function() { + var t = this, li, q, i, it, w = t.getWin(); + + if ( ! t.mcemode ) return; + + li = ('' + document.location.search).replace(/^\?/, '').split('&'); + q = {}; + for (i=0; i*").length>1){a=wpgallery.getWin();c("#save-all, #gallery-settings").show();if(typeof a.tinyMCE!="undefined"&&a.tinyMCE.activeEditor&&!a.tinyMCE.activeEditor.isHidden()){wpgallery.mcemode=true;wpgallery.init()}else{c("#insert-gallery").show()}}});jQuery(window).unload(function(){tinymce=tinyMCE=wpgallery=null});var tinymce=null,tinyMCE,wpgallery;wpgallery={mcemode:false,editor:{},dom:{},is_update:false,el:{},I:function(a){return document.getElementById(a)},init:function(){var d=this,a,f,c,e,b=d.getWin();if(!d.mcemode){return}a=(""+document.location.search).replace(/^\?/,"").split("&");f={};for(c=0;c 0 ) { + t.revert(); + } + }); + + $('#post-query-submit').click(function(e){ + if ( $('form#posts-filter tr.inline-editor').length > 0 ) + t.revert(); + }); + + }, + + toggle : function(el) { + var t = this; + $(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el); + }, + + addEvents : function(r) { + r.each(function() { + var row = $(this); + $('a.editinline', row).click(function() { inlineEditPost.edit(this); return false; }); + }); + }, + + setBulk : function() { + var te = '', type = this.type, tax; + this.revert(); + + $('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length); + $('table.widefat tbody').prepend( $('#bulk-edit') ); + $('#bulk-edit').addClass('inline-editor').show(); + + $('tbody th.check-column input[type="checkbox"]').each(function(i){ + if ( $(this).attr('checked') ) { + var id = $(this).val(), theTitle; + theTitle = $('#inline_'+id+' .post_title').text() || inlineEditL10n.notitle; + te += '
    X'+theTitle+'
    '; + } + }); + + $('#bulk-titles').html(te); + $('#bulk-titles a').click(function() { + var id = $(this).attr('id').substr(1); + + $('table.widefat input[value="'+id+'"]').attr('checked', ''); + $('#ttle'+id).remove(); + }); + + // enable autocomplete for tags + if ( type == 'post' ) { + // support multi taxonomies? + tax = 'post_tag'; + $('tr.inline-editor textarea[name="tags_input"]').suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+tax, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } ); + } + }, + + edit : function(id) { + var t = this, fields, editRow, rowData, cats, status, pageOpt, f, pageLevel, nextPage, pageLoop = true, nextLevel, tax; + t.revert(); + + if ( typeof(id) == 'object' ) + id = t.getId(id); + + fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password']; + if ( t.type == 'page' ) fields.push('post_parent', 'menu_order', 'page_template'); + if ( t.type == 'post' ) fields.push('tags_input'); + + // add the new blank row + editRow = $('#inline-edit').clone(true); + $('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length); + + if ( $(t.what+id).hasClass('alternate') ) + $(editRow).addClass('alternate'); + $(t.what+id).hide().after(editRow); + + // populate the data + rowData = $('#inline_'+id); + for ( f = 0; f < fields.length; f++ ) { + $(':input[name="'+fields[f]+'"]', editRow).val( $('.'+fields[f], rowData).text() ); + } + + if ( $('.comment_status', rowData).text() == 'open' ) + $('input[name="comment_status"]', editRow).attr("checked", "checked"); + if ( $('.ping_status', rowData).text() == 'open' ) + $('input[name="ping_status"]', editRow).attr("checked", "checked"); + if ( $('.sticky', rowData).text() == 'sticky' ) + $('input[name="sticky"]', editRow).attr("checked", "checked"); + + // categories + if ( cats = $('.post_category', rowData).text() ) + $('ul.cat-checklist :checkbox', editRow).val(cats.split(',')); + + // handle the post status + status = $('._status', rowData).text(); + if ( status != 'future' ) $('select[name="_status"] option[value="future"]', editRow).remove(); + if ( status == 'private' ) { + $('input[name="keep_private"]', editRow).attr("checked", "checked"); + $('input.inline-edit-password-input').val('').attr('disabled', 'disabled'); + } + + // remove the current page and children from the parent dropdown + pageOpt = $('select[name="post_parent"] option[value="'+id+'"]', editRow); + if ( pageOpt.length > 0 ) { + pageLevel = pageOpt[0].className.split('-')[1]; + nextPage = pageOpt; + while ( pageLoop ) { + nextPage = nextPage.next('option'); + if (nextPage.length == 0) break; + nextLevel = nextPage[0].className.split('-')[1]; + if ( nextLevel <= pageLevel ) { + pageLoop = false; + } else { + nextPage.remove(); + nextPage = pageOpt; + } + } + pageOpt.remove(); + } + + $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); + $('.ptitle', editRow).focus(); + + // enable autocomplete for tags + if ( t.type == 'post' ) { + tax = 'post_tag'; + $('tr.inline-editor textarea[name="tags_input"]').suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+tax, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } ); + } + + return false; + }, + + save : function(id) { + var params, fields; + + if( typeof(id) == 'object' ) + id = this.getId(id); + + $('table.widefat .inline-edit-save .waiting').show(); + + params = { + action: 'inline-save', + post_type: this.type, + post_ID: id, + edit_date: 'true' + }; + + fields = $('#edit-'+id+' :input').fieldSerialize(); + params = fields + '&' + $.param(params); + + // make ajax request + $.post('admin-ajax.php', params, + function(r) { + $('table.widefat .inline-edit-save .waiting').hide(); + + if (r) { + if ( -1 != r.indexOf(']*?>/g, '' ); + $('#edit-'+id+' .inline-edit-save').append(''+r+''); + } + } else { + $('#edit-'+id+' .inline-edit-save').append(''+inlineEditL10n.error+''); + } + } + , 'html'); + return false; + }, + + revert : function() { + var id; + + if ( id = $('table.widefat tr.inline-editor').attr('id') ) { + $('table.widefat .inline-edit-save .waiting').hide(); + + if ( 'bulk-edit' == id ) { + $('table.widefat #bulk-edit').removeClass('inline-editor').hide(); + $('#bulk-titles').html(''); + $('#inlineedit').append( $('#bulk-edit') ); + } else { + $('#'+id).remove(); + id = id.substr( id.lastIndexOf('-') + 1 ); + $(this.what+id).show(); + } + } + + return false; + }, + + getId : function(o) { + var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-'); + return parts[parts.length - 1]; + } +}; + +$(document).ready(function(){inlineEditPost.init();}); +})(jQuery); diff --git a/wp-admin/js/inline-edit-post.js b/wp-admin/js/inline-edit-post.js new file mode 100644 index 0000000..f8c9bb3 --- /dev/null +++ b/wp-admin/js/inline-edit-post.js @@ -0,0 +1 @@ +(function(a){inlineEditPost={init:function(){var c=this,d=a("#inline-edit"),b=a("#bulk-edit");c.type=a("table.widefat").hasClass("page")?"page":"post";c.what="#"+c.type+"-";c.rows=a("tr.iedit");d.keyup(function(f){if(f.which==27){return inlineEditPost.revert()}});b.keyup(function(f){if(f.which==27){return inlineEditPost.revert()}});a("a.cancel",d).click(function(){return inlineEditPost.revert()});a("a.save",d).click(function(){return inlineEditPost.save(this)});a("td",d).keydown(function(f){if(f.which==13){return inlineEditPost.save(this)}});a("a.cancel",b).click(function(){return inlineEditPost.revert()});a("#inline-edit .inline-edit-private input[value=private]").click(function(){var e=a("input.inline-edit-password-input");if(a(this).attr("checked")){e.val("").attr("disabled","disabled")}else{e.attr("disabled","")}});c.addEvents(c.rows);a("#bulk-title-div").parents("fieldset").after(a("#inline-edit fieldset.inline-edit-categories").clone()).siblings("fieldset:last").prepend(a("#inline-edit label.inline-edit-tags").clone());a("span.catshow").click(function(){a(".inline-editor ul.cat-checklist").addClass("cat-hover");a(".inline-editor span.cathide").show();a(this).hide()});a("span.cathide").click(function(){a(".inline-editor ul.cat-checklist").removeClass("cat-hover");a(".inline-editor span.catshow").show();a(this).hide()});a('select[name="_status"] option[value="future"]',b).remove();a("#doaction, #doaction2").click(function(f){var g=a(this).attr("id").substr(2);if(a('select[name="'+g+'"]').val()=="edit"){f.preventDefault();c.setBulk()}else{if(a("form#posts-filter tr.inline-editor").length>0){c.revert()}}});a("#post-query-submit").click(function(f){if(a("form#posts-filter tr.inline-editor").length>0){c.revert()}})},toggle:function(c){var b=this;a(b.what+b.getId(c)).css("display")=="none"?b.revert():b.edit(c)},addEvents:function(b){b.each(function(){var c=a(this);a("a.editinline",c).click(function(){inlineEditPost.edit(this);return false})})},setBulk:function(){var d="",c=this.type,b;this.revert();a("#bulk-edit td").attr("colspan",a(".widefat:first thead th:visible").length);a("table.widefat tbody").prepend(a("#bulk-edit"));a("#bulk-edit").addClass("inline-editor").show();a('tbody th.check-column input[type="checkbox"]').each(function(f){if(a(this).attr("checked")){var g=a(this).val(),e;e=a("#inline_"+g+" .post_title").text()||inlineEditL10n.notitle;d+='
    X'+e+"
    "}});a("#bulk-titles").html(d);a("#bulk-titles a").click(function(){var e=a(this).attr("id").substr(1);a('table.widefat input[value="'+e+'"]').attr("checked","");a("#ttle"+e).remove()});if(c=="post"){b="post_tag";a('tr.inline-editor textarea[name="tags_input"]').suggest("admin-ajax.php?action=ajax-tag-search&tax="+b,{delay:500,minchars:2,multiple:true,multipleSep:", "})}},edit:function(b){var o=this,j,d,g,n,i,h,k,m,l,c=true,p,e;o.revert();if(typeof(b)=="object"){b=o.getId(b)}j=["post_title","post_name","post_author","_status","jj","mm","aa","hh","mn","ss","post_password"];if(o.type=="page"){j.push("post_parent","menu_order","page_template")}if(o.type=="post"){j.push("tags_input")}d=a("#inline-edit").clone(true);a("td",d).attr("colspan",a(".widefat:first thead th:visible").length);if(a(o.what+b).hasClass("alternate")){a(d).addClass("alternate")}a(o.what+b).hide().after(d);g=a("#inline_"+b);for(k=0;k0){m=h[0].className.split("-")[1];l=h;while(c){l=l.next("option");if(l.length==0){break}p=l[0].className.split("-")[1];if(p<=m){c=false}else{l.remove();l=h}}h.remove()}a(d).attr("id","edit-"+b).addClass("inline-editor").show();a(".ptitle",d).focus();if(o.type=="post"){e="post_tag";a('tr.inline-editor textarea[name="tags_input"]').suggest("admin-ajax.php?action=ajax-tag-search&tax="+e,{delay:500,minchars:2,multiple:true,multipleSep:", "})}return false},save:function(d){var c,b;if(typeof(d)=="object"){d=this.getId(d)}a("table.widefat .inline-edit-save .waiting").show();c={action:"inline-save",post_type:this.type,post_ID:d,edit_date:"true"};b=a("#edit-"+d+" :input").fieldSerialize();c=b+"&"+a.param(c);a.post("admin-ajax.php",c,function(e){a("table.widefat .inline-edit-save .waiting").hide();if(e){if(-1!=e.indexOf("]*?>/g,"");a("#edit-"+d+" .inline-edit-save").append(''+e+"")}}else{a("#edit-"+d+" .inline-edit-save").append(''+inlineEditL10n.error+"")}},"html");return false},revert:function(){var b;if(b=a("table.widefat tr.inline-editor").attr("id")){a("table.widefat .inline-edit-save .waiting").hide();if("bulk-edit"==b){a("table.widefat #bulk-edit").removeClass("inline-editor").hide();a("#bulk-titles").html("");a("#inlineedit").append(a("#bulk-edit"))}else{a("#"+b).remove();b=b.substr(b.lastIndexOf("-")+1);a(this.what+b).show()}}return false},getId:function(c){var d=c.tagName=="TR"?c.id:a(c).parents("tr").attr("id"),b=d.split("-");return b[b.length-1]}};a(document).ready(function(){inlineEditPost.init()})})(jQuery); \ No newline at end of file diff --git a/wp-admin/js/inline-edit-tax.dev.js b/wp-admin/js/inline-edit-tax.dev.js new file mode 100644 index 0000000..91c85ff --- /dev/null +++ b/wp-admin/js/inline-edit-tax.dev.js @@ -0,0 +1,129 @@ + +(function($) { +inlineEditTax = { + + init : function() { + var t = this, row = $('#inline-edit'); + + t.type = $('#the-list').attr('className').substr(5); + t.what = '#'+t.type+'-'; + + // get all editable rows + t.rows = $('tr.iedit'); + + // prepare the edit row + row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); }); + + $('a.cancel', row).click(function() { return inlineEditTax.revert(); }); + $('a.save', row).click(function() { return inlineEditTax.save(this); }); + $('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); }); + + // add events + t.addEvents(t.rows); + + $('#posts-filter input[type="submit"]').click(function(e){ + if ( $('form#posts-filter tr.inline-editor').length > 0 ) + t.revert(); + }); + }, + + toggle : function(el) { + var t = this; + $(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el); + }, + + addEvents : function(r) { + r.each(function() { + $(this).find('a.editinline').click(function() { inlineEditTax.edit(this); return false; }); + }); + }, + + edit : function(id) { + var t = this, editRow; + t.revert(); + + if ( typeof(id) == 'object' ) + id = t.getId(id); + + editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id); + $('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length); + + if ( $(t.what+id).hasClass('alternate') ) + $(editRow).addClass('alternate'); + + $(t.what+id).hide().after(editRow); + + $(':input[name="name"]', editRow).val( $('.name', rowData).text() ); + $(':input[name="slug"]', editRow).val( $('.slug', rowData).text() ); + + $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); + $('.ptitle', editRow).eq(0).focus(); + + return false; + }, + + save : function(id) { + var params, fields, tax = $('input[name="taxonomy"]').val() || ''; + + if( typeof(id) == 'object' ) + id = this.getId(id); + + $('table.widefat .inline-edit-save .waiting').show(); + + params = { + action: 'inline-save-tax', + tax_type: this.type, + tax_ID: id, + taxonomy: tax + }; + + fields = $('#edit-'+id+' :input').fieldSerialize(); + params = fields + '&' + $.param(params); + + // make ajax request + $.post('admin-ajax.php', params, + function(r) { + var row, new_id; + $('table.widefat .inline-edit-save .waiting').hide(); + + if (r) { + if ( -1 != r.indexOf('0){b.revert()}})},toggle:function(c){var b=this;a(b.what+b.getId(c)).css("display")=="none"?b.revert():b.edit(c)},addEvents:function(b){b.each(function(){a(this).find("a.editinline").click(function(){inlineEditTax.edit(this);return false})})},edit:function(d){var c=this,b;c.revert();if(typeof(d)=="object"){d=c.getId(d)}b=a("#inline-edit").clone(true),rowData=a("#inline_"+d);a("td",b).attr("colspan",a(".widefat:first thead th:visible").length);if(a(c.what+d).hasClass("alternate")){a(b).addClass("alternate")}a(c.what+d).hide().after(b);a(':input[name="name"]',b).val(a(".name",rowData).text());a(':input[name="slug"]',b).val(a(".slug",rowData).text());a(b).attr("id","edit-"+d).addClass("inline-editor").show();a(".ptitle",b).eq(0).focus();return false},save:function(e){var d,b,c=a('input[name="taxonomy"]').val()||"";if(typeof(e)=="object"){e=this.getId(e)}a("table.widefat .inline-edit-save .waiting").show();d={action:"inline-save-tax",tax_type:this.type,tax_ID:e,taxonomy:c};b=a("#edit-"+e+" :input").fieldSerialize();d=b+"&"+a.param(d);a.post("admin-ajax.php",d,function(g){var h,f;a("table.widefat .inline-edit-save .waiting").hide();if(g){if(-1!=g.indexOf("' ).text( name ); + } ); + } ); + }; + + $('#categorychecklist').wpList( { + alt: '', + what: 'link-category', + response: 'category-ajax-response', + addAfter: catAddAfter + } ); + + $('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');}); + $('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');}); + if ( 'pop' == getUserSetting('cats') ) + $('a[href="#categories-pop"]').click(); + + $('#category-add-toggle').click( function() { + $(this).parents('div:first').toggleClass( 'wp-hidden-children' ); + $('#category-tabs a[href="#categories-all"]').click(); + return false; + } ); + + $('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change(); +}); diff --git a/wp-admin/js/link.js b/wp-admin/js/link.js new file mode 100644 index 0000000..db140c6 --- /dev/null +++ b/wp-admin/js/link.js @@ -0,0 +1 @@ +jQuery(document).ready(function(c){var b,a=false,d,e;c("#link_name").focus();postboxes.add_postbox_toggles("link");c("#category-tabs a").click(function(){var f=c(this).attr("href");c(this).parent().addClass("tabs").siblings("li").removeClass("tabs");c(".tabs-panel").hide();c(f).show();if("#categories-all"==f){deleteUserSetting("cats")}else{setUserSetting("cats","pop")}return false});if(getUserSetting("cats")){c('#category-tabs a[href="#categories-pop"]').click()}b=c("#newcat").one("focus",function(){c(this).val("").removeClass("form-input-tip")});c("#category-add-submit").click(function(){b.focus()});d=function(){if(a){return}a=true;var f=c(this),h=f.is(":checked"),g=f.val().toString();c("#in-link-category-"+g+", #in-popular-category-"+g).attr("checked",h);a=false};e=function(g,f){c(f.what+" response_data",g).each(function(){var h=c(c(this).text());h.find("label").each(function(){var j=c(this),l=j.find("input").val(),m=j.find("input")[0].id,i=c.trim(j.text()),k;c("#"+m).change(d);k=c('').text(i)})})};c("#categorychecklist").wpList({alt:"",what:"link-category",response:"category-ajax-response",addAfter:e});c('a[href="#categories-all"]').click(function(){deleteUserSetting("cats")});c('a[href="#categories-pop"]').click(function(){setUserSetting("cats","pop")});if("pop"==getUserSetting("cats")){c('a[href="#categories-pop"]').click()}c("#category-add-toggle").click(function(){c(this).parents("div:first").toggleClass("wp-hidden-children");c('#category-tabs a[href="#categories-all"]').click();return false});c(".categorychecklist :checkbox").change(d).filter(":checked").change()}); \ No newline at end of file diff --git a/wp-admin/js/media-upload.dev.js b/wp-admin/js/media-upload.dev.js new file mode 100644 index 0000000..e2c00ae --- /dev/null +++ b/wp-admin/js/media-upload.dev.js @@ -0,0 +1,63 @@ +// send html to the post editor +function send_to_editor(h) { + var ed; + + if ( typeof tinyMCE != 'undefined' && ( ed = tinyMCE.activeEditor ) && !ed.isHidden() ) { + ed.focus(); + if (tinymce.isIE) + ed.selection.moveToBookmark(tinymce.EditorManager.activeEditor.windowManager.bookmark); + + if ( h.indexOf('[caption') === 0 ) { + if ( ed.plugins.wpeditimage ) + h = ed.plugins.wpeditimage._do_shcode(h); + } else if ( h.indexOf('[gallery') === 0 ) { + if ( ed.plugins.wpgallery ) + h = ed.plugins.wpgallery._do_gallery(h); + } + + ed.execCommand('mceInsertContent', false, h); + + } else if ( typeof edInsertContent == 'function' ) { + edInsertContent(edCanvas, h); + } else { + jQuery( edCanvas ).val( jQuery( edCanvas ).val() + h ); + } + + tb_remove(); +} + +// thickbox settings +var tb_position; +(function($) { + tb_position = function() { + var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width; + + if ( tbWindow.size() ) { + tbWindow.width( W - 50 ).height( H - 45 ); + $('#TB_iframeContent').width( W - 50 ).height( H - 75 ); + tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'}); + if ( typeof document.body.style.maxWidth != 'undefined' ) + tbWindow.css({'top':'20px','margin-top':'0'}); + }; + + return $('a.thickbox').each( function() { + var href = $(this).attr('href'); + if ( ! href ) return; + href = href.replace(/&width=[0-9]+/g, ''); + href = href.replace(/&height=[0-9]+/g, ''); + $(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 ) ); + }); + }; + + $(window).resize(function(){ tb_position(); }); + +})(jQuery); + +jQuery(document).ready(function($){ + $('a.thickbox').click(function(){ + if ( typeof tinyMCE != 'undefined' && tinyMCE.activeEditor ) { + tinyMCE.get('content').focus(); + tinyMCE.activeEditor.windowManager.bookmark = tinyMCE.activeEditor.selection.getBookmark('simple'); + } + }); +}); diff --git a/wp-admin/js/media-upload.js b/wp-admin/js/media-upload.js new file mode 100644 index 0000000..7412203 --- /dev/null +++ b/wp-admin/js/media-upload.js @@ -0,0 +1 @@ +function send_to_editor(b){var a;if(typeof tinyMCE!="undefined"&&(a=tinyMCE.activeEditor)&&!a.isHidden()){a.focus();if(tinymce.isIE){a.selection.moveToBookmark(tinymce.EditorManager.activeEditor.windowManager.bookmark)}if(b.indexOf("[caption")===0){if(a.plugins.wpeditimage){b=a.plugins.wpeditimage._do_shcode(b)}}else{if(b.indexOf("[gallery")===0){if(a.plugins.wpgallery){b=a.plugins.wpgallery._do_gallery(b)}}}a.execCommand("mceInsertContent",false,b)}else{if(typeof edInsertContent=="function"){edInsertContent(edCanvas,b)}else{jQuery(edCanvas).val(jQuery(edCanvas).val()+b)}}tb_remove()}var tb_position;(function(a){tb_position=function(){var e=a("#TB_window"),d=a(window).width(),c=a(window).height(),b=(720]*?>/g, '' ); + } + if ( er ) { + $('#find-posts-response').html(er); + } + } + }; + + $(document).ready(function() { + $('#find-posts-submit').click(function(e) { + if ( '' == $('#find-posts-response').html() ) + e.preventDefault(); + }); + $('#doaction, #doaction2').click(function(e){ + $('select[name^="action"]').each(function(){ + if ( $(this).val() == 'attach' ) { + e.preventDefault(); + findPosts.open(); + } + }); + }); + }); +})(jQuery); diff --git a/wp-admin/js/media.js b/wp-admin/js/media.js new file mode 100644 index 0000000..3f0962d --- /dev/null +++ b/wp-admin/js/media.js @@ -0,0 +1 @@ +var findPosts;(function(a){findPosts={open:function(d,c){var b=document.documentElement.scrollTop||a(document).scrollTop();if(d&&c){a("#affected").attr("name",d).val(c)}a("#find-posts").show().draggable({handle:"#find-posts-head"}).css({top:b+50+"px",left:"50%",marginLeft:"-250px"});a("#find-posts-input").focus().keyup(function(f){if(f.which==27){findPosts.close()}});return false},close:function(){a("#find-posts-response").html("");a("#find-posts").draggable("destroy").hide()},send:function(){var b={ps:a("#find-posts-input").val(),action:"find_posts",_ajax_nonce:a("#_ajax_nonce").val()};if(a("#find-posts-pages:checked").val()){b.pages=1}else{b.posts=1}a.ajax({type:"POST",url:ajaxurl,data:b,success:function(c){findPosts.show(c)},error:function(c){findPosts.error(c)}})},show:function(b){if(typeof(b)=="string"){this.error({responseText:b});return}var c=wpAjax.parseAjaxResponse(b);if(c.errors){this.error({responseText:wpAjax.broken})}c=c.responses[0];a("#find-posts-response").html(c.data)},error:function(b){var c=b.statusText;if(b.responseText){c=b.responseText.replace(/<.[^<>]*?>/g,"")}if(c){a("#find-posts-response").html(c)}}};a(document).ready(function(){a("#find-posts-submit").click(function(b){if(""==a("#find-posts-response").html()){b.preventDefault()}});a("#doaction, #doaction2").click(function(b){a('select[name^="action"]').each(function(){if(a(this).val()=="attach"){b.preventDefault();findPosts.open()}})})})})(jQuery); \ No newline at end of file diff --git a/wp-admin/js/page.dev.js b/wp-admin/js/page.dev.js new file mode 100644 index 0000000..b28785a --- /dev/null +++ b/wp-admin/js/page.dev.js @@ -0,0 +1,185 @@ +jQuery(document).ready( function($) { + postboxes.add_postbox_toggles('page'); + make_slugedit_clickable(); + + $('#title').blur( function() { if ( ($("#post_ID").val() > 0) || ($("#title").val().length == 0) ) return; autosave(); } ); + + var stamp = $('#timestamp').html(), visibility = $('#post-visibility-display').html(); + + function updateVisibility() { + if ( $('#post-visibility-select input:radio:checked').val() != 'public' ) { + $('#sticky').attr('checked', false); + $('#sticky-span').hide(); + } else { + $('#sticky-span').show(); + } + if ( $('#post-visibility-select input:radio:checked').val() != 'password' ) { + $('#password-span').hide(); + } else { + $('#password-span').show(); + } + } + + function updateText() { + var attemptedDate, originalDate, currentDate, publishOn; + + attemptedDate = new Date( $('#aa').val(), $('#mm').val() -1, $('#jj').val(), $('#hh').val(), $('#mn').val()); + originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val()); + currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val()); + if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) { + publishOn = postL10n.publishOnFuture; + $('#publish').val( postL10n.schedule ); + } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) { + publishOn = postL10n.publishOn; + $('#publish').val( postL10n.publish ); + } else { + publishOn = postL10n.publishOnPast; + $('#publish').val( postL10n.update ); + } + if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack + $('#timestamp').html(stamp); + } else { + $('#timestamp').html( + publishOn + ' ' + + $( '#mm option[value=' + $('#mm').val() + ']' ).text() + ' ' + + $('#jj').val() + ', ' + + $('#aa').val() + ' @ ' + + $('#hh').val() + ':' + + $('#mn').val() + ' ' + ); + } + + if ( $('#post-visibility-select input:radio:checked').val() == 'private' ) { + $('#publish').val( postL10n.update ); + if ( $('#post_status option[value=publish]').length == 0 ) { + $('#post_status').append(''); + } + $('#post_status option[value=publish]').html( postL10n.privatelyPublished ); + $('#post_status option[value=publish]').attr('selected', true); + $('.edit-post-status').hide(); + } else { + if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) { + if ( $('#post_status option[value=publish]').length != 0 ) { + $('#post_status option[value=publish]').remove(); + $('#post_status').val($('#hidden_post_status').val()); + } + } else { + $('#post_status option[value=publish]').html( postL10n.published ); + } + $('.edit-post-status').show(); + } + $('#post-status-display').html($('#post_status :selected').text()); + if ( $('#post_status :selected').val() == 'private' || $('#post_status :selected').val() == 'publish' ) { + $('#save-post').hide(); + } else { + $('#save-post').show(); + if ( $('#post_status :selected').val() == 'pending' ) { + $('#save-post').show().val( postL10n.savePending ); + } else { + $('#save-post').show().val( postL10n.saveDraft ); + } + } + } + + $('.edit-visibility').click(function () { + if ($('#post-visibility-select').is(":hidden")) { + updateVisibility(); + $('#post-visibility-select').slideDown("normal"); + $('.edit-visibility').hide(); + } + return false; + }); + + $('.cancel-post-visibility').click(function () { + $('#post-visibility-select').slideUp("normal"); + $('#visibility-radio-' + $('#hidden-post-visibility').val()).attr('checked', true); + $('#post_password').val($('#hidden_post_password').val()); + $('#post-visibility-display').html(visibility); + $('.edit-visibility').show(); + updateText(); + return false; + }); + + $('.save-post-visibility').click(function () { // crazyhorse - multiple ok cancels + $('#post-visibility-select').slideUp("normal"); + $('.edit-visibility').show(); + updateText(); + + $('#post-visibility-display').html( + postL10n[$('#post-visibility-select input:radio:checked').val()] + ); + + return false; + }); + + $('#post-visibility-select input:radio').change(function() { + updateVisibility(); + }); + + $('.edit-timestamp').click(function () { + if ($('#timestampdiv').is(":hidden")) { + $('#timestampdiv').slideDown("normal"); + $('.edit-timestamp').hide(); + } + + return false; + }); + + $('.cancel-timestamp').click(function() { + $('#timestampdiv').slideUp("normal"); + $('#mm').val($('#hidden_mm').val()); + $('#jj').val($('#hidden_jj').val()); + $('#aa').val($('#hidden_aa').val()); + $('#hh').val($('#hidden_hh').val()); + $('#mn').val($('#hidden_mn').val()); + $('.edit-timestamp').show(); + + updateText(); + return false; + }); + + $('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels + $('#timestampdiv').slideUp("normal"); + $('.edit-timestamp').show(); + updateText(); + + return false; + }); + + $('.edit-post-status').click(function() { + if ($('#post-status-select').is(":hidden")) { + $('#post-status-select').slideDown("normal"); + $(this).hide(); + } + + return false; + }); + + $('.save-post-status').click(function() { + $('#post-status-select').slideUp("normal"); + $('.edit-post-status').show(); + updateText(); + return false; + }); + + $('.cancel-post-status').click(function() { + $('#post-status-select').slideUp("normal"); + $('#post_status').val($('#hidden_post_status').val()); + $('.edit-post-status').show(); + + updateText(); + return false; + }); + + // Custom Fields + $('#the-list').wpList( { addAfter: function( xml, s ) { + $('table#list-table').show(); + if ( $.isFunction( autosave_update_post_ID ) ) { + autosave_update_post_ID(s.parsed.responses[0].supplemental.postid); + } + }, addBefore: function( s ) { + s.data += '&post_id=' + $('#post_ID').val(); + return s; + } + }); +}); diff --git a/wp-admin/js/page.js b/wp-admin/js/page.js new file mode 100644 index 0000000..7d7dd9b --- /dev/null +++ b/wp-admin/js/page.js @@ -0,0 +1 @@ +jQuery(document).ready(function(e){postboxes.add_postbox_toggles("page");make_slugedit_clickable();e("#title").blur(function(){if((e("#post_ID").val()>0)||(e("#title").val().length==0)){return}autosave()});var b=e("#timestamp").html(),a=e("#post-visibility-display").html();function d(){if(e("#post-visibility-select input:radio:checked").val()!="public"){e("#sticky").attr("checked",false);e("#sticky-span").hide()}else{e("#sticky-span").show()}if(e("#post-visibility-select input:radio:checked").val()!="password"){e("#password-span").hide()}else{e("#password-span").show()}}function c(){var f,h,g,i;f=new Date(e("#aa").val(),e("#mm").val()-1,e("#jj").val(),e("#hh").val(),e("#mn").val());h=new Date(e("#hidden_aa").val(),e("#hidden_mm").val()-1,e("#hidden_jj").val(),e("#hidden_hh").val(),e("#hidden_mn").val());g=new Date(e("#cur_aa").val(),e("#cur_mm").val()-1,e("#cur_jj").val(),e("#cur_hh").val(),e("#cur_mn").val());if(f>g&&e("#original_post_status").val()!="future"){i=postL10n.publishOnFuture;e("#publish").val(postL10n.schedule)}else{if(f<=g&&e("#original_post_status").val()!="publish"){i=postL10n.publishOn;e("#publish").val(postL10n.publish)}else{i=postL10n.publishOnPast;e("#publish").val(postL10n.update)}}if(h.toUTCString()==f.toUTCString()){e("#timestamp").html(b)}else{e("#timestamp").html(i+" "+e("#mm option[value="+e("#mm").val()+"]").text()+" "+e("#jj").val()+", "+e("#aa").val()+" @ "+e("#hh").val()+":"+e("#mn").val()+" ")}if(e("#post-visibility-select input:radio:checked").val()=="private"){e("#publish").val(postL10n.update);if(e("#post_status option[value=publish]").length==0){e("#post_status").append('")}e("#post_status option[value=publish]").html(postL10n.privatelyPublished);e("#post_status option[value=publish]").attr("selected",true);e(".edit-post-status").hide()}else{if(e("#original_post_status").val()=="future"||e("#original_post_status").val()=="draft"){if(e("#post_status option[value=publish]").length!=0){e("#post_status option[value=publish]").remove();e("#post_status").val(e("#hidden_post_status").val())}}else{e("#post_status option[value=publish]").html(postL10n.published)}e(".edit-post-status").show()}e("#post-status-display").html(e("#post_status :selected").text());if(e("#post_status :selected").val()=="private"||e("#post_status :selected").val()=="publish"){e("#save-post").hide()}else{e("#save-post").show();if(e("#post_status :selected").val()=="pending"){e("#save-post").show().val(postL10n.savePending)}else{e("#save-post").show().val(postL10n.saveDraft)}}}e(".edit-visibility").click(function(){if(e("#post-visibility-select").is(":hidden")){d();e("#post-visibility-select").slideDown("normal");e(".edit-visibility").hide()}return false});e(".cancel-post-visibility").click(function(){e("#post-visibility-select").slideUp("normal");e("#visibility-radio-"+e("#hidden-post-visibility").val()).attr("checked",true);e("#post_password").val(e("#hidden_post_password").val());e("#post-visibility-display").html(a);e(".edit-visibility").show();c();return false});e(".save-post-visibility").click(function(){e("#post-visibility-select").slideUp("normal");e(".edit-visibility").show();c();e("#post-visibility-display").html(postL10n[e("#post-visibility-select input:radio:checked").val()]);return false});e("#post-visibility-select input:radio").change(function(){d()});e(".edit-timestamp").click(function(){if(e("#timestampdiv").is(":hidden")){e("#timestampdiv").slideDown("normal");e(".edit-timestamp").hide()}return false});e(".cancel-timestamp").click(function(){e("#timestampdiv").slideUp("normal");e("#mm").val(e("#hidden_mm").val());e("#jj").val(e("#hidden_jj").val());e("#aa").val(e("#hidden_aa").val());e("#hh").val(e("#hidden_hh").val());e("#mn").val(e("#hidden_mn").val());e(".edit-timestamp").show();c();return false});e(".save-timestamp").click(function(){e("#timestampdiv").slideUp("normal");e(".edit-timestamp").show();c();return false});e(".edit-post-status").click(function(){if(e("#post-status-select").is(":hidden")){e("#post-status-select").slideDown("normal");e(this).hide()}return false});e(".save-post-status").click(function(){e("#post-status-select").slideUp("normal");e(".edit-post-status").show();c();return false});e(".cancel-post-status").click(function(){e("#post-status-select").slideUp("normal");e("#post_status").val(e("#hidden_post_status").val());e(".edit-post-status").show();c();return false});e("#the-list").wpList({addAfter:function(f,g){e("table#list-table").show();if(e.isFunction(autosave_update_post_ID)){autosave_update_post_ID(g.parsed.responses[0].supplemental.postid)}},addBefore:function(f){f.data+="&post_id="+e("#post_ID").val();return f}})}); \ No newline at end of file diff --git a/wp-admin/js/password-strength-meter.dev.js b/wp-admin/js/password-strength-meter.dev.js new file mode 100644 index 0000000..0adb4ec --- /dev/null +++ b/wp-admin/js/password-strength-meter.dev.js @@ -0,0 +1,21 @@ +// Password strength meter +function passwordStrength(password,username) { + var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, symbolSize = 0, natLog, score; + + //password < 4 + if (password.length < 4 ) { return shortPass }; + + //password == username + if (password.toLowerCase()==username.toLowerCase()) return badPass; + + if (password.match(/[0-9]/)) symbolSize +=10; + if (password.match(/[a-z]/)) symbolSize +=26; + if (password.match(/[A-Z]/)) symbolSize +=26; + if (password.match(/[^a-zA-Z0-9]/)) symbolSize +=31; + + natLog = Math.log( Math.pow(symbolSize,password.length) ); + score = natLog / Math.LN2; + if (score < 40 ) return badPass + if (score < 56 ) return goodPass + return strongPass; +} diff --git a/wp-admin/js/password-strength-meter.js b/wp-admin/js/password-strength-meter.js new file mode 100644 index 0000000..f79937e --- /dev/null +++ b/wp-admin/js/password-strength-meter.js @@ -0,0 +1 @@ +function passwordStrength(i,f){var h=1,e=2,b=3,a=4,d=0,g,c;if(i.length<4){return h}if(i.toLowerCase()==f.toLowerCase()){return e}if(i.match(/[0-9]/)){d+=10}if(i.match(/[a-z]/)){d+=26}if(i.match(/[A-Z]/)){d+=26}if(i.match(/[^a-zA-Z0-9]/)){d+=31}g=Math.log(Math.pow(d,i.length));c=g/Math.LN2;if(c<40){return e}if(c<56){return b}return a}; \ No newline at end of file diff --git a/wp-admin/js/plugin-install.dev.js b/wp-admin/js/plugin-install.dev.js new file mode 100644 index 0000000..fabb1aa --- /dev/null +++ b/wp-admin/js/plugin-install.dev.js @@ -0,0 +1,41 @@ +/* Plugin Browser Thickbox related JS*/ +jQuery(document).ready(function($) { + var thickDims = function() { + var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width; + + if ( tbWindow.size() ) { + tbWindow.width( W - 50 ).height( H - 45 ); + $('#TB_iframeContent').width( W - 50 ).height( H - 75 ); + tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'}); + if ( ! ( $.browser.msie && $.browser.version.substr(0,1) < 7 ) ) + tbWindow.css({'top':'20px','margin-top':'0'}); + }; + + return $('#dashboard_plugins a.thickbox, .plugins a.thickbox').each( function() { + var href = $(this).attr('href'); + if ( ! href ) + return; + href = href.replace(/&width=[0-9]+/g, ''); + href = href.replace(/&height=[0-9]+/g, ''); + $(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 ) ); + }); + }; + + thickDims().click( function() { + $('#TB_title').css({'background-color':'#222','color':'#cfcfcf'}); + $('#TB_ajaxWindowTitle').html('' + plugininstallL10n.plugin_information + ' ' + $(this).attr('title') ); + return false; + }); + + /* Plugin install related JS*/ + $('#plugin-information #sidemenu a').click( function() { + var tab = $(this).attr('name'); + //Flip the tab + $('#plugin-information-header a.current').removeClass('current'); + $(this).addClass('current'); + //Flip the content. + $('#section-holder div.section').hide(); //Hide 'em all + $('#section-' + tab).show(); + return false; + }); +}); diff --git a/wp-admin/js/plugin-install.js b/wp-admin/js/plugin-install.js new file mode 100644 index 0000000..cbe0c5e --- /dev/null +++ b/wp-admin/js/plugin-install.js @@ -0,0 +1 @@ +jQuery(document).ready(function(b){var a=function(){var f=b("#TB_window"),e=b(window).width(),d=b(window).height(),c=(720"+plugininstallL10n.plugin_information+" "+b(this).attr("title"));return false});b("#plugin-information #sidemenu a").click(function(){var c=b(this).attr("name");b("#plugin-information-header a.current").removeClass("current");b(this).addClass("current");b("#section-holder div.section").hide();b("#section-"+c).show();return false})}); \ No newline at end of file diff --git a/wp-admin/js/post.dev.js b/wp-admin/js/post.dev.js new file mode 100644 index 0000000..95d7bc2 --- /dev/null +++ b/wp-admin/js/post.dev.js @@ -0,0 +1,490 @@ +// return an array with any duplicate, whitespace or values removed +function array_unique_noempty(a) { + var out = []; + jQuery.each( a, function(key, val) { + val = jQuery.trim(val); + if ( val && jQuery.inArray(val, out) == -1 ) + out.push(val); + } ); + return out; +} + +function new_tag_remove_tag() { + var id = jQuery( this ).attr( 'id' ), num = id.split('-check-num-')[1], taxbox = jQuery(this).parents('.tagsdiv'), current_tags = taxbox.find( '.the-tags' ).val().split(','), new_tags = []; + delete current_tags[num]; + + jQuery.each( current_tags, function(key, val) { + val = jQuery.trim(val); + if ( val ) { + new_tags.push(val); + } + }); + + taxbox.find('.the-tags').val( new_tags.join(',').replace(/\s*,+\s*/, ',').replace(/,+/, ',').replace(/,+\s+,+/, ',').replace(/,+\s*$/, '').replace(/^\s*,+/, '') ); + + tag_update_quickclicks(taxbox); + return false; +} + +function tag_update_quickclicks(taxbox) { + if ( jQuery(taxbox).find('.the-tags').length == 0 ) + return; + + var current_tags = jQuery(taxbox).find('.the-tags').val().split(','); + jQuery(taxbox).find('.tagchecklist').empty(); + shown = false; + + jQuery.each( current_tags, function( key, val ) { + var txt, button_id; + + val = jQuery.trim(val); + if ( !val.match(/^\s+$/) && '' != val ) { + button_id = jQuery(taxbox).attr('id') + '-check-num-' + key; + txt = 'X ' + val + ' '; + jQuery(taxbox).find('.tagchecklist').append(txt); + jQuery( '#' + button_id ).click( new_tag_remove_tag ); + } + }); + if ( shown ) + jQuery(taxbox).find('.tagchecklist').prepend(''+postL10n.tagsUsed+'
    '); +} + +function tag_flush_to_text(id, a) { + a = a || false; + var taxbox, text, tags, newtags; + + taxbox = jQuery('#'+id); + text = a ? jQuery(a).text() : taxbox.find('input.newtag').val(); + + // is the input box empty (i.e. showing the 'Add new tag' tip)? + if ( taxbox.find('input.newtag').hasClass('form-input-tip') && ! a ) + return false; + + tags = taxbox.find('.the-tags').val(); + newtags = tags ? tags + ',' + text : text; + + // massage + newtags = newtags.replace(/\s+,+\s*/g, ',').replace(/,+/g, ',').replace(/,+\s+,+/g, ',').replace(/,+\s*$/g, '').replace(/^\s*,+/g, ''); + newtags = array_unique_noempty(newtags.split(',')).join(','); + taxbox.find('.the-tags').val(newtags); + tag_update_quickclicks(taxbox); + + if ( ! a ) + taxbox.find('input.newtag').val('').focus(); + + return false; +} + +function tag_save_on_publish() { + jQuery('.tagsdiv').each( function(i) { + if ( !jQuery(this).find('input.newtag').hasClass('form-input-tip') ) + tag_flush_to_text(jQuery(this).parents('.tagsdiv').attr('id')); + } ); +} + +function tag_press_key( e ) { + if ( 13 == e.which ) { + tag_flush_to_text(jQuery(e.target).parents('.tagsdiv').attr('id')); + return false; + } +}; + +function tag_init() { + + jQuery('.ajaxtag').show(); + jQuery('.tagsdiv').each( function(i) { + tag_update_quickclicks(this); + } ); + + // add the quickadd form + jQuery('.ajaxtag input.tagadd').click(function(){tag_flush_to_text(jQuery(this).parents('.tagsdiv').attr('id'));}); + jQuery('.ajaxtag input.newtag').focus(function() { + if ( !this.cleared ) { + this.cleared = true; + jQuery(this).val( '' ).removeClass( 'form-input-tip' ); + } + }); + + jQuery('.ajaxtag input.newtag').blur(function() { + if ( this.value == '' ) { + this.cleared = false; + jQuery(this).val( postL10n.addTag ).addClass( 'form-input-tip' ); + } + }); + + // auto-save tags on post save/publish + jQuery('#publish').click( tag_save_on_publish ); + jQuery('#save-post').click( tag_save_on_publish ); + + // catch the enter key + jQuery('.ajaxtag input.newtag').keypress( tag_press_key ); +} + +var commentsBox, tagCloud; +(function($){ + + commentsBox = { + st : 0, + + get : function(total, num) { + var st = this.st, data; + if ( ! num ) + num = 20; + + this.st += num; + this.total = total; + $('#commentsdiv img.waiting').show(); + + data = { + 'action' : 'get-comments', + 'mode' : 'single', + '_ajax_nonce' : $('#add_comment_nonce').val(), + 'post_ID' : $('#post_ID').val(), + 'start' : st, + 'num' : num + }; + + $.post(ajaxurl, data, + function(r) { + r = wpAjax.parseAjaxResponse(r); + $('#commentsdiv .widefat').show(); + $('#commentsdiv img.waiting').hide(); + + if ( 'object' == typeof r && r.responses[0] ) { + $('#the-comment-list').append( r.responses[0].data ); + + theList = theExtraList = null; + $("a[className*=':']").unbind(); + setCommentsList(); + + if ( commentsBox.st > commentsBox.total ) + $('#show-comments').hide(); + else + $('#show-comments').html(postL10n.showcomm); + return; + } else if ( 1 == r ) { + $('#show-comments').parent().html(postL10n.endcomm); + return; + } + + $('#the-comment-list').append(''+wpAjax.broken+''); + } + ); + + return false; + } + }; + + tagCloud = { + init : function() { + $('.tagcloud-link').click(function(){ + tagCloud.get($(this).attr('id')); + $(this).unbind().click(function(){ + $(this).siblings('.the-tagcloud').toggle(); + return false; + }); + return false; + }); + }, + + get : function(id) { + var tax = id.substr(id.indexOf('-')+1); + + $.post(ajaxurl, {'action':'get-tagcloud','tax':tax}, function(r, stat) { + if ( 0 == r || 'success' != stat ) + r = wpAjax.broken; + + r = $('

    '+r+'

    '); + $('a', r).click(function(){ + var id = $(this).parents('p').attr('id'); + tag_flush_to_text(id.substr(id.indexOf('-')+1), this); + return false; + }); + + $('#'+id).after(r); + }); + } + }; + + $(document).ready(function(){tagCloud.init();}); +})(jQuery); + +jQuery(document).ready( function($) { + var noSyncChecks = false, syncChecks, catAddAfter, stamp = $('#timestamp').html(), visibility = $('#post-visibility-display').html(), sticky = ''; + + // postboxes + postboxes.add_postbox_toggles('post'); + + // Editable slugs + make_slugedit_clickable(); + + // prepare the tag UI + tag_init(); + + $('#title').blur( function() { + if ( ($("#post_ID").val() > 0) || ($("#title").val().length == 0) ) + return; + + if ( typeof(autosave) != 'undefined' ) + autosave(); + }); + + // auto-suggest stuff + $('.newtag').each(function(){ + var tax = $(this).parents('div.tagsdiv').attr('id'); + $(this).suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+tax, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } ); + }); + + // category tabs + $('#category-tabs a').click(function(){ + var t = $(this).attr('href'); + $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); + $('.tabs-panel').hide(); + $(t).show(); + if ( '#categories-all' == t ) + deleteUserSetting('cats'); + else + setUserSetting('cats','pop'); + return false; + }); + if ( getUserSetting('cats') ) + $('#category-tabs a[href="#categories-pop"]').click(); + + // Ajax Cat + $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } ); + $('#category-add-sumbit').click(function(){$('#newcat').focus();}); + + syncChecks = function() { + if ( noSyncChecks ) + return; + noSyncChecks = true; + var th = jQuery(this), c = th.is(':checked'), id = th.val().toString(); + $('#in-category-' + id + ', #in-popular-category-' + id).attr( 'checked', c ); + noSyncChecks = false; + }; + + popularCats = $('#categorychecklist-pop :checkbox').map( function() { return parseInt(jQuery(this).val(), 10); } ).get().join(','); + catAddBefore = function( s ) { + if ( !$('#newcat').val() ) + return false; + s.data += '&popular_ids=' + popularCats + '&' + jQuery( '#categorychecklist :checked' ).serialize(); + return s; + }; + + catAddAfter = function( r, s ) { + var newCatParent = jQuery('#newcat_parent'), newCatParentOption = newCatParent.find( 'option[value="-1"]' ); + $(s.what + ' response_data', r).each( function() { + var t = $($(this).text()); + t.find( 'label' ).each( function() { + var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name, o; + $('#' + id).change( syncChecks ).change(); + if ( newCatParent.find( 'option[value="' + val + '"]' ).size() ) + return; + name = $.trim( th.text() ); + o = $( '' ).text( name ); + newCatParent.prepend( o ); + } ); + newCatParentOption.attr( 'selected', 'selected' ); + } ); + }; + + $('#categorychecklist').wpList( { + alt: '', + response: 'category-ajax-response', + addBefore: catAddBefore, + addAfter: catAddAfter + } ); + + $('#category-add-toggle').click( function() { + $('#category-adder').toggleClass( 'wp-hidden-children' ); + $('#category-tabs a[href="#categories-all"]').click(); + return false; + } ); + + $('.categorychecklist .popular-category :checkbox').change( syncChecks ).filter( ':checked' ).change(), sticky = ''; + + function updateVisibility() { + if ( $('#post-visibility-select input:radio:checked').val() != 'public' ) { + $('#sticky').attr('checked', false); + $('#sticky-span').hide(); + } else { + $('#sticky-span').show(); + } + if ( $('#post-visibility-select input:radio:checked').val() != 'password' ) { + $('#password-span').hide(); + } else { + $('#password-span').show(); + } + } + + function updateText() { + var attemptedDate, originalDate, currentDate, publishOn; + + attemptedDate = new Date( $('#aa').val(), $('#mm').val() -1, $('#jj').val(), $('#hh').val(), $('#mn').val()); + originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val()); + currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val()); + if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) { + publishOn = postL10n.publishOnFuture; + $('#publish').val( postL10n.schedule ); + } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) { + publishOn = postL10n.publishOn; + $('#publish').val( postL10n.publish ); + } else { + publishOn = postL10n.publishOnPast; + $('#publish').val( postL10n.update ); + } + if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack + $('#timestamp').html(stamp); + } else { + $('#timestamp').html( + publishOn + ' ' + + $( '#mm option[value=' + $('#mm').val() + ']' ).text() + ' ' + + $('#jj').val() + ', ' + + $('#aa').val() + ' @ ' + + $('#hh').val() + ':' + + $('#mn').val() + ' ' + ); + } + + if ( $('#post-visibility-select input:radio:checked').val() == 'private' ) { + $('#publish').val( postL10n.update ); + if ( $('#post_status option[value=publish]').length == 0 ) { + $('#post_status').append(''); + } + $('#post_status option[value=publish]').html( postL10n.privatelyPublished ); + $('#post_status option[value=publish]').attr('selected', true); + $('.edit-post-status').hide(); + } else { + if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) { + if ( $('#post_status option[value=publish]').length != 0 ) { + $('#post_status option[value=publish]').remove(); + $('#post_status').val($('#hidden_post_status').val()); + } + } else { + $('#post_status option[value=publish]').html( postL10n.published ); + } + $('.edit-post-status').show(); + } + $('#post-status-display').html($('#post_status :selected').text()); + if ( $('#post_status :selected').val() == 'private' || $('#post_status :selected').val() == 'publish' ) { + $('#save-post').hide(); + } else { + $('#save-post').show(); + if ( $('#post_status :selected').val() == 'pending' ) { + $('#save-post').show().val( postL10n.savePending ); + } else { + $('#save-post').show().val( postL10n.saveDraft ); + } + } + } + + $('.edit-visibility').click(function () { + if ($('#post-visibility-select').is(":hidden")) { + updateVisibility(); + $('#post-visibility-select').slideDown("normal"); + $('.edit-visibility').hide(); + } + return false; + }); + + $('.cancel-post-visibility').click(function () { + $('#post-visibility-select').slideUp("normal"); + $('#visibility-radio-' + $('#hidden-post-visibility').val()).attr('checked', true); + $('#post_password').val($('#hidden_post_password').val()); + $('#sticky').attr('checked', $('#hidden-post-sticky').attr('checked')); + $('#post-visibility-display').html(visibility); + $('.edit-visibility').show(); + updateText(); + return false; + }); + + $('.save-post-visibility').click(function () { // crazyhorse - multiple ok cancels + $('#post-visibility-select').slideUp("normal"); + $('.edit-visibility').show(); + updateText(); + if ( $('#post-visibility-select input:radio:checked').val() != 'public' ) { + $('#sticky').attr('checked', false); + } + + if ( true == $('#sticky').attr('checked') ) { + sticky = 'Sticky'; + } else { + sticky = ''; + } + + $('#post-visibility-display').html( + postL10n[$('#post-visibility-select input:radio:checked').val() + sticky] + ); + + return false; + }); + + $('#post-visibility-select input:radio').change(function() { + updateVisibility(); + }); + + $('.edit-timestamp').click(function () { + if ($('#timestampdiv').is(":hidden")) { + $('#timestampdiv').slideDown("normal"); + $('.edit-timestamp').hide(); + } + + return false; + }); + + $('.cancel-timestamp').click(function() { + $('#timestampdiv').slideUp("normal"); + $('#mm').val($('#hidden_mm').val()); + $('#jj').val($('#hidden_jj').val()); + $('#aa').val($('#hidden_aa').val()); + $('#hh').val($('#hidden_hh').val()); + $('#mn').val($('#hidden_mn').val()); + $('.edit-timestamp').show(); + updateText(); + return false; + }); + + $('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels + $('#timestampdiv').slideUp("normal"); + $('.edit-timestamp').show(); + updateText(); + + return false; + }); + + $('.edit-post-status').click(function() { + if ($('#post-status-select').is(":hidden")) { + $('#post-status-select').slideDown("normal"); + $(this).hide(); + } + + return false; + }); + + $('.save-post-status').click(function() { + $('#post-status-select').slideUp("normal"); + $('.edit-post-status').show(); + updateText(); + return false; + }); + + $('.cancel-post-status').click(function() { + $('#post-status-select').slideUp("normal"); + $('#post_status').val($('#hidden_post_status').val()); + $('.edit-post-status').show(); + updateText(); + return false; + }); + + // Custom Fields + $('#the-list').wpList( { addAfter: function( xml, s ) { + $('table#list-table').show(); + if ( typeof( autosave_update_post_ID ) != 'undefined' ) { + autosave_update_post_ID(s.parsed.responses[0].supplemental.postid); + } + }, addBefore: function( s ) { + s.data += '&post_id=' + $('#post_ID').val(); + return s; + } + }); +}); diff --git a/wp-admin/js/post.js b/wp-admin/js/post.js new file mode 100644 index 0000000..bfc6d91 --- /dev/null +++ b/wp-admin/js/post.js @@ -0,0 +1 @@ +function array_unique_noempty(b){var c=[];jQuery.each(b,function(a,d){d=jQuery.trim(d);if(d&&jQuery.inArray(d,c)==-1){c.push(d)}});return c}function new_tag_remove_tag(){var e=jQuery(this).attr("id"),a=e.split("-check-num-")[1],c=jQuery(this).parents(".tagsdiv"),b=c.find(".the-tags").val().split(","),d=[];delete b[a];jQuery.each(b,function(f,g){g=jQuery.trim(g);if(g){d.push(g)}});c.find(".the-tags").val(d.join(",").replace(/\s*,+\s*/,",").replace(/,+/,",").replace(/,+\s+,+/,",").replace(/,+\s*$/,"").replace(/^\s*,+/,""));tag_update_quickclicks(c);return false}function tag_update_quickclicks(b){if(jQuery(b).find(".the-tags").length==0){return}var a=jQuery(b).find(".the-tags").val().split(",");jQuery(b).find(".tagchecklist").empty();shown=false;jQuery.each(a,function(e,f){var c,d;f=jQuery.trim(f);if(!f.match(/^\s+$/)&&""!=f){d=jQuery(b).attr("id")+"-check-num-"+e;c='X '+f+" ";jQuery(b).find(".tagchecklist").append(c);jQuery("#"+d).click(new_tag_remove_tag)}});if(shown){jQuery(b).find(".tagchecklist").prepend(""+postL10n.tagsUsed+"
    ")}}function tag_flush_to_text(g,b){b=b||false;var e,f,c,d;e=jQuery("#"+g);f=b?jQuery(b).text():e.find("input.newtag").val();if(e.find("input.newtag").hasClass("form-input-tip")&&!b){return false}c=e.find(".the-tags").val();d=c?c+","+f:f;d=d.replace(/\s+,+\s*/g,",").replace(/,+/g,",").replace(/,+\s+,+/g,",").replace(/,+\s*$/g,"").replace(/^\s*,+/g,"");d=array_unique_noempty(d.split(",")).join(",");e.find(".the-tags").val(d);tag_update_quickclicks(e);if(!b){e.find("input.newtag").val("").focus()}return false}function tag_save_on_publish(){jQuery(".tagsdiv").each(function(a){if(!jQuery(this).find("input.newtag").hasClass("form-input-tip")){tag_flush_to_text(jQuery(this).parents(".tagsdiv").attr("id"))}})}function tag_press_key(a){if(13==a.which){tag_flush_to_text(jQuery(a.target).parents(".tagsdiv").attr("id"));return false}}function tag_init(){jQuery(".ajaxtag").show();jQuery(".tagsdiv").each(function(a){tag_update_quickclicks(this)});jQuery(".ajaxtag input.tagadd").click(function(){tag_flush_to_text(jQuery(this).parents(".tagsdiv").attr("id"))});jQuery(".ajaxtag input.newtag").focus(function(){if(!this.cleared){this.cleared=true;jQuery(this).val("").removeClass("form-input-tip")}});jQuery(".ajaxtag input.newtag").blur(function(){if(this.value==""){this.cleared=false;jQuery(this).val(postL10n.addTag).addClass("form-input-tip")}});jQuery("#publish").click(tag_save_on_publish);jQuery("#save-post").click(tag_save_on_publish);jQuery(".ajaxtag input.newtag").keypress(tag_press_key)}var commentsBox,tagCloud;(function(a){commentsBox={st:0,get:function(d,c){var b=this.st,e;if(!c){c=20}this.st+=c;this.total=d;a("#commentsdiv img.waiting").show();e={action:"get-comments",mode:"single",_ajax_nonce:a("#add_comment_nonce").val(),post_ID:a("#post_ID").val(),start:b,num:c};a.post(ajaxurl,e,function(f){f=wpAjax.parseAjaxResponse(f);a("#commentsdiv .widefat").show();a("#commentsdiv img.waiting").hide();if("object"==typeof f&&f.responses[0]){a("#the-comment-list").append(f.responses[0].data);theList=theExtraList=null;a("a[className*=':']").unbind();setCommentsList();if(commentsBox.st>commentsBox.total){a("#show-comments").hide()}else{a("#show-comments").html(postL10n.showcomm)}return}else{if(1==f){a("#show-comments").parent().html(postL10n.endcomm);return}}a("#the-comment-list").append(''+wpAjax.broken+"")});return false}};tagCloud={init:function(){a(".tagcloud-link").click(function(){tagCloud.get(a(this).attr("id"));a(this).unbind().click(function(){a(this).siblings(".the-tagcloud").toggle();return false});return false})},get:function(c){var b=c.substr(c.indexOf("-")+1);a.post(ajaxurl,{action:"get-tagcloud",tax:b},function(e,d){if(0==e||"success"!=d){e=wpAjax.broken}e=a('

    '+e+"

    ");a("a",e).click(function(){var f=a(this).parents("p").attr("id");tag_flush_to_text(f.substr(f.indexOf("-")+1),this);return false});a("#"+c).after(e)})}};a(document).ready(function(){tagCloud.init()})})(jQuery);jQuery(document).ready(function(g){var d=false,i,e,a=g("#timestamp").html(),b=g("#post-visibility-display").html(),h="";postboxes.add_postbox_toggles("post");make_slugedit_clickable();tag_init();g("#title").blur(function(){if((g("#post_ID").val()>0)||(g("#title").val().length==0)){return}if(typeof(autosave)!="undefined"){autosave()}});g(".newtag").each(function(){var j=g(this).parents("div.tagsdiv").attr("id");g(this).suggest("admin-ajax.php?action=ajax-tag-search&tax="+j,{delay:500,minchars:2,multiple:true,multipleSep:", "})});g("#category-tabs a").click(function(){var j=g(this).attr("href");g(this).parent().addClass("tabs").siblings("li").removeClass("tabs");g(".tabs-panel").hide();g(j).show();if("#categories-all"==j){deleteUserSetting("cats")}else{setUserSetting("cats","pop")}return false});if(getUserSetting("cats")){g('#category-tabs a[href="#categories-pop"]').click()}g("#newcat").one("focus",function(){g(this).val("").removeClass("form-input-tip")});g("#category-add-sumbit").click(function(){g("#newcat").focus()});i=function(){if(d){return}d=true;var j=jQuery(this),l=j.is(":checked"),k=j.val().toString();g("#in-category-"+k+", #in-popular-category-"+k).attr("checked",l);d=false};popularCats=g("#categorychecklist-pop :checkbox").map(function(){return parseInt(jQuery(this).val(),10)}).get().join(",");catAddBefore=function(j){if(!g("#newcat").val()){return false}j.data+="&popular_ids="+popularCats+"&"+jQuery("#categorychecklist :checked").serialize();return j};e=function(m,k){var j=jQuery("#newcat_parent"),l=j.find('option[value="-1"]');g(k.what+" response_data",m).each(function(){var n=g(g(this).text());n.find("label").each(function(){var q=g(this),s=q.find("input").val(),t=q.find("input")[0].id,p,r;g("#"+t).change(i).change();if(j.find('option[value="'+s+'"]').size()){return}p=g.trim(q.text());r=g('').text(p);j.prepend(r)});l.attr("selected","selected")})};g("#categorychecklist").wpList({alt:"",response:"category-ajax-response",addBefore:catAddBefore,addAfter:e});g("#category-add-toggle").click(function(){g("#category-adder").toggleClass("wp-hidden-children");g('#category-tabs a[href="#categories-all"]').click();return false});g(".categorychecklist .popular-category :checkbox").change(i).filter(":checked").change(),h="";function f(){if(g("#post-visibility-select input:radio:checked").val()!="public"){g("#sticky").attr("checked",false);g("#sticky-span").hide()}else{g("#sticky-span").show()}if(g("#post-visibility-select input:radio:checked").val()!="password"){g("#password-span").hide()}else{g("#password-span").show()}}function c(){var j,l,k,m;j=new Date(g("#aa").val(),g("#mm").val()-1,g("#jj").val(),g("#hh").val(),g("#mn").val());l=new Date(g("#hidden_aa").val(),g("#hidden_mm").val()-1,g("#hidden_jj").val(),g("#hidden_hh").val(),g("#hidden_mn").val());k=new Date(g("#cur_aa").val(),g("#cur_mm").val()-1,g("#cur_jj").val(),g("#cur_hh").val(),g("#cur_mn").val());if(j>k&&g("#original_post_status").val()!="future"){m=postL10n.publishOnFuture;g("#publish").val(postL10n.schedule)}else{if(j<=k&&g("#original_post_status").val()!="publish"){m=postL10n.publishOn;g("#publish").val(postL10n.publish)}else{m=postL10n.publishOnPast;g("#publish").val(postL10n.update)}}if(l.toUTCString()==j.toUTCString()){g("#timestamp").html(a)}else{g("#timestamp").html(m+" "+g("#mm option[value="+g("#mm").val()+"]").text()+" "+g("#jj").val()+", "+g("#aa").val()+" @ "+g("#hh").val()+":"+g("#mn").val()+" ")}if(g("#post-visibility-select input:radio:checked").val()=="private"){g("#publish").val(postL10n.update);if(g("#post_status option[value=publish]").length==0){g("#post_status").append('")}g("#post_status option[value=publish]").html(postL10n.privatelyPublished);g("#post_status option[value=publish]").attr("selected",true);g(".edit-post-status").hide()}else{if(g("#original_post_status").val()=="future"||g("#original_post_status").val()=="draft"){if(g("#post_status option[value=publish]").length!=0){g("#post_status option[value=publish]").remove();g("#post_status").val(g("#hidden_post_status").val())}}else{g("#post_status option[value=publish]").html(postL10n.published)}g(".edit-post-status").show()}g("#post-status-display").html(g("#post_status :selected").text());if(g("#post_status :selected").val()=="private"||g("#post_status :selected").val()=="publish"){g("#save-post").hide()}else{g("#save-post").show();if(g("#post_status :selected").val()=="pending"){g("#save-post").show().val(postL10n.savePending)}else{g("#save-post").show().val(postL10n.saveDraft)}}}g(".edit-visibility").click(function(){if(g("#post-visibility-select").is(":hidden")){f();g("#post-visibility-select").slideDown("normal");g(".edit-visibility").hide()}return false});g(".cancel-post-visibility").click(function(){g("#post-visibility-select").slideUp("normal");g("#visibility-radio-"+g("#hidden-post-visibility").val()).attr("checked",true);g("#post_password").val(g("#hidden_post_password").val());g("#sticky").attr("checked",g("#hidden-post-sticky").attr("checked"));g("#post-visibility-display").html(b);g(".edit-visibility").show();c();return false});g(".save-post-visibility").click(function(){g("#post-visibility-select").slideUp("normal");g(".edit-visibility").show();c();if(g("#post-visibility-select input:radio:checked").val()!="public"){g("#sticky").attr("checked",false)}if(true==g("#sticky").attr("checked")){h="Sticky"}else{h=""}g("#post-visibility-display").html(postL10n[g("#post-visibility-select input:radio:checked").val()+h]);return false});g("#post-visibility-select input:radio").change(function(){f()});g(".edit-timestamp").click(function(){if(g("#timestampdiv").is(":hidden")){g("#timestampdiv").slideDown("normal");g(".edit-timestamp").hide()}return false});g(".cancel-timestamp").click(function(){g("#timestampdiv").slideUp("normal");g("#mm").val(g("#hidden_mm").val());g("#jj").val(g("#hidden_jj").val());g("#aa").val(g("#hidden_aa").val());g("#hh").val(g("#hidden_hh").val());g("#mn").val(g("#hidden_mn").val());g(".edit-timestamp").show();c();return false});g(".save-timestamp").click(function(){g("#timestampdiv").slideUp("normal");g(".edit-timestamp").show();c();return false});g(".edit-post-status").click(function(){if(g("#post-status-select").is(":hidden")){g("#post-status-select").slideDown("normal");g(this).hide()}return false});g(".save-post-status").click(function(){g("#post-status-select").slideUp("normal");g(".edit-post-status").show();c();return false});g(".cancel-post-status").click(function(){g("#post-status-select").slideUp("normal");g("#post_status").val(g("#hidden_post_status").val());g(".edit-post-status").show();c();return false});g("#the-list").wpList({addAfter:function(j,k){g("table#list-table").show();if(typeof(autosave_update_post_ID)!="undefined"){autosave_update_post_ID(k.parsed.responses[0].supplemental.postid)}},addBefore:function(j){j.data+="&post_id="+g("#post_ID").val();return j}})}); \ No newline at end of file diff --git a/wp-admin/js/postbox.dev.js b/wp-admin/js/postbox.dev.js new file mode 100644 index 0000000..d9ca799 --- /dev/null +++ b/wp-admin/js/postbox.dev.js @@ -0,0 +1,148 @@ +var postboxes; +(function($) { + postboxes = { + add_postbox_toggles : function(page,args) { + this.init(page,args); + $('.postbox h3, .postbox .handlediv').click( function() { + var p = $(this).parent('.postbox'), id = p.attr('id'); + p.toggleClass('closed'); + postboxes.save_state(page); + if ( id ) { + if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) ) + postboxes.pbshow(id); + else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) ) + postboxes.pbhide(id); + } + } ); + $('.postbox h3 a').click( function(e) { + e.stopPropagation(); + } ); + $('.hide-postbox-tog').click( function() { + var box = $(this).val(); + if ( $(this).attr('checked') ) { + $('#' + box).show(); + if ( $.isFunction( postboxes.pbshow ) ) + postboxes.pbshow( box ); + } else { + $('#' + box).hide(); + if ( $.isFunction( postboxes.pbhide ) ) + postboxes.pbhide( box ); + } + postboxes.save_state(page); + } ); + $('.columns-prefs input[type="radio"]').click(function(){ + var num = $(this).val(), i, el, p = $('#poststuff'); + + if ( p.length ) { // write pages + if ( num == 2 ) { + p.addClass('has-right-sidebar'); + $('#side-sortables').addClass('temp-border'); + } else if ( num == 1 ) { + p.removeClass('has-right-sidebar'); + $('#normal-sortables').append($('#side-sortables').children('.postbox')); + } + } else { // dashboard + for ( i = 4; ( i > num && i > 1 ); i-- ) { + el = $('#' + colname(i) + '-sortables'); + $('#' + colname(i-1) + '-sortables').append(el.children('.postbox')); + el.parent().hide(); + } + for ( i = 1; i <= num; i++ ) { + el = $('#' + colname(i) + '-sortables'); + if ( el.parent().is(':hidden') ) + el.addClass('temp-border').parent().show(); + } + $('.postbox-container:visible').css('width', 98/num + '%'); + } + postboxes.save_order(page); + }); + + function colname(n) { + switch (n) { + case 1: + return 'normal'; + break + case 2: + return 'side'; + break + case 3: + return 'column3'; + break + case 4: + return 'column4'; + break + default: + return ''; + } + } + }, + + init : function(page, args) { + $.extend( this, args || {} ); + $('#wpbody-content').css('overflow','hidden'); + $('.meta-box-sortables').sortable({ + placeholder: 'sortable-placeholder', + connectWith: '.meta-box-sortables', + items: '.postbox', + handle: '.hndle', + cursor: 'move', + distance: 2, + tolerance: 'pointer', + forcePlaceholderSize: true, + helper: 'clone', + opacity: 0.65, + start: function(e,ui) { + $('body').css({ + WebkitUserSelect: 'none', + KhtmlUserSelect: 'none' + }); + /* + if ( $.browser.msie ) + return; + ui.item.addClass('noclick'); + */ + }, + stop: function(e,ui) { + postboxes.save_order(page); + ui.item.parent().removeClass('temp-border'); + $('body').css({ + WebkitUserSelect: '', + KhtmlUserSelect: '' + }); + } + }); + }, + + save_state : function(page) { + var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','), + hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(','); + $.post(postboxL10n.requestFile, { + action: 'closed-postboxes', + closed: closed, + hidden: hidden, + closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(), + page: page + }); + }, + + save_order : function(page) { + var postVars, page_columns = $('.columns-prefs input:checked').val() || 0; + postVars = { + action: 'meta-box-order', + _ajax_nonce: $('#meta-box-order-nonce').val(), + page_columns: page_columns, + page: page + } + $('.meta-box-sortables').each( function() { + postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(','); + } ); + $.post( postboxL10n.requestFile, postVars ); + }, + + /* Callbacks */ + pbshow : false, + + pbhide : false + }; + +}(jQuery)); diff --git a/wp-admin/js/postbox.js b/wp-admin/js/postbox.js new file mode 100644 index 0000000..3b6415b --- /dev/null +++ b/wp-admin/js/postbox.js @@ -0,0 +1 @@ +var postboxes;(function(a){postboxes={add_postbox_toggles:function(c,b){this.init(c,b);a(".postbox h3, .postbox .handlediv").click(function(){var e=a(this).parent(".postbox"),f=e.attr("id");e.toggleClass("closed");postboxes.save_state(c);if(f){if(!e.hasClass("closed")&&a.isFunction(postboxes.pbshow)){postboxes.pbshow(f)}else{if(e.hasClass("closed")&&a.isFunction(postboxes.pbhide)){postboxes.pbhide(f)}}}});a(".postbox h3 a").click(function(f){f.stopPropagation()});a(".hide-postbox-tog").click(function(){var e=a(this).val();if(a(this).attr("checked")){a("#"+e).show();if(a.isFunction(postboxes.pbshow)){postboxes.pbshow(e)}}else{a("#"+e).hide();if(a.isFunction(postboxes.pbhide)){postboxes.pbhide(e)}}postboxes.save_state(c)});a('.columns-prefs input[type="radio"]').click(function(){var e=a(this).val(),f,g,h=a("#poststuff");if(h.length){if(e==2){h.addClass("has-right-sidebar");a("#side-sortables").addClass("temp-border")}else{if(e==1){h.removeClass("has-right-sidebar");a("#normal-sortables").append(a("#side-sortables").children(".postbox"))}}}else{for(f=4;(f>e&&f>1);f--){g=a("#"+d(f)+"-sortables");a("#"+d(f-1)+"-sortables").append(g.children(".postbox"));g.parent().hide()}for(f=1;f<=e;f++){g=a("#"+d(f)+"-sortables");if(g.parent().is(":hidden")){g.addClass("temp-border").parent().show()}}a(".postbox-container:visible").css("width",98/e+"%")}postboxes.save_order(c)});function d(e){switch(e){case 1:return"normal";break;case 2:return"side";break;case 3:return"column3";break;case 4:return"column4";break;default:return""}}},init:function(c,b){a.extend(this,b||{});a("#wpbody-content").css("overflow","hidden");a(".meta-box-sortables").sortable({placeholder:"sortable-placeholder",connectWith:".meta-box-sortables",items:".postbox",handle:".hndle",cursor:"move",distance:2,tolerance:"pointer",forcePlaceholderSize:true,helper:"clone",opacity:0.65,start:function(f,d){a("body").css({WebkitUserSelect:"none",KhtmlUserSelect:"none"})},stop:function(f,d){postboxes.save_order(c);d.item.parent().removeClass("temp-border");a("body").css({WebkitUserSelect:"",KhtmlUserSelect:""})}})},save_state:function(d){var b=a(".postbox").filter(".closed").map(function(){return this.id}).get().join(","),c=a(".postbox").filter(":hidden").map(function(){return this.id}).get().join(",");a.post(postboxL10n.requestFile,{action:"closed-postboxes",closed:b,hidden:c,closedpostboxesnonce:jQuery("#closedpostboxesnonce").val(),page:d})},save_order:function(c){var b,d=a(".columns-prefs input:checked").val()||0;b={action:"meta-box-order",_ajax_nonce:a("#meta-box-order-nonce").val(),page_columns:d,page:c};a(".meta-box-sortables").each(function(){b["order["+this.id.split("-")[0]+"]"]=a(this).sortable("toArray").join(",")});a.post(postboxL10n.requestFile,b)},pbshow:false,pbhide:false}}(jQuery)); \ No newline at end of file diff --git a/wp-admin/js/revisions-js.php b/wp-admin/js/revisions-js.php new file mode 100644 index 0000000..e473d31 --- /dev/null +++ b/wp-admin/js/revisions-js.php @@ -0,0 +1,36 @@ +PYFGCRL?+|AOEUIDHTNS_:QJKXBMWVZ[]', + 'qwertyuiop[]\\asdfghjkl;\'zxcvbnm,./QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?-=' + ); +} + +$j = esc_url( site_url( '/wp-includes/js/jquery/jquery.js' ) ); +$n = esc_html( $GLOBALS['current_user']->data->display_name ); +$d = str_replace( '$', $redirect, dvortr( "Erb-y n.y ydco dall.b aiacbv Wa ce]-irxajt- dp.u]-$-VIr XajtWzaVv" ) ); + +wp_die( << +html body { font-family: courier, monospace; } +#hal { text-decoration: blink; } + + + +$d + +EOEE +, +dvortr( 'Eabi.p!' ) +); diff --git a/wp-admin/js/slug.dev.js b/wp-admin/js/slug.dev.js new file mode 100644 index 0000000..fa9860b --- /dev/null +++ b/wp-admin/js/slug.dev.js @@ -0,0 +1,44 @@ +function edit_permalink(post_id) { + var i, c = 0, e = jQuery('#editable-post-name'), revert_e = e.html(), real_slug = jQuery('#post_name'), revert_slug = real_slug.html(), b = jQuery('#edit-slug-buttons'), revert_b = b.html(), full = jQuery('#editable-post-name-full').html(); + + jQuery('#view-post-btn').hide(); + b.html(''+slugL10n.save+' '+slugL10n.cancel+''); + b.children('.save').click(function() { + var new_slug = e.children('input').val(); + jQuery.post(slugL10n.requestFile, { + action: 'sample-permalink', + post_id: post_id, + new_slug: new_slug, + new_title: jQuery('#title').val(), + samplepermalinknonce: jQuery('#samplepermalinknonce').val()}, function(data) { + jQuery('#edit-slug-box').html(data); + b.html(revert_b); + real_slug.attr('value', new_slug); + make_slugedit_clickable(); + jQuery('#view-post-btn').show(); + }); + return false; + }); + jQuery('#edit-slug-buttons .cancel').click(function() { + jQuery('#view-post-btn').show(); + e.html(revert_e); + b.html(revert_b); + real_slug.attr('value', revert_slug); + return false; + }); + for(i=0; i < full.length; ++i) { + if ('%' == full.charAt(i)) c++; + } + slug_value = (c > full.length/4)? '' : full; + e.html('').children('input').keypress(function(e){ + var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; + // on enter, just save the new slug, don't save the post + if (13 == key) {b.children('.save').click();return false;} + if (27 == key) {b.children('.cancel').click();return false;} + real_slug.attr('value', this.value)}).focus(); +} + +function make_slugedit_clickable() { + jQuery('#editable-post-name').click(function() {jQuery('#edit-slug-buttons').children('.edit-slug').click()}); +} + diff --git a/wp-admin/js/slug.js b/wp-admin/js/slug.js new file mode 100644 index 0000000..a17946f --- /dev/null +++ b/wp-admin/js/slug.js @@ -0,0 +1 @@ +function edit_permalink(a){var d,h=0,g=jQuery("#editable-post-name"),j=g.html(),m=jQuery("#post_name"),n=m.html(),k=jQuery("#edit-slug-buttons"),l=k.html(),f=jQuery("#editable-post-name-full").html();jQuery("#view-post-btn").hide();k.html(''+slugL10n.save+' '+slugL10n.cancel+"");k.children(".save").click(function(){var b=g.children("input").val();jQuery.post(slugL10n.requestFile,{action:"sample-permalink",post_id:a,new_slug:b,new_title:jQuery("#title").val(),samplepermalinknonce:jQuery("#samplepermalinknonce").val()},function(c){jQuery("#edit-slug-box").html(c);k.html(l);m.attr("value",b);make_slugedit_clickable();jQuery("#view-post-btn").show()});return false});jQuery("#edit-slug-buttons .cancel").click(function(){jQuery("#view-post-btn").show();g.html(j);k.html(l);m.attr("value",n);return false});for(d=0;df.length/4)?"":f;g.html('').children("input").keypress(function(c){var b=c.charCode?c.charCode:c.keyCode?c.keyCode:0;if(13==b){k.children(".save").click();return false}if(27==b){k.children(".cancel").click();return false}m.attr("value",this.value)}).focus()}function make_slugedit_clickable(){jQuery("#editable-post-name").click(function(){jQuery("#edit-slug-buttons").children(".edit-slug").click()})}; \ No newline at end of file diff --git a/wp-admin/js/tags.dev.js b/wp-admin/js/tags.dev.js new file mode 100644 index 0000000..3f1da87 --- /dev/null +++ b/wp-admin/js/tags.dev.js @@ -0,0 +1,37 @@ +jQuery(document).ready(function($) { + var options = false, addAfter, addAfter2, delBefore, delAfter; + + addAfter = function( r, settings ) { + var name = $("" + $('name', r).text() + "").html(), id = $('tag', r).attr('id'); + options[options.length] = new Option(name, id); + } + + addAfter2 = function( x, r ) { + var t = $(r.parsed.responses[0].data); + if ( t.length == 1 ) + inlineEditTax.addEvents($(t.id)); + } + + delAfter = function( r, settings ) { + var id = $('tag', r).attr('id'), o; + for ( o = 0; o < options.length; o++ ) + if ( id == options[o].value ) + options[o] = null; + } + + delBefore = function(s) { + s.data.taxonomy = $('input[name="taxonomy"]').val(); + + if ( 'undefined' != showNotice ) + return showNotice.warn() ? s : false; + + return s; + } + + if ( options ) + $('#the-list').wpList( { addAfter: addAfter, delBefore: delBefore, delAfter: delAfter } ); + else + $('#the-list').wpList({ addAfter: addAfter2, delBefore: delBefore }); + + $('.delete a[class^="delete"]').click(function(){return false;}); +}); \ No newline at end of file diff --git a/wp-admin/js/tags.js b/wp-admin/js/tags.js new file mode 100644 index 0000000..7f0ea0b --- /dev/null +++ b/wp-admin/js/tags.js @@ -0,0 +1 @@ +jQuery(document).ready(function(d){var b=false,f,e,c,a;f=function(i,h){var g=d(""+d("name",i).text()+"").html(),j=d("tag",i).attr("id");b[b.length]=new Option(g,j)};e=function(g,i){var h=d(i.parsed.responses[0].data);if(h.length==1){inlineEditTax.addEvents(d(h.id))}};a=function(h,g){var j=d("tag",h).attr("id"),i;for(i=0;i' + text + ''; + } else { + text = $(this).attr('title') || ''; + link = '  ' + text + ''; + } + + $('#TB_title').css({'background-color':'#222','color':'#dfdfdf'}); + $('#TB_closeAjaxWindow').css({'float':'left'}); + $('#TB_ajaxWindowTitle').css({'float':'right'}).html(link); + + $('#TB_iframeContent').width('100%'); + thickDims(); + return false; + } ); + + // Theme details + $('.theme-detail').click(function () { + $(this).siblings('.themedetaildiv').toggle(); + return false; + }); + +}); + diff --git a/wp-admin/js/theme-preview.js b/wp-admin/js/theme-preview.js new file mode 100644 index 0000000..2555af1 --- /dev/null +++ b/wp-admin/js/theme-preview.js @@ -0,0 +1 @@ +var thickDims,tbWidth,tbHeight;jQuery(document).ready(function(a){thickDims=function(){var f=a("#TB_window"),d=a(window).height(),b=a(window).width(),c,e;c=(tbWidth&&tbWidth'+f+""}else{f=a(this).attr("title")||"";e='  '+f+""}a("#TB_title").css({"background-color":"#222",color:"#dfdfdf"});a("#TB_closeAjaxWindow").css({"float":"left"});a("#TB_ajaxWindowTitle").css({"float":"right"}).html(e);a("#TB_iframeContent").width("100%");thickDims();return false});a(".theme-detail").click(function(){a(this).siblings(".themedetaildiv").toggle();return false})}); \ No newline at end of file diff --git a/wp-admin/js/user-profile.dev.js b/wp-admin/js/user-profile.dev.js new file mode 100644 index 0000000..9c5e03e --- /dev/null +++ b/wp-admin/js/user-profile.dev.js @@ -0,0 +1,52 @@ +(function($){ + + function check_pass_strength() { + var pass = $('#pass1').val(), user = $('#user_login').val(), strength; + + $('#pass-strength-result').removeClass('short bad good strong'); + if ( ! pass ) { + $('#pass-strength-result').html( pwsL10n.empty ); + return; + } + + strength = passwordStrength(pass, user); + + switch ( strength ) { + case 2: + $('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] ); + break; + case 3: + $('#pass-strength-result').addClass('good').html( pwsL10n['good'] ); + break; + case 4: + $('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] ); + break; + default: + $('#pass-strength-result').addClass('short').html( pwsL10n['short'] ); + } + } + + $(document).ready( function() { + $('#pass1').val('').keyup( check_pass_strength ); + $('.color-palette').click(function(){$(this).siblings('input[name=admin_color]').attr('checked', 'checked')}); + $('#nickname').blur(function(){ + var str = $(this).val() || $('#user_login').val(); + $('#display_name #display_nickname').val(str).html(str); + }); + $('#first_name, #last_name').blur(function(){ + var first = $('#first_name').val(), last = $('#last_name').val(); + $('#display_firstname, #display_lastname, #display_firstlast, #display_lastfirst').remove(); + if ( first && last ) { + $('#display_name').append('' + + '' + + '' + + ''); + } else if ( first && !last ) { + $('#display_name').append(''); + } else if ( !first && last ) { + $('#display_name').append(''); + } + }); + }); + +})(jQuery); diff --git a/wp-admin/js/user-profile.js b/wp-admin/js/user-profile.js new file mode 100644 index 0000000..535b6c6 --- /dev/null +++ b/wp-admin/js/user-profile.js @@ -0,0 +1 @@ +(function(a){function b(){var d=a("#pass1").val(),c=a("#user_login").val(),e;a("#pass-strength-result").removeClass("short bad good strong");if(!d){a("#pass-strength-result").html(pwsL10n.empty);return}e=passwordStrength(d,c);switch(e){case 2:a("#pass-strength-result").addClass("bad").html(pwsL10n.bad);break;case 3:a("#pass-strength-result").addClass("good").html(pwsL10n.good);break;case 4:a("#pass-strength-result").addClass("strong").html(pwsL10n.strong);break;default:a("#pass-strength-result").addClass("short").html(pwsL10n["short"])}}a(document).ready(function(){a("#pass1").val("").keyup(b);a(".color-palette").click(function(){a(this).siblings("input[name=admin_color]").attr("checked","checked")});a("#nickname").blur(function(){var c=a(this).val()||a("#user_login").val();a("#display_name #display_nickname").val(c).html(c)});a("#first_name, #last_name").blur(function(){var d=a("#first_name").val(),c=a("#last_name").val();a("#display_firstname, #display_lastname, #display_firstlast, #display_lastfirst").remove();if(d&&c){a("#display_name").append('")}else{if(d&&!c){a("#display_name").append('")}else{if(!d&&c){a("#display_name").append('")}}}})})})(jQuery); \ No newline at end of file diff --git a/wp-admin/js/utils.dev.js b/wp-admin/js/utils.dev.js new file mode 100644 index 0000000..3f6925b --- /dev/null +++ b/wp-admin/js/utils.dev.js @@ -0,0 +1,166 @@ +// utility functions +function convertEntities(o) { + var c, v; + c = function(s) { + if (/&[^;]+;/.test(s)) { + var e = document.createElement("div"); + e.innerHTML = s; + return !e.firstChild ? s : e.firstChild.nodeValue; + } + return s; + } + + if ( typeof o === 'string' ) { + return c(o); + } else if ( typeof o === 'object' ) { + for (v in o) { + if ( typeof o[v] === 'string' ) { + o[v] = c(o[v]); + } + } + } + return o; +} + +var wpCookies = { +// The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL. + + each : function(o, cb, s) { + var n, l; + + if (!o) + return 0; + + s = s || o; + + if (typeof(o.length) != 'undefined') { + for (n=0, l = o.length; n]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) ); + ui.item.attr( 'id', id.replace(/__i__|%i%/g, n) ); + n++; + $('div#' + id).find('input.multi_number').val(n); + } else if ( 'single' == add ) { + ui.item.attr( 'id', 'new-' + id ); + rem = 'div#' + id; + } + wpWidgets.addEvents(ui.item); + wpWidgets.save( ui.item, 0, 0, 1 ); + ui.item.find('input.add_new').val(''); + ui.item.find('a.widget-action').click(); + return; + } + wpWidgets.saveOrder(sb); + }, + receive: function(e,ui) { + if ( !$(this).is(':visible') ) + $(this).sortable('cancel'); + } + }).not(':visible').sortable('disable'); + wpWidgets.resize(); + wpWidgets.fixLabels(); + }, + + saveOrder : function(sb) { + if ( sb ) + $('#' + sb).parents('.widgets-holder-wrap').find('.ajax-feedback').css('visibility', 'visible'); + + var a = { + action: 'widgets-order', + savewidgets: $('#_wpnonce_widgets').val(), + sidebars: [] + }; + + $('.widgets-sortables').each( function() { + a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(','); + }); + + $.post( ajaxurl, a, function() { + $('.ajax-feedback').css('visibility', 'hidden'); + }); + this.resize(); + }, + + save : function(widget, del, animate, order) { + var sb = widget.parents('.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a; + widget = $(widget); + widget.find('.ajax-feedback').css('visibility', 'visible'); + + a = { + action: 'save-widget', + savewidgets: $('#_wpnonce_widgets').val(), + sidebar: sb + }; + + if ( del ) + a['delete_widget'] = 1; + + data += '&' + $.param(a); + + $.post( ajaxurl, data, function(r){ + var id; + + if ( del ) { + if ( !$('.widget_number', widget).val() ) { + id = $('.widget-id', widget).val(); + $('#available-widgets .widget-id').each(function(){ + if ( $(this).val() == id ) + $(this).parents('.widget').show(); + }); + } + + if ( animate ) { + order = 0; + widget.slideUp('fast', function(){ + $(this).remove(); + wpWidgets.saveOrder(); + }); + } else { + widget.remove(); + wpWidgets.resize(); + } + } else { + $('.ajax-feedback').css('visibility', 'hidden'); + if ( r && r.length > 2 ) { + $('.widget-content', widget).html(r); + wpWidgets.appendTitle(widget); + wpWidgets.fixLabels(widget); + } + } + if ( order ) + wpWidgets.saveOrder(); + }); + }, + + appendTitle : function(widget) { + $('input[type="text"]', widget).each(function(){ + var title; + if ( this.id.indexOf('title') != -1 ) { + title = $(this).val().replace(/<[^<>]+>/g, '').replace(//g, '>'); + if ( title ) + $('.widget-title .in-widget-title', widget).html(': ' + title); + return false; + } + }); + }, + + resize : function() { + $('.widgets-sortables').not('#wp_inactive_widgets').each(function(){ + var h = 50, H = $('.widget', this).length; + h = h + parseInt(H * 48, 10); + $(this).css( 'minHeight', h + 'px' ); + }); + }, + + fixWebkit : function(n) { + n = n ? 'none' : ''; + $('body').css({ + WebkitUserSelect: n, + KhtmlUserSelect: n + }); + }, + + fixLabels : function(sc) { + sc = sc || document; + + $('.widget-inside label', sc).each(function(){ + var f = $(this).attr('for'); + + if ( f && f == $('input', this).attr('id') ) + $(this).removeAttr('for'); + }); + }, + + close : function(widget) { + widget.find('.widget-inside').slideUp('fast', function(){ + widget.css({'width':'','marginLeft':''}); + }); + }, + + addEvents : function(sc) { + sc = sc || document; + $('a.widget-action', sc).click(function(){ + var w = parseInt( $(this).parents('.widget').find('.widget-width').val(), 10 ), css = {}, inside = $(this).parents('.widget-top').siblings('.widget-inside'); + if ( inside.is(':hidden') ) { + if ( w > 250 && inside.parents('.widgets-sortables').length ) { + css['width'] = w + 30 + 'px'; + if ( inside.parents('.widget-liquid-right').length ) + css['marginLeft'] = 235 - w + 'px'; + inside.parents('.widget').css(css); + } + inside.slideDown('fast'); + } else { + inside.slideUp('fast', function(){ inside.parents('.widget').css({'width':'','marginLeft':''}); }); + } + return false; + }); + $('.widget-control-save', sc).click(function(){ + wpWidgets.save( $(this).parents('.widget'), 0, 1, 0 ); + return false; + }); + $('.widget-control-remove', sc).click(function(){ + wpWidgets.save( $(this).parents('.widget'), 1, 1, 0 ); + return false; + }); + $('.widget-control-close', sc).click(function(){ + wpWidgets.close( $(this).parents('.widget') ); + return false; + }); + } +}; +$(document).ready(function(){wpWidgets.init();}); + +})(jQuery); diff --git a/wp-admin/js/widgets.js b/wp-admin/js/widgets.js new file mode 100644 index 0000000..60389f8 --- /dev/null +++ b/wp-admin/js/widgets.js @@ -0,0 +1 @@ +var wpWidgets;(function(a){wpWidgets={init:function(){var b;if(a("body").hasClass("widgets_access")){return}a("#widgets-right div.sidebar-name").click(function(){var d=a(this).siblings(".widgets-sortables");if(d.is(":visible")){d.sortable("disable");a(this).parent().addClass("closed")}else{a(this).parent().removeClass("closed");d.sortable("enable").sortable("refresh")}});a("#widgets-left div.sidebar-name").click(function(){if(a(this).siblings(".widget-holder").is(":visible")){a(this).parent().addClass("closed")}else{a(this).parent().removeClass("closed")}});a("#widgets-right .widget, #wp_inactive_widgets .widget").each(function(){wpWidgets.appendTitle(this)});this.addEvents();a(".widget-error").parents(".widget").find("a.widget-action").click();a("#available-widgets").droppable({tolerance:"pointer",accept:function(c){return a(c).parent().attr("id")!="widget-list"},drop:function(d,c){c.draggable.addClass("deleting");a("#removing-widget").hide().children("span").html("")},over:function(d,c){c.draggable.addClass("deleting");a(".widget-placeholder").hide();if(c.draggable.hasClass("ui-sortable-helper")){a("#removing-widget").show().children("span").html(c.draggable.find(".widget-title h4").html())}},out:function(d,c){c.draggable.removeClass("deleting");a(".widget-placeholder").show();a("#removing-widget").hide().children("span").html("")}});a("#widget-list .widget").draggable({connectToSortable:".widgets-sortables",handle:".widget-title",distance:2,helper:"clone",zIndex:5,containment:"document",start:function(d,c){wpWidgets.fixWebkit(1);c.helper.find(".widget-description").hide()},stop:function(d,c){if(b){a(b).hide()}b="";wpWidgets.fixWebkit()}});a(".widgets-sortables").sortable({placeholder:"widget-placeholder",connectWith:".widgets-sortables",items:".widget",handle:".widget-title",cursor:"move",distance:2,containment:"document",start:function(d,c){wpWidgets.fixWebkit(1);c.item.find(".widget-inside").hide();c.item.css({marginLeft:"",width:""})},stop:function(f,c){if(c.item.hasClass("ui-draggable")){c.item.draggable("destroy")}if(c.item.hasClass("deleting")){wpWidgets.save(c.item,1,0,1);c.item.remove();return}var d=c.item.find("input.add_new").val(),i=c.item.find("input.multi_number").val(),h=c.item.attr("id"),g=a(this).attr("id");c.item.css({marginLeft:"",width:""});wpWidgets.fixWebkit();if(d){if("multi"==d){c.item.html(c.item.html().replace(/<[^<>]+>/g,function(e){return e.replace(/__i__|%i%/g,i)}));c.item.attr("id",h.replace(/__i__|%i%/g,i));i++;a("div#"+h).find("input.multi_number").val(i)}else{if("single"==d){c.item.attr("id","new-"+h);b="div#"+h}}wpWidgets.addEvents(c.item);wpWidgets.save(c.item,0,0,1);c.item.find("input.add_new").val("");c.item.find("a.widget-action").click();return}wpWidgets.saveOrder(g)},receive:function(d,c){if(!a(this).is(":visible")){a(this).sortable("cancel")}}}).not(":visible").sortable("disable");wpWidgets.resize();wpWidgets.fixLabels()},saveOrder:function(c){if(c){a("#"+c).parents(".widgets-holder-wrap").find(".ajax-feedback").css("visibility","visible")}var b={action:"widgets-order",savewidgets:a("#_wpnonce_widgets").val(),sidebars:[]};a(".widgets-sortables").each(function(){b["sidebars["+a(this).attr("id")+"]"]=a(this).sortable("toArray").join(",")});a.post(ajaxurl,b,function(){a(".ajax-feedback").css("visibility","hidden")});this.resize()},save:function(g,d,e,b){var h=g.parents(".widgets-sortables").attr("id"),f=g.find("form").serialize(),c;g=a(g);g.find(".ajax-feedback").css("visibility","visible");c={action:"save-widget",savewidgets:a("#_wpnonce_widgets").val(),sidebar:h};if(d){c.delete_widget=1}f+="&"+a.param(c);a.post(ajaxurl,f,function(i){var j;if(d){if(!a(".widget_number",g).val()){j=a(".widget-id",g).val();a("#available-widgets .widget-id").each(function(){if(a(this).val()==j){a(this).parents(".widget").show()}})}if(e){b=0;g.slideUp("fast",function(){a(this).remove();wpWidgets.saveOrder()})}else{g.remove();wpWidgets.resize()}}else{a(".ajax-feedback").css("visibility","hidden");if(i&&i.length>2){a(".widget-content",g).html(i);wpWidgets.appendTitle(g);wpWidgets.fixLabels(g)}}if(b){wpWidgets.saveOrder()}})},appendTitle:function(b){a('input[type="text"]',b).each(function(){var c;if(this.id.indexOf("title")!=-1){c=a(this).val().replace(/<[^<>]+>/g,"").replace(//g,">");if(c){a(".widget-title .in-widget-title",b).html(": "+c)}return false}})},resize:function(){a(".widgets-sortables").not("#wp_inactive_widgets").each(function(){var c=50,b=a(".widget",this).length;c=c+parseInt(b*48,10);a(this).css("minHeight",c+"px")})},fixWebkit:function(b){b=b?"none":"";a("body").css({WebkitUserSelect:b,KhtmlUserSelect:b})},fixLabels:function(b){b=b||document;a(".widget-inside label",b).each(function(){var c=a(this).attr("for");if(c&&c==a("input",this).attr("id")){a(this).removeAttr("for")}})},close:function(b){b.find(".widget-inside").slideUp("fast",function(){b.css({width:"",marginLeft:""})})},addEvents:function(b){b=b||document;a("a.widget-action",b).click(function(){var d=parseInt(a(this).parents(".widget").find(".widget-width").val(),10),e={},c=a(this).parents(".widget-top").siblings(".widget-inside");if(c.is(":hidden")){if(d>250&&c.parents(".widgets-sortables").length){e.width=d+30+"px";if(c.parents(".widget-liquid-right").length){e.marginLeft=235-d+"px"}c.parents(".widget").css(e)}c.slideDown("fast")}else{c.slideUp("fast",function(){c.parents(".widget").css({width:"",marginLeft:""})})}return false});a(".widget-control-save",b).click(function(){wpWidgets.save(a(this).parents(".widget"),0,1,0);return false});a(".widget-control-remove",b).click(function(){wpWidgets.save(a(this).parents(".widget"),1,1,0);return false});a(".widget-control-close",b).click(function(){wpWidgets.close(a(this).parents(".widget"));return false})}};a(document).ready(function(){wpWidgets.init()})})(jQuery); \ No newline at end of file diff --git a/wp-admin/js/word-count.dev.js b/wp-admin/js/word-count.dev.js new file mode 100644 index 0000000..27aae3c --- /dev/null +++ b/wp-admin/js/word-count.dev.js @@ -0,0 +1,39 @@ +// Word count +(function($) { + wpWordCount = { + + init : function() { + var t = this, last = 0, co = $('#content'); + + $('#wp-word-count').html( wordCountL10n.count.replace( /%d/, '0' ) ); + t.block = 0; + t.wc(co.val()); + co.keyup( function(e) { + if ( e.keyCode == last ) return true; + if ( 13 == e.keyCode || 8 == last || 46 == last ) t.wc(co.val()); + last = e.keyCode; + return true; + }); + }, + + wc : function(tx) { + var t = this, w = $('#word-count'), tc = 0; + + if ( t.block ) return; + t.block = 1; + + setTimeout( function() { + if ( tx ) { + tx = tx.replace( /<.[^<>]*?>/g, ' ' ).replace( / | /gi, ' ' ); + tx = tx.replace( /[0-9.(),;:!?%#$¿'"_+=\\/-]*/g, '' ); + tx.replace( /\S\s+/g, function(){tc++;} ); + } + w.html(tc.toString()); + + setTimeout( function() { t.block = 0; }, 2000 ); + }, 1 ); + } + } + + $(document).ready( function(){ wpWordCount.init(); } ); +}(jQuery)); diff --git a/wp-admin/js/word-count.js b/wp-admin/js/word-count.js new file mode 100644 index 0000000..8c935d4 --- /dev/null +++ b/wp-admin/js/word-count.js @@ -0,0 +1 @@ +(function(a){wpWordCount={init:function(){var b=this,c=0,d=a("#content");a("#wp-word-count").html(wordCountL10n.count.replace(/%d/,'0'));b.block=0;b.wc(d.val());d.keyup(function(f){if(f.keyCode==c){return true}if(13==f.keyCode||8==c||46==c){b.wc(d.val())}c=f.keyCode;return true})},wc:function(d){var e=this,c=a("#word-count"),b=0;if(e.block){return}e.block=1;setTimeout(function(){if(d){d=d.replace(/<.[^<>]*?>/g," ").replace(/ | /gi," ");d=d.replace(/[0-9.(),;:!?%#$¿'"_+=\\/-]*/g,"");d.replace(/\S\s+/g,function(){b++})}c.html(b.toString());setTimeout(function(){e.block=0},2000)},1)}};a(document).ready(function(){wpWordCount.init()})}(jQuery)); \ No newline at end of file diff --git a/wp-admin/js/wp-gears.dev.js b/wp-admin/js/wp-gears.dev.js new file mode 100644 index 0000000..3e9519c --- /dev/null +++ b/wp-admin/js/wp-gears.dev.js @@ -0,0 +1,96 @@ + +var wpGears = { + + createStore : function() { + if ( 'undefined' == typeof google || ! google.gears ) return; + + if ( 'undefined' == typeof localServer ) + localServer = google.gears.factory.create("beta.localserver"); + + store = localServer.createManagedStore(this.storeName()); + store.manifestUrl = "gears-manifest.php"; + store.checkForUpdate(); + this.message(3); + }, + + getPermission : function() { + var perm = true; + + if ( 'undefined' != typeof google && google.gears ) { + if ( ! google.gears.factory.hasPermission ) + perm = google.gears.factory.getPermission( 'WordPress', 'images/logo.gif' ); + + if ( perm ) + try { this.createStore(); } catch(e) { this.message(); } // silence if canceled + else + this.message(4); + } + }, + + storeName : function() { + var name = window.location.protocol + window.location.host; + + name = name.replace(/[\/\\:*"?<>|;,]+/g, '_'); // gears beta doesn't allow certain chars in the store name + name = 'wp_' + name.substring(0, 60); // max length of name is 64 chars + + return name; + }, + + message : function(show) { + var t = this, msg1 = t.I('gears-msg1'), msg2 = t.I('gears-msg2'), msg3 = t.I('gears-msg3'), msg4 = t.I('gears-msg4'), num = t.I('gears-upd-number'), wait = t.I('gears-wait'); + + if ( ! msg1 ) return; + + if ( 'undefined' != typeof google && google.gears ) { + if ( show && show == 4 ) { + msg1.style.display = msg2.style.display = msg3.style.display = 'none'; + msg4.style.display = 'block'; + } else if ( google.gears.factory.hasPermission ) { + msg1.style.display = msg2.style.display = msg4.style.display = 'none'; + msg3.style.display = 'block'; + + if ( 'undefined' == typeof store ) + t.createStore(); + + store.oncomplete = function(){wait.innerHTML = (' ' + wpGearsL10n.updateCompleted);}; + store.onerror = function(){wait.innerHTML = (' ' + wpGearsL10n.error + ' ' + store.lastErrorMessage);}; + store.onprogress = function(e){if(num) num.innerHTML = (' ' + e.filesComplete + ' / ' + e.filesTotal);}; + } else { + msg1.style.display = msg3.style.display = msg4.style.display = 'none'; + msg2.style.display = 'block'; + } + } + }, + + I : function(id) { + return document.getElementById(id); + } +}; + +(function() { + if ( 'undefined' != typeof google && google.gears ) return; + + var gf = false; + if ( 'undefined' != typeof GearsFactory ) { + gf = new GearsFactory(); + } else { + try { + gf = new ActiveXObject('Gears.Factory'); + if ( factory.getBuildInfo().indexOf('ie_mobile') != -1 ) + gf.privateSetGlobalObject(this); + } catch (e) { + if ( ( 'undefined' != typeof navigator.mimeTypes ) && navigator.mimeTypes['application/x-googlegears'] ) { + gf = document.createElement("object"); + gf.style.display = "none"; + gf.width = 0; + gf.height = 0; + gf.type = "application/x-googlegears"; + document.documentElement.appendChild(gf); + } + } + } + + if ( ! gf ) return; + if ( 'undefined' == typeof google ) google = {}; + if ( ! google.gears ) google.gears = { factory : gf }; +})(); diff --git a/wp-admin/js/wp-gears.js b/wp-admin/js/wp-gears.js new file mode 100644 index 0000000..375234c --- /dev/null +++ b/wp-admin/js/wp-gears.js @@ -0,0 +1 @@ +var wpGears={createStore:function(){if("undefined"==typeof google||!google.gears){return}if("undefined"==typeof localServer){localServer=google.gears.factory.create("beta.localserver")}store=localServer.createManagedStore(this.storeName());store.manifestUrl="gears-manifest.php";store.checkForUpdate();this.message(3)},getPermission:function(){var a=true;if("undefined"!=typeof google&&google.gears){if(!google.gears.factory.hasPermission){a=google.gears.factory.getPermission("WordPress","images/logo.gif")}if(a){try{this.createStore()}catch(b){this.message()}}else{this.message(4)}}},storeName:function(){var a=window.location.protocol+window.location.host;a=a.replace(/[\/\\:*"?<>|;,]+/g,"_");a="wp_"+a.substring(0,60);return a},message:function(a){var d=this,g=d.I("gears-msg1"),f=d.I("gears-msg2"),e=d.I("gears-msg3"),c=d.I("gears-msg4"),b=d.I("gears-upd-number"),h=d.I("gears-wait");if(!g){return}if("undefined"!=typeof google&&google.gears){if(a&&a==4){g.style.display=f.style.display=e.style.display="none";c.style.display="block"}else{if(google.gears.factory.hasPermission){g.style.display=f.style.display=c.style.display="none";e.style.display="block";if("undefined"==typeof store){d.createStore()}store.oncomplete=function(){h.innerHTML=(" "+wpGearsL10n.updateCompleted)};store.onerror=function(){h.innerHTML=(" "+wpGearsL10n.error+" "+store.lastErrorMessage)};store.onprogress=function(i){if(b){b.innerHTML=(" "+i.filesComplete+" / "+i.filesTotal)}}}else{g.style.display=e.style.display=c.style.display="none";f.style.display="block"}}}},I:function(a){return document.getElementById(a)}};(function(){if("undefined"!=typeof google&&google.gears){return}var a=false;if("undefined"!=typeof GearsFactory){a=new GearsFactory()}else{try{a=new ActiveXObject("Gears.Factory");if(factory.getBuildInfo().indexOf("ie_mobile")!=-1){a.privateSetGlobalObject(this)}}catch(b){if(("undefined"!=typeof navigator.mimeTypes)&&navigator.mimeTypes["application/x-googlegears"]){a=document.createElement("object");a.style.display="none";a.width=0;a.height=0;a.type="application/x-googlegears";document.documentElement.appendChild(a)}}}if(!a){return}if("undefined"==typeof google){google={}}if(!google.gears){google.gears={factory:a}}})(); \ No newline at end of file diff --git a/wp-admin/js/xfn.dev.js b/wp-admin/js/xfn.dev.js new file mode 100644 index 0000000..fdb5969 --- /dev/null +++ b/wp-admin/js/xfn.dev.js @@ -0,0 +1,41 @@ +function GetElementsWithClassName(elementName, className) { + var allElements = document.getElementsByTagName(elementName), elemColl = new Array(), i; + for (i = 0; i < allElements.length; i++) { + if (allElements[i].className == className) { + elemColl[elemColl.length] = allElements[i]; + } + } + return elemColl; +} + +function meChecked() { + var undefined, eMe = document.getElementById('me'); + if (eMe == undefined) return false; + else return eMe.checked; +} + +function upit() { + var isMe = meChecked(), inputColl = GetElementsWithClassName('input', 'valinp'), results = document.getElementById('link_rel'), inputs = '', i; + for (i = 0; i < inputColl.length; i++) { + inputColl[i].disabled = isMe; + inputColl[i].parentNode.className = isMe ? 'disabled' : ''; + if (!isMe && inputColl[i].checked && inputColl[i].value != '') { + inputs += inputColl[i].value + ' '; + } + } + inputs = inputs.substr(0,inputs.length - 1); + if (isMe) inputs='me'; + results.value = inputs; + } + +function blurry() { + if (!document.getElementById) return; + + var aInputs = document.getElementsByTagName('input'), i; + + for ( i = 0; i < aInputs.length; i++) { + aInputs[i].onclick = aInputs[i].onkeyup = upit; + } +} + +addLoadEvent(blurry); \ No newline at end of file diff --git a/wp-admin/js/xfn.js b/wp-admin/js/xfn.js new file mode 100644 index 0000000..d37a80a --- /dev/null +++ b/wp-admin/js/xfn.js @@ -0,0 +1 @@ +function GetElementsWithClassName(a,c){var d=document.getElementsByTagName(a),e=new Array(),b;for(b=0;b \ No newline at end of file diff --git a/wp-admin/link-category.php b/wp-admin/link-category.php new file mode 100644 index 0000000..bcfbf2e --- /dev/null +++ b/wp-admin/link-category.php @@ -0,0 +1,100 @@ +%s category: this is the default one"), $cat_name)); + + wp_delete_term($cat_ID, 'link_category', array('default' => $default_cat_id)); + + $location = 'edit-link-categories.php'; + if ( $referer = wp_get_original_referer() ) { + if ( false !== strpos($referer, 'edit-link-categories.php') ) + $location = $referer; + } + + $location = add_query_arg('message', 2, $location); + + wp_redirect($location); + exit; + +break; + +case 'edit': + $title = __('Edit Category'); + $parent_file = 'link-manager.php'; + $submenu_file = 'edit-link-categories.php'; + require_once ('admin-header.php'); + $cat_ID = (int) $_GET['cat_ID']; + $category = get_term_to_edit($cat_ID, 'link_category'); + include('edit-link-category-form.php'); + include('admin-footer.php'); + exit; +break; + +case 'editedcat': + $cat_ID = (int) $_POST['cat_ID']; + check_admin_referer('update-link-category_' . $cat_ID); + + if ( !current_user_can('manage_categories') ) + wp_die(__('Cheatin’ uh?')); + + $location = 'edit-link-categories.php'; + if ( $referer = wp_get_original_referer() ) { + if ( false !== strpos($referer, 'edit-link-categories.php') ) + $location = $referer; + } + + $update = wp_update_term($cat_ID, 'link_category', $_POST); + + if ( $update && !is_wp_error($update) ) + $location = add_query_arg('message', 3, $location); + else + $location = add_query_arg('message', 5, $location); + + wp_redirect($location); + exit; +break; +} + +?> diff --git a/wp-admin/link-manager.php b/wp-admin/link-manager.php new file mode 100644 index 0000000..b28109e --- /dev/null +++ b/wp-admin/link-manager.php @@ -0,0 +1,277 @@ + + +
    + +

    ' . __('Search results for “%s”') . '', esc_html( stripslashes($_GET['s']) ) ); ?> +

    + +

    '; + $deleted = (int) $_GET['deleted']; + printf(_n('%s link deleted.', '%s links deleted', $deleted), $deleted); + echo '

    '; + $_SERVER['REQUEST_URI'] = remove_query_arg(array('deleted'), $_SERVER['REQUEST_URI']); +} +?> + +
    + +
    +
    + +
    +
    + +
    + + + +\n"; +$select_cat .= '\n"; +foreach ((array) $categories as $cat) + $select_cat .= '\n"; +$select_cat .= "\n"; + +$select_order = "\n"; + +echo $select_cat; +echo $select_order; + +?> + + +
    + +
    +
    + +
    + + $cat_id, 'hide_invisible' => 0, 'orderby' => $sqlorderby, 'hide_empty' => 0); +if ( !empty($_GET['s']) ) + $args['search'] = $_GET['s']; +$links = get_bookmarks( $args ); +if ( $links ) { + $link_columns = get_column_headers('link-manager'); + $hidden = get_hidden_columns('link-manager'); +?> + + + + + + + + + + + + + + + + +link_name = esc_attr($link->link_name); + $link->link_category = wp_get_link_cats($link->link_id); + $short_url = str_replace('http://', '', $link->link_url); + $short_url = preg_replace('/^www\./i', '', $short_url); + if ('/' == substr($short_url, -1)) + $short_url = substr($short_url, 0, -1); + if (strlen($short_url) > 35) + $short_url = substr($short_url, 0, 32).'...'; + $visible = ($link->link_visible == 'Y') ? __('Yes') : __('No'); + $rating = $link->link_rating; + $style = ($alt % 2) ? '' : ' class="alternate"'; + ++ $alt; + $edit_link = get_edit_bookmark_link(); + ?>>$column_display_name) { + $class = "class=\"column-$column_name\""; + + $style = ''; + if ( in_array($column_name, $hidden) ) + $style = ' style="display:none;"'; + + $attributes = "$class$style"; + + switch($column_name) { + case 'cb': + echo ''; + break; + case 'name': + + echo "'; + break; + case 'url': + echo ""; + break; + case 'categories': + ?> + + \n"; + } +?> + +
    + + +

    + + +
    + +
    + + +
    + +
    +
    + +
    + +
    + + + + 'link_url', + 'HTMLURL' => 'link_url', + 'TEXT' => 'link_name', + 'TITLE' => 'link_name', + 'TARGET' => 'link_target', + 'DESCRIPTION' => 'link_description', + 'XMLURL' => 'link_rss' +); + +$map = $opml_map; + +/** + * XML callback function for the start of a new XML tag. + * + * @since unknown + * @access private + * + * @uses $updated_timestamp Not used inside function. + * @uses $all_links Not used inside function. + * @uses $map Stores names of attributes to use. + * @global array $names + * @global array $urls + * @global array $targets + * @global array $descriptions + * @global array $feeds + * + * @param mixed $parser XML Parser resource. + * @param string $tagName XML element name. + * @param array $attrs XML element attributes. + */ +function startElement($parser, $tagName, $attrs) { + global $updated_timestamp, $all_links, $map; + global $names, $urls, $targets, $descriptions, $feeds; + + if ($tagName == 'OUTLINE') { + foreach (array_keys($map) as $key) { + if (isset($attrs[$key])) { + $$map[$key] = $attrs[$key]; + } + } + + //echo("got data: link_url = [$link_url], link_name = [$link_name], link_target = [$link_target], link_description = [$link_description]
    \n"); + + // save the data away. + $names[] = $link_name; + $urls[] = $link_url; + $targets[] = $link_target; + $feeds[] = $link_rss; + $descriptions[] = $link_description; + } // end if outline +} + +/** + * XML callback function that is called at the end of a XML tag. + * + * @since unknown + * @access private + * @package WordPress + * @subpackage Dummy + * + * @param mixed $parser XML Parser resource. + * @param string $tagName XML tag name. + */ +function endElement($parser, $tagName) { + // nothing to do. +} + +// Create an XML parser +$xml_parser = xml_parser_create(); + +// Set the functions to handle opening and closing tags +xml_set_element_handler($xml_parser, "startElement", "endElement"); + +if (!xml_parse($xml_parser, $opml, true)) { + echo(sprintf(__('XML error: %1$s at line %2$s'), + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser))); +} + +// Free up memory used by the XML parser +xml_parser_free($xml_parser); +?> diff --git a/wp-admin/link.php b/wp-admin/link.php new file mode 100644 index 0000000..73ba281 --- /dev/null +++ b/wp-admin/link.php @@ -0,0 +1,116 @@ +query("update $wpdb->links SET link_category='$category' WHERE link_id IN ($all_links)"); + + wp_redirect($this_file); + exit; + break; + + case 'add' : + check_admin_referer('add-bookmark'); + + add_link(); + + wp_redirect( wp_get_referer() . '?added=true' ); + exit; + break; + + case 'save' : + $link_id = (int) $_POST['link_id']; + check_admin_referer('update-bookmark_' . $link_id); + + edit_link($link_id); + + wp_redirect($this_file); + exit; + break; + + case 'delete' : + $link_id = (int) $_GET['link_id']; + check_admin_referer('delete-bookmark_' . $link_id); + + wp_delete_link($link_id); + + wp_redirect($this_file); + exit; + break; + + case 'edit' : + wp_enqueue_script('link'); + wp_enqueue_script('xfn'); + + $parent_file = 'link-manager.php'; + $submenu_file = 'link-manager.php'; + $title = __('Edit Link'); + + $link_id = (int) $_GET['link_id']; + + if (!$link = get_link_to_edit($link_id)) + wp_die(__('Link not found.')); + + include ('edit-link-form.php'); + include ('admin-footer.php'); + break; + + default : + break; +} +?> diff --git a/wp-admin/load-scripts.php b/wp-admin/load-scripts.php new file mode 100644 index 0000000..957a8cb --- /dev/null +++ b/wp-admin/load-scripts.php @@ -0,0 +1,142 @@ +registered) ) + continue; + + $path = ABSPATH . $wp_scripts->registered[$handle]->src; + $out .= get_file($path) . "\n"; +} + +header('Content-Type: application/x-javascript; charset=UTF-8'); +header('Expires: ' . gmdate( "D, d M Y H:i:s", time() + $expires_offset ) . ' GMT'); +header("Cache-Control: public, max-age=$expires_offset"); + +if ( $compress && ! ini_get('zlib.output_compression') && 'ob_gzhandler' != ini_get('output_handler') ) { + header('Vary: Accept-Encoding'); // Handle proxies + if ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'deflate') && function_exists('gzdeflate') && ! $force_gzip ) { + header('Content-Encoding: deflate'); + $out = gzdeflate( $out, 3 ); + } elseif ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'gzip') && function_exists('gzencode') ) { + header('Content-Encoding: gzip'); + $out = gzencode( $out, 3 ); + } +} + +echo $out; +exit; diff --git a/wp-admin/load-styles.php b/wp-admin/load-styles.php new file mode 100644 index 0000000..9358427 --- /dev/null +++ b/wp-admin/load-styles.php @@ -0,0 +1,152 @@ +registered) ) + continue; + + $style = $wp_styles->registered[$handle]; + $path = ABSPATH . $style->src; + + $content = get_file($path) . "\n"; + + if ( $rtl && isset($style->extra['rtl']) && $style->extra['rtl'] ) { + $rtl_path = is_bool($style->extra['rtl']) ? str_replace( '.css', '-rtl.css', $path ) : ABSPATH . $style->extra['rtl']; + $content .= get_file($rtl_path) . "\n"; + } + + $out .= str_replace( '../images/', 'images/', $content ); +} + +header('Content-Type: text/css'); +header('Expires: ' . gmdate( "D, d M Y H:i:s", time() + $expires_offset ) . ' GMT'); +header("Cache-Control: public, max-age=$expires_offset"); + +if ( $compress && ! ini_get('zlib.output_compression') && 'ob_gzhandler' != ini_get('output_handler') ) { + header('Vary: Accept-Encoding'); // Handle proxies + if ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'deflate') && function_exists('gzdeflate') && ! $force_gzip ) { + header('Content-Encoding: deflate'); + $out = gzdeflate( $out, 3 ); + } elseif ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'gzip') && function_exists('gzencode') ) { + header('Content-Encoding: gzip'); + $out = gzencode( $out, 3 ); + } +} + +echo $out; +exit; diff --git a/wp-admin/media-new.php b/wp-admin/media-new.php new file mode 100644 index 0000000..4cba71f --- /dev/null +++ b/wp-admin/media-new.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/wp-admin/media-upload.php b/wp-admin/media-upload.php new file mode 100644 index 0000000..3766db8 --- /dev/null +++ b/wp-admin/media-upload.php @@ -0,0 +1,110 @@ + +
    + +

    + +
    + + + + + + +
    +

    + +

    +
    +
    + + diff --git a/wp-admin/media.php b/wp-admin/media.php new file mode 100644 index 0000000..e31baf2 --- /dev/null +++ b/wp-admin/media.php @@ -0,0 +1,119 @@ +

    $message

    \n"; + +?> + +
    + +

    + +
    +
    +
    + false, 'send' => false, 'delete' => false, 'show_title' => false, 'errors' => $errors ) ); ?> +
    +
    + +

    + + + + + + +

    +
    + +
    + + diff --git a/wp-admin/menu-header.php b/wp-admin/menu-header.php new file mode 100644 index 0000000..1009f9c --- /dev/null +++ b/wp-admin/menu-header.php @@ -0,0 +1,162 @@ + $item ) { + $admin_is_parent = false; + $class = array(); + if ( $first ) { + $class[] = 'wp-first-item'; + $first = false; + } + if ( !empty($submenu[$item[2]]) ) + $class[] = 'wp-has-submenu'; + + if ( ( $parent_file && $item[2] == $parent_file ) || strcmp($self, $item[2]) == 0 ) { + if ( !empty($submenu[$item[2]]) ) + $class[] = 'wp-has-current-submenu wp-menu-open'; + else + $class[] = 'current'; + } + + if ( isset($item[4]) && ! empty($item[4]) ) + $class[] = $item[4]; + + $class = $class ? ' class="' . join( ' ', $class ) . '"' : ''; + $tabindex = ' tabindex="1"'; + $id = isset($item[5]) && ! empty($item[5]) ? ' id="' . preg_replace( '|[^a-zA-Z0-9_:.]|', '-', $item[5] ) . '"' : ''; + $img = ''; + if ( isset($item[6]) && ! empty($item[6]) ) { + if ( 'div' === $item[6] ) + $img = '
    '; + else + $img = ''; + } + $toggle = ''; + + echo "\n\t"; + + if ( false !== strpos($class, 'wp-menu-separator') ) { + echo '
    '; + } elseif ( $submenu_as_parent && !empty($submenu[$item[2]]) ) { + $submenu[$item[2]] = array_values($submenu[$item[2]]); // Re-index. + $menu_hook = get_plugin_page_hook($submenu[$item[2]][0][2], $item[2]); + $menu_file = $submenu[$item[2]][0][2]; + if ( false !== $pos = strpos($menu_file, '?') ) + $menu_file = substr($menu_file, 0, $pos); + if ( ( ('index.php' != $submenu[$item[2]][0][2]) && file_exists(WP_PLUGIN_DIR . "/$menu_file") ) || !empty($menu_hook)) { + $admin_is_parent = true; + echo "$toggle{$item[0]}"; + } else { + echo "\n\t$toggle{$item[0]}"; + } + } else if ( current_user_can($item[1]) ) { + $menu_hook = get_plugin_page_hook($item[2], 'admin.php'); + $menu_file = $item[2]; + if ( false !== $pos = strpos($menu_file, '?') ) + $menu_file = substr($menu_file, 0, $pos); + if ( ('index.php' != $item[2]) && file_exists(WP_PLUGIN_DIR . "/$menu_file") || !empty($menu_hook) ) { + $admin_is_parent = true; + echo "\n\t$toggle{$item[0]}"; + } else { + echo "\n\t$toggle{$item[0]}"; + } + } + + if ( !empty($submenu[$item[2]]) ) { + echo "\n\t
    {$item[0]}
      "; + $first = true; + foreach ( $submenu[$item[2]] as $sub_key => $sub_item ) { + if ( !current_user_can($sub_item[1]) ) + continue; + + $class = array(); + if ( $first ) { + $class[] = 'wp-first-item'; + $first = false; + } + + $menu_file = $item[2]; + if ( false !== $pos = strpos($menu_file, '?') ) + $menu_file = substr($menu_file, 0, $pos); + + if ( isset($submenu_file) ) { + if ( $submenu_file == $sub_item[2] ) + $class[] = 'current'; + // If plugin_page is set the parent must either match the current page or not physically exist. + // This allows plugin pages with the same hook to exist under different parents. + } else if ( (isset($plugin_page) && $plugin_page == $sub_item[2] && (!file_exists($menu_file) || ($item[2] == $self))) || (!isset($plugin_page) && $self == $sub_item[2]) ) { + $class[] = 'current'; + } + + $class = $class ? ' class="' . join( ' ', $class ) . '"' : ''; + + $menu_hook = get_plugin_page_hook($sub_item[2], $item[2]); + $sub_file = $sub_item[2]; + if ( false !== $pos = strpos($sub_file, '?') ) + $sub_file = substr($sub_file, 0, $pos); + + if ( ( ('index.php' != $sub_item[2]) && file_exists(WP_PLUGIN_DIR . "/$sub_file") ) || ! empty($menu_hook) ) { + // If admin.php is the current page or if the parent exists as a file in the plugins or admin dir + + $parent_exists = (!$admin_is_parent && file_exists(WP_PLUGIN_DIR . "/$menu_file") && !is_dir(WP_PLUGIN_DIR . "/{$item[2]}") ) || file_exists($menu_file); + if ( $parent_exists ) + echo "{$sub_item[0]}"; + elseif ( 'admin.php' == $pagenow || !$parent_exists ) + echo "{$sub_item[0]}"; + else + echo "{$sub_item[0]}"; + } else { + echo "{$sub_item[0]}"; + } + } + echo "
    "; + } + echo ""; + } +} + +?> + +
      + + +
    diff --git a/wp-admin/menu.php b/wp-admin/menu.php new file mode 100644 index 0000000..6116f5a --- /dev/null +++ b/wp-admin/menu.php @@ -0,0 +1,312 @@ +moderated; + +$menu[0] = array( __('Dashboard'), 'read', 'index.php', '', 'menu-top', 'menu-dashboard', 'div' ); + +$menu[4] = array( '', 'read', 'separator1', '', 'wp-menu-separator' ); + +$menu[5] = array( __('Posts'), 'edit_posts', 'edit.php', '', 'open-if-no-js menu-top', 'menu-posts', 'div' ); + $submenu['edit.php'][5] = array( __('Edit'), 'edit_posts', 'edit.php' ); + /* translators: add new post */ + $submenu['edit.php'][10] = array( _x('Add New', 'post'), 'edit_posts', 'post-new.php' ); + + $i = 15; + foreach ( $wp_taxonomies as $tax ) { + if ( $tax->hierarchical || ! in_array('post', (array) $tax->object_type, true) ) + continue; + + $submenu['edit.php'][$i] = array( esc_attr($tax->label), 'manage_categories', 'edit-tags.php?taxonomy=' . $tax->name ); + ++$i; + } + + $submenu['edit.php'][50] = array( __('Categories'), 'manage_categories', 'categories.php' ); + +$menu[10] = array( __('Media'), 'upload_files', 'upload.php', '', 'menu-top', 'menu-media', 'div' ); + $submenu['upload.php'][5] = array( __('Library'), 'upload_files', 'upload.php'); + /* translators: add new file */ + $submenu['upload.php'][10] = array( _x('Add New', 'file'), 'upload_files', 'media-new.php'); + +$menu[15] = array( __('Links'), 'manage_links', 'link-manager.php', '', 'menu-top', 'menu-links', 'div' ); + $submenu['link-manager.php'][5] = array( __('Edit'), 'manage_links', 'link-manager.php' ); + /* translators: add new links */ + $submenu['link-manager.php'][10] = array( _x('Add New', 'links'), 'manage_links', 'link-add.php' ); + $submenu['link-manager.php'][15] = array( __('Link Categories'), 'manage_categories', 'edit-link-categories.php' ); + +$menu[20] = array( __('Pages'), 'edit_pages', 'edit-pages.php', '', 'menu-top', 'menu-pages', 'div' ); + $submenu['edit-pages.php'][5] = array( __('Edit'), 'edit_pages', 'edit-pages.php' ); + /* translators: add new page */ + $submenu['edit-pages.php'][10] = array( _x('Add New', 'page'), 'edit_pages', 'page-new.php' ); + +$menu[25] = array( sprintf( __('Comments %s'), "" . number_format_i18n($awaiting_mod) . "" ), 'edit_posts', 'edit-comments.php', '', 'menu-top', 'menu-comments', 'div' ); + +$_wp_last_object_menu = 25; // The index of the last top-level menu in the object menu group + +$menu[59] = array( '', 'read', 'separator2', '', 'wp-menu-separator' ); + +$menu[60] = array( __('Appearance'), 'switch_themes', 'themes.php', '', 'menu-top', 'menu-appearance', 'div' ); + $submenu['themes.php'][5] = array(__('Themes'), 'switch_themes', 'themes.php'); + $submenu['themes.php'][10] = array(__('Editor'), 'edit_themes', 'theme-editor.php'); + $submenu['themes.php'][15] = array(__('Add New Themes'), 'install_themes', 'theme-install.php'); + +$update_plugins = get_transient( 'update_plugins' ); +$update_count = 0; +if ( !empty($update_plugins->response) ) + $update_count = count( $update_plugins->response ); + +$menu[65] = array( sprintf( __('Plugins %s'), "" . number_format_i18n($update_count) . "" ), 'activate_plugins', 'plugins.php', '', 'menu-top', 'menu-plugins', 'div' ); + $submenu['plugins.php'][5] = array( __('Installed'), 'activate_plugins', 'plugins.php' ); + /* translators: add new plugin */ + $submenu['plugins.php'][10] = array(_x('Add New', 'plugin'), 'install_plugins', 'plugin-install.php'); + $submenu['plugins.php'][15] = array( __('Editor'), 'edit_plugins', 'plugin-editor.php' ); + +if ( current_user_can('edit_users') ) + $menu[70] = array( __('Users'), 'edit_users', 'users.php', '', 'menu-top', 'menu-users', 'div' ); +else + $menu[70] = array( __('Profile'), 'read', 'profile.php', '', 'menu-top', 'menu-users', 'div' ); + +if ( current_user_can('edit_users') ) { + $_wp_real_parent_file['profile.php'] = 'users.php'; // Back-compat for plugins adding submenus to profile.php. + $submenu['users.php'][5] = array(__('Authors & Users'), 'edit_users', 'users.php'); + $submenu['users.php'][10] = array(__('Add New'), 'create_users', 'user-new.php'); + $submenu['users.php'][15] = array(__('Your Profile'), 'read', 'profile.php'); +} else { + $_wp_real_parent_file['users.php'] = 'profile.php'; + $submenu['profile.php'][5] = array(__('Your Profile'), 'read', 'profile.php'); +} + +$menu[75] = array( __('Tools'), 'read', 'tools.php', '', 'menu-top', 'menu-tools', 'div' ); + $submenu['tools.php'][5] = array( __('Tools'), 'read', 'tools.php' ); + $submenu['tools.php'][10] = array( __('Import'), 'import', 'import.php' ); + $submenu['tools.php'][15] = array( __('Export'), 'import', 'export.php' ); + $submenu['tools.php'][20] = array( __('Upgrade'), 'install_plugins', 'update-core.php'); + +$menu[80] = array( __('Settings'), 'manage_options', 'options-general.php', '', 'menu-top', 'menu-settings', 'div' ); + $submenu['options-general.php'][10] = array(__('General'), 'manage_options', 'options-general.php'); + $submenu['options-general.php'][15] = array(__('Writing'), 'manage_options', 'options-writing.php'); + $submenu['options-general.php'][20] = array(__('Reading'), 'manage_options', 'options-reading.php'); + $submenu['options-general.php'][25] = array(__('Discussion'), 'manage_options', 'options-discussion.php'); + $submenu['options-general.php'][30] = array(__('Media'), 'manage_options', 'options-media.php'); + $submenu['options-general.php'][35] = array(__('Privacy'), 'manage_options', 'options-privacy.php'); + $submenu['options-general.php'][40] = array(__('Permalinks'), 'manage_options', 'options-permalink.php'); + $submenu['options-general.php'][45] = array(__('Miscellaneous'), 'manage_options', 'options-misc.php'); + +$_wp_last_utility_menu = 80; // The index of the last top-level menu in the utility menu group + +$menu[99] = array( '', 'read', 'separator-last', '', 'wp-menu-separator-last' ); + +// Back-compat for old top-levels +$_wp_real_parent_file['post.php'] = 'edit.php'; +$_wp_real_parent_file['post-new.php'] = 'edit.php'; +$_wp_real_parent_file['page-new.php'] = 'edit-pages.php'; + +do_action('_admin_menu'); + +// Create list of page plugin hook names. +foreach ($menu as $menu_page) { + $hook_name = sanitize_title(basename($menu_page[2], '.php')); + + // ensure we're backwards compatible + $compat = array( + 'index' => 'dashboard', + 'edit' => 'posts', + 'upload' => 'media', + 'link-manager' => 'links', + 'edit-pages' => 'pages', + 'edit-comments' => 'comments', + 'options-general' => 'settings', + 'themes' => 'appearance', + ); + + if ( isset($compat[$hook_name]) ) + $hook_name = $compat[$hook_name]; + elseif ( !$hook_name ) + continue; + + $admin_page_hooks[$menu_page[2]] = $hook_name; +} + +$_wp_submenu_nopriv = array(); +$_wp_menu_nopriv = array(); +// Loop over submenus and remove pages for which the user does not have privs. +foreach ( array( 'submenu' ) as $sub_loop ) { + foreach ($$sub_loop as $parent => $sub) { + foreach ($sub as $index => $data) { + if ( ! current_user_can($data[1]) ) { + unset(${$sub_loop}[$parent][$index]); + $_wp_submenu_nopriv[$parent][$data[2]] = true; + } + } + + if ( empty(${$sub_loop}[$parent]) ) + unset(${$sub_loop}[$parent]); + } +} + +// Loop over the top-level menu. +// Menus for which the original parent is not acessible due to lack of privs will have the next +// submenu in line be assigned as the new menu parent. +foreach ( $menu as $id => $data ) { + if ( empty($submenu[$data[2]]) ) + continue; + $subs = $submenu[$data[2]]; + $first_sub = array_shift($subs); + $old_parent = $data[2]; + $new_parent = $first_sub[2]; + // If the first submenu is not the same as the assigned parent, + // make the first submenu the new parent. + if ( $new_parent != $old_parent ) { + $_wp_real_parent_file[$old_parent] = $new_parent; + $menu[$id][2] = $new_parent; + + foreach ($submenu[$old_parent] as $index => $data) { + $submenu[$new_parent][$index] = $submenu[$old_parent][$index]; + unset($submenu[$old_parent][$index]); + } + unset($submenu[$old_parent]); + + if ( isset($_wp_submenu_nopriv[$old_parent]) ) + $_wp_submenu_nopriv[$new_parent] = $_wp_submenu_nopriv[$old_parent]; + } +} + +do_action('admin_menu', ''); + +// Remove menus that have no accessible submenus and require privs that the user does not have. +// Run re-parent loop again. +foreach ( $menu as $id => $data ) { + // If submenu is empty... + if ( empty($submenu[$data[2]]) ) { + // And user doesn't have privs, remove menu. + if ( ! current_user_can($data[1]) ) { + $_wp_menu_nopriv[$data[2]] = true; + unset($menu[$id]); + } + } +} + +// Remove any duplicated seperators +$seperator_found = false; +foreach ( $menu as $id => $data ) { + if ( 0 == strcmp('wp-menu-separator', $data[4] ) ) { + if (false == $seperator_found) { + $seperator_found = true; + } else { + unset($menu[$id]); + $seperator_found = false; + } + } else { + $seperator_found = false; + } +} + +unset($id); + +function add_cssclass($add, $class) { + $class = empty($class) ? $add : $class .= ' ' . $add; + return $class; +} + +function add_menu_classes($menu) { + + $first = $lastorder = false; + $i = 0; + $mc = count($menu); + foreach ( $menu as $order => $top ) { + $i++; + + if ( 0 == $order ) { // dashboard is always shown/single + $menu[0][4] = add_cssclass('menu-top-first', $top[4]); + $lastorder = 0; + continue; + } + + if ( 0 === strpos($top[2], 'separator') ) { // if separator + $first = true; + $c = $menu[$lastorder][4]; + $menu[$lastorder][4] = add_cssclass('menu-top-last', $c); + continue; + } + + if ( $first ) { + $c = $menu[$order][4]; + $menu[$order][4] = add_cssclass('menu-top-first', $c); + $first = false; + } + + if ( $mc == $i ) { // last item + $c = $menu[$order][4]; + $menu[$order][4] = add_cssclass('menu-top-last', $c); + } + + $lastorder = $order; + } + + return apply_filters( 'add_menu_classes', $menu ); +} + +uksort($menu, "strnatcasecmp"); // make it all pretty + +if ( apply_filters('custom_menu_order', false) ) { + $menu_order = array(); + foreach ( $menu as $menu_item ) { + $menu_order[] = $menu_item[2]; + } + unset($menu_item); + $default_menu_order = $menu_order; + $menu_order = apply_filters('menu_order', $menu_order); + $menu_order = array_flip($menu_order); + $default_menu_order = array_flip($default_menu_order); + + function sort_menu($a, $b) { + global $menu_order, $default_menu_order; + $a = $a[2]; + $b = $b[2]; + if ( isset($menu_order[$a]) && !isset($menu_order[$b]) ) { + return -1; + } elseif ( !isset($menu_order[$a]) && isset($menu_order[$b]) ) { + return 1; + } elseif ( isset($menu_order[$a]) && isset($menu_order[$b]) ) { + if ( $menu_order[$a] == $menu_order[$b] ) + return 0; + return ($menu_order[$a] < $menu_order[$b]) ? -1 : 1; + } else { + return ($default_menu_order[$a] <= $default_menu_order[$b]) ? -1 : 1; + } + } + + usort($menu, 'sort_menu'); + unset($menu_order, $default_menu_order); +} + +$menu = add_menu_classes($menu); + +if (! user_can_access_admin_page()) { + do_action('admin_page_access_denied'); + wp_die( __('You do not have sufficient permissions to access this page.') ); +} + +?> diff --git a/wp-admin/moderation.php b/wp-admin/moderation.php new file mode 100644 index 0000000..6a26f23 --- /dev/null +++ b/wp-admin/moderation.php @@ -0,0 +1,12 @@ + diff --git a/wp-admin/options-discussion.php b/wp-admin/options-discussion.php new file mode 100644 index 0000000..132f0b3 --- /dev/null +++ b/wp-admin/options-discussion.php @@ -0,0 +1,231 @@ + + +
    + +

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    +

    + +

    +

    + +

    +
    +

    +

    + +

    +
    + +

    + +

    + + + + + + + + + + + + + + + + + +
    + __("Don’t show Avatars"), 1 => __('Show Avatars')); + foreach ( $yesorno as $key => $value) { + $selected = (get_option('show_avatars') == $key) ? 'checked="checked"' : ''; + echo "\n\t
    "; + } +?> +
    + + __('G — Suitable for all audiences'), 'PG' => __('PG — Possibly offensive, usually for audiences 13 and above'), 'R' => __('R — Intended for adult audiences above 17'), 'X' => __('X — Even more mature than above')); +foreach ($ratings as $key => $rating) : + $selected = (get_option('avatar_rating') == $key) ? 'checked="checked"' : ''; + echo "\n\t
    "; +endforeach; +?> + +
    + +
    + + __('Mystery Man'), + 'blank' => __('Blank'), + 'gravatar_default' => __('Gravatar Logo'), + 'identicon' => __('Identicon (Generated)'), + 'wavatar' => __('Wavatar (Generated)'), + 'monsterid' => __('MonsterID (Generated)') +); +$avatar_defaults = apply_filters('avatar_defaults', $avatar_defaults); +$default = get_option('avatar_default'); +if ( empty($default) ) + $default = 'mystery'; +$size = 32; +$avatar_list = ''; +foreach ( $avatar_defaults as $default_key => $default_name ) { + $selected = ($default == $default_key) ? 'checked="checked" ' : ''; + $avatar_list .= "\n\t'; + $avatar_list .= '
    '; +} +echo apply_filters('default_avatar_select', $avatar_list); +?> + +
    + + + +

    + +

    +
    +
    + + diff --git a/wp-admin/options-general.php b/wp-admin/options-general.php new file mode 100644 index 0000000..def2124 --- /dev/null +++ b/wp-admin/options-general.php @@ -0,0 +1,283 @@ + + + + +
    + +

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + += 0) ? '+' : '') . $offnum; +} +?> + + + + + + + + + + + + + + + + + + +
    +
    " />
    " /> +to be different from the directory you installed WordPress.'); ?>
    +
    +
    + +
    + + +UTC time is %s'), date_i18n( $time_format, false, 'gmt')); ?> + + %2$s'), $current_offset_name, date_i18n($time_format)); ?> + +
    + +
    + + + + UTC time is %s'), date_i18n($timezone_format, false, 'gmt')); ?> + + %1$s'), date_i18n($timezone_format)); ?> + +
    + +
    + + + +
    + time()) { + $found = true; + break; + } + } + + if ( isset($found) && $found === true ) { + echo ' '; + $message = $tr['isdst'] ? + __('Daylight savings time begins on: %s.') : + __('Standard time begins on: %s.'); + printf( $message, date_i18n(get_option('date_format').' '.get_option('time_format'), $tr['ts'] ) ); + } else { + _e('This timezone does not observe daylight savings time.'); + } + } + ?> +
    + +
    +
    + ' . date_i18n( $format ) . "
    \n"; + } + + echo ' ' . date_i18n( get_option('date_format') ) . "\n"; + + echo "\t

    " . __('Documentation on date formatting. Click “Save Changes” to update sample output.') . "

    \n"; +?> +
    +
    +
    + ' . date_i18n( $format ) . "
    \n"; + } + + echo ' ' . date_i18n( get_option('time_format') ) . "\n"; +?> +
    +
    + + + +

    + +

    +
    + +
    + + diff --git a/wp-admin/options-head.php b/wp-admin/options-head.php new file mode 100644 index 0000000..14a177c --- /dev/null +++ b/wp-admin/options-head.php @@ -0,0 +1,17 @@ + + + +

    + \ No newline at end of file diff --git a/wp-admin/options-media.php b/wp-admin/options-media.php new file mode 100644 index 0000000..e5abf4e --- /dev/null +++ b/wp-admin/options-media.php @@ -0,0 +1,78 @@ + + +
    + +

    + +
    + + +

    +

    + + + + + + + + + + + + + + + + + + +
    + + + +
    +/> + +
    + + + + +
    + + + + +
    + + + +

    + +

    + +
    + +
    + + diff --git a/wp-admin/options-misc.php b/wp-admin/options-misc.php new file mode 100644 index 0000000..cc366a9 --- /dev/null +++ b/wp-admin/options-misc.php @@ -0,0 +1,79 @@ + + +
    + +

    + +
    + + +

    + + + + + + + + + + + + + + + +
    +wp-content/uploads'); ?> +
    + +
    + +
    + + + + + + + + +
    + +
    + + + +

    + +

    + +
    +
    + + diff --git a/wp-admin/options-permalink.php b/wp-admin/options-permalink.php new file mode 100644 index 0000000..c06fa08 --- /dev/null +++ b/wp-admin/options-permalink.php @@ -0,0 +1,248 @@ + + +set_permalink_structure($permalink_structure); + } + + if ( isset($_POST['category_base']) ) { + $category_base = $_POST['category_base']; + if (! empty($category_base) ) + $category_base = preg_replace('#/+#', '/', '/' . $_POST['category_base']); + $wp_rewrite->set_category_base($category_base); + } + + if ( isset($_POST['tag_base']) ) { + $tag_base = $_POST['tag_base']; + if (! empty($tag_base) ) + $tag_base = preg_replace('#/+#', '/', '/' . $_POST['tag_base']); + $wp_rewrite->set_tag_base($tag_base); + } +} + +$permalink_structure = get_option('permalink_structure'); +$category_base = get_option('category_base'); +$tag_base = get_option( 'tag_base' ); + +if ( $iis7_permalinks ) { + if ( ( ! file_exists($home_path . 'web.config') && win_is_writable($home_path) ) || win_is_writable($home_path . 'web.config') ) + $writable = true; + else + $writable = false; +} else { + if ( ( ! file_exists($home_path . '.htaccess') && is_writable($home_path) ) || is_writable($home_path . '.htaccess') ) + $writable = true; + else + $writable = false; +} + +if ( $wp_rewrite->using_index_permalinks() ) + $usingpi = true; +else + $usingpi = false; + +$wp_rewrite->flush_rules(); +?> + + +

    +

    + + +
    + +

    + +
    + + +

    URLs which have question marks and lots of numbers in them, however WordPress offers you the ability to create a custom URL structure for your permalinks and archives. This can improve the aesthetics, usability, and forward-compatibility of your links. A number of tags are available, and here are some examples to get you started.'); ?>

    + + +

    + + + + + + + + + + + + + + + + + + + + + +
    /?p=123
    /archives/123
    + + + +
    + +

    + +

    URLs here. For example, using topics as your category base would make your category links like http://example.org/topics/uncategorized/. If you leave these blank the defaults will be used.') ?>

    + +

    URLs here. For example, using topics as your category base would make your category links like http://example.org/index.php/topics/uncategorized/. If you leave these blank the defaults will be used.') ?>

    + + + + + + + + + + + + +
    + + + +

    + +

    +
    + +

    web.config file were writable, we could do this automatically, but it isn’t so this is the url rewrite rule you should have in your web.config file. Click in the field and press CTRL + a to select all. Then insert this rule inside of the /<configuration>/<system.webServer>/<rewrite>/<rules> element in web.config file.') ?>

    +
    + +

    +
    +

    web.config file writable for us to generate rewrite rules automatically, do not forget to revert the permissions after rule has been saved.') ?>

    + + +

    .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all.') ?>

    +
    + +

    +
    + + + +
    + + diff --git a/wp-admin/options-privacy.php b/wp-admin/options-privacy.php new file mode 100644 index 0000000..009e943 --- /dev/null +++ b/wp-admin/options-privacy.php @@ -0,0 +1,51 @@ + + +
    + +

    + +
    + + + + + + + + +
    +

    /> +

    +

    /> +

    + +
    + + + +

    + +

    +
    + +
    + + diff --git a/wp-admin/options-reading.php b/wp-admin/options-reading.php new file mode 100644 index 0000000..dd3ba3b --- /dev/null +++ b/wp-admin/options-reading.php @@ -0,0 +1,90 @@ + + +
    + +

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    +

    +

    +

    +
      +
    • ".__('Front page: %s')."", wp_dropdown_pages("name=page_on_front&echo=0&show_option_none=".__('- Select -')."&selected=" . get_option('page_on_front'))); ?>
    • +
    • ".__('Posts page: %s')."", wp_dropdown_pages("name=page_for_posts&echo=0&show_option_none=".__('- Select -')."&selected=" . get_option('page_for_posts'))); ?>
    • +
    + +
    +

    + Warning: these pages should not be the same!'); ?> +

    +
    + +
    + +
    +


    +

    +
    +recommended)') ?>
    + + + +

    + +

    +
    +
    + diff --git a/wp-admin/options-writing.php b/wp-admin/options-writing.php new file mode 100644 index 0000000..a8979f4 --- /dev/null +++ b/wp-admin/options-writing.php @@ -0,0 +1,138 @@ + + +
    + +

    + +
    + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + +
    + 0, 'name' => 'default_category', 'orderby' => 'name', 'selected' => get_option('default_category'), 'hierarchical' => true)); +?> +
    + 0, 'name' => 'default_link_category', 'orderby' => 'name', 'selected' => get_option('default_link_category'), 'hierarchical' => true, 'type' => 'link')); +?> +
    + +

    +

    + + + + + + + + + + +
    +
    +
    +
    +
    + +

    +

    %s, %s, %s.'), wp_generate_password(8, false), wp_generate_password(8, false), wp_generate_password(8, false)) ?>

    + + + + + + + + + + + + + + + + + + + +
    + + +
    + +
    + 0, 'name' => 'default_email_category', 'orderby' => 'name', 'selected' => get_option('default_email_category'), 'hierarchical' => true)); +?> +
    + +

    + + + +

    + + + + + +

    Update Services because of your blog’s privacy settings.'), 'options-privacy.php'); ?>

    + + + + + +

    + +

    +
    +
    + + diff --git a/wp-admin/options.php b/wp-admin/options.php new file mode 100644 index 0000000..6bc0561 --- /dev/null +++ b/wp-admin/options.php @@ -0,0 +1,143 @@ + array( 'blogname', 'blogdescription', 'admin_email', 'users_can_register', 'gmt_offset', 'date_format', 'time_format', 'start_of_week', 'default_role', 'timezone_string' ), + 'discussion' => array( 'default_pingback_flag', 'default_ping_status', 'default_comment_status', 'comments_notify', 'moderation_notify', 'comment_moderation', 'require_name_email', 'comment_whitelist', 'comment_max_links', 'moderation_keys', 'blacklist_keys', 'show_avatars', 'avatar_rating', 'avatar_default', 'close_comments_for_old_posts', 'close_comments_days_old', 'thread_comments', 'thread_comments_depth', 'page_comments', 'comments_per_page', 'default_comments_page', 'comment_order', 'comment_registration' ), + 'misc' => array( 'use_linksupdate', 'uploads_use_yearmonth_folders', 'upload_path', 'upload_url_path' ), + 'media' => array( 'thumbnail_size_w', 'thumbnail_size_h', 'thumbnail_crop', 'medium_size_w', 'medium_size_h', 'large_size_w', 'large_size_h', 'image_default_size', 'image_default_align', 'image_default_link_type' ), + 'privacy' => array( 'blog_public' ), + 'reading' => array( 'posts_per_page', 'posts_per_rss', 'rss_use_excerpt', 'blog_charset', 'show_on_front', 'page_on_front', 'page_for_posts' ), + 'writing' => array( 'default_post_edit_rows', 'use_smilies', 'ping_sites', 'mailserver_url', 'mailserver_port', 'mailserver_login', 'mailserver_pass', 'default_category', 'default_email_category', 'use_balanceTags', 'default_link_category', 'enable_app', 'enable_xmlrpc' ), + 'options' => array( '' ) ); +if ( !defined( 'WP_SITEURL' ) ) $whitelist_options['general'][] = 'siteurl'; +if ( !defined( 'WP_HOME' ) ) $whitelist_options['general'][] = 'home'; + +$whitelist_options = apply_filters( 'whitelist_options', $whitelist_options ); + +if ( !current_user_can('manage_options') ) + wp_die(__('Cheatin’ uh?')); + +switch($action) { + +case 'update': + if ( isset($_POST[ 'option_page' ]) ) { + $option_page = $_POST[ 'option_page' ]; + check_admin_referer( $option_page . '-options' ); + } else { + // This is for back compat and will eventually be removed. + $option_page = 'options'; + check_admin_referer( 'update-options' ); + } + + if ( !isset( $whitelist_options[ $option_page ] ) ) + wp_die( __( 'Error! Options page not found.' ) ); + + if ( 'options' == $option_page ) { + $options = explode(',', stripslashes( $_POST[ 'page_options' ] )); + } else { + $options = $whitelist_options[ $option_page ]; + } + + // Handle custom date/time formats + if ( 'general' == $option_page ) { + if ( !empty($_POST['date_format']) && isset($_POST['date_format_custom']) && '\c\u\s\t\o\m' == stripslashes( $_POST['date_format'] ) ) + $_POST['date_format'] = $_POST['date_format_custom']; + if ( !empty($_POST['time_format']) && isset($_POST['time_format_custom']) && '\c\u\s\t\o\m' == stripslashes( $_POST['time_format'] ) ) + $_POST['time_format'] = $_POST['time_format_custom']; + } + + if ( $options ) { + foreach ( $options as $option ) { + $option = trim($option); + $value = null; + if ( isset($_POST[$option]) ) + $value = $_POST[$option]; + if ( !is_array($value) ) $value = trim($value); + $value = stripslashes_deep($value); + update_option($option, $value); + } + } + + $goback = add_query_arg( 'updated', 'true', wp_get_referer() ); + wp_redirect( $goback ); + break; + +default: + include('admin-header.php'); ?> + +
    + +

    +
    + + + + +get_results("SELECT * FROM $wpdb->options ORDER BY option_name"); + +foreach ( (array) $options as $option) : + $disabled = ''; + $option->option_name = esc_attr($option->option_name); + if ( is_serialized($option->option_value) ) { + if ( is_serialized_string($option->option_value) ) { + // this is a serialized string, so we should display it + $value = maybe_unserialize($option->option_value); + $options_to_update[] = $option->option_name; + $class = 'all-options'; + } else { + $value = 'SERIALIZED DATA'; + $disabled = ' disabled="disabled"'; + $class = 'all-options disabled'; + } + } else { + $value = $option->option_value; + $options_to_update[] = $option->option_name; + $class = 'all-options'; + } + echo " + + + +"; +endforeach; +?> +
    "; + + if (strpos($value, "\n") !== false) echo ""; + else echo ""; + + echo "
    + +

    +
    +
    + + + diff --git a/wp-admin/page-new.php b/wp-admin/page-new.php new file mode 100644 index 0000000..05ad921 --- /dev/null +++ b/wp-admin/page-new.php @@ -0,0 +1,31 @@ + diff --git a/wp-admin/page.php b/wp-admin/page.php new file mode 100644 index 0000000..68a6690 --- /dev/null +++ b/wp-admin/page.php @@ -0,0 +1,183 @@ +ID) ) wp_die( __('You attempted to edit a page that doesn’t exist. Perhaps it was deleted?') ); + + if ( 'page' != $post->post_type ) { + wp_redirect( get_edit_post_link( $post_ID, 'url' ) ); + exit(); + } + + wp_enqueue_script('page'); + if ( user_can_richedit() ) + wp_enqueue_script('editor'); + add_thickbox(); + wp_enqueue_script('media-upload'); + wp_enqueue_script('word-count'); + + if ( current_user_can('edit_page', $page_ID) ) { + if ( $last = wp_check_post_lock( $post->ID ) ) { + $last_user = get_userdata( $last ); + $last_user_name = $last_user ? $last_user->display_name : __('Somebody'); + $message = sprintf( __( 'Warning: %s is currently editing this page' ), esc_html( $last_user_name ) ); + $message = str_replace( "'", "\'", "

    $message

    " ); + add_action('admin_notices', create_function( '', "echo '$message';" ) ); + } else { + wp_set_post_lock( $post->ID ); + wp_enqueue_script('autosave'); + } + } + + if ( !current_user_can('edit_page', $page_ID) ) + die ( __('You are not allowed to edit this page.') ); + + include('edit-page-form.php'); + break; + +case 'editattachment': + $page_id = $post_ID = (int) $_POST['post_ID']; + check_admin_referer('update-attachment_' . $page_id); + + // Don't let these be changed + unset($_POST['guid']); + $_POST['post_type'] = 'attachment'; + + // Update the thumbnail filename + $newmeta = wp_get_attachment_metadata( $page_id, true ); + $newmeta['thumb'] = $_POST['thumb']; + + wp_update_attachment_metadata( $newmeta ); + +case 'editpost': + $page_ID = (int) $_POST['post_ID']; + check_admin_referer('update-page_' . $page_ID); + + $page_ID = edit_post(); + + redirect_page($page_ID); + + exit(); + break; + +case 'delete': + $page_id = (isset($_GET['post'])) ? intval($_GET['post']) : intval($_POST['post_ID']); + check_admin_referer('delete-page_' . $page_id); + + $page = & get_post($page_id); + + if ( !current_user_can('delete_page', $page_id) ) + wp_die( __('You are not allowed to delete this page.') ); + + if ( $page->post_type == 'attachment' ) { + if ( ! wp_delete_attachment($page_id) ) + wp_die( __('Error in deleting...') ); + } else { + if ( !wp_delete_post($page_id) ) + wp_die( __('Error in deleting...') ); + } + + $sendback = wp_get_referer(); + if (strpos($sendback, 'page.php') !== false) $sendback = admin_url('edit-pages.php?deleted=1'); + elseif (strpos($sendback, 'attachments.php') !== false) $sendback = admin_url('attachments.php'); + else $sendback = add_query_arg('deleted', 1, $sendback); + wp_redirect($sendback); + exit(); + break; + +case 'preview': + check_admin_referer( 'autosave', 'autosavenonce' ); + + $url = post_preview(); + + wp_redirect($url); + exit(); + break; + +default: + wp_redirect('edit-pages.php'); + exit(); + break; +} // end switch +include('admin-footer.php'); +?> diff --git a/wp-admin/plugin-editor.php b/wp-admin/plugin-editor.php new file mode 100644 index 0000000..8b1602c --- /dev/null +++ b/wp-admin/plugin-editor.php @@ -0,0 +1,230 @@ +'.__('You do not have sufficient permissions to edit templates for this blog.').'

    '); + + $newcontent = stripslashes($_POST['newcontent']); + if ( is_writeable($real_file) ) { + $f = fopen($real_file, 'w+'); + fwrite($f, $newcontent); + fclose($f); + + // Deactivate so we can test it. + if ( is_plugin_active($file) || isset($_POST['phperror']) ) { + if ( is_plugin_active($file) ) + deactivate_plugins($file, true); + wp_redirect(add_query_arg('_wpnonce', wp_create_nonce('edit-plugin-test_' . $file), "plugin-editor.php?file=$file&liveupdate=1")); + exit; + } + wp_redirect("plugin-editor.php?file=$file&a=te"); + } else { + wp_redirect("plugin-editor.php?file=$file"); + } + exit; + +break; + +default: + + if ( !current_user_can('edit_plugins') ) + wp_die('

    '.__('You do not have sufficient permissions to edit plugins for this blog.').'

    '); + + if ( isset($_GET['liveupdate']) ) { + check_admin_referer('edit-plugin-test_' . $file); + + $error = validate_plugin($file); + if ( is_wp_error($error) ) + wp_die( $error ); + + if ( ! is_plugin_active($file) ) + activate_plugin($file, "plugin-editor.php?file=$file&phperror=1"); // we'll override this later if the plugin can be included without fatal error + + wp_redirect("plugin-editor.php?file=$file&a=te"); + exit; + } + + // List of allowable extensions + $editable_extensions = array('php', 'txt', 'text', 'js', 'css', 'html', 'htm', 'xml', 'inc', 'include'); + $editable_extensions = (array) apply_filters('editable_extensions', $editable_extensions); + + if ( ! is_file($real_file) ) { + wp_die(sprintf('

    %s

    ', __('No such file exists! Double check the name and try again.'))); + } else { + // Get the extension of the file + if ( preg_match('/\.([^.]+)$/', $real_file, $matches) ) { + $ext = strtolower($matches[1]); + // If extension is not in the acceptable list, skip it + if ( !in_array( $ext, $editable_extensions) ) + wp_die(sprintf('

    %s

    ', __('Files of this type are not editable.'))); + } + } + + require_once('admin-header.php'); + + update_recently_edited(WP_PLUGIN_DIR . '/' . $file); + + $content = file_get_contents( $real_file ); + + if ( '.php' == substr( $real_file, strrpos( $real_file, '.' ) ) ) { + $functions = wp_doc_link_parse( $content ); + + if ( !empty($functions) ) { + $docs_select = ''; + } + } + + $content = htmlspecialchars( $content ); + $codepress_lang = codepress_get_lang($real_file); + + ?> + +

    + +

    fatal error.') ?>

    + + + +
    + +
    + +

    + +
    +
    +%s (active)'), $file); + else + echo sprintf(__('Browsing %s (active)'), $file); + } else { + if ( is_writeable($real_file) ) + echo sprintf(__('Editing %s (inactive)'), $file); + else + echo sprintf(__('Browsing %s (inactive)'), $file); + } + ?> +
    +
    +
    + + + +
    +
    +
    +
    + +
    +

    + +
      + + > + +
    +
    +
    + +
    + + + +
    + +
    + + + +

    Warning: Making changes to active plugins is not recommended. If your changes cause a fatal error, the plugin will be automatically deactivated.'); ?>

    + +

    + "; + else + echo ""; + ?> +

    + +

    the Codex for more information.'); ?>

    + +
    +
    +
    + +
    + +

    + +
      + $text ) { + $sep = ( end($tabs) != $text ) ? ' | ' : ''; + $class = ( $action == $tab ) ? ' class="current"' : ''; + $href = admin_url('plugin-install.php?tab=' . $action); + echo "\t\t
    • $text$sep
    • \n"; +} +?> +
    +
    + +
    +ID, 'plugins_last_view', $status); + +$page = isset($_REQUEST['paged']) ? $_REQUEST['paged'] : 1; + +//Clean up request URI from temporary args for screen options/paging uri's to work as expected. +$_SERVER['REQUEST_URI'] = remove_query_arg(array('error', 'deleted', 'activate', 'activate-multi', 'deactivate', 'deactivate-multi', '_error_nonce'), $_SERVER['REQUEST_URI']); + +if ( !empty($action) ) { + switch ( $action ) { + case 'activate': + if ( ! current_user_can('activate_plugins') ) + wp_die(__('You do not have sufficient permissions to activate plugins for this blog.')); + + check_admin_referer('activate-plugin_' . $plugin); + + $result = activate_plugin($plugin, 'plugins.php?error=true&plugin=' . $plugin); + if ( is_wp_error( $result ) ) + wp_die($result); + + $recent = (array)get_option('recently_activated'); + if ( isset($recent[ $plugin ]) ) { + unset($recent[ $plugin ]); + update_option('recently_activated', $recent); + } + + wp_redirect("plugins.php?activate=true&plugin_status=$status&paged=$page"); // overrides the ?error=true one above + exit; + break; + case 'activate-selected': + if ( ! current_user_can('activate_plugins') ) + wp_die(__('You do not have sufficient permissions to activate plugins for this blog.')); + + check_admin_referer('bulk-manage-plugins'); + + $plugins = (array) $_POST['checked']; + $plugins = array_filter($plugins, create_function('$plugin', 'return !is_plugin_active($plugin);') ); //Only activate plugins which are not already active. + if ( empty($plugins) ) { + wp_redirect("plugins.php?plugin_status=$status&paged=$page"); + exit; + } + + activate_plugins($plugins, 'plugins.php?error=true'); + + $recent = (array)get_option('recently_activated'); + foreach ( $plugins as $plugin => $time) + if ( isset($recent[ $plugin ]) ) + unset($recent[ $plugin ]); + + update_option('recently_activated', $recent); + + wp_redirect("plugins.php?activate-multi=true&plugin_status=$status&paged=$page"); + exit; + break; + case 'error_scrape': + if ( ! current_user_can('activate_plugins') ) + wp_die(__('You do not have sufficient permissions to activate plugins for this blog.')); + + check_admin_referer('plugin-activation-error_' . $plugin); + + $valid = validate_plugin($plugin); + if ( is_wp_error($valid) ) + wp_die($valid); + + error_reporting( E_ALL ^ E_NOTICE ); + @ini_set('display_errors', true); //Ensure that Fatal errors are displayed. + include(WP_PLUGIN_DIR . '/' . $plugin); + do_action('activate_' . $plugin); + exit; + break; + case 'deactivate': + if ( ! current_user_can('activate_plugins') ) + wp_die(__('You do not have sufficient permissions to deactivate plugins for this blog.')); + + check_admin_referer('deactivate-plugin_' . $plugin); + deactivate_plugins($plugin); + update_option('recently_activated', array($plugin => time()) + (array)get_option('recently_activated')); + wp_redirect("plugins.php?deactivate=true&plugin_status=$status&paged=$page"); + exit; + break; + case 'deactivate-selected': + if ( ! current_user_can('activate_plugins') ) + wp_die(__('You do not have sufficient permissions to deactivate plugins for this blog.')); + + check_admin_referer('bulk-manage-plugins'); + + $plugins = (array) $_POST['checked']; + $plugins = array_filter($plugins, 'is_plugin_active'); //Do not deactivate plugins which are already deactivated. + if ( empty($plugins) ) { + wp_redirect("plugins.php?plugin_status=$status&paged=$page"); + exit; + } + + deactivate_plugins($plugins); + + $deactivated = array(); + foreach ( $plugins as $plugin ) + $deactivated[ $plugin ] = time(); + + update_option('recently_activated', $deactivated + (array)get_option('recently_activated')); + wp_redirect("plugins.php?deactivate-multi=true&plugin_status=$status&paged=$page"); + exit; + break; + case 'delete-selected': + if ( ! current_user_can('delete_plugins') ) + wp_die(__('You do not have sufficient permissions to delete plugins for this blog.')); + + check_admin_referer('bulk-manage-plugins'); + + $plugins = (array) $_REQUEST['checked']; //$_POST = from the plugin form; $_GET = from the FTP details screen. + $plugins = array_filter($plugins, create_function('$plugin', 'return !is_plugin_active($plugin);') ); //Do not allow to delete Activated plugins. + if ( empty($plugins) ) { + wp_redirect("plugins.php?plugin_status=$status&paged=$page"); + exit; + } + + include(ABSPATH . 'wp-admin/update.php'); + + $parent_file = 'plugins.php'; + + if ( ! isset($_REQUEST['verify-delete']) ) { + wp_enqueue_script('jquery'); + require_once('admin-header.php'); + ?> +
    +

    + +

    +
      + ', sprintf(__('%s by %s'), $plugin['Name'], $plugin['Author']), ''; + ?> +
    +

    +
    + + + '; + ?> + + +
    +
    + +
    + +

    + +
    + ' . __('Plugins extend and expand the functionality of WordPress. Once a plugin is installed, you may activate it or deactivate it here.') . '

    '; +$help .= '

    ' . sprintf(__('If something goes wrong with a plugin and you can’t use WordPress, delete or rename that file in the %s directory and it will be automatically deactivated.'), WP_PLUGIN_DIR) . '

    '; +$help .= '

    ' . sprintf(__('You can find additional plugins for your site by using the new Plugin Browser/Installer functionality or by browsing the WordPress Plugin Directory directly and installing manually. To manually install a plugin you generally just need to upload the plugin file into your %2$s directory. Once a plugin has been installed, you may activate it here.'), 'plugin-install.php', WP_PLUGIN_DIR) . '

    '; + +add_contextual_help('plugins', $help); + +$title = __('Manage Plugins'); +require_once('admin-header.php'); + +$invalid = validate_active_plugins(); +if ( !empty($invalid) ) + foreach ( $invalid as $plugin_file => $error ) + echo '

    ' . sprintf(__('The plugin %s has been deactivated due to an error: %s'), esc_html($plugin_file), $error->get_error_message()) . '

    '; +?> + + +

    fatal error.') ?>

    + + + +
    + +

    get_error_message() ); ?>

    + +

    deleted.'); ?>

    + + +

    activated.') ?>

    + +

    activated.'); ?>

    + +

    deactivated.') ?>

    + +

    deactivated.'); ?>

    + + +
    + +

    + + $time ) + if ( $time + (7*24*60*60) < time() ) //1 week + unset($recently_activated[ $key ]); +if ( $recently_activated != get_option('recently_activated') ) //If array changed, update it. + update_option('recently_activated', $recently_activated); +$current = get_transient( 'update_plugins' ); + +foreach ( (array)$all_plugins as $plugin_file => $plugin_data) { + + //Translate, Apply Markup, Sanitize HTML + $plugin_data = _get_plugin_data_markup_translate($plugin_file, $plugin_data, false, true); + $all_plugins[ $plugin_file ] = $plugin_data; + + //Filter into individual sections + if ( is_plugin_active($plugin_file) ) { + $active_plugins[ $plugin_file ] = $plugin_data; + } else { + if ( isset( $recently_activated[ $plugin_file ] ) ) // Was the plugin recently activated? + $recent_plugins[ $plugin_file ] = $plugin_data; + $inactive_plugins[ $plugin_file ] = $plugin_data; + } + + if ( isset( $current->response[ $plugin_file ] ) ) + $upgrade_plugins[ $plugin_file ] = $plugin_data; +} + +$total_all_plugins = count($all_plugins); +$total_inactive_plugins = count($inactive_plugins); +$total_active_plugins = count($active_plugins); +$total_recent_plugins = count($recent_plugins); +$total_upgrade_plugins = count($upgrade_plugins); + +//Searching. +if ( isset($_GET['s']) ) { + function _search_plugins_filter_callback($plugin) { + static $term; + if ( is_null($term) ) + $term = stripslashes($_GET['s']); + if ( stripos($plugin['Name'], $term) !== false || + stripos($plugin['Description'], $term) !== false || + stripos($plugin['Author'], $term) !== false || + stripos($plugin['PluginURI'], $term) !== false || + stripos($plugin['AuthorURI'], $term) !== false || + stripos($plugin['Version'], $term) !== false ) + return true; + else + return false; + } + $status = 'search'; + $search_plugins = array_filter($all_plugins, '_search_plugins_filter_callback'); + $total_search_plugins = count($search_plugins); +} + +$plugin_array_name = "${status}_plugins"; +if ( empty($$plugin_array_name) && $status != 'all' ) { + $status = 'all'; + $plugin_array_name = "${status}_plugins"; +} + +$plugins = &$$plugin_array_name; + +//Paging. +$total_this_page = "total_{$status}_plugins"; +$total_this_page = $$total_this_page; +$plugins_per_page = get_user_option('plugins_per_page'); +if ( empty($plugins_per_page) ) + $plugins_per_page = 999; +$plugins_per_page = apply_filters('plugins_per_page', $plugins_per_page); + +$start = ($page - 1) * $plugins_per_page; + +$page_links = paginate_links( array( + 'base' => add_query_arg( 'paged', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil($total_this_page / $plugins_per_page), + 'current' => $page +)); +$page_links_text = sprintf( '' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( $start + 1 ), + number_format_i18n( min( $page * $plugins_per_page, $total_this_page ) ), + '' . number_format_i18n( $total_this_page ) . '', + $page_links +); + +/** + * @ignore + * + * @param array $plugins + * @param string $context + */ +function print_plugins_table($plugins, $context = '') { + global $page; +?> + + + + + + + + + + + + + + + + + + + + + '; + } + foreach ( (array)$plugins as $plugin_file => $plugin_data) { + $actions = array(); + $is_active = is_plugin_active($plugin_file); + + if ( $is_active ) + $actions[] = '' . __('Deactivate') . ''; + else + $actions[] = '' . __('Activate') . ''; + + if ( current_user_can('edit_plugins') && is_writable(WP_PLUGIN_DIR . '/' . $plugin_file) ) + $actions[] = '' . __('Edit') . ''; + + if ( ! $is_active && current_user_can('delete_plugins') ) + $actions[] = '' . __('Delete') . ''; + + $actions = apply_filters( 'plugin_action_links', $actions, $plugin_file, $plugin_data, $context ); + $actions = apply_filters( "plugin_action_links_$plugin_file", $actions, $plugin_file, $plugin_data, $context ); + $action_count = count($actions); + $class = $is_active ? 'active' : 'inactive'; + echo " + + + + + + + + + + \n"; + + do_action( 'after_plugin_row', $plugin_file, $plugin_data, $context ); + do_action( "after_plugin_row_$plugin_file", $plugin_file, $plugin_data, $context ); + } +?> + +
    ' . __('No plugins to show') . '
    {$plugin_data['Name']}

    {$plugin_data['Description']}

    "; + echo '
    '; + foreach ( $actions as $action => $link ) { + $sep = end($actions) == $link ? '' : ' | '; + echo "$link$sep"; + } + echo "
    "; + $plugin_meta = array(); + if ( !empty($plugin_data['Version']) ) + $plugin_meta[] = sprintf(__('Version %s'), $plugin_data['Version']); + if ( !empty($plugin_data['Author']) ) { + $author = $plugin_data['Author']; + if ( !empty($plugin_data['AuthorURI']) ) + $author = '' . $plugin_data['Author'] . ''; + $plugin_meta[] = sprintf( __('By %s'), $author ); + } + if ( ! empty($plugin_data['PluginURI']) ) + $plugin_meta[] = '' . __('Visit plugin site') . ''; + + $plugin_meta = apply_filters('plugin_row_meta', $plugin_meta, $plugin_file, $plugin_data, $context); + echo implode(' | ', $plugin_meta); + echo "
    + +
    + + + + + +
    + + +
    + +
    + +
    + + + + + + +
    +', $page_links_text, '
    '; + +print_plugin_actions($status); +?> +
    +
    + $plugins_per_page ) + $plugins = array_slice($plugins, $start, $plugins_per_page); + + print_plugins_table($plugins, $status); +?> +
    +$page_links_text
    "; + +print_plugin_actions($status, "action2"); +?> + + + + +

    + + + + + diff --git a/wp-admin/post-new.php b/wp-admin/post-new.php new file mode 100644 index 0000000..229f3d0 --- /dev/null +++ b/wp-admin/post-new.php @@ -0,0 +1,40 @@ + +
    +

    edit_posts capability to your user, in order to be authorized to post.
    +You can also e-mail the admin to ask for a promotion.
    +When you’re promoted, just reload this page and you’ll be able to blog. :)'), get_option('admin_email')); ?> +

    +
    + diff --git a/wp-admin/post.php b/wp-admin/post.php new file mode 100644 index 0000000..008778f --- /dev/null +++ b/wp-admin/post.php @@ -0,0 +1,224 @@ +ID) ) wp_die( __('You attempted to edit a post that doesn’t exist. Perhaps it was deleted?') ); + + if ( 'post' != $post->post_type ) { + wp_redirect( get_edit_post_link( $post->ID, 'url' ) ); + exit(); + } + + wp_enqueue_script('post'); + if ( user_can_richedit() ) + wp_enqueue_script('editor'); + add_thickbox(); + wp_enqueue_script('media-upload'); + wp_enqueue_script('word-count'); + wp_enqueue_script( 'admin-comments' ); + enqueue_comment_hotkeys_js(); + + if ( current_user_can('edit_post', $post_ID) ) { + if ( $last = wp_check_post_lock( $post->ID ) ) { + $last_user = get_userdata( $last ); + $last_user_name = $last_user ? $last_user->display_name : __('Somebody'); + $message = sprintf( __( 'Warning: %s is currently editing this post' ), esc_html( $last_user_name ) ); + $message = str_replace( "'", "\'", "

    $message

    " ); + add_action('admin_notices', create_function( '', "echo '$message';" ) ); + } else { + wp_set_post_lock( $post->ID ); + wp_enqueue_script('autosave'); + } + } + + $title = __('Edit Post'); + + if ( !current_user_can('edit_post', $post_ID) ) + die ( __('You are not allowed to edit this post.') ); + + $post = get_post_to_edit($post_ID); + + include('edit-form-advanced.php'); + + break; + +case 'editattachment': + $post_id = (int) $_POST['post_ID']; + + check_admin_referer('update-attachment_' . $post_id); + + // Don't let these be changed + unset($_POST['guid']); + $_POST['post_type'] = 'attachment'; + + // Update the thumbnail filename + $newmeta = wp_get_attachment_metadata( $post_id, true ); + $newmeta['thumb'] = $_POST['thumb']; + + wp_update_attachment_metadata( $post_id, $newmeta ); + +case 'editpost': + $post_ID = (int) $_POST['post_ID']; + check_admin_referer('update-post_' . $post_ID); + + $post_ID = edit_post(); + + redirect_post($post_ID); // Send user on their way while we keep working + + exit(); + break; + +case 'delete': + $post_id = (isset($_GET['post'])) ? intval($_GET['post']) : intval($_POST['post_ID']); + check_admin_referer('delete-post_' . $post_id); + + $post = & get_post($post_id); + + if ( !current_user_can('delete_post', $post_id) ) + wp_die( __('You are not allowed to delete this post.') ); + + if ( $post->post_type == 'attachment' ) { + if ( ! wp_delete_attachment($post_id) ) + wp_die( __('Error in deleting...') ); + } else { + if ( !wp_delete_post($post_id) ) + wp_die( __('Error in deleting...') ); + } + + $sendback = wp_get_referer(); + if (strpos($sendback, 'post.php') !== false) $sendback = admin_url('edit.php?deleted=1'); + elseif (strpos($sendback, 'attachments.php') !== false) $sendback = admin_url('attachments.php'); + else $sendback = add_query_arg('deleted', 1, $sendback); + wp_redirect($sendback); + exit(); + break; + +case 'preview': + check_admin_referer( 'autosave', 'autosavenonce' ); + + $url = post_preview(); + + wp_redirect($url); + exit(); + break; + +default: + wp_redirect('edit.php'); + exit(); + break; +} // end switch +include('admin-footer.php'); +?> diff --git a/wp-admin/press-this.php b/wp-admin/press-this.php new file mode 100644 index 0000000..c6632b5 --- /dev/null +++ b/wp-admin/press-this.php @@ -0,0 +1,562 @@ + $image) + // see if files exist in content - we don't want to upload non-used selected files. + if( strpos($_REQUEST['content'], $image) !== false ) { + $desc = isset($_REQUEST['photo_description'][$key]) ? $_REQUEST['photo_description'][$key] : ''; + $upload = media_sideload_image($image, $post_ID, $desc); + + // Replace the POSTED content with correct uploaded ones. Regex contains fix for Magic Quotes + if( !is_wp_error($upload) ) $content = preg_replace('/]*)src=\\\?(\"|\')'.preg_quote($image, '/').'\\\?(\2)([^>\/]*)\/*>/is', $upload, $content); + } + + // set the post_content and status + $quick['post_status'] = isset($_REQUEST['publish']) ? 'publish' : 'draft'; + $quick['post_content'] = $content; + // error handling for $post + if ( is_wp_error($post_ID)) { + wp_die($id); + wp_delete_post($post_ID); + // error handling for media_sideload + } elseif ( is_wp_error($upload)) { + wp_die($upload); + wp_delete_post($post_ID); + } else { + $quick['ID'] = $post_ID; + wp_update_post($quick); + } + return $post_ID; +} + +// For submitted posts. +if ( isset($_REQUEST['action']) && 'post' == $_REQUEST['action'] ) { + check_admin_referer('press-this'); + $post_ID = press_it(); + $posted = $post_ID; +} else { + $post_ID = 0; +} + +// Set Variables +$title = isset($_GET['t']) ? esc_html(aposfix(stripslashes($_GET['t']))) : ''; +$selection = isset($_GET['s']) ? trim( aposfix( stripslashes($_GET['s']) ) ) : ''; +if ( ! empty($selection) ) { + $selection = preg_replace('/(\r?\n|\r)/', '

    ', $selection); + $selection = '

    '.str_replace('

    ', '', $selection).'

    '; +} +$url = isset($_GET['u']) ? esc_url($_GET['u']) : ''; +$image = isset($_GET['i']) ? $_GET['i'] : ''; + +if ( !empty($_REQUEST['ajax']) ) { +switch ($_REQUEST['ajax']) { + case 'video': ?> + +
    +

    +
    + +

    +
    +
    + + +

    +
    +
    + +
    +
    + +

    + <?php echo esc_attr(__('Click to insert.')); ?>

    + +

    + + + + +

    +
    +
    + +
    +
    + + +

    +
    +
    + +
    +
    + +

    |

    + ]*)src=(\"|\')([^<>]+?\.(png|jpeg|jpg|jpe|gif))[^<>\'\"]*(\2)([^>\/]*)\/*>/is'; + preg_match_all($pattern, $content, $matches); + if ( empty($matches[0]) ) + return ''; + $sources = array(); + foreach ($matches[3] as $src) { + // if no http in url + if(strpos($src, 'http') === false) + // if it doesn't have a relative uri + if( strpos($src, '../') === false && strpos($src, './') === false && strpos($src, '/') === 0) + $src = 'http://'.str_replace('//','/', $host['host'].'/'.$src); + else + $src = 'http://'.str_replace('//','/', $host['host'].'/'.dirname($host['path']).'/'.$src); + $sources[] = esc_url($src); + } + return "'" . implode("','", $sources) . "'"; + } + $url = urldecode($url); + $url = str_replace(' ', '%20', $url); + echo 'new Array('.get_images_from_uri($url).')'; + + break; + + case 'photo_js': ?> + // gather images and load some default JS + var last = null + var img, img_tag, aspect, w, h, skip, i, strtoappend = ""; + var my_src = eval( + jQuery.ajax({ + type: "GET", + url: "", + cache : false, + async : false, + data: "ajax=photo_images&u=", + dataType : "script" + }).responseText + ); + if(my_src.length == 0) { + var my_src = eval( + jQuery.ajax({ + type: "GET", + url: "", + cache : false, + async : false, + data: "ajax=photo_images&u=", + dataType : "script" + }).responseText + ); + if(my_src.length == 0) { + strtoappend = ''; + } + } + + for (i = 0; i < my_src.length; i++) { + img = new Image(); + img.src = my_src[i]; + img_attr = 'id="img' + i + '"'; + skip = false; + + maybeappend = ''; + + if (img.width && img.height) { + if (img.width >= 30 && img.height >= 30) { + aspect = img.width / img.height; + scale = (aspect > 1) ? (71 / img.width) : (71 / img.height); + + w = img.width; + h = img.height; + + if (scale < 1) { + w = parseInt(img.width * scale); + h = parseInt(img.height * scale); + } + img_attr += ' style="width: ' + w + 'px; height: ' + h + 'px;"'; + strtoappend += maybeappend; + } + } else { + strtoappend += maybeappend; + } + } + + function pick(img, desc) { + if (img) { + if('object' == typeof jQuery('.photolist input') && jQuery('.photolist input').length != 0) length = jQuery('.photolist input').length; + if(length == 0) length = 1; + jQuery('.photolist').append(''); + jQuery('.photolist').append(''); + insert_editor( "\n\n" + encodeURI('

    ' + desc + '

    ')); + } + return false; + } + + function image_selector() { + tb_remove(); + desc = jQuery('#this_photo_description').val(); + src = jQuery('#this_photo').val(); + pick(src, desc); + jQuery('#extra_fields').hide(); + jQuery('#extra_fields').html(''); + return false; + } + + jQuery(document).ready(function() { + jQuery('#extra_fields').html('

    Photo ()

    '); + jQuery('.close').click(function() { + jQuery('#extra_fields').hide(); + jQuery('#extra_fields').html(''); + }); + jQuery('.refresh').click(function() { + show('photo'); + }); + jQuery('#img_container').html(strtoappend); + jQuery('#photo_add_url').attr('href', '?ajax=photo_thickbox_url&height=200&width=500'); + tb_init('#extra_fields .thickbox'); + + + }); + + + > + + + <?php _e('Press This') ?> + + + + + + + + + +
    +
    +
    +
    +

    + + + + + + + + +
    + +
    +

    +
    +

    + + + + +

    + + +

    +
    +
    + +
    +

    +
    + +
    +
      + +
    +
    + +
    + +

    + + 0, 'name' => 'newcat_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => __('Parent category'), 'tab_index' => 3 ) ); ?> + + + +

    +
    +
    +
    + +
    +

    +
    +
    +

    + + + +

    +
    +
    + +
    +
    +
    +
    + +
    + +

    | |

    + + +
    +
    + +
    +
    + + + +
    +
      + +
    • + Add: +<?php _e('Insert an Image'); ?> + +
    • +
    • + <?php _e('Embed a Video'); ?> +
    • + +
    • + + + + +
      +
    • + +
    +
    +
    + +
    +
    +
    +
    +
    + + + + diff --git a/wp-admin/profile.php b/wp-admin/profile.php new file mode 100644 index 0000000..7c30cdf --- /dev/null +++ b/wp-admin/profile.php @@ -0,0 +1,19 @@ + diff --git a/wp-admin/revision.php b/wp-admin/revision.php new file mode 100644 index 0000000..9c3ce36 --- /dev/null +++ b/wp-admin/revision.php @@ -0,0 +1,220 @@ +post_parent ) ) + break; + if ( !$post = get_post( $revision->post_parent ) ) + break; + + if ( !constant('WP_POST_REVISIONS') && !wp_is_post_autosave( $revision ) ) // Revisions disabled and we're not looking at an autosave + break; + + check_admin_referer( "restore-post_$post->ID|$revision->ID" ); + + wp_restore_post_revision( $revision->ID ); + $redirect = add_query_arg( array( 'message' => 5, 'revision' => $revision->ID ), get_edit_post_link( $post->ID, 'url' ) ); + break; +case 'diff' : + if ( !$left_revision = get_post( $left ) ) + break; + if ( !$right_revision = get_post( $right ) ) + break; + + if ( !current_user_can( 'read_post', $left_revision->ID ) || !current_user_can( 'read_post', $right_revision->ID ) ) + break; + + // If we're comparing a revision to itself, redirect to the 'view' page for that revision or the edit page for that post + if ( $left_revision->ID == $right_revision->ID ) { + $redirect = get_edit_post_link( $left_revision->ID ); + include( 'js/revisions-js.php' ); + break; + } + + // Don't allow reverse diffs? + if ( strtotime($right_revision->post_modified_gmt) < strtotime($left_revision->post_modified_gmt) ) { + $redirect = add_query_arg( array( 'left' => $right, 'right' => $left ) ); + break; + } + + if ( $left_revision->ID == $right_revision->post_parent ) // right is a revision of left + $post =& $left_revision; + elseif ( $left_revision->post_parent == $right_revision->ID ) // left is a revision of right + $post =& $right_revision; + elseif ( $left_revision->post_parent == $right_revision->post_parent ) // both are revisions of common parent + $post = get_post( $left_revision->post_parent ); + else + break; // Don't diff two unrelated revisions + + if ( !constant('WP_POST_REVISIONS') ) { // Revisions disabled + if ( + // we're not looking at an autosave + ( !wp_is_post_autosave( $left_revision ) && !wp_is_post_autosave( $right_revision ) ) + || + // we're not comparing an autosave to the current post + ( $post->ID !== $left_revision->ID && $post->ID !== $right_revision->ID ) + ) + break; + } + + if ( + // They're the same + $left_revision->ID == $right_revision->ID + || + // Neither is a revision + ( !wp_get_post_revision( $left_revision->ID ) && !wp_get_post_revision( $right_revision->ID ) ) + ) + break; + + $post_title = '' . get_the_title() . ''; + $h2 = sprintf( __( 'Compare Revisions of “%1$s”' ), $post_title ); + + $left = $left_revision->ID; + $right = $right_revision->ID; + + $redirect = false; + break; +case 'view' : +default : + if ( !$revision = wp_get_post_revision( $revision_id ) ) + break; + if ( !$post = get_post( $revision->post_parent ) ) + break; + + if ( !current_user_can( 'read_post', $revision->ID ) || !current_user_can( 'read_post', $post->ID ) ) + break; + + if ( !constant('WP_POST_REVISIONS') && !wp_is_post_autosave( $revision ) ) // Revisions disabled and we're not looking at an autosave + break; + + $post_title = '' . get_the_title() . ''; + $revision_title = wp_post_revision_title( $revision, false ); + $h2 = sprintf( __( 'Post Revision for “%1$s” created on %2$s' ), $post_title, $revision_title ); + + // Sets up the diff radio buttons + $left = $revision->ID; + $right = $post->ID; + + $redirect = false; + break; +endswitch; + +if ( !$redirect && !in_array( $post->post_type, array( 'post', 'page' ) ) ) + $redirect = 'edit.php'; + +if ( $redirect ) { + wp_redirect( $redirect ); + exit; +} + +if ( 'page' == $post->post_type ) { + $submenu_file = 'edit-pages.php'; + $title = __( 'Page Revisions' ); +} else { + $submenu_file = 'edit.php'; + $title = __( 'Post Revisions' ); +} + +require_once( 'admin-header.php' ); + +?> + +
    + +

    + + + + + + + + + $field_title ) : + if ( 'diff' == $action ) { + $left_content = apply_filters( "_wp_post_revision_field_$field", $left_revision->$field, $field ); + $right_content = apply_filters( "_wp_post_revision_field_$field", $right_revision->$field, $field ); + if ( !$content = wp_text_diff( $left_content, $right_content ) ) + continue; // There is no difference between left and right + $identical = false; + } else { + add_filter( "_wp_post_revision_field_$field", 'htmlspecialchars' ); + $content = apply_filters( "_wp_post_revision_field_$field", $revision->$field, $field ); + } + ?> + + + + + + + + + + + + +
    + + +

    + +
    + +

    + + 'form-table', 'parent' => true, 'right' => $right, 'left' => $left ); +if ( !constant( 'WP_POST_REVISIONS' ) ) + $args['type'] = 'autosave'; + +wp_list_post_revisions( $post, $args ); + +?> + +
    + +The file 'wp-config.php' already exists. If you need to reset any of the configuration items in this file, please delete it first. You may try installing now.

    "); + +// Check if wp-config.php exists above the root directory but is not part of another install +if (file_exists(ABSPATH . '../wp-config.php') && ! file_exists(ABSPATH . '../wp-settings.php')) + wp_die("

    The file 'wp-config.php' already exists one level above your WordPress installation. If you need to reset any of the configuration items in this file, please delete it first. You may try installing now.

    "); + +if (isset($_GET['step'])) + $step = $_GET['step']; +else + $step = 0; + +/** + * Display setup wp-config.php file header. + * + * @ignore + * @since 2.3.0 + * @package WordPress + * @subpackage Installer_WP_Config + */ +function display_header() { + header( 'Content-Type: text/html; charset=utf-8' ); +?> + + + + +WordPress › Setup Configuration File + + + + +

    WordPress

    + + +

    Welcome to WordPress. Before getting started, we need some information on the database. You will need to know the following items before proceeding.

    +
      +
    1. Database name
    2. +
    3. Database username
    4. +
    5. Database password
    6. +
    7. Database host
    8. +
    9. Table prefix (if you want to run more than one WordPress in a single database)
    10. +
    +

    If for any reason this automatic file creation doesn't work, don't worry. All this does is fill in the database information to a configuration file. You may also simply open wp-config-sample.php in a text editor, fill in your information, and save it as wp-config.php.

    +

    In all likelihood, these items were supplied to you by your Web Host. If you do not have this information, then you will need to contact them before you can continue. If you’re all ready…

    + +

    Let’s go!

    + +
    +

    Below you should enter your database connection details. If you're not sure about these, contact your host.

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    The name of the database you want to run WP in.
    Your MySQL username
    ...and MySQL password.
    99% chance you won't need to change this value.
    If you want to run multiple WordPress installations in a single database, change this.
    +

    +
    +error) ) + wp_die($wpdb->error->get_error_message()); + + $handle = fopen(ABSPATH . 'wp-config.php', 'w'); + + foreach ($configFile as $line_num => $line) { + switch (substr($line,0,16)) { + case "define('DB_NAME'": + fwrite($handle, str_replace("putyourdbnamehere", $dbname, $line)); + break; + case "define('DB_USER'": + fwrite($handle, str_replace("'usernamehere'", "'$uname'", $line)); + break; + case "define('DB_PASSW": + fwrite($handle, str_replace("'yourpasswordhere'", "'$passwrd'", $line)); + break; + case "define('DB_HOST'": + fwrite($handle, str_replace("localhost", $dbhost, $line)); + break; + case '$table_prefix =': + fwrite($handle, str_replace('wp_', $prefix, $line)); + break; + default: + fwrite($handle, $line); + } + } + fclose($handle); + chmod(ABSPATH . 'wp-config.php', 0666); + + display_header(); +?> +

    All right sparky! You've made it through this part of the installation. WordPress can now communicate with your database. If you are ready, time now to…

    + +

    Run the install

    + + + diff --git a/wp-admin/sidebar.php b/wp-admin/sidebar.php new file mode 100644 index 0000000..62a375d --- /dev/null +++ b/wp-admin/sidebar.php @@ -0,0 +1,128 @@ + + + + +<?php bloginfo('name') ?> › <?php _e('Sidebar'); ?> + + + + +
    +
    + + + + + +

    ' . __('Post published.') . '

    '; +elseif ( 'c' == $_GET['a'] ) + echo '

    ' . __('Post saved.') . '

    '; +?> +

    + + +

    + +

    + + +

    + +
    + + +

    +
    + +

    + + + + +

    +
    + + + + diff --git a/wp-admin/theme-editor.php b/wp-admin/theme-editor.php new file mode 100644 index 0000000..c7343a7 --- /dev/null +++ b/wp-admin/theme-editor.php @@ -0,0 +1,233 @@ +'.__('You do not have sufficient permissions to edit templates for this blog.').'

    '); + + $newcontent = stripslashes($_POST['newcontent']); + $theme = urlencode($theme); + if (is_writeable($real_file)) { + //is_writable() not always reliable, check return value. see comments @ http://uk.php.net/is_writable + $f = fopen($real_file, 'w+'); + if ($f !== FALSE) { + fwrite($f, $newcontent); + fclose($f); + $location = "theme-editor.php?file=$file&theme=$theme&a=te"; + } else { + $location = "theme-editor.php?file=$file&theme=$theme"; + } + } else { + $location = "theme-editor.php?file=$file&theme=$theme"; + } + + $location = wp_kses_no_null($location); + $strip = array('%0d', '%0a', '%0D', '%0A'); + $location = _deep_replace($strip, $location); + header("Location: $location"); + exit(); + +break; + +default: + + if ( !current_user_can('edit_themes') ) + wp_die('

    '.__('You do not have sufficient permissions to edit themes for this blog.').'

    '); + + require_once('admin-header.php'); + + update_recently_edited($file); + + if ( !is_file($real_file) ) + $error = 1; + + if ( !$error && filesize($real_file) > 0 ) { + $f = fopen($real_file, 'r'); + $content = fread($f, filesize($real_file)); + + if ( '.php' == substr( $real_file, strrpos( $real_file, '.' ) ) ) { + $functions = wp_doc_link_parse( $content ); + + $docs_select = ''; + } + + $content = htmlspecialchars( $content ); + $codepress_lang = codepress_get_lang($real_file); + } + + ?> + +

    +$description (%s)" : "%s"; +?> +
    + +

    + +
    +
    + +
    +
    +
    + + + +
    +
    +
    +
    + +
    +

    + + +

    +
      +($template_show)" : "$description"; + $filedesc = ( $template_file == $file ) ? "$description ($template_show)" : $filedesc; + + // If we have two files of the same name prefer the one in the Template Directory + // This means that we display the correct files for child themes which overload Templates as well as Styles + if( array_key_exists($description, $template_mapping ) ) { + if ( false !== strpos( $template_file, $template_dir ) ) { + $template_mapping[ $description ] = array( $template_file, $filedesc ); + } + } else { + $template_mapping[ $description ] = array( $template_file, $filedesc ); + } + } + ksort( $template_mapping ); + while ( list( $template_sorted_key, list( $template_file, $filedesc ) ) = each( $template_mapping ) ) : + ?> +
    • &theme=">
    • + +
    +

    +
      +($style_show)" : "$description"; + $filedesc = ( $style_file == $file ) ? "$description ($style_show)" : $filedesc; + $template_mapping[ $description ] = array( $style_file, $filedesc ); + } + ksort( $template_mapping ); + while ( list( $template_sorted_key, list( $style_file, $filedesc ) ) = each( $template_mapping ) ) : + ?> +
    • &theme=">
    • + +
    + +
    + + +
    + +
    + + + +
    + +
    + + + +
    + + +
    + +

    +"; +?> +

    + +

    the Codex for more information.'); ?>

    + +
    +
    +

    ' . __('Oops, no such file exists! Double check the name and try again, merci.') . '

    '; + } +?> +
    + + +
    + +

    + +
      + $text ) { + $sep = ( end($tabs) != $text ) ? ' | ' : ''; + $class = ( $action == $tab ) ? ' class="current"' : ''; + $href = admin_url('theme-install.php?tab='. $action); + echo "\t\t
    • $text$sep
    • \n"; +} +?> +
    +
    + +
    +' . __('Themes give your WordPress style. Once a theme is installed, you may preview it, activate it or deactivate it here.') . '

    '; +if ( current_user_can('install_themes') ) { + $help .= '

    ' . sprintf(__('You can find additional themes for your site by using the new Theme Browser/Installer functionality or by browsing the WordPress Theme Directory directly and installing manually. To install a theme manually, upload its ZIP archive with the new uploader or copy its folder via FTP into your wp-content/themes directory.'), 'theme-install.php', 'theme-install.php?tab=upload' ) . '

    '; + $help .= '

    ' . __('Once a theme is uploaded, you should see it on this page.') . '

    ' ; +} + +add_contextual_help('themes', $help); + +add_thickbox(); +wp_enqueue_script( 'theme-preview' ); + +require_once('admin-header.php'); +?> + + +

    + +

    widgets settings page to configure them.'), admin_url('widgets.php') ); ?>

    +

    Visit site'), get_bloginfo('url') . '/'); ?>

    +

    + + +name]); + +uksort( $themes, "strnatcasecmp" ); +$theme_total = count( $themes ); +$per_page = 15; + +if ( isset( $_GET['pagenum'] ) ) + $page = absint( $_GET['pagenum'] ); + +if ( empty($page) ) + $page = 1; + +$start = $offset = ( $page - 1 ) * $per_page; + +$page_links = paginate_links( array( + 'base' => add_query_arg( 'pagenum', '%#%' ) . '#themenav', + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => ceil($theme_total / $per_page), + 'current' => $page +)); + +$themes = array_slice( $themes, $start, $per_page ); + +/** + * Check if there is an update for a theme available. + * + * Will display link, if there is an update available. + * + * @since 2.7.0 + * + * @param object $theme Theme data object. + * @return bool False if no valid info was passed. + */ +function theme_update_available( $theme ) { + static $themes_update; + if ( !isset($themes_update) ) + $themes_update = get_transient('update_themes'); + + if ( is_object($theme) && isset($theme->stylesheet) ) + $stylesheet = $theme->stylesheet; + elseif ( is_array($theme) && isset($theme['Stylesheet']) ) + $stylesheet = $theme['Stylesheet']; + else + return false; //No valid info passed. + + if ( isset($themes_update->response[ $stylesheet ]) ) { + $update = $themes_update->response[ $stylesheet ]; + $theme_name = is_object($theme) ? $theme->name : (is_array($theme) ? $theme['Name'] : ''); + $details_url = add_query_arg(array('TB_iframe' => 'true', 'width' => 1024, 'height' => 800), $update['url']); //Theme browser inside WP? replace this, Also, theme preview JS will override this on the available list. + $update_url = wp_nonce_url('update.php?action=upgrade-theme&theme=' . urlencode($stylesheet), 'upgrade-theme_' . $stylesheet); + $update_onclick = 'onclick="if ( confirm(\'' . esc_js( __("Upgrading this theme will lose any customizations you have made. 'Cancel' to stop, 'OK' to upgrade.") ) . '\') ) {return true;}return false;"'; + + if ( ! current_user_can('update_themes') ) + printf( '

    ' . __('There is a new version of %1$s available. View version %3$s Details.') . '

    ', $theme_name, $details_url, $update['new_version']); + else if ( empty($update->package) ) + printf( '

    ' . __('There is a new version of %1$s available. View version %3$s Details automatic upgrade unavailable for this theme.') . '

    ', $theme_name, $details_url, $update['new_version']); + else + printf( '

    ' . __('There is a new version of %1$s available. View version %3$s Details or upgrade automatically.') . '

    ', $theme_name, $details_url, $update['new_version'], $update_url, $update_onclick ); + } +} + +?> + +
    + +

    + +

    +
    +screenshot ) : ?> +<?php _e('Current theme preview'); ?> + +

    title, $ct->version, $ct->author) ; ?>

    +

    description; ?>

    +parent_theme) { ?> +

    %2$s. The stylesheet files are located in %3$s. %4$s uses templates from %5$s. Changes made to the templates will affect both themes.'), $ct->title, $ct->template_dir, $ct->stylesheet_dir, $ct->title, $ct->parent_theme); ?>

    + +

    %2$s.'), $ct->title, $ct->template_dir, $ct->stylesheet_dir); ?>

    + +tags ) : ?> +

    tags); ?>

    + + + +
    + +
    +

    +
    + + + + +
    +
    ' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( $start + 1 ), + number_format_i18n( min( $page * $per_page, $theme_total ) ), + number_format_i18n( $theme_total ), + $page_links +); echo $page_links_text; ?>
    +
    + + + + $cols ) { +?> + + $theme_name ) { + $class = array('available-theme'); + if ( $row == 1 ) $class[] = 'top'; + if ( $col == 1 ) $class[] = 'left'; + if ( $row == $rows ) $class[] = 'bottom'; + if ( $col == 3 ) $class[] = 'right'; +?> + + + + +
    + 1, 'template' => $template, 'stylesheet' => $stylesheet, 'TB_iframe' => 'true' ), $preview_link ) ); + $preview_text = esc_attr( sprintf( __('Preview of “%s”'), $title ) ); + $tags = $themes[$theme_name]['Tags']; + $thickbox_class = 'thickbox thickbox-preview'; + $activate_link = wp_nonce_url("themes.php?action=activate&template=".urlencode($template)."&stylesheet=".urlencode($stylesheet), 'switch-theme_' . $template); + $activate_text = esc_attr( sprintf( __('Activate “%s”'), $title ) ); + $actions = array(); + $actions[] = '' . __('Activate') . ''; + $actions[] = '' . __('Preview') . ''; + if ( current_user_can('update_themes') ) + $actions[] = '' . __('Delete') . ''; + $actions = apply_filters('theme_action_links', $actions, $themes[$theme_name]); + + $actions = implode ( ' | ', $actions ); +?> + + + + + +

    +

    + + +

    %2$s. The stylesheet files are located in %3$s. %4$s uses templates from %5$s. Changes made to the templates will affect both themes.'), $title, $template_dir, $stylesheet_dir, $title, $parent_theme); ?>

    + +

    %2$s.'), $title, $template_dir, $stylesheet_dir); ?>

    + + +

    + + + +
    + +

    + +
    + + +
    +$page_links_text
    "; ?> +
    +
    + + +
    + + + +

    +

    + + + + + + + + + + "; + } +?> +
    $title$description
    + + + + diff --git a/wp-admin/tools.php b/wp-admin/tools.php new file mode 100644 index 0000000..aa953ef --- /dev/null +++ b/wp-admin/tools.php @@ -0,0 +1,97 @@ + +
    +

    + +
    + +
    +

    +


    +

    +

    +

    +
    +
    + + + + + + + + +
    + + +
    +

    +

    + +

    +

    +

    +
    + +
    + diff --git a/wp-admin/update-core.php b/wp-admin/update-core.php new file mode 100644 index 0000000..5bd44c7 --- /dev/null +++ b/wp-admin/update-core.php @@ -0,0 +1,237 @@ +locale && 'en_US' == get_locale() ) ? + $update->current : sprintf("%s–%s", $update->current, $update->locale); + $current = false; + if ( !isset($update->response) || 'latest' == $update->response ) + $current = true; + $submit = __('Upgrade Automatically'); + $form_action = 'update-core.php?action=do-core-upgrade'; + if ( 'development' == $update->response ) { + $message = __('You are using a development version of WordPress. You can upgrade to the latest nightly build automatically or download the nightly build and install it manually:'); + $download = __('Download nightly build'); + } else { + if ( $current ) { + $message = sprintf(__('You have the latest version of WordPress. You do not need to upgrade. However, if you want to re-install version %s, you can do so automatically or download the package and re-install manually:'), $version_string); + $submit = __('Re-install Automatically'); + $form_action = 'update-core.php?action=do-core-reinstall'; + } else { + $message = sprintf(__('You can upgrade to version %s automatically or download the package and install it manually:'), $version_string); + } + $download = sprintf(__('Download %s'), $version_string); + } + + echo '

    '; + echo $message; + echo '

    '; + echo '
    '; + wp_nonce_field('upgrade-core'); + echo '

    '; + echo ' '; + echo ''; + echo ''; + echo '' . $download . ' '; + if ( 'en_US' != $update->locale ) + if ( !isset( $update->dismissed ) || !$update->dismissed ) + echo ''; + else + echo ''; + echo '

    '; + if ( 'en_US' != $update->locale && ( !isset($wp_local_package) || $wp_local_package != $update->locale ) ) + echo '

    '.__('This localized version contains both the translation and various other localization fixes. You can skip upgrading if you want to keep your current translation.').'

    '; + else if ( 'en_US' == $update->locale && get_locale() != 'en_US' ) { + echo '

    '.sprintf( __('You are about to install WordPress %s in English. There is a chance this upgrade will break your translation. You may prefer to wait for the localized version to be released.'), $update->current ).'

    '; + } + echo '
    '; + +} + +function dismissed_updates() { + $dismissed = get_core_updates( array( 'dismissed' => true, 'available' => false ) ); + if ( $dismissed ) { + + $show_text = esc_js(__('Show hidden updates')); + $hide_text = esc_js(__('Hide hidden updates')); + ?> + + '.__('Show hidden updates').'

    '; + echo '
      '; + foreach( (array) $dismissed as $update) { + echo '
    • '; + list_core_update( $update ); + echo '
    • '; + } + echo '
    '; + } +} + +/** + * Display upgrade WordPress for downloading latest or upgrading automatically form. + * + * @since 2.7 + * + * @return null + */ +function core_upgrade_preamble() { + $updates = get_core_updates(); +?> +
    + +

    +response) || 'latest' == $updates[0]->response ) { + echo '

    '; + _e('You have the latest version of WordPress. You do not need to upgrade'); + echo '

    '; + } else { + echo '

    '; + _e('Important: before upgrading, please backup your database and files.'); + echo '

    '; + + echo '

    '; + _e( 'There is a new version of WordPress available for upgrade' ); + echo '

    '; + } + + echo '
      '; + $alternate = true; + foreach( (array) $updates as $update ) { + $class = $alternate? ' class="alternate"' : ''; + $alternate = !$alternate; + echo "
    • "; + list_core_update( $update ); + echo '
    • '; + } + echo '
    '; + dismissed_updates(); + echo '
    '; +} + + +/** + * Upgrade WordPress core display. + * + * @since 2.7 + * + * @return null + */ +function do_core_upgrade( $reinstall = false ) { + global $wp_filesystem; + + if ( $reinstall ) + $url = 'update-core.php?action=do-core-reinstall'; + else + $url = 'update-core.php?action=do-core-upgrade'; + $url = wp_nonce_url($url, 'upgrade-core'); + if ( false === ($credentials = request_filesystem_credentials($url, '', false, ABSPATH)) ) + return; + + $version = isset( $_POST['version'] )? $_POST['version'] : false; + $locale = isset( $_POST['locale'] )? $_POST['locale'] : 'en_US'; + $update = find_core_update( $version, $locale ); + if ( !$update ) + return; + + + if ( ! WP_Filesystem($credentials, ABSPATH) ) { + request_filesystem_credentials($url, '', true, ABSPATH); //Failed to connect, Error and request again + return; + } +?> +
    + +

    +errors->get_error_code() ) { + foreach ( $wp_filesystem->errors->get_error_messages() as $message ) + show_message($message); + echo '
    '; + return; + } + + if ( $reinstall ) + $update->response = 'reinstall'; + + $result = wp_update_core($update, 'show_message'); + + if ( is_wp_error($result) ) { + show_message($result); + if ('up_to_date' != $result->get_error_code() ) + show_message( __('Installation Failed') ); + } else { + show_message( __('WordPress upgraded successfully') ); + } + echo ''; +} + +function do_dismiss_core_update() { + $version = isset( $_POST['version'] )? $_POST['version'] : false; + $locale = isset( $_POST['locale'] )? $_POST['locale'] : 'en_US'; + $update = find_core_update( $version, $locale ); + if ( !$update ) + return; + dismiss_core_update( $update ); + wp_redirect( wp_nonce_url('update-core.php?action=upgrade-core', 'upgrade-core') ); +} + +function do_undismiss_core_update() { + $version = isset( $_POST['version'] )? $_POST['version'] : false; + $locale = isset( $_POST['locale'] )? $_POST['locale'] : 'en_US'; + $update = find_core_update( $version, $locale ); + if ( !$update ) + return; + undismiss_core_update( $version, $locale ); + wp_redirect( wp_nonce_url('update-core.php?action=upgrade-core', 'upgrade-core') ); +} + +$action = isset($_GET['action']) ? $_GET['action'] : 'upgrade-core'; + +if ( 'upgrade-core' == $action ) { + wp_version_check(); + $title = __('Upgrade WordPress'); + $parent_file = 'tools.php'; + require_once('admin-header.php'); + core_upgrade_preamble(); + include('admin-footer.php'); +} elseif ( 'do-core-upgrade' == $action || 'do-core-reinstall' == $action ) { + check_admin_referer('upgrade-core'); + $title = __('Upgrade WordPress'); + $parent_file = 'tools.php'; + // do the (un)dismiss actions before headers, + // so that they can redirect + if ( isset( $_POST['dismiss'] ) ) + do_dismiss_core_update(); + elseif ( isset( $_POST['undismiss'] ) ) + do_undismiss_core_update(); + require_once('admin-header.php'); + if ( 'do-core-reinstall' == $action ) + $reinstall = true; + else + $reinstall = false; + if ( isset( $_POST['upgrade'] ) ) + do_core_upgrade($reinstall); + include('admin-footer.php'); + +}?> diff --git a/wp-admin/update-links.php b/wp-admin/update-links.php new file mode 100644 index 0000000..7b36416 --- /dev/null +++ b/wp-admin/update-links.php @@ -0,0 +1,56 @@ +get_col("SELECT link_url FROM $wpdb->links"); + +if ( !$link_uris ) + wp_die(__('No links')); + +$link_uris = urlencode( join( $link_uris, "\n" ) ); + +$query_string = "uris=$link_uris"; + +$options = array(); +$options['timeout'] = 30; +$options['body'] = $query_string; + +$options['headers'] = array( + 'content-type' => 'application/x-www-form-urlencoded; charset='.get_option('blog_charset'), + 'content-length' => strlen( $query_string ), +); + +$response = wp_remote_get('http://api.pingomatic.com/updated-batch/', $options); + +if ( is_wp_error( $response ) ) + wp_die(__('Request Failed.')); + +if ( $response['response']['code'] != 200 ) + wp_die(__('Request Failed.')); + +$body = str_replace(array("\r\n", "\r"), "\n", $response['body']); +$returns = explode("\n", $body); + +foreach ($returns as $return) { + $time = substr($return, 0, 19); + $uri = preg_replace('/(.*?) | (.*?)/', '$2', $return); + $wdpdb->update( $wpdb->links, array('link_updated' => $time), array('link_url' => $uri) ); +} + +?> diff --git a/wp-admin/update.php b/wp-admin/update.php new file mode 100644 index 0000000..f05de5d --- /dev/null +++ b/wp-admin/update.php @@ -0,0 +1,193 @@ +upgrade($plugin); + + include('admin-footer.php'); + + } elseif ('activate-plugin' == $action ) { + if ( ! current_user_can('update_plugins') ) + wp_die(__('You do not have sufficient permissions to update plugins for this blog.')); + + check_admin_referer('activate-plugin_' . $plugin); + if( ! isset($_GET['failure']) && ! isset($_GET['success']) ) { + wp_redirect( 'update.php?action=activate-plugin&failure=true&plugin=' . $plugin . '&_wpnonce=' . $_GET['_wpnonce'] ); + activate_plugin($plugin); + wp_redirect( 'update.php?action=activate-plugin&success=true&plugin=' . $plugin . '&_wpnonce=' . $_GET['_wpnonce'] ); + die(); + } + iframe_header( __('Plugin Reactivation'), true ); + if( isset($_GET['success']) ) + echo '

    ' . __('Plugin reactivated successfully.') . '

    '; + + if( isset($_GET['failure']) ){ + echo '

    ' . __('Plugin failed to reactivate due to a fatal error.') . '

    '; + error_reporting( E_ALL ^ E_NOTICE ); + @ini_set('display_errors', true); //Ensure that Fatal errors are displayed. + include(WP_PLUGIN_DIR . '/' . $plugin); + } + iframe_footer(); + } elseif ( 'install-plugin' == $action ) { + + if ( ! current_user_can('install_plugins') ) + wp_die(__('You do not have sufficient permissions to install plugins for this blog.')); + + include_once ABSPATH . 'wp-admin/includes/plugin-install.php'; //for plugins_api.. + + check_admin_referer('install-plugin_' . $plugin); + $api = plugins_api('plugin_information', array('slug' => $plugin, 'fields' => array('sections' => false) ) ); //Save on a bit of bandwidth. + + if ( is_wp_error($api) ) + wp_die($api); + + $title = __('Plugin Install'); + $parent_file = 'plugins.php'; + $submenu_file = 'plugin-install.php'; + require_once('admin-header.php'); + + $title = sprintf( __('Installing Plugin: %s'), $api->name . ' ' . $api->version ); + $nonce = 'install-plugin_' . $plugin; + $url = 'update.php?action=install-plugin&plugin=' . $plugin; + $type = 'web'; //Install plugin type, From Web or an Upload. + + $upgrader = new Plugin_Upgrader( new Plugin_Installer_Skin( compact('title', 'url', 'nonce', 'plugin', 'api') ) ); + $upgrader->install($api->download_link); + + include('admin-footer.php'); + + } elseif ( 'upload-plugin' == $action ) { + + if ( ! current_user_can('install_plugins') ) + wp_die(__('You do not have sufficient permissions to install plugins for this blog.')); + + check_admin_referer('plugin-upload'); + + $file_upload = new File_Upload_Upgrader('pluginzip', 'package'); + + $title = __('Upload Plugin'); + $parent_file = 'plugins.php'; + $submenu_file = 'plugin-install.php'; + require_once('admin-header.php'); + + $title = sprintf( __('Installing Plugin from uploaded file: %s'), basename( $file_upload->filename ) ); + $nonce = 'plugin-upload'; + $url = add_query_arg(array('package' => $file_upload->filename ), 'update.php?action=upload-plugin'); + $type = 'upload'; //Install plugin type, From Web or an Upload. + + $upgrader = new Plugin_Upgrader( new Plugin_Installer_Skin( compact('type', 'title', 'nonce', 'url') ) ); + $upgrader->install( $file_upload->package ); + + include('admin-footer.php'); + + } elseif ( 'upgrade-theme' == $action ) { + + if ( ! current_user_can('update_themes') ) + wp_die(__('You do not have sufficient permissions to update themes for this blog.')); + + check_admin_referer('upgrade-theme_' . $theme); + + add_thickbox(); + wp_enqueue_script('theme-preview'); + $title = __('Upgrade Theme'); + $parent_file = 'themes.php'; + $submenu_file = 'themes.php'; + require_once('admin-header.php'); + + $nonce = 'upgrade-theme_' . $theme; + $url = 'update.php?action=upgrade-theme&theme=' . $theme; + + $upgrader = new Theme_Upgrader( new Theme_Upgrader_Skin( compact('title', 'nonce', 'url', 'theme') ) ); + $upgrader->upgrade($theme); + + include('admin-footer.php'); + + } elseif ( 'install-theme' == $action ) { + + if ( ! current_user_can('install_themes') ) + wp_die(__('You do not have sufficient permissions to install themes for this blog.')); + + include_once ABSPATH . 'wp-admin/includes/theme-install.php'; //for themes_api.. + + check_admin_referer('install-theme_' . $theme); + $api = themes_api('theme_information', array('slug' => $theme, 'fields' => array('sections' => false) ) ); //Save on a bit of bandwidth. + + if ( is_wp_error($api) ) + wp_die($api); + + add_thickbox(); + wp_enqueue_script('theme-preview'); + $title = __('Install Themes'); + $parent_file = 'themes.php'; + $submenu_file = 'theme-install.php'; + require_once('admin-header.php'); + + $title = sprintf( __('Installing theme: %s'), $api->name . ' ' . $api->version ); + $nonce = 'install-theme_' . $theme; + $url = 'update.php?action=install-theme&theme=' . $theme; + $type = 'web'; //Install theme type, From Web or an Upload. + + $upgrader = new Theme_Upgrader( new Theme_Installer_Skin( compact('title', 'url', 'nonce', 'plugin', 'api') ) ); + $upgrader->install($api->download_link); + + include('admin-footer.php'); + + } elseif ( 'upload-theme' == $action ) { + + if ( ! current_user_can('install_themes') ) + wp_die(__('You do not have sufficient permissions to install themes for this blog.')); + + check_admin_referer('theme-upload'); + + $file_upload = new File_Upload_Upgrader('themezip', 'package'); + + $title = __('Upload Theme'); + $parent_file = 'themes.php'; + $submenu_file = 'theme-install.php'; + add_thickbox(); + wp_enqueue_script('theme-preview'); + require_once('admin-header.php'); + + $title = sprintf( __('Installing Theme from uploaded file: %s'), basename( $file_upload->filename ) ); + $nonce = 'theme-upload'; + $url = add_query_arg(array('package' => $file_upload->filename), 'update.php?action=upload-theme'); + $type = 'upload'; //Install plugin type, From Web or an Upload. + + $upgrader = new Theme_Upgrader( new Theme_Installer_Skin( compact('type', 'title', 'nonce', 'url') ) ); + $upgrader->install( $file_upload->package ); + + include('admin-footer.php'); + + } else { + do_action('update-custom_' . $action); + } +} \ No newline at end of file diff --git a/wp-admin/upgrade-functions.php b/wp-admin/upgrade-functions.php new file mode 100644 index 0000000..ca14a59 --- /dev/null +++ b/wp-admin/upgrade-functions.php @@ -0,0 +1,13 @@ + diff --git a/wp-admin/upgrade.php b/wp-admin/upgrade.php new file mode 100644 index 0000000..7c093d1 --- /dev/null +++ b/wp-admin/upgrade.php @@ -0,0 +1,95 @@ + + +> + + + <?php _e( 'WordPress › Upgrade' ); ?> + + + +

    WordPress

    + + + +

    +

    +

    + + +

    +

    +

    +

    + +

    +

    +

    + + + + + + diff --git a/wp-admin/upload.php b/wp-admin/upload.php new file mode 100644 index 0000000..61e1d16 --- /dev/null +++ b/wp-admin/upload.php @@ -0,0 +1,417 @@ +get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'post' OR post_type = 'page'"); + $all_att = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'attachment'"); + + $lost = array(); + foreach ( (array) $all_att as $att ) { + if ( $att->post_parent > 0 && ! in_array($att->post_parent, $all_posts) ) + $lost[] = $att->ID; + } + $_GET['detached'] = 1; + +} elseif ( isset($_GET['found_post_id']) && isset($_GET['media']) ) { + check_admin_referer('bulk-media'); + + if ( ! ( $parent_id = (int) $_GET['found_post_id'] ) ) + return; + + $parent = &get_post($parent_id); + if ( !current_user_can('edit_post', $parent_id) ) + wp_die( __('You are not allowed to edit this post.') ); + + $attach = array(); + foreach( (array) $_GET['media'] as $att_id ) { + $att_id = (int) $att_id; + + if ( !current_user_can('edit_post', $att_id) ) + continue; + + $attach[] = $att_id; + } + + if ( ! empty($attach) ) { + $attach = implode(',', $attach); + $attached = $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = 'attachment' AND ID IN ($attach)", $parent_id) ); + } + + if ( isset($attached) ) { + $location = 'upload.php'; + if ( $referer = wp_get_referer() ) { + if ( false !== strpos($referer, 'upload.php') ) + $location = $referer; + } + + $location = add_query_arg( array( 'detached' => 1, 'attached' => $attached ) , $location ); + wp_redirect($location); + exit; + } + +} elseif ( isset($_GET['action']) && isset($_GET['media']) && ( -1 != $_GET['action'] || -1 != $_GET['action2'] ) ) { + check_admin_referer('bulk-media'); + $doaction = ( -1 != $_GET['action'] ) ? $_GET['action'] : $_GET['action2']; + + if ( 'delete' == $doaction ) { + foreach( (array) $_GET['media'] as $post_id_del ) { + $post_del = & get_post($post_id_del); + + if ( !current_user_can('delete_post', $post_id_del) ) + wp_die( __('You are not allowed to delete this post.') ); + + if ( $post_del->post_type == 'attachment' ) + if ( ! wp_delete_attachment($post_id_del) ) + wp_die( __('Error in deleting...') ); + } + + $location = 'upload.php'; + if ( $referer = wp_get_referer() ) { + if ( false !== strpos($referer, 'upload.php') ) + $location = $referer; + } + + $location = add_query_arg('message', 2, $location); + $location = remove_query_arg('posted', $location); + wp_redirect($location); + exit; + } +} elseif ( isset($_GET['_wp_http_referer']) && ! empty($_GET['_wp_http_referer']) ) { + wp_redirect( remove_query_arg( array('_wp_http_referer', '_wpnonce'), stripslashes($_SERVER['REQUEST_URI']) ) ); + exit; +} + +$title = __('Media Library'); +$parent_file = 'upload.php'; + +if ( ! isset( $_GET['paged'] ) || $_GET['paged'] < 1 ) + $_GET['paged'] = 1; + +if ( isset($_GET['detached']) ) { + + if ( !empty($lost) ) { + $start = ( $_GET['paged'] - 1 ) * 50; + $page_links_total = ceil(count($lost) / 50); + $lost = implode(',', $lost); + + $orphans = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_type = 'attachment' AND ID IN ($lost) LIMIT $start, 50" ); + } else { + $start = ( $_GET['paged'] - 1 ) * 25; + $orphans = $wpdb->get_results( "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent < 1 LIMIT $start, 25" ); + $page_links_total = ceil($wpdb->get_var( "SELECT FOUND_ROWS()" ) / 25); + } + + $post_mime_types = array( + 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image (%s)', 'Images (%s)')), + 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio (%s)', 'Audio (%s)')), + 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video (%s)', 'Video (%s)')), + ); + $post_mime_types = apply_filters('post_mime_types', $post_mime_types); + + $avail_post_mime_types = get_available_post_mime_types('attachment'); + + if ( isset($_GET['post_mime_type']) && !array_intersect( (array) $_GET['post_mime_type'], array_keys($post_mime_types) ) ) + unset($_GET['post_mime_type']); + +} else { + list($post_mime_types, $avail_post_mime_types) = wp_edit_attachments_query(); +} + +wp_enqueue_script('media'); +require_once('admin-header.php'); ?> + + + + + +
    + +

    ' . __('Search results for “%s”') . '', esc_html( get_search_query() ) ); ?> +

    + + +

    + + + + +
    + +
    + +
    +
    +max_num_pages; + +$page_links = paginate_links( array( + 'base' => add_query_arg( 'paged', '%#%' ), + 'format' => '', + 'prev_text' => __('«'), + 'next_text' => __('»'), + 'total' => $page_links_total, + 'current' => $_GET['paged'] +)); + +if ( $page_links ) : ?> +
    ' . __( 'Displaying %s–%s of %s' ) . '%s', + number_format_i18n( ( $_GET['paged'] - 1 ) * $wp_query->query_vars['posts_per_page'] + 1 ), + number_format_i18n( min( $_GET['paged'] * $wp_query->query_vars['posts_per_page'], $wp_query->found_posts ) ), + number_format_i18n( $wp_query->found_posts ), + $page_links +); echo $page_links_text; ?>
    + + +
    + + + + +posts WHERE post_type = 'attachment' ORDER BY post_date DESC"; + + $arc_result = $wpdb->get_results( $arc_query ); + + $month_count = count($arc_result); + + if ( $month_count && !( 1 == $month_count && 0 == $arc_result[0]->mmonth ) ) : ?> + + + + + + + + + + + +
    + +
    +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + +ID) ); +?> + + + + + + + +post_date && 'date' == $column_name ) { + $t_time = $h_time = __('Unpublished'); + } else { + $t_time = get_the_time(__('Y/m/d g:i:s A')); + $m_time = $post->post_date; + $time = get_post_time( 'G', true ); + if ( ( abs($t_diff = time() - $time) ) < 86400 ) { + if ( $t_diff < 0 ) + $h_time = sprintf( __('%s from now'), human_time_diff( $time ) ); + else + $h_time = sprintf( __('%s ago'), human_time_diff( $time ) ); + } else { + $h_time = mysql2date(__('Y/m/d'), $m_time); + } + } ?> + + + + + + +
    ID, array(80, 60), true ) ) { ?> + +
    + ID))); ?> + +
    + ID) ) + $actions['edit'] = '' . __('Edit') . ''; + if ( current_user_can('delete_post', $post->ID) ) + $actions['delete'] = "ID) . "' onclick=\"if ( confirm('" . esc_js(sprintf( ('draft' == $post->post_status) ? __("You are about to delete this attachment '%s'\n 'Cancel' to stop, 'OK' to delete.") : __("You are about to delete this attachment '%s'\n 'Cancel' to stop, 'OK' to delete."), $post->post_title )) . "') ) { return true;}return false;\">" . __('Delete') . ""; + $actions['view'] = '' . __('View') . ''; + if ( current_user_can('edit_post', $post->ID) ) + $actions['attach'] = ''.__('Attach').''; + $actions = apply_filters( 'media_row_actions', $actions, $post ); + $action_count = count($actions); + $i = 0; + foreach ( $actions as $action => $link ) { + ++$i; + ( $i == $action_count ) ? $sep = '' : $sep = ' | '; + echo "$link$sep"; + } ?> +
    post_author); echo $author->display_name; ?>
    + + + +
    + +
    + +$page_links_text
    "; +?> + +
    + + +
    + +
    +
    + +
    + + + +ID; + } else { + wp_die(__('Invalid user ID.')); + } +} elseif ( !get_userdata($user_id) ) { + wp_die( __('Invalid user ID.') ); +} + +$all_post_caps = array('posts', 'pages'); +$user_can_edit = false; +foreach ( $all_post_caps as $post_cap ) + $user_can_edit |= current_user_can("edit_$post_cap"); + +/** + * Optional SSL preference that can be turned on by hooking to the 'personal_options' action. + * + * @since 2.7.0 + * + * @param object $user User data object + */ +function use_ssl_preference($user) { +?> + + + + + + + +
    +

    + +

    + +
    + + +
    +
      + get_error_messages() as $message ) + echo "
    • $message
    • "; + ?> +
    +
    + + +
    + +

    + +
    + + + + +

    + + +

    + +

    + + + + + + + + + 1 ) : ?> + + + + + + + + + + +
    + $color_info ): ?> +
    /> + + + colors as $html_color ): ?> + + + +
     
    + + +
    + +
    More information'); ?>
    + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

    + + + + + + + + + + + + + +

    +

    +
    +
    +

    +
    + + + +caps) > count($profileuser->roles) && apply_filters('additional_capabilities_display', true, $profileuser)): ?> +
    + + + + + +
    caps as $cap => $value) { + if(!$wp_roles->is_role($cap)) { + if($output != '') $output .= ', '; + $output .= $value ? $cap : "Denied: {$cap}"; + } + } + echo $output; + ?>
    + + +

    + + + +

    +
    +
    + diff --git a/wp-admin/user-new.php b/wp-admin/user-new.php new file mode 100644 index 0000000..9d14325 --- /dev/null +++ b/wp-admin/user-new.php @@ -0,0 +1,154 @@ + +
    + +

    + + +
    +
      + get_error_messages() as $err ) + echo "
    • $err
    • \n"; + ?> +
    +
    + + + +
    + get_error_messages() as $message ) + echo "

    $message

    "; + ?> +
    + +
    + +' . sprintf(__('Users can register themselves or you can manually create users here.'), site_url('wp-register.php')) . '

    '; + else + echo '

    ' . sprintf(__('Users cannot currently register themselves, but you can manually create users here.'), admin_url('options-general.php#users_can_register')) . '

    '; +?> +
    + + 'login', 'first_name' => 'firstname', 'last_name' => 'lastname', + 'email' => 'email', 'url' => 'uri', 'role' => 'role') as $post_field => $var ) { + $var = "new_user_$var"; + if ( ! isset($$var) ) + $$var = isset($_POST[$post_field]) ? stripslashes($_POST[$post_field]) : ''; +} +$new_user_send_password = !$_POST || isset($_POST['send_password']); +?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + +
    +
    +

    +
    +
    +

    + +

    +
    + +
    + diff --git a/wp-admin/users.php b/wp-admin/users.php new file mode 100644 index 0000000..758a592 --- /dev/null +++ b/wp-admin/users.php @@ -0,0 +1,403 @@ +'; +} elseif ( isset($_REQUEST['wp_http_referer']) ) { + $redirect = remove_query_arg(array('wp_http_referer', 'updated', 'delete_count'), stripslashes($_REQUEST['wp_http_referer'])); + $referer = ''; +} else { + $redirect = 'users.php'; + $referer = ''; +} + +switch ($doaction) { + +/* Bulk Dropdown menu Role changes */ +case 'promote': + check_admin_referer('bulk-users'); + + if (empty($_REQUEST['users'])) { + wp_redirect($redirect); + exit(); + } + + $editable_roles = get_editable_roles(); + if (!$editable_roles[$_REQUEST['new_role']]) + wp_die(__('You can’t give users that role.')); + + $userids = $_REQUEST['users']; + $update = 'promote'; + foreach($userids as $id) { + if ( ! current_user_can('edit_user', $id) ) + wp_die(__('You can’t edit that user.')); + // The new role of the current user must also have edit_users caps + if($id == $current_user->ID && !$wp_roles->role_objects[$_REQUEST['new_role']]->has_cap('edit_users')) { + $update = 'err_admin_role'; + continue; + } + + $user = new WP_User($id); + $user->set_role($_REQUEST['new_role']); + } + + wp_redirect(add_query_arg('update', $update, $redirect)); + exit(); + +break; + +case 'dodelete': + + check_admin_referer('delete-users'); + + if ( empty($_REQUEST['users']) ) { + wp_redirect($redirect); + exit(); + } + + if ( !current_user_can('delete_users') ) + wp_die(__('You can’t delete users.')); + + $userids = $_REQUEST['users']; + $update = 'del'; + $delete_count = 0; + + foreach ( (array) $userids as $id) { + if ( ! current_user_can('delete_user', $id) ) + wp_die(__('You can’t delete that user.')); + + if($id == $current_user->ID) { + $update = 'err_admin_del'; + continue; + } + switch($_REQUEST['delete_option']) { + case 'delete': + wp_delete_user($id); + break; + case 'reassign': + wp_delete_user($id, $_REQUEST['reassign_user']); + break; + } + ++$delete_count; + } + + $redirect = add_query_arg( array('delete_count' => $delete_count, 'update' => $update), $redirect); + wp_redirect($redirect); + exit(); + +break; + +case 'delete': + + check_admin_referer('bulk-users'); + + if ( empty($_REQUEST['users']) && empty($_REQUEST['user']) ) { + wp_redirect($redirect); + exit(); + } + + if ( !current_user_can('delete_users') ) + $errors = new WP_Error('edit_users', __('You can’t delete users.')); + + if ( empty($_REQUEST['users']) ) + $userids = array(intval($_REQUEST['user'])); + else + $userids = $_REQUEST['users']; + + include ('admin-header.php'); +?> +
    + + + +
    + +

    +

    +
      +ID ) { + echo "
    • " . sprintf(__('ID #%1s: %2s The current user will not be deleted.'), $id, $user->user_login) . "
    • \n"; + } else { + echo "
    • " . sprintf(__('ID #%1s: %2s'), $id, $user->user_login) . "
    • \n"; + $go_delete = true; + } + } + $all_logins = $wpdb->get_results("SELECT ID, user_login FROM $wpdb->users ORDER BY user_login"); + $user_dropdown = ''; + ?> +
    + +

    +
      +
    • +
    • + '.__('Attribute all posts and links to:')." $user_dropdown"; ?>
    • +
    + +

    + +

    + +
    +
    +

    ' . sprintf(_n('%s user deleted', '%s users deleted', $delete_count), $delete_count) . '

    '; + break; + case 'add': + $messages[] = '

    ' . __('New user created.') . '

    '; + break; + case 'promote': + $messages[] = '

    ' . __('Changed roles.') . '

    '; + break; + case 'err_admin_role': + $messages[] = '

    ' . __('The current user’s role must have user editing capabilities.') . '

    '; + $messages[] = '

    ' . __('Other user roles have been changed.') . '

    '; + break; + case 'err_admin_del': + $messages[] = '

    ' . __('You can’t delete the current user.') . '

    '; + $messages[] = '

    ' . __('Other users have been deleted.') . '

    '; + break; + } + endif; ?> + + +
    +
      + get_error_messages() as $err ) + echo "
    • $err
    • \n"; + ?> +
    +
    + + +
    + +

    ' . __('Search results for “%s”') . '', esc_html( $_GET['usersearch'] ) ); ?> +

    + +
    +
    +
      +meta_value); + foreach ( (array) $b_roles as $b_role => $val ) { + if ( !isset($avail_roles[$b_role]) ) + $avail_roles[$b_role] = 0; + $avail_roles[$b_role]++; + } +} +unset($users_of_blog); + +$current_role = false; +$class = empty($role) ? ' class="current"' : ''; +$role_links[] = "
    • " . sprintf( _nx( 'All (%s)', 'All (%s)', $total_users, 'users' ), number_format_i18n( $total_users ) ) . ''; +foreach ( $wp_roles->get_names() as $this_role => $name ) { + if ( !isset($avail_roles[$this_role]) ) + continue; + + $class = ''; + + if ( $this_role == $role ) { + $current_role = $role; + $class = ' class="current"'; + } + + $name = translate_user_role( $name ); + /* translators: User role name with count */ + $name = sprintf( __('%1$s (%2$s)'), $name, $avail_roles[$this_role] ); + $role_links[] = "
    • $name"; +} +echo implode( " |
    • \n", $role_links) . ''; +unset($role_links); +?> +
    +
    +
    + +
    + +
    + +
    +
    + +results_are_paged() ) : ?> +
    page_links(); ?>
    + + +
    + + + + + +
    + +
    +
    + + search_errors ) ) : ?> +
    +
      + search_errors->get_error_messages() as $message ) + echo "
    • $message
    • "; + ?> +
    +
    + + + +get_results() ) : ?> + + is_search() ) : ?> +

    + + + + + + + + + + + + + + + + +get_results() as $userid ) { + $user_object = new WP_User($userid); + $roles = $user_object->roles; + $role = array_shift($roles); + + $style = ( ' class="alternate"' == $style ) ? '' : ' class="alternate"'; + echo "\n\t" . user_row($user_object, $style, $role); +} +?> + +
    + +
    + +results_are_paged() ) : ?> +
    page_links(); ?>
    + + +
    + + +
    + +
    +
    + + + +
    +
    + + 'user_login', 'first_name' => 'user_firstname', 'last_name' => 'user_lastname', 'email' => 'user_email', 'url' => 'user_uri', 'role' => 'user_role') as $formpost => $var ) { + $var = 'new_' . $var; + $$var = isset($_REQUEST[$formpost]) ? esc_attr(stripslashes($_REQUEST[$formpost])) : ''; + } + unset($name); +?> + +
    + diff --git a/wp-admin/widgets.php b/wp-admin/widgets.php new file mode 100644 index 0000000..4ead317 --- /dev/null +++ b/wp-admin/widgets.php @@ -0,0 +1,392 @@ + __('Inactive Widgets'), + 'id' => 'wp_inactive_widgets', + 'before_widget' => '', + 'after_widget' => '', + 'before_title' => '', + 'after_title' => '', +)); + +// These are the widgets grouped by sidebar +$sidebars_widgets = wp_get_sidebars_widgets(); +if ( empty( $sidebars_widgets ) ) + $sidebars_widgets = wp_get_widget_defaults(); + +// look for "lost" widgets, this has to run at least on each theme change +function retrieve_widgets() { + global $wp_registered_widget_updates, $wp_registered_sidebars, $sidebars_widgets, $wp_registered_widgets; + + $_sidebars_widgets = array(); + $sidebars = array_keys($wp_registered_sidebars); + + unset( $sidebars_widgets['array_version'] ); + + $old = array_keys($sidebars_widgets); + sort($old); + sort($sidebars); + + if ( $old == $sidebars ) + return; + + // Move the known-good ones first + foreach ( $sidebars as $id ) { + if ( array_key_exists( $id, $sidebars_widgets ) ) { + $_sidebars_widgets[$id] = $sidebars_widgets[$id]; + unset($sidebars_widgets[$id], $sidebars[$id]); + } + } + + // if new theme has less sidebars than the old theme + if ( !empty($sidebars_widgets) ) { + foreach ( $sidebars_widgets as $lost => $val ) { + if ( is_array($val) ) + $_sidebars_widgets['wp_inactive_widgets'] = array_merge( (array) $_sidebars_widgets['wp_inactive_widgets'], $val ); + } + } + + // discard invalid, theme-specific widgets from sidebars + $shown_widgets = array(); + foreach ( $_sidebars_widgets as $sidebar => $widgets ) { + if ( !is_array($widgets) ) + continue; + + $_widgets = array(); + foreach ( $widgets as $widget ) { + if ( isset($wp_registered_widgets[$widget]) ) + $_widgets[] = $widget; + } + $_sidebars_widgets[$sidebar] = $_widgets; + $shown_widgets = array_merge($shown_widgets, $_widgets); + } + + $sidebars_widgets = $_sidebars_widgets; + unset($_sidebars_widgets, $_widgets); + + // find hidden/lost multi-widget instances + $lost_widgets = array(); + foreach ( $wp_registered_widgets as $key => $val ) { + if ( in_array($key, $shown_widgets, true) ) + continue; + + $number = preg_replace('/.+?-([0-9]+)$/', '$1', $key); + + if ( 2 > (int) $number ) + continue; + + $lost_widgets[] = $key; + } + + $sidebars_widgets['wp_inactive_widgets'] = array_merge($lost_widgets, (array) $sidebars_widgets['wp_inactive_widgets']); + wp_set_sidebars_widgets($sidebars_widgets); +} +retrieve_widgets(); + +if ( count($wp_registered_sidebars) == 1 ) { + // If only "wp_inactive_widgets" is defined the theme has no sidebars, die. + require_once( 'admin-header.php' ); +?> + +
    + +

    +
    +

    +
    +

    follow these instructions.' ); ?>

    +
    + + $val ) { + if ( is_array($val) && preg_match('/__i__|%i%/', key($val)) ) { + $_POST[$key] = array( $number => array_shift($val) ); + break; + } + } + } + + $sidebar_id = $_POST['sidebar']; + $position = isset($_POST[$sidebar_id . '_position']) ? (int) $_POST[$sidebar_id . '_position'] - 1 : 0; + + $id_base = $_POST['id_base']; + $sidebar = isset($sidebars_widgets[$sidebar_id]) ? $sidebars_widgets[$sidebar_id] : array(); + + // delete + if ( isset($_POST['removewidget']) && $_POST['removewidget'] ) { + + if ( !in_array($widget_id, $sidebar, true) ) { + wp_redirect('widgets.php?error=0'); + exit; + } + + $sidebar = array_diff( $sidebar, array($widget_id) ); + $_POST = array('sidebar' => $sidebar_id, 'widget-' . $id_base => array(), 'the-widget-id' => $widget_id, 'delete_widget' => '1'); + } + + $_POST['widget-id'] = $sidebar; + + foreach ( (array) $wp_registered_widget_updates as $name => $control ) { + if ( $name != $id_base || !is_callable($control['callback']) ) + continue; + + ob_start(); + call_user_func_array( $control['callback'], $control['params'] ); + ob_end_clean(); + + break; + } + + $sidebars_widgets[$sidebar_id] = $sidebar; + + // remove old position + if ( !isset($_POST['delete_widget']) ) { + foreach ( $sidebars_widgets as $key => $sb ) { + if ( is_array($sb) ) + $sidebars_widgets[$key] = array_diff( $sb, array($widget_id) ); + } + array_splice( $sidebars_widgets[$sidebar_id], $position, 0, $widget_id ); + } + + wp_set_sidebars_widgets($sidebars_widgets); + wp_redirect('widgets.php?message=0'); + exit; +} + +// Output the widget form without js +if ( isset($_GET['editwidget']) && $_GET['editwidget'] ) { + $widget_id = $_GET['editwidget']; + + if ( isset($_GET['addnew']) ) { + // Default to the first sidebar + $sidebar = array_shift( $keys = array_keys($wp_registered_sidebars) ); + + if ( isset($_GET['base']) && isset($_GET['num']) ) { // multi-widget + // Copy minimal info from an existing instance of this widget to a new instance + foreach ( $wp_registered_widget_controls as $control ) { + if ( $_GET['base'] === $control['id_base'] ) { + $control_callback = $control['callback']; + $multi_number = (int) $_GET['num']; + $control['params'][0]['number'] = -1; + $widget_id = $control['id'] = $control['id_base'] . '-' . $multi_number; + $wp_registered_widget_controls[$control['id']] = $control; + break; + } + } + } + } + + if ( isset($wp_registered_widget_controls[$widget_id]) && !isset($control) ) { + $control = $wp_registered_widget_controls[$widget_id]; + $control_callback = $control['callback']; + } elseif ( !isset($wp_registered_widget_controls[$widget_id]) && isset($wp_registered_widgets[$widget_id]) ) { + $name = esc_html( strip_tags($wp_registered_widgets[$widget_id]['name']) ); + } + + if ( !isset($name) ) + $name = esc_html( strip_tags($control['name']) ); + + if ( !isset($sidebar) ) + $sidebar = isset($_GET['sidebar']) ? $_GET['sidebar'] : 'wp_inactive_widgets'; + + if ( !isset($multi_number) ) + $multi_number = isset($control['params'][0]['number']) ? $control['params'][0]['number'] : ''; + + $id_base = isset($control['id_base']) ? $control['id_base'] : $control['id']; + + // show the widget form + $width = ' style="width:' . max($control['width'], 350) . 'px"'; + $key = isset($_GET['key']) ? (int) $_GET['key'] : 0; + + require_once( 'admin-header.php' ); ?> +
    + +

    +
    > +

    + +
    +
    +' . __('There are no options for this widget.') . "

    \n"; ?> +
    + +

    +
    + + $sbvalue ) { + echo "\t\t\n"; + } ?> +
    "; + if ( 'wp_inactive_widgets' == $sbname ) { + echo ' '; + } else { + if ( !isset($sidebars_widgets[$sbname]) || !is_array($sidebars_widgets[$sbname]) ) { + $j = 1; + } else { + $j = count($sidebars_widgets[$sbname]); + if ( isset($_GET['addnew']) || !in_array($widget_id, $sidebars_widgets[$sbname], true) ) + $j++; + } + $selected = ''; + echo "\t\t\n"; + } + echo "
    +
    + +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + +
    + +

    + + +

    + + +

    + + +
    +
    +
    + +
    +

    +
    + +
    +
    +
    +
    +
    + +
    + +
    +

    + +
    +
    +
    +
    +
    + +
    +
    + $registered_sidebar ) { + if ( 'wp_inactive_widgets' == $sidebar ) + continue; + $closed = $i ? ' closed' : ''; ?> +
    + + +
    + +
    +
    +
    + +
    +
    +
    + + + * @author Modified by Dougal Campbell + * @version 1.0.5-dc + */ + +/** + * WordPress is handling an Atom Publishing Protocol request. + * + * @var bool + */ +define('APP_REQUEST', true); + +/** Set up WordPress environment */ +require_once('./wp-load.php'); + +/** Post Template API */ +require_once(ABSPATH . WPINC . '/post-template.php'); + +/** Atom Publishing Protocol Class */ +require_once(ABSPATH . WPINC . '/atomlib.php'); + +/** Feed Handling API */ +require_once(ABSPATH . WPINC . '/feed.php'); + +/** Admin Image API for metadata updating */ +require_once(ABSPATH . '/wp-admin/includes/image.php'); + +$_SERVER['PATH_INFO'] = preg_replace( '/.*\/wp-app\.php/', '', $_SERVER['REQUEST_URI'] ); + +/** + * Whether to enable Atom Publishing Protocol Logging. + * + * @name app_logging + * @var int|bool + */ +$app_logging = 0; + +/** + * Whether to always authenticate user. Permanently set to true. + * + * @name always_authenticate + * @var int|bool + * @todo Should be an option somewhere + */ +$always_authenticate = 1; + +/** + * Writes logging info to a file. + * + * @since 2.2.0 + * @uses $app_logging + * @package WordPress + * @subpackage Logging + * + * @param string $label Type of logging + * @param string $msg Information describing logging reason. + */ +function log_app($label,$msg) { + global $app_logging; + if ($app_logging) { + $fp = fopen( 'wp-app.log', 'a+'); + $date = gmdate( 'Y-m-d H:i:s' ); + fwrite($fp, "\n\n$date - $label\n$msg\n"); + fclose($fp); + } +} + +if ( !function_exists('wp_set_current_user') ) : +/** + * @ignore + */ +function wp_set_current_user($id, $name = '') { + global $current_user; + + if ( isset($current_user) && ($id == $current_user->ID) ) + return $current_user; + + $current_user = new WP_User($id, $name); + + return $current_user; +} +endif; + +/** + * Filter to add more post statuses. + * + * @since 2.2.0 + * + * @param string $where SQL statement to filter. + * @return string Filtered SQL statement with added post_status for where clause. + */ +function wa_posts_where_include_drafts_filter($where) { + $where = str_replace("post_status = 'publish'","post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'inherit'", $where); + return $where; + +} +add_filter('posts_where', 'wa_posts_where_include_drafts_filter'); + +/** + * WordPress AtomPub API implementation. + * + * @package WordPress + * @subpackage Publishing + * @since 2.2.0 + */ +class AtomServer { + + /** + * ATOM content type. + * + * @since 2.2.0 + * @var string + */ + var $ATOM_CONTENT_TYPE = 'application/atom+xml'; + + /** + * Categories ATOM content type. + * + * @since 2.2.0 + * @var string + */ + var $CATEGORIES_CONTENT_TYPE = 'application/atomcat+xml'; + + /** + * Service ATOM content type. + * + * @since 2.3.0 + * @var string + */ + var $SERVICE_CONTENT_TYPE = 'application/atomsvc+xml'; + + /** + * ATOM XML namespace. + * + * @since 2.3.0 + * @var string + */ + var $ATOM_NS = 'http://www.w3.org/2005/Atom'; + + /** + * ATOMPUB XML namespace. + * + * @since 2.3.0 + * @var string + */ + var $ATOMPUB_NS = 'http://www.w3.org/2007/app'; + + /** + * Entries path. + * + * @since 2.2.0 + * @var string + */ + var $ENTRIES_PATH = "posts"; + + /** + * Categories path. + * + * @since 2.2.0 + * @var string + */ + var $CATEGORIES_PATH = "categories"; + + /** + * Media path. + * + * @since 2.2.0 + * @var string + */ + var $MEDIA_PATH = "attachments"; + + /** + * Entry path. + * + * @since 2.2.0 + * @var string + */ + var $ENTRY_PATH = "post"; + + /** + * Service path. + * + * @since 2.2.0 + * @var string + */ + var $SERVICE_PATH = "service"; + + /** + * Media single path. + * + * @since 2.2.0 + * @var string + */ + var $MEDIA_SINGLE_PATH = "attachment"; + + /** + * ATOMPUB parameters. + * + * @since 2.2.0 + * @var array + */ + var $params = array(); + + /** + * Supported ATOMPUB media types. + * + * @since 2.3.0 + * @var array + */ + var $media_content_types = array('image/*','audio/*','video/*'); + + /** + * ATOMPUB content type(s). + * + * @since 2.2.0 + * @var array + */ + var $atom_content_types = array('application/atom+xml'); + + /** + * ATOMPUB methods. + * + * @since 2.2.0 + * @var unknown_type + */ + var $selectors = array(); + + /** + * Whether to do output. + * + * Support for head. + * + * @since 2.2.0 + * @var bool + */ + var $do_output = true; + + /** + * PHP4 constructor - Sets up object properties. + * + * @since 2.2.0 + * @return AtomServer + */ + function AtomServer() { + + $this->script_name = array_pop(explode('/',$_SERVER['SCRIPT_NAME'])); + $this->app_base = get_bloginfo('url') . '/' . $this->script_name . '/'; + if ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) { + $this->app_base = preg_replace( '/^http:\/\//', 'https://', $this->app_base ); + } + + $this->selectors = array( + '@/service$@' => + array('GET' => 'get_service'), + '@/categories$@' => + array('GET' => 'get_categories_xml'), + '@/post/(\d+)$@' => + array('GET' => 'get_post', + 'PUT' => 'put_post', + 'DELETE' => 'delete_post'), + '@/posts/?(\d+)?$@' => + array('GET' => 'get_posts', + 'POST' => 'create_post'), + '@/attachments/?(\d+)?$@' => + array('GET' => 'get_attachment', + 'POST' => 'create_attachment'), + '@/attachment/file/(\d+)$@' => + array('GET' => 'get_file', + 'PUT' => 'put_file', + 'DELETE' => 'delete_file'), + '@/attachment/(\d+)$@' => + array('GET' => 'get_attachment', + 'PUT' => 'put_attachment', + 'DELETE' => 'delete_attachment'), + ); + } + + /** + * Handle ATOMPUB request. + * + * @since 2.2.0 + */ + function handle_request() { + global $always_authenticate; + + if( !empty( $_SERVER['ORIG_PATH_INFO'] ) ) + $path = $_SERVER['ORIG_PATH_INFO']; + else + $path = $_SERVER['PATH_INFO']; + + $method = $_SERVER['REQUEST_METHOD']; + + log_app('REQUEST',"$method $path\n================"); + + $this->process_conditionals(); + //$this->process_conditionals(); + + // exception case for HEAD (treat exactly as GET, but don't output) + if($method == 'HEAD') { + $this->do_output = false; + $method = 'GET'; + } + + // redirect to /service in case no path is found. + if(strlen($path) == 0 || $path == '/') { + $this->redirect($this->get_service_url()); + } + + // check to see if AtomPub is enabled + if( !get_option( 'enable_app' ) ) + $this->forbidden( sprintf( __( 'AtomPub services are disabled on this blog. An admin user can enable them at %s' ), admin_url('options-writing.php') ) ); + + // dispatch + foreach($this->selectors as $regex => $funcs) { + if(preg_match($regex, $path, $matches)) { + if(isset($funcs[$method])) { + + // authenticate regardless of the operation and set the current + // user. each handler will decide if auth is required or not. + if(!$this->authenticate()) { + if ($always_authenticate) { + $this->auth_required('Credentials required.'); + } + } + + array_shift($matches); + call_user_func_array(array(&$this,$funcs[$method]), $matches); + exit(); + } else { + // only allow what we have handlers for... + $this->not_allowed(array_keys($funcs)); + } + } + } + + // oops, nothing found + $this->not_found(); + } + + /** + * Retrieve XML for ATOMPUB service. + * + * @since 2.2.0 + */ + function get_service() { + log_app('function','get_service()'); + + if( !current_user_can( 'edit_posts' ) ) + $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) ); + + $entries_url = esc_attr($this->get_entries_url()); + $categories_url = esc_attr($this->get_categories_url()); + $media_url = esc_attr($this->get_attachments_url()); + foreach ($this->media_content_types as $med) { + $accepted_media_types = $accepted_media_types . "" . $med . ""; + } + $atom_prefix="atom"; + $atom_blogname=get_bloginfo('name'); + $service_doc = << + + <$atom_prefix:title>$atom_blogname Workspace + + <$atom_prefix:title>$atom_blogname Posts + $this->ATOM_CONTENT_TYPE;type=entry + + + + <$atom_prefix:title>$atom_blogname Media + $accepted_media_types + + + + +EOD; + + $this->output($service_doc, $this->SERVICE_CONTENT_TYPE); + } + + /** + * Retrieve categories list in XML format. + * + * @since 2.2.0 + */ + function get_categories_xml() { + log_app('function','get_categories_xml()'); + + if( !current_user_can( 'edit_posts' ) ) + $this->auth_required( __( 'Sorry, you do not have the right to access this blog.' ) ); + + $home = esc_attr(get_bloginfo_rss('home')); + + $categories = ""; + $cats = get_categories("hierarchical=0&hide_empty=0"); + foreach ((array) $cats as $cat) { + $categories .= " name) . "\" />\n"; +} + $output = << + $categories + +EOD; + $this->output($output, $this->CATEGORIES_CONTENT_TYPE); +} + + /** + * Create new post. + * + * @since 2.2.0 + */ + function create_post() { + global $blog_id, $user_ID; + $this->get_accepted_content_type($this->atom_content_types); + + $parser = new AtomParser(); + if(!$parser->parse()) { + $this->client_error(); + } + + $entry = array_pop($parser->feed->entries); + + log_app('Received entry:', print_r($entry,true)); + + $catnames = array(); + foreach($entry->categories as $cat) + array_push($catnames, $cat["term"]); + + $wp_cats = get_categories(array('hide_empty' => false)); + + $post_category = array(); + + foreach($wp_cats as $cat) { + if(in_array($cat->name, $catnames)) + array_push($post_category, $cat->term_id); + } + + $publish = (isset($entry->draft) && trim($entry->draft) == 'yes') ? false : true; + + $cap = ($publish) ? 'publish_posts' : 'edit_posts'; + + if(!current_user_can($cap)) + $this->auth_required(__('Sorry, you do not have the right to edit/publish new posts.')); + + $blog_ID = (int ) $blog_id; + $post_status = ($publish) ? 'publish' : 'draft'; + $post_author = (int) $user_ID; + $post_title = $entry->title[1]; + $post_content = $entry->content[1]; + $post_excerpt = $entry->summary[1]; + $pubtimes = $this->get_publish_time($entry->published); + $post_date = $pubtimes[0]; + $post_date_gmt = $pubtimes[1]; + + if ( isset( $_SERVER['HTTP_SLUG'] ) ) + $post_name = $_SERVER['HTTP_SLUG']; + + $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_name'); + + $this->escape($post_data); + log_app('Inserting Post. Data:', print_r($post_data,true)); + + $postID = wp_insert_post($post_data); + if ( is_wp_error( $postID ) ) + $this->internal_error($postID->get_error_message()); + + if (!$postID) + $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.')); + + // getting warning here about unable to set headers + // because something in the cache is printing to the buffer + // could we clean up wp_set_post_categories or cache to not print + // this could affect our ability to send back the right headers + @wp_set_post_categories($postID, $post_category); + + do_action( 'atompub_create_post', $postID, $entry ); + + $output = $this->get_entry($postID); + + log_app('function',"create_post($postID)"); + $this->created($postID, $output); + } + + /** + * Retrieve post. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function get_post($postID) { + global $entry; + + if( !current_user_can( 'edit_post', $postID ) ) + $this->auth_required( __( 'Sorry, you do not have the right to access this post.' ) ); + + $this->set_current_entry($postID); + $output = $this->get_entry($postID); + log_app('function',"get_post($postID)"); + $this->output($output); + + } + + /** + * Update post. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function put_post($postID) { + // checked for valid content-types (atom+xml) + // quick check and exit + $this->get_accepted_content_type($this->atom_content_types); + + $parser = new AtomParser(); + if(!$parser->parse()) { + $this->bad_request(); + } + + $parsed = array_pop($parser->feed->entries); + + log_app('Received UPDATED entry:', print_r($parsed,true)); + + // check for not found + global $entry; + $this->set_current_entry($postID); + + if(!current_user_can('edit_post', $entry['ID'])) + $this->auth_required(__('Sorry, you do not have the right to edit this post.')); + + $publish = (isset($parsed->draft) && trim($parsed->draft) == 'yes') ? false : true; + $post_status = ($publish) ? 'publish' : 'draft'; + + extract($entry); + + $post_title = $parsed->title[1]; + $post_content = $parsed->content[1]; + $post_excerpt = $parsed->summary[1]; + $pubtimes = $this->get_publish_time($entry->published); + $post_date = $pubtimes[0]; + $post_date_gmt = $pubtimes[1]; + $pubtimes = $this->get_publish_time($parsed->updated); + $post_modified = $pubtimes[0]; + $post_modified_gmt = $pubtimes[1]; + + $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt'); + $this->escape($postdata); + + $result = wp_update_post($postdata); + + if (!$result) { + $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.')); + } + + do_action( 'atompub_put_post', $ID, $parsed ); + + log_app('function',"put_post($postID)"); + $this->ok(); + } + + /** + * Remove post. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function delete_post($postID) { + + // check for not found + global $entry; + $this->set_current_entry($postID); + + if(!current_user_can('edit_post', $postID)) { + $this->auth_required(__('Sorry, you do not have the right to delete this post.')); + } + + if ($entry['post_type'] == 'attachment') { + $this->delete_attachment($postID); + } else { + $result = wp_delete_post($postID); + + if (!$result) { + $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.')); + } + + log_app('function',"delete_post($postID)"); + $this->ok(); + } + + } + + /** + * Retrieve attachment. + * + * @since 2.2.0 + * + * @param int $postID Optional. Post ID. + */ + function get_attachment($postID = null) { + if( !current_user_can( 'upload_files' ) ) + $this->auth_required( __( 'Sorry, you do not have permission to upload files.' ) ); + + if (!isset($postID)) { + $this->get_attachments(); + } else { + $this->set_current_entry($postID); + $output = $this->get_entry($postID, 'attachment'); + log_app('function',"get_attachment($postID)"); + $this->output($output); + } + } + + /** + * Create new attachment. + * + * @since 2.2.0 + */ + function create_attachment() { + + $type = $this->get_accepted_content_type(); + + if(!current_user_can('upload_files')) + $this->auth_required(__('You do not have permission to upload files.')); + + $fp = fopen("php://input", "rb"); + $bits = null; + while(!feof($fp)) { + $bits .= fread($fp, 4096); + } + fclose($fp); + + $slug = ''; + if ( isset( $_SERVER['HTTP_SLUG'] ) ) + $slug = sanitize_file_name( $_SERVER['HTTP_SLUG'] ); + elseif ( isset( $_SERVER['HTTP_TITLE'] ) ) + $slug = sanitize_file_name( $_SERVER['HTTP_TITLE'] ); + elseif ( empty( $slug ) ) // just make a random name + $slug = substr( md5( uniqid( microtime() ) ), 0, 7); + $ext = preg_replace( '|.*/([a-z0-9]+)|', '$1', $_SERVER['CONTENT_TYPE'] ); + $slug = "$slug.$ext"; + $file = wp_upload_bits( $slug, NULL, $bits); + + log_app('wp_upload_bits returns:',print_r($file,true)); + + $url = $file['url']; + $file = $file['file']; + + do_action('wp_create_file_in_uploads', $file); // replicate + + // Construct the attachment array + $attachment = array( + 'post_title' => $slug, + 'post_content' => $slug, + 'post_status' => 'attachment', + 'post_parent' => 0, + 'post_mime_type' => $type, + 'guid' => $url + ); + + // Save the data + $postID = wp_insert_attachment($attachment, $file); + + if (!$postID) + $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.')); + + $output = $this->get_entry($postID, 'attachment'); + + $this->created($postID, $output, 'attachment'); + log_app('function',"create_attachment($postID)"); + } + + /** + * Update attachment. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function put_attachment($postID) { + // checked for valid content-types (atom+xml) + // quick check and exit + $this->get_accepted_content_type($this->atom_content_types); + + $parser = new AtomParser(); + if(!$parser->parse()) { + $this->bad_request(); + } + + $parsed = array_pop($parser->feed->entries); + + // check for not found + global $entry; + $this->set_current_entry($postID); + + if(!current_user_can('edit_post', $entry['ID'])) + $this->auth_required(__('Sorry, you do not have the right to edit this post.')); + + extract($entry); + + $post_title = $parsed->title[1]; + $post_content = $parsed->summary[1]; + $pubtimes = $this->get_publish_time($parsed->updated); + $post_modified = $pubtimes[0]; + $post_modified_gmt = $pubtimes[1]; + + $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'post_modified', 'post_modified_gmt'); + $this->escape($postdata); + + $result = wp_update_post($postdata); + + if (!$result) { + $this->internal_error(__('For some strange yet very annoying reason, this post could not be edited.')); + } + + log_app('function',"put_attachment($postID)"); + $this->ok(); + } + + /** + * Remove attachment. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function delete_attachment($postID) { + log_app('function',"delete_attachment($postID). File '$location' deleted."); + + // check for not found + global $entry; + $this->set_current_entry($postID); + + if(!current_user_can('edit_post', $postID)) { + $this->auth_required(__('Sorry, you do not have the right to delete this post.')); + } + + $location = get_post_meta($entry['ID'], '_wp_attached_file', true); + $filetype = wp_check_filetype($location); + + if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext'])) + $this->internal_error(__('Error ocurred while accessing post metadata for file location.')); + + // delete file + @unlink($location); + + // delete attachment + $result = wp_delete_post($postID); + + if (!$result) { + $this->internal_error(__('For some strange yet very annoying reason, this post could not be deleted.')); + } + + log_app('function',"delete_attachment($postID). File '$location' deleted."); + $this->ok(); + } + + /** + * Retrieve attachment from post. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function get_file($postID) { + + // check for not found + global $entry; + $this->set_current_entry($postID); + + // then whether user can edit the specific post + if(!current_user_can('edit_post', $postID)) { + $this->auth_required(__('Sorry, you do not have the right to edit this post.')); + } + + $location = get_post_meta($entry['ID'], '_wp_attached_file', true); + $filetype = wp_check_filetype($location); + + if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext'])) + $this->internal_error(__('Error ocurred while accessing post metadata for file location.')); + + status_header('200'); + header('Content-Type: ' . $entry['post_mime_type']); + header('Connection: close'); + + $fp = fopen($location, "rb"); + while(!feof($fp)) { + echo fread($fp, 4096); + } + fclose($fp); + + log_app('function',"get_file($postID)"); + exit; + } + + /** + * Upload file to blog and add attachment to post. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function put_file($postID) { + + // first check if user can upload + if(!current_user_can('upload_files')) + $this->auth_required(__('You do not have permission to upload files.')); + + // check for not found + global $entry; + $this->set_current_entry($postID); + + // then whether user can edit the specific post + if(!current_user_can('edit_post', $postID)) { + $this->auth_required(__('Sorry, you do not have the right to edit this post.')); + } + + $upload_dir = wp_upload_dir( ); + $location = get_post_meta($entry['ID'], '_wp_attached_file', true); + $filetype = wp_check_filetype($location); + + $location = "{$upload_dir['basedir']}/{$location}"; + + if(!isset($location) || 'attachment' != $entry['post_type'] || empty($filetype['ext'])) + $this->internal_error(__('Error ocurred while accessing post metadata for file location.')); + + $fp = fopen("php://input", "rb"); + $localfp = fopen($location, "w+"); + while(!feof($fp)) { + fwrite($localfp,fread($fp, 4096)); + } + fclose($fp); + fclose($localfp); + + $ID = $entry['ID']; + $pubtimes = $this->get_publish_time($entry->published); + $post_date = $pubtimes[0]; + $post_date_gmt = $pubtimes[1]; + $pubtimes = $this->get_publish_time($parsed->updated); + $post_modified = $pubtimes[0]; + $post_modified_gmt = $pubtimes[1]; + + $post_data = compact('ID', 'post_date', 'post_date_gmt', 'post_modified', 'post_modified_gmt'); + $result = wp_update_post($post_data); + + if (!$result) { + $this->internal_error(__('Sorry, your entry could not be posted. Something wrong happened.')); + } + + wp_update_attachment_metadata( $postID, wp_generate_attachment_metadata( $postID, $location ) ); + + log_app('function',"put_file($postID)"); + $this->ok(); + } + + /** + * Retrieve entries URL. + * + * @since 2.2.0 + * + * @param int $page Page ID. + * @return string + */ + function get_entries_url($page = null) { + if($GLOBALS['post_type'] == 'attachment') { + $path = $this->MEDIA_PATH; + } else { + $path = $this->ENTRIES_PATH; + } + $url = $this->app_base . $path; + if(isset($page) && is_int($page)) { + $url .= "/$page"; + } + return $url; + } + + /** + * Display entries URL. + * + * @since 2.2.0 + * + * @param int $page Page ID. + */ + function the_entries_url($page = null) { + echo $this->get_entries_url($page); + } + + /** + * Retrieve categories URL. + * + * @since 2.2.0 + * + * @param mixed $deprecated Optional, not used. + * @return string + */ + function get_categories_url($deprecated = '') { + return $this->app_base . $this->CATEGORIES_PATH; + } + + /** + * Display category URL. + * + * @since 2.2.0 + */ + function the_categories_url() { + echo $this->get_categories_url(); + } + + /** + * Retrieve attachment URL. + * + * @since 2.2.0 + * + * @param int $page Page ID. + * @return string + */ + function get_attachments_url($page = null) { + $url = $this->app_base . $this->MEDIA_PATH; + if(isset($page) && is_int($page)) { + $url .= "/$page"; + } + return $url; + } + + /** + * Display attachment URL. + * + * @since 2.2.0 + * + * @param int $page Page ID. + */ + function the_attachments_url($page = null) { + echo $this->get_attachments_url($page); + } + + /** + * Retrieve service URL. + * + * @since 2.3.0 + * + * @return string + */ + function get_service_url() { + return $this->app_base . $this->SERVICE_PATH; + } + + /** + * Retrieve entry URL. + * + * @since 2.7.0 + * + * @param int $postID Post ID. + * @return string + */ + function get_entry_url($postID = null) { + if(!isset($postID)) { + global $post; + $postID = (int) $post->ID; + } + + $url = $this->app_base . $this->ENTRY_PATH . "/$postID"; + + log_app('function',"get_entry_url() = $url"); + return $url; + } + + /** + * Display entry URL. + * + * @since 2.7.0 + * + * @param int $postID Post ID. + */ + function the_entry_url($postID = null) { + echo $this->get_entry_url($postID); + } + + /** + * Retrieve media URL. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + * @return string + */ + function get_media_url($postID = null) { + if(!isset($postID)) { + global $post; + $postID = (int) $post->ID; + } + + $url = $this->app_base . $this->MEDIA_SINGLE_PATH ."/file/$postID"; + + log_app('function',"get_media_url() = $url"); + return $url; + } + + /** + * Display the media URL. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function the_media_url($postID = null) { + echo $this->get_media_url($postID); + } + + /** + * Set the current entry to post ID. + * + * @since 2.2.0 + * + * @param int $postID Post ID. + */ + function set_current_entry($postID) { + global $entry; + log_app('function',"set_current_entry($postID)"); + + if(!isset($postID)) { + // $this->bad_request(); + $this->not_found(); + } + + $entry = wp_get_single_post($postID,ARRAY_A); + + if(!isset($entry) || !isset($entry['ID'])) + $this->not_found(); + + return; + } + + /** + * Display posts XML. + * + * @since 2.2.0 + * + * @param int $page Optional. Page ID. + * @param string $post_type Optional, default is 'post'. Post Type. + */ + function get_posts($page = 1, $post_type = 'post') { + log_app('function',"get_posts($page, '$post_type')"); + $feed = $this->get_feed($page, $post_type); + $this->output($feed); + } + + /** + * Display attachment XML. + * + * @since 2.2.0 + * + * @param int $page Page ID. + * @param string $post_type Optional, default is 'attachment'. Post type. + */ + function get_attachments($page = 1, $post_type = 'attachment') { + log_app('function',"get_attachments($page, '$post_type')"); + $GLOBALS['post_type'] = $post_type; + $feed = $this->get_feed($page, $post_type); + $this->output($feed); + } + + /** + * Retrieve feed XML. + * + * @since 2.2.0 + * + * @param int $page Page ID. + * @param string $post_type Optional, default is post. Post type. + * @return string + */ + function get_feed($page = 1, $post_type = 'post') { + global $post, $wp, $wp_query, $posts, $wpdb, $blog_id; + log_app('function',"get_feed($page, '$post_type')"); + ob_start(); + + $this->ENTRY_PATH = $post_type; + + if(!isset($page)) { + $page = 1; + } + $page = (int) $page; + + $count = get_option('posts_per_rss'); + + wp('posts_per_page=' . $count . '&offset=' . ($count * ($page-1) . '&orderby=modified')); + + $post = $GLOBALS['post']; + $posts = $GLOBALS['posts']; + $wp = $GLOBALS['wp']; + $wp_query = $GLOBALS['wp_query']; + $wpdb = $GLOBALS['wpdb']; + $blog_id = (int) $GLOBALS['blog_id']; + log_app('function',"query_posts(# " . print_r($wp_query, true) . "#)"); + + log_app('function',"total_count(# $wp_query->max_num_pages #)"); + $last_page = $wp_query->max_num_pages; + $next_page = (($page + 1) > $last_page) ? NULL : $page + 1; + $prev_page = ($page - 1) < 1 ? NULL : $page - 1; + $last_page = ((int)$last_page == 1 || (int)$last_page == 0) ? NULL : (int) $last_page; + $self_page = $page > 1 ? $page : NULL; +?> +the_entries_url() ?> + +<?php bloginfo_rss('name') ?> + + + + + + + + + + +Copyright + +echo_entry(); + } + } +?> +ENTRY_PATH = 'attachment'; + $varname = 'attachment_id'; + break; + } + query_posts($varname . '=' . $postID); + if ( have_posts() ) { + while ( have_posts() ) { + the_post(); + $this->echo_entry(); + log_app('$post',print_r($GLOBALS['post'],true)); + $entry = ob_get_contents(); + break; + } + } + ob_end_clean(); + + log_app('get_entry returning:',$entry); + return $entry; + } + + /** + * Display post content XML. + * + * @since 2.3.0 + */ + function echo_entry() { ?> + + ID); ?> + + <?php echo $content ?> + + + + + post_status == 'draft' ? 'yes' : 'no') ?> + + + + + + + +post_type == 'attachment') { ?> + + + + +post_content ) ) : +list($content_type, $content) = prep_atom_text_construct(get_the_content()); ?> + + + + + + + + + + + + 302 Found + + +

    Found

    +

    The document has moved here.

    + + + +EOD; + header('HTTP/1.1 302 Moved'); + header('Content-Type: text/html'); + header('Location: ' . $url); + echo $content; + exit; + + } + + /** + * Set 'Client Error' (400) status header. + * + * @since 2.2.0 + */ + function client_error($msg = 'Client Error') { + log_app('Status','400: Client Error'); + header('Content-Type: text/plain'); + status_header('400'); + exit; + } + + /** + * Set created status headers (201). + * + * Sets the 'content-type', 'content-location', and 'location'. + * + * @since 2.2.0 + */ + function created($post_ID, $content, $post_type = 'post') { + log_app('created()::$post_ID',"$post_ID, $post_type"); + $edit = $this->get_entry_url($post_ID); + switch($post_type) { + case 'post': + $ctloc = $this->get_entry_url($post_ID); + break; + case 'attachment': + $edit = $this->app_base . "attachments/$post_ID"; + break; + } + header("Content-Type: $this->ATOM_CONTENT_TYPE"); + if(isset($ctloc)) + header('Content-Location: ' . $ctloc); + header('Location: ' . $edit); + status_header('201'); + echo $content; + exit; + } + + /** + * Set 'Auth Required' (401) headers. + * + * @since 2.2.0 + * + * @param string $msg Status header content and HTML content. + */ + function auth_required($msg) { + log_app('Status','401: Auth Required'); + nocache_headers(); + header('WWW-Authenticate: Basic realm="WordPress Atom Protocol"'); + header("HTTP/1.1 401 $msg"); + header('Status: 401 ' . $msg); + header('Content-Type: text/html'); + $content = << + + + 401 Unauthorized + + +

    401 Unauthorized

    +

    $msg

    + + + +EOD; + echo $content; + exit; + } + + /** + * Display XML and set headers with content type. + * + * @since 2.2.0 + * + * @param string $xml Display feed content. + * @param string $ctype Optional, default is 'atom+xml'. Feed content type. + */ + function output($xml, $ctype = 'application/atom+xml') { + status_header('200'); + $xml = ''."\n".$xml; + header('Connection: close'); + header('Content-Length: '. strlen($xml)); + header('Content-Type: ' . $ctype); + header('Content-Disposition: attachment; filename=atom.xml'); + header('Date: '. date('r')); + if($this->do_output) + echo $xml; + log_app('function', "output:\n$xml"); + exit; + } + + /** + * Sanitize content for database usage. + * + * @since 2.2.0 + * + * @param array $array Sanitize array and multi-dimension array. + */ + function escape(&$array) { + global $wpdb; + + foreach ($array as $k => $v) { + if (is_array($v)) { + $this->escape($array[$k]); + } else if (is_object($v)) { + //skip + } else { + $array[$k] = $wpdb->escape($v); + } + } + } + + /** + * Access credential through various methods and perform login. + * + * @since 2.2.0 + * + * @return bool + */ + function authenticate() { + log_app("authenticate()",print_r($_ENV, true)); + + // if using mod_rewrite/ENV hack + // http://www.besthostratings.com/articles/http-auth-php-cgi.html + if(isset($_SERVER['HTTP_AUTHORIZATION'])) { + list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = + explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); + } else if (isset($_SERVER['REDIRECT_REMOTE_USER'])) { + // Workaround for setups that do not forward HTTP_AUTHORIZATION + // See http://trac.wordpress.org/ticket/7361 + list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = + explode(':', base64_decode(substr($_SERVER['REDIRECT_REMOTE_USER'], 6))); + } + + // If Basic Auth is working... + if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) { + log_app("Basic Auth",$_SERVER['PHP_AUTH_USER']); + } + + $user = wp_authenticate($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']); + if ( $user && !is_wp_error($user) ) { + wp_set_current_user($user->ID); + log_app("authenticate()", $user->user_login); + return true; + } + + return false; + } + + /** + * Retrieve accepted content types. + * + * @since 2.2.0 + * + * @param array $types Optional. Content Types. + * @return string + */ + function get_accepted_content_type($types = null) { + + if(!isset($types)) { + $types = $this->media_content_types; + } + + if(!isset($_SERVER['CONTENT_LENGTH']) || !isset($_SERVER['CONTENT_TYPE'])) { + $this->length_required(); + } + + $type = $_SERVER['CONTENT_TYPE']; + list($type,$subtype) = explode('/',$type); + list($subtype) = explode(";",$subtype); // strip MIME parameters + log_app("get_accepted_content_type", "type=$type, subtype=$subtype"); + + foreach($types as $t) { + list($acceptedType,$acceptedSubtype) = explode('/',$t); + if($acceptedType == '*' || $acceptedType == $type) { + if($acceptedSubtype == '*' || $acceptedSubtype == $subtype) + return $type . "/" . $subtype; + } + } + + $this->invalid_media(); + } + + /** + * Process conditionals for posts. + * + * @since 2.2.0 + */ + function process_conditionals() { + + if(empty($this->params)) return; + if($_SERVER['REQUEST_METHOD'] == 'DELETE') return; + + switch($this->params[0]) { + case $this->ENTRY_PATH: + global $post; + $post = wp_get_single_post($this->params[1]); + $wp_last_modified = get_post_modified_time('D, d M Y H:i:s', true); + $post = NULL; + break; + case $this->ENTRIES_PATH: + $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT'; + break; + default: + return; + } + $wp_etag = md5($wp_last_modified); + @header("Last-Modified: $wp_last_modified"); + @header("ETag: $wp_etag"); + + // Support for Conditional GET + if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) + $client_etag = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']); + else + $client_etag = false; + + $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE']); + // If string is empty, return 0. If not, attempt to parse into a timestamp + $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0; + + // Make a timestamp for our most recent modification... + $wp_modified_timestamp = strtotime($wp_last_modified); + + if ( ($client_last_modified && $client_etag) ? + (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) : + (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) { + status_header( 304 ); + exit; + } + } + + /** + * Convert RFC3339 time string to timestamp. + * + * @since 2.3.0 + * + * @param string $str String to time. + * @return bool|int false if format is incorrect. + */ + function rfc3339_str2time($str) { + + $match = false; + if(!preg_match("/(\d{4}-\d{2}-\d{2})T(\d{2}\:\d{2}\:\d{2})\.?\d{0,3}(Z|[+-]+\d{2}\:\d{2})/", $str, $match)) + return false; + + if($match[3] == 'Z') + $match[3] == '+0000'; + + return strtotime($match[1] . " " . $match[2] . " " . $match[3]); + } + + /** + * Retrieve published time to display in XML. + * + * @since 2.3.0 + * + * @param string $published Time string. + * @return string + */ + function get_publish_time($published) { + + $pubtime = $this->rfc3339_str2time($published); + + if(!$pubtime) { + return array(current_time('mysql'),current_time('mysql',1)); + } else { + return array(date("Y-m-d H:i:s", $pubtime), gmdate("Y-m-d H:i:s", $pubtime)); + } + } + +} + +/** + * AtomServer + * @var AtomServer + * @global object $server + */ +$server = new AtomServer(); +$server->handle_request(); + +?> diff --git a/wp-atom.php b/wp-atom.php new file mode 100644 index 0000000..f7221f3 --- /dev/null +++ b/wp-atom.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/wp-blog-header.php b/wp-blog-header.php new file mode 100644 index 0000000..0f7118f --- /dev/null +++ b/wp-blog-header.php @@ -0,0 +1,20 @@ + \ No newline at end of file diff --git a/wp-comments-post.php b/wp-comments-post.php new file mode 100644 index 0000000..8289bb4 --- /dev/null +++ b/wp-comments-post.php @@ -0,0 +1,92 @@ +get_row( $wpdb->prepare("SELECT post_status, comment_status FROM $wpdb->posts WHERE ID = %d", $comment_post_ID) ); + +if ( empty($status->comment_status) ) { + do_action('comment_id_not_found', $comment_post_ID); + exit; +} elseif ( !comments_open($comment_post_ID) ) { + do_action('comment_closed', $comment_post_ID); + wp_die( __('Sorry, comments are closed for this item.') ); +} elseif ( in_array($status->post_status, array('draft', 'pending') ) ) { + do_action('comment_on_draft', $comment_post_ID); + exit; +} else { + do_action('pre_comment_on_post', $comment_post_ID); +} + +$comment_author = ( isset($_POST['author']) ) ? trim(strip_tags($_POST['author'])) : null; +$comment_author_email = ( isset($_POST['email']) ) ? trim($_POST['email']) : null; +$comment_author_url = ( isset($_POST['url']) ) ? trim($_POST['url']) : null; +$comment_content = ( isset($_POST['comment']) ) ? trim($_POST['comment']) : null; + +// If the user is logged in +$user = wp_get_current_user(); +if ( $user->ID ) { + if ( empty( $user->display_name ) ) + $user->display_name=$user->user_login; + $comment_author = $wpdb->escape($user->display_name); + $comment_author_email = $wpdb->escape($user->user_email); + $comment_author_url = $wpdb->escape($user->user_url); + if ( current_user_can('unfiltered_html') ) { + if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) { + kses_remove_filters(); // start with a clean slate + kses_init_filters(); // set up the filters + } + } +} else { + if ( get_option('comment_registration') || 'private' == $status->post_status ) + wp_die( __('Sorry, you must be logged in to post a comment.') ); +} + +$comment_type = ''; + +if ( get_option('require_name_email') && !$user->ID ) { + if ( 6 > strlen($comment_author_email) || '' == $comment_author ) + wp_die( __('Error: please fill the required fields (name, email).') ); + elseif ( !is_email($comment_author_email)) + wp_die( __('Error: please enter a valid email address.') ); +} + +if ( '' == $comment_content ) + wp_die( __('Error: please type a comment.') ); + +$comment_parent = isset($_POST['comment_parent']) ? absint($_POST['comment_parent']) : 0; + +$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_ID'); + +$comment_id = wp_new_comment( $commentdata ); + +$comment = get_comment($comment_id); +if ( !$user->ID ) { + $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000); + setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); + setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); + setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); +} + +$location = empty($_POST['redirect_to']) ? get_comment_link($comment_id) : $_POST['redirect_to'] . '#comment-' . $comment_id; +$location = apply_filters('comment_post_redirect', $location, $comment); + +wp_redirect($location); + +?> diff --git a/wp-commentsrss2.php b/wp-commentsrss2.php new file mode 100644 index 0000000..1c146b1 --- /dev/null +++ b/wp-commentsrss2.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/wp-config-sample.php b/wp-config-sample.php new file mode 100644 index 0000000..2e316c7 --- /dev/null +++ b/wp-config-sample.php @@ -0,0 +1,76 @@ + \ No newline at end of file diff --git a/wp-content/plugins/akismet/akismet.gif b/wp-content/plugins/akismet/akismet.gif new file mode 100644 index 0000000..0b93a89 Binary files /dev/null and b/wp-content/plugins/akismet/akismet.gif differ diff --git a/wp-content/plugins/akismet/akismet.php b/wp-content/plugins/akismet/akismet.php new file mode 100644 index 0000000..92bbae2 --- /dev/null +++ b/wp-content/plugins/akismet/akismet.php @@ -0,0 +1,1108 @@ +WordPress.com API key to use it. You can review the spam it catches under "Comments." To show off your Akismet stats just put <?php akismet_counter(); ?> in your template. See also: WP Stats plugin. +Version: 2.2.6 +Author: Matt Mullenweg +Author URI: http://ma.tt/ +*/ + +define('AKISMET_VERSION', '2.2.6'); + +// If you hardcode a WP.com API key here, all key config screens will be hidden +if ( defined('WPCOM_API_KEY') ) + $wpcom_api_key = constant('WPCOM_API_KEY'); +else + $wpcom_api_key = ''; + +function akismet_init() { + global $wpcom_api_key, $akismet_api_host, $akismet_api_port; + + if ( $wpcom_api_key ) + $akismet_api_host = $wpcom_api_key . '.rest.akismet.com'; + else + $akismet_api_host = get_option('wordpress_api_key') . '.rest.akismet.com'; + + $akismet_api_port = 80; + add_action('admin_menu', 'akismet_config_page'); + add_action('admin_menu', 'akismet_stats_page'); + akismet_admin_warnings(); +} +add_action('init', 'akismet_init'); + +function akismet_admin_init() { + if ( function_exists( 'get_plugin_page_hook' ) ) + $hook = get_plugin_page_hook( 'akismet-stats-display', 'index.php' ); + else + $hook = 'dashboard_page_akismet-stats-display'; + add_action('admin_head-'.$hook, 'akismet_stats_script'); +} +add_action('admin_init', 'akismet_admin_init'); + +if ( !function_exists('wp_nonce_field') ) { + function akismet_nonce_field($action = -1) { return; } + $akismet_nonce = -1; +} else { + function akismet_nonce_field($action = -1) { return wp_nonce_field($action); } + $akismet_nonce = 'akismet-update-key'; +} + +if ( !function_exists('number_format_i18n') ) { + function number_format_i18n( $number, $decimals = null ) { return number_format( $number, $decimals ); } +} + +function akismet_config_page() { + if ( function_exists('add_submenu_page') ) + add_submenu_page('plugins.php', __('Akismet Configuration'), __('Akismet Configuration'), 'manage_options', 'akismet-key-config', 'akismet_conf'); + +} + +function akismet_conf() { + global $akismet_nonce, $wpcom_api_key; + + if ( isset($_POST['submit']) ) { + if ( function_exists('current_user_can') && !current_user_can('manage_options') ) + die(__('Cheatin’ uh?')); + + check_admin_referer( $akismet_nonce ); + $key = preg_replace( '/[^a-h0-9]/i', '', $_POST['key'] ); + + if ( empty($key) ) { + $key_status = 'empty'; + $ms[] = 'new_key_empty'; + delete_option('wordpress_api_key'); + } else { + $key_status = akismet_verify_key( $key ); + } + + if ( $key_status == 'valid' ) { + update_option('wordpress_api_key', $key); + $ms[] = 'new_key_valid'; + } else if ( $key_status == 'invalid' ) { + $ms[] = 'new_key_invalid'; + } else if ( $key_status == 'failed' ) { + $ms[] = 'new_key_failed'; + } + + if ( isset( $_POST['akismet_discard_month'] ) ) + update_option( 'akismet_discard_month', 'true' ); + else + update_option( 'akismet_discard_month', 'false' ); + } elseif ( isset($_POST['check']) ) { + akismet_get_server_connectivity(0); + } + + if ( $key_status != 'valid' ) { + $key = get_option('wordpress_api_key'); + if ( empty( $key ) ) { + if ( $key_status != 'failed' ) { + if ( akismet_verify_key( '1234567890ab' ) == 'failed' ) + $ms[] = 'no_connection'; + else + $ms[] = 'key_empty'; + } + $key_status = 'empty'; + } else { + $key_status = akismet_verify_key( $key ); + } + if ( $key_status == 'valid' ) { + $ms[] = 'key_valid'; + } else if ( $key_status == 'invalid' ) { + delete_option('wordpress_api_key'); + $ms[] = 'key_empty'; + } else if ( !empty($key) && $key_status == 'failed' ) { + $ms[] = 'key_failed'; + } + } + + $messages = array( + 'new_key_empty' => array('color' => 'aa0', 'text' => __('Your key has been cleared.')), + 'new_key_valid' => array('color' => '2d2', 'text' => __('Your key has been verified. Happy blogging!')), + 'new_key_invalid' => array('color' => 'd22', 'text' => __('The key you entered is invalid. Please double-check it.')), + 'new_key_failed' => array('color' => 'd22', 'text' => __('The key you entered could not be verified because a connection to akismet.com could not be established. Please check your server configuration.')), + 'no_connection' => array('color' => 'd22', 'text' => __('There was a problem connecting to the Akismet server. Please check your server configuration.')), + 'key_empty' => array('color' => 'aa0', 'text' => sprintf(__('Please enter an API key. (Get your key.)'), 'http://wordpress.com/profile/')), + 'key_valid' => array('color' => '2d2', 'text' => __('This key is valid.')), + 'key_failed' => array('color' => 'aa0', 'text' => __('The key below was previously validated but a connection to akismet.com can not be established at this time. Please check your server configuration.'))); +?> + +

    + +
    +

    +
    +
    + +

    Akismet will greatly reduce or even completely eliminate the comment and trackback spam you get on your site. If one does happen to get through, simply mark it as "spam" on the moderation screen and Akismet will learn from the mistakes. If you don\'t have a WordPress.com account yet, you can get one at WordPress.com.'), 'http://akismet.com/', 'http://wordpress.com/api-keys/'); ?>

    + + +

    + +

    + +

    (What is this?'); ?>)

    + +

    +

    + + +

    +

    +
    + +
    + +

    + 0 ) { + // some connections work, some fail + if ( $fail_count > 0 && $fail_count < count($servers) ) { ?> +

    +

    this information about Akismet and firewalls.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>

    + 0 ) { ?> +

    +

    Akismet cannot work correctly until this is fixed. Please contact your web host or firewall administrator and give them this information about Akismet and firewalls.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>

    + +

    +

    + +

    +

    fsockopen function. Akismet cannot work correctly until this is fixed. Please contact your web host or firewall administrator and give them this information about Akismet\'s system requirements.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>

    + +

    +

    Akismet cannot work correctly until this is fixed. Please contact your web host or firewall administrator and give them this information about Akismet and firewalls.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>

    + + + + + $status ) { + $color = ( $status ? '#2d2' : '#d22'); + ?> + + + + + + +
    +

    +

    +
    + +
    +
    + + +
    + +
    +

    ".__('Akismet is almost ready.')." ".sprintf(__('You must enter your WordPress.com API key for it to work.'), "plugins.php?page=akismet-key-config")."

    + "; + } + add_action('admin_notices', 'akismet_warning'); + return; + } elseif ( get_option('akismet_connectivity_time') && empty($_POST) && is_admin() && !akismet_server_connectivity_ok() ) { + function akismet_warning() { + echo " +

    ".__('Akismet has detected a problem.')." ".sprintf(__('A server or network problem is preventing Akismet from working correctly. Click here for more information about how to fix the problem.'), "plugins.php?page=akismet-key-config")."

    + "; + } + add_action('admin_notices', 'akismet_warning'); + return; + } +} + +function akismet_get_host($host) { + // if all servers are accessible, just return the host name. + // if not, return an IP that was known to be accessible at the last check. + if ( akismet_server_connectivity_ok() ) { + return $host; + } else { + $ips = akismet_get_server_connectivity(); + // a firewall may be blocking access to some Akismet IPs + if ( count($ips) > 0 && count(array_filter($ips)) < count($ips) ) { + // use DNS to get current IPs, but exclude any known to be unreachable + $dns = (array)gethostbynamel( rtrim($host, '.') . '.' ); + $dns = array_filter($dns); + foreach ( $dns as $ip ) { + if ( array_key_exists( $ip, $ips ) && empty( $ips[$ip] ) ) + unset($dns[$ip]); + } + // return a random IP from those available + if ( count($dns) ) + return $dns[ array_rand($dns) ]; + + } + } + // if all else fails try the host name + return $host; +} + +// Returns array with headers in $response[0] and body in $response[1] +function akismet_http_post($request, $host, $path, $port = 80, $ip=null) { + global $wp_version; + + $akismet_version = constant('AKISMET_VERSION'); + + $http_request = "POST $path HTTP/1.0\r\n"; + $http_request .= "Host: $host\r\n"; + $http_request .= "Content-Type: application/x-www-form-urlencoded; charset=" . get_option('blog_charset') . "\r\n"; + $http_request .= "Content-Length: " . strlen($request) . "\r\n"; + $http_request .= "User-Agent: WordPress/$wp_version | Akismet/$akismet_version\r\n"; + $http_request .= "\r\n"; + $http_request .= $request; + + $http_host = $host; + // use a specific IP if provided - needed by akismet_check_server_connectivity() + if ( $ip && long2ip(ip2long($ip)) ) { + $http_host = $ip; + } else { + $http_host = akismet_get_host($host); + } + + $response = ''; + if( false != ( $fs = @fsockopen($http_host, $port, $errno, $errstr, 10) ) ) { + fwrite($fs, $http_request); + + while ( !feof($fs) ) + $response .= fgets($fs, 1160); // One TCP-IP packet + fclose($fs); + $response = explode("\r\n\r\n", $response, 2); + } + return $response; +} + +function akismet_auto_check_comment( $comment ) { + global $akismet_api_host, $akismet_api_port; + + $comment['user_ip'] = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] ); + $comment['user_agent'] = $_SERVER['HTTP_USER_AGENT']; + $comment['referrer'] = $_SERVER['HTTP_REFERER']; + $comment['blog'] = get_option('home'); + $comment['blog_lang'] = get_locale(); + $comment['blog_charset'] = get_option('blog_charset'); + $comment['permalink'] = get_permalink($comment['comment_post_ID']); + + $ignore = array( 'HTTP_COOKIE' ); + + foreach ( $_SERVER as $key => $value ) + if ( !in_array( $key, $ignore ) && is_string($value) ) + $comment["$key"] = $value; + + $query_string = ''; + foreach ( $comment as $key => $data ) + $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; + + $response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port); + if ( 'true' == $response[1] ) { + add_filter('pre_comment_approved', create_function('$a', 'return \'spam\';')); + update_option( 'akismet_spam_count', get_option('akismet_spam_count') + 1 ); + + do_action( 'akismet_spam_caught' ); + + $post = get_post( $comment['comment_post_ID'] ); + $last_updated = strtotime( $post->post_modified_gmt ); + $diff = time() - $last_updated; + $diff = $diff / 86400; + + if ( $post->post_type == 'post' && $diff > 30 && get_option( 'akismet_discard_month' ) == 'true' ) + die; + } + akismet_delete_old(); + return $comment; +} + +function akismet_delete_old() { + global $wpdb; + $now_gmt = current_time('mysql', 1); + $wpdb->query("DELETE FROM $wpdb->comments WHERE DATE_SUB('$now_gmt', INTERVAL 15 DAY) > comment_date_gmt AND comment_approved = 'spam'"); + $n = mt_rand(1, 5000); + if ( $n == 11 ) // lucky number + $wpdb->query("OPTIMIZE TABLE $wpdb->comments"); +} + +function akismet_submit_nonspam_comment ( $comment_id ) { + global $wpdb, $akismet_api_host, $akismet_api_port, $current_user, $current_site; + $comment_id = (int) $comment_id; + + $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_id'"); + if ( !$comment ) // it was deleted + return; + $comment->blog = get_option('home'); + $comment->blog_lang = get_locale(); + $comment->blog_charset = get_option('blog_charset'); + $comment->permalink = get_permalink($comment->comment_post_ID); + if ( is_object($current_user) ) { + $comment->reporter = $current_user->user_login; + } + if ( is_object($current_site) ) { + $comment->site_domain = $current_site->domain; + } + $query_string = ''; + foreach ( $comment as $key => $data ) + $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; + + $response = akismet_http_post($query_string, $akismet_api_host, "/1.1/submit-ham", $akismet_api_port); +} + +function akismet_submit_spam_comment ( $comment_id ) { + global $wpdb, $akismet_api_host, $akismet_api_port, $current_user, $current_site; + $comment_id = (int) $comment_id; + + $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_id'"); + if ( !$comment ) // it was deleted + return; + if ( 'spam' != $comment->comment_approved ) + return; + $comment->blog = get_option('home'); + $comment->blog_lang = get_locale(); + $comment->blog_charset = get_option('blog_charset'); + $comment->permalink = get_permalink($comment->comment_post_ID); + if ( is_object($current_user) ) { + $comment->reporter = $current_user->user_login; + } + if ( is_object($current_site) ) { + $comment->site_domain = $current_site->domain; + } + $query_string = ''; + foreach ( $comment as $key => $data ) + $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; + + $response = akismet_http_post($query_string, $akismet_api_host, "/1.1/submit-spam", $akismet_api_port); +} + +add_action('wp_set_comment_status', 'akismet_submit_spam_comment'); +add_action('edit_comment', 'akismet_submit_spam_comment'); +add_action('preprocess_comment', 'akismet_auto_check_comment', 1); + +function akismet_spamtoham( $comment ) { akismet_submit_nonspam_comment( $comment->comment_ID ); } +add_filter( 'comment_spam_to_approved', 'akismet_spamtoham' ); + +// Total spam in queue +// get_option( 'akismet_spam_count' ) is the total caught ever +function akismet_spam_count( $type = false ) { + global $wpdb; + + if ( !$type ) { // total + $count = wp_cache_get( 'akismet_spam_count', 'widget' ); + if ( false === $count ) { + if ( function_exists('wp_count_comments') ) { + $count = wp_count_comments(); + $count = $count->spam; + } else { + $count = (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_approved = 'spam'"); + } + wp_cache_set( 'akismet_spam_count', $count, 'widget', 3600 ); + } + return $count; + } elseif ( 'comments' == $type || 'comment' == $type ) { // comments + $type = ''; + } else { // pingback, trackback, ... + $type = $wpdb->escape( $type ); + } + + return (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_approved = 'spam' AND comment_type='$type'"); +} + +function akismet_spam_comments( $type = false, $page = 1, $per_page = 50 ) { + global $wpdb; + + $page = (int) $page; + if ( $page < 2 ) + $page = 1; + + $per_page = (int) $per_page; + if ( $per_page < 1 ) + $per_page = 50; + + $start = ( $page - 1 ) * $per_page; + $end = $start + $per_page; + + if ( $type ) { + if ( 'comments' == $type || 'comment' == $type ) + $type = ''; + else + $type = $wpdb->escape( $type ); + return $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = 'spam' AND comment_type='$type' ORDER BY comment_date DESC LIMIT $start, $end"); + } + + // All + return $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = 'spam' ORDER BY comment_date DESC LIMIT $start, $end"); +} + +// Totals for each comment type +// returns array( type => count, ... ) +function akismet_spam_totals() { + global $wpdb; + $totals = $wpdb->get_results( "SELECT comment_type, COUNT(*) AS cc FROM $wpdb->comments WHERE comment_approved = 'spam' GROUP BY comment_type" ); + $return = array(); + foreach ( $totals as $total ) + $return[$total->comment_type ? $total->comment_type : 'comment'] = $total->cc; + return $return; +} + +function akismet_manage_page() { + global $wpdb, $submenu, $wp_db_version; + + // WP 2.7 has its own spam management page + if ( 8645 <= $wp_db_version ) + return; + + $count = sprintf(__('Akismet Spam (%s)'), akismet_spam_count()); + if ( isset( $submenu['edit-comments.php'] ) ) + add_submenu_page('edit-comments.php', __('Akismet Spam'), $count, 'moderate_comments', 'akismet-admin', 'akismet_caught' ); + elseif ( function_exists('add_management_page') ) + add_management_page(__('Akismet Spam'), $count, 'moderate_comments', 'akismet-admin', 'akismet_caught'); +} + +function akismet_caught() { + global $wpdb, $comment, $akismet_caught, $akismet_nonce; + + akismet_recheck_queue(); + if (isset($_POST['submit']) && 'recover' == $_POST['action'] && ! empty($_POST['not_spam'])) { + check_admin_referer( $akismet_nonce ); + if ( function_exists('current_user_can') && !current_user_can('moderate_comments') ) + die(__('You do not have sufficient permission to moderate comments.')); + + $i = 0; + foreach ($_POST['not_spam'] as $comment): + $comment = (int) $comment; + if ( function_exists('wp_set_comment_status') ) + wp_set_comment_status($comment, 'approve'); + else + $wpdb->query("UPDATE $wpdb->comments SET comment_approved = '1' WHERE comment_ID = '$comment'"); + akismet_submit_nonspam_comment($comment); + ++$i; + endforeach; + $to = add_query_arg( 'recovered', $i, $_SERVER['HTTP_REFERER'] ); + wp_redirect( $to ); + exit; + } + if ('delete' == $_POST['action']) { + check_admin_referer( $akismet_nonce ); + if ( function_exists('current_user_can') && !current_user_can('moderate_comments') ) + die(__('You do not have sufficient permission to moderate comments.')); + + $delete_time = $wpdb->escape( $_POST['display_time'] ); + $nuked = $wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_approved = 'spam' AND '$delete_time' > comment_date_gmt" ); + wp_cache_delete( 'akismet_spam_count', 'widget' ); + $to = add_query_arg( 'deleted', 'all', $_SERVER['HTTP_REFERER'] ); + wp_redirect( $to ); + exit; + } + +if ( isset( $_GET['recovered'] ) ) { + $i = (int) $_GET['recovered']; + echo '

    ' . sprintf(__('%1$s comments recovered.'), $i) . "

    "; +} + +if (isset( $_GET['deleted'] ) ) + echo '

    ' . __('All spam deleted.') . '

    '; + +if ( isset( $GLOBALS['submenu']['edit-comments.php'] ) ) + $link = 'edit-comments.php'; +else + $link = 'edit.php'; +?> + +
    +

    + +

    %1$s spam for you since you first installed it.'), number_format_i18n($count) ); ?>

    +'.__('You have no spam currently in the queue. Must be your lucky day. :)').'

    '; + echo '
    '; +} else { + echo '

    '.__('You can delete all of the spam from your database with a single click. This operation cannot be undone, so you may wish to check to ensure that no legitimate comments got through first. Spam is automatically deleted after 15 days, so don’t sweat it.').'

    '; +?> + +
    + + +    + +
    + + +
    + +

    + +'.__('These are the latest comments identified as spam by Akismet. If you see any mistakes, simply mark the comment as "not spam" and Akismet will learn from the submission. If you wish to recover a comment from spam, simply select the comment, and click Not Spam. After 15 days we clean out the junk for you.').'

    '; ?> + +escape($_POST['s']); + $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE + (comment_author LIKE '%$s%' OR + comment_author_email LIKE '%$s%' OR + comment_author_url LIKE ('%$s%') OR + comment_author_IP LIKE ('%$s%') OR + comment_content LIKE ('%$s%') ) AND + comment_approved = 'spam' + ORDER BY comment_date DESC"); +} else { + if ( isset( $_GET['apage'] ) ) + $page = (int) $_GET['apage']; + else + $page = 1; + + if ( $page < 2 ) + $page = 1; + + $current_type = false; + if ( isset( $_GET['ctype'] ) ) + $current_type = preg_replace( '|[^a-z]|', '', $_GET['ctype'] ); + + $comments = akismet_spam_comments( $current_type, $page ); + $total = akismet_spam_count( $current_type ); + $totals = akismet_spam_totals(); +?> +
      +
    • >
    • + $type_count ) { + if ( 'comment' == $type ) { + $type = 'comments'; + $show = __('Comments'); + } else { + $show = ucwords( $type ); + } + $type_count = number_format_i18n( $type_count ); + $extra = $current_type === $type ? ' class="active"' : ''; + echo "
    • $show ($type_count)
    • "; +} +do_action( 'akismet_tabs' ); // so plugins can add more tabs easily +?> +
    + +
    " id="akismetsearch"> +

    +

    +
    + 50 ) { +$total_pages = ceil( $total / 50 ); +$r = ''; +if ( 1 < $page ) { + $args['apage'] = ( 1 == $page - 1 ) ? '' : $page - 1; + $r .= '' . "\n"; +} +if ( ( $total_pages = ceil( $total / 50 ) ) > 1 ) { + for ( $page_num = 1; $page_num <= $total_pages; $page_num++ ) : + if ( $page == $page_num ) : + $r .= "$page_num\n"; + else : + $p = false; + if ( $page_num < 3 || ( $page_num >= $page - 3 && $page_num <= $page + 3 ) || $page_num > $total_pages - 3 ) : + $args['apage'] = ( 1 == $page_num ) ? '' : $page_num; + $r .= '' . ( $page_num ) . "\n"; + $in = true; + elseif ( $in == true ) : + $r .= "...\n"; + $in = false; + endif; + endif; + endfor; +} +if ( ( $page ) * 50 < $total || -1 == $total ) { + $args['apage'] = $page + 1; + $r .= '' . "\n"; +} +echo "

    $r

    "; +?> + + +
    + + +
      +comment_date); + $post = get_post($comment->comment_post_ID); + $post_title = $post->post_title; + if ($i % 2) $class = 'class="alternate"'; + else $class = ''; + echo "\n\t
    • "; + ?> + +

      comment_author_email) { ?>| comment_author_url && 'http://' != $comment->comment_author_url) { ?> | |

      + + + +

      — [ +comment_post_ID); +$post_title = wp_specialchars( $post->post_title, 'double' ); +$post_title = ('' == $post_title) ? "# $comment->comment_post_ID" : $post_title; +?> + ]

      + + + +
    + 50 ) { +$total_pages = ceil( $total / 50 ); +$r = ''; +if ( 1 < $page ) { + $args['apage'] = ( 1 == $page - 1 ) ? '' : $page - 1; + $r .= '' . "\n"; +} +if ( ( $total_pages = ceil( $total / 50 ) ) > 1 ) { + for ( $page_num = 1; $page_num <= $total_pages; $page_num++ ) : + if ( $page == $page_num ) : + $r .= "$page_num\n"; + else : + $p = false; + if ( $page_num < 3 || ( $page_num >= $page - 3 && $page_num <= $page + 3 ) || $page_num > $total_pages - 3 ) : + $args['apage'] = ( 1 == $page_num ) ? '' : $page_num; + $r .= '' . ( $page_num ) . "\n"; + $in = true; + elseif ( $in == true ) : + $r .= "...\n"; + $in = false; + endif; + endif; + endfor; +} +if ( ( $page ) * 50 < $total || -1 == $total ) { + $args['apage'] = $page + 1; + $r .= '' . "\n"; +} +echo "

    $r

    "; +} +?> +

    + +

    +

    +
    + +

    + + + +
    + +

    +    +

    +
    + +
    +'.__('Spam').''; + global $submenu; + if ( isset( $submenu['edit-comments.php'] ) ) + $link = 'edit-comments.php'; + else + $link = 'edit.php'; + echo '

    '.sprintf(__('Akismet has protected your site from %3$s spam comments.'), 'http://akismet.com/', clean_url("$link?page=akismet-admin"), number_format_i18n($count) ).'

    '; +} + +add_action('activity_box_end', 'akismet_stats'); + +// WP 2.5+ +function akismet_rightnow() { + global $submenu, $wp_db_version; + + if ( 8645 < $wp_db_version ) // 2.7 + $link = 'edit-comments.php?comment_status=spam'; + elseif ( isset( $submenu['edit-comments.php'] ) ) + $link = 'edit-comments.php?page=akismet-admin'; + else + $link = 'edit.php?page=akismet-admin'; + + if ( $count = get_option('akismet_spam_count') ) { + $intro = sprintf( __ngettext( + 'Akismet has protected your site from %2$s spam comment already,', + 'Akismet has protected your site from %2$s spam comments already,', + $count + ), 'http://akismet.com/', number_format_i18n( $count ) ); + } else { + $intro = sprintf( __('Akismet blocks spam from getting to your blog,'), 'http://akismet.com/' ); + } + + if ( $queue_count = akismet_spam_count() ) { + $queue_text = sprintf( __ngettext( + 'and there\'s %1$s comment in your spam queue right now.', + 'and there are %1$s comments in your spam queue right now.', + $queue_count + ), number_format_i18n( $queue_count ), clean_url($link) ); + } else { + $queue_text = sprintf( __( "but there's nothing in your spam queue at the moment." ), clean_url($link) ); + } + + $text = sprintf( _c( '%1$s %2$s|akismet_rightnow' ), $intro, $queue_text ); + + echo "

    $text

    \n"; +} + +add_action('rightnow_end', 'akismet_rightnow'); + +// For WP <= 2.3.x +if ( 'moderation.php' == $pagenow ) { + function akismet_recheck_button( $page ) { + global $submenu; + if ( isset( $submenu['edit-comments.php'] ) ) + $link = 'edit-comments.php'; + else + $link = 'edit.php'; + $button = "" . __('Recheck Queue for Spam') . ""; + $page = str_replace( '
    ', '
    ' . $button, $page ); + return $page; + } + + if ( $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0'" ) ) + ob_start( 'akismet_recheck_button' ); +} + +// For WP >= 2.5 +function akismet_check_for_spam_button($comment_status) { + if ( 'approved' == $comment_status ) + return; + if ( function_exists('plugins_url') ) + $link = 'admin.php?action=akismet_recheck_queue'; + else + $link = 'edit-comments.php?page=akismet-admin&recheckqueue=true&noheader=true'; + echo "
    " . __('Check for Spam') . ""; +} +add_action('manage_comments_nav', 'akismet_check_for_spam_button'); + +function akismet_recheck_queue() { + global $wpdb, $akismet_api_host, $akismet_api_port; + + if ( ! ( isset( $_GET['recheckqueue'] ) || ( isset( $_REQUEST['action'] ) && 'akismet_recheck_queue' == $_REQUEST['action'] ) ) ) + return; + + $moderation = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = '0'", ARRAY_A ); + foreach ( (array) $moderation as $c ) { + $c['user_ip'] = $c['comment_author_IP']; + $c['user_agent'] = $c['comment_agent']; + $c['referrer'] = ''; + $c['blog'] = get_option('home'); + $c['blog_lang'] = get_locale(); + $c['blog_charset'] = get_option('blog_charset'); + $c['permalink'] = get_permalink($c['comment_post_ID']); + $id = (int) $c['comment_ID']; + + $query_string = ''; + foreach ( $c as $key => $data ) + $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; + + $response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port); + if ( 'true' == $response[1] ) { + $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = 'spam' WHERE comment_ID = $id" ); + } + } + wp_redirect( $_SERVER['HTTP_REFERER'] ); + exit; +} + +add_action('admin_action_akismet_recheck_queue', 'akismet_recheck_queue'); + +function akismet_check_db_comment( $id ) { + global $wpdb, $akismet_api_host, $akismet_api_port; + + $id = (int) $id; + $c = $wpdb->get_row( "SELECT * FROM $wpdb->comments WHERE comment_ID = '$id'", ARRAY_A ); + if ( !$c ) + return; + + $c['user_ip'] = $c['comment_author_IP']; + $c['user_agent'] = $c['comment_agent']; + $c['referrer'] = ''; + $c['blog'] = get_option('home'); + $c['blog_lang'] = get_locale(); + $c['blog_charset'] = get_option('blog_charset'); + $c['permalink'] = get_permalink($c['comment_post_ID']); + $id = $c['comment_ID']; + + $query_string = ''; + foreach ( $c as $key => $data ) + $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; + + $response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port); + return $response[1]; +} + +// This option causes tons of FPs, was removed in 2.1 +function akismet_kill_proxy_check( $option ) { return 0; } +add_filter('option_open_proxy_check', 'akismet_kill_proxy_check'); + +// Widget stuff +function widget_akismet_register() { + if ( function_exists('register_sidebar_widget') ) : + function widget_akismet($args) { + extract($args); + $options = get_option('widget_akismet'); + $count = number_format_i18n(get_option('akismet_spam_count')); + ?> + + + + + + + +

    + + + + + + diff --git a/wp-content/plugins/akismet/readme.txt b/wp-content/plugins/akismet/readme.txt new file mode 100644 index 0000000..af87370 --- /dev/null +++ b/wp-content/plugins/akismet/readme.txt @@ -0,0 +1,46 @@ +=== Akismet === +Contributors: matt, ryan, andy, mdawaffe, tellyworth +Tags: akismet, comments, spam +Requires at least: 2.0 +Tested up to: 2.8.2 + +Akismet checks your comments against the Akismet web service to see if they look like spam or not. + +== Description == + +Akismet checks your comments against the Akismet web service to see if they look like spam or not and lets you +review the spam it catches under your blog's "Comments" admin screen. + +Want to show off how much spam Akismet has caught for you? Just put `` in your template. + +See also: [WP Stats plugin](http://wordpress.org/extend/plugins/stats/). + +PS: You'll need a [WordPress.com API key](http://wordpress.com/api-keys/) to use it. + +== Installation == + +Upload the Akismet plugin to your blog, Activate it, then enter your [WordPress.com API key](http://wordpress.com/api-keys/). + +1, 2, 3: You're done! + +== Changelog == + += 2.2.7 = + +* Add a new AKISMET_VERSION constant + += 2.2.6 = + +* Fix a global warning introduced in 2.2.5 +* Add changelog and additional readme.txt tags +* Fix an array conversion warning in some versions of PHP +* Support a new WPCOM_API_KEY constant for easier use with WordPress MU + += 2.2.5 = + +* Include a new Server Connectivity diagnostic check, to detect problems caused by firewalls + += 2.2.4 = + +* Fixed a key problem affecting the stats feature in WordPress MU +* Provide additional blog information in Akismet API calls diff --git a/wp-content/plugins/google-analyticator/class.analytics.stats.php b/wp-content/plugins/google-analyticator/class.analytics.stats.php new file mode 100644 index 0000000..0b19882 --- /dev/null +++ b/wp-content/plugins/google-analyticator/class.analytics.stats.php @@ -0,0 +1,360 @@ +token = get_option('ga_google_token'); + + # Revoke the current token + $response = $this->http('https://www.google.com/accounts/AuthSubRevokeToken'); + + # Remove the current token + update_option('ga_google_token', ''); + + return ''; + + } + + $this->token = $token; + + # Request authentication with Google + $response = $this->http('https://www.google.com/accounts/AuthSubSessionToken'); + + # Get the authentication token + $this->token = substr(strstr($response, "Token="), 6); + + # Save the token for future use + update_option('ga_google_token', $this->token); + + # Remove the old username and password fields if they still exists + delete_option('google_stats_user'); + delete_option('google_stats_password'); + + } else { + $this->token = get_option('ga_google_token'); + } + } + + /** + * Connects using the WordPress HTTP API to get data + * + * @param url - url to request + * @param post - post data to pass through WordPress + * @return the raw http response + **/ + function http($url, $post = false) + { + # Return false if the token has not been set + if ( trim($this->token) == '' ) + return ''; + + # Set the arguments to pass to WordPress + $args = array( + 'sslverify' => false + ); + + # Add the optional post values + if ( $post ) { + $post .= '&service=analytics&source=google-analyticator-' . GOOGLE_ANALYTICATOR_VERSION; + $args['body'] = $post; + } + + # Set the content to form data + $args['headers'] = array('Content-Type' => 'application/x-www-form-urlencoded'); + + # Add the token information + if ( $this->token ) { + $args['headers']['Authorization'] = 'AuthSub token="' . $this->token . '"'; + } + + # Disable the fopen transport since it doesn't work with the Google API + add_filter('use_fopen_transport', create_function('$a', 'return false;')); + + # Check compatibility mode settings + if ( get_option('ga_compatibility') == 'level1' ) { + add_filter('use_curl_transport', create_function('$a', 'return false;')); + } elseif ( get_option('ga_compatibility') == 'level2' ) { + add_filter('use_curl_transport', create_function('$a', 'return false;')); + add_filter('use_streams_transport', create_function('$a', 'return false;')); + } + + # Make the connection + if ( $post ) + $response = wp_remote_post($url, $args); + else + $response = wp_remote_get($url, $args); + + # Check for WordPress error + if ( is_wp_error($response) ) { + $this->responseHash['error'] = __('WordPress HTTP error.', 'google-analyticator'); + return ''; + } + + # Set the message response + $this->responseCode = $response['response']['code']; + + # Build an array of messages + foreach( explode("\n", $response['body']) as $line ) { + if ( trim($line) != '' ) { + $pos = strpos($line, '='); + if ( $pos !== false ) { + $this->responseHash[strtolower(substr($line, 0, $pos))] = substr($line, $pos+1); + } + } + } + + # Return the body of the response + return $response['body']; + } + + /** + * Checks if the username and password worked by looking at the token + * + * @return Boolean if the login details worked + **/ + function checkLogin() + { + if ( $this->token != false ) + return true; + else + return false; + } + + /** + * Sets the account id to use for queries + * + * @param id - the account id + **/ + function setAccount($id) + { + $this->accountId = $id; + } + + /** + * Get a list of Analytics accounts + * + * @return a list of analytics accounts + **/ + function getAnalyticsAccounts() + { + # Request the list of accounts + $response = $this->http($this->baseFeed . '/accounts/default'); + + # Check if the response received exists, else stop processing now + if ( $response == '' || $this->responseCode != '200' ) + return false; + + # Parse the XML using SimplePie + $simplePie = new SimplePie(); + $simplePie->set_raw_data($response); + $simplePie->init(); + $simplePie->handle_content_type(); + $accounts = $simplePie->get_items(); + + # Make an array of the accounts + $ids = array(); + foreach ( $accounts AS $account ) { + $id = array(); + + # Get the list of properties + $properties = $account->get_item_tags('http://schemas.google.com/analytics/2009', 'property'); + + # Loop through the properties + foreach ( $properties AS $property ) { + + # Get the property information + $name = $property['attribs']['']['name']; + $value = $property['attribs']['']['value']; + + # Add the propery data to the id array + $id[$name] = $value; + + } + + # Add the backward compatibility array items + $id['title'] = $account->get_title(); + $id['id'] = 'ga:' . $id['ga:profileId']; + + $ids[] = $id; + } + + return $ids; + } + + /** + * Get a specific data metric + * + * @param metric - the metric to get + * @param startDate - the start date to get + * @param endDate - the end date to get + * @return the specific metric + **/ + function getMetric($metric, $startDate, $endDate) + { + # Ensure the start date is after Jan 1 2005 + $startDate = $this->verifyStartDate($startDate); + + # Request the metric data + $response = $this->http($this->baseFeed . "/data?ids=$this->accountId&start-date=$startDate&end-date=$endDate&metrics=$metric"); + + # Check if the response received exists, else stop processing now + if ( $response == '' || $this->responseCode != '200' ) + return false; + + # Parse the XML using SimplePie + $simplePie = new SimplePie(); + $simplePie->set_raw_data($response); + $simplePie->init(); + $simplePie->handle_content_type(); + $datas = $simplePie->get_items(); + + # Read out the data until the metric is found + foreach ( $datas AS $data ) { + $data_tag = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'metric'); + return $data_tag[0]['attribs']['']['value']; + } + } + + /** + * Get a specific data metrics + * + * @param metrics - the metrics to get + * @param startDate - the start date to get + * @param endDate - the end date to get + * @param dimensions - the dimensions to grab + * @param sort - the properties to sort on + * @param filter - the property to filter on + * @param limit - the number of items to get + * @return the specific metrics in array form + **/ + function getMetrics($metric, $startDate, $endDate, $dimensions = false, $sort = false, $filter = false, $limit = false) + { + # Ensure the start date is after Jan 1 2005 + $startDate = $this->verifyStartDate($startDate); + + # Build the query url + $url = $this->baseFeed . "/data?ids=$this->accountId&start-date=$startDate&end-date=$endDate&metrics=$metric"; + + # Add optional dimensions + if ( $dimensions ) + $url .= "&dimensions=$dimensions"; + + # Add optional sort + if ( $sort ) + $url .= "&sort=$sort"; + + # Add optional filter + if ( $filter ) + $url .= "&filters=$filter"; + + # Add optional limit + if ( $limit ) + $url .= "&max-results=$limit"; + + # Request the metric data + $response = $this->http($url); + + # Check if the response received exists, else stop processing now + if ( $response == '' || $this->responseCode != '200' ) + return false; + + # Parse the XML using SimplePie + $simplePie = new SimplePie(); + $simplePie->set_raw_data($response); + $simplePie->enable_order_by_date(false); + $simplePie->init(); + $simplePie->handle_content_type(); + $datas = $simplePie->get_items(); + + $ids = array(); + + # Read out the data until the metric is found + foreach ( $datas AS $data ) { + $metrics = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'metric'); + $dimensions = $data->get_item_tags('http://schemas.google.com/analytics/2009', 'dimension'); + $id = array(); + + $id['title'] = $data->get_title(); + + # Loop through the dimensions + if ( is_array($dimensions) ) { + foreach ( $dimensions AS $property ) { + + # Get the property information + $name = $property['attribs']['']['name']; + $value = $property['attribs']['']['value']; + + # Add the propery data to the id array + $id[$name] = $value; + + } + } + + # Loop through the metrics + if ( is_array($metrics) ) { + foreach ( $metrics AS $property ) { + + # Get the property information + $name = $property['attribs']['']['name']; + $value = $property['attribs']['']['value']; + + # Add the propery data to the id array + $id[$name] = $value; + + } + } + + $ids[] = $id; + } + + return $ids; + } + + /** + * Checks the date against Jan. 1 2005 because GA API only works until that date + * + * @param date - the date to compare + * @return the correct date + **/ + function verifyStartDate($date) + { + if ( strtotime($date) > strtotime('2005-01-01') ) + return $date; + else + return '2005-01-01'; + } + +} // END class + +?> \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/external-tracking.js b/wp-content/plugins/google-analyticator/external-tracking.js new file mode 100644 index 0000000..80767d2 --- /dev/null +++ b/wp-content/plugins/google-analyticator/external-tracking.js @@ -0,0 +1,44 @@ +jQuery(document).ready(function() { + + jQuery('a').each(function() { + var a = jQuery(this); + var href = a.attr('href'); + + // Check if the a tag has a href, if not, stop for the current link + if ( href == undefined ) + return; + + var url = href.replace('http://','').replace('https://',''); + var hrefArray = href.split('.').reverse(); + var extension = hrefArray[0].toLowerCase(); + var hrefArray = href.split('/').reverse(); + var domain = hrefArray[2]; + var downloadTracked = false; + + // If the link is a download + if (jQuery.inArray(extension,analyticsFileTypes) != -1) { + // Mark the link as already tracked + downloadTracked = true; + + // Add the tracking code + a.click(function() { + if ( analyticsEventTracking == 'enabled' ) { + pageTracker._trackEvent("Downloads", extension.toUpperCase(), href); + } else + pageTracker._trackPageview(analyticsDownloadsPrefix + url); + }); + } + + // If the link is external + if ( ( href.match(/^http/) ) && ( !href.match(document.domain) ) && ( downloadTracked == false ) ) { + // Add the tracking code + a.click(function() { + if ( analyticsEventTracking == 'enabled' ) { + pageTracker._trackEvent("Outbound Traffic", href.match(/:\/\/(.[^/]+)/)[1], href); + } else + pageTracker._trackPageview(analyticsOutboundPrefix + url); + }); + } + }); + +}); \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/external-tracking.min.js b/wp-content/plugins/google-analyticator/external-tracking.min.js new file mode 100644 index 0000000..deefdf7 --- /dev/null +++ b/wp-content/plugins/google-analyticator/external-tracking.min.js @@ -0,0 +1,5 @@ +jQuery(document).ready(function(){jQuery('a').each(function(){var a=jQuery(this);var href=a.attr('href');if(href==undefined) +return;var url=href.replace('http://','').replace('https://','');var hrefArray=href.split('.').reverse();var extension=hrefArray[0].toLowerCase();var hrefArray=href.split('/').reverse();var domain=hrefArray[2];var downloadTracked=false;if(jQuery.inArray(extension,analyticsFileTypes)!=-1){downloadTracked=true;a.click(function(){if(analyticsEventTracking=='enabled'){pageTracker._trackEvent("Downloads",extension.toUpperCase(),href);}else +pageTracker._trackPageview(analyticsDownloadsPrefix+url);});} +if((href.match(/^http/))&&(!href.match(document.domain))&&(downloadTracked==false)){a.click(function(){if(analyticsEventTracking=='enabled'){pageTracker._trackEvent("Outbound Traffic",href.match(/:\/\/(.[^/]+)/)[1],href);}else +pageTracker._trackPageview(analyticsOutboundPrefix+url);});}});}); \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/ga_logo.png b/wp-content/plugins/google-analyticator/ga_logo.png new file mode 100644 index 0000000..3d07705 Binary files /dev/null and b/wp-content/plugins/google-analyticator/ga_logo.png differ diff --git a/wp-content/plugins/google-analyticator/google-analyticator.php b/wp-content/plugins/google-analyticator/google-analyticator.php new file mode 100644 index 0000000..5b91e89 --- /dev/null +++ b/wp-content/plugins/google-analyticator/google-analyticator.php @@ -0,0 +1,958 @@ +Google's Analytics. After enabling this plugin visit the settings page and enter your Google Analytics' UID and enable logging. + * Author: Spiral Web Consulting + * Author URI: http://spiralwebconsulting.com/ + * Text Domain: google-analyticator + */ + +define('GOOGLE_ANALYTICATOR_VERSION', '5.3.1'); + +// Constants for enabled/disabled state +define("ga_enabled", "enabled", true); +define("ga_disabled", "disabled", true); + +// Defaults, etc. +define("key_ga_uid", "ga_uid", true); +define("key_ga_status", "ga_status", true); +define("key_ga_admin", "ga_admin_status", true); +define("key_ga_admin_disable", "ga_admin_disable", true); +define("key_ga_admin_level", "ga_admin_level", true); +define("key_ga_adsense", "ga_adsense", true); +define("key_ga_extra", "ga_extra", true); +define("key_ga_extra_after", "ga_extra_after", true); +define("key_ga_event", "ga_event", true); +define("key_ga_outbound", "ga_outbound", true); +define("key_ga_outbound_prefix", "ga_outbound_prefix", true); +define("key_ga_downloads", "ga_downloads", true); +define("key_ga_downloads_prefix", "ga_downloads_prefix", true); +define("key_ga_footer", "ga_footer", true); +define("key_ga_specify_http", "ga_specify_http", true); +define("key_ga_widgets", "ga_widgets", true); + +define("ga_uid_default", "XX-XXXXX-X", true); +define("ga_status_default", ga_disabled, true); +define("ga_admin_default", ga_enabled, true); +define("ga_admin_disable_default", 'remove', true); +define("ga_admin_level_default", 8, true); +define("ga_adsense_default", "", true); +define("ga_extra_default", "", true); +define("ga_extra_after_default", "", true); +define("ga_event_default", ga_enabled, true); +define("ga_outbound_default", ga_enabled, true); +define("ga_outbound_prefix_default", 'outgoing', true); +define("ga_downloads_default", "", true); +define("ga_downloads_prefix_default", "download", true); +define("ga_footer_default", ga_disabled, true); +define("ga_specify_http_default", "auto", true); +define("ga_widgets_default", ga_enabled, true); + +// Create the default key and status +add_option(key_ga_status, ga_status_default, 'If Google Analytics logging in turned on or off.'); +add_option(key_ga_uid, ga_uid_default, 'Your Google Analytics UID.'); +add_option(key_ga_admin, ga_admin_default, 'If WordPress admins are counted in Google Analytics.'); +add_option(key_ga_admin_disable, ga_admin_disable_default, ''); +add_option(key_ga_admin_level, ga_admin_level_default, 'The level to consider a user a WordPress admin.'); +add_option(key_ga_adsense, ga_adsense_default, ''); +add_option(key_ga_extra, ga_extra_default, 'Addition Google Analytics tracking options'); +add_option(key_ga_extra_after, ga_extra_after_default, 'Addition Google Analytics tracking options'); +add_option(key_ga_event, ga_event_default, ''); +add_option(key_ga_outbound, ga_outbound_default, 'Add tracking of outbound links'); +add_option(key_ga_outbound_prefix, ga_outbound_prefix_default, 'Add tracking of outbound links'); +add_option(key_ga_downloads, ga_downloads_default, 'Download extensions to track with Google Analyticator'); +add_option(key_ga_downloads_prefix, ga_downloads_prefix_default, 'Download extensions to track with Google Analyticator'); +add_option(key_ga_footer, ga_footer_default, 'If Google Analyticator is outputting in the footer'); +add_option(key_ga_specify_http, ga_specify_http_default, 'Automatically detect the http/https settings'); +add_option(key_ga_widgets, ga_widgets_default, 'If the widgets are enabled or disabled'); +add_option('ga_google_token', '', 'The token used to authenticate with Google'); +add_option('ga_compatibility', 'off', 'Transport compatibility options'); + +# Check if we have a version of WordPress greater than 2.8 +if ( function_exists('register_widget') ) { + + # Check if widgets are enabled + if ( get_option(key_ga_widgets) == 'enabled' ) { + + # Include Google Analytics Stats widget + require_once('google-analytics-stats-widget.php'); + + # Include the Google Analytics Summary widget + require_once('google-analytics-summary-widget.php'); + $google_analytics_summary = new GoogleAnalyticsSummary(); + + } + +} + +// Create a option page for settings +add_action('admin_init', 'ga_admin_init'); +add_action('admin_menu', 'add_ga_option_page'); + +// Initialize the options +function ga_admin_init() { + # Load the localization information + $plugin_dir = basename(dirname(__FILE__)); + load_plugin_textdomain('google-analyticator', 'wp-content/plugins/' . $plugin_dir . '/localizations', $plugin_dir . '/localizations'); + + // Register out options so WordPress knows about them + if ( function_exists('register_setting') ) { + register_setting('google-analyticator', key_ga_status, ''); + register_setting('google-analyticator', key_ga_uid, ''); + register_setting('google-analyticator', key_ga_admin, ''); + register_setting('google-analyticator', key_ga_admin_disable, ''); + register_setting('google-analyticator', key_ga_admin_level, ''); + register_setting('google-analyticator', key_ga_adsense, ''); + register_setting('google-analyticator', key_ga_extra, ''); + register_setting('google-analyticator', key_ga_extra_after, ''); + register_setting('google-analyticator', key_ga_event, ''); + register_setting('google-analyticator', key_ga_outbound, ''); + register_setting('google-analyticator', key_ga_outbound_prefix, ''); + register_setting('google-analyticator', key_ga_downloads, ''); + register_setting('google-analyticator', key_ga_downloads_prefix, ''); + register_setting('google-analyticator', key_ga_footer, ''); + register_setting('google-analyticator', key_ga_specify_http, ''); + } +} + +// Initialize outbound link tracking +add_action('init', 'ga_outgoing_links'); + +// Hook in the options page function +function add_ga_option_page() { + $plugin_page = add_options_page(__('Google Analyticator Settings', 'google-analyticator'), 'Google Analytics', 8, basename(__FILE__), 'ga_options_page'); + + # Include javascript on the GA settings page + add_action('admin_head-' . $plugin_page, 'ga_admin_ajax'); +} + +add_action('plugin_action_links_' . plugin_basename(__FILE__), 'ga_filter_plugin_actions'); + +// Add settings option +function ga_filter_plugin_actions($links) { + $new_links = array(); + + $new_links[] = '' . __('Settings', 'google-analyticator') . ''; + + return array_merge($new_links, $links); +} + +add_filter('plugin_row_meta', 'ga_filter_plugin_links', 10, 2); + +// Add FAQ and support information +function ga_filter_plugin_links($links, $file) +{ + if ( $file == plugin_basename(__FILE__) ) + { + $links[] = '' . __('FAQ', 'google-analyticator') . ''; + $links[] = '' . __('Support', 'google-analyticator') . ''; + $links[] = '' . __('Donate', 'google-analyticator') . ''; + } + + return $links; +} + +function ga_options_page() { + // If we are a postback, store the options + if (isset($_POST['info_update'])) { +// if ( wp_verify_nonce($_POST['ga-nonce-key'], 'google-analyticator') ) { + + // Update the status + $ga_status = $_POST[key_ga_status]; + if (($ga_status != ga_enabled) && ($ga_status != ga_disabled)) + $ga_status = ga_status_default; + update_option(key_ga_status, $ga_status); + + // Update the UID + $ga_uid = $_POST[key_ga_uid]; + if ($ga_uid == '') + $ga_uid = ga_uid_default; + update_option(key_ga_uid, $ga_uid); + + // Update the admin logging + $ga_admin = $_POST[key_ga_admin]; + if (($ga_admin != ga_enabled) && ($ga_admin != ga_disabled)) + $ga_admin = ga_admin_default; + update_option(key_ga_admin, $ga_admin); + + // Update the admin disable setting + $ga_admin_disable = $_POST[key_ga_admin_disable]; + if ( $ga_admin_disable == '' ) + $ga_admin_disable = ga_admin_disable_default; + update_option(key_ga_admin_disable, $ga_admin_disable); + + // Update the admin level + $ga_admin_level = $_POST[key_ga_admin_level]; + if ( $ga_admin_level == '' ) + $ga_admin_level = ga_admin_level_default; + update_option(key_ga_admin_level, $ga_admin_level); + + // Update the extra tracking code + $ga_extra = $_POST[key_ga_extra]; + update_option(key_ga_extra, $ga_extra); + + // Update the extra after tracking code + $ga_extra_after = $_POST[key_ga_extra_after]; + update_option(key_ga_extra_after, $ga_extra_after); + + // Update the adsense key + $ga_adsense = $_POST[key_ga_adsense]; + update_option(key_ga_adsense, $ga_adsense); + + // Update the event tracking + $ga_event = $_POST[key_ga_event]; + if (($ga_event != ga_enabled) && ($ga_event != ga_disabled)) + $ga_event = ga_event_default; + update_option(key_ga_event, $ga_event); + + // Update the outbound tracking + $ga_outbound = $_POST[key_ga_outbound]; + if (($ga_outbound != ga_enabled) && ($ga_outbound != ga_disabled)) + $ga_outbound = ga_outbound_default; + update_option(key_ga_outbound, $ga_outbound); + + // Update the outbound prefix + $ga_outbound_prefix = $_POST[key_ga_outbound_prefix]; + if ($ga_outbound_prefix == '') + $ga_outbound_prefix = ga_outbound_prefix_default; + update_option(key_ga_outbound_prefix, $ga_outbound_prefix); + + // Update the download tracking code + $ga_downloads = $_POST[key_ga_downloads]; + update_option(key_ga_downloads, $ga_downloads); + + // Update the download prefix + $ga_downloads_prefix = $_POST[key_ga_downloads_prefix]; + if ($ga_downloads_prefix == '') + $ga_downloads_prefix = ga_downloads_prefix_default; + update_option(key_ga_downloads_prefix, $ga_downloads_prefix); + + // Update the footer + $ga_footer = $_POST[key_ga_footer]; + if (($ga_footer != ga_enabled) && ($ga_footer != ga_disabled)) + $ga_footer = ga_footer_default; + update_option(key_ga_footer, $ga_footer); + + // Update the HTTP status + $ga_specify_http = $_POST[key_ga_specify_http]; + if ( $ga_specify_http == '' ) + $ga_specify_http = 'auto'; + update_option(key_ga_specify_http, $ga_specify_http); + + // Update the widgets option + $ga_widgets = $_POST[key_ga_widgets]; + if (($ga_widgets != ga_enabled) && ($ga_widgets != ga_disabled)) + $ga_widgets = ga_widgets_default; + update_option(key_ga_widgets, $ga_widgets); + + // Update the compatibility options + $ga_compatibility = $_POST['ga_compatibility']; + if ( $ga_compatibility == '' ) + $ga_compatibility = 'off'; + update_option('ga_compatibility', $ga_compatibility); + + // Give an updated message + echo "

    " . __('Google Analyticator settings saved.', 'google-analyticator') . "

    "; +// } + } + + // Output the options page + ?> + +
    + +

    + +
    +
    + + + + +
    +
    + +
    + +

    + Spiral Web Consulting. Spiral Web Consulting is a small web development firm specializing in PHP development. Visit our website to learn more, and don\'t hesitate to ask us to develop your next big WordPress plugin idea.', 'google-analyticator'); ?> +

    + +

    + +
    + DISABLED.', 'google-analyticator'); ?> +
    + + +
    + +
    + + + + + + + + + + + + + + + + +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +
    + + + +

    + +

    + + + + +

    authenticating with Google is optional.', 'google-analyticator'); ?>

    +
    + + + \n"; + ?> +

    where can I find my UID?). The UID is needed for Google Analytics to log your website stats.', 'google-analyticator'); ?>

    +
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + + # Generate the user level box + $level = "\n"; + + # Output the current user level + if ( current_user_can('level_10') ) + $user = '10'; + elseif ( current_user_can('level_9') ) + $user = '9'; + elseif ( current_user_can('level_8') ) + $user = '8'; + elseif ( current_user_can('level_7') ) + $user = '7'; + elseif ( current_user_can('level_6') ) + $user = '6'; + elseif ( current_user_can('level_5') ) + $user = '5'; + elseif ( current_user_can('level_4') ) + $user = '4'; + elseif ( current_user_can('level_3') ) + $user = '3'; + elseif ( current_user_can('level_2') ) + $user = '2'; + elseif ( current_user_can('level_1') ) + $user = '1'; + else + $user = '0'; + ?> +

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    event tracking in Analytics, this is the recommended way to track these types of actions. Only disable this option if you must use the old pageview tracking method.', 'google-analyticator'); ?>

    +
    + + + \n"; + ?> +

    mp3,pdf. Outbound link tracking must be enabled for downloads to be tracked.', 'google-analyticator'); ?>

    +
    + + + \n"; + ?> +

    +
    + + + \n"; + ?> +

    +
    + + + \n"; + ?> +

    +
    + + + "; + echo stripslashes(get_option(key_ga_extra))."\n"; + ?> +

    before the Google Analytics tracker is initialized. Read Google Analytics tracker manual to learn what code goes here and how to use it.', 'google-analyticator'); ?>

    +
    + + + "; + echo stripslashes(get_option(key_ga_extra_after))."\n"; + ?> +

    after the Google Analytics tracker is initialized. Read Google Analytics tracker manual to learn what code goes here and how to use it.', 'google-analyticator'); ?>

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    +
    + + + \n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + + echo "\n"; + ?> +

    +
    +

    + + +

    +
    + + + + + + + + + + + '; + echo ''; + + # The list of accounts + foreach ( $ga_accounts AS $account ) { + $select = ( get_option(key_ga_uid) == $account['ga:webPropertyId'] ) ? ' selected="selected"' : ''; + echo ''; + } + + # Close the select box + echo ''; + ?> +

    + + + checkLogin() ) + return false; + + # Get a list of accounts + $accounts = $stats->getAnalyticsAccounts(); + + # Return the account array if there are accounts + if ( count($accounts) > 0 ) + return $accounts; + else + return false; +} + +/** + * Add http_build_query if it doesn't exist already + **/ +if ( !function_exists('http_build_query') ) { + function http_build_query($params, $key = null) + { + $ret = array(); + + foreach( (array) $params as $name => $val ) { + $name = urlencode($name); + + if ( $key !== null ) + $name = $key . "[" . $name . "]"; + + if ( is_array($val) || is_object($val) ) + $ret[] = http_build_query($val, $name); + elseif ($val !== null) + $ret[] = $name . "=" . urlencode($val); + } + + return implode("&", $ret); + } +} + +// Add the script +$ga_in_footer = false; +if (get_option(key_ga_footer) == ga_enabled) { + $ga_in_footer = true; + add_action('wp_head', 'add_ga_adsense'); + add_action('wp_footer', 'add_google_analytics'); +} else { + add_action('wp_head', 'add_google_analytics'); +} + +/** + * Adds the Analytics Adsense tracking code to the header if the main Analytics tracking code is in the footer. + * Idea and code for Adsense tracking with main code in footer props William Charles Nickerson on May 16, 2009. + **/ +function add_ga_adsense() { + $uid = stripslashes(get_option(key_ga_uid)); + // If GA is enabled and has a valid key + if ( (get_option(key_ga_status) != ga_disabled ) && ( $uid != "XX-XXXXX-X" )) { + // Display page tracking if user is not an admin + if ( ( get_option(key_ga_admin) == ga_enabled || !current_user_can('level_' . get_option(key_ga_admin_level)) ) && get_option(key_ga_admin_disable) == 'remove' || get_option(key_ga_admin_disable) != 'remove' ) { + if ( get_option(key_ga_adsense) != '' ) { + echo "\n"; + echo ' \n\n"; + } + } + } +} + +// The guts of the Google Analytics script +function add_google_analytics() { + global $ga_in_footer; + + $uid = stripslashes(get_option(key_ga_uid)); + $extra = stripslashes(get_option(key_ga_extra)); + $extra_after = stripslashes(get_option(key_ga_extra_after)); + $extensions = str_replace (",", "|", get_option(key_ga_downloads)); + + // If GA is enabled and has a valid key + if ( (get_option(key_ga_status) != ga_disabled ) && ( $uid != "XX-XXXXX-X" )) { + + // Display page tracking if user is not an admin + if ( ( get_option(key_ga_admin) == ga_enabled || !current_user_can('level_' . get_option(key_ga_admin_level)) ) && get_option(key_ga_admin_disable) == 'remove' || get_option(key_ga_admin_disable) != 'remove' ) { + + echo "\n"; + # Google Adsense data if enabled + if ( get_option(key_ga_adsense) != '' && !$ga_in_footer ) + echo ' \n\n"; + + // Pick the HTTP connection + if ( get_option(key_ga_specify_http) == 'http' ) { + echo " \n\n"; + } elseif ( get_option(key_ga_specify_http) == 'https' ) { + echo " \n\n"; + } else { + echo " \n\n"; + } + + echo " \n"; + + // Include the file types to track + $extensions = explode(',', stripslashes(get_option(key_ga_downloads))); + $ext = ""; + foreach ( $extensions AS $extension ) + $ext .= "'$extension',"; + $ext = substr($ext, 0, -1); + + // Include the link tracking prefixes + $outbound_prefix = stripslashes(get_option(key_ga_outbound_prefix)); + $downloads_prefix = stripslashes(get_option(key_ga_downloads_prefix)); + $event_tracking = get_option(key_ga_event); + + ?> + + \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/google-analytics-stats-widget.php b/wp-content/plugins/google-analyticator/google-analytics-stats-widget.php new file mode 100644 index 0000000..19bec42 --- /dev/null +++ b/wp-content/plugins/google-analyticator/google-analytics-stats-widget.php @@ -0,0 +1,260 @@ + 'widget_google_stats', 'description' => __("Displays Stat Info From Google Analytics", 'google-analyticator') ); + $control_ops = array('width' => 400, 'height' => 400); + $this->WP_Widget('googlestats', __('Google Analytics Stats', 'google-analyticator'), $widget_ops, $control_ops); + } + + function widget($args, $instance) { + extract($args); + $title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title']); + $acnt = $instance['account']; + $timeFrame = empty($instance['timeFrame']) ? '1' : $instance['timeFrame']; + $pageBg = empty($instance['pageBg']) ? 'fff' : $instance['pageBg']; + $widgetBg = empty($instance['widgetBg']) ? '999' : $instance['widgetBg']; + $innerBg = empty($instance['innerBg']) ? 'fff' : $instance['innerBg']; + $font = empty($instance['font']) ? '333' : $instance['font']; + $line1 = empty($instance['line1']) ? 'Unique' : $instance['line1']; + $line2 = empty($instance['line2']) ? 'Visitors' : $instance['line2']; + + # Before the widget + echo $before_widget; + + # The title + if ( $title ) + echo $before_title . $title . $after_title; + + # Make the stats chicklet + echo ''; + $this->initiateBackground($pageBg, $font); + $this->beginWidget($font, $widgetBg); + $this->widgetInfo($this->getUniqueVisitors($acnt, $timeFrame), $line1, $line2, $innerBg, $font); + $this->endWidget(); + + # After the widget + echo $after_widget; + } + + function update($new_instance, $old_instance) { + $instance = $old_instance; + $instance['title'] = strip_tags(stripslashes($new_instance['title'])); + $instance['account'] = strip_tags(stripslashes($new_instance['account'])); + $instance['timeFrame'] = strip_tags(stripslashes($new_instance['timeFrame'])); + $instance['pageBg'] = strip_tags(stripslashes($new_instance['pageBg'])); + $instance['widgetBg'] = strip_tags(stripslashes($new_instance['widgetBg'])); + $instance['innerBg'] = strip_tags(stripslashes($new_instance['innerBg'])); + $instance['font'] = strip_tags(stripslashes($new_instance['font'])); + $instance['line1'] = strip_tags(stripslashes($new_instance['line1'])); + $instance['line2'] = strip_tags(stripslashes($new_instance['line2'])); + + return $instance; + } + + function form($instance) { + //Defaults + $instance = wp_parse_args( (array) $instance, array('title'=>'', 'account'=>'', 'timeFrame'=>'1', 'pageBg'=>'fff', 'widgetBg'=>'999', 'innerBg'=>'fff', 'font'=>'333', 'line1'=>'Unique', 'line2'=>'Visitors') ); + + $title = htmlspecialchars($instance['title']); + $acnt = htmlspecialchars($instance['account']); + $timeFrame = htmlspecialchars($instance['timeFrame']); + $pageBg = htmlspecialchars($instance['pageBg']); + $widgetBg = htmlspecialchars($instance['widgetBg']); + $innerBg = htmlspecialchars($instance['innerBg']); + $font = htmlspecialchars($instance['font']); + $line1 = htmlspecialchars($instance['line1']); + $line2 = htmlspecialchars($instance['line2']); + + $accounts = array(); + + # Get the current memory limit + $current_mem_limit = substr(ini_get('memory_limit'), 0, -1); + + # Check if this limit is less than 96M, if so, increase it + if ( $current_mem_limit < 96 || $current_mem_limit == '' ) { + if ( function_exists('memory_get_usage') ) + @ini_set('memory_limit', '96M'); + } + + # Get the class for interacting with the Google Analytics + require_once('class.analytics.stats.php'); + + # Create a new Gdata call + $stats = new GoogleAnalyticsStats(); + + # Check if Google sucessfully logged in + $login = $stats->checkLogin(); + + # Get a list of accounts + $accounts = $stats->getAnalyticsAccounts(); + + # Output the options + echo '

    '; + # The list of accounts + echo '

    '; + # Time frame + echo '

    '; + # Page background + echo '

    '; + # Widget background + echo '

    '; + # Inner background + echo '

    '; + # Font color + echo '

    '; + # Text line 1 + echo '

    '; + # Text line 2 + echo '

    '; + } + + /** + * This function is used to display the background color behind the widget. This is necessary + * for the Google Analytics text to have the same background color as the page. + * + * @param $font_color - Hexadecimal value for the font color used within the Widget (does not effect "Powered By Google Analytics Text"). This effects border color as well. + * @param $page_background_color - Hexadecimal value for the page background color + * @return void + **/ + function initiateBackground($page_background_color = 'FFF', $font_color = '000') + { + echo '
    '; + echo '
    '; + } + + /** + * This function starts the widget. The font color and widget background color are customizable. + * + * @param $font_color - Hexadecimal value for the font color used within the Widget (does not effect "Powered By Google Analytics Text"). This effects border color as well. + * @param $widget_background_color - Hexadecimal value for the widget background color. + * @return void + **/ + function beginWidget($font_color = '000', $widget_background_color = 'FFF') + { + echo ''; + } + + /** + * This function encases the text that appears on the right hand side of the widget. + * Both lines of text are customizable by each individual user. + * + * It also displays the visitor count that was pulled from the user's Google Analytics account. + * + * @param $visitor_count - Number of unique visits to the site pulled from the user's Google Analytics account. + * @param $line_one - First line of text displayed on the right hand side of the widget. + * @param $line_two - Second line of text displayed on the right hand side of the widget. + * @param $inner_background_color - Hexadecimal value for the background color that surrounds the Visitor Count. + * @param $font_color - Hexadecimal value for the font color used within the Widget (does not effect "Powered By Google Analytics Text"). This effects border color as well + * @return void + **/ + function widgetInfo($visitor_count, $line_one = 'Unique', $line_two = 'Visitors', $inner_background_color = 'FFF', $font_color = '000') + { + + echo ''; + + echo ''; + + } + + /** + * The function is used strictly for visual appearance. It also displays the Google Analytics text. + * + * @return void + **/ + function endWidget() + { + // This closes off the widget. + echo '
    '. $visitor_count . '
    ' . $line_one . '
    ' . $line_two . '
    '; + + // The following is used to displayed the "Powered By Google Anayltics" text. + echo '
    Powered By Google Analytics
    '; + } + + /** + * Grabs the cached value of the unique visits for the previous day + * + * @param account - the account to get the unique visitors from + * @param time - the amount of days to get + * @return void + **/ + function getUniqueVisitors($account, $time = 1) + { + # Get the value from the database + $visits = unserialize(get_option('google_stats_visits_' . $account)); + + # Check to make sure the timeframe is an int and greater than one + $time = (int) $time; + if ( $time < 1 ) + $time = 1; + + # Check if the call has been made before + if ( is_array($visits) ) { + + # Check if the last time called was within two hours, if so, return that + if ( $visits['lastcalled'] > ( time() - 7200 ) ) + return $visits['unique']; + + } + + # If here, the call has not been made or it is expired + + # Get the current memory limit + $current_mem_limit = substr(ini_get('memory_limit'), 0, -1); + + # Check if this limit is less than 96M, if so, increase it + if ( $current_mem_limit < 96 || $current_mem_limit == '' ) { + if ( function_exists('memory_get_usage') ) + @ini_set('memory_limit', '96M'); + } + + # Get the class for interacting with the Google Analytics + require_once('class.analytics.stats.php'); + + # Create a new Gdata call + $stats = new GoogleAnalyticsStats(); + + # Set the account to the one requested + $stats->setAccount($account); + + # Get the latest stats + $before = date('Y-m-d', strtotime('-' . $time . ' days')); + $yesterday = date('Y-m-d', strtotime('-1 day')); + $uniques = number_format($stats->getMetric('ga:visitors', $before, $yesterday)); + + # Make the array for database storage + $visit = serialize(array('unique'=>$uniques, 'lastcalled'=>time())); + + # Store the array + update_option('google_stats_visits_' . $account, $visit); + + # Return the visits + return $uniques; + } + +}// END class + +/** +* Register Google Analytics Stat Widget. +*/ +function GoogleStatsWidget_init() { + register_widget('GoogleStatsWidget'); +} + +add_action('widgets_init', 'GoogleStatsWidget_init'); +?> \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/google-analytics-summary-widget.php b/wp-content/plugins/google-analyticator/google-analytics-summary-widget.php new file mode 100644 index 0000000..ddc5074 --- /dev/null +++ b/wp-content/plugins/google-analyticator/google-analytics-summary-widget.php @@ -0,0 +1,540 @@ + + + ' . __('Loading') . '...'; + } + + /** + * AJAX data for the widget + **/ + function ajaxWidget() + { + # Check the ajax widget + check_ajax_referer('ga_stats_widget'); + + # Attempt to login and get the current account + $this->id = $this->getAnalyticsAccount(); + $this->api->setAccount($this->id); + + # Check that we can display the widget before continuing + if ( $this->id == false ) { + # Output error message + echo '

    ' . __('No Analytics account selected. Double check you are authenticated with Google on Google Analyticator\'s settings page and make sure an account is selected.', 'google-analyticator') . '

    '; + + # Add Javascript variable to prevent breaking the Javascript + echo ''; + + die(); + } + + # Add the header information for the visits graph + echo '

    ' . __('Visits Over the Past 30 Days', 'google-analyticator') . '

    '; + + # Add the sparkline for the past 30 days + $this->getVisitsGraph(); + + # Add the summary header + echo '

    ' . __('Site Usage', 'google-analyticator') . '

    '; + + # Add the visitor summary + $this->getSiteUsage(); + + # Add the top 5 posts header + echo '

    ' . __('Top Pages', 'google-analyticator') . '

    '; + + # Add the top 5 posts + $this->getTopPages(); + + # Add the tab information + echo '
    '; + + # Add the top 5 referrers header + echo '

    ' . __('Top Referrers', 'google-analyticator') . '

    '; + + # Add the referrer information + $this->getTopReferrers(); + + # Add the second column + echo '
    '; + + # Add the top 5 search header + echo '

    ' . __('Top Searches', 'google-analyticator') . '

    '; + + # Add the search information + $this->getTopSearches(); + + # Close the table + echo '
    '; + + die(); + } + + /** + * Get the current analytics account + * + * @return the analytics account + **/ + function getAnalyticsAccount() + { + $accounts = array(); + + # Get the class for interacting with the Google Analytics + require_once('class.analytics.stats.php'); + + # Create a new Gdata call + $this->api = new GoogleAnalyticsStats(); + + # Check if Google sucessfully logged in + if ( ! $this->api->checkLogin() ) + return false; + + # Get a list of accounts + $accounts = $this->api->getAnalyticsAccounts(); + + # Check if we actually have accounts + if ( !is_array($accounts) ) + return false; + + # Check if we have a list of accounts + if ( count($accounts) <= 0 ) + return false; + + # Loop throught the account and return the current account + foreach ( $accounts AS $account ) { + + # Check if the UID matches the selected UID + if ( $account['ga:webPropertyId'] == get_option('ga_uid') ) + return $account['id']; + + } + + return false; + } + + /** + * Get the visitors graph + **/ + function getVisitsGraph() + { + # Get the value from the database + $cached = unserialize(get_option('google_stats_visitsGraph_' . $this->id)); + $updated = false; + + # Check if the call has been made before + if ( is_array($cached) ) { + + # Check if the last time called was within two hours, if so, mark to not retrieve and grab the stats array + if ( $cached['lastcalled'] > ( time() - 7200 ) ) { + $updated = true; + $stats = $cached['stats']; + } + + } + + # If the stats need to be updated + if ( ! $updated ) { + + # Get the metrics needed to build the visits graph + $before = date('Y-m-d', strtotime('-31 days')); + $yesterday = date('Y-m-d', strtotime('-1 day')); + $stats = $this->api->getMetrics('ga:visits', $before, $yesterday, 'ga:date', 'ga:date'); + + # Store the serialized stats in the database + $newStats = serialize(array('stats'=>$stats, 'lastcalled'=>time())); + update_option('google_stats_visitsGraph_' . $this->id, $newStats); + + } + + # Create a list of the data points for graphing + $data = ''; + $max = 0; + + # Check the size of the stats array + if ( !isset($stats) || !is_array($stats) || count($stats) <= 0 ) { + $data = '0,0'; + } else { + foreach ( $stats AS $stat ) { + # Verify the number is numeric + if ( is_numeric($stat['ga:visits']) ) + $data .= $stat['ga:visits'] . ','; + else + $data .= '0,'; + + # Update the max value if greater + if ( $max < $stat['ga:visits'] ) + $max = $stat['ga:visits']; + } + + # Shorten the string to remove the last comma + $data = substr($data, 0, -1); + } + + # Add a fake stat if need be + if ( !isset($stat['ga:visits']) ) + $stat['ga:visits'] = 0; + + # Output the graph + echo ''; + echo ''; + } + + /** + * Get the site usage + **/ + function getSiteUsage() + { + # Get the value from the database + $cached = unserialize(get_option('google_stats_siteUsage_' . $this->id)); + $updated = false; + + # Check if the call has been made before + if ( is_array($cached) ) { + + # Check if the last time called was within two hours, if so, mark to not retrieve and grab the stats array + if ( $cached['lastcalled'] > ( time() - 7200 ) ) { + $updated = true; + $stats = $cached['stats']; + } + + } + + # If the stats need to be updated + if ( ! $updated ) { + + # Get the metrics needed to build the usage table + $before = date('Y-m-d', strtotime('-31 days')); + $yesterday = date('Y-m-d', strtotime('-1 day')); + $stats = $this->api->getMetrics('ga:visits,ga:bounces,ga:entrances,ga:pageviews,ga:timeOnSite,ga:newVisits', $before, $yesterday); + + # Store the serialized stats in the database + $newStats = serialize(array('stats'=>$stats, 'lastcalled'=>time())); + update_option('google_stats_siteUsage_' . $this->id, $newStats); + + } + + # Create the site usage table + ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    0.00%%
    00:00:00sec2Time($stats[0]['ga:timeOnSite']/$stats[0]['ga:visits']); ?>
    0.000.00%%
    + id)); + $updated = false; + + # Check if the call has been made before + if ( is_array($cached) ) { + + # Check if the last time called was within two hours, if so, mark to not retrieve and grab the stats array + if ( $cached['lastcalled'] > ( time() - 7200 ) ) { + $updated = true; + $stats = $cached['stats']; + } + + } + + # If the stats need to be updated + if ( ! $updated ) { + + # Get the metrics needed to build the top pages + $before = date('Y-m-d', strtotime('-31 days')); + $yesterday = date('Y-m-d', strtotime('-1 day')); + $stats = $this->api->getMetrics('ga:pageviews', $before, $yesterday, 'ga:pageTitle,ga:pagePath', '-ga:pageviews', 'ga:pagePath!%3D%2F', '5'); + + # Store the serialized stats in the database + $newStats = serialize(array('stats'=>$stats, 'lastcalled'=>time())); + update_option('google_stats_topPages_' . $this->id, $newStats); + + } + + # Check the size of the stats array + if ( count($stats) <= 0 || !is_array($stats) ) { + echo '

    ' . __('There is no data for view.', 'google-analyticator') . '

    '; + } else { + # Build the top pages list + echo '
      '; + + # Loop through each stat + foreach ( $stats AS $stat ) { + echo '
    1. ' . $stat['ga:pageTitle'] . ' - ' . number_format($stat['ga:pageviews']) . ' ' . __('Views', 'google-analyticator') . '
    2. '; + } + + # Finish the list + echo '
    '; + } + } + + /** + * Get the top referrers + **/ + function getTopReferrers() + { + # Get the value from the database + $cached = unserialize(get_option('google_stats_topReferrers_' . $this->id)); + $updated = false; + + # Check if the call has been made before + if ( is_array($cached) ) { + + # Check if the last time called was within two hours, if so, mark to not retrieve and grab the stats array + if ( $cached['lastcalled'] > ( time() - 7200 ) ) { + $updated = true; + $stats = $cached['stats']; + } + + } + + # If the stats need to be updated + if ( ! $updated ) { + + # Get the metrics needed to build the top referrers + $before = date('Y-m-d', strtotime('-31 days')); + $yesterday = date('Y-m-d', strtotime('-1 day')); + $stats = $this->api->getMetrics('ga:visits', $before, $yesterday, 'ga:source,ga:medium', '-ga:visits', 'ga:medium%3D%3Dreferral', '5'); + + # Store the serialized stats in the database + $newStats = serialize(array('stats'=>$stats, 'lastcalled'=>time())); + update_option('google_stats_topReferrers_' . $this->id, $newStats); + + } + + # Check the size of the stats array + if ( count($stats) <= 0 || !is_array($stats) ) { + echo '

    ' . __('There is no data for view.', 'google-analyticator') . '

    '; + } else { + # Build the top pages list + echo '
      '; + + # Loop through each stat + foreach ( $stats AS $stat ) { + echo '
    1. ' . esc_html($stat['ga:source']) . ' - ' . number_format($stat['ga:visits']) . ' ' . __('Visits', 'google-analyticator') . '
    2. '; + } + + # Finish the list + echo '
    '; + } + } + + /** + * Get the top searches + **/ + function getTopSearches() + { + # Get the value from the database + $cached = unserialize(get_option('google_stats_topSearches_' . $this->id)); + $updated = false; + + # Check if the call has been made before + if ( is_array($cached) ) { + + # Check if the last time called was within two hours, if so, mark to not retrieve and grab the stats array + if ( $cached['lastcalled'] > ( time() - 7200 ) ) { + $updated = true; + $stats = $cached['stats']; + } + + } + + # If the stats need to be updated + if ( ! $updated ) { + + # Get the metrics needed to build the top searches + $before = date('Y-m-d', strtotime('-31 days')); + $yesterday = date('Y-m-d', strtotime('-1 day')); + $stats = $this->api->getMetrics('ga:visits', $before, $yesterday, 'ga:keyword', '-ga:visits', 'ga:keyword!%3D(not%20set)', '5'); + + # Store the serialized stats in the database + $newStats = serialize(array('stats'=>$stats, 'lastcalled'=>time())); + update_option('google_stats_topSearches_' . $this->id, $newStats); + + } + + # Check the size of the stats array + if ( count($stats) <= 0 || !is_array($stats) ) { + echo '

    ' . __('There is no data for view.', 'google-analyticator') . '

    '; + } else { + # Build the top pages list + echo '
      '; + + # Loop through each stat + foreach ( $stats AS $stat ) { + echo '
    1. ' . esc_html($stat['ga:keyword']) . ' - ' . number_format($stat['ga:visits']) . ' ' . __('Visits', 'google-analyticator') . '
    2. '; + } + + # Finish the list + echo '
    '; + } + } + + /** + * Convert second to a time format + **/ + function sec2Time($time) + { + # Check if numeric + if ( is_numeric($time) ) { + $value = array( + "years" => '00', + "days" => '00', + "hours" => '00', + "minutes" => '00', + "seconds" => '00' + ); + if ( $time >= 31556926 ) { + $value["years"] = floor($time/31556926); + $time = ($time%31556926); + } + if ( $time >= 86400 ) { + $value["days"] = floor($time/86400); + $time = ($time%86400); + } + if ( $time >= 3600 ) { + $value["hours"] = str_pad(floor($time/3600), 2, 0, STR_PAD_LEFT); + $time = ($time%3600); + } + if ( $time >= 60 ) { + $value["minutes"] = str_pad(floor($time/60), 2, 0, STR_PAD_LEFT); + $time = ($time%60); + } + $value["seconds"] = str_pad(floor($time), 2, 0, STR_PAD_LEFT); + + # Get the hour:minute:second version + return $value['hours'] . ':' . $value['minutes'] . ':' . $value['seconds']; + } else { + return false; + } + } + +} // END class + +?> \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/jquery.sparkline.min.js b/wp-content/plugins/google-analyticator/jquery.sparkline.min.js new file mode 100644 index 0000000..8b50d71 --- /dev/null +++ b/wp-content/plugins/google-analyticator/jquery.sparkline.min.js @@ -0,0 +1,72 @@ +/* jquery.sparkline 1.4.2 - http://omnipotent.net/jquery.sparkline/ */ + +(function($){$.fn.simpledraw=function(width,height,use_existing){if(use_existing&&this[0].vcanvas)return this[0].vcanvas;if(width==undefined)width=$(this).innerWidth();if(height==undefined)height=$(this).innerHeight();if($.browser.hasCanvas){return new vcanvas_canvas(width,height,this);}else if($.browser.msie){return new vcanvas_vml(width,height,this);}else{return false;}};var pending=[];$.fn.sparkline=function(uservalues,options){var options=$.extend({type:'line',lineColor:'#00f',fillColor:'#cdf',defaultPixelsPerValue:3,width:'auto',height:'auto',composite:false},options?options:{});return this.each(function(){var render=function(){var values=(uservalues=='html'||uservalues==undefined)?$(this).text().split(','):uservalues;var width=options.width=='auto'?values.length*options.defaultPixelsPerValue:options.width;if(options.height=='auto'){if(!options.composite||!this.vcanvas){var tmp=document.createElement('span');tmp.innerHTML='a';$(this).html(tmp);height=$(tmp).innerHeight();$(tmp).remove();}}else{height=options.height;} +$.fn.sparkline[options.type].call(this,values,options,width,height);} +if(($(this).html()&&$(this).is(':hidden'))||($.fn.jquery<"1.3.0"&&$(this).parents().is(':hidden'))){pending.push([this,render]);}else{render.call(this);}});};$.sparkline_display_visible=function(){for(var i=pending.length-1;i>=0;i--){var el=pending[i][0];if($(el).is(':visible')&&!$(el).parents().is(':hidden')){pending[i][1].call(el);pending.splice(i,1);}}};$.fn.sparkline.line=function(values,options,width,height){var options=$.extend({spotColor:'#f80',spotRadius:1.5,minSpotColor:'#f80',maxSpotColor:'#f80',normalRangeMin:undefined,normalRangeMax:undefined,normalRangeColor:'#ccc',chartRangeMin:undefined,chartRangeMax:undefined},options?options:{});var xvalues=[],yvalues=[];for(i=0;imaxy) +maxy=options.normalRangeMax;} +if(options.chartRangeMin!=undefined&&options.chartRangeMinmaxy){maxy=options.chartRangeMax;} +var rangex=maxx-minx==0?1:maxx-minx;var rangey=maxy-miny==0?1:maxy-miny;var vl=yvalues.length-1;if(vl<1){this.innerHTML='';return;} +var target=$(this).simpledraw(width,height,options.composite);if(target){var canvas_width=target.pixel_width;var canvas_height=target.pixel_height;var canvas_top=0;var canvas_left=0;if(options.spotRadius&&(canvas_width<(options.spotRadius*4)||canvas_height<(options.spotRadius*4))){options.spotRadius=0;} +if(options.spotRadius){if(options.minSpotColor||(options.spotColor&&yvalues[vl]==miny)) +canvas_height-=Math.ceil(options.spotRadius);if(options.maxSpotColor||(options.spotColor&&yvalues[vl]==maxy)){canvas_height-=Math.ceil(options.spotRadius);canvas_top+=Math.ceil(options.spotRadius);} +if(options.minSpotColor||options.maxSpotColor&&(yvalues[0]==miny||yvalues[0]==maxy)){canvas_left+=Math.ceil(options.spotRadius);canvas_width-=Math.ceil(options.spotRadius);} +if(options.spotColor||(options.minSpotColor||options.maxSpotColor&&(yvalues[vl]==miny||yvalues[vl]==maxy))) +canvas_width-=Math.ceil(options.spotRadius);} +canvas_height--;if(options.normalRangeMin!=undefined){var ytop=canvas_top+Math.round(canvas_height-(canvas_height*((options.normalRangeMax-miny)/rangey)));var height=Math.round((canvas_height*(options.normalRangeMax-options.normalRangeMin))/rangey);target.drawRect(canvas_left,ytop,canvas_width,height,undefined,options.normalRangeColor);} +var path=[[canvas_left,canvas_top+canvas_height]];for(var i=0;imax){max=options.chartRangeMax;} +if(options.zeroAxis==undefined)options.zeroAxis=min<0;var range=max-min==0?1:max-min;var target=$(this).simpledraw(width,height);if(target){var canvas_width=target.pixel_width;var canvas_height=target.pixel_height;var yzero=min<0&&options.zeroAxis?canvas_height-Math.round(canvas_height*(Math.abs(min)/range))-1:canvas_height-1;for(var i=0;i0){var y=0;var height=half_height-1;var color=options.posBarColor;}else{var y=half_height-1;var height=2;var color=options.zeroBarColor;} +if(options.colorMap[values[i]]){color=options.colorMap[values[i]];} +target.drawRect(x,y,options.barWidth-1,height-1,color,color);}}else{this.innerHTML='';}};$.fn.sparkline.discrete=function(values,options,width,height){values=$.map(values,Number);var options=$.extend({lineHeight:'auto',thresholdColor:undefined,thresholdValue:0,chartRangeMax:undefined,chartRangeMin:undefined},options);width=options.width=='auto'?values.length*2:width;var interval=Math.floor(width/values.length);var target=$(this).simpledraw(width,height);if(target){var canvas_width=target.pixel_width;var canvas_height=target.pixel_height;var line_height=options.lineHeight=='auto'?Math.round(canvas_height*0.3):options.lineHeight;var pheight=canvas_height-line_height;var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);if(options.chartRangeMin!=undefined&&options.chartRangeMinmax){max=options.chartRangeMax;} +var range=max-min;for(var i=0;i1){var canvas_width=target.pixel_width-Math.ceil(options.targetWidth/2);var canvas_height=target.pixel_height;var min=Math.min.apply(Math,values);var max=Math.max.apply(Math,values);if(options.base==undefined){var min=min<0?min:0;}else{min=options.base;} +var range=max-min;for(i=2;i1){var canvas_width=target.pixel_width;var canvas_height=target.pixel_height;var radius=Math.floor(Math.min(canvas_width,canvas_height)/2);var total=0;for(var i=0;i0){end=next+(circle*(values[i]/total));} +target.drawPieSlice(radius,radius,radius,start,end,undefined,options.sliceColors[i%options.sliceColors.length]);next=end;}}};function quartile(values,q){if(q==2){var vl2=Math.floor(values.length/2);return values.length%2?values[vl2]:(values[vl2]+values[vl2+1])/2;}else{var vl4=Math.floor(values.length/4);return values.length%2?(values[vl4*q]+values[vl4*q+1])/2:values[vl4*q];}};$.fn.sparkline.box=function(values,options,width,height){values=$.map(values,Number);var options=$.extend({raw:false,boxLineColor:'black',boxFillColor:'#cdf',whiskerColor:'black',outlierLineColor:'#333',outlierFillColor:'white',medianColor:'red',showOutliers:true,outlierIQR:1.5,spotRadius:1.5,target:undefined,targetColor:'#4a2',chartRangeMax:undefined,chartRangeMin:undefined},options);width=options.width=='auto'?'4.0em':width;minvalue=options.chartRangeMin==undefined?Math.min.apply(Math,values):options.chartRangeMin;maxvalue=options.chartRangeMax==undefined?Math.max.apply(Math,values):options.chartRangeMax;var target=$(this).simpledraw(width,height);if(target&&values.length>1){var canvas_width=target.pixel_width;var canvas_height=target.pixel_height;if(options.raw){if(options.showOutliers&&values.length>5){var loutlier=values[0],lwhisker=values[1],q1=values[2],q2=values[3],q3=values[4],rwhisker=values[5],routlier=values[6];}else{var lwhisker=values[0],q1=values[1],q2=values[2],q3=values[3],rwhisker=values[4];}}else{values.sort(function(a,b){return a-b;});var q1=quartile(values,1);var q2=quartile(values,2);var q3=quartile(values,3);var iqr=q3-q1;if(options.showOutliers){var lwhisker=undefined,rwhisker=undefined;for(var i=0;iq1-(iqr*options.outlierIQR)) +lwhisker=values[i];if(values[i]rwhisker) +target.drawCircle((routlier-minvalue)*unitsize+canvas_left,canvas_height/2,options.spotRadius,options.outlierLineColor,options.outlierFillColor);} +target.drawRect(Math.round((q1-minvalue)*unitsize+canvas_left),Math.round(canvas_height*0.1),Math.round((q3-q1)*unitsize),Math.round(canvas_height*0.8),options.boxLineColor,options.boxFillColor);target.drawLine(Math.round((lwhisker-minvalue)*unitsize+canvas_left),Math.round(canvas_height/2),Math.round((q1-minvalue)*unitsize+canvas_left),Math.round(canvas_height/2),options.lineColor);target.drawLine(Math.round((lwhisker-minvalue)*unitsize+canvas_left),Math.round(canvas_height/4),Math.round((lwhisker-minvalue)*unitsize+canvas_left),Math.round(canvas_height-canvas_height/4),options.whiskerColor);target.drawLine(Math.round((rwhisker-minvalue)*unitsize+canvas_left),Math.round(canvas_height/2),Math.round((q3-minvalue)*unitsize+canvas_left),Math.round(canvas_height/2),options.lineColor);target.drawLine(Math.round((rwhisker-minvalue)*unitsize+canvas_left),Math.round(canvas_height/4),Math.round((rwhisker-minvalue)*unitsize+canvas_left),Math.round(canvas_height-canvas_height/4),options.whiskerColor);target.drawLine(Math.round((q2-minvalue)*unitsize+canvas_left),Math.round(canvas_height*0.1),Math.round((q2-minvalue)*unitsize+canvas_left),Math.round(canvas_height*0.9),options.medianColor);if(options.target){var size=Math.ceil(options.spotRadius);target.drawLine(Math.round((options.target-minvalue)*unitsize+canvas_left),Math.round((canvas_height/2)-size),Math.round((options.target-minvalue)*unitsize+canvas_left),Math.round((canvas_height/2)+size),options.targetColor);target.drawLine(Math.round((options.target-minvalue)*unitsize+canvas_left-size),Math.round(canvas_height/2),Math.round((options.target-minvalue)*unitsize+canvas_left+size),Math.round(canvas_height/2),options.targetColor);}}else{this.innerHTML='';}};if(!Array.prototype.indexOf){Array.prototype.indexOf=function(entry){for(var i=0;i';this.canvas.insertAdjacentHTML('beforeEnd',groupel);this.group=$(this.canvas).children()[0];},drawShape:function(path,lineColor,fillColor){var vpath=[];for(var i=0;i' ++' ';this.group.insertAdjacentHTML('beforeEnd',vel);},drawCircle:function(x,y,radius,lineColor,fillColor){x-=radius+1;y-=radius+1;var stroke=lineColor==undefined?' stroked="false" ':' strokeWeight="1" strokeColor="'+lineColor+'" ';var fill=fillColor==undefined?' filled="false"':' fillColor="'+fillColor+'" filled="true" ';var vel='';this.group.insertAdjacentHTML('beforeEnd',vel);},drawPieSlice:function(x,y,radius,startAngle,endAngle,lineColor,fillColor){if(startAngle==endAngle){return;} +if((endAngle-startAngle)==(2*Math.PI)){startAngle=0.0;endAngle=(2*Math.PI);} +var startx=x+Math.round(Math.cos(startAngle)*radius);var starty=y+Math.round(Math.sin(startAngle)*radius);var endx=x+Math.round(Math.cos(endAngle)*radius);var endy=y+Math.round(Math.sin(endAngle)*radius);var vpath=[x-radius,y-radius,x+radius,y+radius,startx,starty,endx,endy];var stroke=lineColor==undefined?' stroked="false" ':' strokeWeight="1" strokeColor="'+lineColor+'" ';var fill=fillColor==undefined?' filled="false"':' fillColor="'+fillColor+'" filled="true" ';var vel='' ++' ';this.group.insertAdjacentHTML('beforeEnd',vel);},drawRect:function(x,y,width,height,lineColor,fillColor){return this.drawShape([[x,y],[x,y+height],[x+width,y+height],[x+width,y],[x,y]],lineColor,fillColor);}});})(jQuery); \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/readme.txt b/wp-content/plugins/google-analyticator/readme.txt new file mode 100644 index 0000000..3b066b1 --- /dev/null +++ b/wp-content/plugins/google-analyticator/readme.txt @@ -0,0 +1,267 @@ +=== Google Analyticator === +Contributors: cavemonkey50, jesse_altman, spiralwebconsulting +Donate link: http://plugins.spiralwebconsulting.com/analyticator.html#donate +Tags: stats, statistics, google, analytics, google analytics, tracking, widget +Requires at least: 2.7 +Tested up to: 2.8.3 +Stable tag: 5.3.1 + +Adds the necessary JavaScript code to enable Google Analytics. Includes widgets for Analytics data display. + +== Description == + +Google Analyticator adds the necessary JavaScript code to enable Google Analytics logging on any WordPress blog. This eliminates the need to edit your template code to begin logging. Google Analyticator also includes several widgets for displaying Analytics data in the admin and on your blog. + +*Google Analyticator is brought to you for free by [Spiral Web Consulting](http://spiralwebconsulting.com/). Spiral Web Consulting is a small web development firm specializing in PHP development. Visit our website to learn more, and don't hesitate to ask us to develop your next big WordPress plugin idea.* + += Features = + +Google Analyticator Has the Following Features: + +- Supports standard Google Analytics tracking +- **NEW!** Includes an admin dashboard widget that displays a graph of the last 30 days of visitors, a summary of site usage, the top pages, the top referrers, and the top searches +- Includes a widget that can be used to display visitor stat information on the front-end +- Supports outbound link tracking of all links on the page, including links not managed by WordPress +- Supports download link tracking +- Supports event tracking with outbound links / downloads instead of the old pageview tracking method +- Allows hiding of Administrator visits without affecting Google Analytics' site overlay feature +- Supports any advanced tracking code Google provides +- Installs easily - unlike other plugins, the user doesn't even have to know their Analytics UID +- Allows tracking code to be placed in the footer to ensure faster load times +- Provides complete control over options; disable any feature if needed +- **NEW!** Supports localization - get the settings page in your language of choice + +For more information, visit the [Google Analyticator plugin page](http://plugins.spiralwebconsulting.com/analyticator.html). + +== Installation == + +Please visit [Spiral Web Consulting's forum](http://plugins.spiralwebconsulting.com/forums/viewtopic.php?f=5&t=17) for installation information. + +== Frequently Asked Questions == + +Please visit [Spiral Web Consulting's forum](http://plugins.spiralwebconsulting.com/forums/viewforum.php?f=5) for the latest FAQ information. + +== Screenshots == + +1. An example of the admin dashboard widget displaying stats pulled from Google Analytics. +2. The top half of the settings page. +3. The configuration options for the front-end widget. +4. An example of a front-end widget configuration. +5. An example of a front-end widget configuration. +6. An example of a front-end widget configuration. + +== Changelog == + += 5.3.1 = +* Corrects a fatal error on the settings page under WordPress 2.7. + += 5.3 = +* Converts API data call to AJAX to reduce the memory needed on page loads. +* Removes memory_limit alterations, since the default amount should be enough now. +* Disables the summary dashboard widget for non-admins, as defined by the admin level setting on Google Analyticator's settings page. + += 5.2.1 = +* Corrects a potential html sanitation vulnerability with text retrieved from the Google Analytics API. + += 5.2 = +* Adds support for deauthorizing with Google Analytics. +* Increases checks on the memory limit and now prevents the memory intensive functionality from running if there is insufficient memory. +* Adds authentication compatibility modes for users having issues with cURL and PHP Streams. +* Improves detection of Google Accounts that are not linked to Analytics accounts. +* Improves detection of accounts without stats. +* Cleans up the authentication URL, preventing the malformed URL error that Google would sometimes display. +* Removes hosted Google accounts from Google's authentication page. +* Adds an error message to the settings page if Google authentication fails. + += 5.1 = +* Fixes the broken/frozen error on the Dashboard introduced in Google Analyticator 5.0. +* Fixes an Internal Server Error received on the settings page under IIS servers. +* Adds an option to completely disable the included widgets. +* Removes the outbound and download prefixes from the Javascript if event tracking is enabled. +* Fixes a bug where the settings page always thought the Google account was authenticated. +* Prevents the Google API from even attempting to connect to Google's servers if the account is not authenticated. +* Increases the checks on returned Google API data to prevent unexpected states. +* Adds missing localized string to settings title. +* Removes the Google authentication and widgets from WordPress 2.7 due to compatibility issues. Users wishing to authenticate and use the widgets should upgrade to WordPress 2.8. +* Prevents PHP warnings from displaying on the dashboard summary widget when an Analytics account is new and does not have a history of data. + += 5.0 = +* Adds a new admin dashboard widget that displays a graph of the last 30 days of visitors, a summary of site usage, the top pages, the top referrers, and the top searches. +* Changes the Google authentication method to AuthSub. This removes the Google username / password requirement. **Users who had previously entered their username / password in the settings page will need to revisit the settings page and authenticate for the widget to continue to function.** +* Adds support for automatically retrieving an Analytics account's UID if Google Analyticator is authenticated with Google. +* Updates the Google Analytics API class to use the WordPress HTTP API, thus removing cURL as a core requirement for the widget. +* Updates the UID setting help to remove old urchin.js references and provide additional help for finding a UID. +* Prepares all strings for localization. If you would like to translate Google Analyticator, [visit our forums](http://plugins.spiralwebconsulting.com/forums/viewforum.php?f=16). + += 4.3.4 = +* Fixes a bug that was breaking the save button on the settings page in IE. +* Prevents the widget from grabbing Analytics data earlier January 1, 2005. +* Fixes an incorrect default state for the event tracking option. +* Adds the date range used for widget data in an HTML comment to prevent misrepresented stats. + += 4.3.3 = +* Corrects XHTML validator errors present in the stat widget. +* Removes some stray code. + += 4.3.2 = +* Adds support for WordPress' new changelog readme.txt standard. Version information is now available from within the plugin updater. +* Enhances the links on the plugin page. Adds a settings, FAQ, and support link. + += 4.3.1 = +* Fixes a bug that broke the widget page when a username was not entered in settings. + += 4.3 = +* Adds support for event tracking of outbound links and downloads. This is the new, recommended way to track outbound links and downloads with Analytics. Event tracking is enabled by default, so users wishing to keep using the old method should disable this option immediately. See our FAQ for more information. +* Prevents files that are stored on external servers from being tracked as both a download and an external link. +* Corrects a file extension case sensitivity issue that prevented certain download links from being tracked. +* Includes a minified version of the outbound/download tracking javascript instead of the full code. +* Fixes a text size inconstancy on the settings page. + += 4.2.3 = +* Improves error reporting with API authentication. + += 4.2.2 = +* Fixes a bug in IE8 that would not allow the widget to display in the admin properly. + += 4.2.1 = +* Fixes an issue where stable versions of WordPress 2.8 were not using the new widget API. +* Changes SimplePie include to use WordPress' version if possible, since SimplePie is included in WordPress 2.8. +* Adds version number to the Google Analyticator comment. + += 4.2 = +* Adds support for the WordPress 2.8 widget API. +* Removes Google Analyticator comment in the header that if footer tracking is enabled. + += 4.1.1 = +* Adds support for tracking code in the footer with Adsense integration. +* Corrects the widget image location for users with WordPress installed in a sub-directory. +* Prevents Google API calls when widget information is not configured. +* Supports WordPress 2.8. + += 4.1 = +* Fixes a bug that was causing the Stats Widget to display "0" in every instance. +* Adds functionality to allow a custom timeframe to be configured for the visitors widget. +* Adds a function to enable use of the widget for users not using WordPress widgets. +* Adds an option to output the code needed to link Analytics and Adsense accounts. + += 4.0.1 = +* Disables stat widget if cURL does not exist. + += 4.0 = +* Adds Google Analytics API support. +* Adds a widget that will use your Google Analytics stats to display a visitor counter on your front-end. +* Adds functionality to make widget highly customizable in regards to color and text. + += 3.0.3 = +* Fixes a Javascript error on pages that have links without href tags. + += 3.0.2 = +* Improves display of external/download links in Google Analytics (strips http/https from url). +* Fixes a PHP warning message being displayed on pages with error reporting enabled. + += 3.01 = +* Adds an option to disable admin tracking by either removing the tracking code or setting a variable. +* Removes the external tracking code from back-end admin pages that was causing conflicts with other plugins. + += 3.0 = +* Google Analyticator is now supported by Spiral Web Consulting. +* Corrects bugs preventing both external and download link tracking from working. +* Adds settings to configure the external and download link tracking prefixes. +* Changes the way disabling admin tracking works. Now uses a line of code instead of removing the tracking code altogether. This will allow features like the site overlay to work. + += 2.40 = +* Replaces the PHP-based external tracking solution with a jQuery-based one. + += 2.3 = +* Updates the Analytics script to match a change by Google. This should resolve the undefined _gat errors. + += 2.24 = +* Fixes comment author issues once and for all. +* Fixes a SVN merge issue that prevented people from getting the last update. + += 2.23 = +* Reverting last version as it caused issues. + += 2.22 = +* Improves comment author regex causing some issues in WordPress 2.7. Thanks to jdub. + += 2.21 = +* Adds WordPress 2.7 support. + += 2.2 = +* Adds an option to specify the GA script location instead of relying on Google’s auto detect code. This may resolve the _gat is undefined errors. + += 2.14 = +* Stops the external link tracking code from appearing in feeds, breaking feed validation. +* Adds compatibility for a very rare few users who could not save options. + += 2.13 = +* Stops the external link tracking code from appearing in feeds, breaking feed validation. + += 2.12 = +* Applies the new administrator level selection to outbound tracking (I forgot to that in the last release). +* Fixes a potential plugin conflict. + += 2.11 = +* Adds an option to change what Google Analyticator considers a WordPress administrator. + += 2.1 = +* Fixes a bug preventing options from being saved under WordPress 2.5. +* Updates option page to comply with WordPress 2.5 user interface changes. +* Note: Users of WordPress 2.3 may wish to stay on 2.02 as the UI will look ‘weird’ under 2.3. + += 2.02 = +* Corrects potential XHTML validation issues with external link tracking. + += 2.01 = +* Corrects XHTML validation issues with ga.js. + += 2.0 = +* Adds support for the latest version of Google Analytics’ tracking code (ga.js). +* Reverts external link/download tracking method back to writing the tracking code in the HTML source, due to the previous Javascript library no longer being support. Users of previous Google Analyticator versions may safely delete ga_external-links.js. +* Slightly modified the way extra code is handled. There are now two sections (before tracker initialization and after tracker initialization) to handle ga.js’ extra functions. Refer to Google Analytics’ support documentation for use of these sections. + += 1.54 = +* Corrects problem where certain installation of WordPress do not have the user level value. + += 1.53 = +* Finally fixes the “Are you sure?†bug some users experience. + += 1.52 = +* Addresses compatibility issue with other JavaScript plugins. + += 1.5 = +* Now using JavaScript solution for keeping track of external links instead of the current URL rewrite method. JavaScript library is courtesy of Terenzani.it. +* Note: Google Analyticator is now in a folder. If upgrading from a version less than 1.5, delete google-analyticator.php from your /wp-content/plugins/ folder before proceeding. + += 1.42 = +* Fixes a bug where outbound link tracking would be disabled if the tracking code was in the footer. + += 1.41 = +* Added an option to insert the tracking code in the footer instead of the header. + += 1.4 = +* Adds support for download tracking. + += 1.31 = +* Fixes a small bug with backslashes in the additional tracking code box. + += 1.3 = +* WordPress 2.0 beta is now supported. +* Missing options page bug is finally fixed. + += 1.2 = +* Added support for outbound links. + += 1.12 = +* Fixing missing option button page bug. + += 1.11 = +* Fixed a bug where options page would sometimes not display. + += 1.1 = +* Added an option to disable administrator logging. +* Added an option to add any additional tracking code that Google has. + += 1.0 = +* Initial release. \ No newline at end of file diff --git a/wp-content/plugins/google-analyticator/screenshot-1.png b/wp-content/plugins/google-analyticator/screenshot-1.png new file mode 100644 index 0000000..2c08506 Binary files /dev/null and b/wp-content/plugins/google-analyticator/screenshot-1.png differ diff --git a/wp-content/plugins/google-analyticator/screenshot-2.png b/wp-content/plugins/google-analyticator/screenshot-2.png new file mode 100644 index 0000000..e112589 Binary files /dev/null and b/wp-content/plugins/google-analyticator/screenshot-2.png differ diff --git a/wp-content/plugins/google-analyticator/screenshot-3.png b/wp-content/plugins/google-analyticator/screenshot-3.png new file mode 100644 index 0000000..a81dc75 Binary files /dev/null and b/wp-content/plugins/google-analyticator/screenshot-3.png differ diff --git a/wp-content/plugins/google-analyticator/screenshot-4.png b/wp-content/plugins/google-analyticator/screenshot-4.png new file mode 100644 index 0000000..e4e5f78 Binary files /dev/null and b/wp-content/plugins/google-analyticator/screenshot-4.png differ diff --git a/wp-content/plugins/google-analyticator/screenshot-5.png b/wp-content/plugins/google-analyticator/screenshot-5.png new file mode 100644 index 0000000..e43d29c Binary files /dev/null and b/wp-content/plugins/google-analyticator/screenshot-5.png differ diff --git a/wp-content/plugins/google-analyticator/screenshot-6.png b/wp-content/plugins/google-analyticator/screenshot-6.png new file mode 100644 index 0000000..277cfbf Binary files /dev/null and b/wp-content/plugins/google-analyticator/screenshot-6.png differ diff --git a/wp-content/plugins/hello.php b/wp-content/plugins/hello.php new file mode 100644 index 0000000..a80b1ea --- /dev/null +++ b/wp-content/plugins/hello.php @@ -0,0 +1,84 @@ +Hello, Dolly in the upper right of your admin screen on every page. +Author: Matt Mullenweg +Version: 1.5.1 +Author URI: http://ma.tt/ +*/ + +function hello_dolly_get_lyric() { + /** These are the lyrics to Hello Dolly */ + $lyrics = "Hello, Dolly +Well, hello, Dolly +It's so nice to have you back where you belong +You're lookin' swell, Dolly +I can tell, Dolly +You're still glowin', you're still crowin' +You're still goin' strong +We feel the room swayin' +While the band's playin' +One of your old favourite songs from way back when +So, take her wrap, fellas +Find her an empty lap, fellas +Dolly'll never go away again +Hello, Dolly +Well, hello, Dolly +It's so nice to have you back where you belong +You're lookin' swell, Dolly +I can tell, Dolly +You're still glowin', you're still crowin' +You're still goin' strong +We feel the room swayin' +While the band's playin' +One of your old favourite songs from way back when +Golly, gee, fellas +Find her a vacant knee, fellas +Dolly'll never go away +Dolly'll never go away +Dolly'll never go away again"; + + // Here we split it into lines + $lyrics = explode("\n", $lyrics); + + // And then randomly choose a line + return wptexturize( $lyrics[ mt_rand(0, count($lyrics) - 1) ] ); +} + +// This just echoes the chosen line, we'll position it later +function hello_dolly() { + $chosen = hello_dolly_get_lyric(); + echo "

    $chosen

    "; +} + +// Now we set that function up to execute when the admin_footer action is called +add_action('admin_footer', 'hello_dolly'); + +// We need some CSS to position the paragraph +function dolly_css() { + // This makes sure that the posinioning is also good for right-to-left languages + $x = ( 'rtl' == get_bloginfo( 'text_direction' ) ) ? 'left' : 'right'; + + echo " + + "; +} + +add_action('admin_head', 'dolly_css'); + +?> diff --git a/wp-content/plugins/index.php b/wp-content/plugins/index.php new file mode 100644 index 0000000..4e6c07c --- /dev/null +++ b/wp-content/plugins/index.php @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/wp-content/themes/classic/comments-popup.php b/wp-content/themes/classic/comments-popup.php new file mode 100644 index 0000000..68d5a9c --- /dev/null +++ b/wp-content/themes/classic/comments-popup.php @@ -0,0 +1,126 @@ + + + + <?php echo get_option('blogname'); ?> - <?php echo sprintf(__("Comments on %s"), the_title('','',false)); ?> + + + + + + + +

    + + + +

    + +

    RSS feed for comments on this post."); ?>

    + + +

    URL to TrackBack this entry is:"); ?>

    + + + + + +
      + +
    1. + +

      @

      +
    2. + + +
    + +

    + + + +

    +

    HTML allowed:"); ?>

    + +
    + +

    '.$user_identity.''); ?>

    + +

    + + +

    + +

    + + +

    + +

    + + +

    + + +

    + +
    + +

    + +

    + + " /> + " /> +

    + ID); ?> +
    + +

    + + +
    + + +

    Sorry, no posts matched your criteria.

    + + + + +

    Powered by WordPress"),__("Powered by WordPress, state-of-the-art semantic personal publishing platform.")); ?>

    + + + + diff --git a/wp-content/themes/classic/comments.php b/wp-content/themes/classic/comments.php new file mode 100644 index 0000000..57d6cf3 --- /dev/null +++ b/wp-content/themes/classic/comments.php @@ -0,0 +1,82 @@ + +

    + + +

    + + ">» + +

    + + +
      + + +
    1. id="comment-"> + + +

      @

      +
    2. + + + +
    + + +

    + + +

    RSS feed for comments on this post.')); ?> + + URL'); ?> + +

    + + +

    + + +

    logged in to post a comment.'), wp_login_url( get_permalink() ) );?>

    + + +
    + + + +

    '.$user_identity.''); ?>

    + + + +

    +

    + +

    +

    + +

    +

    + + + + + +

    + +

    + +

    +ID); ?> + +
    + + + + +

    + diff --git a/wp-content/themes/classic/footer.php b/wp-content/themes/classic/footer.php new file mode 100644 index 0000000..819ed42 --- /dev/null +++ b/wp-content/themes/classic/footer.php @@ -0,0 +1,18 @@ + + +
    + + + +

    WordPress"), __("Powered by WordPress, state-of-the-art semantic personal publishing platform.")); ?>

    + +
    + + + + \ No newline at end of file diff --git a/wp-content/themes/classic/functions.php b/wp-content/themes/classic/functions.php new file mode 100644 index 0000000..1bc06e2 --- /dev/null +++ b/wp-content/themes/classic/functions.php @@ -0,0 +1,17 @@ + '
  • ', + 'after_widget' => '
  • ', + 'before_title' => '', + 'after_title' => '', + )); + +?> diff --git a/wp-content/themes/classic/header.php b/wp-content/themes/classic/header.php new file mode 100644 index 0000000..f16c280 --- /dev/null +++ b/wp-content/themes/classic/header.php @@ -0,0 +1,30 @@ + + +> + + + + + <?php wp_title('«', true, 'right'); ?> <?php bloginfo('name'); ?> + + + + + + + + + +> +
    +

    + +
    + diff --git a/wp-content/themes/classic/index.php b/wp-content/themes/classic/index.php new file mode 100644 index 0000000..6cb8c63 --- /dev/null +++ b/wp-content/themes/classic/index.php @@ -0,0 +1,36 @@ + + + + +',''); ?> + +
    id="post-"> +

    +
    @
    + +
    + +
    + + + +
    + + + + +

    + + + + + diff --git a/wp-content/themes/classic/rtl.css b/wp-content/themes/classic/rtl.css new file mode 100644 index 0000000..18188ff --- /dev/null +++ b/wp-content/themes/classic/rtl.css @@ -0,0 +1,92 @@ +/* Based on Arabic (RTL) version of WordPress Classic theme, converted by Serdal (Serdal.com) */ + +#menu ul ul, #wp-calendar caption, #wp-calendar #prev a { text-align: right; } +#wp-calendar #next a, .feedback { text-align: left; } + +blockquote { + border-left: 0; + border-right: 5px solid #ccc; + margin-left: auto; + margin-right: 1.5em; + padding-left: 0; + padding-right: 5px; +} + +body { font-family: 'Geeza Pro', Tahoma, 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; } + +h2 { font: 95% 'Al Bayan', 'Traditional Arabic', "Times New Roman", Times, serif; } + +p, li, .feedback { + font: 90%/175% 'Geeza Pro', Tahoma, 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; + text-align: justify; +} + +acronym, abbr, span.caps, h2, p, li, #header, #menu ul li, #menu ul ul li, #wp-calendar td, .feedback, .meta, .meta a { letter-spacing: normal; } + +#commentlist li ul { + border-left: 0; + border-right: 1px solid #ddd; +} + +#commentlist li .avatar { + margin-right: 0; + margin-left: 12px; +} + +#commentlist li .avatar { + margin-right: 0; + margin-left: 12px; +} + +#content { + margin: 30px 3em 0 13em; + padding-right: 0; + padding-left: 60px; +} + +#header { + border-left: solid 1px #9a9; + border-right: solid 1px #565; + font: normal normal 230% 'Al Bayan', 'Traditional Arabic', 'Times New Roman', Times, serif; + padding: 15px 60px 15px 10px; +} + +#menu { + border-left: 0; + border-right: 1px dotted #ccc; + padding: 20px 30px 10px 0; + right: auto; + left: 2px; +} + +#menu form { margin: 0 13px 0 0; } + +#menu ul { + padding-left: 0; + padding-right: 3px; +} + +#menu ul li { font: normal normal 110% 'Geeza Pro', Tahoma, 'Times New Roman', Times, serif; } + +#menu ul ul li { + font: normal normal 12px/115% 'Geeza Pro', Tahoma, 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; + padding-left: 0; + padding-right: 12px; +} + +#menu ul ul ul.children { + padding-left: 0; + padding-right: 4px; +} + +#wp-calendar #next a { + padding-right: 0; + padding-left: 10px; +} + +#wp-calendar #prev a { + padding-left: 0; + padding-right: 10px; +} + +#wp-calendar td { font: normal normal 12px 'Geeza Pro', Tahoma, 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; } diff --git a/wp-content/themes/classic/screenshot.png b/wp-content/themes/classic/screenshot.png new file mode 100644 index 0000000..6692130 Binary files /dev/null and b/wp-content/themes/classic/screenshot.png differ diff --git a/wp-content/themes/classic/sidebar.php b/wp-content/themes/classic/sidebar.php new file mode 100644 index 0000000..ab7d745 --- /dev/null +++ b/wp-content/themes/classic/sidebar.php @@ -0,0 +1,47 @@ + + + + diff --git a/wp-content/themes/classic/style.css b/wp-content/themes/classic/style.css new file mode 100644 index 0000000..a3b8df9 --- /dev/null +++ b/wp-content/themes/classic/style.css @@ -0,0 +1,368 @@ +/* +Theme Name: WordPress Classic +Theme URI: http://wordpress.org/ +Description: The original WordPress theme that graced versions 1.2.x and prior. +Version: 1.5 +Author: Dave Shea +Tags: mantle color, variable width, two columns, widgets + +Default WordPress by Dave Shea || http://mezzoblue.com +Modifications by Matthew Mullenweg || http://photomatt.net +This is just a basic layout, with only the bare minimum defined. +Please tweak this and make it your own. :) +*/ + +.screen-reader-text { + position: absolute; + left: -1000em; +} + +a { + color: #675; +} + +a img { + border: none; +} + +a:visited { + color: #342; +} + +a:hover { + color: #9a8; +} + +acronym, abbr { + border-bottom: 1px dashed #333; +} + +acronym, abbr, span.caps { + font-size: 90%; + letter-spacing: .07em; +} + +acronym, abbr { + cursor: help; +} + +blockquote { + border-left: 5px solid #ccc; + margin-left: 1.5em; + padding-left: 5px; +} + +body { + background: #fff; + border: 2px solid #565; + border-bottom: 1px solid #565; + border-top: 3px solid #565; + color: #000; + font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; + margin: 0; + padding: 0; +} + +cite { + font-size: 90%; + font-style: normal; +} + +h2 { + border-bottom: 1px dotted #ccc; + font: 95% "Times New Roman", Times, serif; + letter-spacing: 0.2em; + margin: 15px 0 2px 0; + padding-bottom: 2px; +} + +h3 { + border-bottom: 1px dotted #eee; + font-family: "Times New Roman", Times, serif; + margin-top: 0; +} + +ol#comments li p { + font-size: 100%; +} + +p, li, .feedback { + font: 90%/175% 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; + letter-spacing: -1px; +} + +/* classes used by the_meta() */ +ul.post-meta { + list-style: none; +} + +ul.post-meta span.post-meta-key { + font-weight: bold; +} + +.credit { + background: #90a090; + border-top: 3px double #aba; + color: #fff; + font-size: 11px; + margin: 10px 0 0 0; + padding: 3px; + text-align: center; +} + +.credit a:link, .credit a:hover { + color: #fff; +} + +.feedback { + color: #ccc; + text-align: right; + clear: both; +} + +.meta { + font-size: .75em; +} + +.meta li, ul.post-meta li { + display: inline; +} + +.meta ul { + display: inline; + list-style: none; + margin: 0; + padding: 0; +} + +.meta, .meta a { + color: #808080; + font-weight: normal; + letter-spacing: 0; +} + +.storytitle { + margin: 0; +} + +.storytitle a { + text-decoration: none; +} + +#commentform #author, #commentform #email, #commentform #url, #commentform textarea { + background: #fff; + border: 1px solid #333; + padding: .2em; +} + +#commentform textarea { + width: 100%; +} + +#commentlist li ul { + border-left: 1px solid #ddd; + font-size: 110%; + list-style-type: none; +} + +#commentlist li .avatar { + float: right; + margin-right: 25px; + border: 1px dotted #ccc; + padding: 2px; +} + +#content { + margin: 30px 13em 0 3em; + padding-right: 60px; +} + +#header { + background: #90a090; + border-bottom: 3px double #aba; + border-left: 1px solid #9a9; + border-right: 1px solid #565; + border-top: 1px solid #9a9; + font: italic normal 230% 'Times New Roman', Times, serif; + letter-spacing: 0.2em; + margin: 0; + padding: 15px 10px 15px 60px; +} + +#header a { + color: #fff; + text-decoration: none; +} + +#header a:hover { + text-decoration: underline; +} + +#menu { + background: #fff; + border-left: 1px dotted #ccc; + border-top: 3px solid #e0e6e0; + padding: 20px 0 10px 30px; + position: absolute; + right: 2px; + top: 0; + width: 11em; +} + +#menu form { + margin: 0 0 0 13px; +} + +#menu input#s { + width: 80%; + background: #eee; + border: 1px solid #999; + color: #000; +} + +#menu ul { + color: #ccc; + font-weight: bold; + list-style-type: none; + margin: 0; + padding-left: 3px; + text-transform: lowercase; +} + +#menu ul li { + font: italic normal 110% 'Times New Roman', Times, serif; + letter-spacing: 0.1em; + margin-top: 10px; + padding-bottom: 2px; /*border-bottom: dotted 1px #ccc;*/ +} + +#menu ul ul { + font-variant: normal; + font-weight: normal; + line-height: 100%; + list-style-type: none; + margin: 0; + padding: 0; + text-align: left; +} + +#menu ul ul li { + border: 0; + font: normal normal 12px/115% 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; + letter-spacing: 0; + margin-top: 0; + padding: 0; + padding-left: 12px; +} + +#menu ul ul li a { + color: #000; + text-decoration: none; +} + +#menu ul ul li a:hover { + border-bottom: 1px solid #809080; +} + +#menu ul ul ul.children { + font-size: 142%; + padding-left: 4px; +} + +#wp-calendar { + border: 1px solid #ddd; + empty-cells: show; + font-size: 14px; + margin: 0; + width: 90%; +} + +#wp-calendar #next a { + padding-right: 10px; + text-align: right; +} + +#wp-calendar #prev a { + padding-left: 10px; + text-align: left; +} + +#wp-calendar a { + display: block; + text-decoration: none; +} + +#wp-calendar a:hover { + background: #e0e6e0; + color: #333; +} + +#wp-calendar caption { + color: #999; + font-size: 16px; + text-align: left; +} + +#wp-calendar td { + color: #ccc; + font: normal 12px 'Lucida Grande', 'Lucida Sans Unicode', Verdana, sans-serif; + letter-spacing: normal; + padding: 2px 0; + text-align: center; +} + +#wp-calendar td.pad:hover { + background: #fff; +} + +#wp-calendar td:hover, #wp-calendar #today { + background: #eee; + color: #bbb; +} + +#wp-calendar th { + font-style: normal; + text-transform: capitalize; +} + +/* Captions & aligment */ +.aligncenter, +div.aligncenter { + display: block; + margin-left: auto; + margin-right: auto; +} + +.alignleft { + float: left; +} + +.alignright { + float: right; +} + +.wp-caption { + border: 1px solid #ddd; + text-align: center; + background-color: #f3f3f3; + padding-top: 4px; + margin: 10px; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} + +.wp-caption img { + margin: 0; + padding: 0; + border: 0 none; +} + +.wp-caption p.wp-caption-text { + font-size: 11px; + line-height: 17px; + padding: 0 4px 5px; + margin: 0; +} +/* End captions & aligment */ diff --git a/wp-content/themes/default/404.php b/wp-content/themes/default/404.php new file mode 100644 index 0000000..f9fee47 --- /dev/null +++ b/wp-content/themes/default/404.php @@ -0,0 +1,18 @@ + + +
    + +

    Error 404 - Not Found

    + +
    + + + + \ No newline at end of file diff --git a/wp-content/themes/default/archive.php b/wp-content/themes/default/archive.php new file mode 100644 index 0000000..70c2a8c --- /dev/null +++ b/wp-content/themes/default/archive.php @@ -0,0 +1,77 @@ + + +
    + + + + + +

    Archive for the ‘’ Category

    + +

    Posts Tagged ‘

    + +

    Archive for

    + +

    Archive for

    + +

    Archive for

    + +

    Author Archive

    + +

    Blog Archives

    + + + + + + +
    > +

    + + +
    + +
    + + + +
    + + + + + Sorry, but there aren't any posts in the %s category yet.", single_cat_title('',false)); + } else if ( is_date() ) { // If this is a date archive + echo("

    Sorry, but there aren't any posts with this date.

    "); + } else if ( is_author() ) { // If this is a category archive + $userdata = get_userdatabylogin(get_query_var('author_name')); + printf("

    Sorry, but there aren't any posts by %s yet.

    ", $userdata->display_name); + } else { + echo("

    No posts found.

    "); + } + get_search_form(); + + endif; +?> + +
    + + + + diff --git a/wp-content/themes/default/archives.php b/wp-content/themes/default/archives.php new file mode 100644 index 0000000..2042805 --- /dev/null +++ b/wp-content/themes/default/archives.php @@ -0,0 +1,29 @@ + + + + +
    + + + +

    Archives by Month:

    +
      + +
    + +

    Archives by Subject:

    +
      + +
    + +
    + + diff --git a/wp-content/themes/default/comments-popup.php b/wp-content/themes/default/comments-popup.php new file mode 100644 index 0000000..49fe744 --- /dev/null +++ b/wp-content/themes/default/comments-popup.php @@ -0,0 +1,124 @@ + + + + <?php echo get_option('blogname'); ?> - Comments on <?php the_title(); ?> + + + + + + + +

    + + +

    Comments

    + +

    RSS feed for comments on this post.

    + + +

    The URL to TrackBack this entry is:

    + + + + + +
      + +
    1. + +

      by @

      +
    2. + + +
    + +

    No comments yet.

    + + + +

    Leave a comment

    +

    Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed:

    + +
    + +

    Logged in as . Log out »

    + +

    + + +

    + +

    + + +

    + +

    + + +

    + + +

    + +
    + +

    + +

    + + " /> + +

    + ID); ?> +
    + +

    Sorry, the comment form is closed at this time.

    + + + + + +

    Sorry, no posts matched your criteria.

    + + + +

    Powered by WordPress

    + + + + diff --git a/wp-content/themes/default/comments.php b/wp-content/themes/default/comments.php new file mode 100644 index 0000000..7e81cdb --- /dev/null +++ b/wp-content/themes/default/comments.php @@ -0,0 +1,96 @@ + +

    This post is password protected. Enter the password to view comments.

    + + + + + +

    to “

    + + + +
      + +
    + + + + + + + + + +

    Comments are closed.

    + + + + + + + +
    + +

    + +
    + +
    + + +

    You must be logged in to post a comment.

    + + +
    + + + +

    Logged in as . Log out »

    + + + +

    /> +

    + +

    /> +

    + +

    +

    + + + + + +

    + +

    + +

    +ID); ?> + +
    + + +
    + + diff --git a/wp-content/themes/default/footer.php b/wp-content/themes/default/footer.php new file mode 100644 index 0000000..02f6d19 --- /dev/null +++ b/wp-content/themes/default/footer.php @@ -0,0 +1,26 @@ + + +
    + +
    + + + + + + + diff --git a/wp-content/themes/default/functions.php b/wp-content/themes/default/functions.php new file mode 100644 index 0000000..9ad4ef2 --- /dev/null +++ b/wp-content/themes/default/functions.php @@ -0,0 +1,425 @@ + '
  • ', + 'after_widget' => '
  • ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); +} + +/** @ignore */ +function kubrick_head() { + $head = "\n"; + if ( '' != $output ) + echo $head . $output . $foot; +} + +add_action('wp_head', 'kubrick_head'); + +function kubrick_header_image() { + return apply_filters('kubrick_header_image', get_option('kubrick_header_image')); +} + +function kubrick_upper_color() { + if (strpos($url = kubrick_header_image_url(), 'header-img.php?') !== false) { + parse_str(substr($url, strpos($url, '?') + 1), $q); + return $q['upper']; + } else + return '69aee7'; +} + +function kubrick_lower_color() { + if (strpos($url = kubrick_header_image_url(), 'header-img.php?') !== false) { + parse_str(substr($url, strpos($url, '?') + 1), $q); + return $q['lower']; + } else + return '4180b6'; +} + +function kubrick_header_image_url() { + if ( $image = kubrick_header_image() ) + $url = get_template_directory_uri() . '/images/' . $image; + else + $url = get_template_directory_uri() . '/images/kubrickheader.jpg'; + + return $url; +} + +function kubrick_header_color() { + return apply_filters('kubrick_header_color', get_option('kubrick_header_color')); +} + +function kubrick_header_color_string() { + $color = kubrick_header_color(); + if ( false === $color ) + return 'white'; + + return $color; +} + +function kubrick_header_display() { + return apply_filters('kubrick_header_display', get_option('kubrick_header_display')); +} + +function kubrick_header_display_string() { + $display = kubrick_header_display(); + return $display ? $display : 'inline'; +} + +add_action('admin_menu', 'kubrick_add_theme_page'); + +function kubrick_add_theme_page() { + if ( isset( $_GET['page'] ) && $_GET['page'] == basename(__FILE__) ) { + if ( isset( $_REQUEST['action'] ) && 'save' == $_REQUEST['action'] ) { + check_admin_referer('kubrick-header'); + if ( isset($_REQUEST['njform']) ) { + if ( isset($_REQUEST['defaults']) ) { + delete_option('kubrick_header_image'); + delete_option('kubrick_header_color'); + delete_option('kubrick_header_display'); + } else { + if ( '' == $_REQUEST['njfontcolor'] ) + delete_option('kubrick_header_color'); + else { + $fontcolor = preg_replace('/^.*(#[0-9a-fA-F]{6})?.*$/', '$1', $_REQUEST['njfontcolor']); + update_option('kubrick_header_color', $fontcolor); + } + if ( preg_match('/[0-9A-F]{6}|[0-9A-F]{3}/i', $_REQUEST['njuppercolor'], $uc) && preg_match('/[0-9A-F]{6}|[0-9A-F]{3}/i', $_REQUEST['njlowercolor'], $lc) ) { + $uc = ( strlen($uc[0]) == 3 ) ? $uc[0]{0}.$uc[0]{0}.$uc[0]{1}.$uc[0]{1}.$uc[0]{2}.$uc[0]{2} : $uc[0]; + $lc = ( strlen($lc[0]) == 3 ) ? $lc[0]{0}.$lc[0]{0}.$lc[0]{1}.$lc[0]{1}.$lc[0]{2}.$lc[0]{2} : $lc[0]; + update_option('kubrick_header_image', "header-img.php?upper=$uc&lower=$lc"); + } + + if ( isset($_REQUEST['toggledisplay']) ) { + if ( false === get_option('kubrick_header_display') ) + update_option('kubrick_header_display', 'none'); + else + delete_option('kubrick_header_display'); + } + } + } else { + + if ( isset($_REQUEST['headerimage']) ) { + check_admin_referer('kubrick-header'); + if ( '' == $_REQUEST['headerimage'] ) + delete_option('kubrick_header_image'); + else { + $headerimage = preg_replace('/^.*?(header-img.php\?upper=[0-9a-fA-F]{6}&lower=[0-9a-fA-F]{6})?.*$/', '$1', $_REQUEST['headerimage']); + update_option('kubrick_header_image', $headerimage); + } + } + + if ( isset($_REQUEST['fontcolor']) ) { + check_admin_referer('kubrick-header'); + if ( '' == $_REQUEST['fontcolor'] ) + delete_option('kubrick_header_color'); + else { + $fontcolor = preg_replace('/^.*?(#[0-9a-fA-F]{6})?.*$/', '$1', $_REQUEST['fontcolor']); + update_option('kubrick_header_color', $fontcolor); + } + } + + if ( isset($_REQUEST['fontdisplay']) ) { + check_admin_referer('kubrick-header'); + if ( '' == $_REQUEST['fontdisplay'] || 'inline' == $_REQUEST['fontdisplay'] ) + delete_option('kubrick_header_display'); + else + update_option('kubrick_header_display', 'none'); + } + } + //print_r($_REQUEST); + wp_redirect("themes.php?page=functions.php&saved=true"); + die; + } + add_action('admin_head', 'kubrick_theme_page_head'); + } + add_theme_page(__('Custom Header'), __('Custom Header'), 'edit_themes', basename(__FILE__), 'kubrick_theme_page'); +} + +function kubrick_theme_page_head() { +?> + + + +

    '.__('Options saved.').'

    '; +?> +
    +

    +
    +
    + +
    +
    +
    +
    + +
    + red', '#FF0000', 'rgb(255, 0, 0)'); ?>
    + #FF0000', '#F00'); ?>
    + #FF0000', '#F00'); ?>
    + + + + + + +
    +
    +
    +
    + + + + + + + + + + + + +

    +
    + +
    + +
    +
    +
    +
    + diff --git a/wp-content/themes/default/header.php b/wp-content/themes/default/header.php new file mode 100644 index 0000000..5c21f94 --- /dev/null +++ b/wp-content/themes/default/header.php @@ -0,0 +1,45 @@ + + +> + + + + +<?php wp_title('«', true, 'right'); ?> <?php bloginfo('name'); ?> + + + + + + + + + + +> +
    + + + +
    diff --git a/wp-content/themes/default/image.php b/wp-content/themes/default/image.php new file mode 100644 index 0000000..4312630 --- /dev/null +++ b/wp-content/themes/default/image.php @@ -0,0 +1,70 @@ + + +
    + + + +
    +

    post_parent); ?> »

    +
    +

    ID, 'medium' ); ?>

    +
    post_excerpt) ) the_excerpt(); // this is the "caption" ?>
    + + Read the rest of this entry »

    '); ?> + + +
    + + + +
    + +
    + + + + + +

    Sorry, no attachments matched your criteria.

    + + + +
    + + diff --git a/wp-content/themes/default/images/audio.jpg b/wp-content/themes/default/images/audio.jpg new file mode 100644 index 0000000..b02e1c8 Binary files /dev/null and b/wp-content/themes/default/images/audio.jpg differ diff --git a/wp-content/themes/default/images/header-img.php b/wp-content/themes/default/images/header-img.php new file mode 100644 index 0000000..50bd3c3 --- /dev/null +++ b/wp-content/themes/default/images/header-img.php @@ -0,0 +1,82 @@ +array('r1', 'g1', 'b1'), 'lower'=>array('r2', 'g2', 'b2')); +foreach ( $vars as $var => $subvars ) { + if ( isset($_GET[$var]) ) { + foreach ( $subvars as $index => $subvar ) { + $length = strlen($_GET[$var]) / 3; + $v = substr($_GET[$var], $index * $length, $length); + if ( $length == 1 ) $v = '' . $v . $v; + $$subvar = hexdec( $v ); + if ( $$subvar < 0 || $$subvar > 255 ) + $default = true; + } + } else { + $default = true; + } +} + +if ( $default ) + list ( $r1, $g1, $b1, $r2, $g2, $b2 ) = array ( 105, 174, 231, 65, 128, 182 ); + +// Create the image +$im = imagecreatefromjpeg($img); + +// Get the background color, define the rectangle height +$white = imagecolorat( $im, 15, 15 ); +$h = 182; + +// Define the boundaries of the rounded edges ( y => array ( x1, x2 ) ) +$corners = array( + 0 => array ( 25, 734 ), + 1 => array ( 23, 736 ), + 2 => array ( 22, 737 ), + 3 => array ( 21, 738 ), + 4 => array ( 21, 738 ), + 177 => array ( 21, 738 ), + 178 => array ( 21, 738 ), + 179 => array ( 22, 737 ), + 180 => array ( 23, 736 ), + 181 => array ( 25, 734 ), + ); + +// Blank out the blue thing +for ( $i = 0; $i < $h; $i++ ) { + $x1 = 19; + $x2 = 740; + imageline( $im, $x1, 18 + $i, $x2, 18 + $i, $white ); +} + +// Draw a new color thing +for ( $i = 0; $i < $h; $i++ ) { + $x1 = 20; + $x2 = 739; + $r = ( $r2 - $r1 != 0 ) ? $r1 + ( $r2 - $r1 ) * ( $i / $h ) : $r1; + $g = ( $g2 - $g1 != 0 ) ? $g1 + ( $g2 - $g1 ) * ( $i / $h ) : $g1; + $b = ( $b2 - $b1 != 0 ) ? $b1 + ( $b2 - $b1 ) * ( $i / $h ) : $b1; + $color = imagecolorallocate( $im, $r, $g, $b ); + if ( array_key_exists($i, $corners) ) { + imageline( $im, $x1, 18 + $i, $x2, 18 + $i, $white ); + list ( $x1, $x2 ) = $corners[$i]; + } + imageline( $im, $x1, 18 + $i, $x2, 18 + $i, $color ); +} + +//die; +header("Content-Type: image/jpeg"); +imagejpeg($im, '', 92); +imagedestroy($im); +?> diff --git a/wp-content/themes/default/images/kubrickbg-ltr.jpg b/wp-content/themes/default/images/kubrickbg-ltr.jpg new file mode 100644 index 0000000..dc74fb8 Binary files /dev/null and b/wp-content/themes/default/images/kubrickbg-ltr.jpg differ diff --git a/wp-content/themes/default/images/kubrickbg-rtl.jpg b/wp-content/themes/default/images/kubrickbg-rtl.jpg new file mode 100644 index 0000000..2e9e237 Binary files /dev/null and b/wp-content/themes/default/images/kubrickbg-rtl.jpg differ diff --git a/wp-content/themes/default/images/kubrickbgcolor.jpg b/wp-content/themes/default/images/kubrickbgcolor.jpg new file mode 100644 index 0000000..4653b68 Binary files /dev/null and b/wp-content/themes/default/images/kubrickbgcolor.jpg differ diff --git a/wp-content/themes/default/images/kubrickbgwide.jpg b/wp-content/themes/default/images/kubrickbgwide.jpg new file mode 100644 index 0000000..77096f2 Binary files /dev/null and b/wp-content/themes/default/images/kubrickbgwide.jpg differ diff --git a/wp-content/themes/default/images/kubrickfooter.jpg b/wp-content/themes/default/images/kubrickfooter.jpg new file mode 100644 index 0000000..d7a4c65 Binary files /dev/null and b/wp-content/themes/default/images/kubrickfooter.jpg differ diff --git a/wp-content/themes/default/images/kubrickheader.jpg b/wp-content/themes/default/images/kubrickheader.jpg new file mode 100644 index 0000000..69441ee Binary files /dev/null and b/wp-content/themes/default/images/kubrickheader.jpg differ diff --git a/wp-content/themes/default/index.php b/wp-content/themes/default/index.php new file mode 100644 index 0000000..ae5bf80 --- /dev/null +++ b/wp-content/themes/default/index.php @@ -0,0 +1,45 @@ + + +
    + + + + + +
    id="post-"> +

    + + +
    + +
    + + +
    + + + + + + + +

    Not Found

    +

    Sorry, but you are looking for something that isn't here.

    + + + + +
    + + + + diff --git a/wp-content/themes/default/links.php b/wp-content/themes/default/links.php new file mode 100644 index 0000000..81fdc00 --- /dev/null +++ b/wp-content/themes/default/links.php @@ -0,0 +1,23 @@ + + + + +
    + +

    Links:

    +
      + +
    + +
    + + diff --git a/wp-content/themes/default/page.php b/wp-content/themes/default/page.php new file mode 100644 index 0000000..660e477 --- /dev/null +++ b/wp-content/themes/default/page.php @@ -0,0 +1,27 @@ + + +
    + + +
    +

    +
    + Read the rest of this page »

    '); ?> + + '

    Pages: ', 'after' => '

    ', 'next_or_number' => 'number')); ?> + +
    +
    + + ', '

    '); ?> +
    + + + + diff --git a/wp-content/themes/default/rtl.css b/wp-content/themes/default/rtl.css new file mode 100644 index 0000000..ba2361b --- /dev/null +++ b/wp-content/themes/default/rtl.css @@ -0,0 +1,127 @@ +/* +Theme name: WordPress Default - kubrick - +Editors: Navid Kashani +Persian Wordpress Project : wp-persian.com +*/ +body, .commentlist li, #commentform input, #commentform textarea, #commentform p, #sidebar, #wp-calendar caption { + font-family:tahoma, arial; +} +#page { + text-align:right; + direction:rtl; +} +h1, h2, h3, #sidebar h2 { + font-family:arial, tahoma; +} +.commentlist li .avatar { + float:left; +} + +.commentlist li { + padding: 5px 10px 10px 5px; + } +.commentlist li ul li { + margin-left: -5px; + margin-right: 10px; +} + +.commentlist p { + margin: 10px 0 10px 5px; +} +#header { + margin:0 1px 0 0; +} +.narrowcolumn { + float:right; + padding: 0 45px 20px 0; +} +.widecolumn { + margin: 5px 150px 0 0; +} +.widecolumn .smallattachment { + margin: 5px 0 5px 5px; +} +.postmetadata { + clear:right; +} +#sidebar { + margin-left: 0; + margin-right: 545px; +} +img.alignright { + margin: 0 7px 2px 0; +} + +img.alignleft { + margin: 0 0 2px 7px; +} + +.alignright { + float: left; +} + +.alignleft { + float: right; +} +code { + display:block; + direction:ltr; + text-align:left; +} +acronym, abbr, span.caps { + letter-spacing:0; /* fix opera bug */ +} +html>body .entry ul { + padding:0 10px 0 0; + text-indent:10px; +} +html>body .entry li { + margin: 7px 10px 8px 0; +} +.entry ol { + padding: 0 35px 0 0; +} +#sidebar ul ul, #sidebar ul ol { + margin: 5px 10px 0 0; +} +#sidebar ul ul ul, #sidebar ul ol { + margin: 0 10px 0 0; +} +#commentform { + margin: 5px 0 0 10px; + } +#commentform input { + margin: 5px 0 1px 5px; +} +#commentform #submit { + float:left; +} +.commentlist p { + margin: 10px 0 10px 5px; +} + +.children .even, .alt { + border-left: 0; + border-right: 1px solid #ddd; +} + +#wp-calendar #next a { + padding-right:0; + padding-left:10px; + text-align:left; +} +#wp-calendar #prev a { + padding-left:0; + padding-right:10px; + text-align:right; +} +blockquote { + margin: 15px 10px 0 30px; + padding-left: 0; + padding-right: 20px; + border-left: 0 none; + border-right: 5px solid #ddd; +} +#email, #url { + direction:ltr; +} \ No newline at end of file diff --git a/wp-content/themes/default/screenshot.png b/wp-content/themes/default/screenshot.png new file mode 100644 index 0000000..e0b1d48 Binary files /dev/null and b/wp-content/themes/default/screenshot.png differ diff --git a/wp-content/themes/default/search.php b/wp-content/themes/default/search.php new file mode 100644 index 0000000..4e7ad6d --- /dev/null +++ b/wp-content/themes/default/search.php @@ -0,0 +1,48 @@ + + +
    + + + +

    Search Results

    + + + + + + +
    > +

    + + + +
    + + + + + + + +

    No posts found. Try a different search?

    + + + + +
    + + + + diff --git a/wp-content/themes/default/sidebar.php b/wp-content/themes/default/sidebar.php new file mode 100644 index 0000000..d73b632 --- /dev/null +++ b/wp-content/themes/default/sidebar.php @@ -0,0 +1,83 @@ + + + diff --git a/wp-content/themes/default/single.php b/wp-content/themes/default/single.php new file mode 100644 index 0000000..c9cb4d8 --- /dev/null +++ b/wp-content/themes/default/single.php @@ -0,0 +1,73 @@ + + +
    + + + + + +
    id="post-"> +

    + +
    + Read the rest of this entry »

    '); ?> + + '

    Pages: ', 'after' => '

    ', 'next_or_number' => 'number')); ?> + Tags: ', ', ', '

    '); ?> + + + +
    +
    + + + + + +

    Sorry, no posts matched your criteria.

    + + + +
    + + diff --git a/wp-content/themes/default/style.css b/wp-content/themes/default/style.css new file mode 100644 index 0000000..d64c5e7 --- /dev/null +++ b/wp-content/themes/default/style.css @@ -0,0 +1,718 @@ +/* +Theme Name: WordPress Default +Theme URI: http://wordpress.org/ +Description: The default WordPress theme based on the famous Kubrick. +Version: 1.6 +Author: Michael Heilemann +Author URI: http://binarybonsai.com/ +Tags: blue, custom header, fixed width, two columns, widgets + + Kubrick v1.5 + http://binarybonsai.com/kubrick/ + + This theme was designed and built by Michael Heilemann, + whose blog you will find at http://binarybonsai.com/ + + The CSS, XHTML and design is released under GPL: + http://www.opensource.org/licenses/gpl-license.php + +*/ + + + +/* Begin Typography & Colors */ +body { + font-size: 62.5%; /* Resets 1em to 10px */ + font-family: 'Lucida Grande', Verdana, Arial, Sans-Serif; + background: #d5d6d7 url('images/kubrickbgcolor.jpg'); + color: #333; + text-align: center; + } + +#page { + background-color: white; + border: 1px solid #959596; + text-align: left; + } + +#header { + background: #73a0c5 url('images/kubrickheader.jpg') no-repeat bottom center; + } + +#headerimg { + margin: 7px 9px 0; + height: 192px; + width: 740px; + } + +#content { + font-size: 1.2em; + } + +.widecolumn .entry p { + font-size: 1.05em; + } + +.narrowcolumn .entry, .widecolumn .entry { + line-height: 1.4em; + } + +.widecolumn { + line-height: 1.6em; + } + +.narrowcolumn .postmetadata { + text-align: center; + } + +.thread-alt { + background-color: #f8f8f8; +} +.thread-even { + background-color: white; +} +.depth-1 { +border: 1px solid #ddd; +} + +.even, .alt { + + border-left: 1px solid #ddd; +} + +#footer { + background: #e7e7e7 url('images/kubrickfooter.jpg') no-repeat top; + border: none; + } + +small { + font-family: Arial, Helvetica, Sans-Serif; + font-size: 0.9em; + line-height: 1.5em; + } + +h1, h2, h3 { + font-family: 'Trebuchet MS', 'Lucida Grande', Verdana, Arial, Sans-Serif; + font-weight: bold; + } + +h1 { + font-size: 4em; + text-align: center; + } + +#headerimg .description { + font-size: 1.2em; + text-align: center; + } + +h2 { + font-size: 1.6em; + } + +h2.pagetitle { + font-size: 1.6em; + } + +#sidebar h2 { + font-family: 'Lucida Grande', Verdana, Sans-Serif; + font-size: 1.2em; + } + +h3 { + font-size: 1.3em; + } + +h1, h1 a, h1 a:hover, h1 a:visited, #headerimg .description { + text-decoration: none; + color: white; + } + +h2, h2 a, h2 a:visited, h3, h3 a, h3 a:visited { + color: #333; + } + +h2, h2 a, h2 a:hover, h2 a:visited, h3, h3 a, h3 a:hover, h3 a:visited, #sidebar h2, #wp-calendar caption, cite { + text-decoration: none; + } + +.entry p a:visited { + color: #b85b5a; + } + +.sticky { + background: #f7f7f7; + padding: 0 10px 10px; + } +.sticky h2 { + padding-top: 10px; + } + +.commentlist li, #commentform input, #commentform textarea { + font: 0.9em 'Lucida Grande', Verdana, Arial, Sans-Serif; + } +.commentlist li ul li { + font-size: 1em; +} + +.commentlist li { + font-weight: bold; +} + +.commentlist li .avatar { + float: right; + border: 1px solid #eee; + padding: 2px; + background: #fff; + } + +.commentlist cite, .commentlist cite a { + font-weight: bold; + font-style: normal; + font-size: 1.1em; + } + +.commentlist p { + font-weight: normal; + line-height: 1.5em; + text-transform: none; + } + +#commentform p { + font-family: 'Lucida Grande', Verdana, Arial, Sans-Serif; + } + +.commentmetadata { + font-weight: normal; + } + +#sidebar { + font: 1em 'Lucida Grande', Verdana, Arial, Sans-Serif; + } + +small, #sidebar ul ul li, #sidebar ul ol li, .nocomments, .postmetadata, blockquote, strike { + color: #777; + } + +code { + font: 1.1em 'Courier New', Courier, Fixed; + } + +acronym, abbr, span.caps +{ + font-size: 0.9em; + letter-spacing: .07em; + } + +a, h2 a:hover, h3 a:hover { + color: #06c; + text-decoration: none; + } + +a:hover { + color: #147; + text-decoration: underline; + } + +#wp-calendar #prev a, #wp-calendar #next a { + font-size: 9pt; + } + +#wp-calendar a { + text-decoration: none; + } + +#wp-calendar caption { + font: bold 1.3em 'Lucida Grande', Verdana, Arial, Sans-Serif; + text-align: center; + } + +#wp-calendar th { + font-style: normal; + text-transform: capitalize; + } +/* End Typography & Colors */ + + + +/* Begin Structure */ +body { + margin: 0 0 20px 0; + padding: 0; + } + +#page { + background-color: white; + margin: 20px auto; + padding: 0; + width: 760px; + border: 1px solid #959596; + } + +#header { + background-color: #73a0c5; + margin: 0 0 0 1px; + padding: 0; + height: 200px; + width: 758px; + } + +#headerimg { + margin: 0; + height: 200px; + width: 100%; + } + +.narrowcolumn { + float: left; + padding: 0 0 20px 45px; + margin: 0px 0 0; + width: 450px; + } + +.widecolumn { + padding: 10px 0 20px 0; + margin: 5px 0 0 150px; + width: 450px; + } + +.post { + margin: 0 0 40px; + text-align: justify; + } + +.post hr { + display: block; + } + +.widecolumn .post { + margin: 0; + } + +.narrowcolumn .postmetadata { + padding-top: 5px; + } + +.widecolumn .postmetadata { + margin: 30px 0; + } + +.widecolumn .smallattachment { + text-align: center; + float: left; + width: 128px; + margin: 5px 5px 5px 0px; +} + +.widecolumn .attachment { + text-align: center; + margin: 5px 0px; +} + +.postmetadata { + clear: both; +} + +.clear { + clear: both; +} + +#footer { + padding: 0; + margin: 0 auto; + width: 760px; + clear: both; + } + +#footer p { + margin: 0; + padding: 20px 0; + text-align: center; + } +/* End Structure */ + + + +/* Begin Headers */ +h1 { + padding-top: 70px; + margin: 0; + } + +h2 { + margin: 30px 0 0; + } + +h2.pagetitle { + margin-top: 30px; + text-align: center; +} + +#sidebar h2 { + margin: 5px 0 0; + padding: 0; + } + +h3 { + padding: 0; + margin: 30px 0 0; + } + +h3.comments { + padding: 0; + margin: 40px auto 20px ; + } +/* End Headers */ + + + +/* Begin Images */ +p img { + padding: 0; + max-width: 100%; + } + +/* Using 'class="alignright"' on an image will (who would've + thought?!) align the image to the right. And using 'class="centered', + will of course center the image. This is much better than using + align="center", being much more futureproof (and valid) */ + +img.centered { + display: block; + margin-left: auto; + margin-right: auto; + } + +img.alignright { + padding: 4px; + margin: 0 0 2px 7px; + display: inline; + } + +img.alignleft { + padding: 4px; + margin: 0 7px 2px 0; + display: inline; + } + +.alignright { + float: right; + } + +.alignleft { + float: left; + } +/* End Images */ + + + +/* Begin Lists + + Special stylized non-IE bullets + Do not work in Internet Explorer, which merely default to normal bullets. */ + +html>body .entry ul { + margin-left: 0px; + padding: 0 0 0 30px; + list-style: none; + padding-left: 10px; + text-indent: -10px; + } + +html>body .entry li { + margin: 7px 0 8px 10px; + } + +.entry ul li:before, #sidebar ul ul li:before { + content: "\00BB \0020"; + } + +.entry ol { + padding: 0 0 0 35px; + margin: 0; + } + +.entry ol li { + margin: 0; + padding: 0; + } + +.postmetadata ul, .postmetadata li { + display: inline; + list-style-type: none; + list-style-image: none; + } + +#sidebar ul, #sidebar ul ol { + margin: 0; + padding: 0; + } + +#sidebar ul li { + list-style-type: none; + list-style-image: none; + margin-bottom: 15px; + } + +#sidebar ul p, #sidebar ul select { + margin: 5px 0 8px; + } + +#sidebar ul ul, #sidebar ul ol { + margin: 5px 0 0 10px; + } + +#sidebar ul ul ul, #sidebar ul ol { + margin: 0 0 0 10px; + } + +ol li, #sidebar ul ol li { + list-style: decimal outside; + } + +#sidebar ul ul li, #sidebar ul ol li { + margin: 3px 0 0; + padding: 0; + } +/* End Entry Lists */ + + + +/* Begin Form Elements */ +#searchform { + margin: 10px auto; + padding: 5px 3px; + text-align: center; + } + +#sidebar #searchform #s { + width: 108px; + padding: 2px; + } + +#sidebar #searchsubmit { + padding: 1px; + } + +.entry form { /* This is mainly for password protected posts, makes them look better. */ + text-align:center; + } + +select { + width: 130px; + } + +#commentform input { + width: 170px; + padding: 2px; + margin: 5px 5px 1px 0; + } + +#commentform { + margin: 5px 10px 0 0; + } +#commentform textarea { + width: 100%; + padding: 2px; + } +#respond:after { + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; + } +#commentform #submit { + margin: 0 0 5px auto; + float: right; + } +/* End Form Elements */ + + + +/* Begin Comments*/ +.alt { + margin: 0; + padding: 10px; + } + +.commentlist { + padding: 0; + text-align: justify; + } + +.commentlist li { + margin: 15px 0 10px; + padding: 5px 5px 10px 10px; + list-style: none; + + } +.commentlist li ul li { + margin-right: -5px; + margin-left: 10px; +} + +.commentlist p { + margin: 10px 5px 10px 0; +} +.children { padding: 0; } + +#commentform p { + margin: 5px 0; + } + +.nocomments { + text-align: center; + margin: 0; + padding: 0; + } + +.commentmetadata { + margin: 0; + display: block; + } +/* End Comments */ + + + +/* Begin Sidebar */ +#sidebar +{ + padding: 20px 0 10px 0; + margin-left: 545px; + width: 190px; + } + +#sidebar form { + margin: 0; + } +/* End Sidebar */ + + + +/* Begin Calendar */ +#wp-calendar { + empty-cells: show; + margin: 10px auto 0; + width: 155px; + } + +#wp-calendar #next a { + padding-right: 10px; + text-align: right; + } + +#wp-calendar #prev a { + padding-left: 10px; + text-align: left; + } + +#wp-calendar a { + display: block; + } + +#wp-calendar caption { + text-align: center; + width: 100%; + } + +#wp-calendar td { + padding: 3px 0; + text-align: center; + } + +#wp-calendar td.pad:hover { /* Doesn't work in IE */ + background-color: #fff; } +/* End Calendar */ + + + +/* Begin Various Tags & Classes */ +acronym, abbr, span.caps { + cursor: help; + } + +acronym, abbr { + border-bottom: 1px dashed #999; + } + +blockquote { + margin: 15px 30px 0 10px; + padding-left: 20px; + border-left: 5px solid #ddd; + } + +blockquote cite { + margin: 5px 0 0; + display: block; + } + +.center { + text-align: center; + } + +.hidden { + display: none; + } + +.screen-reader-text { + position: absolute; + left: -1000em; +} + +hr { + display: none; + } + +a img { + border: none; + } + +.navigation { + display: block; + text-align: center; + margin-top: 10px; + margin-bottom: 60px; + } +/* End Various Tags & Classes*/ + + + +/* Captions */ +.aligncenter, +div.aligncenter { + display: block; + margin-left: auto; + margin-right: auto; +} + +.wp-caption { + border: 1px solid #ddd; + text-align: center; + background-color: #f3f3f3; + padding-top: 4px; + margin: 10px; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} + +.wp-caption img { + margin: 0; + padding: 0; + border: 0 none; +} + +.wp-caption p.wp-caption-text { + font-size: 11px; + line-height: 17px; + padding: 0 4px 5px; + margin: 0; +} +/* End captions */ + + +/* "Daisy, Daisy, give me your answer do. I'm half crazy all for the love of you. + It won't be a stylish marriage, I can't afford a carriage. + But you'll look sweet upon the seat of a bicycle built for two." */ diff --git a/wp-content/themes/index.php b/wp-content/themes/index.php new file mode 100644 index 0000000..4e6c07c --- /dev/null +++ b/wp-content/themes/index.php @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/wp-content/themes/pixel/GPL_license.txt b/wp-content/themes/pixel/GPL_license.txt new file mode 100644 index 0000000..63e41a4 --- /dev/null +++ b/wp-content/themes/pixel/GPL_license.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. \ No newline at end of file diff --git a/wp-content/themes/pixel/archive.php b/wp-content/themes/pixel/archive.php new file mode 100644 index 0000000..87eaa5f --- /dev/null +++ b/wp-content/themes/pixel/archive.php @@ -0,0 +1,64 @@ + + +
    + +
    + + + + + + +

    + +

    Tag:

    + +

    Archive for

    + +

    Archive for

    + +

    Archive for

    + +

    Author Archive

    + +

    Blog Archives

    + + + + +
    +

    +

    by on , under

    +
    + + :', ', ', ''); ?> + more... +
    +

    + + + + + +
    +

    Not Found

    +

    Sorry, but you are looking for something that isn't here. You can search again by using this form...

    +
    + + + +
    +
    +
    +
    +
    +
    + + + +
    + +
    + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/comments.php b/wp-content/themes/pixel/comments.php new file mode 100644 index 0000000..dbc428b --- /dev/null +++ b/wp-content/themes/pixel/comments.php @@ -0,0 +1,177 @@ +This post is password protected. Enter the password to view comments.

    '; + return; + } + } else + { + if (!empty($post->post_password)) + { // if there's a password + if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password) + { // and it doesn't match the cookie ?> +

    This post is password protected. Enter the password to view comments.

    + + + +

    +
      + +
    + + + + + +

    +
      + +
    + + + + + comment_status) : + // If comments are open, but there are no comments. + else : ?>

    Comments are closed.

    + + + + +

    to “

    +
      + +
    1. + + +"; + } +?> + + +
      + + comment_approved == '0') : ?> + Your comment is awaiting moderation. + +
      + + + +
      +
    2. + + + +
    + + + comment_status) : ?> + + + +

    Comments are closed.

    + + + + + + + + + + + + + +comment_status) : ?> +
    +
    +

    Leave a Reply

    + +
    + +
    + + + +

    You must be logged in to post a comment.

    + +
    + + + +

    Logged in as . +

    + + +

    +

    +

    +

    +

    +

    + + + + + + + +

    +

    + +

    + +ID); ?> + +
    +
    + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/footer.php b/wp-content/themes/pixel/footer.php new file mode 100644 index 0000000..c3138fe --- /dev/null +++ b/wp-content/themes/pixel/footer.php @@ -0,0 +1,46 @@ +
    + +
    + +

    Looking for something?

    +

    Use the form below to search the site:

    + +

    Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

    + +
    + +
    + +

    Visit our friends!

    A few highly recommended friends...

    + +
    + +
    + +

    Archives

    All entries, chronologically...

    + +
    + +
    +
    + + + + + + + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/functions.php b/wp-content/themes/pixel/functions.php new file mode 100644 index 0000000..b645111 --- /dev/null +++ b/wp-content/themes/pixel/functions.php @@ -0,0 +1,122 @@ +'sidebar_full', + 'before_widget' => '
  • ', + 'after_widget' => '
  • ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); + register_sidebar(array( + 'name'=>'sidebar_left', + 'before_widget' => '
  • ', + 'after_widget' => '
  • ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); + register_sidebar(array( + 'name'=>'sidebar_right', + 'before_widget' => '
  • ', + 'after_widget' => '
  • ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); + register_sidebar(array( + 'name'=>'footer_left', + 'before_widget' => '
    ', + 'after_widget' => '
    ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); + register_sidebar(array( + 'name'=>'footer_middle', + 'before_widget' => '
    ', + 'after_widget' => '
    ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); + register_sidebar(array( + 'name'=>'footer_right', + 'before_widget' => '
    ', + 'after_widget' => '
    ', + 'before_title' => '

    ', + 'after_title' => '

    ', + )); + + +add_action('admin_menu', 'add_welcome_interface'); + +function add_welcome_interface() { + add_theme_page('welcome', 'Theme Options', '8', 'functions', 'editoptions'); + } + +function editoptions() { + ?> +
    +

    Theme Options

    +
    + +

    Greeting Heading:

    +

    +

    Welcome Message:

    +

    +

    Please enter the name of your FeedBurner feed below: (What's the name of your feed? Well, for instance, in the following - http://feeds.feedburner.com/NAME - NAME would be your feed :))

    +

    +

    + + +
    +
    + +
  • id="li-comment-"> +
    + + + + +
    + + comment_approved == '0') : ?> + Your comment is awaiting moderation. + +
    + + + +
    + +
    + $depth, 'max_depth' => $args['max_depth']))) ?> +
    +
    + +
  • id="li-comment-"> +
    +
    + + comment_approved == '0') : ?> + Your comment is awaiting moderation. + +
    + + + +
    +
    + \ No newline at end of file diff --git a/wp-content/themes/pixel/header.php b/wp-content/themes/pixel/header.php new file mode 100644 index 0000000..9f01eae --- /dev/null +++ b/wp-content/themes/pixel/header.php @@ -0,0 +1,87 @@ + + + + + + +<?php if (is_home () ) { bloginfo('name'); echo " - "; bloginfo('description'); +} elseif (is_category() ) {single_cat_title(); echo " - "; bloginfo('name'); +} elseif (is_single() || is_page() ) {single_post_title(); echo " - "; bloginfo('name'); +} elseif (is_search() ) {bloginfo('name'); echo " search results: "; echo wp_specialchars($s); +} else { wp_title('',true); }?> + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +
    +
    <?php bloginfo('name'); ?>
    + +
    + +
    diff --git a/wp-content/themes/pixel/ie.css b/wp-content/themes/pixel/ie.css new file mode 100644 index 0000000..5d3af47 --- /dev/null +++ b/wp-content/themes/pixel/ie.css @@ -0,0 +1,16 @@ +#toprss { + margin: 9px 15px 0 0; + } + +#main { + margin-top: 10px; + } + +#main #welcome { + padding: 0; + } + +.submitbutton { + padding: 2px 1px 1px 1px; + } + diff --git a/wp-content/themes/pixel/ie6.css b/wp-content/themes/pixel/ie6.css new file mode 100644 index 0000000..cf79ed9 --- /dev/null +++ b/wp-content/themes/pixel/ie6.css @@ -0,0 +1,17 @@ +#main #welcome { + background: #020202; + } + +#contentwrapper .pageTitle, #contentwrapper2 .pageTitle { + background: #020202; + } + +.topPost span.topComments, .topPost span.topMore, .topPost span.topTags { + background: #020202; + padding: 0 10px; + } + +#sidebars .sidebarbox { + background: #020202; + } + diff --git a/wp-content/themes/pixel/images/bg-trans.png b/wp-content/themes/pixel/images/bg-trans.png new file mode 100644 index 0000000..e7702a6 Binary files /dev/null and b/wp-content/themes/pixel/images/bg-trans.png differ diff --git a/wp-content/themes/pixel/images/bgbody.jpg b/wp-content/themes/pixel/images/bgbody.jpg new file mode 100644 index 0000000..711d912 Binary files /dev/null and b/wp-content/themes/pixel/images/bgbody.jpg differ diff --git a/wp-content/themes/pixel/images/bggrad.jpg b/wp-content/themes/pixel/images/bggrad.jpg new file mode 100644 index 0000000..fa269ca Binary files /dev/null and b/wp-content/themes/pixel/images/bggrad.jpg differ diff --git a/wp-content/themes/pixel/images/bullet.gif b/wp-content/themes/pixel/images/bullet.gif new file mode 100644 index 0000000..d803652 Binary files /dev/null and b/wp-content/themes/pixel/images/bullet.gif differ diff --git a/wp-content/themes/pixel/images/comments.gif b/wp-content/themes/pixel/images/comments.gif new file mode 100644 index 0000000..d4cdac2 Binary files /dev/null and b/wp-content/themes/pixel/images/comments.gif differ diff --git a/wp-content/themes/pixel/images/gravatar-trans.png b/wp-content/themes/pixel/images/gravatar-trans.png new file mode 100644 index 0000000..18a11bd Binary files /dev/null and b/wp-content/themes/pixel/images/gravatar-trans.png differ diff --git a/wp-content/themes/pixel/images/logo.gif b/wp-content/themes/pixel/images/logo.gif new file mode 100644 index 0000000..35e77d8 Binary files /dev/null and b/wp-content/themes/pixel/images/logo.gif differ diff --git a/wp-content/themes/pixel/images/lookingbg.jpg b/wp-content/themes/pixel/images/lookingbg.jpg new file mode 100644 index 0000000..38341b3 Binary files /dev/null and b/wp-content/themes/pixel/images/lookingbg.jpg differ diff --git a/wp-content/themes/pixel/images/more.gif b/wp-content/themes/pixel/images/more.gif new file mode 100644 index 0000000..0b70d8f Binary files /dev/null and b/wp-content/themes/pixel/images/more.gif differ diff --git a/wp-content/themes/pixel/images/rss-trans.png b/wp-content/themes/pixel/images/rss-trans.png new file mode 100644 index 0000000..bc62738 Binary files /dev/null and b/wp-content/themes/pixel/images/rss-trans.png differ diff --git a/wp-content/themes/pixel/images/tags.gif b/wp-content/themes/pixel/images/tags.gif new file mode 100644 index 0000000..e6495bc Binary files /dev/null and b/wp-content/themes/pixel/images/tags.gif differ diff --git a/wp-content/themes/pixel/images/wpfooter-trans.png b/wp-content/themes/pixel/images/wpfooter-trans.png new file mode 100644 index 0000000..99176bc Binary files /dev/null and b/wp-content/themes/pixel/images/wpfooter-trans.png differ diff --git a/wp-content/themes/pixel/index.php b/wp-content/themes/pixel/index.php new file mode 100644 index 0000000..a1470bf --- /dev/null +++ b/wp-content/themes/pixel/index.php @@ -0,0 +1,46 @@ + + +
    + +
    + + + + +
    +

    +

    by on , under

    +
    + + :', ', ', ''); ?> + more... +
    +

    + + + + + +
    +

    Not Found

    +

    Sorry, but you are looking for something that isn't here. You can search again by using this form...

    +
    + + + +
    +
    +
    +
    +
    +
    + + + + +
    + +
    + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/page.php b/wp-content/themes/pixel/page.php new file mode 100644 index 0000000..472758b --- /dev/null +++ b/wp-content/themes/pixel/page.php @@ -0,0 +1,37 @@ + + +
    + +
    + + + + +
    +

    +
    +
    +
    + + + + + + +
    +

    Not Found

    +

    Sorry, but you are looking for something that isn't here. You can search again by using this form...

    +
    + + + +
    + + + +
    + +
    + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/page_fullwidth.php b/wp-content/themes/pixel/page_fullwidth.php new file mode 100644 index 0000000..a608f7c --- /dev/null +++ b/wp-content/themes/pixel/page_fullwidth.php @@ -0,0 +1,42 @@ + + + + +
    + +
    + + + + +
    +

    +
    +
    +
    + + + + + + +
    +

    Not Found

    +

    Sorry, but you are looking for something that isn't here. You can search again by using this form...

    +
    + + + +
    + + +
    + +
    + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/screenshot.png b/wp-content/themes/pixel/screenshot.png new file mode 100644 index 0000000..1220ef5 Binary files /dev/null and b/wp-content/themes/pixel/screenshot.png differ diff --git a/wp-content/themes/pixel/searchform.php b/wp-content/themes/pixel/searchform.php new file mode 100644 index 0000000..c4014a0 --- /dev/null +++ b/wp-content/themes/pixel/searchform.php @@ -0,0 +1,6 @@ +
    +

    + + +

    +
    \ No newline at end of file diff --git a/wp-content/themes/pixel/sidebar.php b/wp-content/themes/pixel/sidebar.php new file mode 100644 index 0000000..1a21933 --- /dev/null +++ b/wp-content/themes/pixel/sidebar.php @@ -0,0 +1,76 @@ + \ No newline at end of file diff --git a/wp-content/themes/pixel/single.php b/wp-content/themes/pixel/single.php new file mode 100644 index 0000000..bd6beda --- /dev/null +++ b/wp-content/themes/pixel/single.php @@ -0,0 +1,59 @@ + + +
    + +
    + + + + +
    +

    +

    by on , under

    +
    +
    +
    + :', ', ', ''); ?> +
    +
    +
    + +
    + + + + + + + + +
    + +
    +RSS feed for this post (comments)')); ?> + + · URI'); ?> +
    +
    + + + + + +
    +

    Not Found

    +

    Sorry, but you are looking for something that isn't here. You can search again by using this form...

    +
    + + + +
    + + + +
    + +
    + + + \ No newline at end of file diff --git a/wp-content/themes/pixel/style.css b/wp-content/themes/pixel/style.css new file mode 100644 index 0000000..d1d6e08 --- /dev/null +++ b/wp-content/themes/pixel/style.css @@ -0,0 +1,795 @@ +/* +Theme Name: Pixel +Theme URI: http://samk.ca/freebies/ +Description: Dark WP theme with 2-3 column layout, dropdown categories menu, multiple widget-ready placement and feedburner email form integrated, easy to customize. Enjoy! +Author: Sam +Author URI: http://samk.ca/ +Version: 1.9.7 +Tags: black, blue, three-columns, two-columns, threaded-comments, fixed-width, theme-options, right-sidebar +. +Released under the GPL. +. +*/ + +/* Defaults */ + +* { + margin: 0; + padding: 0; + } + +h1, h2, h3, h4, h5, h6, p { + margin: 0; + padding: 10px 0; + } + +h1, h2, h3, h4, h5, h6 { + font-family: Verdana; + } + +hr { + color: #333; + border: 1px solid #121212; + } + +pre { + height: auto; + overflow-x:scroll; + } + +fieldset { + margin: 0; + padding: 0; + border: 0; + } + +dd { + padding-left: 15px; + } + + +p { + font-size: 9pt; + } + +a { + color: #6598b8; + text-decoration: none; + } + +a:hover { + color: #222; + text-decoration: underline; + } + +a img { + border: none; + } + +blockquote { + background: #070707; + border: 1px solid #060606; + padding: 5px 15px; + margin: 10px 10px 5px 15px; + font-style: italic; + color: #fff; + } + +code { + color: #3366cc; + font-style: italic; + } + +strong { + font-size: 110%; + } + +body { + text-align: center; + margin: 0; + padding: 0 0 15px 0; + font-family: trebuchet ms, arial, helvetica, sans-serif; + background: #000 url(images/bgbody.jpg) top center no-repeat; + } + + +/* Header and wrapper */ +#wrapper { + margin: 0 auto; + width: 960px; + text-align: left; + padding: 0; + } + +#header { + padding: 0; + margin: 0; + height: 80px; + } + +#header #topright { + text-align: right; + float: right; + width: 600px; + margin: 5px 0 0 0; +} +#header #topright ul { + list-style: none; + padding: 0; + margin: 0; + } +#header #topright li { + display: inline; + } +#header #topright li a { + color: #fff; + font-size: 9pt; + padding: 0 0 0 25px; + text-transform: lowercase; + } +#header #topright li a:hover { + color: #000; + text-decoration: none; + } + +#header #logo { + float: left; + width: 350px; + margin: 25px 0 0 0; + padding: 0; +} +#header h1 { + padding: 0; + margin: 0; + } +#header h1 a { + color: #fff; + font-size: 17pt; + text-decoration: none; + } +#header h1 a:hover { + color: #eee; + text-decoration: none; + } +#header span { + padding: 0; + color: #111; + font-size: 11pt; + } + + +/* Menu */ + +#catnav { + margin: 20px 0 0 0; + padding: 0; + clear: both; + height: 44px; + width: 960px; + } + +#nav { + list-style: none; + margin: 0; + padding: 0; + } + +#nav ul { + margin: 0; + padding: 0; + } + +#nav li { + float: left; + margin: 0; + padding: 0; + } + +#nav a { + display: block; + line-height: 44px; + margin: 0; + padding: 0 20px 0 15px; + font-size: 10pt; + color: #fff; + letter-spacing: -1px; + } + +#nav li a:hover { + color: #6598b8; + text-decoration: none; + display: block; + } + +#nav li ul { + list-style: none; + position: absolute; + width: 150px; + left: -999em; + } + +#nav li:hover ul, #nav li.sfhover ul { + left: auto; + } + +#nav li li { + float: left; + margin: 0; + padding: 0; + width: 150px; + } + +#nav li li a { + width: 150px; + height: 24px; + line-height: 24px; + color: #fff; + border-top: 1px solid #131f27; + background: #040404; + margin: 0; + padding: 5px 20px 5px 15px; + } + +#nav li li a:hover { + border-top: 1px solid #131f27; + background: #000; + padding: 5px 20px 5px 15px; + } + +#nav li:hover, #nav li.sfhover { /* prevents IE7 drop-down menu bug (focus on a page element prevents nested menus from disappearing) */ + position: static; + } + +#toprss { + float: right; + margin: 10px 15px 0 0; + display: inline; + width: 65px; + line-height: 41px; + } + + + +/* Top Content */ + +#main { + margin: 5px 15px 0 15px; + clear: both; + width: 930px; + padding-bottom: 5px; + } +#contentwrapper { + float:left; + width: 560px; + margin: 0 0 15px 0; + padding: 0; + } +#contentwrapper2 { + float:left; + width: 900px; margin: 0 0 15px 0; + padding: 0; + } +#contentwrapper .pageTitle, #contentwrapper2 .pageTitle { + margin: 15px 0 10px 0; + font-size: 14pt; + letter-spacing: -1px; + color: #fff; + font-weight: normal; + background: url(images/bg-trans.png) repeat; + padding: 5px; + } +.topPost { + margin: 0; + padding: 0; + font-size: 9pt; + } +.topPost h2.topTitle a { + font-size: 15pt; + font-weight: normal; + color: #fff; + letter-spacing: -2px; + } +.topPost h2.topTitle a:hover { + text-decoration: none; + color: #abd1ea; + } +.topPost p.topMeta { + padding: 0; + margin: -10px 0 0 0; + font-size: 9pt; + color: #cdcdcd; + } +.topPost p.topMeta a { + text-decoration: underline; + color: #fff; + } +.topPost p.topMeta a:hover { + color: #ccc; + } +.topPost div.topContent { + font-size: 9pt; + color: #efefef; + margin: 8px 0; + } +.topPost div.topContent a { + text-decoration: underline; + color: #fff; + } +.topPost div.topContent a:hover { + text-decoration: underline; + color: #ff9933; + } + +.topPost div.topContent ul, .topPost div.topContent ol { + padding: 0 0 0 30px; + } +.topPost div.topContent ul li, .topPost div.topContent ol li { + color: #eee; + } +.topPost span.topComments, .topPost span.topMore, .topPost span.topTags { + font-size: 9pt; + font-style: italic; + background: url(images/bg-trans.png) repeat; + padding: 8px 10px; + margin-right: 5px; + line-height: 27pt; + color: #fff; + border: 1px solid #111; + } +.topPost span.linkpages { + font-size: 9pt; + font-style: italic; + color: #fff; + margin-bottom: 10px; display:block; + } +.topPost span.linkpages a:hover { + color: #ddd; + } +.topPost span.topComments:hover, .topPost span.topMore:hover, .topPost span.topTags:hover { + background: #040404; + } +.topPost span.topComments a { + color: #fff; + background: url(images/comments.gif) left no-repeat; + padding-left: 20px; + line-height: 27pt; + vertical-align: middle; + } +.topPost span.topMore a { + color: #fff; + background: url(images/more.gif) left no-repeat; + padding-left: 20px; + line-height: 27pt; + vertical-align: middle; + } +.topPost span.topTags em { + background: url(images/tags.gif) left no-repeat; + padding-left: 20px; + line-height: 27pt; + vertical-align: middle; + color: #0a0a0a; + } +.topPost span.topTags a { + color: #fff; + line-height: 27pt; + vertical-align: middle; + } +.topPost span.topComments a:hover, .topPost span.topMore a:hover, .topPost span.topTags a:hover { + color: #fff; + text-decoration: underline; + } + +#nextprevious { + margin: 10px 0 5px 0; + } +#nextprevious a { + color: #83adc8; + text-transform: lowercase; + text-decoration: underline; + } +#nextprevious a:hover { + color: #fff; + } + + +/* Comments */ + +#comments { + margin-bottom: 10px; + margin-top: 15px; + background: #040404; + width: 530px; /* fixes bug in IE7 where putting focus on the text makes it disappear behind the background. yeah, weird. they call it a dimensional bug. */ + border: 1px solid #090909; + padding: 0px 15px 10px 15px; + color: #fff; + } +#comments h3 { + font-size: 10pt; + font-weight: normal; + color: #fff; + margin: 15px 0; + padding: 0; + } +#comments p a { + color: #6598b8; + } +#comments p a:hover { + color: #fff; + } +#comments p { + padding:0; + margin: 7px 0; + } +ul.commentlist, ul.trackback { + list-style-type: none; + margin: 10px 0; + font-size: 9pt; + } +.commentlist li, .trackback li { + margin: 10px 0 15px 0; + padding: 10px; + background: #080808; + border: 1px solid #040404; + list-style-type: none; + } +.commentlist li.alt { + background: #000; + border: 1px solid #020202; + border: none; + margin-top:10px; + } +.commentlist li.cleared { + background: transparent; + border: none; + } +.commentlist a:hover { + color: #eee; + } +.commentlist a.gravatar { + float: left; + margin: 0 15px 10px 0; + width: 60px; + } +.commentlist .commentbody { + margin: 0; + padding: 0; + } +.commentlist .commentbody p a { + text-decoration: underline; + } +.commentlist cite { + font-size: 10pt; + font-style: normal; + color: #ddd; + } +.commentlist small.commentmetadata a { + color: #666; + } +.commentlist p { + color: #dedede; + } +#respond { + clear: both; + margin-top: 15px; + } +textarea#comment { + width: 450px; + background: #fff; + color: #111; + padding: 10px; + } +#comments #submit { + margin: 0; + } +#extrastuff a {color:#222; font-size:0.8em;} +#extrastuff a:hover {color:#6598b8; text-decoration:none;} +#extrastuff #rssleft {float:left; width:250px;} +#extrastuff #trackright {float:right; width:180px; text-align:right;} + + +/* Welcome section */ + +#main #welcome { + margin: 0 0 20px 0; + padding: 0 0 5px 0; + background: url(images/bg-trans.png) repeat; + } +#main #welcome h2 { + font-size: 14pt; + font-weight: normal; + + color: #fff; + letter-spacing: -2px; + margin: 0 10px; + padding: 10px 0 3px 0; + } +#main #welcome p { + font-size: 9pt; + color: #eee; + margin: 0 10px; + padding: 6px 0; + } +#main #welcome a { + text-decoration: underline; + color: #ff9933; + } +#main #welcome a:hover { + color: #6598b8; + } +#main #welcome form { + margin: -5px 0 0 0; + background: transparent; /* required for IE */ + } +#main #welcome #feedbox { + border: 1px solid #ccc; + padding: 2px 1px; + width: 180px; + } +.submitbutton { + margin: -5px 0 0 5px; + background: #010101; + color: #fff; + font-size: 8pt; + padding: 3px 6px; + vertical-align: middle; + border: 1px solid #111; + } +.submitbutton:hover { + cursor: pointer; + background: #050505; + } + + +/* Sidebars */ +#sidebars { + margin: 15px 0 0 0; + float: right; + width: 340px; + color: #eee; + } +#sidebars .sidebarbox { + background: url(images/bg-trans.png) repeat; + padding: 8px 15px; + } + +#sidebar_full { + padding: 0; + margin: 0; + } + +#sidebar_left { + float: left; + width: 160px; + } + +#sidebar_right { + float: right; + width: 160px; + } + +#sidebars h2 { + margin: 0; + padding: 0 0 8px 0; + font-weight: normal; + font-size: 11pt; + color: #fff; + letter-spacing: -1px; + } + +#sidebars table { + width: 130px; + } + +#sidebars ul { + margin: 0; + padding: 0 0 5px 0; + } + +#sidebars li { + margin-bottom: 20px; + list-style: none; + font-size: 9pt; + } + +#sidebars li ul { + padding: 0; + } + +#sidebars ul ul li { + margin: 0; + padding: 2px 2px 2px 16px; + color: #eee; + background: url(images/bullet.gif) left 8px no-repeat; + line-height: 17px; /* Required for cross-browser consistency; cross-browser defaults vary. */ + } + +#sidebars a { + display: inline; + color: #eee; + } +#sidebars a:hover { + color: #6598b8; + text-decoration: underline; + } + +#sidebars p { + padding: 2px 0; + font-size: 9pt; + color: #eee; + } + +#tag_cloud a { + display: inline; + } + +#sidebars ul.children li {border-bottom:none;} +#sidebars ul.children {margin-bottom:0;} + + + +/* Before footer */ + +#morefoot { + background: #000 url(images/bggrad.jpg) top left repeat-x; + border: 1px solid #070707; + padding: 15px; + color: #dfdfdf; + margin: 0 0 10px 0; + } +#morefoot p { + margin: 5px 0; + padding: 5px 0; + } +#morefoot ul { + list-style-type: none; + margin-top: 5px; + } +#morefoot ul li, #morefoot p { + font-size: 9pt; + } +#morefoot a { + text-decoration: underline; + color: #ddd; + } +#morefoot a:hover { + text-decoration: underline; + color: #6598b8; + } +#morefoot h3 { + font-size: 12pt; + font-weight: normal; + color: #dfdfdf; + letter-spacing: -1px; + border-bottom: 1px dotted #444; + margin: 0; + padding: 0 0 2px 0; + } +#morefoot #searchbox { + padding: 1px; + width: 180px; + } +#morefoot .col1 { + float: left; + width: 340px; + } +#morefoot .col2 { + margin: 0 25px; + } +#morefoot .col2, #morefoot .col3 { + float: left; + width: 260px; + } +#morefoot li { + padding-left: 20px; + margin-bottom: 5px; + background: url(images/more.gif) left 2px no-repeat; + line-height: 17px; /* Required for cross-browser consistency; cross-browser defaults vary. */ + } + + +/* footer*/ +#footer { + clear: both; + background: #000; + border: 1px solid #070707; + padding: 15px 15px 10px 15px; + } +#footer p { + font-size: 9pt; + color: #bbb; + padding: 0; + } +#footer a { + color: #bbb; + text-decoration: underline; + } +#footer a:hover { + color: #fff; + } +#footerleft { + float: left; + width: 500px; + } +#footerright { + float: right; + width: 300px; + text-align: right; + } + + + +/* Misc */ + +.highlight { + color: #222; + font-weight: bold; + } + +.cleared { + margin: 0; + padding: 0; + clear: both; + } + +.alignleft { + float: left; + margin: 5px 10px 5px 0; + } +.alignright { + float: right; + margin: 5px 0 5px 10px; + } +.aligncenter, +div.aligncenter { + margin: 10px auto; + text-align: center; + display: block; + } + +img.alignleft { + float: left; + margin: 5px 10px 5px 0; + } +img.alignright { + float: right; + margin: 5px 0 5px 10px; + } +img.aligncenter { + margin: 10px auto; + text-align: center; + display: block; + } + +.wp-caption { + border: 1px solid #ddd; + text-align: center; + background-color: #f3f3f3; + + padding-top: 4px; + + /* optional rounded corners for browsers that support it */ + + -moz-border-radius: 3px; + + -khtml-border-radius: 3px; + + -webkit-border-radius: 3px; + border-radius: 3px; + } + +.wp-caption img { + margin: 0; + padding: 0; + border: none; + } + +.wp-caption p.wp-caption-text { + font-size: 11px; + line-height: 17px; + padding: 0 4px 5px; + margin: 0; + color: #111; + } + + + diff --git a/wp-content/themes/pixel/welcome.php b/wp-content/themes/pixel/welcome.php new file mode 100644 index 0000000..9fb11e3 --- /dev/null +++ b/wp-content/themes/pixel/welcome.php @@ -0,0 +1,50 @@ +
    + + +" . get_option('greeting') . ""; + } + if (get_option('welcomemessage')) { + echo "

    " . get_option('welcomemessage') . "

    "; + } + } else { + echo "

    Welcome to $mysitename!

    This site is devoted to update the people who care about the on-goings of my life. This way you can log on and check into my most recent adventures and view a few pictures of what they turned out to be.

    "; +} + +?> + + + +You can also subscribe by email by filling the field below:

    + +
    +

    + + + + +

    +
    + + +"; + } + + else { + echo ""; + } +?> + + +
    \ No newline at end of file diff --git a/wp-content/uploads/2009/09/contemplative-150x150.jpg b/wp-content/uploads/2009/09/contemplative-150x150.jpg new file mode 100644 index 0000000..df00125 Binary files /dev/null and b/wp-content/uploads/2009/09/contemplative-150x150.jpg differ diff --git a/wp-content/uploads/2009/09/contemplative-179x300.jpg b/wp-content/uploads/2009/09/contemplative-179x300.jpg new file mode 100644 index 0000000..e4742b3 Binary files /dev/null and b/wp-content/uploads/2009/09/contemplative-179x300.jpg differ diff --git a/wp-content/uploads/2009/09/contemplative.jpg b/wp-content/uploads/2009/09/contemplative.jpg new file mode 100644 index 0000000..869d1f2 Binary files /dev/null and b/wp-content/uploads/2009/09/contemplative.jpg differ diff --git a/wp-cron.php b/wp-cron.php new file mode 100644 index 0000000..b7fd6f5 --- /dev/null +++ b/wp-cron.php @@ -0,0 +1,60 @@ + $local_time ) + die(); + +foreach ($crons as $timestamp => $cronhooks) { + if ( $timestamp > $local_time ) + break; + + foreach ($cronhooks as $hook => $keys) { + + foreach ($keys as $k => $v) { + + $schedule = $v['schedule']; + + if ($schedule != false) { + $new_args = array($timestamp, $schedule, $hook, $v['args']); + call_user_func_array('wp_reschedule_event', $new_args); + } + + wp_unschedule_event($timestamp, $hook, $v['args']); + + do_action_ref_array($hook, $v['args']); + } + } +} + +die(); diff --git a/wp-feed.php b/wp-feed.php new file mode 100644 index 0000000..78daa6d --- /dev/null +++ b/wp-feed.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/wp-includes/Text/Diff.php b/wp-includes/Text/Diff.php new file mode 100644 index 0000000..06d1c6c --- /dev/null +++ b/wp-includes/Text/Diff.php @@ -0,0 +1,414 @@ +, and is used/adapted with his permission. + * + * $Horde: framework/Text_Diff/Diff.php,v 1.26 2008/01/04 10:07:49 jan Exp $ + * + * Copyright 2004 Geoffrey T. Dairiki + * Copyright 2004-2008 The Horde Project (http://www.horde.org/) + * + * See the enclosed file COPYING for license information (LGPL). If you did + * not receive this file, see http://opensource.org/licenses/lgpl-license.php. + * + * @package Text_Diff + * @author Geoffrey T. Dairiki + */ +class Text_Diff { + + /** + * Array of changes. + * + * @var array + */ + var $_edits; + + /** + * Computes diffs between sequences of strings. + * + * @param string $engine Name of the diffing engine to use. 'auto' + * will automatically select the best. + * @param array $params Parameters to pass to the diffing engine. + * Normally an array of two arrays, each + * containing the lines from a file. + */ + function Text_Diff($engine, $params) + { + // Backward compatibility workaround. + if (!is_string($engine)) { + $params = array($engine, $params); + $engine = 'auto'; + } + + if ($engine == 'auto') { + $engine = extension_loaded('xdiff') ? 'xdiff' : 'native'; + } else { + $engine = basename($engine); + } + + // WP #7391 + require_once dirname(__FILE__).'/Diff/Engine/' . $engine . '.php'; + $class = 'Text_Diff_Engine_' . $engine; + $diff_engine = new $class(); + + $this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params); + } + + /** + * Returns the array of differences. + */ + function getDiff() + { + return $this->_edits; + } + + /** + * Computes a reversed diff. + * + * Example: + * + * $diff = new Text_Diff($lines1, $lines2); + * $rev = $diff->reverse(); + * + * + * @return Text_Diff A Diff object representing the inverse of the + * original diff. Note that we purposely don't return a + * reference here, since this essentially is a clone() + * method. + */ + function reverse() + { + if (version_compare(zend_version(), '2', '>')) { + $rev = clone($this); + } else { + $rev = $this; + } + $rev->_edits = array(); + foreach ($this->_edits as $edit) { + $rev->_edits[] = $edit->reverse(); + } + return $rev; + } + + /** + * Checks for an empty diff. + * + * @return boolean True if two sequences were identical. + */ + function isEmpty() + { + foreach ($this->_edits as $edit) { + if (!is_a($edit, 'Text_Diff_Op_copy')) { + return false; + } + } + return true; + } + + /** + * Computes the length of the Longest Common Subsequence (LCS). + * + * This is mostly for diagnostic purposes. + * + * @return integer The length of the LCS. + */ + function lcs() + { + $lcs = 0; + foreach ($this->_edits as $edit) { + if (is_a($edit, 'Text_Diff_Op_copy')) { + $lcs += count($edit->orig); + } + } + return $lcs; + } + + /** + * Gets the original set of lines. + * + * This reconstructs the $from_lines parameter passed to the constructor. + * + * @return array The original sequence of strings. + */ + function getOriginal() + { + $lines = array(); + foreach ($this->_edits as $edit) { + if ($edit->orig) { + array_splice($lines, count($lines), 0, $edit->orig); + } + } + return $lines; + } + + /** + * Gets the final set of lines. + * + * This reconstructs the $to_lines parameter passed to the constructor. + * + * @return array The sequence of strings. + */ + function getFinal() + { + $lines = array(); + foreach ($this->_edits as $edit) { + if ($edit->final) { + array_splice($lines, count($lines), 0, $edit->final); + } + } + return $lines; + } + + /** + * Removes trailing newlines from a line of text. This is meant to be used + * with array_walk(). + * + * @param string $line The line to trim. + * @param integer $key The index of the line in the array. Not used. + */ + function trimNewlines(&$line, $key) + { + $line = str_replace(array("\n", "\r"), '', $line); + } + + /** + * Determines the location of the system temporary directory. + * + * @static + * + * @access protected + * + * @return string A directory name which can be used for temp files. + * Returns false if one could not be found. + */ + function _getTempDir() + { + $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', + 'c:\windows\temp', 'c:\winnt\temp'); + + /* Try PHP's upload_tmp_dir directive. */ + $tmp = ini_get('upload_tmp_dir'); + + /* Otherwise, try to determine the TMPDIR environment variable. */ + if (!strlen($tmp)) { + $tmp = getenv('TMPDIR'); + } + + /* If we still cannot determine a value, then cycle through a list of + * preset possibilities. */ + while (!strlen($tmp) && count($tmp_locations)) { + $tmp_check = array_shift($tmp_locations); + if (@is_dir($tmp_check)) { + $tmp = $tmp_check; + } + } + + /* If it is still empty, we have failed, so return false; otherwise + * return the directory determined. */ + return strlen($tmp) ? $tmp : false; + } + + /** + * Checks a diff for validity. + * + * This is here only for debugging purposes. + */ + function _check($from_lines, $to_lines) + { + if (serialize($from_lines) != serialize($this->getOriginal())) { + trigger_error("Reconstructed original doesn't match", E_USER_ERROR); + } + if (serialize($to_lines) != serialize($this->getFinal())) { + trigger_error("Reconstructed final doesn't match", E_USER_ERROR); + } + + $rev = $this->reverse(); + if (serialize($to_lines) != serialize($rev->getOriginal())) { + trigger_error("Reversed original doesn't match", E_USER_ERROR); + } + if (serialize($from_lines) != serialize($rev->getFinal())) { + trigger_error("Reversed final doesn't match", E_USER_ERROR); + } + + $prevtype = null; + foreach ($this->_edits as $edit) { + if ($prevtype == get_class($edit)) { + trigger_error("Edit sequence is non-optimal", E_USER_ERROR); + } + $prevtype = get_class($edit); + } + + return true; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + */ +class Text_MappedDiff extends Text_Diff { + + /** + * Computes a diff between sequences of strings. + * + * This can be used to compute things like case-insensitve diffs, or diffs + * which ignore changes in white-space. + * + * @param array $from_lines An array of strings. + * @param array $to_lines An array of strings. + * @param array $mapped_from_lines This array should have the same size + * number of elements as $from_lines. The + * elements in $mapped_from_lines and + * $mapped_to_lines are what is actually + * compared when computing the diff. + * @param array $mapped_to_lines This array should have the same number + * of elements as $to_lines. + */ + function Text_MappedDiff($from_lines, $to_lines, + $mapped_from_lines, $mapped_to_lines) + { + assert(count($from_lines) == count($mapped_from_lines)); + assert(count($to_lines) == count($mapped_to_lines)); + + parent::Text_Diff($mapped_from_lines, $mapped_to_lines); + + $xi = $yi = 0; + for ($i = 0; $i < count($this->_edits); $i++) { + $orig = &$this->_edits[$i]->orig; + if (is_array($orig)) { + $orig = array_slice($from_lines, $xi, count($orig)); + $xi += count($orig); + } + + $final = &$this->_edits[$i]->final; + if (is_array($final)) { + $final = array_slice($to_lines, $yi, count($final)); + $yi += count($final); + } + } + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op { + + var $orig; + var $final; + + function &reverse() + { + trigger_error('Abstract method', E_USER_ERROR); + } + + function norig() + { + return $this->orig ? count($this->orig) : 0; + } + + function nfinal() + { + return $this->final ? count($this->final) : 0; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_copy extends Text_Diff_Op { + + function Text_Diff_Op_copy($orig, $final = false) + { + if (!is_array($final)) { + $final = $orig; + } + $this->orig = $orig; + $this->final = $final; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_copy($this->final, $this->orig); + return $reverse; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_delete extends Text_Diff_Op { + + function Text_Diff_Op_delete($lines) + { + $this->orig = $lines; + $this->final = false; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_add($this->orig); + return $reverse; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_add extends Text_Diff_Op { + + function Text_Diff_Op_add($lines) + { + $this->final = $lines; + $this->orig = false; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_delete($this->final); + return $reverse; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_change extends Text_Diff_Op { + + function Text_Diff_Op_change($orig, $final) + { + $this->orig = $orig; + $this->final = $final; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_change($this->final, $this->orig); + return $reverse; + } + +} diff --git a/wp-includes/Text/Diff/Engine/native.php b/wp-includes/Text/Diff/Engine/native.php new file mode 100644 index 0000000..aa5bca5 --- /dev/null +++ b/wp-includes/Text/Diff/Engine/native.php @@ -0,0 +1,437 @@ + 2, and some optimizations) are from + * Geoffrey T. Dairiki . The original PHP version of this + * code was written by him, and is used/adapted with his permission. + * + * Copyright 2004-2008 The Horde Project (http://www.horde.org/) + * + * See the enclosed file COPYING for license information (LGPL). If you did + * not receive this file, see http://opensource.org/licenses/lgpl-license.php. + * + * @author Geoffrey T. Dairiki + * @package Text_Diff + */ +class Text_Diff_Engine_native { + + function diff($from_lines, $to_lines) + { + array_walk($from_lines, array('Text_Diff', 'trimNewlines')); + array_walk($to_lines, array('Text_Diff', 'trimNewlines')); + + $n_from = count($from_lines); + $n_to = count($to_lines); + + $this->xchanged = $this->ychanged = array(); + $this->xv = $this->yv = array(); + $this->xind = $this->yind = array(); + unset($this->seq); + unset($this->in_seq); + unset($this->lcs); + + // Skip leading common lines. + for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) { + if ($from_lines[$skip] !== $to_lines[$skip]) { + break; + } + $this->xchanged[$skip] = $this->ychanged[$skip] = false; + } + + // Skip trailing common lines. + $xi = $n_from; $yi = $n_to; + for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) { + if ($from_lines[$xi] !== $to_lines[$yi]) { + break; + } + $this->xchanged[$xi] = $this->ychanged[$yi] = false; + } + + // Ignore lines which do not exist in both files. + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $xhash[$from_lines[$xi]] = 1; + } + for ($yi = $skip; $yi < $n_to - $endskip; $yi++) { + $line = $to_lines[$yi]; + if (($this->ychanged[$yi] = empty($xhash[$line]))) { + continue; + } + $yhash[$line] = 1; + $this->yv[] = $line; + $this->yind[] = $yi; + } + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $line = $from_lines[$xi]; + if (($this->xchanged[$xi] = empty($yhash[$line]))) { + continue; + } + $this->xv[] = $line; + $this->xind[] = $xi; + } + + // Find the LCS. + $this->_compareseq(0, count($this->xv), 0, count($this->yv)); + + // Merge edits when possible. + $this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged); + $this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged); + + // Compute the edit operations. + $edits = array(); + $xi = $yi = 0; + while ($xi < $n_from || $yi < $n_to) { + assert($yi < $n_to || $this->xchanged[$xi]); + assert($xi < $n_from || $this->ychanged[$yi]); + + // Skip matching "snake". + $copy = array(); + while ($xi < $n_from && $yi < $n_to + && !$this->xchanged[$xi] && !$this->ychanged[$yi]) { + $copy[] = $from_lines[$xi++]; + ++$yi; + } + if ($copy) { + $edits[] = &new Text_Diff_Op_copy($copy); + } + + // Find deletes & adds. + $delete = array(); + while ($xi < $n_from && $this->xchanged[$xi]) { + $delete[] = $from_lines[$xi++]; + } + + $add = array(); + while ($yi < $n_to && $this->ychanged[$yi]) { + $add[] = $to_lines[$yi++]; + } + + if ($delete && $add) { + $edits[] = &new Text_Diff_Op_change($delete, $add); + } elseif ($delete) { + $edits[] = &new Text_Diff_Op_delete($delete); + } elseif ($add) { + $edits[] = &new Text_Diff_Op_add($add); + } + } + + return $edits; + } + + /** + * Divides the Largest Common Subsequence (LCS) of the sequences (XOFF, + * XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized + * segments. + * + * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of + * NCHUNKS+1 (X, Y) indexes giving the diving points between sub + * sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1), + * the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) == + * (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM). + * + * This function assumes that the first lines of the specified portions of + * the two files do not match, and likewise that the last lines do not + * match. The caller must trim matching lines from the beginning and end + * of the portions it is going to specify. + */ + function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) + { + $flip = false; + + if ($xlim - $xoff > $ylim - $yoff) { + /* Things seems faster (I'm not sure I understand why) when the + * shortest sequence is in X. */ + $flip = true; + list ($xoff, $xlim, $yoff, $ylim) + = array($yoff, $ylim, $xoff, $xlim); + } + + if ($flip) { + for ($i = $ylim - 1; $i >= $yoff; $i--) { + $ymatches[$this->xv[$i]][] = $i; + } + } else { + for ($i = $ylim - 1; $i >= $yoff; $i--) { + $ymatches[$this->yv[$i]][] = $i; + } + } + + $this->lcs = 0; + $this->seq[0]= $yoff - 1; + $this->in_seq = array(); + $ymids[0] = array(); + + $numer = $xlim - $xoff + $nchunks - 1; + $x = $xoff; + for ($chunk = 0; $chunk < $nchunks; $chunk++) { + if ($chunk > 0) { + for ($i = 0; $i <= $this->lcs; $i++) { + $ymids[$i][$chunk - 1] = $this->seq[$i]; + } + } + + $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks); + for (; $x < $x1; $x++) { + $line = $flip ? $this->yv[$x] : $this->xv[$x]; + if (empty($ymatches[$line])) { + continue; + } + $matches = $ymatches[$line]; + reset($matches); + while (list(, $y) = each($matches)) { + if (empty($this->in_seq[$y])) { + $k = $this->_lcsPos($y); + assert($k > 0); + $ymids[$k] = $ymids[$k - 1]; + break; + } + } + while (list(, $y) = each($matches)) { + if ($y > $this->seq[$k - 1]) { + assert($y <= $this->seq[$k]); + /* Optimization: this is a common case: next match is + * just replacing previous match. */ + $this->in_seq[$this->seq[$k]] = false; + $this->seq[$k] = $y; + $this->in_seq[$y] = 1; + } elseif (empty($this->in_seq[$y])) { + $k = $this->_lcsPos($y); + assert($k > 0); + $ymids[$k] = $ymids[$k - 1]; + } + } + } + } + + $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); + $ymid = $ymids[$this->lcs]; + for ($n = 0; $n < $nchunks - 1; $n++) { + $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); + $y1 = $ymid[$n] + 1; + $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); + } + $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); + + return array($this->lcs, $seps); + } + + function _lcsPos($ypos) + { + $end = $this->lcs; + if ($end == 0 || $ypos > $this->seq[$end]) { + $this->seq[++$this->lcs] = $ypos; + $this->in_seq[$ypos] = 1; + return $this->lcs; + } + + $beg = 1; + while ($beg < $end) { + $mid = (int)(($beg + $end) / 2); + if ($ypos > $this->seq[$mid]) { + $beg = $mid + 1; + } else { + $end = $mid; + } + } + + assert($ypos != $this->seq[$end]); + + $this->in_seq[$this->seq[$end]] = false; + $this->seq[$end] = $ypos; + $this->in_seq[$ypos] = 1; + return $end; + } + + /** + * Finds LCS of two sequences. + * + * The results are recorded in the vectors $this->{x,y}changed[], by + * storing a 1 in the element for each line that is an insertion or + * deletion (ie. is not in the LCS). + * + * The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1. + * + * Note that XLIM, YLIM are exclusive bounds. All line numbers are + * origin-0 and discarded lines are not counted. + */ + function _compareseq ($xoff, $xlim, $yoff, $ylim) + { + /* Slide down the bottom initial diagonal. */ + while ($xoff < $xlim && $yoff < $ylim + && $this->xv[$xoff] == $this->yv[$yoff]) { + ++$xoff; + ++$yoff; + } + + /* Slide up the top initial diagonal. */ + while ($xlim > $xoff && $ylim > $yoff + && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { + --$xlim; + --$ylim; + } + + if ($xoff == $xlim || $yoff == $ylim) { + $lcs = 0; + } else { + /* This is ad hoc but seems to work well. $nchunks = + * sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks = + * max(2,min(8,(int)$nchunks)); */ + $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; + list($lcs, $seps) + = $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks); + } + + if ($lcs == 0) { + /* X and Y sequences have no common subsequence: mark all + * changed. */ + while ($yoff < $ylim) { + $this->ychanged[$this->yind[$yoff++]] = 1; + } + while ($xoff < $xlim) { + $this->xchanged[$this->xind[$xoff++]] = 1; + } + } else { + /* Use the partitions to split this problem into subproblems. */ + reset($seps); + $pt1 = $seps[0]; + while ($pt2 = next($seps)) { + $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); + $pt1 = $pt2; + } + } + } + + /** + * Adjusts inserts/deletes of identical lines to join changes as much as + * possible. + * + * We do something when a run of changed lines include a line at one end + * and has an excluded, identical line at the other. We are free to + * choose which identical line is included. `compareseq' usually chooses + * the one at the beginning, but usually it is cleaner to consider the + * following identical line to be the "change". + * + * This is extracted verbatim from analyze.c (GNU diffutils-2.7). + */ + function _shiftBoundaries($lines, &$changed, $other_changed) + { + $i = 0; + $j = 0; + + assert('count($lines) == count($changed)'); + $len = count($lines); + $other_len = count($other_changed); + + while (1) { + /* Scan forward to find the beginning of another run of + * changes. Also keep track of the corresponding point in the + * other file. + * + * Throughout this code, $i and $j are adjusted together so that + * the first $i elements of $changed and the first $j elements of + * $other_changed both contain the same number of zeros (unchanged + * lines). + * + * Furthermore, $j is always kept so that $j == $other_len or + * $other_changed[$j] == false. */ + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + + while ($i < $len && ! $changed[$i]) { + assert('$j < $other_len && ! $other_changed[$j]'); + $i++; $j++; + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + } + + if ($i == $len) { + break; + } + + $start = $i; + + /* Find the end of this run of changes. */ + while (++$i < $len && $changed[$i]) { + continue; + } + + do { + /* Record the length of this run of changes, so that we can + * later determine whether the run has grown. */ + $runlength = $i - $start; + + /* Move the changed region back, so long as the previous + * unchanged line matches the last changed one. This merges + * with previous changed regions. */ + while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { + $changed[--$start] = 1; + $changed[--$i] = false; + while ($start > 0 && $changed[$start - 1]) { + $start--; + } + assert('$j > 0'); + while ($other_changed[--$j]) { + continue; + } + assert('$j >= 0 && !$other_changed[$j]'); + } + + /* Set CORRESPONDING to the end of the changed run, at the + * last point where it corresponds to a changed run in the + * other file. CORRESPONDING == LEN means no such point has + * been found. */ + $corresponding = $j < $other_len ? $i : $len; + + /* Move the changed region forward, so long as the first + * changed line matches the following unchanged one. This + * merges with following changed regions. Do this second, so + * that if there are no merges, the changed region is moved + * forward as far as possible. */ + while ($i < $len && $lines[$start] == $lines[$i]) { + $changed[$start++] = false; + $changed[$i++] = 1; + while ($i < $len && $changed[$i]) { + $i++; + } + + assert('$j < $other_len && ! $other_changed[$j]'); + $j++; + if ($j < $other_len && $other_changed[$j]) { + $corresponding = $i; + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + } + } + } while ($runlength != $i - $start); + + /* If possible, move the fully-merged run of changes back to a + * corresponding run in the other file. */ + while ($corresponding < $i) { + $changed[--$start] = 1; + $changed[--$i] = 0; + assert('$j > 0'); + while ($other_changed[--$j]) { + continue; + } + assert('$j >= 0 && !$other_changed[$j]'); + } + } + } + +} diff --git a/wp-includes/Text/Diff/Engine/shell.php b/wp-includes/Text/Diff/Engine/shell.php new file mode 100644 index 0000000..7e9629f --- /dev/null +++ b/wp-includes/Text/Diff/Engine/shell.php @@ -0,0 +1,164 @@ + + * @package Text_Diff + * @since 0.3.0 + */ +class Text_Diff_Engine_shell { + + /** + * Path to the diff executable + * + * @var string + */ + var $_diffCommand = 'diff'; + + /** + * Returns the array of differences. + * + * @param array $from_lines lines of text from old file + * @param array $to_lines lines of text from new file + * + * @return array all changes made (array with Text_Diff_Op_* objects) + */ + function diff($from_lines, $to_lines) + { + array_walk($from_lines, array('Text_Diff', 'trimNewlines')); + array_walk($to_lines, array('Text_Diff', 'trimNewlines')); + + $temp_dir = Text_Diff::_getTempDir(); + + // Execute gnu diff or similar to get a standard diff file. + $from_file = tempnam($temp_dir, 'Text_Diff'); + $to_file = tempnam($temp_dir, 'Text_Diff'); + $fp = fopen($from_file, 'w'); + fwrite($fp, implode("\n", $from_lines)); + fclose($fp); + $fp = fopen($to_file, 'w'); + fwrite($fp, implode("\n", $to_lines)); + fclose($fp); + $diff = shell_exec($this->_diffCommand . ' ' . $from_file . ' ' . $to_file); + unlink($from_file); + unlink($to_file); + + if (is_null($diff)) { + // No changes were made + return array(new Text_Diff_Op_copy($from_lines)); + } + + $from_line_no = 1; + $to_line_no = 1; + $edits = array(); + + // Get changed lines by parsing something like: + // 0a1,2 + // 1,2c4,6 + // 1,5d6 + preg_match_all('#^(\d+)(?:,(\d+))?([adc])(\d+)(?:,(\d+))?$#m', $diff, + $matches, PREG_SET_ORDER); + + foreach ($matches as $match) { + if (!isset($match[5])) { + // This paren is not set every time (see regex). + $match[5] = false; + } + + if ($match[3] == 'a') { + $from_line_no--; + } + + if ($match[3] == 'd') { + $to_line_no--; + } + + if ($from_line_no < $match[1] || $to_line_no < $match[4]) { + // copied lines + assert('$match[1] - $from_line_no == $match[4] - $to_line_no'); + array_push($edits, + new Text_Diff_Op_copy( + $this->_getLines($from_lines, $from_line_no, $match[1] - 1), + $this->_getLines($to_lines, $to_line_no, $match[4] - 1))); + } + + switch ($match[3]) { + case 'd': + // deleted lines + array_push($edits, + new Text_Diff_Op_delete( + $this->_getLines($from_lines, $from_line_no, $match[2]))); + $to_line_no++; + break; + + case 'c': + // changed lines + array_push($edits, + new Text_Diff_Op_change( + $this->_getLines($from_lines, $from_line_no, $match[2]), + $this->_getLines($to_lines, $to_line_no, $match[5]))); + break; + + case 'a': + // added lines + array_push($edits, + new Text_Diff_Op_add( + $this->_getLines($to_lines, $to_line_no, $match[5]))); + $from_line_no++; + break; + } + } + + if (!empty($from_lines)) { + // Some lines might still be pending. Add them as copied + array_push($edits, + new Text_Diff_Op_copy( + $this->_getLines($from_lines, $from_line_no, + $from_line_no + count($from_lines) - 1), + $this->_getLines($to_lines, $to_line_no, + $to_line_no + count($to_lines) - 1))); + } + + return $edits; + } + + /** + * Get lines from either the old or new text + * + * @access private + * + * @param array &$text_lines Either $from_lines or $to_lines + * @param int &$line_no Current line number + * @param int $end Optional end line, when we want to chop more + * than one line. + * + * @return array The chopped lines + */ + function _getLines(&$text_lines, &$line_no, $end = false) + { + if (!empty($end)) { + $lines = array(); + // We can shift even more + while ($line_no <= $end) { + array_push($lines, array_shift($text_lines)); + $line_no++; + } + } else { + $lines = array(array_shift($text_lines)); + $line_no++; + } + + return $lines; + } + +} diff --git a/wp-includes/Text/Diff/Engine/string.php b/wp-includes/Text/Diff/Engine/string.php new file mode 100644 index 0000000..1a0bd3f --- /dev/null +++ b/wp-includes/Text/Diff/Engine/string.php @@ -0,0 +1,234 @@ + + * $patch = file_get_contents('example.patch'); + * $diff = new Text_Diff('string', array($patch)); + * $renderer = new Text_Diff_Renderer_inline(); + * echo $renderer->render($diff); + * + * + * $Horde: framework/Text_Diff/Diff/Engine/string.php,v 1.7 2008/01/04 10:07:50 jan Exp $ + * + * Copyright 2005 Örjan Persson + * Copyright 2005-2008 The Horde Project (http://www.horde.org/) + * + * See the enclosed file COPYING for license information (LGPL). If you did + * not receive this file, see http://opensource.org/licenses/lgpl-license.php. + * + * @author Örjan Persson + * @package Text_Diff + * @since 0.2.0 + */ +class Text_Diff_Engine_string { + + /** + * Parses a unified or context diff. + * + * First param contains the whole diff and the second can be used to force + * a specific diff type. If the second parameter is 'autodetect', the + * diff will be examined to find out which type of diff this is. + * + * @param string $diff The diff content. + * @param string $mode The diff mode of the content in $diff. One of + * 'context', 'unified', or 'autodetect'. + * + * @return array List of all diff operations. + */ + function diff($diff, $mode = 'autodetect') + { + if ($mode != 'autodetect' && $mode != 'context' && $mode != 'unified') { + return PEAR::raiseError('Type of diff is unsupported'); + } + + if ($mode == 'autodetect') { + $context = strpos($diff, '***'); + $unified = strpos($diff, '---'); + if ($context === $unified) { + return PEAR::raiseError('Type of diff could not be detected'); + } elseif ($context === false || $context === false) { + $mode = $context !== false ? 'context' : 'unified'; + } else { + $mode = $context < $unified ? 'context' : 'unified'; + } + } + + // split by new line and remove the diff header + $diff = explode("\n", $diff); + array_shift($diff); + array_shift($diff); + + if ($mode == 'context') { + return $this->parseContextDiff($diff); + } else { + return $this->parseUnifiedDiff($diff); + } + } + + /** + * Parses an array containing the unified diff. + * + * @param array $diff Array of lines. + * + * @return array List of all diff operations. + */ + function parseUnifiedDiff($diff) + { + $edits = array(); + $end = count($diff) - 1; + for ($i = 0; $i < $end;) { + $diff1 = array(); + switch (substr($diff[$i], 0, 1)) { + case ' ': + do { + $diff1[] = substr($diff[$i], 1); + } while (++$i < $end && substr($diff[$i], 0, 1) == ' '); + $edits[] = &new Text_Diff_Op_copy($diff1); + break; + + case '+': + // get all new lines + do { + $diff1[] = substr($diff[$i], 1); + } while (++$i < $end && substr($diff[$i], 0, 1) == '+'); + $edits[] = &new Text_Diff_Op_add($diff1); + break; + + case '-': + // get changed or removed lines + $diff2 = array(); + do { + $diff1[] = substr($diff[$i], 1); + } while (++$i < $end && substr($diff[$i], 0, 1) == '-'); + + while ($i < $end && substr($diff[$i], 0, 1) == '+') { + $diff2[] = substr($diff[$i++], 1); + } + if (count($diff2) == 0) { + $edits[] = &new Text_Diff_Op_delete($diff1); + } else { + $edits[] = &new Text_Diff_Op_change($diff1, $diff2); + } + break; + + default: + $i++; + break; + } + } + + return $edits; + } + + /** + * Parses an array containing the context diff. + * + * @param array $diff Array of lines. + * + * @return array List of all diff operations. + */ + function parseContextDiff(&$diff) + { + $edits = array(); + $i = $max_i = $j = $max_j = 0; + $end = count($diff) - 1; + while ($i < $end && $j < $end) { + while ($i >= $max_i && $j >= $max_j) { + // Find the boundaries of the diff output of the two files + for ($i = $j; + $i < $end && substr($diff[$i], 0, 3) == '***'; + $i++); + for ($max_i = $i; + $max_i < $end && substr($diff[$max_i], 0, 3) != '---'; + $max_i++); + for ($j = $max_i; + $j < $end && substr($diff[$j], 0, 3) == '---'; + $j++); + for ($max_j = $j; + $max_j < $end && substr($diff[$max_j], 0, 3) != '***'; + $max_j++); + } + + // find what hasn't been changed + $array = array(); + while ($i < $max_i && + $j < $max_j && + strcmp($diff[$i], $diff[$j]) == 0) { + $array[] = substr($diff[$i], 2); + $i++; + $j++; + } + + while ($i < $max_i && ($max_j-$j) <= 1) { + if ($diff[$i] != '' && substr($diff[$i], 0, 1) != ' ') { + break; + } + $array[] = substr($diff[$i++], 2); + } + + while ($j < $max_j && ($max_i-$i) <= 1) { + if ($diff[$j] != '' && substr($diff[$j], 0, 1) != ' ') { + break; + } + $array[] = substr($diff[$j++], 2); + } + if (count($array) > 0) { + $edits[] = &new Text_Diff_Op_copy($array); + } + + if ($i < $max_i) { + $diff1 = array(); + switch (substr($diff[$i], 0, 1)) { + case '!': + $diff2 = array(); + do { + $diff1[] = substr($diff[$i], 2); + if ($j < $max_j && substr($diff[$j], 0, 1) == '!') { + $diff2[] = substr($diff[$j++], 2); + } + } while (++$i < $max_i && substr($diff[$i], 0, 1) == '!'); + $edits[] = &new Text_Diff_Op_change($diff1, $diff2); + break; + + case '+': + do { + $diff1[] = substr($diff[$i], 2); + } while (++$i < $max_i && substr($diff[$i], 0, 1) == '+'); + $edits[] = &new Text_Diff_Op_add($diff1); + break; + + case '-': + do { + $diff1[] = substr($diff[$i], 2); + } while (++$i < $max_i && substr($diff[$i], 0, 1) == '-'); + $edits[] = &new Text_Diff_Op_delete($diff1); + break; + } + } + + if ($j < $max_j) { + $diff2 = array(); + switch (substr($diff[$j], 0, 1)) { + case '+': + do { + $diff2[] = substr($diff[$j++], 2); + } while ($j < $max_j && substr($diff[$j], 0, 1) == '+'); + $edits[] = &new Text_Diff_Op_add($diff2); + break; + + case '-': + do { + $diff2[] = substr($diff[$j++], 2); + } while ($j < $max_j && substr($diff[$j], 0, 1) == '-'); + $edits[] = &new Text_Diff_Op_delete($diff2); + break; + } + } + } + + return $edits; + } + +} diff --git a/wp-includes/Text/Diff/Engine/xdiff.php b/wp-includes/Text/Diff/Engine/xdiff.php new file mode 100644 index 0000000..a39a4be --- /dev/null +++ b/wp-includes/Text/Diff/Engine/xdiff.php @@ -0,0 +1,63 @@ + + * @package Text_Diff + */ +class Text_Diff_Engine_xdiff { + + /** + */ + function diff($from_lines, $to_lines) + { + array_walk($from_lines, array('Text_Diff', 'trimNewlines')); + array_walk($to_lines, array('Text_Diff', 'trimNewlines')); + + /* Convert the two input arrays into strings for xdiff processing. */ + $from_string = implode("\n", $from_lines); + $to_string = implode("\n", $to_lines); + + /* Diff the two strings and convert the result to an array. */ + $diff = xdiff_string_diff($from_string, $to_string, count($to_lines)); + $diff = explode("\n", $diff); + + /* Walk through the diff one line at a time. We build the $edits + * array of diff operations by reading the first character of the + * xdiff output (which is in the "unified diff" format). + * + * Note that we don't have enough information to detect "changed" + * lines using this approach, so we can't add Text_Diff_Op_changed + * instances to the $edits array. The result is still perfectly + * valid, albeit a little less descriptive and efficient. */ + $edits = array(); + foreach ($diff as $line) { + switch ($line[0]) { + case ' ': + $edits[] = &new Text_Diff_Op_copy(array(substr($line, 1))); + break; + + case '+': + $edits[] = &new Text_Diff_Op_add(array(substr($line, 1))); + break; + + case '-': + $edits[] = &new Text_Diff_Op_delete(array(substr($line, 1))); + break; + } + } + + return $edits; + } + +} diff --git a/wp-includes/Text/Diff/Renderer.php b/wp-includes/Text/Diff/Renderer.php new file mode 100644 index 0000000..5d226b4 --- /dev/null +++ b/wp-includes/Text/Diff/Renderer.php @@ -0,0 +1,237 @@ + $value) { + $v = '_' . $param; + if (isset($this->$v)) { + $this->$v = $value; + } + } + } + + /** + * Get any renderer parameters. + * + * @return array All parameters of this renderer object. + */ + function getParams() + { + $params = array(); + foreach (get_object_vars($this) as $k => $v) { + if ($k[0] == '_') { + $params[substr($k, 1)] = $v; + } + } + + return $params; + } + + /** + * Renders a diff. + * + * @param Text_Diff $diff A Text_Diff object. + * + * @return string The formatted output. + */ + function render($diff) + { + $xi = $yi = 1; + $block = false; + $context = array(); + + $nlead = $this->_leading_context_lines; + $ntrail = $this->_trailing_context_lines; + + $output = $this->_startDiff(); + + $diffs = $diff->getDiff(); + foreach ($diffs as $i => $edit) { + /* If these are unchanged (copied) lines, and we want to keep + * leading or trailing context lines, extract them from the copy + * block. */ + if (is_a($edit, 'Text_Diff_Op_copy')) { + /* Do we have any diff blocks yet? */ + if (is_array($block)) { + /* How many lines to keep as context from the copy + * block. */ + $keep = $i == count($diffs) - 1 ? $ntrail : $nlead + $ntrail; + if (count($edit->orig) <= $keep) { + /* We have less lines in the block than we want for + * context => keep the whole block. */ + $block[] = $edit; + } else { + if ($ntrail) { + /* Create a new block with as many lines as we need + * for the trailing context. */ + $context = array_slice($edit->orig, 0, $ntrail); + $block[] = &new Text_Diff_Op_copy($context); + } + /* @todo */ + $output .= $this->_block($x0, $ntrail + $xi - $x0, + $y0, $ntrail + $yi - $y0, + $block); + $block = false; + } + } + /* Keep the copy block as the context for the next block. */ + $context = $edit->orig; + } else { + /* Don't we have any diff blocks yet? */ + if (!is_array($block)) { + /* Extract context lines from the preceding copy block. */ + $context = array_slice($context, count($context) - $nlead); + $x0 = $xi - count($context); + $y0 = $yi - count($context); + $block = array(); + if ($context) { + $block[] = &new Text_Diff_Op_copy($context); + } + } + $block[] = $edit; + } + + if ($edit->orig) { + $xi += count($edit->orig); + } + if ($edit->final) { + $yi += count($edit->final); + } + } + + if (is_array($block)) { + $output .= $this->_block($x0, $xi - $x0, + $y0, $yi - $y0, + $block); + } + + return $output . $this->_endDiff(); + } + + function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) + { + $output = $this->_startBlock($this->_blockHeader($xbeg, $xlen, $ybeg, $ylen)); + + foreach ($edits as $edit) { + switch (strtolower(get_class($edit))) { + case 'text_diff_op_copy': + $output .= $this->_context($edit->orig); + break; + + case 'text_diff_op_add': + $output .= $this->_added($edit->final); + break; + + case 'text_diff_op_delete': + $output .= $this->_deleted($edit->orig); + break; + + case 'text_diff_op_change': + $output .= $this->_changed($edit->orig, $edit->final); + break; + } + } + + return $output . $this->_endBlock(); + } + + function _startDiff() + { + return ''; + } + + function _endDiff() + { + return ''; + } + + function _blockHeader($xbeg, $xlen, $ybeg, $ylen) + { + if ($xlen > 1) { + $xbeg .= ',' . ($xbeg + $xlen - 1); + } + if ($ylen > 1) { + $ybeg .= ',' . ($ybeg + $ylen - 1); + } + + // this matches the GNU Diff behaviour + if ($xlen && !$ylen) { + $ybeg--; + } elseif (!$xlen) { + $xbeg--; + } + + return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg; + } + + function _startBlock($header) + { + return $header . "\n"; + } + + function _endBlock() + { + return ''; + } + + function _lines($lines, $prefix = ' ') + { + return $prefix . implode("\n$prefix", $lines) . "\n"; + } + + function _context($lines) + { + return $this->_lines($lines, ' '); + } + + function _added($lines) + { + return $this->_lines($lines, '> '); + } + + function _deleted($lines) + { + return $this->_lines($lines, '< '); + } + + function _changed($orig, $final) + { + return $this->_deleted($orig) . "---\n" . $this->_added($final); + } + +} diff --git a/wp-includes/Text/Diff/Renderer/inline.php b/wp-includes/Text/Diff/Renderer/inline.php new file mode 100644 index 0000000..1493eaa --- /dev/null +++ b/wp-includes/Text/Diff/Renderer/inline.php @@ -0,0 +1,172 @@ +'; + + /** + * Suffix for inserted text. + */ + var $_ins_suffix = ''; + + /** + * Prefix for deleted text. + */ + var $_del_prefix = ''; + + /** + * Suffix for deleted text. + */ + var $_del_suffix = ''; + + /** + * Header for each change block. + */ + var $_block_header = ''; + + /** + * What are we currently splitting on? Used to recurse to show word-level + * changes. + */ + var $_split_level = 'lines'; + + function _blockHeader($xbeg, $xlen, $ybeg, $ylen) + { + return $this->_block_header; + } + + function _startBlock($header) + { + return $header; + } + + function _lines($lines, $prefix = ' ', $encode = true) + { + if ($encode) { + array_walk($lines, array(&$this, '_encode')); + } + + if ($this->_split_level == 'words') { + return implode('', $lines); + } else { + return implode("\n", $lines) . "\n"; + } + } + + function _added($lines) + { + array_walk($lines, array(&$this, '_encode')); + $lines[0] = $this->_ins_prefix . $lines[0]; + $lines[count($lines) - 1] .= $this->_ins_suffix; + return $this->_lines($lines, ' ', false); + } + + function _deleted($lines, $words = false) + { + array_walk($lines, array(&$this, '_encode')); + $lines[0] = $this->_del_prefix . $lines[0]; + $lines[count($lines) - 1] .= $this->_del_suffix; + return $this->_lines($lines, ' ', false); + } + + function _changed($orig, $final) + { + /* If we've already split on words, don't try to do so again - just + * display. */ + if ($this->_split_level == 'words') { + $prefix = ''; + while ($orig[0] !== false && $final[0] !== false && + substr($orig[0], 0, 1) == ' ' && + substr($final[0], 0, 1) == ' ') { + $prefix .= substr($orig[0], 0, 1); + $orig[0] = substr($orig[0], 1); + $final[0] = substr($final[0], 1); + } + return $prefix . $this->_deleted($orig) . $this->_added($final); + } + + $text1 = implode("\n", $orig); + $text2 = implode("\n", $final); + + /* Non-printing newline marker. */ + $nl = "\0"; + + /* We want to split on word boundaries, but we need to + * preserve whitespace as well. Therefore we split on words, + * but include all blocks of whitespace in the wordlist. */ + $diff = new Text_Diff($this->_splitOnWords($text1, $nl), + $this->_splitOnWords($text2, $nl)); + + /* Get the diff in inline format. */ + $renderer = new Text_Diff_Renderer_inline(array_merge($this->getParams(), + array('split_level' => 'words'))); + + /* Run the diff and get the output. */ + return str_replace($nl, "\n", $renderer->render($diff)) . "\n"; + } + + function _splitOnWords($string, $newlineEscape = "\n") + { + // Ignore \0; otherwise the while loop will never finish. + $string = str_replace("\0", '', $string); + + $words = array(); + $length = strlen($string); + $pos = 0; + + while ($pos < $length) { + // Eat a word with any preceding whitespace. + $spaces = strspn(substr($string, $pos), " \n"); + $nextpos = strcspn(substr($string, $pos + $spaces), " \n"); + $words[] = str_replace("\n", $newlineEscape, substr($string, $pos, $spaces + $nextpos)); + $pos += $spaces + $nextpos; + } + + return $words; + } + + function _encode(&$string) + { + $string = htmlspecialchars($string); + } + +} diff --git a/wp-includes/atomlib.php b/wp-includes/atomlib.php new file mode 100644 index 0000000..e75ca39 --- /dev/null +++ b/wp-includes/atomlib.php @@ -0,0 +1,354 @@ + + * @version 0.4 + * @since 2.3 + */ + +/** + * Structure that store common Atom Feed Properties + * + * @package AtomLib + */ +class AtomFeed { + /** + * Stores Links + * @var array + * @access public + */ + var $links = array(); + /** + * Stores Categories + * @var array + * @access public + */ + var $categories = array(); + /** + * Stores Entries + * + * @var array + * @access public + */ + var $entries = array(); +} + +/** + * Structure that store Atom Entry Properties + * + * @package AtomLib + */ +class AtomEntry { + /** + * Stores Links + * @var array + * @access public + */ + var $links = array(); + /** + * Stores Categories + * @var array + * @access public + */ + var $categories = array(); +} + +/** + * AtomLib Atom Parser API + * + * @package AtomLib + */ +class AtomParser { + + var $NS = 'http://www.w3.org/2005/Atom'; + var $ATOM_CONTENT_ELEMENTS = array('content','summary','title','subtitle','rights'); + var $ATOM_SIMPLE_ELEMENTS = array('id','updated','published','draft'); + + var $debug = false; + + var $depth = 0; + var $indent = 2; + var $in_content; + var $ns_contexts = array(); + var $ns_decls = array(); + var $content_ns_decls = array(); + var $content_ns_contexts = array(); + var $is_xhtml = false; + var $is_html = false; + var $is_text = true; + var $skipped_div = false; + + var $FILE = "php://input"; + + var $feed; + var $current; + + function AtomParser() { + + $this->feed = new AtomFeed(); + $this->current = null; + $this->map_attrs_func = create_function('$k,$v', 'return "$k=\"$v\"";'); + $this->map_xmlns_func = create_function('$p,$n', '$xd = "xmlns"; if(strlen($n[0])>0) $xd .= ":{$n[0]}"; return "{$xd}=\"{$n[1]}\"";'); + } + + function _p($msg) { + if($this->debug) { + print str_repeat(" ", $this->depth * $this->indent) . $msg ."\n"; + } + } + + function error_handler($log_level, $log_text, $error_file, $error_line) { + $this->error = $log_text; + } + + function parse() { + + set_error_handler(array(&$this, 'error_handler')); + + array_unshift($this->ns_contexts, array()); + + $parser = xml_parser_create_ns(); + xml_set_object($parser, $this); + xml_set_element_handler($parser, "start_element", "end_element"); + xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); + xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,0); + xml_set_character_data_handler($parser, "cdata"); + xml_set_default_handler($parser, "_default"); + xml_set_start_namespace_decl_handler($parser, "start_ns"); + xml_set_end_namespace_decl_handler($parser, "end_ns"); + + $this->content = ''; + + $ret = true; + + $fp = fopen($this->FILE, "r"); + while ($data = fread($fp, 4096)) { + if($this->debug) $this->content .= $data; + + if(!xml_parse($parser, $data, feof($fp))) { + trigger_error(sprintf(__('XML error: %s at line %d')."\n", + xml_error_string(xml_get_error_code($xml_parser)), + xml_get_current_line_number($xml_parser))); + $ret = false; + break; + } + } + fclose($fp); + + xml_parser_free($parser); + + restore_error_handler(); + + return $ret; + } + + function start_element($parser, $name, $attrs) { + + $tag = array_pop(split(":", $name)); + + switch($name) { + case $this->NS . ':feed': + $this->current = $this->feed; + break; + case $this->NS . ':entry': + $this->current = new AtomEntry(); + break; + }; + + $this->_p("start_element('$name')"); + #$this->_p(print_r($this->ns_contexts,true)); + #$this->_p('current(' . $this->current . ')'); + + array_unshift($this->ns_contexts, $this->ns_decls); + + $this->depth++; + + if(!empty($this->in_content)) { + + $this->content_ns_decls = array(); + + if($this->is_html || $this->is_text) + trigger_error("Invalid content in element found. Content must not be of type text or html if it contains markup."); + + $attrs_prefix = array(); + + // resolve prefixes for attributes + foreach($attrs as $key => $value) { + $with_prefix = $this->ns_to_prefix($key, true); + $attrs_prefix[$with_prefix[1]] = $this->xml_escape($value); + } + + $attrs_str = join(' ', array_map($this->map_attrs_func, array_keys($attrs_prefix), array_values($attrs_prefix))); + if(strlen($attrs_str) > 0) { + $attrs_str = " " . $attrs_str; + } + + $with_prefix = $this->ns_to_prefix($name); + + if(!$this->is_declared_content_ns($with_prefix[0])) { + array_push($this->content_ns_decls, $with_prefix[0]); + } + + $xmlns_str = ''; + if(count($this->content_ns_decls) > 0) { + array_unshift($this->content_ns_contexts, $this->content_ns_decls); + $xmlns_str .= join(' ', array_map($this->map_xmlns_func, array_keys($this->content_ns_contexts[0]), array_values($this->content_ns_contexts[0]))); + if(strlen($xmlns_str) > 0) { + $xmlns_str = " " . $xmlns_str; + } + } + + array_push($this->in_content, array($tag, $this->depth, "<". $with_prefix[1] ."{$xmlns_str}{$attrs_str}" . ">")); + + } else if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS) || in_array($tag, $this->ATOM_SIMPLE_ELEMENTS)) { + $this->in_content = array(); + $this->is_xhtml = $attrs['type'] == 'xhtml'; + $this->is_html = $attrs['type'] == 'html' || $attrs['type'] == 'text/html'; + $this->is_text = !in_array('type',array_keys($attrs)) || $attrs['type'] == 'text'; + $type = $this->is_xhtml ? 'XHTML' : ($this->is_html ? 'HTML' : ($this->is_text ? 'TEXT' : $attrs['type'])); + + if(in_array('src',array_keys($attrs))) { + $this->current->$tag = $attrs; + } else { + array_push($this->in_content, array($tag,$this->depth, $type)); + } + } else if($tag == 'link') { + array_push($this->current->links, $attrs); + } else if($tag == 'category') { + array_push($this->current->categories, $attrs); + } + + $this->ns_decls = array(); + } + + function end_element($parser, $name) { + + $tag = array_pop(split(":", $name)); + + $ccount = count($this->in_content); + + # if we are *in* content, then let's proceed to serialize it + if(!empty($this->in_content)) { + # if we are ending the original content element + # then let's finalize the content + if($this->in_content[0][0] == $tag && + $this->in_content[0][1] == $this->depth) { + $origtype = $this->in_content[0][2]; + array_shift($this->in_content); + $newcontent = array(); + foreach($this->in_content as $c) { + if(count($c) == 3) { + array_push($newcontent, $c[2]); + } else { + if($this->is_xhtml || $this->is_text) { + array_push($newcontent, $this->xml_escape($c)); + } else { + array_push($newcontent, $c); + } + } + } + if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS)) { + $this->current->$tag = array($origtype, join('',$newcontent)); + } else { + $this->current->$tag = join('',$newcontent); + } + $this->in_content = array(); + } else if($this->in_content[$ccount-1][0] == $tag && + $this->in_content[$ccount-1][1] == $this->depth) { + $this->in_content[$ccount-1][2] = substr($this->in_content[$ccount-1][2],0,-1) . "/>"; + } else { + # else, just finalize the current element's content + $endtag = $this->ns_to_prefix($name); + array_push($this->in_content, array($tag, $this->depth, "")); + } + } + + array_shift($this->ns_contexts); + + $this->depth--; + + if($name == ($this->NS . ':entry')) { + array_push($this->feed->entries, $this->current); + $this->current = null; + } + + $this->_p("end_element('$name')"); + } + + function start_ns($parser, $prefix, $uri) { + $this->_p("starting: " . $prefix . ":" . $uri); + array_push($this->ns_decls, array($prefix,$uri)); + } + + function end_ns($parser, $prefix) { + $this->_p("ending: #" . $prefix . "#"); + } + + function cdata($parser, $data) { + $this->_p("data: #" . str_replace(array("\n"), array("\\n"), trim($data)) . "#"); + if(!empty($this->in_content)) { + array_push($this->in_content, $data); + } + } + + function _default($parser, $data) { + # when does this gets called? + } + + + function ns_to_prefix($qname, $attr=false) { + # split 'http://www.w3.org/1999/xhtml:div' into ('http','//www.w3.org/1999/xhtml','div') + $components = split(":", $qname); + + # grab the last one (e.g 'div') + $name = array_pop($components); + + if(!empty($components)) { + # re-join back the namespace component + $ns = join(":",$components); + foreach($this->ns_contexts as $context) { + foreach($context as $mapping) { + if($mapping[1] == $ns && strlen($mapping[0]) > 0) { + return array($mapping, "$mapping[0]:$name"); + } + } + } + } + + if($attr) { + return array(null, $name); + } else { + foreach($this->ns_contexts as $context) { + foreach($context as $mapping) { + if(strlen($mapping[0]) == 0) { + return array($mapping, $name); + } + } + } + } + } + + function is_declared_content_ns($new_mapping) { + foreach($this->content_ns_contexts as $context) { + foreach($context as $mapping) { + if($new_mapping == $mapping) { + return true; + } + } + } + return false; + } + + function xml_escape($string) + { + return str_replace(array('&','"',"'",'<','>'), + array('&','"',''','<','>'), + $string ); + } +} + +?> diff --git a/wp-includes/author-template.php b/wp-includes/author-template.php new file mode 100644 index 0000000..19e7b86 --- /dev/null +++ b/wp-includes/author-template.php @@ -0,0 +1,341 @@ +display_name); +} + +/** + * Display the name of the author of the current post. + * + * The behavior of this function is based off of old functionality predating + * get_the_author(). This function is not deprecated, but is designed to echo + * the value from get_the_author() and as an result of any old theme that might + * still use the old behavior will also pass the value from get_the_author(). + * + * The normal, expected behavior of this function is to echo the author and not + * return it. However, backwards compatiability has to be maintained. + * + * @since 0.71 + * @see get_the_author() + * @link http://codex.wordpress.org/Template_Tags/the_author + * + * @param string $deprecated Deprecated. + * @param string $deprecated_echo Echo the string or return it. + * @return string The author's display name, from get_the_author(). + */ +function the_author($deprecated = '', $deprecated_echo = true) { + if ( $deprecated_echo ) + echo get_the_author(); + return get_the_author(); +} + +/** + * Retrieve the author who last edited the current post. + * + * @since 2.8 + * @uses $post The current post's DB object. + * @uses get_post_meta() Retrieves the ID of the author who last edited the current post. + * @uses get_userdata() Retrieves the author's DB object. + * @uses apply_filters() Calls 'the_modified_author' hook on the author display name. + * @return string The author's display name. + */ +function get_the_modified_author() { + global $post; + if ( $last_id = get_post_meta($post->ID, '_edit_last', true) ) { + $last_user = get_userdata($last_id); + return apply_filters('the_modified_author', $last_user->display_name); + } +} + +/** + * Display the name of the author who last edited the current post. + * + * @since 2.8 + * @see get_the_author() + * @return string The author's display name, from get_the_modified_author(). + */ +function the_modified_author() { + echo get_the_modified_author(); +} + +/** + * Retrieve the requested data of the author of the current post. + * @link http://codex.wordpress.org/Template_Tags/the_author_meta + * @since 2.8.0 + * @uses $authordata The current author's DB object (if $user_id not specified). + * @param string $field selects the field of the users record. + * @param int $user_id Optional. User ID. + * @return string The author's field from the current author's DB object. + */ +function get_the_author_meta($field = '', $user_id = false) { + if ( ! $user_id ) + global $authordata; + else + $authordata = get_userdata( $user_id ); + + $field = strtolower($field); + $user_field = "user_$field"; + + if ( 'id' == $field ) + $value = isset($authordata->ID) ? (int)$authordata->ID : 0; + elseif ( isset($authordata->$user_field) ) + $value = $authordata->$user_field; + else + $value = isset($authordata->$field) ? $authordata->$field : ''; + + return apply_filters('get_the_author_' . $field, $value); +} + +/** + * Retrieve the requested data of the author of the current post. + * @link http://codex.wordpress.org/Template_Tags/the_author_meta + * @since 2.8.0 + * @param string $field selects the field of the users record. + * @param int $user_id Optional. User ID. + * @echo string The author's field from the current author's DB object. + */ +function the_author_meta($field = '', $user_id = false) { + echo apply_filters('the_author_' . $field, get_the_author_meta($field, $user_id)); +} + +/** + * Display either author's link or author's name. + * + * If the author has a home page set, echo an HTML link, otherwise just echo the + * author's name. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_link + * @since 2.1 + * @uses get_the_author_meta() + * @uses the_author() + */ +function the_author_link() { + if ( get_the_author_meta('url') ) { + echo '' . get_the_author() . ''; + } else { + the_author(); + } +} + +/** + * Retrieve the number of posts by the author of the current post. + * + * @since 1.5 + * @uses $post The current post in the Loop's DB object. + * @uses get_usernumposts() + * @return int The number of posts by the author. + */ +function get_the_author_posts() { + global $post; + return get_usernumposts($post->post_author); +} + +/** + * Display the number of posts by the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_posts + * @since 0.71 + * @uses get_the_author_posts() Echos returned value from function. + */ +function the_author_posts() { + echo get_the_author_posts(); +} + +/** + * Display an HTML link to the author page of the author of the current post. + * + * Does just echo get_author_posts_url() function, like the others do. The + * reason for this, is that another function is used to help in printing the + * link to the author's posts. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_posts_link + * @since 1.2.0 + * @uses $authordata The current author's DB object. + * @uses get_author_posts_url() + * @uses get_the_author() + * @param string $deprecated Deprecated. + */ +function the_author_posts_link($deprecated = '') { + global $authordata; + printf( + '%3$s', + get_author_posts_url( $authordata->ID, $authordata->user_nicename ), + sprintf( __( 'Posts by %s' ), esc_attr( get_the_author() ) ), + get_the_author() + ); +} + +/** + * Retrieve the URL to the author page of the author of the current post. + * + * @since 2.1.0 + * @uses $wp_rewrite WP_Rewrite + * @return string The URL to the author's page. + */ +function get_author_posts_url($author_id, $author_nicename = '') { + global $wp_rewrite; + $auth_ID = (int) $author_id; + $link = $wp_rewrite->get_author_permastruct(); + + if ( empty($link) ) { + $file = get_option('home') . '/'; + $link = $file . '?author=' . $auth_ID; + } else { + if ( '' == $author_nicename ) { + $user = get_userdata($author_id); + if ( !empty($user->user_nicename) ) + $author_nicename = $user->user_nicename; + } + $link = str_replace('%author%', $author_nicename, $link); + $link = get_option('home') . trailingslashit($link); + } + + $link = apply_filters('author_link', $link, $author_id, $author_nicename); + + return $link; +} + +/** + * List all the authors of the blog, with several options available. + * + *
      + *
    • optioncount (boolean) (false): Show the count in parenthesis next to the + * author's name.
    • + *
    • exclude_admin (boolean) (true): Exclude the 'admin' user that is + * installed bydefault.
    • + *
    • show_fullname (boolean) (false): Show their full names.
    • + *
    • hide_empty (boolean) (true): Don't show authors without any posts.
    • + *
    • feed (string) (''): If isn't empty, show links to author's feeds.
    • + *
    • feed_image (string) (''): If isn't empty, use this image to link to + * feeds.
    • + *
    • echo (boolean) (true): Set to false to return the output, instead of + * echoing.
    • + *
    • style (string) ('list'): Whether to display list of authors in list form + * or as a string.
    • + *
    • html (bool) (true): Whether to list the items in html for or plaintext. + *
    • + *
    + * + * @link http://codex.wordpress.org/Template_Tags/wp_list_authors + * @since 1.2.0 + * @param array $args The argument array. + * @return null|string The output, if echo is set to false. + */ +function wp_list_authors($args = '') { + global $wpdb; + + $defaults = array( + 'optioncount' => false, 'exclude_admin' => true, + 'show_fullname' => false, 'hide_empty' => true, + 'feed' => '', 'feed_image' => '', 'feed_type' => '', 'echo' => true, + 'style' => 'list', 'html' => true + ); + + $r = wp_parse_args( $args, $defaults ); + extract($r, EXTR_SKIP); + $return = ''; + + /** @todo Move select to get_authors(). */ + $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users " . ($exclude_admin ? "WHERE user_login <> 'admin' " : '') . "ORDER BY display_name"); + + $author_count = array(); + foreach ((array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author") as $row) { + $author_count[$row->post_author] = $row->count; + } + + foreach ( (array) $authors as $author ) { + + $link = ''; + + $author = get_userdata( $author->ID ); + $posts = (isset($author_count[$author->ID])) ? $author_count[$author->ID] : 0; + $name = $author->display_name; + + if ( $show_fullname && ($author->first_name != '' && $author->last_name != '') ) + $name = "$author->first_name $author->last_name"; + + if( !$html ) { + if ( $posts == 0 ) { + if ( ! $hide_empty ) + $return .= $name . ', '; + } else + $return .= $name . ', '; + + // No need to go further to process HTML. + continue; + } + + if ( !($posts == 0 && $hide_empty) && 'list' == $style ) + $return .= '
  • '; + if ( $posts == 0 ) { + if ( ! $hide_empty ) + $link = $name; + } else { + $link = 'display_name)) . '">' . $name . ''; + + if ( (! empty($feed_image)) || (! empty($feed)) ) { + $link .= ' '; + if (empty($feed_image)) + $link .= '('; + $link .= ''; + else + $link .= $name; + + $link .= ''; + + if ( empty($feed_image) ) + $link .= ')'; + } + + if ( $optioncount ) + $link .= ' ('. $posts . ')'; + + } + + if ( !($posts == 0 && $hide_empty) && 'list' == $style ) + $return .= $link . '
  • '; + else if ( ! $hide_empty ) + $return .= $link . ', '; + } + + $return = trim($return, ', '); + + if ( ! $echo ) + return $return; + echo $return; +} + +?> diff --git a/wp-includes/bookmark-template.php b/wp-includes/bookmark-template.php new file mode 100644 index 0000000..bb4f6ef --- /dev/null +++ b/wp-includes/bookmark-template.php @@ -0,0 +1,254 @@ +' (string). The html or text to prepend to each + * bookmarks. + * 'after' - Default is '' (string). The html or text to append to each + * bookmarks. + * 'link_before' - Default is '' (string). The html or text to prepend to each + * bookmarks inside the tag. + * 'link_after' - Default is '' (string). The html or text to append to each + * bookmarks inside the tag. + * 'between' - Default is '\n' (string). The string for use in between the link, + * description, and image. + * 'show_rating' - Default is 0 (integer). Whether to show the link rating. + * + * @since 2.1.0 + * @access private + * @usedby wp_list_bookmarks() + * + * @param array $bookmarks List of bookmarks to traverse + * @param string|array $args Optional. Overwrite the defaults. + * @return string Formatted output in HTML + */ +function _walk_bookmarks($bookmarks, $args = '' ) { + $defaults = array( + 'show_updated' => 0, 'show_description' => 0, + 'show_images' => 1, 'show_name' => 0, + 'before' => '
  • ', 'after' => '
  • ', 'between' => "\n", + 'show_rating' => 0, 'link_before' => '', 'link_after' => '' + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + $output = ''; // Blank string to start with. + + foreach ( (array) $bookmarks as $bookmark ) { + if ( !isset($bookmark->recently_updated) ) + $bookmark->recently_updated = false; + $output .= $before; + if ( $show_updated && $bookmark->recently_updated ) + $output .= get_option('links_recently_updated_prepend'); + + $the_link = '#'; + if ( !empty($bookmark->link_url) ) + $the_link = esc_url($bookmark->link_url); + + $desc = esc_attr(sanitize_bookmark_field('link_description', $bookmark->link_description, $bookmark->link_id, 'display')); + $name = esc_attr(sanitize_bookmark_field('link_name', $bookmark->link_name, $bookmark->link_id, 'display')); + $title = $desc; + + if ( $show_updated ) + if ( '00' != substr($bookmark->link_updated_f, 0, 2) ) { + $title .= ' ('; + $title .= sprintf(__('Last updated: %s'), date(get_option('links_updated_date_format'), $bookmark->link_updated_f + (get_option('gmt_offset') * 3600))); + $title .= ')'; + } + + $alt = ' alt="' . $name . ( $show_description ? ' ' . $title : '' ) . '"'; + + if ( '' != $title ) + $title = ' title="' . $title . '"'; + + $rel = $bookmark->link_rel; + if ( '' != $rel ) + $rel = ' rel="' . $rel . '"'; + + $target = $bookmark->link_target; + if ( '' != $target ) + $target = ' target="' . $target . '"'; + + $output .= '
    '; + + $output .= $link_before; + + if ( $bookmark->link_image != null && $show_images ) { + if ( strpos($bookmark->link_image, 'http') === 0 ) + $output .= "link_image\" $alt $title />"; + else // If it's a relative path + $output .= "link_image\" $alt $title />"; + + if ( $show_name ) + $output .= " $name"; + } else { + $output .= $name; + } + + $output .= $link_after; + + $output .= ''; + + if ( $show_updated && $bookmark->recently_updated ) + $output .= get_option('links_recently_updated_append'); + + if ( $show_description && '' != $desc ) + $output .= $between . $desc; + + if ( $show_rating ) + $output .= $between . sanitize_bookmark_field('link_rating', $bookmark->link_rating, $bookmark->link_id, 'display'); + + $output .= "$after\n"; + } // end while + + return $output; +} + +/** + * Retrieve or echo all of the bookmarks. + * + * List of default arguments are as follows: + * 'orderby' - Default is 'name' (string). How to order the links by. String is + * based off of the bookmark scheme. + * 'order' - Default is 'ASC' (string). Either 'ASC' or 'DESC'. Orders in either + * ascending or descending order. + * 'limit' - Default is -1 (integer) or show all. The amount of bookmarks to + * display. + * 'category' - Default is empty string (string). Include the links in what + * category ID(s). + * 'category_name' - Default is empty string (string). Get links by category + * name. + * 'hide_invisible' - Default is 1 (integer). Whether to show (default) or hide + * links marked as 'invisible'. + * 'show_updated' - Default is 0 (integer). Will show the time of when the + * bookmark was last updated. + * 'echo' - Default is 1 (integer). Whether to echo (default) or return the + * formatted bookmarks. + * 'categorize' - Default is 1 (integer). Whether to show links listed by + * category (default) or show links in one column. + * + * These options define how the Category name will appear before the category + * links are displayed, if 'categorize' is 1. If 'categorize' is 0, then it will + * display for only the 'title_li' string and only if 'title_li' is not empty. + * 'title_li' - Default is 'Bookmarks' (translatable string). What to show + * before the links appear. + * 'title_before' - Default is '

    ' (string). The HTML or text to show before + * the 'title_li' string. + * 'title_after' - Default is '

    ' (string). The HTML or text to show after + * the 'title_li' string. + * 'class' - Default is 'linkcat' (string). The CSS class to use for the + * 'title_li'. + * + * 'category_before' - Default is '
  • '. String must + * contain '%id' and '%class' to get + * the id of the category and the 'class' argument. These are used for + * formatting in themes. + * Argument will be displayed before the 'title_before' argument. + * 'category_after' - Default is '
  • ' (string). The HTML or text that will + * appear after the list of links. + * + * These are only used if 'categorize' is set to 1 or true. + * 'category_orderby' - Default is 'name'. How to order the bookmark category + * based on term scheme. + * 'category_order' - Default is 'ASC'. Set the order by either ASC (ascending) + * or DESC (descending). + * + * @see _walk_bookmarks() For other arguments that can be set in this function + * and passed to _walk_bookmarks(). + * @see get_bookmarks() For other arguments that can be set in this function and + * passed to get_bookmarks(). + * @link http://codex.wordpress.org/Template_Tags/wp_list_bookmarks + * + * @since 2.1.0 + * @uses _list_bookmarks() Used to iterate over all of the bookmarks and return + * the html + * @uses get_terms() Gets all of the categories that are for links. + * + * @param string|array $args Optional. Overwrite the defaults of the function + * @return string|null Will only return if echo option is set to not echo. + * Default is not return anything. + */ +function wp_list_bookmarks($args = '') { + $defaults = array( + 'orderby' => 'name', 'order' => 'ASC', + 'limit' => -1, 'category' => '', 'exclude_category' => '', + 'category_name' => '', 'hide_invisible' => 1, + 'show_updated' => 0, 'echo' => 1, + 'categorize' => 1, 'title_li' => __('Bookmarks'), + 'title_before' => '

    ', 'title_after' => '

    ', + 'category_orderby' => 'name', 'category_order' => 'ASC', + 'class' => 'linkcat', 'category_before' => '
  • ', + 'category_after' => '
  • ' + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + $output = ''; + + if ( $categorize ) { + //Split the bookmarks into ul's for each category + $cats = get_terms('link_category', array('name__like' => $category_name, 'include' => $category, 'exclude' => $exclude_category, 'orderby' => $category_orderby, 'order' => $category_order, 'hierarchical' => 0)); + + foreach ( (array) $cats as $cat ) { + $params = array_merge($r, array('category'=>$cat->term_id)); + $bookmarks = get_bookmarks($params); + if ( empty($bookmarks) ) + continue; + $output .= str_replace(array('%id', '%class'), array("linkcat-$cat->term_id", $class), $category_before); + $catname = apply_filters( "link_category", $cat->name ); + $output .= "$title_before$catname$title_after\n\t
      \n"; + $output .= _walk_bookmarks($bookmarks, $r); + $output .= "\n\t
    \n$category_after\n"; + } + } else { + //output one single list using title_li for the title + $bookmarks = get_bookmarks($r); + + if ( !empty($bookmarks) ) { + if ( !empty( $title_li ) ){ + $output .= str_replace(array('%id', '%class'), array("linkcat-$category", $class), $category_before); + $output .= "$title_before$title_li$title_after\n\t
      \n"; + $output .= _walk_bookmarks($bookmarks, $r); + $output .= "\n\t
    \n$category_after\n"; + } else { + $output .= _walk_bookmarks($bookmarks, $r); + } + } + } + + $output = apply_filters( 'wp_list_bookmarks', $output ); + + if ( !$echo ) + return $output; + echo $output; +} + +?> diff --git a/wp-includes/bookmark.php b/wp-includes/bookmark.php new file mode 100644 index 0000000..81df5a7 --- /dev/null +++ b/wp-includes/bookmark.php @@ -0,0 +1,376 @@ +link_id, $bookmark, 'bookmark'); + $_bookmark = $bookmark; + } else { + if ( isset($GLOBALS['link']) && ($GLOBALS['link']->link_id == $bookmark) ) { + $_bookmark = & $GLOBALS['link']; + } elseif ( ! $_bookmark = wp_cache_get($bookmark, 'bookmark') ) { + $_bookmark = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark)); + $_bookmark->link_category = array_unique( wp_get_object_terms($_bookmark->link_id, 'link_category', 'fields=ids') ); + wp_cache_add($_bookmark->link_id, $_bookmark, 'bookmark'); + } + } + + $_bookmark = sanitize_bookmark($_bookmark, $filter); + + if ( $output == OBJECT ) { + return $_bookmark; + } elseif ( $output == ARRAY_A ) { + return get_object_vars($_bookmark); + } elseif ( $output == ARRAY_N ) { + return array_values(get_object_vars($_bookmark)); + } else { + return $_bookmark; + } +} + +/** + * Retrieve single bookmark data item or field. + * + * @since 2.3.0 + * @uses get_bookmark() Gets bookmark object using $bookmark as ID + * @uses sanitize_bookmark_field() Sanitizes Bookmark field based on $context. + * + * @param string $field The name of the data field to return + * @param int $bookmark The bookmark ID to get field + * @param string $context Optional. The context of how the field will be used. + * @return string + */ +function get_bookmark_field( $field, $bookmark, $context = 'display' ) { + $bookmark = (int) $bookmark; + $bookmark = get_bookmark( $bookmark ); + + if ( is_wp_error($bookmark) ) + return $bookmark; + + if ( !is_object($bookmark) ) + return ''; + + if ( !isset($bookmark->$field) ) + return ''; + + return sanitize_bookmark_field($field, $bookmark->$field, $bookmark->link_id, $context); +} + +/** + * Retrieve bookmark data based on ID. + * + * @since 2.0.0 + * @deprecated Use get_bookmark() + * @see get_bookmark() + * + * @param int $bookmark_id ID of link + * @param string $output Either OBJECT, ARRAY_N, or ARRAY_A + * @return object|array + */ +function get_link($bookmark_id, $output = OBJECT, $filter = 'raw') { + return get_bookmark($bookmark_id, $output, $filter); +} + +/** + * Retrieves the list of bookmarks + * + * Attempts to retrieve from the cache first based on MD5 hash of arguments. If + * that fails, then the query will be built from the arguments and executed. The + * results will be stored to the cache. + * + * List of default arguments are as follows: + * 'orderby' - Default is 'name' (string). How to order the links by. String is + * based off of the bookmark scheme. + * 'order' - Default is 'ASC' (string). Either 'ASC' or 'DESC'. Orders in either + * ascending or descending order. + * 'limit' - Default is -1 (integer) or show all. The amount of bookmarks to + * display. + * 'category' - Default is empty string (string). Include the links in what + * category ID(s). + * 'category_name' - Default is empty string (string). Get links by category + * name. + * 'hide_invisible' - Default is 1 (integer). Whether to show (default) or hide + * links marked as 'invisible'. + * 'show_updated' - Default is 0 (integer). Will show the time of when the + * bookmark was last updated. + * 'include' - Default is empty string (string). Include other categories + * separated by commas. + * 'exclude' - Default is empty string (string). Exclude other categories + * separated by commas. + * + * @since 2.1.0 + * @uses $wpdb Database Object + * @link http://codex.wordpress.org/Template_Tags/get_bookmarks + * + * @param string|array $args List of arguments to overwrite the defaults + * @return array List of bookmark row objects + */ +function get_bookmarks($args = '') { + global $wpdb; + + $defaults = array( + 'orderby' => 'name', 'order' => 'ASC', + 'limit' => -1, 'category' => '', + 'category_name' => '', 'hide_invisible' => 1, + 'show_updated' => 0, 'include' => '', + 'exclude' => '', 'search' => '' + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + $cache = array(); + $key = md5( serialize( $r ) ); + if ( $cache = wp_cache_get( 'get_bookmarks', 'bookmark' ) ) { + if ( is_array($cache) && isset( $cache[ $key ] ) ) + return apply_filters('get_bookmarks', $cache[ $key ], $r ); + } + + if ( !is_array($cache) ) + $cache = array(); + + $inclusions = ''; + if ( !empty($include) ) { + $exclude = ''; //ignore exclude, category, and category_name params if using include + $category = ''; + $category_name = ''; + $inclinks = preg_split('/[\s,]+/',$include); + if ( count($inclinks) ) { + foreach ( $inclinks as $inclink ) { + if (empty($inclusions)) + $inclusions = ' AND ( link_id = ' . intval($inclink) . ' '; + else + $inclusions .= ' OR link_id = ' . intval($inclink) . ' '; + } + } + } + if (!empty($inclusions)) + $inclusions .= ')'; + + $exclusions = ''; + if ( !empty($exclude) ) { + $exlinks = preg_split('/[\s,]+/',$exclude); + if ( count($exlinks) ) { + foreach ( $exlinks as $exlink ) { + if (empty($exclusions)) + $exclusions = ' AND ( link_id <> ' . intval($exlink) . ' '; + else + $exclusions .= ' AND link_id <> ' . intval($exlink) . ' '; + } + } + } + if (!empty($exclusions)) + $exclusions .= ')'; + + if ( !empty($category_name) ) { + if ( $category = get_term_by('name', $category_name, 'link_category') ) { + $category = $category->term_id; + } else { + $cache[ $key ] = array(); + wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); + return apply_filters( 'get_bookmarks', array(), $r ); + } + } + + if ( ! empty($search) ) { + $search = like_escape($search); + $search = " AND ( (link_url LIKE '%$search%') OR (link_name LIKE '%$search%') OR (link_description LIKE '%$search%') ) "; + } + + $category_query = ''; + $join = ''; + if ( !empty($category) ) { + $incategories = preg_split('/[\s,]+/',$category); + if ( count($incategories) ) { + foreach ( $incategories as $incat ) { + if (empty($category_query)) + $category_query = ' AND ( tt.term_id = ' . intval($incat) . ' '; + else + $category_query .= ' OR tt.term_id = ' . intval($incat) . ' '; + } + } + } + if (!empty($category_query)) { + $category_query .= ") AND taxonomy = 'link_category'"; + $join = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id"; + } + + if (get_option('links_recently_updated_time')) { + $recently_updated_test = ", IF (DATE_ADD(link_updated, INTERVAL " . get_option('links_recently_updated_time') . " MINUTE) >= NOW(), 1,0) as recently_updated "; + } else { + $recently_updated_test = ''; + } + + $get_updated = ( $show_updated ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : ''; + + $orderby = strtolower($orderby); + $length = ''; + switch ($orderby) { + case 'length': + $length = ", CHAR_LENGTH(link_name) AS length"; + break; + case 'rand': + $orderby = 'rand()'; + break; + default: + $orderby = "link_" . $orderby; + } + + if ( 'link_id' == $orderby ) + $orderby = "$wpdb->links.link_id"; + + $visible = ''; + if ( $hide_invisible ) + $visible = "AND link_visible = 'Y'"; + + $query = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query"; + $query .= " $exclusions $inclusions $search"; + $query .= " ORDER BY $orderby $order"; + if ($limit != -1) + $query .= " LIMIT $limit"; + + $results = $wpdb->get_results($query); + + $cache[ $key ] = $results; + wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); + + return apply_filters('get_bookmarks', $results, $r); +} + +/** + * Sanitizes all bookmark fields + * + * @since 2.3.0 + * + * @param object|array $bookmark Bookmark row + * @param string $context Optional, default is 'display'. How to filter the + * fields + * @return object|array Same type as $bookmark but with fields sanitized. + */ +function sanitize_bookmark($bookmark, $context = 'display') { + $fields = array('link_id', 'link_url', 'link_name', 'link_image', 'link_target', 'link_category', + 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_updated', + 'link_rel', 'link_notes', 'link_rss', ); + + if ( is_object($bookmark) ) { + $do_object = true; + $link_id = $bookmark->link_id; + } else { + $do_object = false; + $link_id = $bookmark['link_id']; + } + + foreach ( $fields as $field ) { + if ( $do_object ) { + if ( isset($bookmark->$field) ) + $bookmark->$field = sanitize_bookmark_field($field, $bookmark->$field, $link_id, $context); + } else { + if ( isset($bookmark[$field]) ) + $bookmark[$field] = sanitize_bookmark_field($field, $bookmark[$field], $link_id, $context); + } + } + + return $bookmark; +} + +/** + * Sanitizes a bookmark field + * + * Sanitizes the bookmark fields based on what the field name is. If the field + * has a strict value set, then it will be tested for that, else a more generic + * filtering is applied. After the more strict filter is applied, if the + * $context is 'raw' then the value is immediately return. + * + * Hooks exist for the more generic cases. With the 'edit' context, the + * 'edit_$field' filter will be called and passed the $value and $bookmark_id + * respectively. With the 'db' context, the 'pre_$field' filter is called and + * passed the value. The 'display' context is the final context and has the + * $field has the filter name and is passed the $value, $bookmark_id, and + * $context respectively. + * + * @since 2.3.0 + * + * @param string $field The bookmark field + * @param mixed $value The bookmark field value + * @param int $bookmark_id Bookmark ID + * @param string $context How to filter the field value. Either 'raw', 'edit', + * 'attribute', 'js', 'db', or 'display' + * @return mixed The filtered value + */ +function sanitize_bookmark_field($field, $value, $bookmark_id, $context) { + $int_fields = array('link_id', 'link_rating'); + if ( in_array($field, $int_fields) ) + $value = (int) $value; + + $yesno = array('link_visible'); + if ( in_array($field, $yesno) ) + $value = preg_replace('/[^YNyn]/', '', $value); + + if ( 'link_target' == $field ) { + $targets = array('_top', '_blank'); + if ( ! in_array($value, $targets) ) + $value = ''; + } + + if ( 'raw' == $context ) + return $value; + + if ( 'edit' == $context ) { + $format_to_edit = array('link_notes'); + $value = apply_filters("edit_$field", $value, $bookmark_id); + + if ( in_array($field, $format_to_edit) ) { + $value = format_to_edit($value); + } else { + $value = esc_attr($value); + } + } else if ( 'db' == $context ) { + $value = apply_filters("pre_$field", $value); + } else { + // Use display filters by default. + $value = apply_filters($field, $value, $bookmark_id, $context); + } + + if ( 'attribute' == $context ) + $value = esc_attr($value); + else if ( 'js' == $context ) + $value = esc_js($value); + + return $value; +} + +/** + * Deletes bookmark cache + * + * @since 2.7.0 + * @uses wp_cache_delete() Deletes the contents of 'get_bookmarks' + */ +function clean_bookmark_cache($bookmark_id) { + wp_cache_delete( $bookmark_id, 'bookmark' ); + wp_cache_delete( 'get_bookmarks', 'bookmark' ); +} + +?> diff --git a/wp-includes/cache.php b/wp-includes/cache.php new file mode 100644 index 0000000..5eef60b --- /dev/null +++ b/wp-includes/cache.php @@ -0,0 +1,452 @@ +add($key, $data, $flag, $expire); +} + +/** + * Closes the cache. + * + * This function has ceased to do anything since WordPress 2.5. The + * functionality was removed along with the rest of the persistant cache. This + * does not mean that plugins can't implement this function when they need to + * make sure that the cache is cleaned up after WordPress no longer needs it. + * + * @since 2.0.0 + * + * @return bool Always returns True + */ +function wp_cache_close() { + return true; +} + +/** + * Removes the cache contents matching ID and flag. + * + * @since 2.0.0 + * @uses $wp_object_cache Object Cache Class + * @see WP_Object_Cache::delete() + * + * @param int|string $id What the contents in the cache are called + * @param string $flag Where the cache contents are grouped + * @return bool True on successful removal, false on failure + */ +function wp_cache_delete($id, $flag = '') { + global $wp_object_cache; + + return $wp_object_cache->delete($id, $flag); +} + +/** + * Removes all cache items. + * + * @since 2.0.0 + * @uses $wp_object_cache Object Cache Class + * @see WP_Object_Cache::flush() + * + * @return bool Always returns true + */ +function wp_cache_flush() { + global $wp_object_cache; + + return $wp_object_cache->flush(); +} + +/** + * Retrieves the cache contents from the cache by ID and flag. + * + * @since 2.0.0 + * @uses $wp_object_cache Object Cache Class + * @see WP_Object_Cache::get() + * + * @param int|string $id What the contents in the cache are called + * @param string $flag Where the cache contents are grouped + * @return bool|mixed False on failure to retrieve contents or the cache + * contents on success + */ +function wp_cache_get($id, $flag = '') { + global $wp_object_cache; + + return $wp_object_cache->get($id, $flag); +} + +/** + * Sets up Object Cache Global and assigns it. + * + * @since 2.0.0 + * @global WP_Object_Cache $wp_object_cache WordPress Object Cache + */ +function wp_cache_init() { + $GLOBALS['wp_object_cache'] =& new WP_Object_Cache(); +} + +/** + * Replaces the contents of the cache with new data. + * + * @since 2.0.0 + * @uses $wp_object_cache Object Cache Class + * @see WP_Object_Cache::replace() + * + * @param int|string $id What to call the contents in the cache + * @param mixed $data The contents to store in the cache + * @param string $flag Where to group the cache contents + * @param int $expire When to expire the cache contents + * @return bool False if cache ID and group already exists, true on success + */ +function wp_cache_replace($key, $data, $flag = '', $expire = 0) { + global $wp_object_cache; + + return $wp_object_cache->replace($key, $data, $flag, $expire); +} + +/** + * Saves the data to the cache. + * + * @since 2.0 + * @uses $wp_object_cache Object Cache Class + * @see WP_Object_Cache::set() + * + * @param int|string $id What to call the contents in the cache + * @param mixed $data The contents to store in the cache + * @param string $flag Where to group the cache contents + * @param int $expire When to expire the cache contents + * @return bool False if cache ID and group already exists, true on success + */ +function wp_cache_set($key, $data, $flag = '', $expire = 0) { + global $wp_object_cache; + + return $wp_object_cache->set($key, $data, $flag, $expire); +} + +/** + * Adds a group or set of groups to the list of global groups. + * + * @since 2.6.0 + * + * @param string|array $groups A group or an array of groups to add + */ +function wp_cache_add_global_groups( $groups ) { + // Default cache doesn't persist so nothing to do here. + return; +} + +/** + * Adds a group or set of groups to the list of non-persistent groups. + * + * @since 2.6.0 + * + * @param string|array $groups A group or an array of groups to add + */ +function wp_cache_add_non_persistent_groups( $groups ) { + // Default cache doesn't persist so nothing to do here. + return; +} + +/** + * WordPress Object Cache + * + * The WordPress Object Cache is used to save on trips to the database. The + * Object Cache stores all of the cache data to memory and makes the cache + * contents available by using a key, which is used to name and later retrieve + * the cache contents. + * + * The Object Cache can be replaced by other caching mechanisms by placing files + * in the wp-content folder which is looked at in wp-settings. If that file + * exists, then this file will not be included. + * + * @package WordPress + * @subpackage Cache + * @since 2.0 + */ +class WP_Object_Cache { + + /** + * Holds the cached objects + * + * @var array + * @access private + * @since 2.0.0 + */ + var $cache = array (); + + /** + * Cache objects that do not exist in the cache + * + * @var array + * @access private + * @since 2.0.0 + */ + var $non_existant_objects = array (); + + /** + * The amount of times the cache data was already stored in the cache. + * + * @since 2.5.0 + * @access private + * @var int + */ + var $cache_hits = 0; + + /** + * Amount of times the cache did not have the request in cache + * + * @var int + * @access public + * @since 2.0.0 + */ + var $cache_misses = 0; + + /** + * Adds data to the cache if it doesn't already exist. + * + * @uses WP_Object_Cache::get Checks to see if the cache already has data. + * @uses WP_Object_Cache::set Sets the data after the checking the cache + * contents existance. + * + * @since 2.0.0 + * + * @param int|string $id What to call the contents in the cache + * @param mixed $data The contents to store in the cache + * @param string $group Where to group the cache contents + * @param int $expire When to expire the cache contents + * @return bool False if cache ID and group already exists, true on success + */ + function add($id, $data, $group = 'default', $expire = '') { + if (empty ($group)) + $group = 'default'; + + if (false !== $this->get($id, $group, false)) + return false; + + return $this->set($id, $data, $group, $expire); + } + + /** + * Remove the contents of the cache ID in the group + * + * If the cache ID does not exist in the group and $force parameter is set + * to false, then nothing will happen. The $force parameter is set to false + * by default. + * + * On success the group and the id will be added to the + * $non_existant_objects property in the class. + * + * @since 2.0.0 + * + * @param int|string $id What the contents in the cache are called + * @param string $group Where the cache contents are grouped + * @param bool $force Optional. Whether to force the unsetting of the cache + * ID in the group + * @return bool False if the contents weren't deleted and true on success + */ + function delete($id, $group = 'default', $force = false) { + if (empty ($group)) + $group = 'default'; + + if (!$force && false === $this->get($id, $group, false)) + return false; + + unset ($this->cache[$group][$id]); + $this->non_existant_objects[$group][$id] = true; + return true; + } + + /** + * Clears the object cache of all data + * + * @since 2.0.0 + * + * @return bool Always returns true + */ + function flush() { + $this->cache = array (); + + return true; + } + + /** + * Retrieves the cache contents, if it exists + * + * The contents will be first attempted to be retrieved by searching by the + * ID in the cache group. If the cache is hit (success) then the contents + * are returned. + * + * On failure, the $non_existant_objects property is checked and if the + * cache group and ID exist in there the cache misses will not be + * incremented. If not in the nonexistant objects property, then the cache + * misses will be incremented and the cache group and ID will be added to + * the nonexistant objects. + * + * @since 2.0.0 + * + * @param int|string $id What the contents in the cache are called + * @param string $group Where the cache contents are grouped + * @return bool|mixed False on failure to retrieve contents or the cache + * contents on success + */ + function get($id, $group = 'default') { + if (empty ($group)) + $group = 'default'; + + if (isset ($this->cache[$group][$id])) { + $this->cache_hits += 1; + if ( is_object($this->cache[$group][$id]) ) + return wp_clone($this->cache[$group][$id]); + else + return $this->cache[$group][$id]; + } + + if ( isset ($this->non_existant_objects[$group][$id]) ) + return false; + + $this->non_existant_objects[$group][$id] = true; + $this->cache_misses += 1; + return false; + } + + /** + * Replace the contents in the cache, if contents already exist + * + * @since 2.0.0 + * @see WP_Object_Cache::set() + * + * @param int|string $id What to call the contents in the cache + * @param mixed $data The contents to store in the cache + * @param string $group Where to group the cache contents + * @param int $expire When to expire the cache contents + * @return bool False if not exists, true if contents were replaced + */ + function replace($id, $data, $group = 'default', $expire = '') { + if (empty ($group)) + $group = 'default'; + + if (false === $this->get($id, $group, false)) + return false; + + return $this->set($id, $data, $group, $expire); + } + + /** + * Sets the data contents into the cache + * + * The cache contents is grouped by the $group parameter followed by the + * $id. This allows for duplicate ids in unique groups. Therefore, naming of + * the group should be used with care and should follow normal function + * naming guidelines outside of core WordPress usage. + * + * The $expire parameter is not used, because the cache will automatically + * expire for each time a page is accessed and PHP finishes. The method is + * more for cache plugins which use files. + * + * @since 2.0.0 + * + * @param int|string $id What to call the contents in the cache + * @param mixed $data The contents to store in the cache + * @param string $group Where to group the cache contents + * @param int $expire Not Used + * @return bool Always returns true + */ + function set($id, $data, $group = 'default', $expire = '') { + if (empty ($group)) + $group = 'default'; + + if (NULL === $data) + $data = ''; + + if ( is_object($data) ) + $data = wp_clone($data); + + $this->cache[$group][$id] = $data; + + if(isset($this->non_existant_objects[$group][$id])) + unset ($this->non_existant_objects[$group][$id]); + + return true; + } + + /** + * Echos the stats of the caching. + * + * Gives the cache hits, and cache misses. Also prints every cached group, + * key and the data. + * + * @since 2.0.0 + */ + function stats() { + echo "

    "; + echo "Cache Hits: {$this->cache_hits}
    "; + echo "Cache Misses: {$this->cache_misses}
    "; + echo "

    "; + + foreach ($this->cache as $group => $cache) { + echo "

    "; + echo "Group: $group
    "; + echo "Cache:"; + echo "

    ";
    +			print_r($cache);
    +			echo "
    "; + } + } + + /** + * PHP4 constructor; Calls PHP 5 style constructor + * + * @since 2.0.0 + * + * @return WP_Object_Cache + */ + function WP_Object_Cache() { + return $this->__construct(); + } + + /** + * Sets up object properties; PHP 5 style constructor + * + * @since 2.0.8 + * @return null|WP_Object_Cache If cache is disabled, returns null. + */ + function __construct() { + /** + * @todo This should be moved to the PHP4 style constructor, PHP5 + * already calls __destruct() + */ + register_shutdown_function(array(&$this, "__destruct")); + } + + /** + * Will save the object cache before object is completely destroyed. + * + * Called upon object destruction, which should be when PHP ends. + * + * @since 2.0.8 + * + * @return bool True value. Won't be used by PHP + */ + function __destruct() { + return true; + } +} +?> diff --git a/wp-includes/canonical.php b/wp-includes/canonical.php new file mode 100644 index 0000000..c17e2f1 --- /dev/null +++ b/wp-includes/canonical.php @@ -0,0 +1,339 @@ + $wp_query->post_count && ($id = get_query_var('p')) ) { + + $vars = $wpdb->get_results( $wpdb->prepare("SELECT post_type, post_parent FROM $wpdb->posts WHERE ID = %d", $id) ); + + if ( isset($vars[0]) && $vars = $vars[0] ) { + if ( 'revision' == $vars->post_type && $vars->post_parent > 0 ) + $id = $vars->post_parent; + + if ( $redirect_url = get_permalink($id) ) + $redirect['query'] = remove_query_arg(array('p', 'page_id', 'attachment_id'), $redirect['query']); + } + } + + // These tests give us a WP-generated permalink + if ( is_404() ) { + $redirect_url = redirect_guess_404_permalink(); + } elseif ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) { + // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101 + if ( is_single() && !empty($_GET['p']) && ! $redirect_url ) { + if ( $redirect_url = get_permalink(get_query_var('p')) ) + $redirect['query'] = remove_query_arg('p', $redirect['query']); + if ( get_query_var( 'page' ) ) { + $redirect_url = trailingslashit( $redirect_url ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' ); + $redirect['query'] = remove_query_arg( 'page', $redirect['query'] ); + } + } elseif ( is_page() && !empty($_GET['page_id']) && ! $redirect_url ) { + if ( $redirect_url = get_permalink(get_query_var('page_id')) ) + $redirect['query'] = remove_query_arg('page_id', $redirect['query']); + } elseif ( !empty($_GET['m']) && ( is_year() || is_month() || is_day() ) ) { + $m = get_query_var('m'); + switch ( strlen($m) ) { + case 4: // Yearly + $redirect_url = get_year_link($m); + break; + case 6: // Monthly + $redirect_url = get_month_link( substr($m, 0, 4), substr($m, 4, 2) ); + break; + case 8: // Daily + $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2)); + break; + } + if ( $redirect_url ) + $redirect['query'] = remove_query_arg('m', $redirect['query']); + // now moving on to non ?m=X year/month/day links + } elseif ( is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day']) ) { + if ( $redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day')) ) + $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']); + } elseif ( is_month() && get_query_var('year') && !empty($_GET['monthnum']) ) { + if ( $redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum')) ) + $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']); + } elseif ( is_year() && !empty($_GET['year']) ) { + if ( $redirect_url = get_year_link(get_query_var('year')) ) + $redirect['query'] = remove_query_arg('year', $redirect['query']); + } elseif ( is_category() && !empty($_GET['cat']) && preg_match( '|^[0-9]+$|', $_GET['cat'] ) ) { + if ( $redirect_url = get_category_link(get_query_var('cat')) ) + $redirect['query'] = remove_query_arg('cat', $redirect['query']); + } elseif ( is_author() && !empty($_GET['author']) ) { + $author = get_userdata(get_query_var('author')); + if ( false !== $author && $redirect_url = get_author_posts_url($author->ID, $author->user_nicename) ) + $redirect['query'] = remove_query_arg('author', $redirect['author']); + } + + // paging and feeds + if ( get_query_var('paged') || is_feed() || get_query_var('cpage') ) { + if ( !$redirect_url ) + $redirect_url = $requested_url; + $paged_redirect = @parse_url($redirect_url); + while ( preg_match( '#/page/[0-9]+?(/+)?$#', $paged_redirect['path'] ) || preg_match( '#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $paged_redirect['path'] ) || preg_match( '#/comment-page-[0-9]+(/+)?$#', $paged_redirect['path'] ) ) { + // Strip off paging and feed + $paged_redirect['path'] = preg_replace('#/page/[0-9]+?(/+)?$#', '/', $paged_redirect['path']); // strip off any existing paging + $paged_redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $paged_redirect['path']); // strip off feed endings + $paged_redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $paged_redirect['path']); // strip off any existing comment paging + } + + $addl_path = ''; + if ( is_feed() ) { + $addl_path = !empty( $addl_path ) ? trailingslashit($addl_path) : ''; + if ( get_query_var( 'withcomments' ) ) + $addl_path .= 'comments/'; + $addl_path .= user_trailingslashit( 'feed/' . ( ( 'rss2' == get_query_var('feed') || 'feed' == get_query_var('feed') ) ? '' : get_query_var('feed') ), 'feed' ); + $redirect['query'] = remove_query_arg( 'feed', $redirect['query'] ); + } + + if ( get_query_var('paged') > 0 ) { + $paged = get_query_var('paged'); + $redirect['query'] = remove_query_arg( 'paged', $redirect['query'] ); + if ( !is_feed() ) { + if ( $paged > 1 && !is_single() ) { + $addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit("page/$paged", 'paged'); + } elseif ( !is_single() ) { + $addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit($paged_redirect['path'], 'paged'); + } + } elseif ( $paged > 1 ) { + $redirect['query'] = add_query_arg( 'paged', $paged, $redirect['query'] ); + } + } + + if ( get_option('page_comments') && ( ( 'newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 ) || ( 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1 ) ) ) { + $addl_path = ( !empty( $addl_path ) ? trailingslashit($addl_path) : '' ) . user_trailingslashit( 'comment-page-' . get_query_var('cpage'), 'commentpaged' ); + $redirect['query'] = remove_query_arg( 'cpage', $redirect['query'] ); + } + + $paged_redirect['path'] = user_trailingslashit( preg_replace('|/index.php/?$|', '/', $paged_redirect['path']) ); // strip off trailing /index.php/ + if ( !empty( $addl_path ) && $wp_rewrite->using_index_permalinks() && strpos($paged_redirect['path'], '/index.php/') === false ) + $paged_redirect['path'] = trailingslashit($paged_redirect['path']) . 'index.php/'; + if ( !empty( $addl_path ) ) + $paged_redirect['path'] = trailingslashit($paged_redirect['path']) . $addl_path; + $redirect_url = $paged_redirect['scheme'] . '://' . $paged_redirect['host'] . $paged_redirect['path']; + $redirect['path'] = $paged_redirect['path']; + } + } + + // tack on any additional query vars + $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] ); + if ( $redirect_url && !empty($redirect['query']) ) { + if ( strpos($redirect_url, '?') !== false ) + $redirect_url .= '&'; + else + $redirect_url .= '?'; + $redirect_url .= $redirect['query']; + } + + if ( $redirect_url ) + $redirect = @parse_url($redirect_url); + + // www.example.com vs example.com + $user_home = @parse_url(get_option('home')); + if ( !empty($user_home['host']) ) + $redirect['host'] = $user_home['host']; + if ( empty($user_home['path']) ) + $user_home['path'] = '/'; + + // Handle ports + if ( !empty($user_home['port']) ) + $redirect['port'] = $user_home['port']; + else + unset($redirect['port']); + + // trailing /index.php + $redirect['path'] = preg_replace('|/index.php/*?$|', '/', $redirect['path']); + + // Remove trailing spaces from the path + $redirect['path'] = preg_replace( '#(%20| )+$#', '', $redirect['path'] ); + + if ( !empty( $redirect['query'] ) ) { + // Remove trailing spaces from certain terminating query string args + $redirect['query'] = preg_replace( '#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query'] ); + + // Clean up empty query strings + $redirect['query'] = trim(preg_replace( '#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&'); + + // Remove redundant leading ampersands + $redirect['query'] = preg_replace( '#^\??&*?#', '', $redirect['query'] ); + } + + // strip /index.php/ when we're not using PATHINFO permalinks + if ( !$wp_rewrite->using_index_permalinks() ) + $redirect['path'] = str_replace('/index.php/', '/', $redirect['path']); + + // trailing slashes + if ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || ( is_front_page() && (get_query_var('paged') > 1) ) ) ) { + $user_ts_type = ''; + if ( get_query_var('paged') > 0 ) { + $user_ts_type = 'paged'; + } else { + foreach ( array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type ) { + $func = 'is_' . $type; + if ( call_user_func($func) ) { + $user_ts_type = $type; + break; + } + } + } + $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type); + } elseif ( is_front_page() ) { + $redirect['path'] = trailingslashit($redirect['path']); + } + + // Always trailing slash the Front Page URL + if ( trailingslashit( $redirect['path'] ) == trailingslashit( $user_home['path'] ) ) + $redirect['path'] = trailingslashit($redirect['path']); + + // Ignore differences in host capitalization, as this can lead to infinite redirects + // Only redirect no-www <=> yes-www + if ( strtolower($original['host']) == strtolower($redirect['host']) || + ( strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host']) ) ) + $redirect['host'] = $original['host']; + + $compare_original = array($original['host'], $original['path']); + + if ( !empty( $original['port'] ) ) + $compare_original[] = $original['port']; + + if ( !empty( $original['query'] ) ) + $compare_original[] = $original['query']; + + $compare_redirect = array($redirect['host'], $redirect['path']); + + if ( !empty( $redirect['port'] ) ) + $compare_redirect[] = $redirect['port']; + + if ( !empty( $redirect['query'] ) ) + $compare_redirect[] = $redirect['query']; + + if ( $compare_original !== $compare_redirect ) { + $redirect_url = $redirect['scheme'] . '://' . $redirect['host']; + if ( !empty($redirect['port']) ) + $redirect_url .= ':' . $redirect['port']; + $redirect_url .= $redirect['path']; + if ( !empty($redirect['query']) ) + $redirect_url .= '?' . $redirect['query']; + } + + if ( $redirect_url == $requested_url ) + return false; + + // Note that you can use the "redirect_canonical" filter to cancel a canonical redirect for whatever reason by returning FALSE + $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url); + + if ( !$redirect_url || $redirect_url == $requested_url ) // yes, again -- in case the filter aborted the request + return false; + + if ( $do_redirect ) { + // protect against chained redirects + if ( !redirect_canonical($redirect_url, false) ) { + wp_redirect($redirect_url, 301); + exit(); + } else { + // Debug + // die("1: $redirect_url
    2: " . redirect_canonical( $redirect_url, false ) ); + return false; + } + } else { + return $redirect_url; + } +} + +/** + * Attempts to guess correct post based on query vars. + * + * @since 2.3.0 + * @uses $wpdb + * + * @return bool|string Returns False, if it can't find post, returns correct + * location on success. + */ +function redirect_guess_404_permalink() { + global $wpdb; + + if ( !get_query_var('name') ) + return false; + + $where = $wpdb->prepare("post_name LIKE %s", get_query_var('name') . '%'); + + // if any of year, monthnum, or day are set, use them to refine the query + if ( get_query_var('year') ) + $where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year')); + if ( get_query_var('monthnum') ) + $where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum')); + if ( get_query_var('day') ) + $where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day')); + + $post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'"); + if ( !$post_id ) + return false; + return get_permalink($post_id); +} + +add_action('template_redirect', 'redirect_canonical'); + +?> diff --git a/wp-includes/capabilities.php b/wp-includes/capabilities.php new file mode 100644 index 0000000..cccd68d --- /dev/null +++ b/wp-includes/capabilities.php @@ -0,0 +1,987 @@ + + * array ( + * 'rolename' => array ( + * 'name' => 'rolename', + * 'capabilities' => array() + * ) + * ) + * + * + * @since 2.0.0 + * @package WordPress + * @subpackage User + */ +class WP_Roles { + /** + * List of roles and capabilities. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $roles; + + /** + * List of the role objects. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $role_objects = array(); + + /** + * List of role names. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $role_names = array(); + + /** + * Option name for storing role list. + * + * @since 2.0.0 + * @access public + * @var string + */ + var $role_key; + + /** + * Whether to use the database for retrieval and storage. + * + * @since 2.1.0 + * @access public + * @var bool + */ + var $use_db = true; + + /** + * PHP4 Constructor - Call {@link WP_Roles::_init()} method. + * + * @since 2.0.0 + * @access public + * + * @return WP_Roles + */ + function WP_Roles() { + $this->_init(); + } + + /** + * Setup the object properties. + * + * The role key is set to the current prefix for the $wpdb object with + * 'user_roles' appended. If the $wp_user_roles global is set, then it will + * be used and the role option will not be updated or used. + * + * @since 2.1.0 + * @access protected + * @uses $wpdb Used to get the database prefix. + * @global array $wp_user_roles Used to set the 'roles' property value. + */ + function _init () { + global $wpdb; + global $wp_user_roles; + $this->role_key = $wpdb->prefix . 'user_roles'; + if ( ! empty( $wp_user_roles ) ) { + $this->roles = $wp_user_roles; + $this->use_db = false; + } else { + $this->roles = get_option( $this->role_key ); + } + + if ( empty( $this->roles ) ) + return; + + $this->role_objects = array(); + $this->role_names = array(); + foreach ( (array) $this->roles as $role => $data ) { + $this->role_objects[$role] = new WP_Role( $role, $this->roles[$role]['capabilities'] ); + $this->role_names[$role] = $this->roles[$role]['name']; + } + } + + /** + * Add role name with capabilities to list. + * + * Updates the list of roles, if the role doesn't already exist. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + * @param string $display_name Role display name. + * @param array $capabilities List of role capabilities. + * @return null|WP_Role WP_Role object if role is added, null if already exists. + */ + function add_role( $role, $display_name, $capabilities = array() ) { + if ( isset( $this->roles[$role] ) ) + return; + + $this->roles[$role] = array( + 'name' => $display_name, + 'capabilities' => $capabilities + ); + if ( $this->use_db ) + update_option( $this->role_key, $this->roles ); + $this->role_objects[$role] = new WP_Role( $role, $capabilities ); + $this->role_names[$role] = $display_name; + return $this->role_objects[$role]; + } + + /** + * Remove role by name. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + */ + function remove_role( $role ) { + if ( ! isset( $this->role_objects[$role] ) ) + return; + + unset( $this->role_objects[$role] ); + unset( $this->role_names[$role] ); + unset( $this->roles[$role] ); + + if ( $this->use_db ) + update_option( $this->role_key, $this->roles ); + } + + /** + * Add capability to role. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + * @param string $cap Capability name. + * @param bool $grant Optional, default is true. Whether role is capable of preforming capability. + */ + function add_cap( $role, $cap, $grant = true ) { + $this->roles[$role]['capabilities'][$cap] = $grant; + if ( $this->use_db ) + update_option( $this->role_key, $this->roles ); + } + + /** + * Remove capability from role. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + * @param string $cap Capability name. + */ + function remove_cap( $role, $cap ) { + unset( $this->roles[$role]['capabilities'][$cap] ); + if ( $this->use_db ) + update_option( $this->role_key, $this->roles ); + } + + /** + * Retrieve role object by name. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + * @return object|null Null, if role does not exist. WP_Role object, if found. + */ + function &get_role( $role ) { + if ( isset( $this->role_objects[$role] ) ) + return $this->role_objects[$role]; + else + return null; + } + + /** + * Retrieve list of role names. + * + * @since 2.0.0 + * @access public + * + * @return array List of role names. + */ + function get_names() { + return $this->role_names; + } + + /** + * Whether role name is currently in the list of available roles. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name to look up. + * @return bool + */ + function is_role( $role ) + { + return isset( $this->role_names[$role] ); + } +} + +/** + * WordPress Role class. + * + * @since 2.0.0 + * @package WordPress + * @subpackage User + */ +class WP_Role { + /** + * Role name. + * + * @since 2.0.0 + * @access public + * @var string + */ + var $name; + + /** + * List of capabilities the role contains. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $capabilities; + + /** + * PHP4 Constructor - Setup object properties. + * + * The list of capabilities, must have the key as the name of the capability + * and the value a boolean of whether it is granted to the role or not. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + * @param array $capabilities List of capabilities. + * @return WP_Role + */ + function WP_Role( $role, $capabilities ) { + $this->name = $role; + $this->capabilities = $capabilities; + } + + /** + * Assign role a capability. + * + * @see WP_Roles::add_cap() Method uses implementation for role. + * @since 2.0.0 + * @access public + * + * @param string $cap Capability name. + * @param bool $grant Whether role has capability privilege. + */ + function add_cap( $cap, $grant = true ) { + global $wp_roles; + + if ( ! isset( $wp_roles ) ) + $wp_roles = new WP_Roles(); + + $this->capabilities[$cap] = $grant; + $wp_roles->add_cap( $this->name, $cap, $grant ); + } + + /** + * Remove capability from role. + * + * This is a container for {@link WP_Roles::remove_cap()} to remove the + * capability from the role. That is to say, that {@link + * WP_Roles::remove_cap()} implements the functionality, but it also makes + * sense to use this class, because you don't need to enter the role name. + * + * @since 2.0.0 + * @access public + * + * @param string $cap Capability name. + */ + function remove_cap( $cap ) { + global $wp_roles; + + if ( ! isset( $wp_roles ) ) + $wp_roles = new WP_Roles(); + + unset( $this->capabilities[$cap] ); + $wp_roles->remove_cap( $this->name, $cap ); + } + + /** + * Whether role has capability. + * + * The capabilities is passed through the 'role_has_cap' filter. The first + * parameter for the hook is the list of capabilities the class has + * assigned. The second parameter is the capability name to look for. The + * third and final parameter for the hook is the role name. + * + * @since 2.0.0 + * @access public + * + * @param string $cap Capability name. + * @return bool True, if user has capability. False, if doesn't have capability. + */ + function has_cap( $cap ) { + $capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name ); + if ( !empty( $capabilities[$cap] ) ) + return $capabilities[$cap]; + else + return false; + } + +} + +/** + * WordPress User class. + * + * @since 2.0.0 + * @package WordPress + * @subpackage User + */ +class WP_User { + /** + * User data container. + * + * This will be set as properties of the object. + * + * @since 2.0.0 + * @access private + * @var array + */ + var $data; + + /** + * The user's ID. + * + * @since 2.1.0 + * @access public + * @var int + */ + var $ID = 0; + + /** + * The deprecated user's ID. + * + * @since 2.0.0 + * @access public + * @deprecated Use WP_User::$ID + * @see WP_User::$ID + * @var int + */ + var $id = 0; + + /** + * The individual capabilities the user has been given. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $caps = array(); + + /** + * User metadata option name. + * + * @since 2.0.0 + * @access public + * @var string + */ + var $cap_key; + + /** + * The roles the user is part of. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $roles = array(); + + /** + * All capabilities the user has, including individual and role based. + * + * @since 2.0.0 + * @access public + * @var array + */ + var $allcaps = array(); + + /** + * First name of the user. + * + * Created to prevent notices. + * + * @since 2.7.0 + * @access public + * @var string + */ + var $first_name = ''; + + /** + * Last name of the user. + * + * Created to prevent notices. + * + * @since 2.7.0 + * @access public + * @var string + */ + var $last_name = ''; + + /** + * PHP4 Constructor - Sets up the object properties. + * + * Retrieves the userdata and then assigns all of the data keys to direct + * properties of the object. Calls {@link WP_User::_init_caps()} after + * setting up the object's user data properties. + * + * @since 2.0.0 + * @access public + * + * @param int|string $id User's ID or username + * @param int $name Optional. User's username + * @return WP_User + */ + function WP_User( $id, $name = '' ) { + + if ( empty( $id ) && empty( $name ) ) + return; + + if ( ! is_numeric( $id ) ) { + $name = $id; + $id = 0; + } + + if ( ! empty( $id ) ) + $this->data = get_userdata( $id ); + else + $this->data = get_userdatabylogin( $name ); + + if ( empty( $this->data->ID ) ) + return; + + foreach ( get_object_vars( $this->data ) as $key => $value ) { + $this->{$key} = $value; + } + + $this->id = $this->ID; + $this->_init_caps(); + } + + /** + * Setup capability object properties. + * + * Will set the value for the 'cap_key' property to current database table + * prefix, followed by 'capabilities'. Will then check to see if the + * property matching the 'cap_key' exists and is an array. If so, it will be + * used. + * + * @since 2.1.0 + * @access protected + */ + function _init_caps() { + global $wpdb; + $this->cap_key = $wpdb->prefix . 'capabilities'; + $this->caps = &$this->{$this->cap_key}; + if ( ! is_array( $this->caps ) ) + $this->caps = array(); + $this->get_role_caps(); + } + + /** + * Retrieve all of the role capabilities and merge with individual capabilities. + * + * All of the capabilities of the roles the user belongs to are merged with + * the users individual roles. This also means that the user can be denied + * specific roles that their role might have, but the specific user isn't + * granted permission to. + * + * @since 2.0.0 + * @uses $wp_roles + * @access public + */ + function get_role_caps() { + global $wp_roles; + + if ( ! isset( $wp_roles ) ) + $wp_roles = new WP_Roles(); + + //Filter out caps that are not role names and assign to $this->roles + if ( is_array( $this->caps ) ) + $this->roles = array_filter( array_keys( $this->caps ), array( &$wp_roles, 'is_role' ) ); + + //Build $allcaps from role caps, overlay user's $caps + $this->allcaps = array(); + foreach ( (array) $this->roles as $role ) { + $role =& $wp_roles->get_role( $role ); + $this->allcaps = array_merge( (array) $this->allcaps, (array) $role->capabilities ); + } + $this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps ); + } + + /** + * Add role to user. + * + * Updates the user's meta data option with capabilities and roles. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + */ + function add_role( $role ) { + $this->caps[$role] = true; + update_usermeta( $this->ID, $this->cap_key, $this->caps ); + $this->get_role_caps(); + $this->update_user_level_from_caps(); + } + + /** + * Remove role from user. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + */ + function remove_role( $role ) { + if ( empty( $this->roles[$role] ) || ( count( $this->roles ) <= 1 ) ) + return; + unset( $this->caps[$role] ); + update_usermeta( $this->ID, $this->cap_key, $this->caps ); + $this->get_role_caps(); + } + + /** + * Set the role of the user. + * + * This will remove the previous roles of the user and assign the user the + * new one. You can set the role to an empty string and it will remove all + * of the roles from the user. + * + * @since 2.0.0 + * @access public + * + * @param string $role Role name. + */ + function set_role( $role ) { + foreach ( (array) $this->roles as $oldrole ) + unset( $this->caps[$oldrole] ); + if ( !empty( $role ) ) { + $this->caps[$role] = true; + $this->roles = array( $role => true ); + } else { + $this->roles = false; + } + update_usermeta( $this->ID, $this->cap_key, $this->caps ); + $this->get_role_caps(); + $this->update_user_level_from_caps(); + } + + /** + * Choose the maximum level the user has. + * + * Will compare the level from the $item parameter against the $max + * parameter. If the item is incorrect, then just the $max parameter value + * will be returned. + * + * Used to get the max level based on the capabilities the user has. This + * is also based on roles, so if the user is assigned the Administrator role + * then the capability 'level_10' will exist and the user will get that + * value. + * + * @since 2.0.0 + * @access public + * + * @param int $max Max level of user. + * @param string $item Level capability name. + * @return int Max Level. + */ + function level_reduction( $max, $item ) { + if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) { + $level = intval( $matches[1] ); + return max( $max, $level ); + } else { + return $max; + } + } + + /** + * Update the maximum user level for the user. + * + * Updates the 'user_level' user metadata (includes prefix that is the + * database table prefix) with the maximum user level. Gets the value from + * the all of the capabilities that the user has. + * + * @since 2.0.0 + * @access public + */ + function update_user_level_from_caps() { + global $wpdb; + $this->user_level = array_reduce( array_keys( $this->allcaps ), array( &$this, 'level_reduction' ), 0 ); + update_usermeta( $this->ID, $wpdb->prefix.'user_level', $this->user_level ); + } + + /** + * Add capability and grant or deny access to capability. + * + * @since 2.0.0 + * @access public + * + * @param string $cap Capability name. + * @param bool $grant Whether to grant capability to user. + */ + function add_cap( $cap, $grant = true ) { + $this->caps[$cap] = $grant; + update_usermeta( $this->ID, $this->cap_key, $this->caps ); + } + + /** + * Remove capability from user. + * + * @since 2.0.0 + * @access public + * + * @param string $cap Capability name. + */ + function remove_cap( $cap ) { + if ( empty( $this->caps[$cap] ) ) return; + unset( $this->caps[$cap] ); + update_usermeta( $this->ID, $this->cap_key, $this->caps ); + } + + /** + * Remove all of the capabilities of the user. + * + * @since 2.1.0 + * @access public + */ + function remove_all_caps() { + global $wpdb; + $this->caps = array(); + update_usermeta( $this->ID, $this->cap_key, '' ); + update_usermeta( $this->ID, $wpdb->prefix.'user_level', '' ); + $this->get_role_caps(); + } + + /** + * Whether user has capability or role name. + * + * This is useful for looking up whether the user has a specific role + * assigned to the user. The second optional parameter can also be used to + * check for capabilities against a specfic post. + * + * @since 2.0.0 + * @access public + * + * @param string|int $cap Capability or role name to search. + * @param int $post_id Optional. Post ID to check capability against specific post. + * @return bool True, if user has capability; false, if user does not have capability. + */ + function has_cap( $cap ) { + if ( is_numeric( $cap ) ) + $cap = $this->translate_level_to_cap( $cap ); + + $args = array_slice( func_get_args(), 1 ); + $args = array_merge( array( $cap, $this->ID ), $args ); + $caps = call_user_func_array( 'map_meta_cap', $args ); + // Must have ALL requested caps + $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args ); + foreach ( (array) $caps as $cap ) { + //echo "Checking cap $cap
    "; + if ( empty( $capabilities[$cap] ) || !$capabilities[$cap] ) + return false; + } + + return true; + } + + /** + * Convert numeric level to level capability name. + * + * Prepends 'level_' to level number. + * + * @since 2.0.0 + * @access public + * + * @param int $level Level number, 1 to 10. + * @return string + */ + function translate_level_to_cap( $level ) { + return 'level_' . $level; + } + +} + +/** + * Map meta capabilities to primitive capabilities. + * + * This does not actually compare whether the user ID has the actual capability, + * just what the capability or capabilities are. Meta capability list value can + * be 'delete_user', 'edit_user', 'delete_post', 'delete_page', 'edit_post', + * 'edit_page', 'read_post', or 'read_page'. + * + * @since 2.0.0 + * + * @param string $cap Capability name. + * @param int $user_id User ID. + * @return array Actual capabilities for meta capability. + */ +function map_meta_cap( $cap, $user_id ) { + $args = array_slice( func_get_args(), 2 ); + $caps = array(); + + switch ( $cap ) { + case 'delete_user': + $caps[] = 'delete_users'; + break; + case 'edit_user': + if ( !isset( $args[0] ) || $user_id != $args[0] ) { + $caps[] = 'edit_users'; + } + break; + case 'delete_post': + $author_data = get_userdata( $user_id ); + //echo "post ID: {$args[0]}
    "; + $post = get_post( $args[0] ); + if ( 'page' == $post->post_type ) { + $args = array_merge( array( 'delete_page', $user_id ), $args ); + return call_user_func_array( 'map_meta_cap', $args ); + } + $post_author_data = get_userdata( $post->post_author ); + //echo "current user id : $user_id, post author id: " . $post_author_data->ID . "
    "; + // If the user is the author... + if ( $user_id == $post_author_data->ID ) { + // If the post is published... + if ( 'publish' == $post->post_status ) + $caps[] = 'delete_published_posts'; + else + // If the post is draft... + $caps[] = 'delete_posts'; + } else { + // The user is trying to edit someone else's post. + $caps[] = 'delete_others_posts'; + // The post is published, extra cap required. + if ( 'publish' == $post->post_status ) + $caps[] = 'delete_published_posts'; + elseif ( 'private' == $post->post_status ) + $caps[] = 'delete_private_posts'; + } + break; + case 'delete_page': + $author_data = get_userdata( $user_id ); + //echo "post ID: {$args[0]}
    "; + $page = get_page( $args[0] ); + $page_author_data = get_userdata( $page->post_author ); + //echo "current user id : $user_id, page author id: " . $page_author_data->ID . "
    "; + // If the user is the author... + if ( $user_id == $page_author_data->ID ) { + // If the page is published... + if ( $page->post_status == 'publish' ) + $caps[] = 'delete_published_pages'; + else + // If the page is draft... + $caps[] = 'delete_pages'; + } else { + // The user is trying to edit someone else's page. + $caps[] = 'delete_others_pages'; + // The page is published, extra cap required. + if ( $page->post_status == 'publish' ) + $caps[] = 'delete_published_pages'; + elseif ( $page->post_status == 'private' ) + $caps[] = 'delete_private_pages'; + } + break; + // edit_post breaks down to edit_posts, edit_published_posts, or + // edit_others_posts + case 'edit_post': + $author_data = get_userdata( $user_id ); + //echo "post ID: {$args[0]}
    "; + $post = get_post( $args[0] ); + if ( 'page' == $post->post_type ) { + $args = array_merge( array( 'edit_page', $user_id ), $args ); + return call_user_func_array( 'map_meta_cap', $args ); + } + $post_author_data = get_userdata( $post->post_author ); + //echo "current user id : $user_id, post author id: " . $post_author_data->ID . "
    "; + // If the user is the author... + if ( $user_id == $post_author_data->ID ) { + // If the post is published... + if ( 'publish' == $post->post_status ) + $caps[] = 'edit_published_posts'; + else + // If the post is draft... + $caps[] = 'edit_posts'; + } else { + // The user is trying to edit someone else's post. + $caps[] = 'edit_others_posts'; + // The post is published, extra cap required. + if ( 'publish' == $post->post_status ) + $caps[] = 'edit_published_posts'; + elseif ( 'private' == $post->post_status ) + $caps[] = 'edit_private_posts'; + } + break; + case 'edit_page': + $author_data = get_userdata( $user_id ); + //echo "post ID: {$args[0]}
    "; + $page = get_page( $args[0] ); + $page_author_data = get_userdata( $page->post_author ); + //echo "current user id : $user_id, page author id: " . $page_author_data->ID . "
    "; + // If the user is the author... + if ( $user_id == $page_author_data->ID ) { + // If the page is published... + if ( 'publish' == $page->post_status ) + $caps[] = 'edit_published_pages'; + else + // If the page is draft... + $caps[] = 'edit_pages'; + } else { + // The user is trying to edit someone else's page. + $caps[] = 'edit_others_pages'; + // The page is published, extra cap required. + if ( 'publish' == $page->post_status ) + $caps[] = 'edit_published_pages'; + elseif ( 'private' == $page->post_status ) + $caps[] = 'edit_private_pages'; + } + break; + case 'read_post': + $post = get_post( $args[0] ); + if ( 'page' == $post->post_type ) { + $args = array_merge( array( 'read_page', $user_id ), $args ); + return call_user_func_array( 'map_meta_cap', $args ); + } + + if ( 'private' != $post->post_status ) { + $caps[] = 'read'; + break; + } + + $author_data = get_userdata( $user_id ); + $post_author_data = get_userdata( $post->post_author ); + if ( $user_id == $post_author_data->ID ) + $caps[] = 'read'; + else + $caps[] = 'read_private_posts'; + break; + case 'read_page': + $page = get_page( $args[0] ); + + if ( 'private' != $page->post_status ) { + $caps[] = 'read'; + break; + } + + $author_data = get_userdata( $user_id ); + $page_author_data = get_userdata( $page->post_author ); + if ( $user_id == $page_author_data->ID ) + $caps[] = 'read'; + else + $caps[] = 'read_private_pages'; + break; + default: + // If no meta caps match, return the original cap. + $caps[] = $cap; + } + + return apply_filters('map_meta_cap', $caps, $cap, $user_id, $args); +} + +/** + * Whether current user has capability or role. + * + * @since 2.0.0 + * + * @param string $capability Capability or role name. + * @return bool + */ +function current_user_can( $capability ) { + $current_user = wp_get_current_user(); + + if ( empty( $current_user ) ) + return false; + + $args = array_slice( func_get_args(), 1 ); + $args = array_merge( array( $capability ), $args ); + + return call_user_func_array( array( &$current_user, 'has_cap' ), $args ); +} + +/** + * Retrieve role object. + * + * @see WP_Roles::get_role() Uses method to retrieve role object. + * @since 2.0.0 + * + * @param string $role Role name. + * @return object + */ +function get_role( $role ) { + global $wp_roles; + + if ( ! isset( $wp_roles ) ) + $wp_roles = new WP_Roles(); + + return $wp_roles->get_role( $role ); +} + +/** + * Add role, if it does not exist. + * + * @see WP_Roles::add_role() Uses method to add role. + * @since 2.0.0 + * + * @param string $role Role name. + * @param string $display_name Display name for role. + * @param array $capabilities List of capabilities. + * @return null|WP_Role WP_Role object if role is added, null if already exists. + */ +function add_role( $role, $display_name, $capabilities = array() ) { + global $wp_roles; + + if ( ! isset( $wp_roles ) ) + $wp_roles = new WP_Roles(); + + return $wp_roles->add_role( $role, $display_name, $capabilities ); +} + +/** + * Remove role, if it exists. + * + * @see WP_Roles::remove_role() Uses method to remove role. + * @since 2.0.0 + * + * @param string $role Role name. + * @return null + */ +function remove_role( $role ) { + global $wp_roles; + + if ( ! isset( $wp_roles ) ) + $wp_roles = new WP_Roles(); + + return $wp_roles->remove_role( $role ); +} + +?> diff --git a/wp-includes/category-template.php b/wp-includes/category-template.php new file mode 100644 index 0000000..61f2faf --- /dev/null +++ b/wp-includes/category-template.php @@ -0,0 +1,956 @@ +get_category_permastruct(); + + if ( empty( $catlink ) ) { + $file = get_option( 'home' ) . '/'; + $catlink = $file . '?cat=' . $category_id; + } else { + $category = &get_category( $category_id ); + if ( is_wp_error( $category ) ) + return $category; + $category_nicename = $category->slug; + + if ( $category->parent == $category_id ) // recursive recursion + $category->parent = 0; + elseif ($category->parent != 0 ) + $category_nicename = get_category_parents( $category->parent, false, '/', true ) . $category_nicename; + + $catlink = str_replace( '%category%', $category_nicename, $catlink ); + $catlink = get_option( 'home' ) . user_trailingslashit( $catlink, 'category' ); + } + return apply_filters( 'category_link', $catlink, $category_id ); +} + +/** + * Retrieve category parents with separator. + * + * @since 1.2.0 + * + * @param int $id Category ID. + * @param bool $link Optional, default is false. Whether to format with link. + * @param string $separator Optional, default is '/'. How to separate categories. + * @param bool $nicename Optional, default is false. Whether to use nice name for display. + * @param array $visited Optional. Already linked to categories to prevent duplicates. + * @return string + */ +function get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array() ) { + $chain = ''; + $parent = &get_category( $id ); + if ( is_wp_error( $parent ) ) + return $parent; + + if ( $nicename ) + $name = $parent->slug; + else + $name = $parent->cat_name; + + if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) { + $visited[] = $parent->parent; + $chain .= get_category_parents( $parent->parent, $link, $separator, $nicename, $visited ); + } + + if ( $link ) + $chain .= 'cat_name ) . '">'.$name.'' . $separator; + else + $chain .= $name.$separator; + return $chain; +} + +/** + * Retrieve post categories. + * + * @since 0.71 + * @uses $post + * + * @param int $id Optional, default to current post ID. The post ID. + * @return array + */ +function get_the_category( $id = false ) { + global $post; + + $id = (int) $id; + if ( !$id ) + $id = (int) $post->ID; + + $categories = get_object_term_cache( $id, 'category' ); + if ( false === $categories ) { + $categories = wp_get_object_terms( $id, 'category' ); + wp_cache_add($id, $categories, 'category_relationships'); + } + + if ( !empty( $categories ) ) + usort( $categories, '_usort_terms_by_name' ); + else + $categories = array(); + + foreach ( (array) array_keys( $categories ) as $key ) { + _make_cat_compat( $categories[$key] ); + } + + return $categories; +} + +/** + * Sort categories by name. + * + * Used by usort() as a callback, should not be used directly. Can actually be + * used to sort any term object. + * + * @since 2.3.0 + * @access private + * + * @param object $a + * @param object $b + * @return int + */ +function _usort_terms_by_name( $a, $b ) { + return strcmp( $a->name, $b->name ); +} + +/** + * Sort categories by ID. + * + * Used by usort() as a callback, should not be used directly. Can actually be + * used to sort any term object. + * + * @since 2.3.0 + * @access private + * + * @param object $a + * @param object $b + * @return int + */ +function _usort_terms_by_ID( $a, $b ) { + if ( $a->term_id > $b->term_id ) + return 1; + elseif ( $a->term_id < $b->term_id ) + return -1; + else + return 0; +} + +/** + * Retrieve category name based on category ID. + * + * @since 0.71 + * + * @param int $cat_ID Category ID. + * @return string Category name. + */ +function get_the_category_by_ID( $cat_ID ) { + $cat_ID = (int) $cat_ID; + $category = &get_category( $cat_ID ); + if ( is_wp_error( $category ) ) + return $category; + return $category->name; +} + +/** + * Retrieve category list in either HTML list or custom format. + * + * @since 1.5.1 + * + * @param string $separator Optional, default is empty string. Separator for between the categories. + * @param string $parents Optional. How to display the parents. + * @param int $post_id Optional. Post ID to retrieve categories. + * @return string + */ +function get_the_category_list( $separator = '', $parents='', $post_id = false ) { + global $wp_rewrite; + $categories = get_the_category( $post_id ); + if ( empty( $categories ) ) + return apply_filters( 'the_category', __( 'Uncategorized' ), $separator, $parents ); + + $rel = ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) ? 'rel="category tag"' : 'rel="category"'; + + $thelist = ''; + if ( '' == $separator ) { + $thelist .= ''; + } else { + $i = 0; + foreach ( $categories as $category ) { + if ( 0 < $i ) + $thelist .= $separator . ' '; + switch ( strtolower( $parents ) ) { + case 'multiple': + if ( $category->parent ) + $thelist .= get_category_parents( $category->parent, true, $separator ); + $thelist .= 'name ) . '" ' . $rel . '>' . $category->cat_name.''; + break; + case 'single': + $thelist .= 'name ) . '" ' . $rel . '>'; + if ( $category->parent ) + $thelist .= get_category_parents( $category->parent, false, $separator ); + $thelist .= "$category->cat_name"; + break; + case '': + default: + $thelist .= 'name ) . '" ' . $rel . '>' . $category->name.''; + } + ++$i; + } + } + return apply_filters( 'the_category', $thelist, $separator, $parents ); +} + + +/** + * Check if the current post in within any of the given categories. + * + * The given categories are checked against the post's categories' term_ids, names and slugs. + * Categories given as integers will only be checked against the post's categories' term_ids. + * + * Prior to v2.5 of WordPress, category names were not supported. + * Prior to v2.7, category slugs were not supported. + * Prior to v2.7, only one category could be compared: in_category( $single_category ). + * Prior to v2.7, this function could only be used in the WordPress Loop. + * As of 2.7, the function can be used anywhere if it is provided a post ID or post object. + * + * @since 1.2.0 + * + * @uses is_object_in_term() + * + * @param int|string|array $category. Category ID, name or slug, or array of said. + * @param int|post object Optional. Post to check instead of the current post. @since 2.7.0 + * @return bool True if the current post is in any of the given categories. + */ +function in_category( $category, $_post = null ) { + if ( empty( $category ) ) + return false; + + if ( $_post ) { + $_post = get_post( $_post ); + } else { + $_post =& $GLOBALS['post']; + } + + if ( !$_post ) + return false; + + $r = is_object_in_term( $_post->ID, 'category', $category ); + if ( is_wp_error( $r ) ) + return false; + return $r; +} + +/** + * Display the category list for the post. + * + * @since 0.71 + * + * @param string $separator Optional, default is empty string. Separator for between the categories. + * @param string $parents Optional. How to display the parents. + * @param int $post_id Optional. Post ID to retrieve categories. + */ +function the_category( $separator = '', $parents='', $post_id = false ) { + echo get_the_category_list( $separator, $parents, $post_id ); +} + +/** + * Retrieve category description. + * + * @since 1.0.0 + * + * @param int $category Optional. Category ID. Will use global category ID by default. + * @return string Category description, available. + */ +function category_description( $category = 0 ) { + return term_description( $category, 'category' ); +} + +/** + * Display or retrieve the HTML dropdown list of categories. + * + * The list of arguments is below: + * 'show_option_all' (string) - Text to display for showing all categories. + * 'show_option_none' (string) - Text to display for showing no categories. + * 'orderby' (string) default is 'ID' - What column to use for ordering the + * categories. + * 'order' (string) default is 'ASC' - What direction to order categories. + * 'show_last_update' (bool|int) default is 0 - See {@link get_categories()} + * 'show_count' (bool|int) default is 0 - Whether to show how many posts are + * in the category. + * 'hide_empty' (bool|int) default is 1 - Whether to hide categories that + * don't have any posts attached to them. + * 'child_of' (int) default is 0 - See {@link get_categories()}. + * 'exclude' (string) - See {@link get_categories()}. + * 'echo' (bool|int) default is 1 - Whether to display or retrieve content. + * 'depth' (int) - The max depth. + * 'tab_index' (int) - Tab index for select element. + * 'name' (string) - The name attribute value for selected element. + * 'class' (string) - The class attribute value for selected element. + * 'selected' (int) - Which category ID is selected. + * + * The 'hierarchical' argument, which is disabled by default, will override the + * depth argument, unless it is true. When the argument is false, it will + * display all of the categories. When it is enabled it will use the value in + * the 'depth' argument. + * + * @since 2.1.0 + * + * @param string|array $args Optional. Override default arguments. + * @return string HTML content only if 'echo' argument is 0. + */ +function wp_dropdown_categories( $args = '' ) { + $defaults = array( + 'show_option_all' => '', 'show_option_none' => '', + 'orderby' => 'id', 'order' => 'ASC', + 'show_last_update' => 0, 'show_count' => 0, + 'hide_empty' => 1, 'child_of' => 0, + 'exclude' => '', 'echo' => 1, + 'selected' => 0, 'hierarchical' => 0, + 'name' => 'cat', 'class' => 'postform', + 'depth' => 0, 'tab_index' => 0 + ); + + $defaults['selected'] = ( is_category() ) ? get_query_var( 'cat' ) : 0; + + $r = wp_parse_args( $args, $defaults ); + $r['include_last_update_time'] = $r['show_last_update']; + extract( $r ); + + $tab_index_attribute = ''; + if ( (int) $tab_index > 0 ) + $tab_index_attribute = " tabindex=\"$tab_index\""; + + $categories = get_categories( $r ); + + $output = ''; + if ( ! empty( $categories ) ) { + $output = "\n"; + } + + $output = apply_filters( 'wp_dropdown_cats', $output ); + + if ( $echo ) + echo $output; + + return $output; +} + +/** + * Display or retrieve the HTML list of categories. + * + * The list of arguments is below: + * 'show_option_all' (string) - Text to display for showing all categories. + * 'orderby' (string) default is 'ID' - What column to use for ordering the + * categories. + * 'order' (string) default is 'ASC' - What direction to order categories. + * 'show_last_update' (bool|int) default is 0 - See {@link + * walk_category_dropdown_tree()} + * 'show_count' (bool|int) default is 0 - Whether to show how many posts are + * in the category. + * 'hide_empty' (bool|int) default is 1 - Whether to hide categories that + * don't have any posts attached to them. + * 'use_desc_for_title' (bool|int) default is 1 - Whether to use the + * description instead of the category title. + * 'feed' - See {@link get_categories()}. + * 'feed_type' - See {@link get_categories()}. + * 'feed_image' - See {@link get_categories()}. + * 'child_of' (int) default is 0 - See {@link get_categories()}. + * 'exclude' (string) - See {@link get_categories()}. + * 'exclude_tree' (string) - See {@link get_categories()}. + * 'echo' (bool|int) default is 1 - Whether to display or retrieve content. + * 'current_category' (int) - See {@link get_categories()}. + * 'hierarchical' (bool) - See {@link get_categories()}. + * 'title_li' (string) - See {@link get_categories()}. + * 'depth' (int) - The max depth. + * + * @since 2.1.0 + * + * @param string|array $args Optional. Override default arguments. + * @return string HTML content only if 'echo' argument is 0. + */ +function wp_list_categories( $args = '' ) { + $defaults = array( + 'show_option_all' => '', 'orderby' => 'name', + 'order' => 'ASC', 'show_last_update' => 0, + 'style' => 'list', 'show_count' => 0, + 'hide_empty' => 1, 'use_desc_for_title' => 1, + 'child_of' => 0, 'feed' => '', 'feed_type' => '', + 'feed_image' => '', 'exclude' => '', 'exclude_tree' => '', 'current_category' => 0, + 'hierarchical' => true, 'title_li' => __( 'Categories' ), + 'echo' => 1, 'depth' => 0 + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) { + $r['pad_counts'] = true; + } + + if ( isset( $r['show_date'] ) ) { + $r['include_last_update_time'] = $r['show_date']; + } + + if ( true == $r['hierarchical'] ) { + $r['exclude_tree'] = $r['exclude']; + $r['exclude'] = ''; + } + + extract( $r ); + + $categories = get_categories( $r ); + + $output = ''; + if ( $title_li && 'list' == $style ) + $output = '
  • ' . $r['title_li'] . '
      '; + + if ( empty( $categories ) ) { + if ( 'list' == $style ) + $output .= '
    • ' . __( "No categories" ) . '
    • '; + else + $output .= __( "No categories" ); + } else { + global $wp_query; + + if( !empty( $show_option_all ) ) + if ( 'list' == $style ) + $output .= '
    • ' . $show_option_all . '
    • '; + else + $output .= '' . $show_option_all . ''; + + if ( empty( $r['current_category'] ) && is_category() ) + $r['current_category'] = $wp_query->get_queried_object_id(); + + if ( $hierarchical ) + $depth = $r['depth']; + else + $depth = -1; // Flat. + + $output .= walk_category_tree( $categories, $depth, $r ); + } + + if ( $title_li && 'list' == $style ) + $output .= '
  • '; + + $output = apply_filters( 'wp_list_categories', $output ); + + if ( $echo ) + echo $output; + else + return $output; +} + +/** + * Display tag cloud. + * + * The text size is set by the 'smallest' and 'largest' arguments, which will + * use the 'unit' argument value for the CSS text size unit. The 'format' + * argument can be 'flat' (default), 'list', or 'array'. The flat value for the + * 'format' argument will separate tags with spaces. The list value for the + * 'format' argument will format the tags in a UL HTML list. The array value for + * the 'format' argument will return in PHP array type format. + * + * The 'orderby' argument will accept 'name' or 'count' and defaults to 'name'. + * The 'order' is the direction to sort, defaults to 'ASC' and can be 'DESC'. + * + * The 'number' argument is how many tags to return. By default, the limit will + * be to return the top 45 tags in the tag cloud list. + * + * The 'topic_count_text_callback' argument is a function, which, given the count + * of the posts with that tag, returns a text for the tooltip of the tag link. + * + * The 'exclude' and 'include' arguments are used for the {@link get_tags()} + * function. Only one should be used, because only one will be used and the + * other ignored, if they are both set. + * + * @since 2.3.0 + * + * @param array|string $args Optional. Override default arguments. + * @return array Generated tag cloud, only if no failures and 'array' is set for the 'format' argument. + */ +function wp_tag_cloud( $args = '' ) { + $defaults = array( + 'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, + 'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC', + 'exclude' => '', 'include' => '', 'link' => 'view', 'taxonomy' => 'post_tag', 'echo' => true + ); + $args = wp_parse_args( $args, $defaults ); + + $tags = get_terms( $args['taxonomy'], array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) ); // Always query top tags + + if ( empty( $tags ) ) + return; + + foreach ( $tags as $key => $tag ) { + if ( 'edit' == $args['link'] ) + $link = get_edit_tag_link( $tag->term_id, $args['taxonomy'] ); + else + $link = get_term_link( intval($tag->term_id), $args['taxonomy'] ); + if ( is_wp_error( $link ) ) + return false; + + $tags[ $key ]->link = $link; + $tags[ $key ]->id = $tag->term_id; + } + + $return = wp_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args + + $return = apply_filters( 'wp_tag_cloud', $return, $args ); + + if ( 'array' == $args['format'] || empty($args['echo']) ) + return $return; + + echo $return; +} + +/** + * Default text for tooltip for tag links + * + * @param integer $count number of posts with that tag + * @return string text for the tooltip of a tag link. + */ +function default_topic_count_text( $count ) { + return sprintf( _n('%s topic', '%s topics', $count), number_format_i18n( $count ) ); +} + +/** + * Generates a tag cloud (heatmap) from provided data. + * + * The text size is set by the 'smallest' and 'largest' arguments, which will + * use the 'unit' argument value for the CSS text size unit. The 'format' + * argument can be 'flat' (default), 'list', or 'array'. The flat value for the + * 'format' argument will separate tags with spaces. The list value for the + * 'format' argument will format the tags in a UL HTML list. The array value for + * the 'format' argument will return in PHP array type format. + * + * The 'tag_cloud_sort' filter allows you to override the sorting done + * by the 'orderby' argument; passed to the filter: $tags array and $args array. + * + * The 'orderby' argument will accept 'name' or 'count' and defaults to 'name'. + * The 'order' is the direction to sort, defaults to 'ASC' and can be 'DESC' or + * 'RAND'. + * + * The 'number' argument is how many tags to return. By default, the limit will + * be to return the entire tag cloud list. + * + * The 'topic_count_text_callback' argument is a function, which given the count + * of the posts with that tag returns a text for the tooltip of the tag link. + * + * @todo Complete functionality. + * @since 2.3.0 + * + * @param array $tags List of tags. + * @param string|array $args Optional, override default arguments. + * @return string + */ +function wp_generate_tag_cloud( $tags, $args = '' ) { + global $wp_rewrite; + $defaults = array( + 'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 0, + 'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC', + 'topic_count_text_callback' => 'default_topic_count_text', + 'filter' => 1, + ); + + if ( !isset( $args['topic_count_text_callback'] ) && isset( $args['single_text'] ) && isset( $args['multiple_text'] ) ) { + $body = 'return sprintf ( + _n('.var_export($args['single_text'], true).', '.var_export($args['multiple_text'], true).', $count), + number_format_i18n( $count ));'; + $args['topic_count_text_callback'] = create_function('$count', $body); + } + + $args = wp_parse_args( $args, $defaults ); + + extract( $args ); + + if ( empty( $tags ) ) + return; + + // SQL cannot save you; this is a second (potentially different) sort on a subset of data. + if ( 'name' == $orderby ) + uasort( $tags, create_function('$a, $b', 'return strnatcasecmp($a->name, $b->name);') ); + else + uasort( $tags, create_function('$a, $b', 'return ($a->count > $b->count);') ); + + $tags = apply_filters( 'tag_cloud_sort', $tags, $args ); + + if ( 'DESC' == $order ) + $tags = array_reverse( $tags, true ); + elseif ( 'RAND' == $order ) { + $keys = (array) array_rand( $tags, count( $tags ) ); + $temp = array(); + foreach ( $keys as $key ) + $temp[$key] = $tags[$key]; + + $tags = $temp; + $temp = null; + unset( $temp ); + } + + if ( $number > 0 ) + $tags = array_slice($tags, 0, $number); + + $counts = array(); + foreach ( (array) $tags as $key => $tag ) + $counts[ $key ] = $tag->count; + + $min_count = min( $counts ); + $spread = max( $counts ) - $min_count; + if ( $spread <= 0 ) + $spread = 1; + $font_spread = $largest - $smallest; + if ( $font_spread < 0 ) + $font_spread = 1; + $font_step = $font_spread / $spread; + + $a = array(); + + $rel = ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) ? ' rel="tag"' : ''; + + foreach ( $tags as $key => $tag ) { + $count = $counts[ $key ]; + $tag_link = '#' != $tag->link ? esc_url( $tag->link ) : '#'; + $tag_id = isset($tags[ $key ]->id) ? $tags[ $key ]->id : $key; + $tag_name = $tags[ $key ]->name; + $a[] = "$tag_name"; + } + + switch ( $format ) : + case 'array' : + $return =& $a; + break; + case 'list' : + $return = "
      \n\t
    • "; + $return .= join( "
    • \n\t
    • ", $a ); + $return .= "
    • \n
    \n"; + break; + default : + $return = join( "\n", $a ); + break; + endswitch; + + if ( $filter ) + return apply_filters( 'wp_generate_tag_cloud', $return, $tags, $args ); + else + return $return; +} + +// +// Helper functions +// + +/** + * Retrieve HTML list content for category list. + * + * @uses Walker_Category to create HTML list content. + * @since 2.1.0 + * @see Walker_Category::walk() for parameters and return description. + */ +function walk_category_tree() { + $args = func_get_args(); + // the user's options are the third parameter + if ( empty($args[2]['walker']) || !is_a($args[2]['walker'], 'Walker') ) + $walker = new Walker_Category; + else + $walker = $args[2]['walker']; + + return call_user_func_array(array( &$walker, 'walk' ), $args ); +} + +/** + * Retrieve HTML dropdown (select) content for category list. + * + * @uses Walker_CategoryDropdown to create HTML dropdown content. + * @since 2.1.0 + * @see Walker_CategoryDropdown::walk() for parameters and return description. + */ +function walk_category_dropdown_tree() { + $args = func_get_args(); + // the user's options are the third parameter + if ( empty($args[2]['walker']) || !is_a($args[2]['walker'], 'Walker') ) + $walker = new Walker_CategoryDropdown; + else + $walker = $args[2]['walker']; + + return call_user_func_array(array( &$walker, 'walk' ), $args ); +} + +// +// Tags +// + +/** + * Retrieve the link to the tag. + * + * @since 2.3.0 + * @uses apply_filters() Calls 'tag_link' with tag link and tag ID as parameters. + * + * @param int $tag_id Tag (term) ID. + * @return string + */ +function get_tag_link( $tag_id ) { + global $wp_rewrite; + $taglink = $wp_rewrite->get_tag_permastruct(); + + $tag = &get_term( $tag_id, 'post_tag' ); + if ( is_wp_error( $tag ) ) + return $tag; + $slug = $tag->slug; + + if ( empty( $taglink ) ) { + $file = get_option( 'home' ) . '/'; + $taglink = $file . '?tag=' . $slug; + } else { + $taglink = str_replace( '%tag%', $slug, $taglink ); + $taglink = get_option( 'home' ) . user_trailingslashit( $taglink, 'category' ); + } + return apply_filters( 'tag_link', $taglink, $tag_id ); +} + +/** + * Retrieve the tags for a post. + * + * @since 2.3.0 + * @uses apply_filters() Calls 'get_the_tags' filter on the list of post tags. + * + * @param int $id Post ID. + * @return array + */ +function get_the_tags( $id = 0 ) { + return apply_filters( 'get_the_tags', get_the_terms( $id, 'post_tag' ) ); +} + +/** + * Retrieve the tags for a post formatted as a string. + * + * @since 2.3.0 + * @uses apply_filters() Calls 'the_tags' filter on string list of tags. + * + * @param string $before Optional. Before tags. + * @param string $sep Optional. Between tags. + * @param string $after Optional. After tags. + * @return string + */ +function get_the_tag_list( $before = '', $sep = '', $after = '' ) { + return apply_filters( 'the_tags', get_the_term_list( 0, 'post_tag', $before, $sep, $after ), $before, $sep, $after); +} + +/** + * Retrieve the tags for a post. + * + * @since 2.3.0 + * + * @param string $before Optional. Before list. + * @param string $sep Optional. Separate items using this. + * @param string $after Optional. After list. + * @return string + */ +function the_tags( $before = null, $sep = ', ', $after = '' ) { + if ( null === $before ) + $before = __('Tags: '); + echo get_the_tag_list($before, $sep, $after); +} + +/** + * Retrieve tag description. + * + * @since 2.8 + * + * @param int $tag Optional. Tag ID. Will use global tag ID by default. + * @return string Tag description, available. + */ +function tag_description( $tag = 0 ) { + return term_description( $tag ); +} + +/** + * Retrieve term description. + * + * @since 2.8 + * + * @param int $term Optional. Term ID. Will use global term ID by default. + * @return string Term description, available. + */ +function term_description( $term = 0, $taxonomy = 'post_tag' ) { + if ( !$term && ( is_tax() || is_tag() || is_category() ) ) { + global $wp_query; + $term = $wp_query->get_queried_object(); + $taxonomy = $term->taxonomy; + $term = $term->term_id; + } + return get_term_field( 'description', $term, $taxonomy ); +} + +/** + * Retrieve the terms of the taxonomy that are attached to the post. + * + * This function can only be used within the loop. + * + * @since 2.5.0 + * + * @param int $id Post ID. Is not optional. + * @param string $taxonomy Taxonomy name. + * @return array|bool False on failure. Array of term objects on success. + */ +function get_the_terms( $id = 0, $taxonomy ) { + global $post; + + $id = (int) $id; + + if ( ! $id && ! in_the_loop() ) + return false; // in-the-loop function + + if ( !$id ) + $id = (int) $post->ID; + + $terms = get_object_term_cache( $id, $taxonomy ); + if ( false === $terms ) + $terms = wp_get_object_terms( $id, $taxonomy ); + + if ( empty( $terms ) ) + return false; + + return $terms; +} + +/** + * Retrieve terms as a list with specified format. + * + * @since 2.5.0 + * + * @param int $id Term ID. + * @param string $taxonomy Taxonomy name. + * @param string $before Optional. Before list. + * @param string $sep Optional. Separate items using this. + * @param string $after Optional. After list. + * @return string + */ +function get_the_term_list( $id = 0, $taxonomy, $before = '', $sep = '', $after = '' ) { + $terms = get_the_terms( $id, $taxonomy ); + + if ( is_wp_error( $terms ) ) + return $terms; + + if ( empty( $terms ) ) + return false; + + foreach ( $terms as $term ) { + $link = get_term_link( $term, $taxonomy ); + if ( is_wp_error( $link ) ) + return $link; + $term_links[] = ''; + } + + $term_links = apply_filters( "term_links-$taxonomy", $term_links ); + + return $before . join( $sep, $term_links ) . $after; +} + +/** + * Display the terms in a list. + * + * @since 2.5.0 + * + * @param int $id Term ID. + * @param string $taxonomy Taxonomy name. + * @param string $before Optional. Before list. + * @param string $sep Optional. Separate items using this. + * @param string $after Optional. After list. + * @return null|bool False on WordPress error. Returns null when displaying. + */ +function the_terms( $id, $taxonomy, $before = '', $sep = '', $after = '' ) { + $return = get_the_term_list( $id, $taxonomy, $before, $sep, $after ); + if ( is_wp_error( $return ) ) + return false; + else + echo $return; +} + +/** + * Check if the current post has any of given tags. + * + * The given tags are checked against the post's tags' term_ids, names and slugs. + * Tags given as integers will only be checked against the post's tags' term_ids. + * If no tags are given, determines if post has any tags. + * + * Prior to v2.7 of WordPress, tags given as integers would also be checked against the post's tags' names and slugs (in addition to term_ids) + * Prior to v2.7, this function could only be used in the WordPress Loop. + * As of 2.7, the function can be used anywhere if it is provided a post ID or post object. + * + * @since 2.6.0 + * + * @uses is_object_in_term() + * + * @param string|int|array $tag Optional. The tag name/term_id/slug or array of them to check for. + * @param int|post object Optional. Post to check instead of the current post. @since 2.7.0 + * @return bool True if the current post has any of the the given tags (or any tag, if no tag specified). + */ +function has_tag( $tag = '', $_post = null ) { + if ( $_post ) { + $_post = get_post( $_post ); + } else { + $_post =& $GLOBALS['post']; + } + + if ( !$_post ) + return false; + + $r = is_object_in_term( $_post->ID, 'post_tag', $tag ); + if ( is_wp_error( $r ) ) + return false; + return $r; +} + +?> diff --git a/wp-includes/category.php b/wp-includes/category.php new file mode 100644 index 0000000..372c4c7 --- /dev/null +++ b/wp-includes/category.php @@ -0,0 +1,368 @@ + 'category' ); + $args = wp_parse_args( $args, $defaults ); + + $taxonomy = apply_filters( 'get_categories_taxonomy', 'category', $args ); + if ( 'link' == $args['type'] ) + $taxonomy = 'link_category'; + $categories = (array) get_terms( $taxonomy, $args ); + + foreach ( array_keys( $categories ) as $k ) + _make_cat_compat( $categories[$k] ); + + return $categories; +} + +/** + * Retrieves category data given a category ID or category object. + * + * If you pass the $category parameter an object, which is assumed to be the + * category row object retrieved the database. It will cache the category data. + * + * If you pass $category an integer of the category ID, then that category will + * be retrieved from the database, if it isn't already cached, and pass it back. + * + * If you look at get_term(), then both types will be passed through several + * filters and finally sanitized based on the $filter parameter value. + * + * The category will converted to maintain backwards compatibility. + * + * @since 1.5.1 + * @uses get_term() Used to get the category data from the taxonomy. + * + * @param int|object $category Category ID or Category row object + * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N + * @param string $filter Optional. Default is raw or no WordPress defined filter will applied. + * @return mixed Category data in type defined by $output parameter. + */ +function &get_category( $category, $output = OBJECT, $filter = 'raw' ) { + $category = get_term( $category, 'category', $output, $filter ); + if ( is_wp_error( $category ) ) + return $category; + + _make_cat_compat( $category ); + + return $category; +} + +/** + * Retrieve category based on URL containing the category slug. + * + * Breaks the $category_path parameter up to get the category slug. + * + * Tries to find the child path and will return it. If it doesn't find a + * match, then it will return the first category matching slug, if $full_match, + * is set to false. If it does not, then it will return null. + * + * It is also possible that it will return a WP_Error object on failure. Check + * for it when using this function. + * + * @since 2.1.0 + * + * @param string $category_path URL containing category slugs. + * @param bool $full_match Optional. Whether should match full path or not. + * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N + * @return null|object|array Null on failure. Type is based on $output value. + */ +function get_category_by_path( $category_path, $full_match = true, $output = OBJECT ) { + $category_path = rawurlencode( urldecode( $category_path ) ); + $category_path = str_replace( '%2F', '/', $category_path ); + $category_path = str_replace( '%20', ' ', $category_path ); + $category_paths = '/' . trim( $category_path, '/' ); + $leaf_path = sanitize_title( basename( $category_paths ) ); + $category_paths = explode( '/', $category_paths ); + $full_path = ''; + foreach ( (array) $category_paths as $pathdir ) + $full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title( $pathdir ); + + $categories = get_terms( 'category', "get=all&slug=$leaf_path" ); + + if ( empty( $categories ) ) + return null; + + foreach ( $categories as $category ) { + $path = '/' . $leaf_path; + $curcategory = $category; + while ( ( $curcategory->parent != 0 ) && ( $curcategory->parent != $curcategory->term_id ) ) { + $curcategory = get_term( $curcategory->parent, 'category' ); + if ( is_wp_error( $curcategory ) ) + return $curcategory; + $path = '/' . $curcategory->slug . $path; + } + + if ( $path == $full_path ) + return get_category( $category->term_id, $output ); + } + + // If full matching is not required, return the first cat that matches the leaf. + if ( ! $full_match ) + return get_category( $categories[0]->term_id, $output ); + + return null; +} + +/** + * Retrieve category object by category slug. + * + * @since 2.3.0 + * + * @param string $slug The category slug. + * @return object Category data object + */ +function get_category_by_slug( $slug ) { + $category = get_term_by( 'slug', $slug, 'category' ); + if ( $category ) + _make_cat_compat( $category ); + + return $category; +} + + +/** + * Retrieve the ID of a category from its name. + * + * @since 1.0.0 + * + * @param string $cat_name Optional. Default is 'General' and can be any category name. + * @return int 0, if failure and ID of category on success. + */ +function get_cat_ID( $cat_name='General' ) { + $cat = get_term_by( 'name', $cat_name, 'category' ); + if ( $cat ) + return $cat->term_id; + return 0; +} + + +/** + * Retrieve the name of a category from its ID. + * + * @since 1.0.0 + * + * @param int $cat_id Category ID + * @return string Category name + */ +function get_cat_name( $cat_id ) { + $cat_id = (int) $cat_id; + $category = &get_category( $cat_id ); + return $category->name; +} + + +/** + * Check if a category is an ancestor of another category. + * + * You can use either an id or the category object for both parameters. If you + * use an integer the category will be retrieved. + * + * @since 2.1.0 + * + * @param int|object $cat1 ID or object to check if this is the parent category. + * @param int|object $cat2 The child category. + * @return bool Whether $cat2 is child of $cat1 + */ +function cat_is_ancestor_of( $cat1, $cat2 ) { + if ( ! isset($cat1->term_id) ) + $cat1 = &get_category( $cat1 ); + if ( ! isset($cat2->parent) ) + $cat2 = &get_category( $cat2 ); + + if ( empty($cat1->term_id) || empty($cat2->parent) ) + return false; + if ( $cat2->parent == $cat1->term_id ) + return true; + + return cat_is_ancestor_of( $cat1, get_category( $cat2->parent ) ); +} + + +/** + * Sanitizes category data based on context. + * + * @since 2.3.0 + * @uses sanitize_term() See this function for what context are supported. + * + * @param object|array $category Category data + * @param string $context Optional. Default is 'display'. + * @return object|array Same type as $category with sanitized data for safe use. + */ +function sanitize_category( $category, $context = 'display' ) { + return sanitize_term( $category, 'category', $context ); +} + + +/** + * Sanitizes data in single category key field. + * + * @since 2.3.0 + * @uses sanitize_term_field() See function for more details. + * + * @param string $field Category key to sanitize + * @param mixed $value Category value to sanitize + * @param int $cat_id Category ID + * @param string $context What filter to use, 'raw', 'display', etc. + * @return mixed Same type as $value after $value has been sanitized. + */ +function sanitize_category_field( $field, $value, $cat_id, $context ) { + return sanitize_term_field( $field, $value, $cat_id, 'category', $context ); +} + +/* Tags */ + + +/** + * Retrieves all post tags. + * + * @since 2.3.0 + * @see get_terms() For list of arguments to pass. + * @uses apply_filters() Calls 'get_tags' hook on array of tags and with $args. + * + * @param string|array $args Tag arguments to use when retrieving tags. + * @return array List of tags. + */ +function &get_tags( $args = '' ) { + $tags = get_terms( 'post_tag', $args ); + + if ( empty( $tags ) ) { + $return = array(); + return $return; + } + + $tags = apply_filters( 'get_tags', $tags, $args ); + return $tags; +} + + +/** + * Retrieve post tag by tag ID or tag object. + * + * If you pass the $tag parameter an object, which is assumed to be the tag row + * object retrieved the database. It will cache the tag data. + * + * If you pass $tag an integer of the tag ID, then that tag will + * be retrieved from the database, if it isn't already cached, and pass it back. + * + * If you look at get_term(), then both types will be passed through several + * filters and finally sanitized based on the $filter parameter value. + * + * @since 2.3.0 + * + * @param int|object $tag + * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N + * @param string $filter Optional. Default is raw or no WordPress defined filter will applied. + * @return object|array Return type based on $output value. + */ +function &get_tag( $tag, $output = OBJECT, $filter = 'raw' ) { + return get_term( $tag, 'post_tag', $output, $filter ); +} + + +/* Cache */ + + +/** + * Update the categories cache. + * + * This function does not appear to be used anymore or does not appear to be + * needed. It might be a legacy function left over from when there was a need + * for updating the category cache. + * + * @since 1.5.0 + * + * @return bool Always return True + */ +function update_category_cache() { + return true; +} + + +/** + * Remove the category cache data based on ID. + * + * @since 2.1.0 + * @uses clean_term_cache() Clears the cache for the category based on ID + * + * @param int $id Category ID + */ +function clean_category_cache( $id ) { + clean_term_cache( $id, 'category' ); +} + + +/** + * Update category structure to old pre 2.3 from new taxonomy structure. + * + * This function was added for the taxonomy support to update the new category + * structure with the old category one. This will maintain compatibility with + * plugins and themes which depend on the old key or property names. + * + * The parameter should only be passed a variable and not create the array or + * object inline to the parameter. The reason for this is that parameter is + * passed by reference and PHP will fail unless it has the variable. + * + * There is no return value, because everything is updated on the variable you + * pass to it. This is one of the features with using pass by reference in PHP. + * + * @since 2.3.0 + * @access private + * + * @param array|object $category Category Row object or array + */ +function _make_cat_compat( &$category ) { + if ( is_object( $category ) ) { + $category->cat_ID = &$category->term_id; + $category->category_count = &$category->count; + $category->category_description = &$category->description; + $category->cat_name = &$category->name; + $category->category_nicename = &$category->slug; + $category->category_parent = &$category->parent; + } elseif ( is_array( $category ) && isset( $category['term_id'] ) ) { + $category['cat_ID'] = &$category['term_id']; + $category['category_count'] = &$category['count']; + $category['category_description'] = &$category['description']; + $category['cat_name'] = &$category['name']; + $category['category_nicename'] = &$category['slug']; + $category['category_parent'] = &$category['parent']; + } +} + + +?> diff --git a/wp-includes/class-IXR.php b/wp-includes/class-IXR.php new file mode 100644 index 0000000..a4bcfbd --- /dev/null +++ b/wp-includes/class-IXR.php @@ -0,0 +1,900 @@ +data = $data; + if (!$type) { + $type = $this->calculateType(); + } + $this->type = $type; + if ($type == 'struct') { + /* Turn all the values in the array in to new IXR_Value objects */ + foreach ($this->data as $key => $value) { + $this->data[$key] = new IXR_Value($value); + } + } + if ($type == 'array') { + for ($i = 0, $j = count($this->data); $i < $j; $i++) { + $this->data[$i] = new IXR_Value($this->data[$i]); + } + } + } + + function calculateType() { + if ($this->data === true || $this->data === false) { + return 'boolean'; + } + if (is_integer($this->data)) { + return 'int'; + } + if (is_double($this->data)) { + return 'double'; + } + // Deal with IXR object types base64 and date + if (is_object($this->data) && is_a($this->data, 'IXR_Date')) { + return 'date'; + } + if (is_object($this->data) && is_a($this->data, 'IXR_Base64')) { + return 'base64'; + } + // If it is a normal PHP object convert it in to a struct + if (is_object($this->data)) { + + $this->data = get_object_vars($this->data); + return 'struct'; + } + if (!is_array($this->data)) { + return 'string'; + } + /* We have an array - is it an array or a struct ? */ + if ($this->isStruct($this->data)) { + return 'struct'; + } else { + return 'array'; + } + } + + function getXml() { + /* Return XML for this value */ + switch ($this->type) { + case 'boolean': + return ''.(($this->data) ? '1' : '0').''; + break; + case 'int': + return ''.$this->data.''; + break; + case 'double': + return ''.$this->data.''; + break; + case 'string': + return ''.htmlspecialchars($this->data).''; + break; + case 'array': + $return = ''."\n"; + foreach ($this->data as $item) { + $return .= ' '.$item->getXml()."\n"; + } + $return .= ''; + return $return; + break; + case 'struct': + $return = ''."\n"; + foreach ($this->data as $name => $value) { + $name = htmlspecialchars($name); + $return .= " $name"; + $return .= $value->getXml()."\n"; + } + $return .= ''; + return $return; + break; + case 'date': + case 'base64': + return $this->data->getXml(); + break; + } + return false; + } + + function isStruct($array) { + /* Nasty function to check if an array is a struct or not */ + $expected = 0; + foreach ($array as $key => $value) { + if ((string)$key != (string)$expected) { + return true; + } + $expected++; + } + return false; + } +} + +/** + * IXR_Message + * + * @package IXR + * @since 1.5 + */ +class IXR_Message { + var $message; + var $messageType; // methodCall / methodResponse / fault + var $faultCode; + var $faultString; + var $methodName; + var $params; + // Current variable stacks + var $_arraystructs = array(); // The stack used to keep track of the current array/struct + var $_arraystructstypes = array(); // Stack keeping track of if things are structs or array + var $_currentStructName = array(); // A stack as well + var $_param; + var $_value; + var $_currentTag; + var $_currentTagContents; + // The XML parser + var $_parser; + function IXR_Message ($message) { + $this->message = $message; + } + function parse() { + // first remove the XML declaration + $this->message = preg_replace('/<\?xml.*?\?'.'>/', '', $this->message); + if (trim($this->message) == '') { + return false; + } + $this->_parser = xml_parser_create(); + // Set XML parser to take the case of tags in to account + xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false); + // Set XML parser callback functions + xml_set_object($this->_parser, $this); + xml_set_element_handler($this->_parser, 'tag_open', 'tag_close'); + xml_set_character_data_handler($this->_parser, 'cdata'); + if (!xml_parse($this->_parser, $this->message)) { + /* die(sprintf('XML error: %s at line %d', + xml_error_string(xml_get_error_code($this->_parser)), + xml_get_current_line_number($this->_parser))); */ + return false; + } + xml_parser_free($this->_parser); + // Grab the error messages, if any + if ($this->messageType == 'fault') { + $this->faultCode = $this->params[0]['faultCode']; + $this->faultString = $this->params[0]['faultString']; + } + return true; + } + function tag_open($parser, $tag, $attr) { + $this->_currentTagContents = ''; + $this->currentTag = $tag; + switch($tag) { + case 'methodCall': + case 'methodResponse': + case 'fault': + $this->messageType = $tag; + break; + /* Deal with stacks of arrays and structs */ + case 'data': // data is to all intents and puposes more interesting than array + $this->_arraystructstypes[] = 'array'; + $this->_arraystructs[] = array(); + break; + case 'struct': + $this->_arraystructstypes[] = 'struct'; + $this->_arraystructs[] = array(); + break; + } + } + function cdata($parser, $cdata) { + $this->_currentTagContents .= $cdata; + } + function tag_close($parser, $tag) { + $valueFlag = false; + switch($tag) { + case 'int': + case 'i4': + $value = (int) trim($this->_currentTagContents); + $valueFlag = true; + break; + case 'double': + $value = (double) trim($this->_currentTagContents); + $valueFlag = true; + break; + case 'string': + $value = $this->_currentTagContents; + $valueFlag = true; + break; + case 'dateTime.iso8601': + $value = new IXR_Date(trim($this->_currentTagContents)); + // $value = $iso->getTimestamp(); + $valueFlag = true; + break; + case 'value': + // "If no type is indicated, the type is string." + if (trim($this->_currentTagContents) != '') { + $value = (string)$this->_currentTagContents; + $valueFlag = true; + } + break; + case 'boolean': + $value = (boolean) trim($this->_currentTagContents); + $valueFlag = true; + break; + case 'base64': + $value = base64_decode( trim( $this->_currentTagContents ) ); + $valueFlag = true; + break; + /* Deal with stacks of arrays and structs */ + case 'data': + case 'struct': + $value = array_pop($this->_arraystructs); + array_pop($this->_arraystructstypes); + $valueFlag = true; + break; + case 'member': + array_pop($this->_currentStructName); + break; + case 'name': + $this->_currentStructName[] = trim($this->_currentTagContents); + break; + case 'methodName': + $this->methodName = trim($this->_currentTagContents); + break; + } + if ($valueFlag) { + if (count($this->_arraystructs) > 0) { + // Add value to struct or array + if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') { + // Add to struct + $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value; + } else { + // Add to array + $this->_arraystructs[count($this->_arraystructs)-1][] = $value; + } + } else { + // Just add as a paramater + $this->params[] = $value; + } + } + $this->_currentTagContents = ''; + } +} + +/** + * IXR_Server + * + * @package IXR + * @since 1.5 + */ +class IXR_Server { + var $data; + var $callbacks = array(); + var $message; + var $capabilities; + function IXR_Server($callbacks = false, $data = false) { + $this->setCapabilities(); + if ($callbacks) { + $this->callbacks = $callbacks; + } + $this->setCallbacks(); + $this->serve($data); + } + function serve($data = false) { + if (!$data) { + global $HTTP_RAW_POST_DATA; + if (!$HTTP_RAW_POST_DATA) { + header( 'Content-Type: text/plain' ); + die('XML-RPC server accepts POST requests only.'); + } + $data = $HTTP_RAW_POST_DATA; + } + $this->message = new IXR_Message($data); + if (!$this->message->parse()) { + $this->error(-32700, 'parse error. not well formed'); + } + if ($this->message->messageType != 'methodCall') { + $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall'); + } + $result = $this->call($this->message->methodName, $this->message->params); + // Is the result an error? + if (is_a($result, 'IXR_Error')) { + $this->error($result); + } + // Encode the result + $r = new IXR_Value($result); + $resultxml = $r->getXml(); + // Create the XML + $xml = << + + + + $resultxml + + + + + +EOD; + // Send it + $this->output($xml); + } + function call($methodname, $args) { + if (!$this->hasMethod($methodname)) { + return new IXR_Error(-32601, 'server error. requested method '. + $methodname.' does not exist.'); + } + $method = $this->callbacks[$methodname]; + // Perform the callback and send the response + if (count($args) == 1) { + // If only one paramater just send that instead of the whole array + $args = $args[0]; + } + // Are we dealing with a function or a method? + if (substr($method, 0, 5) == 'this:') { + // It's a class method - check it exists + $method = substr($method, 5); + if (!method_exists($this, $method)) { + return new IXR_Error(-32601, 'server error. requested class method "'. + $method.'" does not exist.'); + } + // Call the method + $result = $this->$method($args); + } else { + // It's a function - does it exist? + if (is_array($method)) { + if (!method_exists($method[0], $method[1])) { + return new IXR_Error(-32601, 'server error. requested object method "'. + $method[1].'" does not exist.'); + } + } else if (!function_exists($method)) { + return new IXR_Error(-32601, 'server error. requested function "'. + $method.'" does not exist.'); + } + // Call the function + $result = call_user_func($method, $args); + } + return $result; + } + + function error($error, $message = false) { + // Accepts either an error object or an error code and message + if ($message && !is_object($error)) { + $error = new IXR_Error($error, $message); + } + $this->output($error->getXml()); + } + function output($xml) { + $xml = ''."\n".$xml; + $length = strlen($xml); + header('Connection: close'); + header('Content-Length: '.$length); + header('Content-Type: text/xml'); + header('Date: '.date('r')); + echo $xml; + exit; + } + function hasMethod($method) { + return in_array($method, array_keys($this->callbacks)); + } + function setCapabilities() { + // Initialises capabilities array + $this->capabilities = array( + 'xmlrpc' => array( + 'specUrl' => 'http://www.xmlrpc.com/spec', + 'specVersion' => 1 + ), + 'faults_interop' => array( + 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php', + 'specVersion' => 20010516 + ), + 'system.multicall' => array( + 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208', + 'specVersion' => 1 + ), + ); + } + function getCapabilities($args) { + return $this->capabilities; + } + function setCallbacks() { + $this->callbacks['system.getCapabilities'] = 'this:getCapabilities'; + $this->callbacks['system.listMethods'] = 'this:listMethods'; + $this->callbacks['system.multicall'] = 'this:multiCall'; + } + function listMethods($args) { + // Returns a list of methods - uses array_reverse to ensure user defined + // methods are listed before server defined methods + return array_reverse(array_keys($this->callbacks)); + } + function multiCall($methodcalls) { + // See http://www.xmlrpc.com/discuss/msgReader$1208 + $return = array(); + foreach ($methodcalls as $call) { + $method = $call['methodName']; + $params = $call['params']; + if ($method == 'system.multicall') { + $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden'); + } else { + $result = $this->call($method, $params); + } + if (is_a($result, 'IXR_Error')) { + $return[] = array( + 'faultCode' => $result->code, + 'faultString' => $result->message + ); + } else { + $return[] = array($result); + } + } + return $return; + } +} + +/** + * IXR_Request + * + * @package IXR + * @since 1.5 + */ +class IXR_Request { + var $method; + var $args; + var $xml; + function IXR_Request($method, $args) { + $this->method = $method; + $this->args = $args; + $this->xml = << + +{$this->method} + + +EOD; + foreach ($this->args as $arg) { + $this->xml .= ''; + $v = new IXR_Value($arg); + $this->xml .= $v->getXml(); + $this->xml .= "\n"; + } + $this->xml .= ''; + } + function getLength() { + return strlen($this->xml); + } + function getXml() { + return $this->xml; + } +} + +/** + * IXR_Client + * + * @package IXR + * @since 1.5 + */ +class IXR_Client { + var $server; + var $port; + var $path; + var $useragent; + var $headers; + var $response; + var $message = false; + var $debug = false; + var $timeout; + // Storage place for an error message + var $error = false; + function IXR_Client($server, $path = false, $port = 80, $timeout = false) { + if (!$path) { + // Assume we have been given a URL instead + $bits = parse_url($server); + $this->server = $bits['host']; + $this->port = isset($bits['port']) ? $bits['port'] : 80; + $this->path = isset($bits['path']) ? $bits['path'] : '/'; + // Make absolutely sure we have a path + if (!$this->path) { + $this->path = '/'; + } + } else { + $this->server = $server; + $this->path = $path; + $this->port = $port; + } + $this->useragent = 'The Incutio XML-RPC PHP Library'; + $this->timeout = $timeout; + } + function query() { + $args = func_get_args(); + $method = array_shift($args); + $request = new IXR_Request($method, $args); + $length = $request->getLength(); + $xml = $request->getXml(); + $r = "\r\n"; + $request = "POST {$this->path} HTTP/1.0$r"; + + $this->headers['Host'] = $this->server; + $this->headers['Content-Type'] = 'text/xml'; + $this->headers['User-Agent'] = $this->useragent; + $this->headers['Content-Length']= $length; + + foreach( $this->headers as $header => $value ) { + $request .= "{$header}: {$value}{$r}"; + } + $request .= $r; + + $request .= $xml; + // Now send the request + if ($this->debug) { + echo '
    '.htmlspecialchars($request)."\n
    \n\n"; + } + if ($this->timeout) { + $fp = @fsockopen($this->server, $this->port, $errno, $errstr, $this->timeout); + } else { + $fp = @fsockopen($this->server, $this->port, $errno, $errstr); + } + if (!$fp) { + $this->error = new IXR_Error(-32300, "transport error - could not open socket: $errno $errstr"); + return false; + } + fputs($fp, $request); + $contents = ''; + $debug_contents = ''; + $gotFirstLine = false; + $gettingHeaders = true; + while (!feof($fp)) { + $line = fgets($fp, 4096); + if (!$gotFirstLine) { + // Check line for '200' + if (strstr($line, '200') === false) { + $this->error = new IXR_Error(-32301, 'transport error - HTTP status code was not 200'); + return false; + } + $gotFirstLine = true; + } + if (trim($line) == '') { + $gettingHeaders = false; + } + if (!$gettingHeaders) { + $contents .= trim($line); + } + if ($this->debug) { + $debug_contents .= $line; + } + } + if ($this->debug) { + echo '
    '.htmlspecialchars($debug_contents)."\n
    \n\n"; + } + // Now parse what we've got back + $this->message = new IXR_Message($contents); + if (!$this->message->parse()) { + // XML error + $this->error = new IXR_Error(-32700, 'parse error. not well formed'); + return false; + } + // Is the message a fault? + if ($this->message->messageType == 'fault') { + $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString); + return false; + } + // Message must be OK + return true; + } + function getResponse() { + // methodResponses can only have one param - return that + return $this->message->params[0]; + } + function isError() { + return (is_object($this->error)); + } + function getErrorCode() { + return $this->error->code; + } + function getErrorMessage() { + return $this->error->message; + } +} + +/** + * IXR_Error + * + * @package IXR + * @since 1.5 + */ +class IXR_Error { + var $code; + var $message; + function IXR_Error($code, $message) { + $this->code = $code; + // WP adds htmlspecialchars(). See #5666 + $this->message = htmlspecialchars($message); + } + function getXml() { + $xml = << + + + + + faultCode + {$this->code} + + + faultString + {$this->message} + + + + + + +EOD; + return $xml; + } +} + +/** + * IXR_Date + * + * @package IXR + * @since 1.5 + */ +class IXR_Date { + var $year; + var $month; + var $day; + var $hour; + var $minute; + var $second; + var $timezone; + function IXR_Date($time) { + // $time can be a PHP timestamp or an ISO one + if (is_numeric($time)) { + $this->parseTimestamp($time); + } else { + $this->parseIso($time); + } + } + function parseTimestamp($timestamp) { + $this->year = date('Y', $timestamp); + $this->month = date('m', $timestamp); + $this->day = date('d', $timestamp); + $this->hour = date('H', $timestamp); + $this->minute = date('i', $timestamp); + $this->second = date('s', $timestamp); + // WP adds timezone. See #2036 + $this->timezone = ''; + } + function parseIso($iso) { + $this->year = substr($iso, 0, 4); + $this->month = substr($iso, 4, 2); + $this->day = substr($iso, 6, 2); + $this->hour = substr($iso, 9, 2); + $this->minute = substr($iso, 12, 2); + $this->second = substr($iso, 15, 2); + // WP adds timezone. See #2036 + $this->timezone = substr($iso, 17); + } + function getIso() { + // WP adds timezone. See #2036 + return $this->year.$this->month.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second.$this->timezone; + } + function getXml() { + return ''.$this->getIso().''; + } + function getTimestamp() { + return mktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year); + } +} + +/** + * IXR_Base64 + * + * @package IXR + * @since 1.5 + */ +class IXR_Base64 { + var $data; + function IXR_Base64($data) { + $this->data = $data; + } + function getXml() { + return ''.base64_encode($this->data).''; + } +} + +/** + * IXR_IntrospectionServer + * + * @package IXR + * @since 1.5 + */ +class IXR_IntrospectionServer extends IXR_Server { + var $signatures; + var $help; + function IXR_IntrospectionServer() { + $this->setCallbacks(); + $this->setCapabilities(); + $this->capabilities['introspection'] = array( + 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html', + 'specVersion' => 1 + ); + $this->addCallback( + 'system.methodSignature', + 'this:methodSignature', + array('array', 'string'), + 'Returns an array describing the return type and required parameters of a method' + ); + $this->addCallback( + 'system.getCapabilities', + 'this:getCapabilities', + array('struct'), + 'Returns a struct describing the XML-RPC specifications supported by this server' + ); + $this->addCallback( + 'system.listMethods', + 'this:listMethods', + array('array'), + 'Returns an array of available methods on this server' + ); + $this->addCallback( + 'system.methodHelp', + 'this:methodHelp', + array('string', 'string'), + 'Returns a documentation string for the specified method' + ); + } + function addCallback($method, $callback, $args, $help) { + $this->callbacks[$method] = $callback; + $this->signatures[$method] = $args; + $this->help[$method] = $help; + } + function call($methodname, $args) { + // Make sure it's in an array + if ($args && !is_array($args)) { + $args = array($args); + } + // Over-rides default call method, adds signature check + if (!$this->hasMethod($methodname)) { + return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.'); + } + $method = $this->callbacks[$methodname]; + $signature = $this->signatures[$methodname]; + $returnType = array_shift($signature); + // Check the number of arguments + if (count($args) != count($signature)) { + return new IXR_Error(-32602, 'server error. wrong number of method parameters'); + } + // Check the argument types + $ok = true; + $argsbackup = $args; + for ($i = 0, $j = count($args); $i < $j; $i++) { + $arg = array_shift($args); + $type = array_shift($signature); + switch ($type) { + case 'int': + case 'i4': + if (is_array($arg) || !is_int($arg)) { + $ok = false; + } + break; + case 'base64': + case 'string': + if (!is_string($arg)) { + $ok = false; + } + break; + case 'boolean': + if ($arg !== false && $arg !== true) { + $ok = false; + } + break; + case 'float': + case 'double': + if (!is_float($arg)) { + $ok = false; + } + break; + case 'date': + case 'dateTime.iso8601': + if (!is_a($arg, 'IXR_Date')) { + $ok = false; + } + break; + } + if (!$ok) { + return new IXR_Error(-32602, 'server error. invalid method parameters'); + } + } + // It passed the test - run the "real" method call + return parent::call($methodname, $argsbackup); + } + function methodSignature($method) { + if (!$this->hasMethod($method)) { + return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.'); + } + // We should be returning an array of types + $types = $this->signatures[$method]; + $return = array(); + foreach ($types as $type) { + switch ($type) { + case 'string': + $return[] = 'string'; + break; + case 'int': + case 'i4': + $return[] = 42; + break; + case 'double': + $return[] = 3.1415; + break; + case 'dateTime.iso8601': + $return[] = new IXR_Date(time()); + break; + case 'boolean': + $return[] = true; + break; + case 'base64': + $return[] = new IXR_Base64('base64'); + break; + case 'array': + $return[] = array('array'); + break; + case 'struct': + $return[] = array('struct' => 'struct'); + break; + } + } + return $return; + } + function methodHelp($method) { + return $this->help[$method]; + } +} + +/** + * IXR_ClientMulticall + * + * @package IXR + * @since 1.5 + */ +class IXR_ClientMulticall extends IXR_Client { + var $calls = array(); + function IXR_ClientMulticall($server, $path = false, $port = 80) { + parent::IXR_Client($server, $path, $port); + $this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)'; + } + function addCall() { + $args = func_get_args(); + $methodName = array_shift($args); + $struct = array( + 'methodName' => $methodName, + 'params' => $args + ); + $this->calls[] = $struct; + } + function query() { + // Prepare multicall, then call the parent::query() method + return parent::query('system.multicall', $this->calls); + } +} + +?> diff --git a/wp-includes/class-feed.php b/wp-includes/class-feed.php new file mode 100644 index 0000000..7012439 --- /dev/null +++ b/wp-includes/class-feed.php @@ -0,0 +1,103 @@ +name = 'feed_' . $filename; + $this->mod_name = 'feed_mod_' . $filename; + $this->lifetime = apply_filters('wp_feed_cache_transient_lifetime', $this->lifetime); + } + + function save($data) { + if ( is_a($data, 'SimplePie') ) + $data = $data->data; + + set_transient($this->name, $data, $this->lifetime); + set_transient($this->mod_name, time(), $this->lifetime); + return true; + } + + function load() { + return get_transient($this->name); + } + + function mtime() { + return get_transient($this->mod_name); + } + + function touch() { + return set_transient($this->mod_name, time(), $this->lifetime); + } + + function unlink() { + delete_transient($this->name); + delete_transient($this->mod_name); + return true; + } +} + +class WP_SimplePie_File extends SimplePie_File { + + function WP_SimplePie_File($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) { + $this->url = $url; + $this->timeout = $timeout; + $this->redirects = $redirects; + $this->headers = $headers; + $this->useragent = $useragent; + + $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE; + + if ( preg_match('/^http(s)?:\/\//i', $url) ) { + $args = array( 'timeout' => $this->timeout, 'redirection' => $this->redirects); + + if ( !empty($this->headers) ) + $args['headers'] = $this->headers; + + if ( SIMPLEPIE_USERAGENT != $this->useragent ) //Use default WP user agent unless custom has been specified + $args['user-agent'] = $this->useragent; + + $res = wp_remote_request($url, $args); + + if ( is_wp_error($res) ) { + $this->error = 'WP HTTP Error: ' . $res->get_error_message(); + $this->success = false; + } else { + $this->headers = $res['headers']; + $this->body = $res['body']; + $this->status_code = $res['response']['code']; + } + } else { + if ( ! $this->body = file_get_contents($url) ) { + $this->error = 'file_get_contents could not read the file'; + $this->success = false; + } + } + } +} \ No newline at end of file diff --git a/wp-includes/class-phpass.php b/wp-includes/class-phpass.php new file mode 100644 index 0000000..93f4536 --- /dev/null +++ b/wp-includes/class-phpass.php @@ -0,0 +1,258 @@ + in 2004-2006 and placed in +# the public domain. +# +# There's absolutely no warranty. +# +# Please be sure to update the Version line if you edit this file in any way. +# It is suggested that you leave the main version number intact, but indicate +# your project name (after the slash) and add your own revision information. +# +# Please do not change the "private" password hashing method implemented in +# here, thereby making your hashes incompatible. However, if you must, please +# change the hash type identifier (the "$P$") to something different. +# +# Obviously, since this code is in the public domain, the above are not +# requirements (there can be none), but merely suggestions. +# + +/** + * Portable PHP password hashing framework. + * + * @package phpass + * @version 0.1 / genuine + * @link http://www.openwall.com/phpass/ + * @since 2.5 + */ +class PasswordHash { + var $itoa64; + var $iteration_count_log2; + var $portable_hashes; + var $random_state; + + function PasswordHash($iteration_count_log2, $portable_hashes) + { + $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + + if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) + $iteration_count_log2 = 8; + $this->iteration_count_log2 = $iteration_count_log2; + + $this->portable_hashes = $portable_hashes; + + $this->random_state = microtime() . (function_exists('getmypid') ? getmypid() : '') . uniqid(rand(), TRUE); + + } + + function get_random_bytes($count) + { + $output = ''; + if (($fh = @fopen('/dev/urandom', 'rb'))) { + $output = fread($fh, $count); + fclose($fh); + } + + if (strlen($output) < $count) { + $output = ''; + for ($i = 0; $i < $count; $i += 16) { + $this->random_state = + md5(microtime() . $this->random_state); + $output .= + pack('H*', md5($this->random_state)); + } + $output = substr($output, 0, $count); + } + + return $output; + } + + function encode64($input, $count) + { + $output = ''; + $i = 0; + do { + $value = ord($input[$i++]); + $output .= $this->itoa64[$value & 0x3f]; + if ($i < $count) + $value |= ord($input[$i]) << 8; + $output .= $this->itoa64[($value >> 6) & 0x3f]; + if ($i++ >= $count) + break; + if ($i < $count) + $value |= ord($input[$i]) << 16; + $output .= $this->itoa64[($value >> 12) & 0x3f]; + if ($i++ >= $count) + break; + $output .= $this->itoa64[($value >> 18) & 0x3f]; + } while ($i < $count); + + return $output; + } + + function gensalt_private($input) + { + $output = '$P$'; + $output .= $this->itoa64[min($this->iteration_count_log2 + + ((PHP_VERSION >= '5') ? 5 : 3), 30)]; + $output .= $this->encode64($input, 6); + + return $output; + } + + function crypt_private($password, $setting) + { + $output = '*0'; + if (substr($setting, 0, 2) == $output) + $output = '*1'; + + if (substr($setting, 0, 3) != '$P$') + return $output; + + $count_log2 = strpos($this->itoa64, $setting[3]); + if ($count_log2 < 7 || $count_log2 > 30) + return $output; + + $count = 1 << $count_log2; + + $salt = substr($setting, 4, 8); + if (strlen($salt) != 8) + return $output; + + # We're kind of forced to use MD5 here since it's the only + # cryptographic primitive available in all versions of PHP + # currently in use. To implement our own low-level crypto + # in PHP would result in much worse performance and + # consequently in lower iteration counts and hashes that are + # quicker to crack (by non-PHP code). + if (PHP_VERSION >= '5') { + $hash = md5($salt . $password, TRUE); + do { + $hash = md5($hash . $password, TRUE); + } while (--$count); + } else { + $hash = pack('H*', md5($salt . $password)); + do { + $hash = pack('H*', md5($hash . $password)); + } while (--$count); + } + + $output = substr($setting, 0, 12); + $output .= $this->encode64($hash, 16); + + return $output; + } + + function gensalt_extended($input) + { + $count_log2 = min($this->iteration_count_log2 + 8, 24); + # This should be odd to not reveal weak DES keys, and the + # maximum valid value is (2**24 - 1) which is odd anyway. + $count = (1 << $count_log2) - 1; + + $output = '_'; + $output .= $this->itoa64[$count & 0x3f]; + $output .= $this->itoa64[($count >> 6) & 0x3f]; + $output .= $this->itoa64[($count >> 12) & 0x3f]; + $output .= $this->itoa64[($count >> 18) & 0x3f]; + + $output .= $this->encode64($input, 3); + + return $output; + } + + function gensalt_blowfish($input) + { + # This one needs to use a different order of characters and a + # different encoding scheme from the one in encode64() above. + # We care because the last character in our encoded string will + # only represent 2 bits. While two known implementations of + # bcrypt will happily accept and correct a salt string which + # has the 4 unused bits set to non-zero, we do not want to take + # chances and we also do not want to waste an additional byte + # of entropy. + $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + + $output = '$2a$'; + $output .= chr(ord('0') + $this->iteration_count_log2 / 10); + $output .= chr(ord('0') + $this->iteration_count_log2 % 10); + $output .= '$'; + + $i = 0; + do { + $c1 = ord($input[$i++]); + $output .= $itoa64[$c1 >> 2]; + $c1 = ($c1 & 0x03) << 4; + if ($i >= 16) { + $output .= $itoa64[$c1]; + break; + } + + $c2 = ord($input[$i++]); + $c1 |= $c2 >> 4; + $output .= $itoa64[$c1]; + $c1 = ($c2 & 0x0f) << 2; + + $c2 = ord($input[$i++]); + $c1 |= $c2 >> 6; + $output .= $itoa64[$c1]; + $output .= $itoa64[$c2 & 0x3f]; + } while (1); + + return $output; + } + + function HashPassword($password) + { + $random = ''; + + if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) { + $random = $this->get_random_bytes(16); + $hash = + crypt($password, $this->gensalt_blowfish($random)); + if (strlen($hash) == 60) + return $hash; + } + + if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) { + if (strlen($random) < 3) + $random = $this->get_random_bytes(3); + $hash = + crypt($password, $this->gensalt_extended($random)); + if (strlen($hash) == 20) + return $hash; + } + + if (strlen($random) < 6) + $random = $this->get_random_bytes(6); + $hash = + $this->crypt_private($password, + $this->gensalt_private($random)); + if (strlen($hash) == 34) + return $hash; + + # Returning '*' on error is safe here, but would _not_ be safe + # in a crypt(3)-like function used _both_ for generating new + # hashes and for validating passwords against existing hashes. + return '*'; + } + + function CheckPassword($password, $stored_hash) + { + $hash = $this->crypt_private($password, $stored_hash); + if ($hash[0] == '*') + $hash = crypt($password, $stored_hash); + + return $hash == $stored_hash; + } +} + +?> diff --git a/wp-includes/class-phpmailer.php b/wp-includes/class-phpmailer.php new file mode 100644 index 0000000..e9fb2b0 --- /dev/null +++ b/wp-includes/class-phpmailer.php @@ -0,0 +1,1921 @@ +ContentType = 'text/html'; + } else { + $this->ContentType = 'text/plain'; + } + } + + /** + * Sets Mailer to send message using SMTP. + * @return void + */ + function IsSMTP() { + $this->Mailer = 'smtp'; + } + + /** + * Sets Mailer to send message using PHP mail() function. + * @return void + */ + function IsMail() { + $this->Mailer = 'mail'; + } + + /** + * Sets Mailer to send message using the $Sendmail program. + * @return void + */ + function IsSendmail() { + $this->Mailer = 'sendmail'; + } + + /** + * Sets Mailer to send message using the qmail MTA. + * @return void + */ + function IsQmail() { + $this->Sendmail = '/var/qmail/bin/sendmail'; + $this->Mailer = 'sendmail'; + } + + ///////////////////////////////////////////////// + // METHODS, RECIPIENTS + ///////////////////////////////////////////////// + + /** + * Adds a "To" address. + * @param string $address + * @param string $name + * @return void + */ + function AddAddress($address, $name = '') { + $cur = count($this->to); + $this->to[$cur][0] = trim($address); + $this->to[$cur][1] = $name; + } + + /** + * Adds a "Cc" address. Note: this function works + * with the SMTP mailer on win32, not with the "mail" + * mailer. + * @param string $address + * @param string $name + * @return void + */ + function AddCC($address, $name = '') { + $cur = count($this->cc); + $this->cc[$cur][0] = trim($address); + $this->cc[$cur][1] = $name; + } + + /** + * Adds a "Bcc" address. Note: this function works + * with the SMTP mailer on win32, not with the "mail" + * mailer. + * @param string $address + * @param string $name + * @return void + */ + function AddBCC($address, $name = '') { + $cur = count($this->bcc); + $this->bcc[$cur][0] = trim($address); + $this->bcc[$cur][1] = $name; + } + + /** + * Adds a "Reply-To" address. + * @param string $address + * @param string $name + * @return void + */ + function AddReplyTo($address, $name = '') { + $cur = count($this->ReplyTo); + $this->ReplyTo[$cur][0] = trim($address); + $this->ReplyTo[$cur][1] = $name; + } + + ///////////////////////////////////////////////// + // METHODS, MAIL SENDING + ///////////////////////////////////////////////// + + /** + * Creates message and assigns Mailer. If the message is + * not sent successfully then it returns false. Use the ErrorInfo + * variable to view description of the error. + * @return bool + */ + function Send() { + $header = ''; + $body = ''; + $result = true; + + if((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { + $this->SetError($this->Lang('provide_address')); + return false; + } + + /* Set whether the message is multipart/alternative */ + if(!empty($this->AltBody)) { + $this->ContentType = 'multipart/alternative'; + } + + $this->error_count = 0; // reset errors + $this->SetMessageType(); + $header .= $this->CreateHeader(); + $body = $this->CreateBody(); + + if($body == '') { + return false; + } + + /* Choose the mailer */ + switch($this->Mailer) { + case 'sendmail': + $result = $this->SendmailSend($header, $body); + break; + case 'smtp': + $result = $this->SmtpSend($header, $body); + break; + case 'mail': + $result = $this->MailSend($header, $body); + break; + default: + $result = $this->MailSend($header, $body); + break; + //$this->SetError($this->Mailer . $this->Lang('mailer_not_supported')); + //$result = false; + //break; + } + + return $result; + } + + /** + * Sends mail using the $Sendmail program. + * @access private + * @return bool + */ + function SendmailSend($header, $body) { + if ($this->Sender != '') { + $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); + } else { + $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); + } + + if(!@$mail = popen($sendmail, 'w')) { + $this->SetError($this->Lang('execute') . $this->Sendmail); + return false; + } + + fputs($mail, $header); + fputs($mail, $body); + + $result = pclose($mail); + if (version_compare(phpversion(), '4.2.3') == -1) { + $result = $result >> 8 & 0xFF; + } + if($result != 0) { + $this->SetError($this->Lang('execute') . $this->Sendmail); + return false; + } + return true; + } + + /** + * Sends mail using the PHP mail() function. + * @access private + * @return bool + */ + function MailSend($header, $body) { + + $to = ''; + for($i = 0; $i < count($this->to); $i++) { + if($i != 0) { $to .= ', '; } + $to .= $this->AddrFormat($this->to[$i]); + } + + $toArr = split(',', $to); + + $params = sprintf("-oi -f %s", $this->Sender); + if ($this->Sender != '' && strlen(ini_get('safe_mode')) < 1) { + $old_from = ini_get('sendmail_from'); + ini_set('sendmail_from', $this->Sender); + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $key => $val) { + $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + } + } else { + $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + } + } else { + if ($this->SingleTo === true && count($toArr) > 1) { + foreach ($toArr as $key => $val) { + $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); + } + } else { + $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header); + } + } + + if (isset($old_from)) { + ini_set('sendmail_from', $old_from); + } + + if(!$rt) { + $this->SetError($this->Lang('instantiate')); + return false; + } + + return true; + } + + /** + * Sends mail via SMTP using PhpSMTP (Author: + * Chris Ryan). Returns bool. Returns false if there is a + * bad MAIL FROM, RCPT, or DATA input. + * @access private + * @return bool + */ + function SmtpSend($header, $body) { + include_once($this->PluginDir . 'class-smtp.php'); + $error = ''; + $bad_rcpt = array(); + + if(!$this->SmtpConnect()) { + return false; + } + + $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; + if(!$this->smtp->Mail($smtp_from)) { + $error = $this->Lang('from_failed') . $smtp_from; + $this->SetError($error); + $this->smtp->Reset(); + return false; + } + + /* Attempt to send attach all recipients */ + for($i = 0; $i < count($this->to); $i++) { + if(!$this->smtp->Recipient($this->to[$i][0])) { + $bad_rcpt[] = $this->to[$i][0]; + } + } + for($i = 0; $i < count($this->cc); $i++) { + if(!$this->smtp->Recipient($this->cc[$i][0])) { + $bad_rcpt[] = $this->cc[$i][0]; + } + } + for($i = 0; $i < count($this->bcc); $i++) { + if(!$this->smtp->Recipient($this->bcc[$i][0])) { + $bad_rcpt[] = $this->bcc[$i][0]; + } + } + + if(count($bad_rcpt) > 0) { // Create error message + for($i = 0; $i < count($bad_rcpt); $i++) { + if($i != 0) { + $error .= ', '; + } + $error .= $bad_rcpt[$i]; + } + $error = $this->Lang('recipients_failed') . $error; + $this->SetError($error); + $this->smtp->Reset(); + return false; + } + + if(!$this->smtp->Data($header . $body)) { + $this->SetError($this->Lang('data_not_accepted')); + $this->smtp->Reset(); + return false; + } + if($this->SMTPKeepAlive == true) { + $this->smtp->Reset(); + } else { + $this->SmtpClose(); + } + + return true; + } + + /** + * Initiates a connection to an SMTP server. Returns false if the + * operation failed. + * @access private + * @return bool + */ + function SmtpConnect() { + if($this->smtp == NULL) { + $this->smtp = new SMTP(); + } + + $this->smtp->do_debug = $this->SMTPDebug; + $hosts = explode(';', $this->Host); + $index = 0; + $connection = ($this->smtp->Connected()); + + /* Retry while there is no connection */ + while($index < count($hosts) && $connection == false) { + $hostinfo = array(); + if(eregi('^(.+):([0-9]+)$', $hosts[$index], $hostinfo)) { + $host = $hostinfo[1]; + $port = $hostinfo[2]; + } else { + $host = $hosts[$index]; + $port = $this->Port; + } + + if($this->smtp->Connect(((!empty($this->SMTPSecure))?$this->SMTPSecure.'://':'').$host, $port, $this->Timeout)) { + if ($this->Helo != '') { + $this->smtp->Hello($this->Helo); + } else { + $this->smtp->Hello($this->ServerHostname()); + } + + $connection = true; + if($this->SMTPAuth) { + if(!$this->smtp->Authenticate($this->Username, $this->Password)) { + $this->SetError($this->Lang('authenticate')); + $this->smtp->Reset(); + $connection = false; + } + } + } + $index++; + } + if(!$connection) { + $this->SetError($this->Lang('connect_host')); + } + + return $connection; + } + + /** + * Closes the active SMTP session if one exists. + * @return void + */ + function SmtpClose() { + if($this->smtp != NULL) { + if($this->smtp->Connected()) { + $this->smtp->Quit(); + $this->smtp->Close(); + } + } + } + + /** + * Sets the language for all class error messages. Returns false + * if it cannot load the language file. The default language type + * is English. + * @param string $lang_type Type of language (e.g. Portuguese: "br") + * @param string $lang_path Path to the language file directory + * @access public + * @return bool + */ + function SetLanguage($lang_type, $lang_path = 'language/') { + if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php')) { + include($lang_path.'phpmailer.lang-'.$lang_type.'.php'); + } elseif (file_exists($lang_path.'phpmailer.lang-en.php')) { + include($lang_path.'phpmailer.lang-en.php'); + } else { + $PHPMAILER_LANG = array(); + $PHPMAILER_LANG["provide_address"] = 'You must provide at least one ' . + $PHPMAILER_LANG["mailer_not_supported"] = ' mailer is not supported.'; + $PHPMAILER_LANG["execute"] = 'Could not execute: '; + $PHPMAILER_LANG["instantiate"] = 'Could not instantiate mail function.'; + $PHPMAILER_LANG["authenticate"] = 'SMTP Error: Could not authenticate.'; + $PHPMAILER_LANG["from_failed"] = 'The following From address failed: '; + $PHPMAILER_LANG["recipients_failed"] = 'SMTP Error: The following ' . + $PHPMAILER_LANG["data_not_accepted"] = 'SMTP Error: Data not accepted.'; + $PHPMAILER_LANG["connect_host"] = 'SMTP Error: Could not connect to SMTP host.'; + $PHPMAILER_LANG["file_access"] = 'Could not access file: '; + $PHPMAILER_LANG["file_open"] = 'File Error: Could not open file: '; + $PHPMAILER_LANG["encoding"] = 'Unknown encoding: '; + $PHPMAILER_LANG["signing"] = 'Signing Error: '; + } + $this->language = $PHPMAILER_LANG; + + return true; + } + + ///////////////////////////////////////////////// + // METHODS, MESSAGE CREATION + ///////////////////////////////////////////////// + + /** + * Creates recipient headers. + * @access private + * @return string + */ + function AddrAppend($type, $addr) { + $addr_str = $type . ': '; + $addr_str .= $this->AddrFormat($addr[0]); + if(count($addr) > 1) { + for($i = 1; $i < count($addr); $i++) { + $addr_str .= ', ' . $this->AddrFormat($addr[$i]); + } + } + $addr_str .= $this->LE; + + return $addr_str; + } + + /** + * Formats an address correctly. + * @access private + * @return string + */ + function AddrFormat($addr) { + if(empty($addr[1])) { + $formatted = $this->SecureHeader($addr[0]); + } else { + $formatted = $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; + } + + return $formatted; + } + + /** + * Wraps message for use with mailers that do not + * automatically perform wrapping and for quoted-printable. + * Original written by philippe. + * @access private + * @return string + */ + function WrapText($message, $length, $qp_mode = false) { + $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; + // If utf-8 encoding is used, we will need to make sure we don't + // split multibyte characters when we wrap + $is_utf8 = (strtolower($this->CharSet) == "utf-8"); + + $message = $this->FixEOL($message); + if (substr($message, -1) == $this->LE) { + $message = substr($message, 0, -1); + } + + $line = explode($this->LE, $message); + $message = ''; + for ($i=0 ;$i < count($line); $i++) { + $line_part = explode(' ', $line[$i]); + $buf = ''; + for ($e = 0; $e $length)) { + $space_left = $length - strlen($buf) - 1; + if ($e != 0) { + if ($space_left > 20) { + $len = $space_left; + if ($is_utf8) { + $len = $this->UTF8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + $buf .= ' ' . $part; + $message .= $buf . sprintf("=%s", $this->LE); + } else { + $message .= $buf . $soft_break; + } + $buf = ''; + } + while (strlen($word) > 0) { + $len = $length; + if ($is_utf8) { + $len = $this->UTF8CharBoundary($word, $len); + } elseif (substr($word, $len - 1, 1) == "=") { + $len--; + } elseif (substr($word, $len - 2, 1) == "=") { + $len -= 2; + } + $part = substr($word, 0, $len); + $word = substr($word, $len); + + if (strlen($word) > 0) { + $message .= $part . sprintf("=%s", $this->LE); + } else { + $buf = $part; + } + } + } else { + $buf_o = $buf; + $buf .= ($e == 0) ? $word : (' ' . $word); + + if (strlen($buf) > $length and $buf_o != '') { + $message .= $buf_o . $soft_break; + $buf = $word; + } + } + } + $message .= $buf . $this->LE; + } + + return $message; + } + + /** + * Finds last character boundary prior to maxLength in a utf-8 + * quoted (printable) encoded string. + * Original written by Colin Brown. + * @access private + * @param string $encodedText utf-8 QP text + * @param int $maxLength find last character boundary prior to this length + * @return int + */ + function UTF8CharBoundary($encodedText, $maxLength) { + $foundSplitPos = false; + $lookBack = 3; + while (!$foundSplitPos) { + $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); + $encodedCharPos = strpos($lastChunk, "="); + if ($encodedCharPos !== false) { + // Found start of encoded character byte within $lookBack block. + // Check the encoded byte value (the 2 chars after the '=') + $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); + $dec = hexdec($hex); + if ($dec < 128) { // Single byte character. + // If the encoded char was found at pos 0, it will fit + // otherwise reduce maxLength to start of the encoded char + $maxLength = ($encodedCharPos == 0) ? $maxLength : + $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec >= 192) { // First byte of a multi byte character + // Reduce maxLength to split at start of character + $maxLength = $maxLength - ($lookBack - $encodedCharPos); + $foundSplitPos = true; + } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back + $lookBack += 3; + } + } else { + // No encoded character found + $foundSplitPos = true; + } + } + return $maxLength; + } + + /** + * Set the body wrapping. + * @access private + * @return void + */ + function SetWordWrap() { + if($this->WordWrap < 1) { + return; + } + + switch($this->message_type) { + case 'alt': + /* fall through */ + case 'alt_attachments': + $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); + break; + default: + $this->Body = $this->WrapText($this->Body, $this->WordWrap); + break; + } + } + + /** + * Assembles message header. + * @access private + * @return string + */ + function CreateHeader() { + $result = ''; + + /* Set the boundaries */ + $uniq_id = md5(uniqid(time())); + $this->boundary[1] = 'b1_' . $uniq_id; + $this->boundary[2] = 'b2_' . $uniq_id; + + $result .= $this->HeaderLine('Date', $this->RFCDate()); + if($this->Sender == '') { + $result .= $this->HeaderLine('Return-Path', trim($this->From)); + } else { + $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); + } + + /* To be created automatically by mail() */ + if($this->Mailer != 'mail') { + if(count($this->to) > 0) { + $result .= $this->AddrAppend('To', $this->to); + } elseif (count($this->cc) == 0) { + $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); + } + } + + $from = array(); + $from[0][0] = trim($this->From); + $from[0][1] = $this->FromName; + $result .= $this->AddrAppend('From', $from); + + /* sendmail and mail() extract Cc from the header before sending */ + if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->cc) > 0)) { + $result .= $this->AddrAppend('Cc', $this->cc); + } + + /* sendmail and mail() extract Bcc from the header before sending */ + if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { + $result .= $this->AddrAppend('Bcc', $this->bcc); + } + + if(count($this->ReplyTo) > 0) { + $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); + } + + /* mail() sets the subject itself */ + if($this->Mailer != 'mail') { + $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); + } + + if($this->MessageID != '') { + $result .= $this->HeaderLine('Message-ID',$this->MessageID); + } else { + $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); + } + $result .= $this->HeaderLine('X-Priority', $this->Priority); + $result .= $this->HeaderLine('X-Mailer', 'PHPMailer (phpmailer.sourceforge.net) [version ' . $this->Version . ']'); + + if($this->ConfirmReadingTo != '') { + $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); + } + + // Add custom headers + for($index = 0; $index < count($this->CustomHeader); $index++) { + $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); + } + if (!$this->sign_key_file) { + $result .= $this->HeaderLine('MIME-Version', '1.0'); + $result .= $this->GetMailMIME(); + } + + return $result; + } + + /** + * Returns the message MIME. + * @access private + * @return string + */ + function GetMailMIME() { + $result = ''; + switch($this->message_type) { + case 'plain': + $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); + $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet); + break; + case 'attachments': + /* fall through */ + case 'alt_attachments': + if($this->InlineImageExists()){ + $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE); + } else { + $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + } + break; + case 'alt': + $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); + $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); + break; + } + + if($this->Mailer != 'mail') { + $result .= $this->LE.$this->LE; + } + + return $result; + } + + /** + * Assembles the message body. Returns an empty string on failure. + * @access private + * @return string + */ + function CreateBody() { + $result = ''; + if ($this->sign_key_file) { + $result .= $this->GetMailMIME(); + } + + $this->SetWordWrap(); + + switch($this->message_type) { + case 'alt': + $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); + $result .= $this->EncodeString($this->AltBody, $this->Encoding); + $result .= $this->LE.$this->LE; + $result .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); + $result .= $this->EncodeString($this->Body, $this->Encoding); + $result .= $this->LE.$this->LE; + $result .= $this->EndBoundary($this->boundary[1]); + break; + case 'plain': + $result .= $this->EncodeString($this->Body, $this->Encoding); + break; + case 'attachments': + $result .= $this->GetBoundary($this->boundary[1], '', '', ''); + $result .= $this->EncodeString($this->Body, $this->Encoding); + $result .= $this->LE; + $result .= $this->AttachAll(); + break; + case 'alt_attachments': + $result .= sprintf("--%s%s", $this->boundary[1], $this->LE); + $result .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE); + $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body + $result .= $this->EncodeString($this->AltBody, $this->Encoding); + $result .= $this->LE.$this->LE; + $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body + $result .= $this->EncodeString($this->Body, $this->Encoding); + $result .= $this->LE.$this->LE; + $result .= $this->EndBoundary($this->boundary[2]); + $result .= $this->AttachAll(); + break; + } + + if($this->IsError()) { + $result = ''; + } else if ($this->sign_key_file) { + $file = tempnam("", "mail"); + $fp = fopen($file, "w"); + fwrite($fp, $result); + fclose($fp); + $signed = tempnam("", "signed"); + + if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), null)) { + $fp = fopen($signed, "r"); + $result = fread($fp, filesize($this->sign_key_file)); + $result = ''; + while(!feof($fp)){ + $result = $result . fread($fp, 1024); + } + fclose($fp); + } else { + $this->SetError($this->Lang("signing").openssl_error_string()); + $result = ''; + } + + unlink($file); + unlink($signed); + } + + return $result; + } + + /** + * Returns the start of a message boundary. + * @access private + */ + function GetBoundary($boundary, $charSet, $contentType, $encoding) { + $result = ''; + if($charSet == '') { + $charSet = $this->CharSet; + } + if($contentType == '') { + $contentType = $this->ContentType; + } + if($encoding == '') { + $encoding = $this->Encoding; + } + $result .= $this->TextLine('--' . $boundary); + $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet); + $result .= $this->LE; + $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); + $result .= $this->LE; + + return $result; + } + + /** + * Returns the end of a message boundary. + * @access private + */ + function EndBoundary($boundary) { + return $this->LE . '--' . $boundary . '--' . $this->LE; + } + + /** + * Sets the message type. + * @access private + * @return void + */ + function SetMessageType() { + if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) { + $this->message_type = 'plain'; + } else { + if(count($this->attachment) > 0) { + $this->message_type = 'attachments'; + } + if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) { + $this->message_type = 'alt'; + } + if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) { + $this->message_type = 'alt_attachments'; + } + } + } + + /* Returns a formatted header line. + * @access private + * @return string + */ + function HeaderLine($name, $value) { + return $name . ': ' . $value . $this->LE; + } + + /** + * Returns a formatted mail line. + * @access private + * @return string + */ + function TextLine($value) { + return $value . $this->LE; + } + + ///////////////////////////////////////////////// + // CLASS METHODS, ATTACHMENTS + ///////////////////////////////////////////////// + + /** + * Adds an attachment from a path on the filesystem. + * Returns false if the file could not be found + * or accessed. + * @param string $path Path to the attachment. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { + if(!@is_file($path)) { + $this->SetError($this->Lang('file_access') . $path); + return false; + } + + $filename = basename($path); + if($name == '') { + $name = $filename; + } + + $cur = count($this->attachment); + $this->attachment[$cur][0] = $path; + $this->attachment[$cur][1] = $filename; + $this->attachment[$cur][2] = $name; + $this->attachment[$cur][3] = $encoding; + $this->attachment[$cur][4] = $type; + $this->attachment[$cur][5] = false; // isStringAttachment + $this->attachment[$cur][6] = 'attachment'; + $this->attachment[$cur][7] = 0; + + return true; + } + + /** + * Attaches all fs, string, and binary attachments to the message. + * Returns an empty string on failure. + * @access private + * @return string + */ + function AttachAll() { + /* Return text of body */ + $mime = array(); + + /* Add all attachments */ + for($i = 0; $i < count($this->attachment); $i++) { + /* Check for string attachment */ + $bString = $this->attachment[$i][5]; + if ($bString) { + $string = $this->attachment[$i][0]; + } else { + $path = $this->attachment[$i][0]; + } + + $filename = $this->attachment[$i][1]; + $name = $this->attachment[$i][2]; + $encoding = $this->attachment[$i][3]; + $type = $this->attachment[$i][4]; + $disposition = $this->attachment[$i][6]; + $cid = $this->attachment[$i][7]; + + $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE); + $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); + $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); + + if($disposition == 'inline') { + $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); + } + + $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); + + /* Encode as string attachment */ + if($bString) { + $mime[] = $this->EncodeString($string, $encoding); + if($this->IsError()) { + return ''; + } + $mime[] = $this->LE.$this->LE; + } else { + $mime[] = $this->EncodeFile($path, $encoding); + if($this->IsError()) { + return ''; + } + $mime[] = $this->LE.$this->LE; + } + } + + $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE); + + return join('', $mime); + } + + /** + * Encodes attachment in requested format. Returns an + * empty string on failure. + * @access private + * @return string + */ + function EncodeFile ($path, $encoding = 'base64') { + if(!@$fd = fopen($path, 'rb')) { + $this->SetError($this->Lang('file_open') . $path); + return ''; + } + $magic_quotes = get_magic_quotes_runtime(); + set_magic_quotes_runtime(0); + $file_buffer = fread($fd, filesize($path)); + $file_buffer = $this->EncodeString($file_buffer, $encoding); + fclose($fd); + set_magic_quotes_runtime($magic_quotes); + + return $file_buffer; + } + + /** + * Encodes string to requested format. Returns an + * empty string on failure. + * @access private + * @return string + */ + function EncodeString ($str, $encoding = 'base64') { + $encoded = ''; + switch(strtolower($encoding)) { + case 'base64': + /* chunk_split is found in PHP >= 3.0.6 */ + $encoded = chunk_split(base64_encode($str), 76, $this->LE); + break; + case '7bit': + case '8bit': + $encoded = $this->FixEOL($str); + if (substr($encoded, -(strlen($this->LE))) != $this->LE) + $encoded .= $this->LE; + break; + case 'binary': + $encoded = $str; + break; + case 'quoted-printable': + $encoded = $this->EncodeQP($str); + break; + default: + $this->SetError($this->Lang('encoding') . $encoding); + break; + } + return $encoded; + } + + /** + * Encode a header string to best of Q, B, quoted or none. + * @access private + * @return string + */ + function EncodeHeader ($str, $position = 'text') { + $x = 0; + + switch (strtolower($position)) { + case 'phrase': + if (!preg_match('/[\200-\377]/', $str)) { + /* Can't use addslashes as we don't know what value has magic_quotes_sybase. */ + $encoded = addcslashes($str, "\0..\37\177\\\""); + if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { + return ($encoded); + } else { + return ("\"$encoded\""); + } + } + $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); + break; + case 'comment': + $x = preg_match_all('/[()"]/', $str, $matches); + /* Fall-through */ + case 'text': + default: + $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); + break; + } + + if ($x == 0) { + return ($str); + } + + $maxlen = 75 - 7 - strlen($this->CharSet); + /* Try to select the encoding which should produce the shortest output */ + if (strlen($str)/3 < $x) { + $encoding = 'B'; + if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { + // Use a custom function which correctly encodes and wraps long + // multibyte strings without breaking lines within a character + $encoded = $this->Base64EncodeWrapMB($str); + } else { + $encoded = base64_encode($str); + $maxlen -= $maxlen % 4; + $encoded = trim(chunk_split($encoded, $maxlen, "\n")); + } + } else { + $encoding = 'Q'; + $encoded = $this->EncodeQ($str, $position); + $encoded = $this->WrapText($encoded, $maxlen, true); + $encoded = str_replace('='.$this->LE, "\n", trim($encoded)); + } + + $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); + $encoded = trim(str_replace("\n", $this->LE, $encoded)); + + return $encoded; + } + + /** + * Checks if a string contains multibyte characters. + * @access private + * @param string $str multi-byte text to wrap encode + * @return bool + */ + function HasMultiBytes($str) { + if (function_exists('mb_strlen')) { + return (strlen($str) > mb_strlen($str, $this->CharSet)); + } else { // Assume no multibytes (we can't handle without mbstring functions anyway) + return False; + } + } + + /** + * Correctly encodes and wraps long multibyte strings for mail headers + * without breaking lines within a character. + * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php + * @access private + * @param string $str multi-byte text to wrap encode + * @return string + */ + function Base64EncodeWrapMB($str) { + $start = "=?".$this->CharSet."?B?"; + $end = "?="; + $encoded = ""; + + $mb_length = mb_strlen($str, $this->CharSet); + // Each line must have length <= 75, including $start and $end + $length = 75 - strlen($start) - strlen($end); + // Average multi-byte ratio + $ratio = $mb_length / strlen($str); + // Base64 has a 4:3 ratio + $offset = $avgLength = floor($length * $ratio * .75); + + for ($i = 0; $i < $mb_length; $i += $offset) { + $lookBack = 0; + + do { + $offset = $avgLength - $lookBack; + $chunk = mb_substr($str, $i, $offset, $this->CharSet); + $chunk = base64_encode($chunk); + $lookBack++; + } + while (strlen($chunk) > $length); + + $encoded .= $chunk . $this->LE; + } + + // Chomp the last linefeed + $encoded = substr($encoded, 0, -strlen($this->LE)); + return $encoded; + } + + /** + * Encode string to quoted-printable. + * @access private + * @return string + */ + function EncodeQP( $input = '', $line_max = 76, $space_conv = false ) { + $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); + $lines = preg_split('/(?:\r\n|\r|\n)/', $input); + $eol = "\r\n"; + $escape = '='; + $output = ''; + while( list(, $line) = each($lines) ) { + $linlen = strlen($line); + $newline = ''; + for($i = 0; $i < $linlen; $i++) { + $c = substr( $line, $i, 1 ); + $dec = ord( $c ); + if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E + $c = '=2E'; + } + if ( $dec == 32 ) { + if ( $i == ( $linlen - 1 ) ) { // convert space at eol only + $c = '=20'; + } else if ( $space_conv ) { + $c = '=20'; + } + } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required + $h2 = floor($dec/16); + $h1 = floor($dec%16); + $c = $escape.$hex[$h2].$hex[$h1]; + } + if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted + $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay + $newline = ''; + // check if newline first character will be point or not + if ( $dec == 46 ) { + $c = '=2E'; + } + } + $newline .= $c; + } // end of for + $output .= $newline.$eol; + } // end of while + return $output; + } + + /** + * Callback for converting to "=XX". + * @access private + * @return string + */ + function EncodeQ_callback ($matches) { + return sprintf('=%02X', ord($matches[1])); + } + + /** + * Encode string to q encoding. + * @access private + * @return string + */ + function EncodeQ ($str, $position = 'text') { + /* There should not be any EOL in the string */ + $encoded = preg_replace("/[\r\n]/", '', $str); + + switch (strtolower($position)) { + case 'phrase': + $encoded = preg_replace_callback("/([^A-Za-z0-9!*+\/ -])/", + array('PHPMailer', 'EncodeQ_callback'), $encoded); + break; + case 'comment': + $encoded = preg_replace_callback("/([\(\)\"])/", + array('PHPMailer', 'EncodeQ_callback'), $encoded); + break; + case 'text': + default: + /* Replace every high ascii, control =, ? and _ characters */ + $encoded = preg_replace_callback('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/', + array('PHPMailer', 'EncodeQ_callback'), $encoded); + break; + } + + /* Replace every spaces to _ (more readable than =20) */ + $encoded = str_replace(' ', '_', $encoded); + + return $encoded; + } + + /** + * Adds a string or binary attachment (non-filesystem) to the list. + * This method can be used to attach ascii or binary data, + * such as a BLOB record from a database. + * @param string $string String attachment data. + * @param string $filename Name of the attachment. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return void + */ + function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { + /* Append to $attachment array */ + $cur = count($this->attachment); + $this->attachment[$cur][0] = $string; + $this->attachment[$cur][1] = $filename; + $this->attachment[$cur][2] = $filename; + $this->attachment[$cur][3] = $encoding; + $this->attachment[$cur][4] = $type; + $this->attachment[$cur][5] = true; // isString + $this->attachment[$cur][6] = 'attachment'; + $this->attachment[$cur][7] = 0; + } + + /** + * Adds an embedded attachment. This can include images, sounds, and + * just about any other document. Make sure to set the $type to an + * image type. For JPEG images use "image/jpeg" and for GIF images + * use "image/gif". + * @param string $path Path to the attachment. + * @param string $cid Content ID of the attachment. Use this to identify + * the Id for accessing the image in an HTML form. + * @param string $name Overrides the attachment name. + * @param string $encoding File encoding (see $Encoding). + * @param string $type File extension (MIME) type. + * @return bool + */ + function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { + + if(!@is_file($path)) { + $this->SetError($this->Lang('file_access') . $path); + return false; + } + + $filename = basename($path); + if($name == '') { + $name = $filename; + } + + /* Append to $attachment array */ + $cur = count($this->attachment); + $this->attachment[$cur][0] = $path; + $this->attachment[$cur][1] = $filename; + $this->attachment[$cur][2] = $name; + $this->attachment[$cur][3] = $encoding; + $this->attachment[$cur][4] = $type; + $this->attachment[$cur][5] = false; + $this->attachment[$cur][6] = 'inline'; + $this->attachment[$cur][7] = $cid; + + return true; + } + + /** + * Returns true if an inline attachment is present. + * @access private + * @return bool + */ + function InlineImageExists() { + $result = false; + for($i = 0; $i < count($this->attachment); $i++) { + if($this->attachment[$i][6] == 'inline') { + $result = true; + break; + } + } + + return $result; + } + + ///////////////////////////////////////////////// + // CLASS METHODS, MESSAGE RESET + ///////////////////////////////////////////////// + + /** + * Clears all recipients assigned in the TO array. Returns void. + * @return void + */ + function ClearAddresses() { + $this->to = array(); + } + + /** + * Clears all recipients assigned in the CC array. Returns void. + * @return void + */ + function ClearCCs() { + $this->cc = array(); + } + + /** + * Clears all recipients assigned in the BCC array. Returns void. + * @return void + */ + function ClearBCCs() { + $this->bcc = array(); + } + + /** + * Clears all recipients assigned in the ReplyTo array. Returns void. + * @return void + */ + function ClearReplyTos() { + $this->ReplyTo = array(); + } + + /** + * Clears all recipients assigned in the TO, CC and BCC + * array. Returns void. + * @return void + */ + function ClearAllRecipients() { + $this->to = array(); + $this->cc = array(); + $this->bcc = array(); + } + + /** + * Clears all previously set filesystem, string, and binary + * attachments. Returns void. + * @return void + */ + function ClearAttachments() { + $this->attachment = array(); + } + + /** + * Clears all custom headers. Returns void. + * @return void + */ + function ClearCustomHeaders() { + $this->CustomHeader = array(); + } + + ///////////////////////////////////////////////// + // CLASS METHODS, MISCELLANEOUS + ///////////////////////////////////////////////// + + /** + * Adds the error message to the error container. + * Returns void. + * @access private + * @return void + */ + function SetError($msg) { + $this->error_count++; + $this->ErrorInfo = $msg; + } + + /** + * Returns the proper RFC 822 formatted date. + * @access private + * @return string + */ + function RFCDate() { + $tz = date('Z'); + $tzs = ($tz < 0) ? '-' : '+'; + $tz = abs($tz); + $tz = (int)($tz/3600)*100 + ($tz%3600)/60; + $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); + + return $result; + } + + /** + * Returns the appropriate server variable. Should work with both + * PHP 4.1.0+ as well as older versions. Returns an empty string + * if nothing is found. + * @access private + * @return mixed + */ + function ServerVar($varName) { + global $HTTP_SERVER_VARS; + global $HTTP_ENV_VARS; + + if(!isset($_SERVER)) { + $_SERVER = $HTTP_SERVER_VARS; + if(!isset($_SERVER['REMOTE_ADDR'])) { + $_SERVER = $HTTP_ENV_VARS; // must be Apache + } + } + + if(isset($_SERVER[$varName])) { + return $_SERVER[$varName]; + } else { + return ''; + } + } + + /** + * Returns the server hostname or 'localhost.localdomain' if unknown. + * @access private + * @return string + */ + function ServerHostname() { + if ($this->Hostname != '') { + $result = $this->Hostname; + } elseif ($this->ServerVar('SERVER_NAME') != '') { + $result = $this->ServerVar('SERVER_NAME'); + } else { + $result = 'localhost.localdomain'; + } + + return $result; + } + + /** + * Returns a message in the appropriate language. + * @access private + * @return string + */ + function Lang($key) { + if(count($this->language) < 1) { + $this->SetLanguage('en'); // set the default language + } + + if(isset($this->language[$key])) { + return $this->language[$key]; + } else { + return 'Language string failed to load: ' . $key; + } + } + + /** + * Returns true if an error occurred. + * @return bool + */ + function IsError() { + return ($this->error_count > 0); + } + + /** + * Changes every end of line from CR or LF to CRLF. + * @access private + * @return string + */ + function FixEOL($str) { + $str = str_replace("\r\n", "\n", $str); + $str = str_replace("\r", "\n", $str); + $str = str_replace("\n", $this->LE, $str); + return $str; + } + + /** + * Adds a custom header. + * @return void + */ + function AddCustomHeader($custom_header) { + $this->CustomHeader[] = explode(':', $custom_header, 2); + } + + /** + * Evaluates the message and returns modifications for inline images and backgrounds + * @access public + * @return $message + */ + function MsgHTML($message,$basedir='') { + preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images); + if(isset($images[2])) { + foreach($images[2] as $i => $url) { + // do not change urls for absolute images (thanks to corvuscorax) + if (!preg_match('/^[A-z][A-z]*:\/\//',$url)) { + $filename = basename($url); + $directory = dirname($url); + ($directory == '.')?$directory='':''; + $cid = 'cid:' . md5($filename); + $fileParts = split("\.", $filename); + $ext = $fileParts[1]; + $mimeType = $this->_mime_types($ext); + if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; } + if ( strlen($directory) > 1 && substr($directory,-1) != '/') { $directory .= '/'; } + if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) { + $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message); + } + } + } + } + $this->IsHTML(true); + $this->Body = $message; + $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message))); + if ( !empty($textMsg) && empty($this->AltBody) ) { + $this->AltBody = html_entity_decode($textMsg); + } + if ( empty($this->AltBody) ) { + $this->AltBody = 'To view this email message, open the email in with HTML compatibility!' . "\n\n"; + } + } + + /** + * Gets the mime type of the embedded or inline image + * @access private + * @return mime type of ext + */ + function _mime_types($ext = '') { + $mimes = array( + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', + 'avi' => 'video/x-msvideo', + 'bin' => 'application/macbinary', + 'bmp' => 'image/bmp', + 'class' => 'application/octet-stream', + 'cpt' => 'application/mac-compactpro', + 'css' => 'text/css', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dll' => 'application/octet-stream', + 'dms' => 'application/octet-stream', + 'doc' => 'application/msword', + 'dvi' => 'application/x-dvi', + 'dxr' => 'application/x-director', + 'eml' => 'message/rfc822', + 'eps' => 'application/postscript', + 'exe' => 'application/octet-stream', + 'gif' => 'image/gif', + 'gtar' => 'application/x-gtar', + 'htm' => 'text/html', + 'html' => 'text/html', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'hqx' => 'application/mac-binhex40', + 'js' => 'application/x-javascript', + 'lha' => 'application/octet-stream', + 'log' => 'text/plain', + 'lzh' => 'application/octet-stream', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mif' => 'application/vnd.mif', + 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', + 'mp2' => 'audio/mpeg', + 'mp3' => 'audio/mpeg', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpga' => 'audio/mpeg', + 'oda' => 'application/oda', + 'pdf' => 'application/pdf', + 'php' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'phtml' => 'application/x-httpd-php', + 'png' => 'image/png', + 'ppt' => 'application/vnd.ms-powerpoint', + 'ps' => 'application/postscript', + 'psd' => 'application/octet-stream', + 'qt' => 'video/quicktime', + 'ra' => 'audio/x-realaudio', + 'ram' => 'audio/x-pn-realaudio', + 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', + 'rtf' => 'text/rtf', + 'rtx' => 'text/richtext', + 'rv' => 'video/vnd.rn-realvideo', + 'sea' => 'application/octet-stream', + 'shtml' => 'text/html', + 'sit' => 'application/x-stuffit', + 'so' => 'application/octet-stream', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'swf' => 'application/x-shockwave-flash', + 'tar' => 'application/x-tar', + 'text' => 'text/plain', + 'txt' => 'text/plain', + 'tgz' => 'application/x-tar', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'wav' => 'audio/x-wav', + 'wbxml' => 'application/vnd.wap.wbxml', + 'wmlc' => 'application/vnd.wap.wmlc', + 'word' => 'application/msword', + 'xht' => 'application/xhtml+xml', + 'xhtml' => 'application/xhtml+xml', + 'xl' => 'application/excel', + 'xls' => 'application/vnd.ms-excel', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'zip' => 'application/zip' + ); + return ( ! isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; + } + + /** + * Set (or reset) Class Objects (variables) + * + * Usage Example: + * $page->set('X-Priority', '3'); + * + * @access public + * @param string $name Parameter Name + * @param mixed $value Parameter Value + * NOTE: will not work with arrays, there are no arrays to set/reset + */ + function set ( $name, $value = '' ) { + if ( isset($this->$name) ) { + $this->$name = $value; + } else { + $this->SetError('Cannot set or reset variable ' . $name); + return false; + } + } + + /** + * Read a file from a supplied filename and return it. + * + * @access public + * @param string $filename Parameter File Name + */ + function getFile($filename) { + $return = ''; + if ($fp = fopen($filename, 'rb')) { + while (!feof($fp)) { + $return .= fread($fp, 1024); + } + fclose($fp); + return $return; + } else { + return false; + } + } + + /** + * Strips newlines to prevent header injection. + * @access private + * @param string $str String + * @return string + */ + function SecureHeader($str) { + $str = trim($str); + $str = str_replace("\r", "", $str); + $str = str_replace("\n", "", $str); + return $str; + } + + /** + * Set the private key file and password to sign the message. + * + * @access public + * @param string $key_filename Parameter File Name + * @param string $key_pass Password for private key + */ + function Sign($cert_filename, $key_filename, $key_pass) { + $this->sign_cert_file = $cert_filename; + $this->sign_key_file = $key_filename; + $this->sign_key_pass = $key_pass; + } + +} + +?> diff --git a/wp-includes/class-pop3.php b/wp-includes/class-pop3.php new file mode 100644 index 0000000..c11676c --- /dev/null +++ b/wp-includes/class-pop3.php @@ -0,0 +1,651 @@ +BUFFER,"integer"); + if( !empty($server) ) { + // Do not allow programs to alter MAILSERVER + // if it is already specified. They can get around + // this if they -really- want to, so don't count on it. + if(empty($this->MAILSERVER)) + $this->MAILSERVER = $server; + } + if(!empty($timeout)) { + settype($timeout,"integer"); + $this->TIMEOUT = $timeout; + if (!ini_get('safe_mode')) + set_time_limit($timeout); + } + return true; + } + + function update_timer () { + if (!ini_get('safe_mode')) + set_time_limit($this->TIMEOUT); + return true; + } + + function connect ($server, $port = 110) { + // Opens a socket to the specified server. Unless overridden, + // port defaults to 110. Returns true on success, false on fail + + // If MAILSERVER is set, override $server with it's value + + if (!isset($port) || !$port) {$port = 110;} + if(!empty($this->MAILSERVER)) + $server = $this->MAILSERVER; + + if(empty($server)){ + $this->ERROR = "POP3 connect: " . _("No server specified"); + unset($this->FP); + return false; + } + + $fp = @fsockopen("$server", $port, $errno, $errstr); + + if(!$fp) { + $this->ERROR = "POP3 connect: " . _("Error ") . "[$errno] [$errstr]"; + unset($this->FP); + return false; + } + + socket_set_blocking($fp,-1); + $this->update_timer(); + $reply = fgets($fp,$this->BUFFER); + $reply = $this->strip_clf($reply); + if($this->DEBUG) + error_log("POP3 SEND [connect: $server] GOT [$reply]",0); + if(!$this->is_ok($reply)) { + $this->ERROR = "POP3 connect: " . _("Error ") . "[$reply]"; + unset($this->FP); + return false; + } + $this->FP = $fp; + $this->BANNER = $this->parse_banner($reply); + return true; + } + + function user ($user = "") { + // Sends the USER command, returns true or false + + if( empty($user) ) { + $this->ERROR = "POP3 user: " . _("no login ID submitted"); + return false; + } elseif(!isset($this->FP)) { + $this->ERROR = "POP3 user: " . _("connection not established"); + return false; + } else { + $reply = $this->send_cmd("USER $user"); + if(!$this->is_ok($reply)) { + $this->ERROR = "POP3 user: " . _("Error ") . "[$reply]"; + return false; + } else + return true; + } + } + + function pass ($pass = "") { + // Sends the PASS command, returns # of msgs in mailbox, + // returns false (undef) on Auth failure + + if(empty($pass)) { + $this->ERROR = "POP3 pass: " . _("No password submitted"); + return false; + } elseif(!isset($this->FP)) { + $this->ERROR = "POP3 pass: " . _("connection not established"); + return false; + } else { + $reply = $this->send_cmd("PASS $pass"); + if(!$this->is_ok($reply)) { + $this->ERROR = "POP3 pass: " . _("Authentication failed") . " [$reply]"; + $this->quit(); + return false; + } else { + // Auth successful. + $count = $this->last("count"); + $this->COUNT = $count; + return $count; + } + } + } + + function apop ($login,$pass) { + // Attempts an APOP login. If this fails, it'll + // try a standard login. YOUR SERVER MUST SUPPORT + // THE USE OF THE APOP COMMAND! + // (apop is optional per rfc1939) + + if(!isset($this->FP)) { + $this->ERROR = "POP3 apop: " . _("No connection to server"); + return false; + } elseif(!$this->ALLOWAPOP) { + $retVal = $this->login($login,$pass); + return $retVal; + } elseif(empty($login)) { + $this->ERROR = "POP3 apop: " . _("No login ID submitted"); + return false; + } elseif(empty($pass)) { + $this->ERROR = "POP3 apop: " . _("No password submitted"); + return false; + } else { + $banner = $this->BANNER; + if( (!$banner) or (empty($banner)) ) { + $this->ERROR = "POP3 apop: " . _("No server banner") . ' - ' . _("abort"); + $retVal = $this->login($login,$pass); + return $retVal; + } else { + $AuthString = $banner; + $AuthString .= $pass; + $APOPString = md5($AuthString); + $cmd = "APOP $login $APOPString"; + $reply = $this->send_cmd($cmd); + if(!$this->is_ok($reply)) { + $this->ERROR = "POP3 apop: " . _("apop authentication failed") . ' - ' . _("abort"); + $retVal = $this->login($login,$pass); + return $retVal; + } else { + // Auth successful. + $count = $this->last("count"); + $this->COUNT = $count; + return $count; + } + } + } + } + + function login ($login = "", $pass = "") { + // Sends both user and pass. Returns # of msgs in mailbox or + // false on failure (or -1, if the error occurs while getting + // the number of messages.) + + if( !isset($this->FP) ) { + $this->ERROR = "POP3 login: " . _("No connection to server"); + return false; + } else { + $fp = $this->FP; + if( !$this->user( $login ) ) { + // Preserve the error generated by user() + return false; + } else { + $count = $this->pass($pass); + if( (!$count) || ($count == -1) ) { + // Preserve the error generated by last() and pass() + return false; + } else + return $count; + } + } + } + + function top ($msgNum, $numLines = "0") { + // Gets the header and first $numLines of the msg body + // returns data in an array with each returned line being + // an array element. If $numLines is empty, returns + // only the header information, and none of the body. + + if(!isset($this->FP)) { + $this->ERROR = "POP3 top: " . _("No connection to server"); + return false; + } + $this->update_timer(); + + $fp = $this->FP; + $buffer = $this->BUFFER; + $cmd = "TOP $msgNum $numLines"; + fwrite($fp, "TOP $msgNum $numLines\r\n"); + $reply = fgets($fp, $buffer); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { + @error_log("POP3 SEND [$cmd] GOT [$reply]",0); + } + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 top: " . _("Error ") . "[$reply]"; + return false; + } + + $count = 0; + $MsgArray = array(); + + $line = fgets($fp,$buffer); + while ( !ereg("^\.\r\n",$line)) + { + $MsgArray[$count] = $line; + $count++; + $line = fgets($fp,$buffer); + if(empty($line)) { break; } + } + + return $MsgArray; + } + + function pop_list ($msgNum = "") { + // If called with an argument, returns that msgs' size in octets + // No argument returns an associative array of undeleted + // msg numbers and their sizes in octets + + if(!isset($this->FP)) + { + $this->ERROR = "POP3 pop_list: " . _("No connection to server"); + return false; + } + $fp = $this->FP; + $Total = $this->COUNT; + if( (!$Total) or ($Total == -1) ) + { + return false; + } + if($Total == 0) + { + return array("0","0"); + // return -1; // mailbox empty + } + + $this->update_timer(); + + if(!empty($msgNum)) + { + $cmd = "LIST $msgNum"; + fwrite($fp,"$cmd\r\n"); + $reply = fgets($fp,$this->BUFFER); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { + @error_log("POP3 SEND [$cmd] GOT [$reply]",0); + } + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]"; + return false; + } + list($junk,$num,$size) = preg_split('/\s+/',$reply); + return $size; + } + $cmd = "LIST"; + $reply = $this->send_cmd($cmd); + if(!$this->is_ok($reply)) + { + $reply = $this->strip_clf($reply); + $this->ERROR = "POP3 pop_list: " . _("Error ") . "[$reply]"; + return false; + } + $MsgArray = array(); + $MsgArray[0] = $Total; + for($msgC=1;$msgC <= $Total; $msgC++) + { + if($msgC > $Total) { break; } + $line = fgets($fp,$this->BUFFER); + $line = $this->strip_clf($line); + if(ereg("^\.",$line)) + { + $this->ERROR = "POP3 pop_list: " . _("Premature end of list"); + return false; + } + list($thisMsg,$msgSize) = preg_split('/\s+/',$line); + settype($thisMsg,"integer"); + if($thisMsg != $msgC) + { + $MsgArray[$msgC] = "deleted"; + } + else + { + $MsgArray[$msgC] = $msgSize; + } + } + return $MsgArray; + } + + function get ($msgNum) { + // Retrieve the specified msg number. Returns an array + // where each line of the msg is an array element. + + if(!isset($this->FP)) + { + $this->ERROR = "POP3 get: " . _("No connection to server"); + return false; + } + + $this->update_timer(); + + $fp = $this->FP; + $buffer = $this->BUFFER; + $cmd = "RETR $msgNum"; + $reply = $this->send_cmd($cmd); + + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 get: " . _("Error ") . "[$reply]"; + return false; + } + + $count = 0; + $MsgArray = array(); + + $line = fgets($fp,$buffer); + while ( !ereg("^\.\r\n",$line)) + { + if ( $line{0} == '.' ) { $line = substr($line,1); } + $MsgArray[$count] = $line; + $count++; + $line = fgets($fp,$buffer); + if(empty($line)) { break; } + } + return $MsgArray; + } + + function last ( $type = "count" ) { + // Returns the highest msg number in the mailbox. + // returns -1 on error, 0+ on success, if type != count + // results in a popstat() call (2 element array returned) + + $last = -1; + if(!isset($this->FP)) + { + $this->ERROR = "POP3 last: " . _("No connection to server"); + return $last; + } + + $reply = $this->send_cmd("STAT"); + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 last: " . _("Error ") . "[$reply]"; + return $last; + } + + $Vars = preg_split('/\s+/',$reply); + $count = $Vars[1]; + $size = $Vars[2]; + settype($count,"integer"); + settype($size,"integer"); + if($type != "count") + { + return array($count,$size); + } + return $count; + } + + function reset () { + // Resets the status of the remote server. This includes + // resetting the status of ALL msgs to not be deleted. + // This method automatically closes the connection to the server. + + if(!isset($this->FP)) + { + $this->ERROR = "POP3 reset: " . _("No connection to server"); + return false; + } + $reply = $this->send_cmd("RSET"); + if(!$this->is_ok($reply)) + { + // The POP3 RSET command -never- gives a -ERR + // response - if it ever does, something truely + // wild is going on. + + $this->ERROR = "POP3 reset: " . _("Error ") . "[$reply]"; + @error_log("POP3 reset: ERROR [$reply]",0); + } + $this->quit(); + return true; + } + + function send_cmd ( $cmd = "" ) + { + // Sends a user defined command string to the + // POP server and returns the results. Useful for + // non-compliant or custom POP servers. + // Do NOT includ the \r\n as part of your command + // string - it will be appended automatically. + + // The return value is a standard fgets() call, which + // will read up to $this->BUFFER bytes of data, until it + // encounters a new line, or EOF, whichever happens first. + + // This method works best if $cmd responds with only + // one line of data. + + if(!isset($this->FP)) + { + $this->ERROR = "POP3 send_cmd: " . _("No connection to server"); + return false; + } + + if(empty($cmd)) + { + $this->ERROR = "POP3 send_cmd: " . _("Empty command string"); + return ""; + } + + $fp = $this->FP; + $buffer = $this->BUFFER; + $this->update_timer(); + fwrite($fp,"$cmd\r\n"); + $reply = fgets($fp,$buffer); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); } + return $reply; + } + + function quit() { + // Closes the connection to the POP3 server, deleting + // any msgs marked as deleted. + + if(!isset($this->FP)) + { + $this->ERROR = "POP3 quit: " . _("connection does not exist"); + return false; + } + $fp = $this->FP; + $cmd = "QUIT"; + fwrite($fp,"$cmd\r\n"); + $reply = fgets($fp,$this->BUFFER); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); } + fclose($fp); + unset($this->FP); + return true; + } + + function popstat () { + // Returns an array of 2 elements. The number of undeleted + // msgs in the mailbox, and the size of the mbox in octets. + + $PopArray = $this->last("array"); + + if($PopArray == -1) { return false; } + + if( (!$PopArray) or (empty($PopArray)) ) + { + return false; + } + return $PopArray; + } + + function uidl ($msgNum = "") + { + // Returns the UIDL of the msg specified. If called with + // no arguments, returns an associative array where each + // undeleted msg num is a key, and the msg's uidl is the element + // Array element 0 will contain the total number of msgs + + if(!isset($this->FP)) { + $this->ERROR = "POP3 uidl: " . _("No connection to server"); + return false; + } + + $fp = $this->FP; + $buffer = $this->BUFFER; + + if(!empty($msgNum)) { + $cmd = "UIDL $msgNum"; + $reply = $this->send_cmd($cmd); + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]"; + return false; + } + list ($ok,$num,$myUidl) = preg_split('/\s+/',$reply); + return $myUidl; + } else { + $this->update_timer(); + + $UIDLArray = array(); + $Total = $this->COUNT; + $UIDLArray[0] = $Total; + + if ($Total < 1) + { + return $UIDLArray; + } + $cmd = "UIDL"; + fwrite($fp, "UIDL\r\n"); + $reply = fgets($fp, $buffer); + $reply = $this->strip_clf($reply); + if($this->DEBUG) { @error_log("POP3 SEND [$cmd] GOT [$reply]",0); } + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 uidl: " . _("Error ") . "[$reply]"; + return false; + } + + $line = ""; + $count = 1; + $line = fgets($fp,$buffer); + while ( !ereg("^\.\r\n",$line)) { + if(ereg("^\.\r\n",$line)) { + break; + } + list ($msg,$msgUidl) = preg_split('/\s+/',$line); + $msgUidl = $this->strip_clf($msgUidl); + if($count == $msg) { + $UIDLArray[$msg] = $msgUidl; + } + else + { + $UIDLArray[$count] = 'deleted'; + } + $count++; + $line = fgets($fp,$buffer); + } + } + return $UIDLArray; + } + + function delete ($msgNum = "") { + // Flags a specified msg as deleted. The msg will not + // be deleted until a quit() method is called. + + if(!isset($this->FP)) + { + $this->ERROR = "POP3 delete: " . _("No connection to server"); + return false; + } + if(empty($msgNum)) + { + $this->ERROR = "POP3 delete: " . _("No msg number submitted"); + return false; + } + $reply = $this->send_cmd("DELE $msgNum"); + if(!$this->is_ok($reply)) + { + $this->ERROR = "POP3 delete: " . _("Command failed ") . "[$reply]"; + return false; + } + return true; + } + + // ********************************************************* + + // The following methods are internal to the class. + + function is_ok ($cmd = "") { + // Return true or false on +OK or -ERR + + if( empty($cmd) ) + return false; + else + return( ereg ("^\+OK", $cmd ) ); + } + + function strip_clf ($text = "") { + // Strips \r\n from server responses + + if(empty($text)) + return $text; + else { + $stripped = str_replace("\r",'',$text); + $stripped = str_replace("\n",'',$stripped); + return $stripped; + } + } + + function parse_banner ( $server_text ) { + $outside = true; + $banner = ""; + $length = strlen($server_text); + for($count =0; $count < $length; $count++) + { + $digit = substr($server_text,$count,1); + if(!empty($digit)) { + if( (!$outside) && ($digit != '<') && ($digit != '>') ) + { + $banner .= $digit; + } + if ($digit == '<') + { + $outside = false; + } + if($digit == '>') + { + $outside = true; + } + } + } + $banner = $this->strip_clf($banner); // Just in case + return "<$banner>"; + } + +} // End class +?> diff --git a/wp-includes/class-simplepie.php b/wp-includes/class-simplepie.php new file mode 100644 index 0000000..88050b3 --- /dev/null +++ b/wp-includes/class-simplepie.php @@ -0,0 +1,13641 @@ +' . SIMPLEPIE_NAME . ''); + +/** + * No Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_NONE', 0); + +/** + * Feed Link Element Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_AUTODISCOVERY', 1); + +/** + * Local Feed Extension Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_LOCAL_EXTENSION', 2); + +/** + * Local Feed Body Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_LOCAL_BODY', 4); + +/** + * Remote Feed Extension Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_REMOTE_EXTENSION', 8); + +/** + * Remote Feed Body Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_REMOTE_BODY', 16); + +/** + * All Feed Autodiscovery + * @see SimplePie::set_autodiscovery_level() + */ +define('SIMPLEPIE_LOCATOR_ALL', 31); + +/** + * No known feed type + */ +define('SIMPLEPIE_TYPE_NONE', 0); + +/** + * RSS 0.90 + */ +define('SIMPLEPIE_TYPE_RSS_090', 1); + +/** + * RSS 0.91 (Netscape) + */ +define('SIMPLEPIE_TYPE_RSS_091_NETSCAPE', 2); + +/** + * RSS 0.91 (Userland) + */ +define('SIMPLEPIE_TYPE_RSS_091_USERLAND', 4); + +/** + * RSS 0.91 (both Netscape and Userland) + */ +define('SIMPLEPIE_TYPE_RSS_091', 6); + +/** + * RSS 0.92 + */ +define('SIMPLEPIE_TYPE_RSS_092', 8); + +/** + * RSS 0.93 + */ +define('SIMPLEPIE_TYPE_RSS_093', 16); + +/** + * RSS 0.94 + */ +define('SIMPLEPIE_TYPE_RSS_094', 32); + +/** + * RSS 1.0 + */ +define('SIMPLEPIE_TYPE_RSS_10', 64); + +/** + * RSS 2.0 + */ +define('SIMPLEPIE_TYPE_RSS_20', 128); + +/** + * RDF-based RSS + */ +define('SIMPLEPIE_TYPE_RSS_RDF', 65); + +/** + * Non-RDF-based RSS (truly intended as syndication format) + */ +define('SIMPLEPIE_TYPE_RSS_SYNDICATION', 190); + +/** + * All RSS + */ +define('SIMPLEPIE_TYPE_RSS_ALL', 255); + +/** + * Atom 0.3 + */ +define('SIMPLEPIE_TYPE_ATOM_03', 256); + +/** + * Atom 1.0 + */ +define('SIMPLEPIE_TYPE_ATOM_10', 512); + +/** + * All Atom + */ +define('SIMPLEPIE_TYPE_ATOM_ALL', 768); + +/** + * All feed types + */ +define('SIMPLEPIE_TYPE_ALL', 1023); + +/** + * No construct + */ +define('SIMPLEPIE_CONSTRUCT_NONE', 0); + +/** + * Text construct + */ +define('SIMPLEPIE_CONSTRUCT_TEXT', 1); + +/** + * HTML construct + */ +define('SIMPLEPIE_CONSTRUCT_HTML', 2); + +/** + * XHTML construct + */ +define('SIMPLEPIE_CONSTRUCT_XHTML', 4); + +/** + * base64-encoded construct + */ +define('SIMPLEPIE_CONSTRUCT_BASE64', 8); + +/** + * IRI construct + */ +define('SIMPLEPIE_CONSTRUCT_IRI', 16); + +/** + * A construct that might be HTML + */ +define('SIMPLEPIE_CONSTRUCT_MAYBE_HTML', 32); + +/** + * All constructs + */ +define('SIMPLEPIE_CONSTRUCT_ALL', 63); + +/** + * PCRE for HTML attributes + */ +define('SIMPLEPIE_PCRE_HTML_ATTRIBUTE', '((?:[\x09\x0A\x0B\x0C\x0D\x20]+[^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"(?:[^"]*)"|\'(?:[^\']*)\'|(?:[^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?)*)[\x09\x0A\x0B\x0C\x0D\x20]*'); + +/** + * PCRE for XML attributes + */ +define('SIMPLEPIE_PCRE_XML_ATTRIBUTE', '((?:\s+(?:(?:[^\s:]+:)?[^\s:]+)\s*=\s*(?:"(?:[^"]*)"|\'(?:[^\']*)\'))*)\s*'); + +/** + * XML Namespace + */ +define('SIMPLEPIE_NAMESPACE_XML', 'http://www.w3.org/XML/1998/namespace'); + +/** + * Atom 1.0 Namespace + */ +define('SIMPLEPIE_NAMESPACE_ATOM_10', 'http://www.w3.org/2005/Atom'); + +/** + * Atom 0.3 Namespace + */ +define('SIMPLEPIE_NAMESPACE_ATOM_03', 'http://purl.org/atom/ns#'); + +/** + * RDF Namespace + */ +define('SIMPLEPIE_NAMESPACE_RDF', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); + +/** + * RSS 0.90 Namespace + */ +define('SIMPLEPIE_NAMESPACE_RSS_090', 'http://my.netscape.com/rdf/simple/0.9/'); + +/** + * RSS 1.0 Namespace + */ +define('SIMPLEPIE_NAMESPACE_RSS_10', 'http://purl.org/rss/1.0/'); + +/** + * RSS 1.0 Content Module Namespace + */ +define('SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT', 'http://purl.org/rss/1.0/modules/content/'); + +/** + * RSS 2.0 Namespace + * (Stupid, I know, but I'm certain it will confuse people less with support.) + */ +define('SIMPLEPIE_NAMESPACE_RSS_20', ''); + +/** + * DC 1.0 Namespace + */ +define('SIMPLEPIE_NAMESPACE_DC_10', 'http://purl.org/dc/elements/1.0/'); + +/** + * DC 1.1 Namespace + */ +define('SIMPLEPIE_NAMESPACE_DC_11', 'http://purl.org/dc/elements/1.1/'); + +/** + * W3C Basic Geo (WGS84 lat/long) Vocabulary Namespace + */ +define('SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO', 'http://www.w3.org/2003/01/geo/wgs84_pos#'); + +/** + * GeoRSS Namespace + */ +define('SIMPLEPIE_NAMESPACE_GEORSS', 'http://www.georss.org/georss'); + +/** + * Media RSS Namespace + */ +define('SIMPLEPIE_NAMESPACE_MEDIARSS', 'http://search.yahoo.com/mrss/'); + +/** + * Wrong Media RSS Namespace + */ +define('SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG', 'http://search.yahoo.com/mrss'); + +/** + * iTunes RSS Namespace + */ +define('SIMPLEPIE_NAMESPACE_ITUNES', 'http://www.itunes.com/dtds/podcast-1.0.dtd'); + +/** + * XHTML Namespace + */ +define('SIMPLEPIE_NAMESPACE_XHTML', 'http://www.w3.org/1999/xhtml'); + +/** + * IANA Link Relations Registry + */ +define('SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY', 'http://www.iana.org/assignments/relation/'); + +/** + * Whether we're running on PHP5 + */ +define('SIMPLEPIE_PHP5', version_compare(PHP_VERSION, '5.0.0', '>=')); + +/** + * No file source + */ +define('SIMPLEPIE_FILE_SOURCE_NONE', 0); + +/** + * Remote file source + */ +define('SIMPLEPIE_FILE_SOURCE_REMOTE', 1); + +/** + * Local file source + */ +define('SIMPLEPIE_FILE_SOURCE_LOCAL', 2); + +/** + * fsockopen() file source + */ +define('SIMPLEPIE_FILE_SOURCE_FSOCKOPEN', 4); + +/** + * cURL file source + */ +define('SIMPLEPIE_FILE_SOURCE_CURL', 8); + +/** + * file_get_contents() file source + */ +define('SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS', 16); + +/** + * SimplePie + * + * @package SimplePie + * @version "Razzleberry" + * @copyright 2004-2007 Ryan Parman, Geoffrey Sneddon + * @author Ryan Parman + * @author Geoffrey Sneddon + * @todo Option for type of fetching (cache, not modified header, fetch, etc.) + */ +class SimplePie +{ + /** + * @var array Raw data + * @access private + */ + var $data = array(); + + /** + * @var mixed Error string + * @access private + */ + var $error; + + /** + * @var object Instance of SimplePie_Sanitize (or other class) + * @see SimplePie::set_sanitize_class() + * @access private + */ + var $sanitize; + + /** + * @var string SimplePie Useragent + * @see SimplePie::set_useragent() + * @access private + */ + var $useragent = SIMPLEPIE_USERAGENT; + + /** + * @var string Feed URL + * @see SimplePie::set_feed_url() + * @access private + */ + var $feed_url; + + /** + * @var object Instance of SimplePie_File to use as a feed + * @see SimplePie::set_file() + * @access private + */ + var $file; + + /** + * @var string Raw feed data + * @see SimplePie::set_raw_data() + * @access private + */ + var $raw_data; + + /** + * @var int Timeout for fetching remote files + * @see SimplePie::set_timeout() + * @access private + */ + var $timeout = 10; + + /** + * @var bool Forces fsockopen() to be used for remote files instead + * of cURL, even if a new enough version is installed + * @see SimplePie::force_fsockopen() + * @access private + */ + var $force_fsockopen = false; + + /** + * @var bool Force the given data/URL to be treated as a feed no matter what + * it appears like + * @see SimplePie::force_feed() + * @access private + */ + var $force_feed = false; + + /** + * @var bool Enable/Disable XML dump + * @see SimplePie::enable_xml_dump() + * @access private + */ + var $xml_dump = false; + + /** + * @var bool Enable/Disable Caching + * @see SimplePie::enable_cache() + * @access private + */ + var $cache = true; + + /** + * @var int Cache duration (in seconds) + * @see SimplePie::set_cache_duration() + * @access private + */ + var $cache_duration = 3600; + + /** + * @var int Auto-discovery cache duration (in seconds) + * @see SimplePie::set_autodiscovery_cache_duration() + * @access private + */ + var $autodiscovery_cache_duration = 604800; // 7 Days. + + /** + * @var string Cache location (relative to executing script) + * @see SimplePie::set_cache_location() + * @access private + */ + var $cache_location = './cache'; + + /** + * @var string Function that creates the cache filename + * @see SimplePie::set_cache_name_function() + * @access private + */ + var $cache_name_function = 'md5'; + + /** + * @var bool Reorder feed by date descending + * @see SimplePie::enable_order_by_date() + * @access private + */ + var $order_by_date = true; + + /** + * @var mixed Force input encoding to be set to the follow value + * (false, or anything type-cast to false, disables this feature) + * @see SimplePie::set_input_encoding() + * @access private + */ + var $input_encoding = false; + + /** + * @var int Feed Autodiscovery Level + * @see SimplePie::set_autodiscovery_level() + * @access private + */ + var $autodiscovery = SIMPLEPIE_LOCATOR_ALL; + + /** + * @var string Class used for caching feeds + * @see SimplePie::set_cache_class() + * @access private + */ + var $cache_class = 'SimplePie_Cache'; + + /** + * @var string Class used for locating feeds + * @see SimplePie::set_locator_class() + * @access private + */ + var $locator_class = 'SimplePie_Locator'; + + /** + * @var string Class used for parsing feeds + * @see SimplePie::set_parser_class() + * @access private + */ + var $parser_class = 'SimplePie_Parser'; + + /** + * @var string Class used for fetching feeds + * @see SimplePie::set_file_class() + * @access private + */ + var $file_class = 'SimplePie_File'; + + /** + * @var string Class used for items + * @see SimplePie::set_item_class() + * @access private + */ + var $item_class = 'SimplePie_Item'; + + /** + * @var string Class used for authors + * @see SimplePie::set_author_class() + * @access private + */ + var $author_class = 'SimplePie_Author'; + + /** + * @var string Class used for categories + * @see SimplePie::set_category_class() + * @access private + */ + var $category_class = 'SimplePie_Category'; + + /** + * @var string Class used for enclosures + * @see SimplePie::set_enclosures_class() + * @access private + */ + var $enclosure_class = 'SimplePie_Enclosure'; + + /** + * @var string Class used for Media RSS captions + * @see SimplePie::set_caption_class() + * @access private + */ + var $caption_class = 'SimplePie_Caption'; + + /** + * @var string Class used for Media RSS + * @see SimplePie::set_copyright_class() + * @access private + */ + var $copyright_class = 'SimplePie_Copyright'; + + /** + * @var string Class used for Media RSS + * @see SimplePie::set_credit_class() + * @access private + */ + var $credit_class = 'SimplePie_Credit'; + + /** + * @var string Class used for Media RSS + * @see SimplePie::set_rating_class() + * @access private + */ + var $rating_class = 'SimplePie_Rating'; + + /** + * @var string Class used for Media RSS + * @see SimplePie::set_restriction_class() + * @access private + */ + var $restriction_class = 'SimplePie_Restriction'; + + /** + * @var string Class used for content-type sniffing + * @see SimplePie::set_content_type_sniffer_class() + * @access private + */ + var $content_type_sniffer_class = 'SimplePie_Content_Type_Sniffer'; + + /** + * @var string Class used for item sources. + * @see SimplePie::set_source_class() + * @access private + */ + var $source_class = 'SimplePie_Source'; + + /** + * @var mixed Set javascript query string parameter (false, or + * anything type-cast to false, disables this feature) + * @see SimplePie::set_javascript() + * @access private + */ + var $javascript = 'js'; + + /** + * @var int Maximum number of feeds to check with autodiscovery + * @see SimplePie::set_max_checked_feeds() + * @access private + */ + var $max_checked_feeds = 10; + + /** + * @var string Web-accessible path to the handler_favicon.php file. + * @see SimplePie::set_favicon_handler() + * @access private + */ + var $favicon_handler = ''; + + /** + * @var string Web-accessible path to the handler_image.php file. + * @see SimplePie::set_image_handler() + * @access private + */ + var $image_handler = ''; + + /** + * @var array Stores the URLs when multiple feeds are being initialized. + * @see SimplePie::set_feed_url() + * @access private + */ + var $multifeed_url = array(); + + /** + * @var array Stores SimplePie objects when multiple feeds initialized. + * @access private + */ + var $multifeed_objects = array(); + + /** + * @var array Stores the get_object_vars() array for use with multifeeds. + * @see SimplePie::set_feed_url() + * @access private + */ + var $config_settings = null; + + /** + * @var integer Stores the number of items to return per-feed with multifeeds. + * @see SimplePie::set_item_limit() + * @access private + */ + var $item_limit = 0; + + /** + * @var array Stores the default attributes to be stripped by strip_attributes(). + * @see SimplePie::strip_attributes() + * @access private + */ + var $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'); + + /** + * @var array Stores the default tags to be stripped by strip_htmltags(). + * @see SimplePie::strip_htmltags() + * @access private + */ + var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'); + + /** + * The SimplePie class contains feed level data and options + * + * There are two ways that you can create a new SimplePie object. The first + * is by passing a feed URL as a parameter to the SimplePie constructor + * (as well as optionally setting the cache location and cache expiry). This + * will initialise the whole feed with all of the default settings, and you + * can begin accessing methods and properties immediately. + * + * The second way is to create the SimplePie object with no parameters + * at all. This will enable you to set configuration options. After setting + * them, you must initialise the feed using $feed->init(). At that point the + * object's methods and properties will be available to you. This format is + * what is used throughout this documentation. + * + * @access public + * @since 1.0 Preview Release + * @param string $feed_url This is the URL you want to parse. + * @param string $cache_location This is where you want the cache to be stored. + * @param int $cache_duration This is the number of seconds that you want to store the cache file for. + */ + function SimplePie($feed_url = null, $cache_location = null, $cache_duration = null) + { + // Other objects, instances created here so we can set options on them + $this->sanitize =& new SimplePie_Sanitize; + + // Set options if they're passed to the constructor + if ($cache_location !== null) + { + $this->set_cache_location($cache_location); + } + + if ($cache_duration !== null) + { + $this->set_cache_duration($cache_duration); + } + + // Only init the script if we're passed a feed URL + if ($feed_url !== null) + { + $this->set_feed_url($feed_url); + $this->init(); + } + } + + /** + * Used for converting object to a string + */ + function __toString() + { + return md5(serialize($this->data)); + } + + /** + * Remove items that link back to this before destroying this object + */ + function __destruct() + { + if ((version_compare(PHP_VERSION, '5.3', '<') || !gc_enabled()) && !ini_get('zend.ze1_compatibility_mode')) + { + if (!empty($this->data['items'])) + { + foreach ($this->data['items'] as $item) + { + $item->__destruct(); + } + unset($item, $this->data['items']); + } + if (!empty($this->data['ordered_items'])) + { + foreach ($this->data['ordered_items'] as $item) + { + $item->__destruct(); + } + unset($item, $this->data['ordered_items']); + } + } + } + + /** + * Force the given data/URL to be treated as a feed no matter what it + * appears like + * + * @access public + * @since 1.1 + * @param bool $enable Force the given data/URL to be treated as a feed + */ + function force_feed($enable = false) + { + $this->force_feed = (bool) $enable; + } + + /** + * This is the URL of the feed you want to parse. + * + * This allows you to enter the URL of the feed you want to parse, or the + * website you want to try to use auto-discovery on. This takes priority + * over any set raw data. + * + * You can set multiple feeds to mash together by passing an array instead + * of a string for the $url. Remember that with each additional feed comes + * additional processing and resources. + * + * @access public + * @since 1.0 Preview Release + * @param mixed $url This is the URL (or array of URLs) that you want to parse. + * @see SimplePie::set_raw_data() + */ + function set_feed_url($url) + { + if (is_array($url)) + { + $this->multifeed_url = array(); + foreach ($url as $value) + { + $this->multifeed_url[] = SimplePie_Misc::fix_protocol($value, 1); + } + } + else + { + $this->feed_url = SimplePie_Misc::fix_protocol($url, 1); + } + } + + /** + * Provides an instance of SimplePie_File to use as a feed + * + * @access public + * @param object &$file Instance of SimplePie_File (or subclass) + * @return bool True on success, false on failure + */ + function set_file(&$file) + { + if (is_a($file, 'SimplePie_File')) + { + $this->feed_url = $file->url; + $this->file =& $file; + return true; + } + return false; + } + + /** + * Allows you to use a string of RSS/Atom data instead of a remote feed. + * + * If you have a feed available as a string in PHP, you can tell SimplePie + * to parse that data string instead of a remote feed. Any set feed URL + * takes precedence. + * + * @access public + * @since 1.0 Beta 3 + * @param string $data RSS or Atom data as a string. + * @see SimplePie::set_feed_url() + */ + function set_raw_data($data) + { + $this->raw_data = $data; + } + + /** + * Allows you to override the default timeout for fetching remote feeds. + * + * This allows you to change the maximum time the feed's server to respond + * and send the feed back. + * + * @access public + * @since 1.0 Beta 3 + * @param int $timeout The maximum number of seconds to spend waiting to retrieve a feed. + */ + function set_timeout($timeout = 10) + { + $this->timeout = (int) $timeout; + } + + /** + * Forces SimplePie to use fsockopen() instead of the preferred cURL + * functions. + * + * @access public + * @since 1.0 Beta 3 + * @param bool $enable Force fsockopen() to be used + */ + function force_fsockopen($enable = false) + { + $this->force_fsockopen = (bool) $enable; + } + + /** + * Outputs the raw XML content of the feed, after it has gone through + * SimplePie's filters. + * + * Used only for debugging, this function will output the XML content as + * text/xml. When SimplePie reads in a feed, it does a bit of cleaning up + * before trying to parse it. Many parts of the feed are re-written in + * memory, and in the end, you have a parsable feed. XML dump shows you the + * actual XML that SimplePie tries to parse, which may or may not be very + * different from the original feed. + * + * @access public + * @since 1.0 Preview Release + * @param bool $enable Enable XML dump + */ + function enable_xml_dump($enable = false) + { + $this->xml_dump = (bool) $enable; + } + + /** + * Enables/disables caching in SimplePie. + * + * This option allows you to disable caching all-together in SimplePie. + * However, disabling the cache can lead to longer load times. + * + * @access public + * @since 1.0 Preview Release + * @param bool $enable Enable caching + */ + function enable_cache($enable = true) + { + $this->cache = (bool) $enable; + } + + /** + * Set the length of time (in seconds) that the contents of a feed + * will be cached. + * + * @access public + * @param int $seconds The feed content cache duration. + */ + function set_cache_duration($seconds = 3600) + { + $this->cache_duration = (int) $seconds; + } + + /** + * Set the length of time (in seconds) that the autodiscovered feed + * URL will be cached. + * + * @access public + * @param int $seconds The autodiscovered feed URL cache duration. + */ + function set_autodiscovery_cache_duration($seconds = 604800) + { + $this->autodiscovery_cache_duration = (int) $seconds; + } + + /** + * Set the file system location where the cached files should be stored. + * + * @access public + * @param string $location The file system location. + */ + function set_cache_location($location = './cache') + { + $this->cache_location = (string) $location; + } + + /** + * Determines whether feed items should be sorted into reverse chronological order. + * + * @access public + * @param bool $enable Sort as reverse chronological order. + */ + function enable_order_by_date($enable = true) + { + $this->order_by_date = (bool) $enable; + } + + /** + * Allows you to override the character encoding reported by the feed. + * + * @access public + * @param string $encoding Character encoding. + */ + function set_input_encoding($encoding = false) + { + if ($encoding) + { + $this->input_encoding = (string) $encoding; + } + else + { + $this->input_encoding = false; + } + } + + /** + * Set how much feed autodiscovery to do + * + * @access public + * @see SIMPLEPIE_LOCATOR_NONE + * @see SIMPLEPIE_LOCATOR_AUTODISCOVERY + * @see SIMPLEPIE_LOCATOR_LOCAL_EXTENSION + * @see SIMPLEPIE_LOCATOR_LOCAL_BODY + * @see SIMPLEPIE_LOCATOR_REMOTE_EXTENSION + * @see SIMPLEPIE_LOCATOR_REMOTE_BODY + * @see SIMPLEPIE_LOCATOR_ALL + * @param int $level Feed Autodiscovery Level (level can be a + * combination of the above constants, see bitwise OR operator) + */ + function set_autodiscovery_level($level = SIMPLEPIE_LOCATOR_ALL) + { + $this->autodiscovery = (int) $level; + } + + /** + * Allows you to change which class SimplePie uses for caching. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_cache_class($class = 'SimplePie_Cache') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Cache')) + { + $this->cache_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for auto-discovery. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_locator_class($class = 'SimplePie_Locator') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Locator')) + { + $this->locator_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for XML parsing. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_parser_class($class = 'SimplePie_Parser') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Parser')) + { + $this->parser_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for remote file fetching. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_file_class($class = 'SimplePie_File') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_File')) + { + $this->file_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for data sanitization. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_sanitize_class($class = 'SimplePie_Sanitize') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Sanitize')) + { + $this->sanitize =& new $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for handling feed items. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_item_class($class = 'SimplePie_Item') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Item')) + { + $this->item_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for handling author data. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_author_class($class = 'SimplePie_Author') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Author')) + { + $this->author_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for handling category data. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_category_class($class = 'SimplePie_Category') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Category')) + { + $this->category_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for feed enclosures. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_enclosure_class($class = 'SimplePie_Enclosure') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Enclosure')) + { + $this->enclosure_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for captions + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_caption_class($class = 'SimplePie_Caption') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Caption')) + { + $this->caption_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_copyright_class($class = 'SimplePie_Copyright') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Copyright')) + { + $this->copyright_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_credit_class($class = 'SimplePie_Credit') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Credit')) + { + $this->credit_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_rating_class($class = 'SimplePie_Rating') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Rating')) + { + $this->rating_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_restriction_class($class = 'SimplePie_Restriction') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Restriction')) + { + $this->restriction_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses for content-type sniffing. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_content_type_sniffer_class($class = 'SimplePie_Content_Type_Sniffer') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Content_Type_Sniffer')) + { + $this->content_type_sniffer_class = $class; + return true; + } + return false; + } + + /** + * Allows you to change which class SimplePie uses item sources. + * Useful when you are overloading or extending SimplePie's default classes. + * + * @access public + * @param string $class Name of custom class. + * @link http://php.net/manual/en/keyword.extends.php PHP4 extends documentation + * @link http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.extends PHP5 extends documentation + */ + function set_source_class($class = 'SimplePie_Source') + { + if (SimplePie_Misc::is_subclass_of($class, 'SimplePie_Source')) + { + $this->source_class = $class; + return true; + } + return false; + } + + /** + * Allows you to override the default user agent string. + * + * @access public + * @param string $ua New user agent string. + */ + function set_useragent($ua = SIMPLEPIE_USERAGENT) + { + $this->useragent = (string) $ua; + } + + /** + * Set callback function to create cache filename with + * + * @access public + * @param mixed $function Callback function + */ + function set_cache_name_function($function = 'md5') + { + if (is_callable($function)) + { + $this->cache_name_function = $function; + } + } + + /** + * Set javascript query string parameter + * + * @access public + * @param mixed $get Javascript query string parameter + */ + function set_javascript($get = 'js') + { + if ($get) + { + $this->javascript = (string) $get; + } + else + { + $this->javascript = false; + } + } + + /** + * Set options to make SP as fast as possible. Forgoes a + * substantial amount of data sanitization in favor of speed. + * + * @access public + * @param bool $set Whether to set them or not + */ + function set_stupidly_fast($set = false) + { + if ($set) + { + $this->enable_order_by_date(false); + $this->remove_div(false); + $this->strip_comments(false); + $this->strip_htmltags(false); + $this->strip_attributes(false); + $this->set_image_handler(false); + } + } + + /** + * Set maximum number of feeds to check with autodiscovery + * + * @access public + * @param int $max Maximum number of feeds to check + */ + function set_max_checked_feeds($max = 10) + { + $this->max_checked_feeds = (int) $max; + } + + function remove_div($enable = true) + { + $this->sanitize->remove_div($enable); + } + + function strip_htmltags($tags = '', $encode = null) + { + if ($tags === '') + { + $tags = $this->strip_htmltags; + } + $this->sanitize->strip_htmltags($tags); + if ($encode !== null) + { + $this->sanitize->encode_instead_of_strip($tags); + } + } + + function encode_instead_of_strip($enable = true) + { + $this->sanitize->encode_instead_of_strip($enable); + } + + function strip_attributes($attribs = '') + { + if ($attribs === '') + { + $attribs = $this->strip_attributes; + } + $this->sanitize->strip_attributes($attribs); + } + + function set_output_encoding($encoding = 'UTF-8') + { + $this->sanitize->set_output_encoding($encoding); + } + + function strip_comments($strip = false) + { + $this->sanitize->strip_comments($strip); + } + + /** + * Set element/attribute key/value pairs of HTML attributes + * containing URLs that need to be resolved relative to the feed + * + * @access public + * @since 1.0 + * @param array $element_attribute Element/attribute key/value pairs + */ + function set_url_replacements($element_attribute = array('a' => 'href', 'area' => 'href', 'blockquote' => 'cite', 'del' => 'cite', 'form' => 'action', 'img' => array('longdesc', 'src'), 'input' => 'src', 'ins' => 'cite', 'q' => 'cite')) + { + $this->sanitize->set_url_replacements($element_attribute); + } + + /** + * Set the handler to enable the display of cached favicons. + * + * @access public + * @param str $page Web-accessible path to the handler_favicon.php file. + * @param str $qs The query string that the value should be passed to. + */ + function set_favicon_handler($page = false, $qs = 'i') + { + if ($page != false) + { + $this->favicon_handler = $page . '?' . $qs . '='; + } + else + { + $this->favicon_handler = ''; + } + } + + /** + * Set the handler to enable the display of cached images. + * + * @access public + * @param str $page Web-accessible path to the handler_image.php file. + * @param str $qs The query string that the value should be passed to. + */ + function set_image_handler($page = false, $qs = 'i') + { + if ($page != false) + { + $this->sanitize->set_image_handler($page . '?' . $qs . '='); + } + else + { + $this->image_handler = ''; + } + } + + /** + * Set the limit for items returned per-feed with multifeeds. + * + * @access public + * @param integer $limit The maximum number of items to return. + */ + function set_item_limit($limit = 0) + { + $this->item_limit = (int) $limit; + } + + function init() + { + if ((function_exists('version_compare') && version_compare(PHP_VERSION, '4.3.0', '<')) || !extension_loaded('xml') || !extension_loaded('pcre')) + { + return false; + } + if (isset($_GET[$this->javascript])) + { + if (function_exists('ob_gzhandler')) + { + ob_start('ob_gzhandler'); + } + header('Content-type: text/javascript; charset: UTF-8'); + header('Cache-Control: must-revalidate'); + header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 604800) . ' GMT'); // 7 days + ?> +function embed_odeo(link) { + document.writeln(''); +} + +function embed_quicktime(type, bgcolor, width, height, link, placeholder, loop) { + if (placeholder != '') { + document.writeln(''); + } + else { + document.writeln(''); + } +} + +function embed_flash(bgcolor, width, height, link, loop, type) { + document.writeln(''); +} + +function embed_flv(width, height, link, placeholder, loop, player) { + document.writeln(''); +} + +function embed_wmedia(width, height, link) { + document.writeln(''); +} + sanitize->pass_cache_data($this->cache, $this->cache_location, $this->cache_name_function, $this->cache_class); + $this->sanitize->pass_file_data($this->file_class, $this->timeout, $this->useragent, $this->force_fsockopen); + + if ($this->feed_url !== null || $this->raw_data !== null) + { + $this->data = array(); + $this->multifeed_objects = array(); + $cache = false; + + if ($this->feed_url !== null) + { + $parsed_feed_url = SimplePie_Misc::parse_url($this->feed_url); + // Decide whether to enable caching + if ($this->cache && $parsed_feed_url['scheme'] !== '') + { + $cache = call_user_func(array($this->cache_class, 'create'), $this->cache_location, call_user_func($this->cache_name_function, $this->feed_url), 'spc'); + } + // If it's enabled and we don't want an XML dump, use the cache + if ($cache && !$this->xml_dump) + { + // Load the Cache + $this->data = $cache->load(); + if (!empty($this->data)) + { + // If the cache is for an outdated build of SimplePie + if (!isset($this->data['build']) || $this->data['build'] != SIMPLEPIE_BUILD) + { + $cache->unlink(); + $this->data = array(); + } + // If we've hit a collision just rerun it with caching disabled + elseif (isset($this->data['url']) && $this->data['url'] != $this->feed_url) + { + $cache = false; + $this->data = array(); + } + // If we've got a non feed_url stored (if the page isn't actually a feed, or is a redirect) use that URL. + elseif (isset($this->data['feed_url'])) + { + // If the autodiscovery cache is still valid use it. + if ($cache->mtime() + $this->autodiscovery_cache_duration > time()) + { + // Do not need to do feed autodiscovery yet. + if ($this->data['feed_url'] == $this->data['url']) + { + $cache->unlink(); + $this->data = array(); + } + else + { + $this->set_feed_url($this->data['feed_url']); + return $this->init(); + } + } + } + // Check if the cache has been updated + elseif ($cache->mtime() + $this->cache_duration < time()) + { + // If we have last-modified and/or etag set + if (isset($this->data['headers']['last-modified']) || isset($this->data['headers']['etag'])) + { + $headers = array(); + if (isset($this->data['headers']['last-modified'])) + { + $headers['if-modified-since'] = $this->data['headers']['last-modified']; + } + if (isset($this->data['headers']['etag'])) + { + $headers['if-none-match'] = '"' . $this->data['headers']['etag'] . '"'; + } + $file =& new $this->file_class($this->feed_url, $this->timeout/10, 5, $headers, $this->useragent, $this->force_fsockopen); + if ($file->success) + { + if ($file->status_code == 304) + { + $cache->touch(); + return true; + } + else + { + $headers = $file->headers; + } + } + else + { + unset($file); + } + } + } + // If the cache is still valid, just return true + else + { + return true; + } + } + // If the cache is empty, delete it + else + { + $cache->unlink(); + $this->data = array(); + } + } + // If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it. + if (!isset($file)) + { + if (is_a($this->file, 'SimplePie_File') && $this->file->url == $this->feed_url) + { + $file =& $this->file; + } + else + { + $file =& new $this->file_class($this->feed_url, $this->timeout, 5, null, $this->useragent, $this->force_fsockopen); + } + } + // If the file connection has an error, set SimplePie::error to that and quit + if (!$file->success) + { + $this->error = $file->error; + if (!empty($this->data)) + { + return true; + } + else + { + return false; + } + } + + if (!$this->force_feed) + { + // Check if the supplied URL is a feed, if it isn't, look for it. + $locate =& new $this->locator_class($file, $this->timeout, $this->useragent, $this->file_class, $this->max_checked_feeds, $this->content_type_sniffer_class); + if (!$locate->is_feed($file)) + { + // We need to unset this so that if SimplePie::set_file() has been called that object is untouched + unset($file); + if ($file = $locate->find($this->autodiscovery)) + { + if ($cache) + { + $this->data = array('url' => $this->feed_url, 'feed_url' => $file->url, 'build' => SIMPLEPIE_BUILD); + if (!$cache->save($this)) + { + trigger_error("$cache->name is not writeable", E_USER_WARNING); + } + $cache = call_user_func(array($this->cache_class, 'create'), $this->cache_location, call_user_func($this->cache_name_function, $file->url), 'spc'); + } + $this->feed_url = $file->url; + } + else + { + $this->error = "A feed could not be found at $this->feed_url"; + SimplePie_Misc::error($this->error, E_USER_NOTICE, __FILE__, __LINE__); + return false; + } + } + $locate = null; + } + + $headers = $file->headers; + $data = $file->body; + $sniffer =& new $this->content_type_sniffer_class($file); + $sniffed = $sniffer->get_type(); + } + else + { + $data = $this->raw_data; + } + + // Set up array of possible encodings + $encodings = array(); + + // First check to see if input has been overridden. + if ($this->input_encoding !== false) + { + $encodings[] = $this->input_encoding; + } + + $application_types = array('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity'); + $text_types = array('text/xml', 'text/xml-external-parsed-entity'); + + // RFC 3023 (only applies to sniffed content) + if (isset($sniffed)) + { + if (in_array($sniffed, $application_types) || substr($sniffed, 0, 12) === 'application/' && substr($sniffed, -4) === '+xml') + { + if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset)) + { + $encodings[] = strtoupper($charset[1]); + } + $encodings = array_merge($encodings, SimplePie_Misc::xml_encoding($data)); + $encodings[] = 'UTF-8'; + } + elseif (in_array($sniffed, $text_types) || substr($sniffed, 0, 5) === 'text/' && substr($sniffed, -4) === '+xml') + { + if (isset($headers['content-type']) && preg_match('/;\x20?charset=([^;]*)/i', $headers['content-type'], $charset)) + { + $encodings[] = $charset[1]; + } + $encodings[] = 'US-ASCII'; + } + // Text MIME-type default + elseif (substr($sniffed, 0, 5) === 'text/') + { + $encodings[] = 'US-ASCII'; + } + } + + // Fallback to XML 1.0 Appendix F.1/UTF-8/ISO-8859-1 + $encodings = array_merge($encodings, SimplePie_Misc::xml_encoding($data)); + $encodings[] = 'UTF-8'; + $encodings[] = 'ISO-8859-1'; + + // There's no point in trying an encoding twice + $encodings = array_unique($encodings); + + // If we want the XML, just output that with the most likely encoding and quit + if ($this->xml_dump) + { + header('Content-type: text/xml; charset=' . $encodings[0]); + echo $data; + exit; + } + + // Loop through each possible encoding, till we return something, or run out of possibilities + foreach ($encodings as $encoding) + { + // Change the encoding to UTF-8 (as we always use UTF-8 internally) + if ($utf8_data = SimplePie_Misc::change_encoding($data, $encoding, 'UTF-8')) + { + // Create new parser + $parser =& new $this->parser_class(); + + // If it's parsed fine + if ($parser->parse($utf8_data, 'UTF-8')) + { + $this->data = $parser->get_data(); + if ($this->get_type() & ~SIMPLEPIE_TYPE_NONE) + { + if (isset($headers)) + { + $this->data['headers'] = $headers; + } + $this->data['build'] = SIMPLEPIE_BUILD; + + // Cache the file if caching is enabled + if ($cache && !$cache->save($this)) + { + trigger_error("$cache->name is not writeable", E_USER_WARNING); + } + return true; + } + else + { + $this->error = "A feed could not be found at $this->feed_url"; + SimplePie_Misc::error($this->error, E_USER_NOTICE, __FILE__, __LINE__); + return false; + } + } + } + } + // We have an error, just set SimplePie::error to it and quit + $this->error = sprintf('XML error: %s at line %d, column %d', $parser->get_error_string(), $parser->get_current_line(), $parser->get_current_column()); + SimplePie_Misc::error($this->error, E_USER_NOTICE, __FILE__, __LINE__); + return false; + } + elseif (!empty($this->multifeed_url)) + { + $i = 0; + $success = 0; + $this->multifeed_objects = array(); + foreach ($this->multifeed_url as $url) + { + if (SIMPLEPIE_PHP5) + { + // This keyword needs to defy coding standards for PHP4 compatibility + $this->multifeed_objects[$i] = clone($this); + } + else + { + $this->multifeed_objects[$i] = $this; + } + $this->multifeed_objects[$i]->set_feed_url($url); + $success |= $this->multifeed_objects[$i]->init(); + $i++; + } + return (bool) $success; + } + else + { + return false; + } + } + + /** + * Return the error message for the occured error + * + * @access public + * @return string Error message + */ + function error() + { + return $this->error; + } + + function get_encoding() + { + return $this->sanitize->output_encoding; + } + + function handle_content_type($mime = 'text/html') + { + if (!headers_sent()) + { + $header = "Content-type: $mime;"; + if ($this->get_encoding()) + { + $header .= ' charset=' . $this->get_encoding(); + } + else + { + $header .= ' charset=UTF-8'; + } + header($header); + } + } + + function get_type() + { + if (!isset($this->data['type'])) + { + $this->data['type'] = SIMPLEPIE_TYPE_ALL; + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'])) + { + $this->data['type'] &= SIMPLEPIE_TYPE_ATOM_10; + } + elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'])) + { + $this->data['type'] &= SIMPLEPIE_TYPE_ATOM_03; + } + elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'])) + { + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['channel']) + || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['image']) + || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['item']) + || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_10]['textinput'])) + { + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_10; + } + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['channel']) + || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['image']) + || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['item']) + || isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_090]['textinput'])) + { + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_090; + } + } + elseif (isset($this->data['child']['']['rss'])) + { + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_ALL; + if (isset($this->data['child']['']['rss'][0]['attribs']['']['version'])) + { + switch (trim($this->data['child']['']['rss'][0]['attribs']['']['version'])) + { + case '0.91': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_091; + if (isset($this->data['child']['']['rss'][0]['child']['']['skiphours']['hour'][0]['data'])) + { + switch (trim($this->data['child']['']['rss'][0]['child']['']['skiphours']['hour'][0]['data'])) + { + case '0': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_091_NETSCAPE; + break; + + case '24': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_091_USERLAND; + break; + } + } + break; + + case '0.92': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_092; + break; + + case '0.93': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_093; + break; + + case '0.94': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_094; + break; + + case '2.0': + $this->data['type'] &= SIMPLEPIE_TYPE_RSS_20; + break; + } + } + } + else + { + $this->data['type'] = SIMPLEPIE_TYPE_NONE; + } + } + return $this->data['type']; + } + + /** + * Returns the URL for the favicon of the feed's website. + * + * @todo Cache atom:icon + * @access public + * @since 1.0 + */ + function get_favicon() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif (($url = $this->get_link()) !== null && preg_match('/^http(s)?:\/\//i', $url)) + { + $favicon = SimplePie_Misc::absolutize_url('/favicon.ico', $url); + + if ($this->cache && $this->favicon_handler) + { + $favicon_filename = call_user_func($this->cache_name_function, $favicon); + $cache = call_user_func(array($this->cache_class, 'create'), $this->cache_location, $favicon_filename, 'spi'); + + if ($cache->load()) + { + return $this->sanitize($this->favicon_handler . $favicon_filename, SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + $file =& new $this->file_class($favicon, $this->timeout / 10, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen); + + if ($file->success && ($file->status_code == 200 || ($file->status_code > 206 && $file->status_code < 300)) && strlen($file->body) > 0) + { + $sniffer =& new $this->content_type_sniffer_class($file); + if (substr($sniffer->get_type(), 0, 6) === 'image/') + { + if ($cache->save(array('headers' => $file->headers, 'body' => $file->body))) + { + return $this->sanitize($this->favicon_handler . $favicon_filename, SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + trigger_error("$cache->name is not writeable", E_USER_WARNING); + return $this->sanitize($favicon, SIMPLEPIE_CONSTRUCT_IRI); + } + } + } + } + } + else + { + return $this->sanitize($favicon, SIMPLEPIE_CONSTRUCT_IRI); + } + } + return false; + } + + /** + * @todo If we have a perm redirect we should return the new URL + * @todo When we make the above change, let's support as well + * @todo Also, |atom:link|@rel=self + */ + function subscribe_url() + { + if ($this->feed_url !== null) + { + return $this->sanitize($this->feed_url, SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + return null; + } + } + + function subscribe_feed() + { + if ($this->feed_url !== null) + { + return $this->sanitize(SimplePie_Misc::fix_protocol($this->feed_url, 2), SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + return null; + } + } + + function subscribe_outlook() + { + if ($this->feed_url !== null) + { + return 'outlook' . $this->sanitize(SimplePie_Misc::fix_protocol($this->feed_url, 2), SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + return null; + } + } + + function subscribe_podcast() + { + if ($this->feed_url !== null) + { + return $this->sanitize(SimplePie_Misc::fix_protocol($this->feed_url, 3), SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + return null; + } + } + + function subscribe_itunes() + { + if ($this->feed_url !== null) + { + return $this->sanitize(SimplePie_Misc::fix_protocol($this->feed_url, 4), SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + return null; + } + } + + /** + * Creates the subscribe_* methods' return data + * + * @access private + * @param string $feed_url String to prefix to the feed URL + * @param string $site_url String to prefix to the site URL (and + * suffix to the feed URL) + * @return mixed URL if feed exists, false otherwise + */ + function subscribe_service($feed_url, $site_url = null) + { + if ($this->subscribe_url()) + { + $return = $this->sanitize($feed_url, SIMPLEPIE_CONSTRUCT_IRI) . rawurlencode($this->feed_url); + if ($site_url !== null && $this->get_link() !== null) + { + $return .= $this->sanitize($site_url, SIMPLEPIE_CONSTRUCT_IRI) . rawurlencode($this->get_link()); + } + return $return; + } + else + { + return null; + } + } + + function subscribe_aol() + { + return $this->subscribe_service('http://feeds.my.aol.com/add.jsp?url='); + } + + function subscribe_bloglines() + { + return urldecode($this->subscribe_service('http://www.bloglines.com/sub/')); + } + + function subscribe_eskobo() + { + return $this->subscribe_service('http://www.eskobo.com/?AddToMyPage='); + } + + function subscribe_feedfeeds() + { + return $this->subscribe_service('http://www.feedfeeds.com/add?feed='); + } + + function subscribe_feedster() + { + return $this->subscribe_service('http://www.feedster.com/myfeedster.php?action=addrss&confirm=no&rssurl='); + } + + function subscribe_google() + { + return $this->subscribe_service('http://fusion.google.com/add?feedurl='); + } + + function subscribe_gritwire() + { + return $this->subscribe_service('http://my.gritwire.com/feeds/addExternalFeed.aspx?FeedUrl='); + } + + function subscribe_msn() + { + return $this->subscribe_service('http://my.msn.com/addtomymsn.armx?id=rss&ut=', '&ru='); + } + + function subscribe_netvibes() + { + return $this->subscribe_service('http://www.netvibes.com/subscribe.php?url='); + } + + function subscribe_newsburst() + { + return $this->subscribe_service('http://www.newsburst.com/Source/?add='); + } + + function subscribe_newsgator() + { + return $this->subscribe_service('http://www.newsgator.com/ngs/subscriber/subext.aspx?url='); + } + + function subscribe_odeo() + { + return $this->subscribe_service('http://www.odeo.com/listen/subscribe?feed='); + } + + function subscribe_podnova() + { + return $this->subscribe_service('http://www.podnova.com/index_your_podcasts.srf?action=add&url='); + } + + function subscribe_rojo() + { + return $this->subscribe_service('http://www.rojo.com/add-subscription?resource='); + } + + function subscribe_yahoo() + { + return $this->subscribe_service('http://add.my.yahoo.com/rss?url='); + } + + function get_feed_tags($namespace, $tag) + { + $type = $this->get_type(); + if ($type & SIMPLEPIE_TYPE_ATOM_10) + { + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag])) + { + return $this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['child'][$namespace][$tag]; + } + } + if ($type & SIMPLEPIE_TYPE_ATOM_03) + { + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag])) + { + return $this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['child'][$namespace][$tag]; + } + } + if ($type & SIMPLEPIE_TYPE_RSS_RDF) + { + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag])) + { + return $this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['child'][$namespace][$tag]; + } + } + if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION) + { + if (isset($this->data['child']['']['rss'][0]['child'][$namespace][$tag])) + { + return $this->data['child']['']['rss'][0]['child'][$namespace][$tag]; + } + } + return null; + } + + function get_channel_tags($namespace, $tag) + { + $type = $this->get_type(); + if ($type & SIMPLEPIE_TYPE_ATOM_ALL) + { + if ($return = $this->get_feed_tags($namespace, $tag)) + { + return $return; + } + } + if ($type & SIMPLEPIE_TYPE_RSS_10) + { + if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'channel')) + { + if (isset($channel[0]['child'][$namespace][$tag])) + { + return $channel[0]['child'][$namespace][$tag]; + } + } + } + if ($type & SIMPLEPIE_TYPE_RSS_090) + { + if ($channel = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'channel')) + { + if (isset($channel[0]['child'][$namespace][$tag])) + { + return $channel[0]['child'][$namespace][$tag]; + } + } + } + if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION) + { + if ($channel = $this->get_feed_tags('', 'channel')) + { + if (isset($channel[0]['child'][$namespace][$tag])) + { + return $channel[0]['child'][$namespace][$tag]; + } + } + } + return null; + } + + function get_image_tags($namespace, $tag) + { + $type = $this->get_type(); + if ($type & SIMPLEPIE_TYPE_RSS_10) + { + if ($image = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'image')) + { + if (isset($image[0]['child'][$namespace][$tag])) + { + return $image[0]['child'][$namespace][$tag]; + } + } + } + if ($type & SIMPLEPIE_TYPE_RSS_090) + { + if ($image = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'image')) + { + if (isset($image[0]['child'][$namespace][$tag])) + { + return $image[0]['child'][$namespace][$tag]; + } + } + } + if ($type & SIMPLEPIE_TYPE_RSS_SYNDICATION) + { + if ($image = $this->get_channel_tags('', 'image')) + { + if (isset($image[0]['child'][$namespace][$tag])) + { + return $image[0]['child'][$namespace][$tag]; + } + } + } + return null; + } + + function get_base($element = array()) + { + if (!($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION) && !empty($element['xml_base_explicit']) && isset($element['xml_base'])) + { + return $element['xml_base']; + } + elseif ($this->get_link() !== null) + { + return $this->get_link(); + } + else + { + return $this->subscribe_url(); + } + } + + function sanitize($data, $type, $base = '') + { + return $this->sanitize->sanitize($data, $type, $base); + } + + function get_title() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags('', 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_category($key = 0) + { + $categories = $this->get_categories(); + if (isset($categories[$key])) + { + return $categories[$key]; + } + else + { + return null; + } + } + + function get_categories() + { + $categories = array(); + + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['attribs']['']['term'])) + { + $term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories[] =& new $this->category_class($term, $scheme, $label); + } + foreach ((array) $this->get_channel_tags('', 'category') as $category) + { + $categories[] =& new $this->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category) + { + $categories[] =& new $this->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category) + { + $categories[] =& new $this->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + + if (!empty($categories)) + { + return SimplePie_Misc::array_unique($categories); + } + else + { + return null; + } + } + + function get_author($key = 0) + { + $authors = $this->get_authors(); + if (isset($authors[$key])) + { + return $authors[$key]; + } + else + { + return null; + } + } + + function get_authors() + { + $authors = array(); + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author) + { + $name = null; + $uri = null; + $email = null; + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) + { + $name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) + { + $uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); + } + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) + { + $email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $uri !== null) + { + $authors[] =& new $this->author_class($name, $uri, $email); + } + } + if ($author = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author')) + { + $name = null; + $url = null; + $email = null; + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) + { + $name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) + { + $url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); + } + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) + { + $email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $url !== null) + { + $authors[] =& new $this->author_class($name, $url, $email); + } + } + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author) + { + $authors[] =& new $this->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author) + { + $authors[] =& new $this->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author) + { + $authors[] =& new $this->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + + if (!empty($authors)) + { + return SimplePie_Misc::array_unique($authors); + } + else + { + return null; + } + } + + function get_contributor($key = 0) + { + $contributors = $this->get_contributors(); + if (isset($contributors[$key])) + { + return $contributors[$key]; + } + else + { + return null; + } + } + + function get_contributors() + { + $contributors = array(); + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor) + { + $name = null; + $uri = null; + $email = null; + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) + { + $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) + { + $uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) + { + $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $uri !== null) + { + $contributors[] =& new $this->author_class($name, $uri, $email); + } + } + foreach ((array) $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor) + { + $name = null; + $url = null; + $email = null; + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) + { + $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) + { + $url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) + { + $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $url !== null) + { + $contributors[] =& new $this->author_class($name, $url, $email); + } + } + + if (!empty($contributors)) + { + return SimplePie_Misc::array_unique($contributors); + } + else + { + return null; + } + } + + function get_link($key = 0, $rel = 'alternate') + { + $links = $this->get_links($rel); + if (isset($links[$key])) + { + return $links[$key]; + } + else + { + return null; + } + } + + /** + * Added for parity between the parent-level and the item/entry-level. + */ + function get_permalink() + { + return $this->get_link(0); + } + + function get_links($rel = 'alternate') + { + if (!isset($this->data['links'])) + { + $this->data['links'] = array(); + if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link')) + { + foreach ($links as $link) + { + if (isset($link['attribs']['']['href'])) + { + $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; + $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + } + } + } + if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link')) + { + foreach ($links as $link) + { + if (isset($link['attribs']['']['href'])) + { + $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; + $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + + } + } + } + if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_channel_tags('', 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + + $keys = array_keys($this->data['links']); + foreach ($keys as $key) + { + if (SimplePie_Misc::is_isegment_nz_nc($key)) + { + if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key])) + { + $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]); + $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; + } + else + { + $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; + } + } + elseif (substr($key, 0, 41) == SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY) + { + $this->data['links'][substr($key, 41)] =& $this->data['links'][$key]; + } + $this->data['links'][$key] = array_unique($this->data['links'][$key]); + } + } + + if (isset($this->data['links'][$rel])) + { + return $this->data['links'][$rel]; + } + else + { + return null; + } + } + + function get_description() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'subtitle')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'tagline')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags('', 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + else + { + return null; + } + } + + function get_copyright() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'copyright')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags('', 'copyright')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_language() + { + if ($return = $this->get_channel_tags('', 'language')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_11, 'language')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_DC_10, 'language')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['xml_lang'])) + { + return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['xml_lang'])) + { + return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['xml_lang'])) + { + return $this->sanitize($this->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($this->data['headers']['content-language'])) + { + return $this->sanitize($this->data['headers']['content-language'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_latitude() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat')) + { + return (float) $return[0]['data']; + } + elseif (($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', $return[0]['data'], $match)) + { + return (float) $match[1]; + } + else + { + return null; + } + } + + function get_longitude() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long')) + { + return (float) $return[0]['data']; + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon')) + { + return (float) $return[0]['data']; + } + elseif (($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', $return[0]['data'], $match)) + { + return (float) $match[2]; + } + else + { + return null; + } + } + + function get_image_title() + { + if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_image_tags('', 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_image_url() + { + if ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'image')) + { + return $this->sanitize($return[0]['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'logo')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_channel_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'url')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'url')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_image_tags('', 'url')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + else + { + return null; + } + } + + function get_image_link() + { + if ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_image_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_image_tags('', 'link')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + else + { + return null; + } + } + + function get_image_width() + { + if ($return = $this->get_image_tags('', 'width')) + { + return round($return[0]['data']); + } + elseif ($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION && $this->get_image_tags('', 'url')) + { + return 88.0; + } + else + { + return null; + } + } + + function get_image_height() + { + if ($return = $this->get_image_tags('', 'height')) + { + return round($return[0]['data']); + } + elseif ($this->get_type() & SIMPLEPIE_TYPE_RSS_SYNDICATION && $this->get_image_tags('', 'url')) + { + return 31.0; + } + else + { + return null; + } + } + + function get_item_quantity($max = 0) + { + $qty = count($this->get_items()); + if ($max == 0) + { + return $qty; + } + else + { + return ($qty > $max) ? $max : $qty; + } + } + + function get_item($key = 0) + { + $items = $this->get_items(); + if (isset($items[$key])) + { + return $items[$key]; + } + else + { + return null; + } + } + + function get_items($start = 0, $end = 0) + { + if (!empty($this->multifeed_objects)) + { + return SimplePie::merge_items($this->multifeed_objects, $start, $end, $this->item_limit); + } + elseif (!isset($this->data['items'])) + { + if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'entry')) + { + $keys = array_keys($items); + foreach ($keys as $key) + { + $this->data['items'][] =& new $this->item_class($this, $items[$key]); + } + } + if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'entry')) + { + $keys = array_keys($items); + foreach ($keys as $key) + { + $this->data['items'][] =& new $this->item_class($this, $items[$key]); + } + } + if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'item')) + { + $keys = array_keys($items); + foreach ($keys as $key) + { + $this->data['items'][] =& new $this->item_class($this, $items[$key]); + } + } + if ($items = $this->get_feed_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'item')) + { + $keys = array_keys($items); + foreach ($keys as $key) + { + $this->data['items'][] =& new $this->item_class($this, $items[$key]); + } + } + if ($items = $this->get_channel_tags('', 'item')) + { + $keys = array_keys($items); + foreach ($keys as $key) + { + $this->data['items'][] =& new $this->item_class($this, $items[$key]); + } + } + } + + if (!empty($this->data['items'])) + { + // If we want to order it by date, check if all items have a date, and then sort it + if ($this->order_by_date) + { + if (!isset($this->data['ordered_items'])) + { + $do_sort = true; + foreach ($this->data['items'] as $item) + { + if (!$item->get_date('U')) + { + $do_sort = false; + break; + } + } + $item = null; + $this->data['ordered_items'] = $this->data['items']; + if ($do_sort) + { + usort($this->data['ordered_items'], array(&$this, 'sort_items')); + } + } + $items = $this->data['ordered_items']; + } + else + { + $items = $this->data['items']; + } + + // Slice the data as desired + if ($end == 0) + { + return array_slice($items, $start); + } + else + { + return array_slice($items, $start, $end); + } + } + else + { + return array(); + } + } + + function sort_items($a, $b) + { + return $a->get_date('U') <= $b->get_date('U'); + } + + function merge_items($urls, $start = 0, $end = 0, $limit = 0) + { + if (is_array($urls) && sizeof($urls) > 0) + { + $items = array(); + foreach ($urls as $arg) + { + if (is_a($arg, 'SimplePie')) + { + $items = array_merge($items, $arg->get_items(0, $limit)); + } + else + { + trigger_error('Arguments must be SimplePie objects', E_USER_WARNING); + } + } + + $do_sort = true; + foreach ($items as $item) + { + if (!$item->get_date('U')) + { + $do_sort = false; + break; + } + } + $item = null; + if ($do_sort) + { + usort($items, array('SimplePie', 'sort_items')); + } + + if ($end == 0) + { + return array_slice($items, $start); + } + else + { + return array_slice($items, $start, $end); + } + } + else + { + trigger_error('Cannot merge zero SimplePie objects', E_USER_WARNING); + return array(); + } + } +} + +class SimplePie_Item +{ + var $feed; + var $data = array(); + + function SimplePie_Item($feed, $data) + { + $this->feed = $feed; + $this->data = $data; + } + + function __toString() + { + return md5(serialize($this->data)); + } + + /** + * Remove items that link back to this before destroying this object + */ + function __destruct() + { + if ((version_compare(PHP_VERSION, '5.3', '<') || !gc_enabled()) && !ini_get('zend.ze1_compatibility_mode')) + { + unset($this->feed); + } + } + + function get_item_tags($namespace, $tag) + { + if (isset($this->data['child'][$namespace][$tag])) + { + return $this->data['child'][$namespace][$tag]; + } + else + { + return null; + } + } + + function get_base($element = array()) + { + return $this->feed->get_base($element); + } + + function sanitize($data, $type, $base = '') + { + return $this->feed->sanitize($data, $type, $base); + } + + function get_feed() + { + return $this->feed; + } + + function get_id($hash = false) + { + if (!$hash) + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'id')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'id')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags('', 'guid')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'identifier')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'identifier')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (($return = $this->get_permalink()) !== null) + { + return $return; + } + elseif (($return = $this->get_title()) !== null) + { + return $return; + } + } + if ($this->get_permalink() !== null || $this->get_title() !== null) + { + return md5($this->get_permalink() . $this->get_title()); + } + else + { + return md5(serialize($this->data)); + } + } + + function get_title() + { + if (!isset($this->data['title'])) + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags('', 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) + { + $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $this->data['title'] = null; + } + } + return $this->data['title']; + } + + function get_description($description_only = false) + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'summary')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'summary')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags('', 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (!$description_only) + { + return $this->get_content(true); + } + else + { + return null; + } + } + + function get_content($content_only = false) + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'content')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_content_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'content')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT, 'encoded')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + elseif (!$content_only) + { + return $this->get_description(true); + } + else + { + return null; + } + } + + function get_category($key = 0) + { + $categories = $this->get_categories(); + if (isset($categories[$key])) + { + return $categories[$key]; + } + else + { + return null; + } + } + + function get_categories() + { + $categories = array(); + + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['attribs']['']['term'])) + { + $term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories[] =& new $this->feed->category_class($term, $scheme, $label); + } + foreach ((array) $this->get_item_tags('', 'category') as $category) + { + $categories[] =& new $this->feed->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category) + { + $categories[] =& new $this->feed->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category) + { + $categories[] =& new $this->feed->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + + if (!empty($categories)) + { + return SimplePie_Misc::array_unique($categories); + } + else + { + return null; + } + } + + function get_author($key = 0) + { + $authors = $this->get_authors(); + if (isset($authors[$key])) + { + return $authors[$key]; + } + else + { + return null; + } + } + + function get_contributor($key = 0) + { + $contributors = $this->get_contributors(); + if (isset($contributors[$key])) + { + return $contributors[$key]; + } + else + { + return null; + } + } + + function get_contributors() + { + $contributors = array(); + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor) + { + $name = null; + $uri = null; + $email = null; + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) + { + $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) + { + $uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) + { + $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $uri !== null) + { + $contributors[] =& new $this->feed->author_class($name, $uri, $email); + } + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor) + { + $name = null; + $url = null; + $email = null; + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) + { + $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) + { + $url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) + { + $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $url !== null) + { + $contributors[] =& new $this->feed->author_class($name, $url, $email); + } + } + + if (!empty($contributors)) + { + return SimplePie_Misc::array_unique($contributors); + } + else + { + return null; + } + } + + /** + * @todo Atom inheritance (item author, source author, feed author) + */ + function get_authors() + { + $authors = array(); + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author) + { + $name = null; + $uri = null; + $email = null; + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) + { + $name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) + { + $uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); + } + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) + { + $email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $uri !== null) + { + $authors[] =& new $this->feed->author_class($name, $uri, $email); + } + } + if ($author = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author')) + { + $name = null; + $url = null; + $email = null; + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) + { + $name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) + { + $url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); + } + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) + { + $email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $url !== null) + { + $authors[] =& new $this->feed->author_class($name, $url, $email); + } + } + if ($author = $this->get_item_tags('', 'author')) + { + $authors[] =& new $this->feed->author_class(null, null, $this->sanitize($author[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author) + { + $authors[] =& new $this->feed->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author) + { + $authors[] =& new $this->feed->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author) + { + $authors[] =& new $this->feed->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + + if (!empty($authors)) + { + return SimplePie_Misc::array_unique($authors); + } + elseif (($source = $this->get_source()) && ($authors = $source->get_authors())) + { + return $authors; + } + elseif ($authors = $this->feed->get_authors()) + { + return $authors; + } + else + { + return null; + } + } + + function get_copyright() + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_date($date_format = 'j F Y, g:i a') + { + if (!isset($this->data['date'])) + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'published')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'updated')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'issued')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'created')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'modified')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags('', 'pubDate')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'date')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'date')) + { + $this->data['date']['raw'] = $return[0]['data']; + } + + if (!empty($this->data['date']['raw'])) + { + $parser = SimplePie_Parse_Date::get(); + $this->data['date']['parsed'] = $parser->parse($this->data['date']['raw']); + } + else + { + $this->data['date'] = null; + } + } + if ($this->data['date']) + { + $date_format = (string) $date_format; + switch ($date_format) + { + case '': + return $this->sanitize($this->data['date']['raw'], SIMPLEPIE_CONSTRUCT_TEXT); + + case 'U': + return $this->data['date']['parsed']; + + default: + return date($date_format, $this->data['date']['parsed']); + } + } + else + { + return null; + } + } + + function get_local_date($date_format = '%c') + { + if (!$date_format) + { + return $this->sanitize($this->get_date(''), SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (($date = $this->get_date('U')) !== null) + { + return strftime($date_format, $date); + } + else + { + return null; + } + } + + function get_permalink() + { + $link = $this->get_link(); + $enclosure = $this->get_enclosure(0); + if ($link !== null) + { + return $link; + } + elseif ($enclosure !== null) + { + return $enclosure->get_link(); + } + else + { + return null; + } + } + + function get_link($key = 0, $rel = 'alternate') + { + $links = $this->get_links($rel); + if ($links[$key] !== null) + { + return $links[$key]; + } + else + { + return null; + } + } + + function get_links($rel = 'alternate') + { + if (!isset($this->data['links'])) + { + $this->data['links'] = array(); + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link') as $link) + { + if (isset($link['attribs']['']['href'])) + { + $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; + $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + + } + } + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link') as $link) + { + if (isset($link['attribs']['']['href'])) + { + $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; + $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + } + } + if ($links = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_item_tags('', 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_item_tags('', 'guid')) + { + if (!isset($links[0]['attribs']['']['isPermaLink']) || strtolower(trim($links[0]['attribs']['']['isPermaLink'])) == 'true') + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + } + + $keys = array_keys($this->data['links']); + foreach ($keys as $key) + { + if (SimplePie_Misc::is_isegment_nz_nc($key)) + { + if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key])) + { + $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]); + $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; + } + else + { + $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; + } + } + elseif (substr($key, 0, 41) == SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY) + { + $this->data['links'][substr($key, 41)] =& $this->data['links'][$key]; + } + $this->data['links'][$key] = array_unique($this->data['links'][$key]); + } + } + if (isset($this->data['links'][$rel])) + { + return $this->data['links'][$rel]; + } + else + { + return null; + } + } + + /** + * @todo Add ability to prefer one type of content over another (in a media group). + */ + function get_enclosure($key = 0, $prefer = null) + { + $enclosures = $this->get_enclosures(); + if (isset($enclosures[$key])) + { + return $enclosures[$key]; + } + else + { + return null; + } + } + + /** + * Grabs all available enclosures (podcasts, etc.) + * + * Supports the RSS tag, as well as Media RSS and iTunes RSS. + * + * At this point, we're pretty much assuming that all enclosures for an item are the same content. Anything else is too complicated to properly support. + * + * @todo Add support for end-user defined sorting of enclosures by type/handler (so we can prefer the faster-loading FLV over MP4). + * @todo If an element exists at a level, but it's value is empty, we should fall back to the value from the parent (if it exists). + */ + function get_enclosures() + { + if (!isset($this->data['enclosures'])) + { + $this->data['enclosures'] = array(); + + // Elements + $captions_parent = null; + $categories_parent = null; + $copyrights_parent = null; + $credits_parent = null; + $description_parent = null; + $duration_parent = null; + $hashes_parent = null; + $keywords_parent = null; + $player_parent = null; + $ratings_parent = null; + $restrictions_parent = null; + $thumbnails_parent = null; + $title_parent = null; + + // Let's do the channel and item-level ones first, and just re-use them if we need to. + $parent = $this->get_feed(); + + // CAPTIONS + if ($captions = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'text')) + { + foreach ($captions as $caption) + { + $caption_type = null; + $caption_lang = null; + $caption_startTime = null; + $caption_endTime = null; + $caption_text = null; + if (isset($caption['attribs']['']['type'])) + { + $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['lang'])) + { + $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['start'])) + { + $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['end'])) + { + $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['data'])) + { + $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $captions_parent[] =& new $this->feed->caption_class($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text); + } + } + elseif ($captions = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'text')) + { + foreach ($captions as $caption) + { + $caption_type = null; + $caption_lang = null; + $caption_startTime = null; + $caption_endTime = null; + $caption_text = null; + if (isset($caption['attribs']['']['type'])) + { + $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['lang'])) + { + $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['start'])) + { + $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['end'])) + { + $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['data'])) + { + $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $captions_parent[] =& new $this->feed->caption_class($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text); + } + } + if (is_array($captions_parent)) + { + $captions_parent = array_values(SimplePie_Misc::array_unique($captions_parent)); + } + + // CATEGORIES + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'category') as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['data'])) + { + $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $scheme = 'http://search.yahoo.com/mrss/category_schema'; + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories_parent[] =& new $this->feed->category_class($term, $scheme, $label); + } + foreach ((array) $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'category') as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['data'])) + { + $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $scheme = 'http://search.yahoo.com/mrss/category_schema'; + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories_parent[] =& new $this->feed->category_class($term, $scheme, $label); + } + foreach ((array) $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'category') as $category) + { + $term = null; + $scheme = 'http://www.itunes.com/dtds/podcast-1.0.dtd'; + $label = null; + if (isset($category['attribs']['']['text'])) + { + $label = $this->sanitize($category['attribs']['']['text'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories_parent[] =& new $this->feed->category_class($term, $scheme, $label); + + if (isset($category['child'][SIMPLEPIE_NAMESPACE_ITUNES]['category'])) + { + foreach ((array) $category['child'][SIMPLEPIE_NAMESPACE_ITUNES]['category'] as $subcategory) + { + if (isset($subcategory['attribs']['']['text'])) + { + $label = $this->sanitize($subcategory['attribs']['']['text'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories_parent[] =& new $this->feed->category_class($term, $scheme, $label); + } + } + } + if (is_array($categories_parent)) + { + $categories_parent = array_values(SimplePie_Misc::array_unique($categories_parent)); + } + + // COPYRIGHT + if ($copyright = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'copyright')) + { + $copyright_url = null; + $copyright_label = null; + if (isset($copyright[0]['attribs']['']['url'])) + { + $copyright_url = $this->sanitize($copyright[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($copyright[0]['data'])) + { + $copyright_label = $this->sanitize($copyright[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $copyrights_parent =& new $this->feed->copyright_class($copyright_url, $copyright_label); + } + elseif ($copyright = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'copyright')) + { + $copyright_url = null; + $copyright_label = null; + if (isset($copyright[0]['attribs']['']['url'])) + { + $copyright_url = $this->sanitize($copyright[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($copyright[0]['data'])) + { + $copyright_label = $this->sanitize($copyright[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $copyrights_parent =& new $this->feed->copyright_class($copyright_url, $copyright_label); + } + + // CREDITS + if ($credits = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'credit')) + { + foreach ($credits as $credit) + { + $credit_role = null; + $credit_scheme = null; + $credit_name = null; + if (isset($credit['attribs']['']['role'])) + { + $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($credit['attribs']['']['scheme'])) + { + $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $credit_scheme = 'urn:ebu'; + } + if (isset($credit['data'])) + { + $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $credits_parent[] =& new $this->feed->credit_class($credit_role, $credit_scheme, $credit_name); + } + } + elseif ($credits = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'credit')) + { + foreach ($credits as $credit) + { + $credit_role = null; + $credit_scheme = null; + $credit_name = null; + if (isset($credit['attribs']['']['role'])) + { + $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($credit['attribs']['']['scheme'])) + { + $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $credit_scheme = 'urn:ebu'; + } + if (isset($credit['data'])) + { + $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $credits_parent[] =& new $this->feed->credit_class($credit_role, $credit_scheme, $credit_name); + } + } + if (is_array($credits_parent)) + { + $credits_parent = array_values(SimplePie_Misc::array_unique($credits_parent)); + } + + // DESCRIPTION + if ($description_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'description')) + { + if (isset($description_parent[0]['data'])) + { + $description_parent = $this->sanitize($description_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + } + elseif ($description_parent = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'description')) + { + if (isset($description_parent[0]['data'])) + { + $description_parent = $this->sanitize($description_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + } + + // DURATION + if ($duration_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'duration')) + { + $seconds = null; + $minutes = null; + $hours = null; + if (isset($duration_parent[0]['data'])) + { + $temp = explode(':', $this->sanitize($duration_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + if (sizeof($temp) > 0) + { + (int) $seconds = array_pop($temp); + } + if (sizeof($temp) > 0) + { + (int) $minutes = array_pop($temp); + $seconds += $minutes * 60; + } + if (sizeof($temp) > 0) + { + (int) $hours = array_pop($temp); + $seconds += $hours * 3600; + } + unset($temp); + $duration_parent = $seconds; + } + } + + // HASHES + if ($hashes_iterator = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'hash')) + { + foreach ($hashes_iterator as $hash) + { + $value = null; + $algo = null; + if (isset($hash['data'])) + { + $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($hash['attribs']['']['algo'])) + { + $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $algo = 'md5'; + } + $hashes_parent[] = $algo.':'.$value; + } + } + elseif ($hashes_iterator = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'hash')) + { + foreach ($hashes_iterator as $hash) + { + $value = null; + $algo = null; + if (isset($hash['data'])) + { + $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($hash['attribs']['']['algo'])) + { + $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $algo = 'md5'; + } + $hashes_parent[] = $algo.':'.$value; + } + } + if (is_array($hashes_parent)) + { + $hashes_parent = array_values(SimplePie_Misc::array_unique($hashes_parent)); + } + + // KEYWORDS + if ($keywords = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'keywords')) + { + if (isset($keywords[0]['data'])) + { + $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords_parent[] = trim($word); + } + } + unset($temp); + } + elseif ($keywords = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'keywords')) + { + if (isset($keywords[0]['data'])) + { + $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords_parent[] = trim($word); + } + } + unset($temp); + } + elseif ($keywords = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'keywords')) + { + if (isset($keywords[0]['data'])) + { + $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords_parent[] = trim($word); + } + } + unset($temp); + } + elseif ($keywords = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'keywords')) + { + if (isset($keywords[0]['data'])) + { + $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords_parent[] = trim($word); + } + } + unset($temp); + } + if (is_array($keywords_parent)) + { + $keywords_parent = array_values(SimplePie_Misc::array_unique($keywords_parent)); + } + + // PLAYER + if ($player_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'player')) + { + if (isset($player_parent[0]['attribs']['']['url'])) + { + $player_parent = $this->sanitize($player_parent[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + } + elseif ($player_parent = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'player')) + { + if (isset($player_parent[0]['attribs']['']['url'])) + { + $player_parent = $this->sanitize($player_parent[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + } + + // RATINGS + if ($ratings = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'rating')) + { + foreach ($ratings as $rating) + { + $rating_scheme = null; + $rating_value = null; + if (isset($rating['attribs']['']['scheme'])) + { + $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $rating_scheme = 'urn:simple'; + } + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings_parent[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + } + elseif ($ratings = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'explicit')) + { + foreach ($ratings as $rating) + { + $rating_scheme = 'urn:itunes'; + $rating_value = null; + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings_parent[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + } + elseif ($ratings = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'rating')) + { + foreach ($ratings as $rating) + { + $rating_scheme = null; + $rating_value = null; + if (isset($rating['attribs']['']['scheme'])) + { + $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $rating_scheme = 'urn:simple'; + } + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings_parent[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + } + elseif ($ratings = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'explicit')) + { + foreach ($ratings as $rating) + { + $rating_scheme = 'urn:itunes'; + $rating_value = null; + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings_parent[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + } + if (is_array($ratings_parent)) + { + $ratings_parent = array_values(SimplePie_Misc::array_unique($ratings_parent)); + } + + // RESTRICTIONS + if ($restrictions = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'restriction')) + { + foreach ($restrictions as $restriction) + { + $restriction_relationship = null; + $restriction_type = null; + $restriction_value = null; + if (isset($restriction['attribs']['']['relationship'])) + { + $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['attribs']['']['type'])) + { + $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['data'])) + { + $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $restrictions_parent[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + } + elseif ($restrictions = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'block')) + { + foreach ($restrictions as $restriction) + { + $restriction_relationship = 'allow'; + $restriction_type = null; + $restriction_value = 'itunes'; + if (isset($restriction['data']) && strtolower($restriction['data']) == 'yes') + { + $restriction_relationship = 'deny'; + } + $restrictions_parent[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + } + elseif ($restrictions = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'restriction')) + { + foreach ($restrictions as $restriction) + { + $restriction_relationship = null; + $restriction_type = null; + $restriction_value = null; + if (isset($restriction['attribs']['']['relationship'])) + { + $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['attribs']['']['type'])) + { + $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['data'])) + { + $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $restrictions_parent[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + } + elseif ($restrictions = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'block')) + { + foreach ($restrictions as $restriction) + { + $restriction_relationship = 'allow'; + $restriction_type = null; + $restriction_value = 'itunes'; + if (isset($restriction['data']) && strtolower($restriction['data']) == 'yes') + { + $restriction_relationship = 'deny'; + } + $restrictions_parent[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + } + if (is_array($restrictions_parent)) + { + $restrictions_parent = array_values(SimplePie_Misc::array_unique($restrictions_parent)); + } + + // THUMBNAILS + if ($thumbnails = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail')) + { + foreach ($thumbnails as $thumbnail) + { + if (isset($thumbnail['attribs']['']['url'])) + { + $thumbnails_parent[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + } + } + elseif ($thumbnails = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail')) + { + foreach ($thumbnails as $thumbnail) + { + if (isset($thumbnail['attribs']['']['url'])) + { + $thumbnails_parent[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + } + } + + // TITLES + if ($title_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'title')) + { + if (isset($title_parent[0]['data'])) + { + $title_parent = $this->sanitize($title_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + } + elseif ($title_parent = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'title')) + { + if (isset($title_parent[0]['data'])) + { + $title_parent = $this->sanitize($title_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + } + + // Clear the memory + unset($parent); + + // Attributes + $bitrate = null; + $channels = null; + $duration = null; + $expression = null; + $framerate = null; + $height = null; + $javascript = null; + $lang = null; + $length = null; + $medium = null; + $samplingrate = null; + $type = null; + $url = null; + $width = null; + + // Elements + $captions = null; + $categories = null; + $copyrights = null; + $credits = null; + $description = null; + $hashes = null; + $keywords = null; + $player = null; + $ratings = null; + $restrictions = null; + $thumbnails = null; + $title = null; + + // If we have media:group tags, loop through them. + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'group') as $group) + { + // If we have media:content tags, loop through them. + foreach ((array) $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] as $content) + { + if (isset($content['attribs']['']['url'])) + { + // Attributes + $bitrate = null; + $channels = null; + $duration = null; + $expression = null; + $framerate = null; + $height = null; + $javascript = null; + $lang = null; + $length = null; + $medium = null; + $samplingrate = null; + $type = null; + $url = null; + $width = null; + + // Elements + $captions = null; + $categories = null; + $copyrights = null; + $credits = null; + $description = null; + $hashes = null; + $keywords = null; + $player = null; + $ratings = null; + $restrictions = null; + $thumbnails = null; + $title = null; + + // Start checking the attributes of media:content + if (isset($content['attribs']['']['bitrate'])) + { + $bitrate = $this->sanitize($content['attribs']['']['bitrate'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['channels'])) + { + $channels = $this->sanitize($content['attribs']['']['channels'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['duration'])) + { + $duration = $this->sanitize($content['attribs']['']['duration'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $duration = $duration_parent; + } + if (isset($content['attribs']['']['expression'])) + { + $expression = $this->sanitize($content['attribs']['']['expression'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['framerate'])) + { + $framerate = $this->sanitize($content['attribs']['']['framerate'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['height'])) + { + $height = $this->sanitize($content['attribs']['']['height'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['lang'])) + { + $lang = $this->sanitize($content['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['fileSize'])) + { + $length = ceil($content['attribs']['']['fileSize']); + } + if (isset($content['attribs']['']['medium'])) + { + $medium = $this->sanitize($content['attribs']['']['medium'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['samplingrate'])) + { + $samplingrate = $this->sanitize($content['attribs']['']['samplingrate'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['type'])) + { + $type = $this->sanitize($content['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['width'])) + { + $width = $this->sanitize($content['attribs']['']['width'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $url = $this->sanitize($content['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + + // Checking the other optional media: elements. Priority: media:content, media:group, item, channel + + // CAPTIONS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption) + { + $caption_type = null; + $caption_lang = null; + $caption_startTime = null; + $caption_endTime = null; + $caption_text = null; + if (isset($caption['attribs']['']['type'])) + { + $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['lang'])) + { + $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['start'])) + { + $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['end'])) + { + $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['data'])) + { + $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $captions[] =& new $this->feed->caption_class($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text); + } + if (is_array($captions)) + { + $captions = array_values(SimplePie_Misc::array_unique($captions)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'])) + { + foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption) + { + $caption_type = null; + $caption_lang = null; + $caption_startTime = null; + $caption_endTime = null; + $caption_text = null; + if (isset($caption['attribs']['']['type'])) + { + $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['lang'])) + { + $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['start'])) + { + $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['end'])) + { + $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['data'])) + { + $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $captions[] =& new $this->feed->caption_class($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text); + } + if (is_array($captions)) + { + $captions = array_values(SimplePie_Misc::array_unique($captions)); + } + } + else + { + $captions = $captions_parent; + } + + // CATEGORIES + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'])) + { + foreach ((array) $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['data'])) + { + $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $scheme = 'http://search.yahoo.com/mrss/category_schema'; + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories[] =& new $this->feed->category_class($term, $scheme, $label); + } + } + if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'])) + { + foreach ((array) $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['data'])) + { + $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $scheme = 'http://search.yahoo.com/mrss/category_schema'; + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories[] =& new $this->feed->category_class($term, $scheme, $label); + } + } + if (is_array($categories) && is_array($categories_parent)) + { + $categories = array_values(SimplePie_Misc::array_unique(array_merge($categories, $categories_parent))); + } + elseif (is_array($categories)) + { + $categories = array_values(SimplePie_Misc::array_unique($categories)); + } + elseif (is_array($categories_parent)) + { + $categories = array_values(SimplePie_Misc::array_unique($categories_parent)); + } + + // COPYRIGHTS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'])) + { + $copyright_url = null; + $copyright_label = null; + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) + { + $copyright_url = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'])) + { + $copyright_label = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $copyrights =& new $this->feed->copyright_class($copyright_url, $copyright_label); + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'])) + { + $copyright_url = null; + $copyright_label = null; + if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) + { + $copyright_url = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'])) + { + $copyright_label = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $copyrights =& new $this->feed->copyright_class($copyright_url, $copyright_label); + } + else + { + $copyrights = $copyrights_parent; + } + + // CREDITS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit) + { + $credit_role = null; + $credit_scheme = null; + $credit_name = null; + if (isset($credit['attribs']['']['role'])) + { + $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($credit['attribs']['']['scheme'])) + { + $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $credit_scheme = 'urn:ebu'; + } + if (isset($credit['data'])) + { + $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $credits[] =& new $this->feed->credit_class($credit_role, $credit_scheme, $credit_name); + } + if (is_array($credits)) + { + $credits = array_values(SimplePie_Misc::array_unique($credits)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'])) + { + foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit) + { + $credit_role = null; + $credit_scheme = null; + $credit_name = null; + if (isset($credit['attribs']['']['role'])) + { + $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($credit['attribs']['']['scheme'])) + { + $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $credit_scheme = 'urn:ebu'; + } + if (isset($credit['data'])) + { + $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $credits[] =& new $this->feed->credit_class($credit_role, $credit_scheme, $credit_name); + } + if (is_array($credits)) + { + $credits = array_values(SimplePie_Misc::array_unique($credits)); + } + } + else + { + $credits = $credits_parent; + } + + // DESCRIPTION + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'])) + { + $description = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'])) + { + $description = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $description = $description_parent; + } + + // HASHES + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash) + { + $value = null; + $algo = null; + if (isset($hash['data'])) + { + $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($hash['attribs']['']['algo'])) + { + $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $algo = 'md5'; + } + $hashes[] = $algo.':'.$value; + } + if (is_array($hashes)) + { + $hashes = array_values(SimplePie_Misc::array_unique($hashes)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'])) + { + foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash) + { + $value = null; + $algo = null; + if (isset($hash['data'])) + { + $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($hash['attribs']['']['algo'])) + { + $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $algo = 'md5'; + } + $hashes[] = $algo.':'.$value; + } + if (is_array($hashes)) + { + $hashes = array_values(SimplePie_Misc::array_unique($hashes)); + } + } + else + { + $hashes = $hashes_parent; + } + + // KEYWORDS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'])) + { + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'])) + { + $temp = explode(',', $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords[] = trim($word); + } + unset($temp); + } + if (is_array($keywords)) + { + $keywords = array_values(SimplePie_Misc::array_unique($keywords)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'])) + { + if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'])) + { + $temp = explode(',', $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords[] = trim($word); + } + unset($temp); + } + if (is_array($keywords)) + { + $keywords = array_values(SimplePie_Misc::array_unique($keywords)); + } + } + else + { + $keywords = $keywords_parent; + } + + // PLAYER + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) + { + $player = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) + { + $player = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + $player = $player_parent; + } + + // RATINGS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating) + { + $rating_scheme = null; + $rating_value = null; + if (isset($rating['attribs']['']['scheme'])) + { + $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $rating_scheme = 'urn:simple'; + } + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + if (is_array($ratings)) + { + $ratings = array_values(SimplePie_Misc::array_unique($ratings)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'])) + { + foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating) + { + $rating_scheme = null; + $rating_value = null; + if (isset($rating['attribs']['']['scheme'])) + { + $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $rating_scheme = 'urn:simple'; + } + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + if (is_array($ratings)) + { + $ratings = array_values(SimplePie_Misc::array_unique($ratings)); + } + } + else + { + $ratings = $ratings_parent; + } + + // RESTRICTIONS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction) + { + $restriction_relationship = null; + $restriction_type = null; + $restriction_value = null; + if (isset($restriction['attribs']['']['relationship'])) + { + $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['attribs']['']['type'])) + { + $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['data'])) + { + $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $restrictions[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + if (is_array($restrictions)) + { + $restrictions = array_values(SimplePie_Misc::array_unique($restrictions)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'])) + { + foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction) + { + $restriction_relationship = null; + $restriction_type = null; + $restriction_value = null; + if (isset($restriction['attribs']['']['relationship'])) + { + $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['attribs']['']['type'])) + { + $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['data'])) + { + $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $restrictions[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + if (is_array($restrictions)) + { + $restrictions = array_values(SimplePie_Misc::array_unique($restrictions)); + } + } + else + { + $restrictions = $restrictions_parent; + } + + // THUMBNAILS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) + { + $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + if (is_array($thumbnails)) + { + $thumbnails = array_values(SimplePie_Misc::array_unique($thumbnails)); + } + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'])) + { + foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) + { + $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + if (is_array($thumbnails)) + { + $thumbnails = array_values(SimplePie_Misc::array_unique($thumbnails)); + } + } + else + { + $thumbnails = $thumbnails_parent; + } + + // TITLES + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'])) + { + $title = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'])) + { + $title = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $title = $title_parent; + } + + $this->data['enclosures'][] =& new $this->feed->enclosure_class($url, $type, $length, $this->feed->javascript, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width); + } + } + } + + // If we have standalone media:content tags, loop through them. + if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'])) + { + foreach ((array) $this->data['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] as $content) + { + if (isset($content['attribs']['']['url'])) + { + // Attributes + $bitrate = null; + $channels = null; + $duration = null; + $expression = null; + $framerate = null; + $height = null; + $javascript = null; + $lang = null; + $length = null; + $medium = null; + $samplingrate = null; + $type = null; + $url = null; + $width = null; + + // Elements + $captions = null; + $categories = null; + $copyrights = null; + $credits = null; + $description = null; + $hashes = null; + $keywords = null; + $player = null; + $ratings = null; + $restrictions = null; + $thumbnails = null; + $title = null; + + // Start checking the attributes of media:content + if (isset($content['attribs']['']['bitrate'])) + { + $bitrate = $this->sanitize($content['attribs']['']['bitrate'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['channels'])) + { + $channels = $this->sanitize($content['attribs']['']['channels'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['duration'])) + { + $duration = $this->sanitize($content['attribs']['']['duration'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $duration = $duration_parent; + } + if (isset($content['attribs']['']['expression'])) + { + $expression = $this->sanitize($content['attribs']['']['expression'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['framerate'])) + { + $framerate = $this->sanitize($content['attribs']['']['framerate'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['height'])) + { + $height = $this->sanitize($content['attribs']['']['height'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['lang'])) + { + $lang = $this->sanitize($content['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['fileSize'])) + { + $length = ceil($content['attribs']['']['fileSize']); + } + if (isset($content['attribs']['']['medium'])) + { + $medium = $this->sanitize($content['attribs']['']['medium'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['samplingrate'])) + { + $samplingrate = $this->sanitize($content['attribs']['']['samplingrate'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['type'])) + { + $type = $this->sanitize($content['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['attribs']['']['width'])) + { + $width = $this->sanitize($content['attribs']['']['width'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $url = $this->sanitize($content['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + + // Checking the other optional media: elements. Priority: media:content, media:group, item, channel + + // CAPTIONS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption) + { + $caption_type = null; + $caption_lang = null; + $caption_startTime = null; + $caption_endTime = null; + $caption_text = null; + if (isset($caption['attribs']['']['type'])) + { + $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['lang'])) + { + $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['start'])) + { + $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['attribs']['']['end'])) + { + $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($caption['data'])) + { + $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $captions[] =& new $this->feed->caption_class($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text); + } + if (is_array($captions)) + { + $captions = array_values(SimplePie_Misc::array_unique($captions)); + } + } + else + { + $captions = $captions_parent; + } + + // CATEGORIES + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'])) + { + foreach ((array) $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['data'])) + { + $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $scheme = 'http://search.yahoo.com/mrss/category_schema'; + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories[] =& new $this->feed->category_class($term, $scheme, $label); + } + } + if (is_array($categories) && is_array($categories_parent)) + { + $categories = array_values(SimplePie_Misc::array_unique(array_merge($categories, $categories_parent))); + } + elseif (is_array($categories)) + { + $categories = array_values(SimplePie_Misc::array_unique($categories)); + } + elseif (is_array($categories_parent)) + { + $categories = array_values(SimplePie_Misc::array_unique($categories_parent)); + } + else + { + $categories = null; + } + + // COPYRIGHTS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'])) + { + $copyright_url = null; + $copyright_label = null; + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) + { + $copyright_url = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'])) + { + $copyright_label = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $copyrights =& new $this->feed->copyright_class($copyright_url, $copyright_label); + } + else + { + $copyrights = $copyrights_parent; + } + + // CREDITS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit) + { + $credit_role = null; + $credit_scheme = null; + $credit_name = null; + if (isset($credit['attribs']['']['role'])) + { + $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($credit['attribs']['']['scheme'])) + { + $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $credit_scheme = 'urn:ebu'; + } + if (isset($credit['data'])) + { + $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $credits[] =& new $this->feed->credit_class($credit_role, $credit_scheme, $credit_name); + } + if (is_array($credits)) + { + $credits = array_values(SimplePie_Misc::array_unique($credits)); + } + } + else + { + $credits = $credits_parent; + } + + // DESCRIPTION + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'])) + { + $description = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $description = $description_parent; + } + + // HASHES + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash) + { + $value = null; + $algo = null; + if (isset($hash['data'])) + { + $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($hash['attribs']['']['algo'])) + { + $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $algo = 'md5'; + } + $hashes[] = $algo.':'.$value; + } + if (is_array($hashes)) + { + $hashes = array_values(SimplePie_Misc::array_unique($hashes)); + } + } + else + { + $hashes = $hashes_parent; + } + + // KEYWORDS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'])) + { + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'])) + { + $temp = explode(',', $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); + foreach ($temp as $word) + { + $keywords[] = trim($word); + } + unset($temp); + } + if (is_array($keywords)) + { + $keywords = array_values(SimplePie_Misc::array_unique($keywords)); + } + } + else + { + $keywords = $keywords_parent; + } + + // PLAYER + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) + { + $player = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + else + { + $player = $player_parent; + } + + // RATINGS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating) + { + $rating_scheme = null; + $rating_value = null; + if (isset($rating['attribs']['']['scheme'])) + { + $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $rating_scheme = 'urn:simple'; + } + if (isset($rating['data'])) + { + $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $ratings[] =& new $this->feed->rating_class($rating_scheme, $rating_value); + } + if (is_array($ratings)) + { + $ratings = array_values(SimplePie_Misc::array_unique($ratings)); + } + } + else + { + $ratings = $ratings_parent; + } + + // RESTRICTIONS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction) + { + $restriction_relationship = null; + $restriction_type = null; + $restriction_value = null; + if (isset($restriction['attribs']['']['relationship'])) + { + $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['attribs']['']['type'])) + { + $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($restriction['data'])) + { + $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $restrictions[] =& new $this->feed->restriction_class($restriction_relationship, $restriction_type, $restriction_value); + } + if (is_array($restrictions)) + { + $restrictions = array_values(SimplePie_Misc::array_unique($restrictions)); + } + } + else + { + $restrictions = $restrictions_parent; + } + + // THUMBNAILS + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'])) + { + foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) + { + $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); + } + if (is_array($thumbnails)) + { + $thumbnails = array_values(SimplePie_Misc::array_unique($thumbnails)); + } + } + else + { + $thumbnails = $thumbnails_parent; + } + + // TITLES + if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'])) + { + $title = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + $title = $title_parent; + } + + $this->data['enclosures'][] =& new $this->feed->enclosure_class($url, $type, $length, $this->feed->javascript, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width); + } + } + } + + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link') as $link) + { + if (isset($link['attribs']['']['href']) && !empty($link['attribs']['']['rel']) && $link['attribs']['']['rel'] == 'enclosure') + { + // Attributes + $bitrate = null; + $channels = null; + $duration = null; + $expression = null; + $framerate = null; + $height = null; + $javascript = null; + $lang = null; + $length = null; + $medium = null; + $samplingrate = null; + $type = null; + $url = null; + $width = null; + + $url = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + if (isset($link['attribs']['']['type'])) + { + $type = $this->sanitize($link['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($link['attribs']['']['length'])) + { + $length = ceil($link['attribs']['']['length']); + } + + // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor + $this->data['enclosures'][] =& new $this->feed->enclosure_class($url, $type, $length, $this->feed->javascript, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width); + } + } + + foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link') as $link) + { + if (isset($link['attribs']['']['href']) && !empty($link['attribs']['']['rel']) && $link['attribs']['']['rel'] == 'enclosure') + { + // Attributes + $bitrate = null; + $channels = null; + $duration = null; + $expression = null; + $framerate = null; + $height = null; + $javascript = null; + $lang = null; + $length = null; + $medium = null; + $samplingrate = null; + $type = null; + $url = null; + $width = null; + + $url = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + if (isset($link['attribs']['']['type'])) + { + $type = $this->sanitize($link['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($link['attribs']['']['length'])) + { + $length = ceil($link['attribs']['']['length']); + } + + // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor + $this->data['enclosures'][] =& new $this->feed->enclosure_class($url, $type, $length, $this->feed->javascript, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width); + } + } + + if ($enclosure = $this->get_item_tags('', 'enclosure')) + { + if (isset($enclosure[0]['attribs']['']['url'])) + { + // Attributes + $bitrate = null; + $channels = null; + $duration = null; + $expression = null; + $framerate = null; + $height = null; + $javascript = null; + $lang = null; + $length = null; + $medium = null; + $samplingrate = null; + $type = null; + $url = null; + $width = null; + + $url = $this->sanitize($enclosure[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($enclosure[0])); + if (isset($enclosure[0]['attribs']['']['type'])) + { + $type = $this->sanitize($enclosure[0]['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($enclosure[0]['attribs']['']['length'])) + { + $length = ceil($enclosure[0]['attribs']['']['length']); + } + + // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor + $this->data['enclosures'][] =& new $this->feed->enclosure_class($url, $type, $length, $this->feed->javascript, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width); + } + } + + if (sizeof($this->data['enclosures']) == 0 && ($url || $type || $length || $bitrate || $captions_parent || $categories_parent || $channels || $copyrights_parent || $credits_parent || $description_parent || $duration_parent || $expression || $framerate || $hashes_parent || $height || $keywords_parent || $lang || $medium || $player_parent || $ratings_parent || $restrictions_parent || $samplingrate || $thumbnails_parent || $title_parent || $width)) + { + // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor + $this->data['enclosures'][] =& new $this->feed->enclosure_class($url, $type, $length, $this->feed->javascript, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width); + } + + $this->data['enclosures'] = array_values(SimplePie_Misc::array_unique($this->data['enclosures'])); + } + if (!empty($this->data['enclosures'])) + { + return $this->data['enclosures']; + } + else + { + return null; + } + } + + function get_latitude() + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat')) + { + return (float) $return[0]['data']; + } + elseif (($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', $return[0]['data'], $match)) + { + return (float) $match[1]; + } + else + { + return null; + } + } + + function get_longitude() + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long')) + { + return (float) $return[0]['data']; + } + elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon')) + { + return (float) $return[0]['data']; + } + elseif (($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', $return[0]['data'], $match)) + { + return (float) $match[2]; + } + else + { + return null; + } + } + + function get_source() + { + if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'source')) + { + return new $this->feed->source_class($this, $return[0]); + } + else + { + return null; + } + } + + /** + * Creates the add_to_* methods' return data + * + * @access private + * @param string $item_url String to prefix to the item permalink + * @param string $title_url String to prefix to the item title + * (and suffix to the item permalink) + * @return mixed URL if feed exists, false otherwise + */ + function add_to_service($item_url, $title_url = null, $summary_url = null) + { + if ($this->get_permalink() !== null) + { + $return = $this->sanitize($item_url, SIMPLEPIE_CONSTRUCT_IRI) . rawurlencode($this->get_permalink()); + if ($title_url !== null && $this->get_title() !== null) + { + $return .= $this->sanitize($title_url, SIMPLEPIE_CONSTRUCT_IRI) . rawurlencode($this->get_title()); + } + if ($summary_url !== null && $this->get_description() !== null) + { + $return .= $this->sanitize($summary_url, SIMPLEPIE_CONSTRUCT_IRI) . rawurlencode($this->get_description()); + } + return $return; + } + else + { + return null; + } + } + + function add_to_blinklist() + { + return $this->add_to_service('http://www.blinklist.com/index.php?Action=Blink/addblink.php&Description=&Url=', '&Title='); + } + + function add_to_blogmarks() + { + return $this->add_to_service('http://blogmarks.net/my/new.php?mini=1&simple=1&url=', '&title='); + } + + function add_to_delicious() + { + return $this->add_to_service('http://del.icio.us/post/?v=4&url=', '&title='); + } + + function add_to_digg() + { + return $this->add_to_service('http://digg.com/submit?url=', '&title=', '&bodytext='); + } + + function add_to_furl() + { + return $this->add_to_service('http://www.furl.net/storeIt.jsp?u=', '&t='); + } + + function add_to_magnolia() + { + return $this->add_to_service('http://ma.gnolia.com/bookmarklet/add?url=', '&title='); + } + + function add_to_myweb20() + { + return $this->add_to_service('http://myweb2.search.yahoo.com/myresults/bookmarklet?u=', '&t='); + } + + function add_to_newsvine() + { + return $this->add_to_service('http://www.newsvine.com/_wine/save?u=', '&h='); + } + + function add_to_reddit() + { + return $this->add_to_service('http://reddit.com/submit?url=', '&title='); + } + + function add_to_segnalo() + { + return $this->add_to_service('http://segnalo.com/post.html.php?url=', '&title='); + } + + function add_to_simpy() + { + return $this->add_to_service('http://www.simpy.com/simpy/LinkAdd.do?href=', '&title='); + } + + function add_to_spurl() + { + return $this->add_to_service('http://www.spurl.net/spurl.php?v=3&url=', '&title='); + } + + function add_to_wists() + { + return $this->add_to_service('http://wists.com/r.php?c=&r=', '&title='); + } + + function search_technorati() + { + return $this->add_to_service('http://www.technorati.com/search/'); + } +} + +class SimplePie_Source +{ + var $item; + var $data = array(); + + function SimplePie_Source($item, $data) + { + $this->item = $item; + $this->data = $data; + } + + function __toString() + { + return md5(serialize($this->data)); + } + + function get_source_tags($namespace, $tag) + { + if (isset($this->data['child'][$namespace][$tag])) + { + return $this->data['child'][$namespace][$tag]; + } + else + { + return null; + } + } + + function get_base($element = array()) + { + return $this->item->get_base($element); + } + + function sanitize($data, $type, $base = '') + { + return $this->item->sanitize($data, $type, $base); + } + + function get_item() + { + return $this->item; + } + + function get_title() + { + if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags('', 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_category($key = 0) + { + $categories = $this->get_categories(); + if (isset($categories[$key])) + { + return $categories[$key]; + } + else + { + return null; + } + } + + function get_categories() + { + $categories = array(); + + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category) + { + $term = null; + $scheme = null; + $label = null; + if (isset($category['attribs']['']['term'])) + { + $term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['scheme'])) + { + $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($category['attribs']['']['label'])) + { + $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); + } + $categories[] =& new $this->item->feed->category_class($term, $scheme, $label); + } + foreach ((array) $this->get_source_tags('', 'category') as $category) + { + $categories[] =& new $this->item->feed->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category) + { + $categories[] =& new $this->item->feed->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category) + { + $categories[] =& new $this->item->feed->category_class($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + + if (!empty($categories)) + { + return SimplePie_Misc::array_unique($categories); + } + else + { + return null; + } + } + + function get_author($key = 0) + { + $authors = $this->get_authors(); + if (isset($authors[$key])) + { + return $authors[$key]; + } + else + { + return null; + } + } + + function get_authors() + { + $authors = array(); + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author) + { + $name = null; + $uri = null; + $email = null; + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) + { + $name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) + { + $uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); + } + if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) + { + $email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $uri !== null) + { + $authors[] =& new $this->item->feed->author_class($name, $uri, $email); + } + } + if ($author = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author')) + { + $name = null; + $url = null; + $email = null; + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) + { + $name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) + { + $url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); + } + if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) + { + $email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $url !== null) + { + $authors[] =& new $this->item->feed->author_class($name, $url, $email); + } + } + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author) + { + $authors[] =& new $this->item->feed->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author) + { + $authors[] =& new $this->item->feed->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author) + { + $authors[] =& new $this->item->feed->author_class($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null); + } + + if (!empty($authors)) + { + return SimplePie_Misc::array_unique($authors); + } + else + { + return null; + } + } + + function get_contributor($key = 0) + { + $contributors = $this->get_contributors(); + if (isset($contributors[$key])) + { + return $contributors[$key]; + } + else + { + return null; + } + } + + function get_contributors() + { + $contributors = array(); + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor) + { + $name = null; + $uri = null; + $email = null; + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) + { + $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) + { + $uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) + { + $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $uri !== null) + { + $contributors[] =& new $this->item->feed->author_class($name, $uri, $email); + } + } + foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor) + { + $name = null; + $url = null; + $email = null; + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) + { + $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) + { + $url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); + } + if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) + { + $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + if ($name !== null || $email !== null || $url !== null) + { + $contributors[] =& new $this->item->feed->author_class($name, $url, $email); + } + } + + if (!empty($contributors)) + { + return SimplePie_Misc::array_unique($contributors); + } + else + { + return null; + } + } + + function get_link($key = 0, $rel = 'alternate') + { + $links = $this->get_links($rel); + if (isset($links[$key])) + { + return $links[$key]; + } + else + { + return null; + } + } + + /** + * Added for parity between the parent-level and the item/entry-level. + */ + function get_permalink() + { + return $this->get_link(0); + } + + function get_links($rel = 'alternate') + { + if (!isset($this->data['links'])) + { + $this->data['links'] = array(); + if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link')) + { + foreach ($links as $link) + { + if (isset($link['attribs']['']['href'])) + { + $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; + $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + } + } + } + if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link')) + { + foreach ($links as $link) + { + if (isset($link['attribs']['']['href'])) + { + $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; + $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); + + } + } + } + if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + if ($links = $this->get_source_tags('', 'link')) + { + $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); + } + + $keys = array_keys($this->data['links']); + foreach ($keys as $key) + { + if (SimplePie_Misc::is_isegment_nz_nc($key)) + { + if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key])) + { + $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]); + $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; + } + else + { + $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; + } + } + elseif (substr($key, 0, 41) == SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY) + { + $this->data['links'][substr($key, 41)] =& $this->data['links'][$key]; + } + $this->data['links'][$key] = array_unique($this->data['links'][$key]); + } + } + + if (isset($this->data['links'][$rel])) + { + return $this->data['links'][$rel]; + } + else + { + return null; + } + } + + function get_description() + { + if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'subtitle')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'tagline')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags('', 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); + } + else + { + return null; + } + } + + function get_copyright() + { + if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_10_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'copyright')) + { + return $this->sanitize($return[0]['data'], SimplePie_Misc::atom_03_construct_type($return[0]['attribs']), $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags('', 'copyright')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_language() + { + if ($return = $this->get_source_tags('', 'language')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'language')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'language')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); + } + elseif (isset($this->data['xml_lang'])) + { + return $this->sanitize($this->data['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); + } + else + { + return null; + } + } + + function get_latitude() + { + if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat')) + { + return (float) $return[0]['data']; + } + elseif (($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', $return[0]['data'], $match)) + { + return (float) $match[1]; + } + else + { + return null; + } + } + + function get_longitude() + { + if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long')) + { + return (float) $return[0]['data']; + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon')) + { + return (float) $return[0]['data']; + } + elseif (($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', $return[0]['data'], $match)) + { + return (float) $match[2]; + } + else + { + return null; + } + } + + function get_image_url() + { + if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'image')) + { + return $this->sanitize($return[0]['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'logo')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon')) + { + return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); + } + else + { + return null; + } + } +} + +class SimplePie_Author +{ + var $name; + var $link; + var $email; + + // Constructor, used to input the data + function SimplePie_Author($name = null, $link = null, $email = null) + { + $this->name = $name; + $this->link = $link; + $this->email = $email; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_name() + { + if ($this->name !== null) + { + return $this->name; + } + else + { + return null; + } + } + + function get_link() + { + if ($this->link !== null) + { + return $this->link; + } + else + { + return null; + } + } + + function get_email() + { + if ($this->email !== null) + { + return $this->email; + } + else + { + return null; + } + } +} + +class SimplePie_Category +{ + var $term; + var $scheme; + var $label; + + // Constructor, used to input the data + function SimplePie_Category($term = null, $scheme = null, $label = null) + { + $this->term = $term; + $this->scheme = $scheme; + $this->label = $label; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_term() + { + if ($this->term !== null) + { + return $this->term; + } + else + { + return null; + } + } + + function get_scheme() + { + if ($this->scheme !== null) + { + return $this->scheme; + } + else + { + return null; + } + } + + function get_label() + { + if ($this->label !== null) + { + return $this->label; + } + else + { + return $this->get_term(); + } + } +} + +class SimplePie_Enclosure +{ + var $bitrate; + var $captions; + var $categories; + var $channels; + var $copyright; + var $credits; + var $description; + var $duration; + var $expression; + var $framerate; + var $handler; + var $hashes; + var $height; + var $javascript; + var $keywords; + var $lang; + var $length; + var $link; + var $medium; + var $player; + var $ratings; + var $restrictions; + var $samplingrate; + var $thumbnails; + var $title; + var $type; + var $width; + + // Constructor, used to input the data + function SimplePie_Enclosure($link = null, $type = null, $length = null, $javascript = null, $bitrate = null, $captions = null, $categories = null, $channels = null, $copyright = null, $credits = null, $description = null, $duration = null, $expression = null, $framerate = null, $hashes = null, $height = null, $keywords = null, $lang = null, $medium = null, $player = null, $ratings = null, $restrictions = null, $samplingrate = null, $thumbnails = null, $title = null, $width = null) + { + $this->bitrate = $bitrate; + $this->captions = $captions; + $this->categories = $categories; + $this->channels = $channels; + $this->copyright = $copyright; + $this->credits = $credits; + $this->description = $description; + $this->duration = $duration; + $this->expression = $expression; + $this->framerate = $framerate; + $this->hashes = $hashes; + $this->height = $height; + $this->javascript = $javascript; + $this->keywords = $keywords; + $this->lang = $lang; + $this->length = $length; + $this->link = $link; + $this->medium = $medium; + $this->player = $player; + $this->ratings = $ratings; + $this->restrictions = $restrictions; + $this->samplingrate = $samplingrate; + $this->thumbnails = $thumbnails; + $this->title = $title; + $this->type = $type; + $this->width = $width; + if (class_exists('idna_convert')) + { + $idn =& new idna_convert; + $parsed = SimplePie_Misc::parse_url($link); + $this->link = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']); + } + $this->handler = $this->get_handler(); // Needs to load last + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_bitrate() + { + if ($this->bitrate !== null) + { + return $this->bitrate; + } + else + { + return null; + } + } + + function get_caption($key = 0) + { + $captions = $this->get_captions(); + if (isset($captions[$key])) + { + return $captions[$key]; + } + else + { + return null; + } + } + + function get_captions() + { + if ($this->captions !== null) + { + return $this->captions; + } + else + { + return null; + } + } + + function get_category($key = 0) + { + $categories = $this->get_categories(); + if (isset($categories[$key])) + { + return $categories[$key]; + } + else + { + return null; + } + } + + function get_categories() + { + if ($this->categories !== null) + { + return $this->categories; + } + else + { + return null; + } + } + + function get_channels() + { + if ($this->channels !== null) + { + return $this->channels; + } + else + { + return null; + } + } + + function get_copyright() + { + if ($this->copyright !== null) + { + return $this->copyright; + } + else + { + return null; + } + } + + function get_credit($key = 0) + { + $credits = $this->get_credits(); + if (isset($credits[$key])) + { + return $credits[$key]; + } + else + { + return null; + } + } + + function get_credits() + { + if ($this->credits !== null) + { + return $this->credits; + } + else + { + return null; + } + } + + function get_description() + { + if ($this->description !== null) + { + return $this->description; + } + else + { + return null; + } + } + + function get_duration($convert = false) + { + if ($this->duration !== null) + { + if ($convert) + { + $time = SimplePie_Misc::time_hms($this->duration); + return $time; + } + else + { + return $this->duration; + } + } + else + { + return null; + } + } + + function get_expression() + { + if ($this->expression !== null) + { + return $this->expression; + } + else + { + return 'full'; + } + } + + function get_extension() + { + if ($this->link !== null) + { + $url = SimplePie_Misc::parse_url($this->link); + if ($url['path'] !== '') + { + return pathinfo($url['path'], PATHINFO_EXTENSION); + } + } + return null; + } + + function get_framerate() + { + if ($this->framerate !== null) + { + return $this->framerate; + } + else + { + return null; + } + } + + function get_handler() + { + return $this->get_real_type(true); + } + + function get_hash($key = 0) + { + $hashes = $this->get_hashes(); + if (isset($hashes[$key])) + { + return $hashes[$key]; + } + else + { + return null; + } + } + + function get_hashes() + { + if ($this->hashes !== null) + { + return $this->hashes; + } + else + { + return null; + } + } + + function get_height() + { + if ($this->height !== null) + { + return $this->height; + } + else + { + return null; + } + } + + function get_language() + { + if ($this->lang !== null) + { + return $this->lang; + } + else + { + return null; + } + } + + function get_keyword($key = 0) + { + $keywords = $this->get_keywords(); + if (isset($keywords[$key])) + { + return $keywords[$key]; + } + else + { + return null; + } + } + + function get_keywords() + { + if ($this->keywords !== null) + { + return $this->keywords; + } + else + { + return null; + } + } + + function get_length() + { + if ($this->length !== null) + { + return $this->length; + } + else + { + return null; + } + } + + function get_link() + { + if ($this->link !== null) + { + return urldecode($this->link); + } + else + { + return null; + } + } + + function get_medium() + { + if ($this->medium !== null) + { + return $this->medium; + } + else + { + return null; + } + } + + function get_player() + { + if ($this->player !== null) + { + return $this->player; + } + else + { + return null; + } + } + + function get_rating($key = 0) + { + $ratings = $this->get_ratings(); + if (isset($ratings[$key])) + { + return $ratings[$key]; + } + else + { + return null; + } + } + + function get_ratings() + { + if ($this->ratings !== null) + { + return $this->ratings; + } + else + { + return null; + } + } + + function get_restriction($key = 0) + { + $restrictions = $this->get_restrictions(); + if (isset($restrictions[$key])) + { + return $restrictions[$key]; + } + else + { + return null; + } + } + + function get_restrictions() + { + if ($this->restrictions !== null) + { + return $this->restrictions; + } + else + { + return null; + } + } + + function get_sampling_rate() + { + if ($this->samplingrate !== null) + { + return $this->samplingrate; + } + else + { + return null; + } + } + + function get_size() + { + $length = $this->get_length(); + if ($length !== null) + { + return round($length/1048576, 2); + } + else + { + return null; + } + } + + function get_thumbnail($key = 0) + { + $thumbnails = $this->get_thumbnails(); + if (isset($thumbnails[$key])) + { + return $thumbnails[$key]; + } + else + { + return null; + } + } + + function get_thumbnails() + { + if ($this->thumbnails !== null) + { + return $this->thumbnails; + } + else + { + return null; + } + } + + function get_title() + { + if ($this->title !== null) + { + return $this->title; + } + else + { + return null; + } + } + + function get_type() + { + if ($this->type !== null) + { + return $this->type; + } + else + { + return null; + } + } + + function get_width() + { + if ($this->width !== null) + { + return $this->width; + } + else + { + return null; + } + } + + function native_embed($options='') + { + return $this->embed($options, true); + } + + /** + * @todo If the dimensions for media:content are defined, use them when width/height are set to 'auto'. + */ + function embed($options = '', $native = false) + { + // Set up defaults + $audio = ''; + $video = ''; + $alt = ''; + $altclass = ''; + $loop = 'false'; + $width = 'auto'; + $height = 'auto'; + $bgcolor = '#ffffff'; + $mediaplayer = ''; + $widescreen = false; + $handler = $this->get_handler(); + $type = $this->get_real_type(); + + // Process options and reassign values as necessary + if (is_array($options)) + { + extract($options); + } + else + { + $options = explode(',', $options); + foreach($options as $option) + { + $opt = explode(':', $option, 2); + if (isset($opt[0], $opt[1])) + { + $opt[0] = trim($opt[0]); + $opt[1] = trim($opt[1]); + switch ($opt[0]) + { + case 'audio': + $audio = $opt[1]; + break; + + case 'video': + $video = $opt[1]; + break; + + case 'alt': + $alt = $opt[1]; + break; + + case 'altclass': + $altclass = $opt[1]; + break; + + case 'loop': + $loop = $opt[1]; + break; + + case 'width': + $width = $opt[1]; + break; + + case 'height': + $height = $opt[1]; + break; + + case 'bgcolor': + $bgcolor = $opt[1]; + break; + + case 'mediaplayer': + $mediaplayer = $opt[1]; + break; + + case 'widescreen': + $widescreen = $opt[1]; + break; + } + } + } + } + + $mime = explode('/', $type, 2); + $mime = $mime[0]; + + // Process values for 'auto' + if ($width == 'auto') + { + if ($mime == 'video') + { + if ($height == 'auto') + { + $width = 480; + } + elseif ($widescreen) + { + $width = round((intval($height)/9)*16); + } + else + { + $width = round((intval($height)/3)*4); + } + } + else + { + $width = '100%'; + } + } + + if ($height == 'auto') + { + if ($mime == 'audio') + { + $height = 0; + } + elseif ($mime == 'video') + { + if ($width == 'auto') + { + if ($widescreen) + { + $height = 270; + } + else + { + $height = 360; + } + } + elseif ($widescreen) + { + $height = round((intval($width)/16)*9); + } + else + { + $height = round((intval($width)/4)*3); + } + } + else + { + $height = 376; + } + } + elseif ($mime == 'audio') + { + $height = 0; + } + + // Set proper placeholder value + if ($mime == 'audio') + { + $placeholder = $audio; + } + elseif ($mime == 'video') + { + $placeholder = $video; + } + + $embed = ''; + + // Make sure the JS library is included + if (!$native) + { + static $javascript_outputted = null; + if (!$javascript_outputted && $this->javascript) + { + $embed .= ''; + $javascript_outputted = true; + } + } + + // Odeo Feed MP3's + if ($handler == 'odeo') + { + if ($native) + { + $embed .= ''; + } + else + { + $embed .= ''; + } + } + + // Flash + elseif ($handler == 'flash') + { + if ($native) + { + $embed .= "get_link() . "\" pluginspage=\"http://adobe.com/go/getflashplayer\" type=\"$type\" quality=\"high\" width=\"$width\" height=\"$height\" bgcolor=\"$bgcolor\" loop=\"$loop\">"; + } + else + { + $embed .= ""; + } + } + + // Flash Media Player file types. + // Preferred handler for MP3 file types. + elseif ($handler == 'fmedia' || ($handler == 'mp3' && $mediaplayer != '')) + { + $height += 20; + if ($native) + { + $embed .= "get_link().'?file_extension=.'.$this->get_extension()) . "&autostart=false&repeat=$loop&showdigits=true&showfsbutton=false\">"; + } + else + { + $embed .= ""; + } + } + + // QuickTime 7 file types. Need to test with QuickTime 6. + // Only handle MP3's if the Flash Media Player is not present. + elseif ($handler == 'quicktime' || ($handler == 'mp3' && $mediaplayer == '')) + { + $height += 16; + if ($native) + { + if ($placeholder != ""){ + $embed .= "get_link() . "\" src=\"$placeholder\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"false\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://apple.com/quicktime/download/\">"; + } + else { + $embed .= "get_link() . "\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"true\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://apple.com/quicktime/download/\">"; + } + } + else + { + $embed .= ""; + } + } + + // Windows Media + elseif ($handler == 'wmedia') + { + $height += 45; + if ($native) + { + $embed .= "get_link() . "\" autosize=\"1\" width=\"$width\" height=\"$height\" showcontrols=\"1\" showstatusbar=\"0\" showdisplay=\"0\" autostart=\"0\">"; + } + else + { + $embed .= ""; + } + } + + // Everything else + else $embed .= '' . $alt . ''; + + return $embed; + } + + function get_real_type($find_handler = false) + { + // If it's Odeo, let's get it out of the way. + if (substr(strtolower($this->get_link()), 0, 15) == 'http://odeo.com') + { + return 'odeo'; + } + + // Mime-types by handler. + $types_flash = array('application/x-shockwave-flash', 'application/futuresplash'); // Flash + $types_fmedia = array('video/flv', 'video/x-flv','flv-application/octet-stream'); // Flash Media Player + $types_quicktime = array('audio/3gpp', 'audio/3gpp2', 'audio/aac', 'audio/x-aac', 'audio/aiff', 'audio/x-aiff', 'audio/mid', 'audio/midi', 'audio/x-midi', 'audio/mp4', 'audio/m4a', 'audio/x-m4a', 'audio/wav', 'audio/x-wav', 'video/3gpp', 'video/3gpp2', 'video/m4v', 'video/x-m4v', 'video/mp4', 'video/mpeg', 'video/x-mpeg', 'video/quicktime', 'video/sd-video'); // QuickTime + $types_wmedia = array('application/asx', 'application/x-mplayer2', 'audio/x-ms-wma', 'audio/x-ms-wax', 'video/x-ms-asf-plugin', 'video/x-ms-asf', 'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-ms-wvx'); // Windows Media + $types_mp3 = array('audio/mp3', 'audio/x-mp3', 'audio/mpeg', 'audio/x-mpeg'); // MP3 + + if ($this->get_type() !== null) + { + $type = strtolower($this->type); + } + else + { + $type = null; + } + + // If we encounter an unsupported mime-type, check the file extension and guess intelligently. + if (!in_array($type, array_merge($types_flash, $types_fmedia, $types_quicktime, $types_wmedia, $types_mp3))) + { + switch (strtolower($this->get_extension())) + { + // Audio mime-types + case 'aac': + case 'adts': + $type = 'audio/acc'; + break; + + case 'aif': + case 'aifc': + case 'aiff': + case 'cdda': + $type = 'audio/aiff'; + break; + + case 'bwf': + $type = 'audio/wav'; + break; + + case 'kar': + case 'mid': + case 'midi': + case 'smf': + $type = 'audio/midi'; + break; + + case 'm4a': + $type = 'audio/x-m4a'; + break; + + case 'mp3': + case 'swa': + $type = 'audio/mp3'; + break; + + case 'wav': + $type = 'audio/wav'; + break; + + case 'wax': + $type = 'audio/x-ms-wax'; + break; + + case 'wma': + $type = 'audio/x-ms-wma'; + break; + + // Video mime-types + case '3gp': + case '3gpp': + $type = 'video/3gpp'; + break; + + case '3g2': + case '3gp2': + $type = 'video/3gpp2'; + break; + + case 'asf': + $type = 'video/x-ms-asf'; + break; + + case 'flv': + $type = 'video/x-flv'; + break; + + case 'm1a': + case 'm1s': + case 'm1v': + case 'm15': + case 'm75': + case 'mp2': + case 'mpa': + case 'mpeg': + case 'mpg': + case 'mpm': + case 'mpv': + $type = 'video/mpeg'; + break; + + case 'm4v': + $type = 'video/x-m4v'; + break; + + case 'mov': + case 'qt': + $type = 'video/quicktime'; + break; + + case 'mp4': + case 'mpg4': + $type = 'video/mp4'; + break; + + case 'sdv': + $type = 'video/sd-video'; + break; + + case 'wm': + $type = 'video/x-ms-wm'; + break; + + case 'wmv': + $type = 'video/x-ms-wmv'; + break; + + case 'wvx': + $type = 'video/x-ms-wvx'; + break; + + // Flash mime-types + case 'spl': + $type = 'application/futuresplash'; + break; + + case 'swf': + $type = 'application/x-shockwave-flash'; + break; + } + } + + if ($find_handler) + { + if (in_array($type, $types_flash)) + { + return 'flash'; + } + elseif (in_array($type, $types_fmedia)) + { + return 'fmedia'; + } + elseif (in_array($type, $types_quicktime)) + { + return 'quicktime'; + } + elseif (in_array($type, $types_wmedia)) + { + return 'wmedia'; + } + elseif (in_array($type, $types_mp3)) + { + return 'mp3'; + } + else + { + return null; + } + } + else + { + return $type; + } + } +} + +class SimplePie_Caption +{ + var $type; + var $lang; + var $startTime; + var $endTime; + var $text; + + // Constructor, used to input the data + function SimplePie_Caption($type = null, $lang = null, $startTime = null, $endTime = null, $text = null) + { + $this->type = $type; + $this->lang = $lang; + $this->startTime = $startTime; + $this->endTime = $endTime; + $this->text = $text; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_endtime() + { + if ($this->endTime !== null) + { + return $this->endTime; + } + else + { + return null; + } + } + + function get_language() + { + if ($this->lang !== null) + { + return $this->lang; + } + else + { + return null; + } + } + + function get_starttime() + { + if ($this->startTime !== null) + { + return $this->startTime; + } + else + { + return null; + } + } + + function get_text() + { + if ($this->text !== null) + { + return $this->text; + } + else + { + return null; + } + } + + function get_type() + { + if ($this->type !== null) + { + return $this->type; + } + else + { + return null; + } + } +} + +class SimplePie_Credit +{ + var $role; + var $scheme; + var $name; + + // Constructor, used to input the data + function SimplePie_Credit($role = null, $scheme = null, $name = null) + { + $this->role = $role; + $this->scheme = $scheme; + $this->name = $name; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_role() + { + if ($this->role !== null) + { + return $this->role; + } + else + { + return null; + } + } + + function get_scheme() + { + if ($this->scheme !== null) + { + return $this->scheme; + } + else + { + return null; + } + } + + function get_name() + { + if ($this->name !== null) + { + return $this->name; + } + else + { + return null; + } + } +} + +class SimplePie_Copyright +{ + var $url; + var $label; + + // Constructor, used to input the data + function SimplePie_Copyright($url = null, $label = null) + { + $this->url = $url; + $this->label = $label; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_url() + { + if ($this->url !== null) + { + return $this->url; + } + else + { + return null; + } + } + + function get_attribution() + { + if ($this->label !== null) + { + return $this->label; + } + else + { + return null; + } + } +} + +class SimplePie_Rating +{ + var $scheme; + var $value; + + // Constructor, used to input the data + function SimplePie_Rating($scheme = null, $value = null) + { + $this->scheme = $scheme; + $this->value = $value; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_scheme() + { + if ($this->scheme !== null) + { + return $this->scheme; + } + else + { + return null; + } + } + + function get_value() + { + if ($this->value !== null) + { + return $this->value; + } + else + { + return null; + } + } +} + +class SimplePie_Restriction +{ + var $relationship; + var $type; + var $value; + + // Constructor, used to input the data + function SimplePie_Restriction($relationship = null, $type = null, $value = null) + { + $this->relationship = $relationship; + $this->type = $type; + $this->value = $value; + } + + function __toString() + { + // There is no $this->data here + return md5(serialize($this)); + } + + function get_relationship() + { + if ($this->relationship !== null) + { + return $this->relationship; + } + else + { + return null; + } + } + + function get_type() + { + if ($this->type !== null) + { + return $this->type; + } + else + { + return null; + } + } + + function get_value() + { + if ($this->value !== null) + { + return $this->value; + } + else + { + return null; + } + } +} + +/** + * @todo Move to properly supporting RFC2616 (HTTP/1.1) + */ +class SimplePie_File +{ + var $url; + var $useragent; + var $success = true; + var $headers = array(); + var $body; + var $status_code; + var $redirects = 0; + var $error; + var $method = SIMPLEPIE_FILE_SOURCE_NONE; + + function SimplePie_File($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) + { + if (class_exists('idna_convert')) + { + $idn =& new idna_convert; + $parsed = SimplePie_Misc::parse_url($url); + $url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']); + } + $this->url = $url; + $this->useragent = $useragent; + if (preg_match('/^http(s)?:\/\//i', $url)) + { + if ($useragent === null) + { + $useragent = ini_get('user_agent'); + $this->useragent = $useragent; + } + if (!is_array($headers)) + { + $headers = array(); + } + if (!$force_fsockopen && function_exists('curl_exec')) + { + $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL; + $fp = curl_init(); + $headers2 = array(); + foreach ($headers as $key => $value) + { + $headers2[] = "$key: $value"; + } + if (version_compare(SimplePie_Misc::get_curl_version(), '7.10.5', '>=')) + { + curl_setopt($fp, CURLOPT_ENCODING, ''); + } + curl_setopt($fp, CURLOPT_URL, $url); + curl_setopt($fp, CURLOPT_HEADER, 1); + curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($fp, CURLOPT_TIMEOUT, $timeout); + curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout); + curl_setopt($fp, CURLOPT_REFERER, $url); + curl_setopt($fp, CURLOPT_USERAGENT, $useragent); + curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2); + if (!ini_get('open_basedir') && !ini_get('safe_mode') && version_compare(SimplePie_Misc::get_curl_version(), '7.15.2', '>=')) + { + curl_setopt($fp, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($fp, CURLOPT_MAXREDIRS, $redirects); + } + + $this->headers = curl_exec($fp); + if (curl_errno($fp) == 23 || curl_errno($fp) == 61) + { + curl_setopt($fp, CURLOPT_ENCODING, 'none'); + $this->headers = curl_exec($fp); + } + if (curl_errno($fp)) + { + $this->error = 'cURL error ' . curl_errno($fp) . ': ' . curl_error($fp); + $this->success = false; + } + else + { + $info = curl_getinfo($fp); + curl_close($fp); + $this->headers = explode("\r\n\r\n", $this->headers, $info['redirect_count'] + 1); + $this->headers = array_pop($this->headers); + $parser =& new SimplePie_HTTP_Parser($this->headers); + if ($parser->parse()) + { + $this->headers = $parser->headers; + $this->body = $parser->body; + $this->status_code = $parser->status_code; + if (($this->status_code == 300 || $this->status_code == 301 || $this->status_code == 302 || $this->status_code == 303 || $this->status_code == 307 || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) + { + $this->redirects++; + $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url); + return $this->SimplePie_File($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen); + } + } + } + } + else + { + $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_FSOCKOPEN; + $url_parts = parse_url($url); + if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) == 'https') + { + $url_parts['host'] = "ssl://$url_parts[host]"; + $url_parts['port'] = 443; + } + if (!isset($url_parts['port'])) + { + $url_parts['port'] = 80; + } + $fp = @fsockopen($url_parts['host'], $url_parts['port'], $errno, $errstr, $timeout); + if (!$fp) + { + $this->error = 'fsockopen error: ' . $errstr; + $this->success = false; + } + else + { + stream_set_timeout($fp, $timeout); + if (isset($url_parts['path'])) + { + if (isset($url_parts['query'])) + { + $get = "$url_parts[path]?$url_parts[query]"; + } + else + { + $get = $url_parts['path']; + } + } + else + { + $get = '/'; + } + $out = "GET $get HTTP/1.0\r\n"; + $out .= "Host: $url_parts[host]\r\n"; + $out .= "User-Agent: $useragent\r\n"; + if (extension_loaded('zlib')) + { + $out .= "Accept-Encoding: x-gzip,gzip,deflate\r\n"; + } + + if (isset($url_parts['user']) && isset($url_parts['pass'])) + { + $out .= "Authorization: Basic " . base64_encode("$url_parts[user]:$url_parts[pass]") . "\r\n"; + } + foreach ($headers as $key => $value) + { + $out .= "$key: $value\r\n"; + } + $out .= "Connection: Close\r\n\r\n"; + fwrite($fp, $out); + + $info = stream_get_meta_data($fp); + + $this->headers = ''; + while (!$info['eof'] && !$info['timed_out']) + { + $this->headers .= fread($fp, 1160); + $info = stream_get_meta_data($fp); + } + if (!$info['timed_out']) + { + $parser =& new SimplePie_HTTP_Parser($this->headers); + if ($parser->parse()) + { + $this->headers = $parser->headers; + $this->body = $parser->body; + $this->status_code = $parser->status_code; + if (($this->status_code == 300 || $this->status_code == 301 || $this->status_code == 302 || $this->status_code == 303 || $this->status_code == 307 || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) + { + $this->redirects++; + $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url); + return $this->SimplePie_File($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen); + } + if (isset($this->headers['content-encoding'])) + { + // Hey, we act dumb elsewhere, so let's do that here too + switch (strtolower(trim($this->headers['content-encoding'], "\x09\x0A\x0D\x20"))) + { + case 'gzip': + case 'x-gzip': + $decoder =& new SimplePie_gzdecode($this->body); + if (!$decoder->parse()) + { + $this->error = 'Unable to decode HTTP "gzip" stream'; + $this->success = false; + } + else + { + $this->body = $decoder->data; + } + break; + + case 'deflate': + if (($body = gzuncompress($this->body)) === false) + { + if (($body = gzinflate($this->body)) === false) + { + $this->error = 'Unable to decode HTTP "deflate" stream'; + $this->success = false; + } + } + $this->body = $body; + break; + + default: + $this->error = 'Unknown content coding'; + $this->success = false; + } + } + } + } + else + { + $this->error = 'fsocket timed out'; + $this->success = false; + } + fclose($fp); + } + } + } + else + { + $this->method = SIMPLEPIE_FILE_SOURCE_LOCAL | SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS; + if (!$this->body = file_get_contents($url)) + { + $this->error = 'file_get_contents could not read the file'; + $this->success = false; + } + } + } +} + +/** + * HTTP Response Parser + * + * @package SimplePie + */ +class SimplePie_HTTP_Parser +{ + /** + * HTTP Version + * + * @access public + * @var float + */ + var $http_version = 0.0; + + /** + * Status code + * + * @access public + * @var int + */ + var $status_code = 0; + + /** + * Reason phrase + * + * @access public + * @var string + */ + var $reason = ''; + + /** + * Key/value pairs of the headers + * + * @access public + * @var array + */ + var $headers = array(); + + /** + * Body of the response + * + * @access public + * @var string + */ + var $body = ''; + + /** + * Current state of the state machine + * + * @access private + * @var string + */ + var $state = 'http_version'; + + /** + * Input data + * + * @access private + * @var string + */ + var $data = ''; + + /** + * Input data length (to avoid calling strlen() everytime this is needed) + * + * @access private + * @var int + */ + var $data_length = 0; + + /** + * Current position of the pointer + * + * @var int + * @access private + */ + var $position = 0; + + /** + * Name of the hedaer currently being parsed + * + * @access private + * @var string + */ + var $name = ''; + + /** + * Value of the hedaer currently being parsed + * + * @access private + * @var string + */ + var $value = ''; + + /** + * Create an instance of the class with the input data + * + * @access public + * @param string $data Input data + */ + function SimplePie_HTTP_Parser($data) + { + $this->data = $data; + $this->data_length = strlen($this->data); + } + + /** + * Parse the input data + * + * @access public + * @return bool true on success, false on failure + */ + function parse() + { + while ($this->state && $this->state !== 'emit' && $this->has_data()) + { + $state = $this->state; + $this->$state(); + } + $this->data = ''; + if ($this->state === 'emit' || $this->state === 'body') + { + return true; + } + else + { + $this->http_version = ''; + $this->status_code = ''; + $this->reason = ''; + $this->headers = array(); + $this->body = ''; + return false; + } + } + + /** + * Check whether there is data beyond the pointer + * + * @access private + * @return bool true if there is further data, false if not + */ + function has_data() + { + return (bool) ($this->position < $this->data_length); + } + + /** + * See if the next character is LWS + * + * @access private + * @return bool true if the next character is LWS, false if not + */ + function is_linear_whitespace() + { + return (bool) ($this->data[$this->position] === "\x09" + || $this->data[$this->position] === "\x20" + || ($this->data[$this->position] === "\x0A" + && isset($this->data[$this->position + 1]) + && ($this->data[$this->position + 1] === "\x09" || $this->data[$this->position + 1] === "\x20"))); + } + + /** + * Parse the HTTP version + * + * @access private + */ + function http_version() + { + if (strpos($this->data, "\x0A") !== false && strtoupper(substr($this->data, 0, 5)) === 'HTTP/') + { + $len = strspn($this->data, '0123456789.', 5); + $this->http_version = substr($this->data, 5, $len); + $this->position += 5 + $len; + if (substr_count($this->http_version, '.') <= 1) + { + $this->http_version = (float) $this->http_version; + $this->position += strspn($this->data, "\x09\x20", $this->position); + $this->state = 'status'; + } + else + { + $this->state = false; + } + } + else + { + $this->state = false; + } + } + + /** + * Parse the status code + * + * @access private + */ + function status() + { + if ($len = strspn($this->data, '0123456789', $this->position)) + { + $this->status_code = (int) substr($this->data, $this->position, $len); + $this->position += $len; + $this->state = 'reason'; + } + else + { + $this->state = false; + } + } + + /** + * Parse the reason phrase + * + * @access private + */ + function reason() + { + $len = strcspn($this->data, "\x0A", $this->position); + $this->reason = trim(substr($this->data, $this->position, $len), "\x09\x0D\x20"); + $this->position += $len + 1; + $this->state = 'new_line'; + } + + /** + * Deal with a new line, shifting data around as needed + * + * @access private + */ + function new_line() + { + $this->value = trim($this->value, "\x0D\x20"); + if ($this->name !== '' && $this->value !== '') + { + $this->name = strtolower($this->name); + if (isset($this->headers[$this->name])) + { + $this->headers[$this->name] .= ', ' . $this->value; + } + else + { + $this->headers[$this->name] = $this->value; + } + } + $this->name = ''; + $this->value = ''; + if (substr($this->data[$this->position], 0, 2) === "\x0D\x0A") + { + $this->position += 2; + $this->state = 'body'; + } + elseif ($this->data[$this->position] === "\x0A") + { + $this->position++; + $this->state = 'body'; + } + else + { + $this->state = 'name'; + } + } + + /** + * Parse a header name + * + * @access private + */ + function name() + { + $len = strcspn($this->data, "\x0A:", $this->position); + if (isset($this->data[$this->position + $len])) + { + if ($this->data[$this->position + $len] === "\x0A") + { + $this->position += $len; + $this->state = 'new_line'; + } + else + { + $this->name = substr($this->data, $this->position, $len); + $this->position += $len + 1; + $this->state = 'value'; + } + } + else + { + $this->state = false; + } + } + + /** + * Parse LWS, replacing consecutive LWS characters with a single space + * + * @access private + */ + function linear_whitespace() + { + do + { + if (substr($this->data, $this->position, 2) === "\x0D\x0A") + { + $this->position += 2; + } + elseif ($this->data[$this->position] === "\x0A") + { + $this->position++; + } + $this->position += strspn($this->data, "\x09\x20", $this->position); + } while ($this->has_data() && $this->is_linear_whitespace()); + $this->value .= "\x20"; + } + + /** + * See what state to move to while within non-quoted header values + * + * @access private + */ + function value() + { + if ($this->is_linear_whitespace()) + { + $this->linear_whitespace(); + } + else + { + switch ($this->data[$this->position]) + { + case '"': + $this->position++; + $this->state = 'quote'; + break; + + case "\x0A": + $this->position++; + $this->state = 'new_line'; + break; + + default: + $this->state = 'value_char'; + break; + } + } + } + + /** + * Parse a header value while outside quotes + * + * @access private + */ + function value_char() + { + $len = strcspn($this->data, "\x09\x20\x0A\"", $this->position); + $this->value .= substr($this->data, $this->position, $len); + $this->position += $len; + $this->state = 'value'; + } + + /** + * See what state to move to while within quoted header values + * + * @access private + */ + function quote() + { + if ($this->is_linear_whitespace()) + { + $this->linear_whitespace(); + } + else + { + switch ($this->data[$this->position]) + { + case '"': + $this->position++; + $this->state = 'value'; + break; + + case "\x0A": + $this->position++; + $this->state = 'new_line'; + break; + + case '\\': + $this->position++; + $this->state = 'quote_escaped'; + break; + + default: + $this->state = 'quote_char'; + break; + } + } + } + + /** + * Parse a header value while within quotes + * + * @access private + */ + function quote_char() + { + $len = strcspn($this->data, "\x09\x20\x0A\"\\", $this->position); + $this->value .= substr($this->data, $this->position, $len); + $this->position += $len; + $this->state = 'value'; + } + + /** + * Parse an escaped character within quotes + * + * @access private + */ + function quote_escaped() + { + $this->value .= $this->data[$this->position]; + $this->position++; + $this->state = 'quote'; + } + + /** + * Parse the body + * + * @access private + */ + function body() + { + $this->body = substr($this->data, $this->position); + $this->state = 'emit'; + } +} + +/** + * gzdecode + * + * @package SimplePie + */ +class SimplePie_gzdecode +{ + /** + * Compressed data + * + * @access private + * @see gzdecode::$data + */ + var $compressed_data; + + /** + * Size of compressed data + * + * @access private + */ + var $compressed_size; + + /** + * Minimum size of a valid gzip string + * + * @access private + */ + var $min_compressed_size = 18; + + /** + * Current position of pointer + * + * @access private + */ + var $position = 0; + + /** + * Flags (FLG) + * + * @access private + */ + var $flags; + + /** + * Uncompressed data + * + * @access public + * @see gzdecode::$compressed_data + */ + var $data; + + /** + * Modified time + * + * @access public + */ + var $MTIME; + + /** + * Extra Flags + * + * @access public + */ + var $XFL; + + /** + * Operating System + * + * @access public + */ + var $OS; + + /** + * Subfield ID 1 + * + * @access public + * @see gzdecode::$extra_field + * @see gzdecode::$SI2 + */ + var $SI1; + + /** + * Subfield ID 2 + * + * @access public + * @see gzdecode::$extra_field + * @see gzdecode::$SI1 + */ + var $SI2; + + /** + * Extra field content + * + * @access public + * @see gzdecode::$SI1 + * @see gzdecode::$SI2 + */ + var $extra_field; + + /** + * Original filename + * + * @access public + */ + var $filename; + + /** + * Human readable comment + * + * @access public + */ + var $comment; + + /** + * Don't allow anything to be set + * + * @access public + */ + function __set($name, $value) + { + trigger_error("Cannot write property $name", E_USER_ERROR); + } + + /** + * Set the compressed string and related properties + * + * @access public + */ + function SimplePie_gzdecode($data) + { + $this->compressed_data = $data; + $this->compressed_size = strlen($data); + } + + /** + * Decode the GZIP stream + * + * @access public + */ + function parse() + { + if ($this->compressed_size >= $this->min_compressed_size) + { + // Check ID1, ID2, and CM + if (substr($this->compressed_data, 0, 3) !== "\x1F\x8B\x08") + { + return false; + } + + // Get the FLG (FLaGs) + $this->flags = ord($this->compressed_data[3]); + + // FLG bits above (1 << 4) are reserved + if ($this->flags > 0x1F) + { + return false; + } + + // Advance the pointer after the above + $this->position += 4; + + // MTIME + $mtime = substr($this->compressed_data, $this->position, 4); + // Reverse the string if we're on a big-endian arch because l is the only signed long and is machine endianness + if (current(unpack('S', "\x00\x01")) === 1) + { + $mtime = strrev($mtime); + } + $this->MTIME = current(unpack('l', $mtime)); + $this->position += 4; + + // Get the XFL (eXtra FLags) + $this->XFL = ord($this->compressed_data[$this->position++]); + + // Get the OS (Operating System) + $this->OS = ord($this->compressed_data[$this->position++]); + + // Parse the FEXTRA + if ($this->flags & 4) + { + // Read subfield IDs + $this->SI1 = $this->compressed_data[$this->position++]; + $this->SI2 = $this->compressed_data[$this->position++]; + + // SI2 set to zero is reserved for future use + if ($this->SI2 === "\x00") + { + return false; + } + + // Get the length of the extra field + $len = current(unpack('v', substr($this->compressed_data, $this->position, 2))); + $position += 2; + + // Check the length of the string is still valid + $this->min_compressed_size += $len + 4; + if ($this->compressed_size >= $this->min_compressed_size) + { + // Set the extra field to the given data + $this->extra_field = substr($this->compressed_data, $this->position, $len); + $this->position += $len; + } + else + { + return false; + } + } + + // Parse the FNAME + if ($this->flags & 8) + { + // Get the length of the filename + $len = strspn($this->compressed_data, "\x00", $this->position); + + // Check the length of the string is still valid + $this->min_compressed_size += $len + 1; + if ($this->compressed_size >= $this->min_compressed_size) + { + // Set the original filename to the given string + $this->filename = substr($this->compressed_data, $this->position, $len); + $this->position += $len + 1; + } + else + { + return false; + } + } + + // Parse the FCOMMENT + if ($this->flags & 16) + { + // Get the length of the comment + $len = strspn($this->compressed_data, "\x00", $this->position); + + // Check the length of the string is still valid + $this->min_compressed_size += $len + 1; + if ($this->compressed_size >= $this->min_compressed_size) + { + // Set the original comment to the given string + $this->comment = substr($this->compressed_data, $this->position, $len); + $this->position += $len + 1; + } + else + { + return false; + } + } + + // Parse the FHCRC + if ($this->flags & 2) + { + // Check the length of the string is still valid + $this->min_compressed_size += $len + 2; + if ($this->compressed_size >= $this->min_compressed_size) + { + // Read the CRC + $crc = current(unpack('v', substr($this->compressed_data, $this->position, 2))); + + // Check the CRC matches + if ((crc32(substr($this->compressed_data, 0, $this->position)) & 0xFFFF) === $crc) + { + $this->position += 2; + } + else + { + return false; + } + } + else + { + return false; + } + } + + // Decompress the actual data + if (($this->data = gzinflate(substr($this->compressed_data, $this->position, -8))) === false) + { + return false; + } + else + { + $this->position = $this->compressed_size - 8; + } + + // Check CRC of data + $crc = current(unpack('V', substr($this->compressed_data, $this->position, 4))); + $this->position += 4; + /*if (extension_loaded('hash') && sprintf('%u', current(unpack('V', hash('crc32b', $this->data)))) !== sprintf('%u', $crc)) + { + return false; + }*/ + + // Check ISIZE of data + $isize = current(unpack('V', substr($this->compressed_data, $this->position, 4))); + $this->position += 4; + if (sprintf('%u', strlen($this->data) & 0xFFFFFFFF) !== sprintf('%u', $isize)) + { + return false; + } + + // Wow, against all odds, we've actually got a valid gzip string + return true; + } + else + { + return false; + } + } +} + +class SimplePie_Cache +{ + /** + * Don't call the constructor. Please. + * + * @access private + */ + function SimplePie_Cache() + { + trigger_error('Please call SimplePie_Cache::create() instead of the constructor', E_USER_ERROR); + } + + /** + * Create a new SimplePie_Cache object + * + * @static + * @access public + */ + function create($location, $filename, $extension) + { + return new SimplePie_Cache_File($location, $filename, $extension); + } +} + +class SimplePie_Cache_File +{ + var $location; + var $filename; + var $extension; + var $name; + + function SimplePie_Cache_File($location, $filename, $extension) + { + $this->location = $location; + $this->filename = rawurlencode($filename); + $this->extension = rawurlencode($extension); + $this->name = "$location/$this->filename.$this->extension"; + } + + function save($data) + { + if (file_exists($this->name) && is_writeable($this->name) || file_exists($this->location) && is_writeable($this->location)) + { + if (is_a($data, 'SimplePie')) + { + $data = $data->data; + } + + $data = serialize($data); + + if (function_exists('file_put_contents')) + { + return (bool) file_put_contents($this->name, $data); + } + else + { + $fp = fopen($this->name, 'wb'); + if ($fp) + { + fwrite($fp, $data); + fclose($fp); + return true; + } + } + } + return false; + } + + function load() + { + if (file_exists($this->name) && is_readable($this->name)) + { + return unserialize(file_get_contents($this->name)); + } + return false; + } + + function mtime() + { + if (file_exists($this->name)) + { + return filemtime($this->name); + } + return false; + } + + function touch() + { + if (file_exists($this->name)) + { + return touch($this->name); + } + return false; + } + + function unlink() + { + if (file_exists($this->name)) + { + return unlink($this->name); + } + return false; + } +} + +class SimplePie_Misc +{ + function time_hms($seconds) + { + $time = ''; + + $hours = floor($seconds / 3600); + $remainder = $seconds % 3600; + if ($hours > 0) + { + $time .= $hours.':'; + } + + $minutes = floor($remainder / 60); + $seconds = $remainder % 60; + if ($minutes < 10 && $hours > 0) + { + $minutes = '0' . $minutes; + } + if ($seconds < 10) + { + $seconds = '0' . $seconds; + } + + $time .= $minutes.':'; + $time .= $seconds; + + return $time; + } + + function absolutize_url($relative, $base) + { + if ($relative !== '') + { + $relative = SimplePie_Misc::parse_url($relative); + if ($relative['scheme'] !== '') + { + $target = $relative; + } + elseif ($base !== '') + { + $base = SimplePie_Misc::parse_url($base); + $target = SimplePie_Misc::parse_url(''); + if ($relative['authority'] !== '') + { + $target = $relative; + $target['scheme'] = $base['scheme']; + } + else + { + $target['scheme'] = $base['scheme']; + $target['authority'] = $base['authority']; + if ($relative['path'] !== '') + { + if (strpos($relative['path'], '/') === 0) + { + $target['path'] = $relative['path']; + } + elseif ($base['authority'] !== '' && $base['path'] === '') + { + $target['path'] = '/' . $relative['path']; + } + elseif (($last_segment = strrpos($base['path'], '/')) !== false) + { + $target['path'] = substr($base['path'], 0, $last_segment + 1) . $relative['path']; + } + else + { + $target['path'] = $relative['path']; + } + $target['query'] = $relative['query']; + } + else + { + $target['path'] = $base['path']; + if ($relative['query'] !== '') + { + $target['query'] = $relative['query']; + } + elseif ($base['query'] !== '') + { + $target['query'] = $base['query']; + } + } + } + $target['fragment'] = $relative['fragment']; + } + else + { + // No base URL, just return the relative URL + $target = $relative; + } + $return = SimplePie_Misc::compress_parse_url($target['scheme'], $target['authority'], $target['path'], $target['query'], $target['fragment']); + } + else + { + $return = $base; + } + $return = SimplePie_Misc::normalize_url($return); + return $return; + } + + function remove_dot_segments($input) + { + $output = ''; + while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input == '.' || $input == '..') + { + // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise, + if (strpos($input, '../') === 0) + { + $input = substr($input, 3); + } + elseif (strpos($input, './') === 0) + { + $input = substr($input, 2); + } + // B: if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise, + elseif (strpos($input, '/./') === 0) + { + $input = substr_replace($input, '/', 0, 3); + } + elseif ($input == '/.') + { + $input = '/'; + } + // C: if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise, + elseif (strpos($input, '/../') === 0) + { + $input = substr_replace($input, '/', 0, 4); + $output = substr_replace($output, '', strrpos($output, '/')); + } + elseif ($input == '/..') + { + $input = '/'; + $output = substr_replace($output, '', strrpos($output, '/')); + } + // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise, + elseif ($input == '.' || $input == '..') + { + $input = ''; + } + // E: move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer + elseif (($pos = strpos($input, '/', 1)) !== false) + { + $output .= substr($input, 0, $pos); + $input = substr_replace($input, '', 0, $pos); + } + else + { + $output .= $input; + $input = ''; + } + } + return $output . $input; + } + + function get_element($realname, $string) + { + $return = array(); + $name = preg_quote($realname, '/'); + if (preg_match_all("/<($name)" . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . "(>(.*)<\/$name>|(\/)?>)/siU", $string, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) + { + for ($i = 0, $total_matches = count($matches); $i < $total_matches; $i++) + { + $return[$i]['tag'] = $realname; + $return[$i]['full'] = $matches[$i][0][0]; + $return[$i]['offset'] = $matches[$i][0][1]; + if (strlen($matches[$i][3][0]) <= 2) + { + $return[$i]['self_closing'] = true; + } + else + { + $return[$i]['self_closing'] = false; + $return[$i]['content'] = $matches[$i][4][0]; + } + $return[$i]['attribs'] = array(); + if (isset($matches[$i][2][0]) && preg_match_all('/[\x09\x0A\x0B\x0C\x0D\x20]+([^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*)(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"([^"]*)"|\'([^\']*)\'|([^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?/', ' ' . $matches[$i][2][0] . ' ', $attribs, PREG_SET_ORDER)) + { + for ($j = 0, $total_attribs = count($attribs); $j < $total_attribs; $j++) + { + if (count($attribs[$j]) == 2) + { + $attribs[$j][2] = $attribs[$j][1]; + } + $return[$i]['attribs'][strtolower($attribs[$j][1])]['data'] = SimplePie_Misc::entities_decode(end($attribs[$j]), 'UTF-8'); + } + } + } + } + return $return; + } + + function element_implode($element) + { + $full = "<$element[tag]"; + foreach ($element['attribs'] as $key => $value) + { + $key = strtolower($key); + $full .= " $key=\"" . htmlspecialchars($value['data']) . '"'; + } + if ($element['self_closing']) + { + $full .= ' />'; + } + else + { + $full .= ">$element[content]"; + } + return $full; + } + + function error($message, $level, $file, $line) + { + switch ($level) + { + case E_USER_ERROR: + $note = 'PHP Error'; + break; + case E_USER_WARNING: + $note = 'PHP Warning'; + break; + case E_USER_NOTICE: + $note = 'PHP Notice'; + break; + default: + $note = 'Unknown Error'; + break; + } + error_log("$note: $message in $file on line $line", 0); + return $message; + } + + /** + * If a file has been cached, retrieve and display it. + * + * This is most useful for caching images (get_favicon(), etc.), + * however it works for all cached files. This WILL NOT display ANY + * file/image/page/whatever, but rather only display what has already + * been cached by SimplePie. + * + * @access public + * @see SimplePie::get_favicon() + * @param str $identifier_url URL that is used to identify the content. + * This may or may not be the actual URL of the live content. + * @param str $cache_location Location of SimplePie's cache. Defaults + * to './cache'. + * @param str $cache_extension The file extension that the file was + * cached with. Defaults to 'spc'. + * @param str $cache_class Name of the cache-handling class being used + * in SimplePie. Defaults to 'SimplePie_Cache', and should be left + * as-is unless you've overloaded the class. + * @param str $cache_name_function Obsolete. Exists for backwards + * compatibility reasons only. + */ + function display_cached_file($identifier_url, $cache_location = './cache', $cache_extension = 'spc', $cache_class = 'SimplePie_Cache', $cache_name_function = 'md5') + { + $cache = call_user_func(array($cache_class, 'create'), $cache_location, $identifier_url, $cache_extension); + + if ($file = $cache->load()) + { + if (isset($file['headers']['content-type'])) + { + header('Content-type:' . $file['headers']['content-type']); + } + else + { + header('Content-type: application/octet-stream'); + } + header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 604800) . ' GMT'); // 7 days + echo $file['body']; + exit; + } + + die('Cached file for ' . $identifier_url . ' cannot be found.'); + } + + function fix_protocol($url, $http = 1) + { + $url = SimplePie_Misc::normalize_url($url); + $parsed = SimplePie_Misc::parse_url($url); + if ($parsed['scheme'] !== '' && $parsed['scheme'] != 'http' && $parsed['scheme'] != 'https') + { + return SimplePie_Misc::fix_protocol(SimplePie_Misc::compress_parse_url('http', $parsed['authority'], $parsed['path'], $parsed['query'], $parsed['fragment']), $http); + } + + if ($parsed['scheme'] === '' && $parsed['authority'] === '' && !file_exists($url)) + { + return SimplePie_Misc::fix_protocol(SimplePie_Misc::compress_parse_url('http', $parsed['path'], '', $parsed['query'], $parsed['fragment']), $http); + } + + if ($http == 2 && $parsed['scheme'] !== '') + { + return "feed:$url"; + } + elseif ($http == 3 && strtolower($parsed['scheme']) == 'http') + { + return substr_replace($url, 'podcast', 0, 4); + } + elseif ($http == 4 && strtolower($parsed['scheme']) == 'http') + { + return substr_replace($url, 'itpc', 0, 4); + } + else + { + return $url; + } + } + + function parse_url($url) + { + preg_match('/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/', $url, $match); + for ($i = count($match); $i <= 9; $i++) + { + $match[$i] = ''; + } + return array('scheme' => $match[2], 'authority' => $match[4], 'path' => $match[5], 'query' => $match[7], 'fragment' => $match[9]); + } + + function compress_parse_url($scheme = '', $authority = '', $path = '', $query = '', $fragment = '') + { + $return = ''; + if ($scheme !== '') + { + $return .= "$scheme:"; + } + if ($authority !== '') + { + $return .= "//$authority"; + } + if ($path !== '') + { + $return .= $path; + } + if ($query !== '') + { + $return .= "?$query"; + } + if ($fragment !== '') + { + $return .= "#$fragment"; + } + return $return; + } + + function normalize_url($url) + { + $url = preg_replace_callback('/%([0-9A-Fa-f]{2})/', array('SimplePie_Misc', 'percent_encoding_normalization'), $url); + $url = SimplePie_Misc::parse_url($url); + $url['scheme'] = strtolower($url['scheme']); + if ($url['authority'] !== '') + { + $url['authority'] = strtolower($url['authority']); + $url['path'] = SimplePie_Misc::remove_dot_segments($url['path']); + } + return SimplePie_Misc::compress_parse_url($url['scheme'], $url['authority'], $url['path'], $url['query'], $url['fragment']); + } + + function percent_encoding_normalization($match) + { + $integer = hexdec($match[1]); + if ($integer >= 0x41 && $integer <= 0x5A || $integer >= 0x61 && $integer <= 0x7A || $integer >= 0x30 && $integer <= 0x39 || $integer == 0x2D || $integer == 0x2E || $integer == 0x5F || $integer == 0x7E) + { + return chr($integer); + } + else + { + return strtoupper($match[0]); + } + } + + /** + * Remove bad UTF-8 bytes + * + * PCRE Pattern to locate bad bytes in a UTF-8 string comes from W3C + * FAQ: Multilingual Forms (modified to include full ASCII range) + * + * @author Geoffrey Sneddon + * @see http://www.w3.org/International/questions/qa-forms-utf-8 + * @param string $str String to remove bad UTF-8 bytes from + * @return string UTF-8 string + */ + function utf8_bad_replace($str) + { + if (function_exists('iconv') && ($return = @iconv('UTF-8', 'UTF-8//IGNORE', $str))) + { + return $return; + } + elseif (function_exists('mb_convert_encoding') && ($return = @mb_convert_encoding($str, 'UTF-8', 'UTF-8'))) + { + return $return; + } + elseif (preg_match_all('/(?:[\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})+/', $str, $matches)) + { + return implode("\xEF\xBF\xBD", $matches[0]); + } + elseif ($str !== '') + { + return "\xEF\xBF\xBD"; + } + else + { + return ''; + } + } + + /** + * Converts a Windows-1252 encoded string to a UTF-8 encoded string + * + * @static + * @access public + * @param string $string Windows-1252 encoded string + * @return string UTF-8 encoded string + */ + function windows_1252_to_utf8($string) + { + static $convert_table = array("\x80" => "\xE2\x82\xAC", "\x81" => "\xEF\xBF\xBD", "\x82" => "\xE2\x80\x9A", "\x83" => "\xC6\x92", "\x84" => "\xE2\x80\x9E", "\x85" => "\xE2\x80\xA6", "\x86" => "\xE2\x80\xA0", "\x87" => "\xE2\x80\xA1", "\x88" => "\xCB\x86", "\x89" => "\xE2\x80\xB0", "\x8A" => "\xC5\xA0", "\x8B" => "\xE2\x80\xB9", "\x8C" => "\xC5\x92", "\x8D" => "\xEF\xBF\xBD", "\x8E" => "\xC5\xBD", "\x8F" => "\xEF\xBF\xBD", "\x90" => "\xEF\xBF\xBD", "\x91" => "\xE2\x80\x98", "\x92" => "\xE2\x80\x99", "\x93" => "\xE2\x80\x9C", "\x94" => "\xE2\x80\x9D", "\x95" => "\xE2\x80\xA2", "\x96" => "\xE2\x80\x93", "\x97" => "\xE2\x80\x94", "\x98" => "\xCB\x9C", "\x99" => "\xE2\x84\xA2", "\x9A" => "\xC5\xA1", "\x9B" => "\xE2\x80\xBA", "\x9C" => "\xC5\x93", "\x9D" => "\xEF\xBF\xBD", "\x9E" => "\xC5\xBE", "\x9F" => "\xC5\xB8", "\xA0" => "\xC2\xA0", "\xA1" => "\xC2\xA1", "\xA2" => "\xC2\xA2", "\xA3" => "\xC2\xA3", "\xA4" => "\xC2\xA4", "\xA5" => "\xC2\xA5", "\xA6" => "\xC2\xA6", "\xA7" => "\xC2\xA7", "\xA8" => "\xC2\xA8", "\xA9" => "\xC2\xA9", "\xAA" => "\xC2\xAA", "\xAB" => "\xC2\xAB", "\xAC" => "\xC2\xAC", "\xAD" => "\xC2\xAD", "\xAE" => "\xC2\xAE", "\xAF" => "\xC2\xAF", "\xB0" => "\xC2\xB0", "\xB1" => "\xC2\xB1", "\xB2" => "\xC2\xB2", "\xB3" => "\xC2\xB3", "\xB4" => "\xC2\xB4", "\xB5" => "\xC2\xB5", "\xB6" => "\xC2\xB6", "\xB7" => "\xC2\xB7", "\xB8" => "\xC2\xB8", "\xB9" => "\xC2\xB9", "\xBA" => "\xC2\xBA", "\xBB" => "\xC2\xBB", "\xBC" => "\xC2\xBC", "\xBD" => "\xC2\xBD", "\xBE" => "\xC2\xBE", "\xBF" => "\xC2\xBF", "\xC0" => "\xC3\x80", "\xC1" => "\xC3\x81", "\xC2" => "\xC3\x82", "\xC3" => "\xC3\x83", "\xC4" => "\xC3\x84", "\xC5" => "\xC3\x85", "\xC6" => "\xC3\x86", "\xC7" => "\xC3\x87", "\xC8" => "\xC3\x88", "\xC9" => "\xC3\x89", "\xCA" => "\xC3\x8A", "\xCB" => "\xC3\x8B", "\xCC" => "\xC3\x8C", "\xCD" => "\xC3\x8D", "\xCE" => "\xC3\x8E", "\xCF" => "\xC3\x8F", "\xD0" => "\xC3\x90", "\xD1" => "\xC3\x91", "\xD2" => "\xC3\x92", "\xD3" => "\xC3\x93", "\xD4" => "\xC3\x94", "\xD5" => "\xC3\x95", "\xD6" => "\xC3\x96", "\xD7" => "\xC3\x97", "\xD8" => "\xC3\x98", "\xD9" => "\xC3\x99", "\xDA" => "\xC3\x9A", "\xDB" => "\xC3\x9B", "\xDC" => "\xC3\x9C", "\xDD" => "\xC3\x9D", "\xDE" => "\xC3\x9E", "\xDF" => "\xC3\x9F", "\xE0" => "\xC3\xA0", "\xE1" => "\xC3\xA1", "\xE2" => "\xC3\xA2", "\xE3" => "\xC3\xA3", "\xE4" => "\xC3\xA4", "\xE5" => "\xC3\xA5", "\xE6" => "\xC3\xA6", "\xE7" => "\xC3\xA7", "\xE8" => "\xC3\xA8", "\xE9" => "\xC3\xA9", "\xEA" => "\xC3\xAA", "\xEB" => "\xC3\xAB", "\xEC" => "\xC3\xAC", "\xED" => "\xC3\xAD", "\xEE" => "\xC3\xAE", "\xEF" => "\xC3\xAF", "\xF0" => "\xC3\xB0", "\xF1" => "\xC3\xB1", "\xF2" => "\xC3\xB2", "\xF3" => "\xC3\xB3", "\xF4" => "\xC3\xB4", "\xF5" => "\xC3\xB5", "\xF6" => "\xC3\xB6", "\xF7" => "\xC3\xB7", "\xF8" => "\xC3\xB8", "\xF9" => "\xC3\xB9", "\xFA" => "\xC3\xBA", "\xFB" => "\xC3\xBB", "\xFC" => "\xC3\xBC", "\xFD" => "\xC3\xBD", "\xFE" => "\xC3\xBE", "\xFF" => "\xC3\xBF"); + + return strtr($string, $convert_table); + } + + function change_encoding($data, $input, $output) + { + $input = SimplePie_Misc::encoding($input); + $output = SimplePie_Misc::encoding($output); + + // We fail to fail on non US-ASCII bytes + if ($input === 'US-ASCII') + { + static $non_ascii_octects = ''; + if (!$non_ascii_octects) + { + for ($i = 0x80; $i <= 0xFF; $i++) + { + $non_ascii_octects .= chr($i); + } + } + $data = substr($data, 0, strcspn($data, $non_ascii_octects)); + } + + // This is first, as behaviour of this is completely predictable + if ($input === 'Windows-1252' && $output === 'UTF-8') + { + return SimplePie_Misc::windows_1252_to_utf8($data); + } + // This is second, as behaviour of this varies only with PHP version + elseif (function_exists('mb_convert_encoding') && ($return = @mb_convert_encoding($data, $output, $input))) + { + return $return; + } + // This is last, as behaviour of this varies with OS userland and PHP version + elseif (function_exists('iconv') && ($return = @iconv($input, $output, $data))) + { + return $return; + } + // If we can't do anything, just fail + else + { + return false; + } + } + + function encoding($charset) + { + /* Character sets are case-insensitive, and also need some further + normalization in the real world (though we'll return them in the form given + in their registration). */ + switch (strtolower(preg_replace('/[\x09-\x0D\x20-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]/', '', $charset))) + { + case 'adobestandardencoding': + case 'csadobestandardencoding': + return 'Adobe-Standard-Encoding'; + + case 'adobesymbolencoding': + case 'cshppsmath': + return 'Adobe-Symbol-Encoding'; + + case 'ami1251': + case 'ami1251': + case 'amiga1251': + case 'amiga1251': + return 'Amiga-1251'; + + case 'ansix31101983': + case 'csat5001983': + case 'csiso99naplps': + case 'isoir99': + case 'naplps': + return 'ANSI_X3.110-1983'; + + case 'arabic7': + case 'asmo449': + case 'csiso89asmo449': + case 'isoir89': + case 'iso9036': + return 'ASMO_449'; + + case 'big5': + case 'csbig5': + case 'xxbig5': + return 'Big5'; + + case 'big5hkscs': + return 'Big5-HKSCS'; + + case 'bocu1': + case 'csbocu1': + return 'BOCU-1'; + + case 'brf': + case 'csbrf': + return 'BRF'; + + case 'bs4730': + case 'csiso4unitedkingdom': + case 'gb': + case 'isoir4': + case 'iso646gb': + case 'uk': + return 'BS_4730'; + + case 'bsviewdata': + case 'csiso47bsviewdata': + case 'isoir47': + return 'BS_viewdata'; + + case 'cesu8': + case 'cscesu8': + return 'CESU-8'; + + case 'ca': + case 'csa71': + case 'csaz243419851': + case 'csiso121canadian1': + case 'isoir121': + case 'iso646ca': + return 'CSA_Z243.4-1985-1'; + + case 'csa72': + case 'csaz243419852': + case 'csiso122canadian2': + case 'isoir122': + case 'iso646ca2': + return 'CSA_Z243.4-1985-2'; + + case 'csaz24341985gr': + case 'csiso123csaz24341985gr': + case 'isoir123': + return 'CSA_Z243.4-1985-gr'; + + case 'csiso139csn369103': + case 'csn369103': + case 'isoir139': + return 'CSN_369103'; + + case 'csdecmcs': + case 'dec': + case 'decmcs': + return 'DEC-MCS'; + + case 'csiso21german': + case 'de': + case 'din66003': + case 'isoir21': + case 'iso646de': + return 'DIN_66003'; + + case 'csdkus': + case 'dkus': + return 'dk-us'; + + case 'csiso646danish': + case 'dk': + case 'ds2089': + case 'ds2089': + case 'iso646dk': + return 'DS_2089'; + + case 'csibmebcdicatde': + case 'ebcdicatde': + return 'EBCDIC-AT-DE'; + + case 'csebcdicatdea': + case 'ebcdicatdea': + return 'EBCDIC-AT-DE-A'; + + case 'csebcdiccafr': + case 'ebcdiccafr': + return 'EBCDIC-CA-FR'; + + case 'csebcdicdkno': + case 'ebcdicdkno': + return 'EBCDIC-DK-NO'; + + case 'csebcdicdknoa': + case 'ebcdicdknoa': + return 'EBCDIC-DK-NO-A'; + + case 'csebcdices': + case 'ebcdices': + return 'EBCDIC-ES'; + + case 'csebcdicesa': + case 'ebcdicesa': + return 'EBCDIC-ES-A'; + + case 'csebcdicess': + case 'ebcdicess': + return 'EBCDIC-ES-S'; + + case 'csebcdicfise': + case 'ebcdicfise': + return 'EBCDIC-FI-SE'; + + case 'csebcdicfisea': + case 'ebcdicfisea': + return 'EBCDIC-FI-SE-A'; + + case 'csebcdicfr': + case 'ebcdicfr': + return 'EBCDIC-FR'; + + case 'csebcdicit': + case 'ebcdicit': + return 'EBCDIC-IT'; + + case 'csebcdicpt': + case 'ebcdicpt': + return 'EBCDIC-PT'; + + case 'csebcdicuk': + case 'ebcdicuk': + return 'EBCDIC-UK'; + + case 'csebcdicus': + case 'ebcdicus': + return 'EBCDIC-US'; + + case 'csiso111ecmacyrillic': + case 'ecmacyrillic': + case 'isoir111': + case 'koi8e': + return 'ECMA-cyrillic'; + + case 'csiso17spanish': + case 'es': + case 'isoir17': + case 'iso646es': + return 'ES'; + + case 'csiso85spanish2': + case 'es2': + case 'isoir85': + case 'iso646es2': + return 'ES2'; + + case 'cseucfixwidjapanese': + case 'extendedunixcodefixedwidthforjapanese': + return 'Extended_UNIX_Code_Fixed_Width_for_Japanese'; + + case 'cseucpkdfmtjapanese': + case 'eucjp': + case 'extendedunixcodepackedformatforjapanese': + return 'Extended_UNIX_Code_Packed_Format_for_Japanese'; + + case 'gb18030': + return 'GB18030'; + + case 'cp936': + case 'gbk': + case 'ms936': + case 'windows936': + case 'csgb2312': + case 'gb2312': + case 'chinese': + case 'csiso58gb231280': + case 'gb231280': + case 'isoir58': + return 'GBK'; + + case 'cn': + case 'csiso57gb1988': + case 'gb198880': + case 'isoir57': + case 'iso646cn': + return 'GB_1988-80'; + + case 'csiso153gost1976874': + case 'gost1976874': + case 'isoir153': + case 'stsev35888': + return 'GOST_19768-74'; + + case 'csiso150': + case 'csiso150greekccitt': + case 'greekccitt': + case 'isoir150': + return 'greek-ccitt'; + + case 'csiso88greek7': + case 'greek7': + case 'isoir88': + return 'greek7'; + + case 'csiso18greek7old': + case 'greek7old': + case 'isoir18': + return 'greek7-old'; + + case 'cshpdesktop': + case 'hpdesktop': + return 'HP-DeskTop'; + + case 'cshplegal': + case 'hplegal': + return 'HP-Legal'; + + case 'cshpmath8': + case 'hpmath8': + return 'HP-Math8'; + + case 'cshppifont': + case 'hppifont': + return 'HP-Pi-font'; + + case 'cshproman8': + case 'hproman8': + case 'r8': + case 'roman8': + return 'hp-roman8'; + + case 'hzgb2312': + return 'HZ-GB-2312'; + + case 'csibmsymbols': + case 'ibmsymbols': + return 'IBM-Symbols'; + + case 'csibmthai': + case 'ibmthai': + return 'IBM-Thai'; + + case 'ccsid00858': + case 'cp00858': + case 'ibm00858': + case 'pcmultilingual850euro': + return 'IBM00858'; + + case 'ccsid00924': + case 'cp00924': + case 'ebcdiclatin9euro': + case 'ibm00924': + return 'IBM00924'; + + case 'ccsid01140': + case 'cp01140': + case 'ebcdicus37euro': + case 'ibm01140': + return 'IBM01140'; + + case 'ccsid01141': + case 'cp01141': + case 'ebcdicde273euro': + case 'ibm01141': + return 'IBM01141'; + + case 'ccsid01142': + case 'cp01142': + case 'ebcdicdk277euro': + case 'ebcdicno277euro': + case 'ibm01142': + return 'IBM01142'; + + case 'ccsid01143': + case 'cp01143': + case 'ebcdicfi278euro': + case 'ebcdicse278euro': + case 'ibm01143': + return 'IBM01143'; + + case 'ccsid01144': + case 'cp01144': + case 'ebcdicit280euro': + case 'ibm01144': + return 'IBM01144'; + + case 'ccsid01145': + case 'cp01145': + case 'ebcdices284euro': + case 'ibm01145': + return 'IBM01145'; + + case 'ccsid01146': + case 'cp01146': + case 'ebcdicgb285euro': + case 'ibm01146': + return 'IBM01146'; + + case 'ccsid01147': + case 'cp01147': + case 'ebcdicfr297euro': + case 'ibm01147': + return 'IBM01147'; + + case 'ccsid01148': + case 'cp01148': + case 'ebcdicinternational500euro': + case 'ibm01148': + return 'IBM01148'; + + case 'ccsid01149': + case 'cp01149': + case 'ebcdicis871euro': + case 'ibm01149': + return 'IBM01149'; + + case 'cp037': + case 'csibm037': + case 'ebcdiccpca': + case 'ebcdiccpnl': + case 'ebcdiccpus': + case 'ebcdiccpwt': + case 'ibm037': + return 'IBM037'; + + case 'cp038': + case 'csibm038': + case 'ebcdicint': + case 'ibm038': + return 'IBM038'; + + case 'cp273': + case 'csibm273': + case 'ibm273': + return 'IBM273'; + + case 'cp274': + case 'csibm274': + case 'ebcdicbe': + case 'ibm274': + return 'IBM274'; + + case 'cp275': + case 'csibm275': + case 'ebcdicbr': + case 'ibm275': + return 'IBM275'; + + case 'csibm277': + case 'ebcdiccpdk': + case 'ebcdiccpno': + case 'ibm277': + return 'IBM277'; + + case 'cp278': + case 'csibm278': + case 'ebcdiccpfi': + case 'ebcdiccpse': + case 'ibm278': + return 'IBM278'; + + case 'cp280': + case 'csibm280': + case 'ebcdiccpit': + case 'ibm280': + return 'IBM280'; + + case 'cp281': + case 'csibm281': + case 'ebcdicjpe': + case 'ibm281': + return 'IBM281'; + + case 'cp284': + case 'csibm284': + case 'ebcdiccpes': + case 'ibm284': + return 'IBM284'; + + case 'cp285': + case 'csibm285': + case 'ebcdiccpgb': + case 'ibm285': + return 'IBM285'; + + case 'cp290': + case 'csibm290': + case 'ebcdicjpkana': + case 'ibm290': + return 'IBM290'; + + case 'cp297': + case 'csibm297': + case 'ebcdiccpfr': + case 'ibm297': + return 'IBM297'; + + case 'cp420': + case 'csibm420': + case 'ebcdiccpar1': + case 'ibm420': + return 'IBM420'; + + case 'cp423': + case 'csibm423': + case 'ebcdiccpgr': + case 'ibm423': + return 'IBM423'; + + case 'cp424': + case 'csibm424': + case 'ebcdiccphe': + case 'ibm424': + return 'IBM424'; + + case '437': + case 'cp437': + case 'cspc8codepage437': + case 'ibm437': + return 'IBM437'; + + case 'cp500': + case 'csibm500': + case 'ebcdiccpbe': + case 'ebcdiccpch': + case 'ibm500': + return 'IBM500'; + + case 'cp775': + case 'cspc775baltic': + case 'ibm775': + return 'IBM775'; + + case '850': + case 'cp850': + case 'cspc850multilingual': + case 'ibm850': + return 'IBM850'; + + case '851': + case 'cp851': + case 'csibm851': + case 'ibm851': + return 'IBM851'; + + case '852': + case 'cp852': + case 'cspcp852': + case 'ibm852': + return 'IBM852'; + + case '855': + case 'cp855': + case 'csibm855': + case 'ibm855': + return 'IBM855'; + + case '857': + case 'cp857': + case 'csibm857': + case 'ibm857': + return 'IBM857'; + + case '860': + case 'cp860': + case 'csibm860': + case 'ibm860': + return 'IBM860'; + + case '861': + case 'cpis': + case 'cp861': + case 'csibm861': + case 'ibm861': + return 'IBM861'; + + case '862': + case 'cp862': + case 'cspc862latinhebrew': + case 'ibm862': + return 'IBM862'; + + case '863': + case 'cp863': + case 'csibm863': + case 'ibm863': + return 'IBM863'; + + case 'cp864': + case 'csibm864': + case 'ibm864': + return 'IBM864'; + + case '865': + case 'cp865': + case 'csibm865': + case 'ibm865': + return 'IBM865'; + + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866'; + + case 'cpar': + case 'cp868': + case 'csibm868': + case 'ibm868': + return 'IBM868'; + + case '869': + case 'cpgr': + case 'cp869': + case 'csibm869': + case 'ibm869': + return 'IBM869'; + + case 'cp870': + case 'csibm870': + case 'ebcdiccproece': + case 'ebcdiccpyu': + case 'ibm870': + return 'IBM870'; + + case 'cp871': + case 'csibm871': + case 'ebcdiccpis': + case 'ibm871': + return 'IBM871'; + + case 'cp880': + case 'csibm880': + case 'ebcdiccyrillic': + case 'ibm880': + return 'IBM880'; + + case 'cp891': + case 'csibm891': + case 'ibm891': + return 'IBM891'; + + case 'cp903': + case 'csibm903': + case 'ibm903': + return 'IBM903'; + + case '904': + case 'cp904': + case 'csibbm904': + case 'ibm904': + return 'IBM904'; + + case 'cp905': + case 'csibm905': + case 'ebcdiccptr': + case 'ibm905': + return 'IBM905'; + + case 'cp918': + case 'csibm918': + case 'ebcdiccpar2': + case 'ibm918': + return 'IBM918'; + + case 'cp1026': + case 'csibm1026': + case 'ibm1026': + return 'IBM1026'; + + case 'ibm1047': + case 'ibm1047': + return 'IBM1047'; + + case 'csiso143iecp271': + case 'iecp271': + case 'isoir143': + return 'IEC_P27-1'; + + case 'csiso49inis': + case 'inis': + case 'isoir49': + return 'INIS'; + + case 'csiso50inis8': + case 'inis8': + case 'isoir50': + return 'INIS-8'; + + case 'csiso51iniscyrillic': + case 'iniscyrillic': + case 'isoir51': + return 'INIS-cyrillic'; + + case 'csinvariant': + case 'invariant': + return 'INVARIANT'; + + case 'iso2022cn': + return 'ISO-2022-CN'; + + case 'iso2022cnext': + return 'ISO-2022-CN-EXT'; + + case 'csiso2022jp': + case 'iso2022jp': + return 'ISO-2022-JP'; + + case 'csiso2022jp2': + case 'iso2022jp2': + return 'ISO-2022-JP-2'; + + case 'csiso2022kr': + case 'iso2022kr': + return 'ISO-2022-KR'; + + case 'cswindows30latin1': + case 'iso88591windows30latin1': + return 'ISO-8859-1-Windows-3.0-Latin-1'; + + case 'cswindows31latin1': + case 'iso88591windows31latin1': + return 'ISO-8859-1-Windows-3.1-Latin-1'; + + case 'csisolatin2': + case 'iso88592': + case 'isoir101': + case 'iso88592': + case 'iso885921987': + case 'l2': + case 'latin2': + return 'ISO-8859-2'; + + case 'cswindows31latin2': + case 'iso88592windowslatin2': + return 'ISO-8859-2-Windows-Latin-2'; + + case 'csisolatin3': + case 'iso88593': + case 'isoir109': + case 'iso88593': + case 'iso885931988': + case 'l3': + case 'latin3': + return 'ISO-8859-3'; + + case 'csisolatin4': + case 'iso88594': + case 'isoir110': + case 'iso88594': + case 'iso885941988': + case 'l4': + case 'latin4': + return 'ISO-8859-4'; + + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso88595': + case 'isoir144': + case 'iso88595': + case 'iso885951988': + return 'ISO-8859-5'; + + case 'arabic': + case 'asmo708': + case 'csisolatinarabic': + case 'ecma114': + case 'iso88596': + case 'isoir127': + case 'iso88596': + case 'iso885961987': + return 'ISO-8859-6'; + + case 'csiso88596e': + case 'iso88596e': + case 'iso88596e': + return 'ISO-8859-6-E'; + + case 'csiso88596i': + case 'iso88596i': + case 'iso88596i': + return 'ISO-8859-6-I'; + + case 'csisolatingreek': + case 'ecma118': + case 'elot928': + case 'greek': + case 'greek8': + case 'iso88597': + case 'isoir126': + case 'iso88597': + case 'iso885971987': + return 'ISO-8859-7'; + + case 'csisolatinhebrew': + case 'hebrew': + case 'iso88598': + case 'isoir138': + case 'iso88598': + case 'iso885981988': + return 'ISO-8859-8'; + + case 'csiso88598e': + case 'iso88598e': + case 'iso88598e': + return 'ISO-8859-8-E'; + + case 'csiso88598i': + case 'iso88598i': + case 'iso88598i': + return 'ISO-8859-8-I'; + + case 'cswindows31latin5': + case 'iso88599windowslatin5': + return 'ISO-8859-9-Windows-Latin-5'; + + case 'csisolatin6': + case 'iso885910': + case 'isoir157': + case 'iso8859101992': + case 'l6': + case 'latin6': + return 'ISO-8859-10'; + + case 'iso885913': + return 'ISO-8859-13'; + + case 'iso885914': + case 'isoceltic': + case 'isoir199': + case 'iso885914': + case 'iso8859141998': + case 'l8': + case 'latin8': + return 'ISO-8859-14'; + + case 'iso885915': + case 'iso885915': + case 'latin9': + return 'ISO-8859-15'; + + case 'iso885916': + case 'isoir226': + case 'iso885916': + case 'iso8859162001': + case 'l10': + case 'latin10': + return 'ISO-8859-16'; + + case 'iso10646j1': + return 'ISO-10646-J-1'; + + case 'csunicode': + case 'iso10646ucs2': + return 'ISO-10646-UCS-2'; + + case 'csucs4': + case 'iso10646ucs4': + return 'ISO-10646-UCS-4'; + + case 'csunicodeascii': + case 'iso10646ucsbasic': + return 'ISO-10646-UCS-Basic'; + + case 'csunicodelatin1': + case 'iso10646': + case 'iso10646unicodelatin1': + return 'ISO-10646-Unicode-Latin1'; + + case 'csiso10646utf1': + case 'iso10646utf1': + return 'ISO-10646-UTF-1'; + + case 'csiso115481': + case 'iso115481': + case 'iso115481': + case 'isotr115481': + return 'ISO-11548-1'; + + case 'csiso90': + case 'isoir90': + return 'iso-ir-90'; + + case 'csunicodeibm1261': + case 'isounicodeibm1261': + return 'ISO-Unicode-IBM-1261'; + + case 'csunicodeibm1264': + case 'isounicodeibm1264': + return 'ISO-Unicode-IBM-1264'; + + case 'csunicodeibm1265': + case 'isounicodeibm1265': + return 'ISO-Unicode-IBM-1265'; + + case 'csunicodeibm1268': + case 'isounicodeibm1268': + return 'ISO-Unicode-IBM-1268'; + + case 'csunicodeibm1276': + case 'isounicodeibm1276': + return 'ISO-Unicode-IBM-1276'; + + case 'csiso646basic1983': + case 'iso646basic1983': + case 'ref': + return 'ISO_646.basic:1983'; + + case 'csiso2intlrefversion': + case 'irv': + case 'isoir2': + case 'iso646irv1983': + return 'ISO_646.irv:1983'; + + case 'csiso2033': + case 'e13b': + case 'isoir98': + case 'iso20331983': + return 'ISO_2033-1983'; + + case 'csiso5427cyrillic': + case 'isoir37': + case 'iso5427': + return 'ISO_5427'; + + case 'isoir54': + case 'iso5427cyrillic1981': + case 'iso54271981': + return 'ISO_5427:1981'; + + case 'csiso5428greek': + case 'isoir55': + case 'iso54281980': + return 'ISO_5428:1980'; + + case 'csiso6937add': + case 'isoir152': + case 'iso6937225': + return 'ISO_6937-2-25'; + + case 'csisotextcomm': + case 'isoir142': + case 'iso69372add': + return 'ISO_6937-2-add'; + + case 'csiso8859supp': + case 'isoir154': + case 'iso8859supp': + case 'latin125': + return 'ISO_8859-supp'; + + case 'csiso10367box': + case 'isoir155': + case 'iso10367box': + return 'ISO_10367-box'; + + case 'csiso15italian': + case 'isoir15': + case 'iso646it': + case 'it': + return 'IT'; + + case 'csiso13jisc6220jp': + case 'isoir13': + case 'jisc62201969': + case 'jisc62201969jp': + case 'katakana': + case 'x02017': + return 'JIS_C6220-1969-jp'; + + case 'csiso14jisc6220ro': + case 'isoir14': + case 'iso646jp': + case 'jisc62201969ro': + case 'jp': + return 'JIS_C6220-1969-ro'; + + case 'csiso42jisc62261978': + case 'isoir42': + case 'jisc62261978': + return 'JIS_C6226-1978'; + + case 'csiso87jisx0208': + case 'isoir87': + case 'jisc62261983': + case 'jisx02081983': + case 'x0208': + return 'JIS_C6226-1983'; + + case 'csiso91jisc62291984a': + case 'isoir91': + case 'jisc62291984a': + case 'jpocra': + return 'JIS_C6229-1984-a'; + + case 'csiso92jisc62991984b': + case 'isoir92': + case 'iso646jpocrb': + case 'jisc62291984b': + case 'jpocrb': + return 'JIS_C6229-1984-b'; + + case 'csiso93jis62291984badd': + case 'isoir93': + case 'jisc62291984badd': + case 'jpocrbadd': + return 'JIS_C6229-1984-b-add'; + + case 'csiso94jis62291984hand': + case 'isoir94': + case 'jisc62291984hand': + case 'jpocrhand': + return 'JIS_C6229-1984-hand'; + + case 'csiso95jis62291984handadd': + case 'isoir95': + case 'jisc62291984handadd': + case 'jpocrhandadd': + return 'JIS_C6229-1984-hand-add'; + + case 'csiso96jisc62291984kana': + case 'isoir96': + case 'jisc62291984kana': + return 'JIS_C6229-1984-kana'; + + case 'csjisencoding': + case 'jisencoding': + return 'JIS_Encoding'; + + case 'cshalfwidthkatakana': + case 'jisx0201': + case 'x0201': + return 'JIS_X0201'; + + case 'csiso159jisx02121990': + case 'isoir159': + case 'jisx02121990': + case 'x0212': + return 'JIS_X0212-1990'; + + case 'csiso141jusib1002': + case 'isoir141': + case 'iso646yu': + case 'js': + case 'jusib1002': + case 'yu': + return 'JUS_I.B1.002'; + + case 'csiso147macedonian': + case 'isoir147': + case 'jusib1003mac': + case 'macedonian': + return 'JUS_I.B1.003-mac'; + + case 'csiso146serbian': + case 'isoir146': + case 'jusib1003serb': + case 'serbian': + return 'JUS_I.B1.003-serb'; + + case 'koi7switched': + return 'KOI7-switched'; + + case 'cskoi8r': + case 'koi8r': + return 'KOI8-R'; + + case 'koi8u': + return 'KOI8-U'; + + case 'csksc5636': + case 'iso646kr': + case 'ksc5636': + return 'KSC5636'; + + case 'cskz1048': + case 'kz1048': + case 'rk1048': + case 'strk10482002': + return 'KZ-1048'; + + case 'csiso19latingreek': + case 'isoir19': + case 'latingreek': + return 'latin-greek'; + + case 'csiso27latingreek1': + case 'isoir27': + case 'latingreek1': + return 'Latin-greek-1'; + + case 'csiso158lap': + case 'isoir158': + case 'lap': + case 'latinlap': + return 'latin-lap'; + + case 'csmacintosh': + case 'mac': + case 'macintosh': + return 'macintosh'; + + case 'csmicrosoftpublishing': + case 'microsoftpublishing': + return 'Microsoft-Publishing'; + + case 'csmnem': + case 'mnem': + return 'MNEM'; + + case 'csmnemonic': + case 'mnemonic': + return 'MNEMONIC'; + + case 'csiso86hungarian': + case 'hu': + case 'isoir86': + case 'iso646hu': + case 'msz77953': + return 'MSZ_7795.3'; + + case 'csnatsdano': + case 'isoir91': + case 'natsdano': + return 'NATS-DANO'; + + case 'csnatsdanoadd': + case 'isoir92': + case 'natsdanoadd': + return 'NATS-DANO-ADD'; + + case 'csnatssefi': + case 'isoir81': + case 'natssefi': + return 'NATS-SEFI'; + + case 'csnatssefiadd': + case 'isoir82': + case 'natssefiadd': + return 'NATS-SEFI-ADD'; + + case 'csiso151cuba': + case 'cuba': + case 'isoir151': + case 'iso646cu': + case 'ncnc001081': + return 'NC_NC00-10:81'; + + case 'csiso69french': + case 'fr': + case 'isoir69': + case 'iso646fr': + case 'nfz62010': + return 'NF_Z_62-010'; + + case 'csiso25french': + case 'isoir25': + case 'iso646fr1': + case 'nfz620101973': + return 'NF_Z_62-010_(1973)'; + + case 'csiso60danishnorwegian': + case 'csiso60norwegian1': + case 'isoir60': + case 'iso646no': + case 'no': + case 'ns45511': + return 'NS_4551-1'; + + case 'csiso61norwegian2': + case 'isoir61': + case 'iso646no2': + case 'no2': + case 'ns45512': + return 'NS_4551-2'; + + case 'osdebcdicdf03irv': + return 'OSD_EBCDIC_DF03_IRV'; + + case 'osdebcdicdf041': + return 'OSD_EBCDIC_DF04_1'; + + case 'osdebcdicdf0415': + return 'OSD_EBCDIC_DF04_15'; + + case 'cspc8danishnorwegian': + case 'pc8danishnorwegian': + return 'PC8-Danish-Norwegian'; + + case 'cspc8turkish': + case 'pc8turkish': + return 'PC8-Turkish'; + + case 'csiso16portuguese': + case 'isoir16': + case 'iso646pt': + case 'pt': + return 'PT'; + + case 'csiso84portuguese2': + case 'isoir84': + case 'iso646pt2': + case 'pt2': + return 'PT2'; + + case 'cp154': + case 'csptcp154': + case 'cyrillicasian': + case 'pt154': + case 'ptcp154': + return 'PTCP154'; + + case 'scsu': + return 'SCSU'; + + case 'csiso10swedish': + case 'fi': + case 'isoir10': + case 'iso646fi': + case 'iso646se': + case 'se': + case 'sen850200b': + return 'SEN_850200_B'; + + case 'csiso11swedishfornames': + case 'isoir11': + case 'iso646se2': + case 'se2': + case 'sen850200c': + return 'SEN_850200_C'; + + case 'csshiftjis': + case 'mskanji': + case 'shiftjis': + return 'Shift_JIS'; + + case 'csiso102t617bit': + case 'isoir102': + case 't617bit': + return 'T.61-7bit'; + + case 'csiso103t618bit': + case 'isoir103': + case 't61': + case 't618bit': + return 'T.61-8bit'; + + case 'csiso128t101g2': + case 'isoir128': + case 't101g2': + return 'T.101-G2'; + + case 'cstscii': + case 'tscii': + return 'TSCII'; + + case 'csunicode11': + case 'unicode11': + return 'UNICODE-1-1'; + + case 'csunicode11utf7': + case 'unicode11utf7': + return 'UNICODE-1-1-UTF-7'; + + case 'csunknown8bit': + case 'unknown8bit': + return 'UNKNOWN-8BIT'; + + case 'ansix341968': + case 'ansix341986': + case 'ascii': + case 'cp367': + case 'csascii': + case 'ibm367': + case 'isoir6': + case 'iso646us': + case 'iso646irv1991': + case 'us': + case 'usascii': + return 'US-ASCII'; + + case 'csusdk': + case 'usdk': + return 'us-dk'; + + case 'utf7': + return 'UTF-7'; + + case 'utf8': + return 'UTF-8'; + + case 'utf16': + return 'UTF-16'; + + case 'utf16be': + return 'UTF-16BE'; + + case 'utf16le': + return 'UTF-16LE'; + + case 'utf32': + return 'UTF-32'; + + case 'utf32be': + return 'UTF-32BE'; + + case 'utf32le': + return 'UTF-32LE'; + + case 'csventurainternational': + case 'venturainternational': + return 'Ventura-International'; + + case 'csventuramath': + case 'venturamath': + return 'Ventura-Math'; + + case 'csventuraus': + case 'venturaus': + return 'Ventura-US'; + + case 'csiso70videotexsupp1': + case 'isoir70': + case 'videotexsuppl': + return 'videotex-suppl'; + + case 'csviqr': + case 'viqr': + return 'VIQR'; + + case 'csviscii': + case 'viscii': + return 'VISCII'; + + case 'cswindows31j': + case 'windows31j': + return 'Windows-31J'; + + case 'iso885911': + case 'tis620': + return 'Windows-874'; + + case 'cseuckr': + case 'euckr': + case 'windows949': + case 'csksc56011987': + case 'isoir149': + case 'korean': + case 'ksc5601': + case 'ksc56011987': + case 'ksc56011989': + return 'Windows-949'; + + case 'windows1250': + return 'windows-1250'; + + case 'windows1251': + return 'windows-1251'; + + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso88591': + case 'isoir100': + case 'iso885911987': + case 'l1': + case 'latin1': + case 'windows1252': + return 'Windows-1252'; + + case 'windows1252': + return 'windows-1252'; + + case 'windows1253': + return 'windows-1253'; + + case 'csisolatin5': + case 'iso88599': + case 'isoir148': + case 'iso885991989': + case 'l5': + case 'latin5': + case 'windows1254': + return 'Windows-1254'; + + case 'windows1254': + return 'windows-1254'; + + case 'windows1255': + return 'windows-1255'; + + case 'windows1256': + return 'windows-1256'; + + case 'windows1257': + return 'windows-1257'; + + case 'windows1258': + return 'windows-1258'; + + default: + return $charset; + } + } + + function get_curl_version() + { + if (is_array($curl = curl_version())) + { + $curl = $curl['version']; + } + elseif (substr($curl, 0, 5) == 'curl/') + { + $curl = substr($curl, 5, strcspn($curl, "\x09\x0A\x0B\x0C\x0D", 5)); + } + elseif (substr($curl, 0, 8) == 'libcurl/') + { + $curl = substr($curl, 8, strcspn($curl, "\x09\x0A\x0B\x0C\x0D", 8)); + } + else + { + $curl = 0; + } + return $curl; + } + + function is_subclass_of($class1, $class2) + { + if (func_num_args() != 2) + { + trigger_error('Wrong parameter count for SimplePie_Misc::is_subclass_of()', E_USER_WARNING); + } + elseif (version_compare(PHP_VERSION, '5.0.3', '>=') || is_object($class1)) + { + return is_subclass_of($class1, $class2); + } + elseif (is_string($class1) && is_string($class2)) + { + if (class_exists($class1)) + { + if (class_exists($class2)) + { + $class2 = strtolower($class2); + while ($class1 = strtolower(get_parent_class($class1))) + { + if ($class1 == $class2) + { + return true; + } + } + } + } + else + { + trigger_error('Unknown class passed as parameter', E_USER_WARNNG); + } + } + return false; + } + + /** + * Strip HTML comments + * + * @access public + * @param string $data Data to strip comments from + * @return string Comment stripped string + */ + function strip_comments($data) + { + $output = ''; + while (($start = strpos($data, '', $start)) !== false) + { + $data = substr_replace($data, '', 0, $end + 3); + } + else + { + $data = ''; + } + } + return $output . $data; + } + + function parse_date($dt) + { + $parser = SimplePie_Parse_Date::get(); + return $parser->parse($dt); + } + + /** + * Decode HTML entities + * + * @static + * @access public + * @param string $data Input data + * @return string Output data + */ + function entities_decode($data) + { + $decoder =& new SimplePie_Decode_HTML_Entities($data); + return $decoder->parse(); + } + + /** + * Remove RFC822 comments + * + * @access public + * @param string $data Data to strip comments from + * @return string Comment stripped string + */ + function uncomment_rfc822($string) + { + $string = (string) $string; + $position = 0; + $length = strlen($string); + $depth = 0; + + $output = ''; + + while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) + { + $output .= substr($string, $position, $pos - $position); + $position = $pos + 1; + if ($string[$pos - 1] !== '\\') + { + $depth++; + while ($depth && $position < $length) + { + $position += strcspn($string, '()', $position); + if ($string[$position - 1] === '\\') + { + $position++; + continue; + } + elseif (isset($string[$position])) + { + switch ($string[$position]) + { + case '(': + $depth++; + break; + + case ')': + $depth--; + break; + } + $position++; + } + else + { + break; + } + } + } + else + { + $output .= '('; + } + } + $output .= substr($string, $position); + + return $output; + } + + function parse_mime($mime) + { + if (($pos = strpos($mime, ';')) === false) + { + return trim($mime); + } + else + { + return trim(substr($mime, 0, $pos)); + } + } + + function htmlspecialchars_decode($string, $quote_style) + { + if (function_exists('htmlspecialchars_decode')) + { + return htmlspecialchars_decode($string, $quote_style); + } + else + { + return strtr($string, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style))); + } + } + + function atom_03_construct_type($attribs) + { + if (isset($attribs['']['mode']) && strtolower(trim($attribs['']['mode']) == 'base64')) + { + $mode = SIMPLEPIE_CONSTRUCT_BASE64; + } + else + { + $mode = SIMPLEPIE_CONSTRUCT_NONE; + } + if (isset($attribs['']['type'])) + { + switch (strtolower(trim($attribs['']['type']))) + { + case 'text': + case 'text/plain': + return SIMPLEPIE_CONSTRUCT_TEXT | $mode; + + case 'html': + case 'text/html': + return SIMPLEPIE_CONSTRUCT_HTML | $mode; + + case 'xhtml': + case 'application/xhtml+xml': + return SIMPLEPIE_CONSTRUCT_XHTML | $mode; + + default: + return SIMPLEPIE_CONSTRUCT_NONE | $mode; + } + } + else + { + return SIMPLEPIE_CONSTRUCT_TEXT | $mode; + } + } + + function atom_10_construct_type($attribs) + { + if (isset($attribs['']['type'])) + { + switch (strtolower(trim($attribs['']['type']))) + { + case 'text': + return SIMPLEPIE_CONSTRUCT_TEXT; + + case 'html': + return SIMPLEPIE_CONSTRUCT_HTML; + + case 'xhtml': + return SIMPLEPIE_CONSTRUCT_XHTML; + + default: + return SIMPLEPIE_CONSTRUCT_NONE; + } + } + return SIMPLEPIE_CONSTRUCT_TEXT; + } + + function atom_10_content_construct_type($attribs) + { + if (isset($attribs['']['type'])) + { + $type = strtolower(trim($attribs['']['type'])); + switch ($type) + { + case 'text': + return SIMPLEPIE_CONSTRUCT_TEXT; + + case 'html': + return SIMPLEPIE_CONSTRUCT_HTML; + + case 'xhtml': + return SIMPLEPIE_CONSTRUCT_XHTML; + } + if (in_array(substr($type, -4), array('+xml', '/xml')) || substr($type, 0, 5) == 'text/') + { + return SIMPLEPIE_CONSTRUCT_NONE; + } + else + { + return SIMPLEPIE_CONSTRUCT_BASE64; + } + } + else + { + return SIMPLEPIE_CONSTRUCT_TEXT; + } + } + + function is_isegment_nz_nc($string) + { + return (bool) preg_match('/^([A-Za-z0-9\-._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!$&\'()*+,;=@]|(%[0-9ABCDEF]{2}))+$/u', $string); + } + + function space_seperated_tokens($string) + { + $space_characters = "\x20\x09\x0A\x0B\x0C\x0D"; + $string_length = strlen($string); + + $position = strspn($string, $space_characters); + $tokens = array(); + + while ($position < $string_length) + { + $len = strcspn($string, $space_characters, $position); + $tokens[] = substr($string, $position, $len); + $position += $len; + $position += strspn($string, $space_characters, $position); + } + + return $tokens; + } + + function array_unique($array) + { + if (version_compare(PHP_VERSION, '5.2', '>=')) + { + return array_unique($array); + } + else + { + $array = (array) $array; + $new_array = array(); + $new_array_strings = array(); + foreach ($array as $key => $value) + { + if (is_object($value)) + { + if (method_exists($value, '__toString')) + { + $cmp = $value->__toString(); + } + else + { + trigger_error('Object of class ' . get_class($value) . ' could not be converted to string', E_USER_ERROR); + } + } + elseif (is_array($value)) + { + $cmp = (string) reset($value); + } + else + { + $cmp = (string) $value; + } + if (!in_array($cmp, $new_array_strings)) + { + $new_array[$key] = $value; + $new_array_strings[] = $cmp; + } + } + return $new_array; + } + } + + /** + * Converts a unicode codepoint to a UTF-8 character + * + * @static + * @access public + * @param int $codepoint Unicode codepoint + * @return string UTF-8 character + */ + function codepoint_to_utf8($codepoint) + { + $codepoint = (int) $codepoint; + if ($codepoint < 0) + { + return false; + } + else if ($codepoint <= 0x7f) + { + return chr($codepoint); + } + else if ($codepoint <= 0x7ff) + { + return chr(0xc0 | ($codepoint >> 6)) . chr(0x80 | ($codepoint & 0x3f)); + } + else if ($codepoint <= 0xffff) + { + return chr(0xe0 | ($codepoint >> 12)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f)); + } + else if ($codepoint <= 0x10ffff) + { + return chr(0xf0 | ($codepoint >> 18)) . chr(0x80 | (($codepoint >> 12) & 0x3f)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f)); + } + else + { + // U+FFFD REPLACEMENT CHARACTER + return "\xEF\xBF\xBD"; + } + } + + /** + * Re-implementation of PHP 5's stripos() + * + * Returns the numeric position of the first occurrence of needle in the + * haystack string. + * + * @static + * @access string + * @param object $haystack + * @param string $needle Note that the needle may be a string of one or more + * characters. If needle is not a string, it is converted to an integer + * and applied as the ordinal value of a character. + * @param int $offset The optional offset parameter allows you to specify which + * character in haystack to start searching. The position returned is still + * relative to the beginning of haystack. + * @return bool If needle is not found, stripos() will return boolean false. + */ + function stripos($haystack, $needle, $offset = 0) + { + if (function_exists('stripos')) + { + return stripos($haystack, $needle, $offset); + } + else + { + if (is_string($needle)) + { + $needle = strtolower($needle); + } + elseif (is_int($needle) || is_bool($needle) || is_double($needle)) + { + $needle = strtolower(chr($needle)); + } + else + { + trigger_error('needle is not a string or an integer', E_USER_WARNING); + return false; + } + + return strpos(strtolower($haystack), $needle, $offset); + } + } + + /** + * Similar to parse_str() + * + * Returns an associative array of name/value pairs, where the value is an + * array of values that have used the same name + * + * @static + * @access string + * @param string $str The input string. + * @return array + */ + function parse_str($str) + { + $return = array(); + $str = explode('&', $str); + + foreach ($str as $section) + { + if (strpos($section, '=') !== false) + { + list($name, $value) = explode('=', $section, 2); + $return[urldecode($name)][] = urldecode($value); + } + else + { + $return[urldecode($section)][] = null; + } + } + + return $return; + } + + /** + * Detect XML encoding, as per XML 1.0 Appendix F.1 + * + * @todo Add support for EBCDIC + * @param string $data XML data + * @return array Possible encodings + */ + function xml_encoding($data) + { + // UTF-32 Big Endian BOM + if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") + { + $encoding[] = 'UTF-32BE'; + } + // UTF-32 Little Endian BOM + elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") + { + $encoding[] = 'UTF-32LE'; + } + // UTF-16 Big Endian BOM + elseif (substr($data, 0, 2) === "\xFE\xFF") + { + $encoding[] = 'UTF-16BE'; + } + // UTF-16 Little Endian BOM + elseif (substr($data, 0, 2) === "\xFF\xFE") + { + $encoding[] = 'UTF-16LE'; + } + // UTF-8 BOM + elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") + { + $encoding[] = 'UTF-8'; + } + // UTF-32 Big Endian Without BOM + elseif (substr($data, 0, 20) === "\x00\x00\x00\x3C\x00\x00\x00\x3F\x00\x00\x00\x78\x00\x00\x00\x6D\x00\x00\x00\x6C") + { + if ($pos = strpos($data, "\x00\x00\x00\x3F\x00\x00\x00\x3E")) + { + $parser =& new SimplePie_XML_Declaration_Parser(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 20), 'UTF-32BE', 'UTF-8')); + if ($parser->parse()) + { + $encoding[] = $parser->encoding; + } + } + $encoding[] = 'UTF-32BE'; + } + // UTF-32 Little Endian Without BOM + elseif (substr($data, 0, 20) === "\x3C\x00\x00\x00\x3F\x00\x00\x00\x78\x00\x00\x00\x6D\x00\x00\x00\x6C\x00\x00\x00") + { + if ($pos = strpos($data, "\x3F\x00\x00\x00\x3E\x00\x00\x00")) + { + $parser =& new SimplePie_XML_Declaration_Parser(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 20), 'UTF-32LE', 'UTF-8')); + if ($parser->parse()) + { + $encoding[] = $parser->encoding; + } + } + $encoding[] = 'UTF-32LE'; + } + // UTF-16 Big Endian Without BOM + elseif (substr($data, 0, 10) === "\x00\x3C\x00\x3F\x00\x78\x00\x6D\x00\x6C") + { + if ($pos = strpos($data, "\x00\x3F\x00\x3E")) + { + $parser =& new SimplePie_XML_Declaration_Parser(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 10), 'UTF-16BE', 'UTF-8')); + if ($parser->parse()) + { + $encoding[] = $parser->encoding; + } + } + $encoding[] = 'UTF-16BE'; + } + // UTF-16 Little Endian Without BOM + elseif (substr($data, 0, 10) === "\x3C\x00\x3F\x00\x78\x00\x6D\x00\x6C\x00") + { + if ($pos = strpos($data, "\x3F\x00\x3E\x00")) + { + $parser =& new SimplePie_XML_Declaration_Parser(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 10), 'UTF-16LE', 'UTF-8')); + if ($parser->parse()) + { + $encoding[] = $parser->encoding; + } + } + $encoding[] = 'UTF-16LE'; + } + // US-ASCII (or superset) + elseif (substr($data, 0, 5) === "\x3C\x3F\x78\x6D\x6C") + { + if ($pos = strpos($data, "\x3F\x3E")) + { + $parser =& new SimplePie_XML_Declaration_Parser(substr($data, 5, $pos - 5)); + if ($parser->parse()) + { + $encoding[] = $parser->encoding; + } + } + $encoding[] = 'UTF-8'; + } + // Fallback to UTF-8 + else + { + $encoding[] = 'UTF-8'; + } + return $encoding; + } +} + +/** + * Decode HTML Entities + * + * This implements HTML5 as of revision 967 (2007-06-28) + * + * @package SimplePie + */ +class SimplePie_Decode_HTML_Entities +{ + /** + * Data to be parsed + * + * @access private + * @var string + */ + var $data = ''; + + /** + * Currently consumed bytes + * + * @access private + * @var string + */ + var $consumed = ''; + + /** + * Position of the current byte being parsed + * + * @access private + * @var int + */ + var $position = 0; + + /** + * Create an instance of the class with the input data + * + * @access public + * @param string $data Input data + */ + function SimplePie_Decode_HTML_Entities($data) + { + $this->data = $data; + } + + /** + * Parse the input data + * + * @access public + * @return string Output data + */ + function parse() + { + while (($this->position = strpos($this->data, '&', $this->position)) !== false) + { + $this->consume(); + $this->entity(); + $this->consumed = ''; + } + return $this->data; + } + + /** + * Consume the next byte + * + * @access private + * @return mixed The next byte, or false, if there is no more data + */ + function consume() + { + if (isset($this->data[$this->position])) + { + $this->consumed .= $this->data[$this->position]; + return $this->data[$this->position++]; + } + else + { + $this->consumed = false; + return false; + } + } + + /** + * Consume a range of characters + * + * @access private + * @param string $chars Characters to consume + * @return mixed A series of characters that match the range, or false + */ + function consume_range($chars) + { + if ($len = strspn($this->data, $chars, $this->position)) + { + $data = substr($this->data, $this->position, $len); + $this->consumed .= $data; + $this->position += $len; + return $data; + } + else + { + $this->consumed = false; + return false; + } + } + + /** + * Unconsume one byte + * + * @access private + */ + function unconsume() + { + $this->consumed = substr($this->consumed, 0, -1); + $this->position--; + } + + /** + * Decode an entity + * + * @access private + */ + function entity() + { + switch ($this->consume()) + { + case "\x09": + case "\x0A": + case "\x0B": + case "\x0B": + case "\x0C": + case "\x20": + case "\x3C": + case "\x26": + case false: + break; + + case "\x23": + switch ($this->consume()) + { + case "\x78": + case "\x58": + $range = '0123456789ABCDEFabcdef'; + $hex = true; + break; + + default: + $range = '0123456789'; + $hex = false; + $this->unconsume(); + break; + } + + if ($codepoint = $this->consume_range($range)) + { + static $windows_1252_specials = array(0x0D => "\x0A", 0x80 => "\xE2\x82\xAC", 0x81 => "\xEF\xBF\xBD", 0x82 => "\xE2\x80\x9A", 0x83 => "\xC6\x92", 0x84 => "\xE2\x80\x9E", 0x85 => "\xE2\x80\xA6", 0x86 => "\xE2\x80\xA0", 0x87 => "\xE2\x80\xA1", 0x88 => "\xCB\x86", 0x89 => "\xE2\x80\xB0", 0x8A => "\xC5\xA0", 0x8B => "\xE2\x80\xB9", 0x8C => "\xC5\x92", 0x8D => "\xEF\xBF\xBD", 0x8E => "\xC5\xBD", 0x8F => "\xEF\xBF\xBD", 0x90 => "\xEF\xBF\xBD", 0x91 => "\xE2\x80\x98", 0x92 => "\xE2\x80\x99", 0x93 => "\xE2\x80\x9C", 0x94 => "\xE2\x80\x9D", 0x95 => "\xE2\x80\xA2", 0x96 => "\xE2\x80\x93", 0x97 => "\xE2\x80\x94", 0x98 => "\xCB\x9C", 0x99 => "\xE2\x84\xA2", 0x9A => "\xC5\xA1", 0x9B => "\xE2\x80\xBA", 0x9C => "\xC5\x93", 0x9D => "\xEF\xBF\xBD", 0x9E => "\xC5\xBE", 0x9F => "\xC5\xB8"); + + if ($hex) + { + $codepoint = hexdec($codepoint); + } + else + { + $codepoint = intval($codepoint); + } + + if (isset($windows_1252_specials[$codepoint])) + { + $replacement = $windows_1252_specials[$codepoint]; + } + else + { + $replacement = SimplePie_Misc::codepoint_to_utf8($codepoint); + } + + if ($this->consume() != ';') + { + $this->unconsume(); + } + + $consumed_length = strlen($this->consumed); + $this->data = substr_replace($this->data, $replacement, $this->position - $consumed_length, $consumed_length); + $this->position += strlen($replacement) - $consumed_length; + } + break; + + default: + static $entities = array('Aacute' => "\xC3\x81", 'aacute' => "\xC3\xA1", 'Aacute;' => "\xC3\x81", 'aacute;' => "\xC3\xA1", 'Acirc' => "\xC3\x82", 'acirc' => "\xC3\xA2", 'Acirc;' => "\xC3\x82", 'acirc;' => "\xC3\xA2", 'acute' => "\xC2\xB4", 'acute;' => "\xC2\xB4", 'AElig' => "\xC3\x86", 'aelig' => "\xC3\xA6", 'AElig;' => "\xC3\x86", 'aelig;' => "\xC3\xA6", 'Agrave' => "\xC3\x80", 'agrave' => "\xC3\xA0", 'Agrave;' => "\xC3\x80", 'agrave;' => "\xC3\xA0", 'alefsym;' => "\xE2\x84\xB5", 'Alpha;' => "\xCE\x91", 'alpha;' => "\xCE\xB1", 'AMP' => "\x26", 'amp' => "\x26", 'AMP;' => "\x26", 'amp;' => "\x26", 'and;' => "\xE2\x88\xA7", 'ang;' => "\xE2\x88\xA0", 'apos;' => "\x27", 'Aring' => "\xC3\x85", 'aring' => "\xC3\xA5", 'Aring;' => "\xC3\x85", 'aring;' => "\xC3\xA5", 'asymp;' => "\xE2\x89\x88", 'Atilde' => "\xC3\x83", 'atilde' => "\xC3\xA3", 'Atilde;' => "\xC3\x83", 'atilde;' => "\xC3\xA3", 'Auml' => "\xC3\x84", 'auml' => "\xC3\xA4", 'Auml;' => "\xC3\x84", 'auml;' => "\xC3\xA4", 'bdquo;' => "\xE2\x80\x9E", 'Beta;' => "\xCE\x92", 'beta;' => "\xCE\xB2", 'brvbar' => "\xC2\xA6", 'brvbar;' => "\xC2\xA6", 'bull;' => "\xE2\x80\xA2", 'cap;' => "\xE2\x88\xA9", 'Ccedil' => "\xC3\x87", 'ccedil' => "\xC3\xA7", 'Ccedil;' => "\xC3\x87", 'ccedil;' => "\xC3\xA7", 'cedil' => "\xC2\xB8", 'cedil;' => "\xC2\xB8", 'cent' => "\xC2\xA2", 'cent;' => "\xC2\xA2", 'Chi;' => "\xCE\xA7", 'chi;' => "\xCF\x87", 'circ;' => "\xCB\x86", 'clubs;' => "\xE2\x99\xA3", 'cong;' => "\xE2\x89\x85", 'COPY' => "\xC2\xA9", 'copy' => "\xC2\xA9", 'COPY;' => "\xC2\xA9", 'copy;' => "\xC2\xA9", 'crarr;' => "\xE2\x86\xB5", 'cup;' => "\xE2\x88\xAA", 'curren' => "\xC2\xA4", 'curren;' => "\xC2\xA4", 'Dagger;' => "\xE2\x80\xA1", 'dagger;' => "\xE2\x80\xA0", 'dArr;' => "\xE2\x87\x93", 'darr;' => "\xE2\x86\x93", 'deg' => "\xC2\xB0", 'deg;' => "\xC2\xB0", 'Delta;' => "\xCE\x94", 'delta;' => "\xCE\xB4", 'diams;' => "\xE2\x99\xA6", 'divide' => "\xC3\xB7", 'divide;' => "\xC3\xB7", 'Eacute' => "\xC3\x89", 'eacute' => "\xC3\xA9", 'Eacute;' => "\xC3\x89", 'eacute;' => "\xC3\xA9", 'Ecirc' => "\xC3\x8A", 'ecirc' => "\xC3\xAA", 'Ecirc;' => "\xC3\x8A", 'ecirc;' => "\xC3\xAA", 'Egrave' => "\xC3\x88", 'egrave' => "\xC3\xA8", 'Egrave;' => "\xC3\x88", 'egrave;' => "\xC3\xA8", 'empty;' => "\xE2\x88\x85", 'emsp;' => "\xE2\x80\x83", 'ensp;' => "\xE2\x80\x82", 'Epsilon;' => "\xCE\x95", 'epsilon;' => "\xCE\xB5", 'equiv;' => "\xE2\x89\xA1", 'Eta;' => "\xCE\x97", 'eta;' => "\xCE\xB7", 'ETH' => "\xC3\x90", 'eth' => "\xC3\xB0", 'ETH;' => "\xC3\x90", 'eth;' => "\xC3\xB0", 'Euml' => "\xC3\x8B", 'euml' => "\xC3\xAB", 'Euml;' => "\xC3\x8B", 'euml;' => "\xC3\xAB", 'euro;' => "\xE2\x82\xAC", 'exist;' => "\xE2\x88\x83", 'fnof;' => "\xC6\x92", 'forall;' => "\xE2\x88\x80", 'frac12' => "\xC2\xBD", 'frac12;' => "\xC2\xBD", 'frac14' => "\xC2\xBC", 'frac14;' => "\xC2\xBC", 'frac34' => "\xC2\xBE", 'frac34;' => "\xC2\xBE", 'frasl;' => "\xE2\x81\x84", 'Gamma;' => "\xCE\x93", 'gamma;' => "\xCE\xB3", 'ge;' => "\xE2\x89\xA5", 'GT' => "\x3E", 'gt' => "\x3E", 'GT;' => "\x3E", 'gt;' => "\x3E", 'hArr;' => "\xE2\x87\x94", 'harr;' => "\xE2\x86\x94", 'hearts;' => "\xE2\x99\xA5", 'hellip;' => "\xE2\x80\xA6", 'Iacute' => "\xC3\x8D", 'iacute' => "\xC3\xAD", 'Iacute;' => "\xC3\x8D", 'iacute;' => "\xC3\xAD", 'Icirc' => "\xC3\x8E", 'icirc' => "\xC3\xAE", 'Icirc;' => "\xC3\x8E", 'icirc;' => "\xC3\xAE", 'iexcl' => "\xC2\xA1", 'iexcl;' => "\xC2\xA1", 'Igrave' => "\xC3\x8C", 'igrave' => "\xC3\xAC", 'Igrave;' => "\xC3\x8C", 'igrave;' => "\xC3\xAC", 'image;' => "\xE2\x84\x91", 'infin;' => "\xE2\x88\x9E", 'int;' => "\xE2\x88\xAB", 'Iota;' => "\xCE\x99", 'iota;' => "\xCE\xB9", 'iquest' => "\xC2\xBF", 'iquest;' => "\xC2\xBF", 'isin;' => "\xE2\x88\x88", 'Iuml' => "\xC3\x8F", 'iuml' => "\xC3\xAF", 'Iuml;' => "\xC3\x8F", 'iuml;' => "\xC3\xAF", 'Kappa;' => "\xCE\x9A", 'kappa;' => "\xCE\xBA", 'Lambda;' => "\xCE\x9B", 'lambda;' => "\xCE\xBB", 'lang;' => "\xE3\x80\x88", 'laquo' => "\xC2\xAB", 'laquo;' => "\xC2\xAB", 'lArr;' => "\xE2\x87\x90", 'larr;' => "\xE2\x86\x90", 'lceil;' => "\xE2\x8C\x88", 'ldquo;' => "\xE2\x80\x9C", 'le;' => "\xE2\x89\xA4", 'lfloor;' => "\xE2\x8C\x8A", 'lowast;' => "\xE2\x88\x97", 'loz;' => "\xE2\x97\x8A", 'lrm;' => "\xE2\x80\x8E", 'lsaquo;' => "\xE2\x80\xB9", 'lsquo;' => "\xE2\x80\x98", 'LT' => "\x3C", 'lt' => "\x3C", 'LT;' => "\x3C", 'lt;' => "\x3C", 'macr' => "\xC2\xAF", 'macr;' => "\xC2\xAF", 'mdash;' => "\xE2\x80\x94", 'micro' => "\xC2\xB5", 'micro;' => "\xC2\xB5", 'middot' => "\xC2\xB7", 'middot;' => "\xC2\xB7", 'minus;' => "\xE2\x88\x92", 'Mu;' => "\xCE\x9C", 'mu;' => "\xCE\xBC", 'nabla;' => "\xE2\x88\x87", 'nbsp' => "\xC2\xA0", 'nbsp;' => "\xC2\xA0", 'ndash;' => "\xE2\x80\x93", 'ne;' => "\xE2\x89\xA0", 'ni;' => "\xE2\x88\x8B", 'not' => "\xC2\xAC", 'not;' => "\xC2\xAC", 'notin;' => "\xE2\x88\x89", 'nsub;' => "\xE2\x8A\x84", 'Ntilde' => "\xC3\x91", 'ntilde' => "\xC3\xB1", 'Ntilde;' => "\xC3\x91", 'ntilde;' => "\xC3\xB1", 'Nu;' => "\xCE\x9D", 'nu;' => "\xCE\xBD", 'Oacute' => "\xC3\x93", 'oacute' => "\xC3\xB3", 'Oacute;' => "\xC3\x93", 'oacute;' => "\xC3\xB3", 'Ocirc' => "\xC3\x94", 'ocirc' => "\xC3\xB4", 'Ocirc;' => "\xC3\x94", 'ocirc;' => "\xC3\xB4", 'OElig;' => "\xC5\x92", 'oelig;' => "\xC5\x93", 'Ograve' => "\xC3\x92", 'ograve' => "\xC3\xB2", 'Ograve;' => "\xC3\x92", 'ograve;' => "\xC3\xB2", 'oline;' => "\xE2\x80\xBE", 'Omega;' => "\xCE\xA9", 'omega;' => "\xCF\x89", 'Omicron;' => "\xCE\x9F", 'omicron;' => "\xCE\xBF", 'oplus;' => "\xE2\x8A\x95", 'or;' => "\xE2\x88\xA8", 'ordf' => "\xC2\xAA", 'ordf;' => "\xC2\xAA", 'ordm' => "\xC2\xBA", 'ordm;' => "\xC2\xBA", 'Oslash' => "\xC3\x98", 'oslash' => "\xC3\xB8", 'Oslash;' => "\xC3\x98", 'oslash;' => "\xC3\xB8", 'Otilde' => "\xC3\x95", 'otilde' => "\xC3\xB5", 'Otilde;' => "\xC3\x95", 'otilde;' => "\xC3\xB5", 'otimes;' => "\xE2\x8A\x97", 'Ouml' => "\xC3\x96", 'ouml' => "\xC3\xB6", 'Ouml;' => "\xC3\x96", 'ouml;' => "\xC3\xB6", 'para' => "\xC2\xB6", 'para;' => "\xC2\xB6", 'part;' => "\xE2\x88\x82", 'permil;' => "\xE2\x80\xB0", 'perp;' => "\xE2\x8A\xA5", 'Phi;' => "\xCE\xA6", 'phi;' => "\xCF\x86", 'Pi;' => "\xCE\xA0", 'pi;' => "\xCF\x80", 'piv;' => "\xCF\x96", 'plusmn' => "\xC2\xB1", 'plusmn;' => "\xC2\xB1", 'pound' => "\xC2\xA3", 'pound;' => "\xC2\xA3", 'Prime;' => "\xE2\x80\xB3", 'prime;' => "\xE2\x80\xB2", 'prod;' => "\xE2\x88\x8F", 'prop;' => "\xE2\x88\x9D", 'Psi;' => "\xCE\xA8", 'psi;' => "\xCF\x88", 'QUOT' => "\x22", 'quot' => "\x22", 'QUOT;' => "\x22", 'quot;' => "\x22", 'radic;' => "\xE2\x88\x9A", 'rang;' => "\xE3\x80\x89", 'raquo' => "\xC2\xBB", 'raquo;' => "\xC2\xBB", 'rArr;' => "\xE2\x87\x92", 'rarr;' => "\xE2\x86\x92", 'rceil;' => "\xE2\x8C\x89", 'rdquo;' => "\xE2\x80\x9D", 'real;' => "\xE2\x84\x9C", 'REG' => "\xC2\xAE", 'reg' => "\xC2\xAE", 'REG;' => "\xC2\xAE", 'reg;' => "\xC2\xAE", 'rfloor;' => "\xE2\x8C\x8B", 'Rho;' => "\xCE\xA1", 'rho;' => "\xCF\x81", 'rlm;' => "\xE2\x80\x8F", 'rsaquo;' => "\xE2\x80\xBA", 'rsquo;' => "\xE2\x80\x99", 'sbquo;' => "\xE2\x80\x9A", 'Scaron;' => "\xC5\xA0", 'scaron;' => "\xC5\xA1", 'sdot;' => "\xE2\x8B\x85", 'sect' => "\xC2\xA7", 'sect;' => "\xC2\xA7", 'shy' => "\xC2\xAD", 'shy;' => "\xC2\xAD", 'Sigma;' => "\xCE\xA3", 'sigma;' => "\xCF\x83", 'sigmaf;' => "\xCF\x82", 'sim;' => "\xE2\x88\xBC", 'spades;' => "\xE2\x99\xA0", 'sub;' => "\xE2\x8A\x82", 'sube;' => "\xE2\x8A\x86", 'sum;' => "\xE2\x88\x91", 'sup;' => "\xE2\x8A\x83", 'sup1' => "\xC2\xB9", 'sup1;' => "\xC2\xB9", 'sup2' => "\xC2\xB2", 'sup2;' => "\xC2\xB2", 'sup3' => "\xC2\xB3", 'sup3;' => "\xC2\xB3", 'supe;' => "\xE2\x8A\x87", 'szlig' => "\xC3\x9F", 'szlig;' => "\xC3\x9F", 'Tau;' => "\xCE\xA4", 'tau;' => "\xCF\x84", 'there4;' => "\xE2\x88\xB4", 'Theta;' => "\xCE\x98", 'theta;' => "\xCE\xB8", 'thetasym;' => "\xCF\x91", 'thinsp;' => "\xE2\x80\x89", 'THORN' => "\xC3\x9E", 'thorn' => "\xC3\xBE", 'THORN;' => "\xC3\x9E", 'thorn;' => "\xC3\xBE", 'tilde;' => "\xCB\x9C", 'times' => "\xC3\x97", 'times;' => "\xC3\x97", 'TRADE;' => "\xE2\x84\xA2", 'trade;' => "\xE2\x84\xA2", 'Uacute' => "\xC3\x9A", 'uacute' => "\xC3\xBA", 'Uacute;' => "\xC3\x9A", 'uacute;' => "\xC3\xBA", 'uArr;' => "\xE2\x87\x91", 'uarr;' => "\xE2\x86\x91", 'Ucirc' => "\xC3\x9B", 'ucirc' => "\xC3\xBB", 'Ucirc;' => "\xC3\x9B", 'ucirc;' => "\xC3\xBB", 'Ugrave' => "\xC3\x99", 'ugrave' => "\xC3\xB9", 'Ugrave;' => "\xC3\x99", 'ugrave;' => "\xC3\xB9", 'uml' => "\xC2\xA8", 'uml;' => "\xC2\xA8", 'upsih;' => "\xCF\x92", 'Upsilon;' => "\xCE\xA5", 'upsilon;' => "\xCF\x85", 'Uuml' => "\xC3\x9C", 'uuml' => "\xC3\xBC", 'Uuml;' => "\xC3\x9C", 'uuml;' => "\xC3\xBC", 'weierp;' => "\xE2\x84\x98", 'Xi;' => "\xCE\x9E", 'xi;' => "\xCE\xBE", 'Yacute' => "\xC3\x9D", 'yacute' => "\xC3\xBD", 'Yacute;' => "\xC3\x9D", 'yacute;' => "\xC3\xBD", 'yen' => "\xC2\xA5", 'yen;' => "\xC2\xA5", 'yuml' => "\xC3\xBF", 'Yuml;' => "\xC5\xB8", 'yuml;' => "\xC3\xBF", 'Zeta;' => "\xCE\x96", 'zeta;' => "\xCE\xB6", 'zwj;' => "\xE2\x80\x8D", 'zwnj;' => "\xE2\x80\x8C"); + + for ($i = 0, $match = null; $i < 9 && $this->consume() !== false; $i++) + { + $consumed = substr($this->consumed, 1); + if (isset($entities[$consumed])) + { + $match = $consumed; + } + } + + if ($match !== null) + { + $this->data = substr_replace($this->data, $entities[$match], $this->position - strlen($consumed) - 1, strlen($match) + 1); + $this->position += strlen($entities[$match]) - strlen($consumed) - 1; + } + break; + } + } +} + +/** + * Date Parser + * + * @package SimplePie + */ +class SimplePie_Parse_Date +{ + /** + * Input data + * + * @access protected + * @var string + */ + var $date; + + /** + * List of days, calendar day name => ordinal day number in the week + * + * @access protected + * @var array + */ + var $day = array( + // English + 'mon' => 1, + 'monday' => 1, + 'tue' => 2, + 'tuesday' => 2, + 'wed' => 3, + 'wednesday' => 3, + 'thu' => 4, + 'thursday' => 4, + 'fri' => 5, + 'friday' => 5, + 'sat' => 6, + 'saturday' => 6, + 'sun' => 7, + 'sunday' => 7, + // Dutch + 'maandag' => 1, + 'dinsdag' => 2, + 'woensdag' => 3, + 'donderdag' => 4, + 'vrijdag' => 5, + 'zaterdag' => 6, + 'zondag' => 7, + // French + 'lundi' => 1, + 'mardi' => 2, + 'mercredi' => 3, + 'jeudi' => 4, + 'vendredi' => 5, + 'samedi' => 6, + 'dimanche' => 7, + // German + 'montag' => 1, + 'dienstag' => 2, + 'mittwoch' => 3, + 'donnerstag' => 4, + 'freitag' => 5, + 'samstag' => 6, + 'sonnabend' => 6, + 'sonntag' => 7, + // Italian + 'lunedì' => 1, + 'martedì' => 2, + 'mercoledì' => 3, + 'giovedì' => 4, + 'venerdì' => 5, + 'sabato' => 6, + 'domenica' => 7, + // Spanish + 'lunes' => 1, + 'martes' => 2, + 'miércoles' => 3, + 'jueves' => 4, + 'viernes' => 5, + 'sábado' => 6, + 'domingo' => 7, + // Finnish + 'maanantai' => 1, + 'tiistai' => 2, + 'keskiviikko' => 3, + 'torstai' => 4, + 'perjantai' => 5, + 'lauantai' => 6, + 'sunnuntai' => 7, + // Hungarian + 'hétfÅ‘' => 1, + 'kedd' => 2, + 'szerda' => 3, + 'csütörtok' => 4, + 'péntek' => 5, + 'szombat' => 6, + 'vasárnap' => 7, + // Greek + 'Δευ' => 1, + 'ΤÏι' => 2, + 'Τετ' => 3, + 'Πεμ' => 4, + 'ΠαÏ' => 5, + 'Σαβ' => 6, + 'ΚυÏ' => 7, + ); + + /** + * List of months, calendar month name => calendar month number + * + * @access protected + * @var array + */ + var $month = array( + // English + 'jan' => 1, + 'january' => 1, + 'feb' => 2, + 'february' => 2, + 'mar' => 3, + 'march' => 3, + 'apr' => 4, + 'april' => 4, + 'may' => 5, + // No long form of May + 'jun' => 6, + 'june' => 6, + 'jul' => 7, + 'july' => 7, + 'aug' => 8, + 'august' => 8, + 'sep' => 9, + 'september' => 8, + 'oct' => 10, + 'october' => 10, + 'nov' => 11, + 'november' => 11, + 'dec' => 12, + 'december' => 12, + // Dutch + 'januari' => 1, + 'februari' => 2, + 'maart' => 3, + 'april' => 4, + 'mei' => 5, + 'juni' => 6, + 'juli' => 7, + 'augustus' => 8, + 'september' => 9, + 'oktober' => 10, + 'november' => 11, + 'december' => 12, + // French + 'janvier' => 1, + 'février' => 2, + 'mars' => 3, + 'avril' => 4, + 'mai' => 5, + 'juin' => 6, + 'juillet' => 7, + 'août' => 8, + 'septembre' => 9, + 'octobre' => 10, + 'novembre' => 11, + 'décembre' => 12, + // German + 'januar' => 1, + 'februar' => 2, + 'märz' => 3, + 'april' => 4, + 'mai' => 5, + 'juni' => 6, + 'juli' => 7, + 'august' => 8, + 'september' => 9, + 'oktober' => 10, + 'november' => 11, + 'dezember' => 12, + // Italian + 'gennaio' => 1, + 'febbraio' => 2, + 'marzo' => 3, + 'aprile' => 4, + 'maggio' => 5, + 'giugno' => 6, + 'luglio' => 7, + 'agosto' => 8, + 'settembre' => 9, + 'ottobre' => 10, + 'novembre' => 11, + 'dicembre' => 12, + // Spanish + 'enero' => 1, + 'febrero' => 2, + 'marzo' => 3, + 'abril' => 4, + 'mayo' => 5, + 'junio' => 6, + 'julio' => 7, + 'agosto' => 8, + 'septiembre' => 9, + 'setiembre' => 9, + 'octubre' => 10, + 'noviembre' => 11, + 'diciembre' => 12, + // Finnish + 'tammikuu' => 1, + 'helmikuu' => 2, + 'maaliskuu' => 3, + 'huhtikuu' => 4, + 'toukokuu' => 5, + 'kesäkuu' => 6, + 'heinäkuu' => 7, + 'elokuu' => 8, + 'suuskuu' => 9, + 'lokakuu' => 10, + 'marras' => 11, + 'joulukuu' => 12, + // Hungarian + 'január' => 1, + 'február' => 2, + 'március' => 3, + 'április' => 4, + 'május' => 5, + 'június' => 6, + 'július' => 7, + 'augusztus' => 8, + 'szeptember' => 9, + 'október' => 10, + 'november' => 11, + 'december' => 12, + // Greek + 'Ιαν' => 1, + 'Φεβ' => 2, + 'Μάώ' => 3, + 'Μαώ' => 3, + 'ΑπÏ' => 4, + 'Μάι' => 5, + 'Μαϊ' => 5, + 'Μαι' => 5, + 'ΙοÏν' => 6, + 'Ιον' => 6, + 'ΙοÏλ' => 7, + 'Ιολ' => 7, + 'ΑÏγ' => 8, + 'Αυγ' => 8, + 'Σεπ' => 9, + 'Οκτ' => 10, + 'Îοέ' => 11, + 'Δεκ' => 12, + ); + + /** + * List of timezones, abbreviation => offset from UTC + * + * @access protected + * @var array + */ + var $timezone = array( + 'ACDT' => 37800, + 'ACIT' => 28800, + 'ACST' => 34200, + 'ACT' => -18000, + 'ACWDT' => 35100, + 'ACWST' => 31500, + 'AEDT' => 39600, + 'AEST' => 36000, + 'AFT' => 16200, + 'AKDT' => -28800, + 'AKST' => -32400, + 'AMDT' => 18000, + 'AMT' => -14400, + 'ANAST' => 46800, + 'ANAT' => 43200, + 'ART' => -10800, + 'AZOST' => -3600, + 'AZST' => 18000, + 'AZT' => 14400, + 'BIOT' => 21600, + 'BIT' => -43200, + 'BOT' => -14400, + 'BRST' => -7200, + 'BRT' => -10800, + 'BST' => 3600, + 'BTT' => 21600, + 'CAST' => 18000, + 'CAT' => 7200, + 'CCT' => 23400, + 'CDT' => -18000, + 'CEDT' => 7200, + 'CET' => 3600, + 'CGST' => -7200, + 'CGT' => -10800, + 'CHADT' => 49500, + 'CHAST' => 45900, + 'CIST' => -28800, + 'CKT' => -36000, + 'CLDT' => -10800, + 'CLST' => -14400, + 'COT' => -18000, + 'CST' => -21600, + 'CVT' => -3600, + 'CXT' => 25200, + 'DAVT' => 25200, + 'DTAT' => 36000, + 'EADT' => -18000, + 'EAST' => -21600, + 'EAT' => 10800, + 'ECT' => -18000, + 'EDT' => -14400, + 'EEST' => 10800, + 'EET' => 7200, + 'EGT' => -3600, + 'EKST' => 21600, + 'EST' => -18000, + 'FJT' => 43200, + 'FKDT' => -10800, + 'FKST' => -14400, + 'FNT' => -7200, + 'GALT' => -21600, + 'GEDT' => 14400, + 'GEST' => 10800, + 'GFT' => -10800, + 'GILT' => 43200, + 'GIT' => -32400, + 'GST' => 14400, + 'GST' => -7200, + 'GYT' => -14400, + 'HAA' => -10800, + 'HAC' => -18000, + 'HADT' => -32400, + 'HAE' => -14400, + 'HAP' => -25200, + 'HAR' => -21600, + 'HAST' => -36000, + 'HAT' => -9000, + 'HAY' => -28800, + 'HKST' => 28800, + 'HMT' => 18000, + 'HNA' => -14400, + 'HNC' => -21600, + 'HNE' => -18000, + 'HNP' => -28800, + 'HNR' => -25200, + 'HNT' => -12600, + 'HNY' => -32400, + 'IRDT' => 16200, + 'IRKST' => 32400, + 'IRKT' => 28800, + 'IRST' => 12600, + 'JFDT' => -10800, + 'JFST' => -14400, + 'JST' => 32400, + 'KGST' => 21600, + 'KGT' => 18000, + 'KOST' => 39600, + 'KOVST' => 28800, + 'KOVT' => 25200, + 'KRAST' => 28800, + 'KRAT' => 25200, + 'KST' => 32400, + 'LHDT' => 39600, + 'LHST' => 37800, + 'LINT' => 50400, + 'LKT' => 21600, + 'MAGST' => 43200, + 'MAGT' => 39600, + 'MAWT' => 21600, + 'MDT' => -21600, + 'MESZ' => 7200, + 'MEZ' => 3600, + 'MHT' => 43200, + 'MIT' => -34200, + 'MNST' => 32400, + 'MSDT' => 14400, + 'MSST' => 10800, + 'MST' => -25200, + 'MUT' => 14400, + 'MVT' => 18000, + 'MYT' => 28800, + 'NCT' => 39600, + 'NDT' => -9000, + 'NFT' => 41400, + 'NMIT' => 36000, + 'NOVST' => 25200, + 'NOVT' => 21600, + 'NPT' => 20700, + 'NRT' => 43200, + 'NST' => -12600, + 'NUT' => -39600, + 'NZDT' => 46800, + 'NZST' => 43200, + 'OMSST' => 25200, + 'OMST' => 21600, + 'PDT' => -25200, + 'PET' => -18000, + 'PETST' => 46800, + 'PETT' => 43200, + 'PGT' => 36000, + 'PHOT' => 46800, + 'PHT' => 28800, + 'PKT' => 18000, + 'PMDT' => -7200, + 'PMST' => -10800, + 'PONT' => 39600, + 'PST' => -28800, + 'PWT' => 32400, + 'PYST' => -10800, + 'PYT' => -14400, + 'RET' => 14400, + 'ROTT' => -10800, + 'SAMST' => 18000, + 'SAMT' => 14400, + 'SAST' => 7200, + 'SBT' => 39600, + 'SCDT' => 46800, + 'SCST' => 43200, + 'SCT' => 14400, + 'SEST' => 3600, + 'SGT' => 28800, + 'SIT' => 28800, + 'SRT' => -10800, + 'SST' => -39600, + 'SYST' => 10800, + 'SYT' => 7200, + 'TFT' => 18000, + 'THAT' => -36000, + 'TJT' => 18000, + 'TKT' => -36000, + 'TMT' => 18000, + 'TOT' => 46800, + 'TPT' => 32400, + 'TRUT' => 36000, + 'TVT' => 43200, + 'TWT' => 28800, + 'UYST' => -7200, + 'UYT' => -10800, + 'UZT' => 18000, + 'VET' => -14400, + 'VLAST' => 39600, + 'VLAT' => 36000, + 'VOST' => 21600, + 'VUT' => 39600, + 'WAST' => 7200, + 'WAT' => 3600, + 'WDT' => 32400, + 'WEST' => 3600, + 'WFT' => 43200, + 'WIB' => 25200, + 'WIT' => 32400, + 'WITA' => 28800, + 'WKST' => 18000, + 'WST' => 28800, + 'YAKST' => 36000, + 'YAKT' => 32400, + 'YAPT' => 36000, + 'YEKST' => 21600, + 'YEKT' => 18000, + ); + + /** + * Cached PCRE for SimplePie_Parse_Date::$day + * + * @access protected + * @var string + */ + var $day_pcre; + + /** + * Cached PCRE for SimplePie_Parse_Date::$month + * + * @access protected + * @var string + */ + var $month_pcre; + + /** + * Array of user-added callback methods + * + * @access private + * @var array + */ + var $built_in = array(); + + /** + * Array of user-added callback methods + * + * @access private + * @var array + */ + var $user = array(); + + /** + * Create new SimplePie_Parse_Date object, and set self::day_pcre, + * self::month_pcre, and self::built_in + * + * @access private + */ + function SimplePie_Parse_Date() + { + $this->day_pcre = '(' . implode(array_keys($this->day), '|') . ')'; + $this->month_pcre = '(' . implode(array_keys($this->month), '|') . ')'; + + static $cache; + if (!isset($cache[get_class($this)])) + { + $all_methods = get_class_methods($this); + + foreach ($all_methods as $method) + { + if (strtolower(substr($method, 0, 5)) === 'date_') + { + $cache[get_class($this)][] = $method; + } + } + } + + foreach ($cache[get_class($this)] as $method) + { + $this->built_in[] = $method; + } + } + + /** + * Get the object + * + * @access public + */ + function get() + { + static $object; + if (!$object) + { + $object =& new SimplePie_Parse_Date; + } + return $object; + } + + /** + * Parse a date + * + * @final + * @access public + * @param string $date Date to parse + * @return int Timestamp corresponding to date string, or false on failure + */ + function parse($date) + { + foreach ($this->user as $method) + { + if (($returned = call_user_func($method, $date)) !== false) + { + return $returned; + } + } + + foreach ($this->built_in as $method) + { + if (($returned = call_user_func(array(&$this, $method), $date)) !== false) + { + return $returned; + } + } + + return false; + } + + /** + * Add a callback method to parse a date + * + * @final + * @access public + * @param callback $callback + */ + function add_callback($callback) + { + if (is_callable($callback)) + { + $this->user[] = $callback; + } + else + { + trigger_error('User-supplied function must be a valid callback', E_USER_WARNING); + } + } + + /** + * Parse a superset of W3C-DTF (allows hyphens and colons to be omitted, as + * well as allowing any of upper or lower case "T", horizontal tabs, or + * spaces to be used as the time seperator (including more than one)) + * + * @access protected + * @return int Timestamp + */ + function date_w3cdtf($date) + { + static $pcre; + if (!$pcre) + { + $year = '([0-9]{4})'; + $month = $day = $hour = $minute = $second = '([0-9]{2})'; + $decimal = '([0-9]*)'; + $zone = '(?:(Z)|([+\-])([0-9]{1,2}):?([0-9]{1,2}))'; + $pcre = '/^' . $year . '(?:-?' . $month . '(?:-?' . $day . '(?:[Tt\x09\x20]+' . $hour . '(?::?' . $minute . '(?::?' . $second . '(?:.' . $decimal . ')?)?)?' . $zone . ')?)?)?$/'; + } + if (preg_match($pcre, $date, $match)) + { + /* + Capturing subpatterns: + 1: Year + 2: Month + 3: Day + 4: Hour + 5: Minute + 6: Second + 7: Decimal fraction of a second + 8: Zulu + 9: Timezone ± + 10: Timezone hours + 11: Timezone minutes + */ + + // Fill in empty matches + for ($i = count($match); $i <= 3; $i++) + { + $match[$i] = '1'; + } + + for ($i = count($match); $i <= 7; $i++) + { + $match[$i] = '0'; + } + + // Numeric timezone + if (isset($match[9]) && $match[9] !== '') + { + $timezone = $match[10] * 3600; + $timezone += $match[11] * 60; + if ($match[9] === '-') + { + $timezone = 0 - $timezone; + } + } + else + { + $timezone = 0; + } + + // Convert the number of seconds to an integer, taking decimals into account + $second = round($match[6] + $match[7] / pow(10, strlen($match[7]))); + + return gmmktime($match[4], $match[5], $second, $match[2], $match[3], $match[1]) - $timezone; + } + else + { + return false; + } + } + + /** + * Remove RFC822 comments + * + * @access protected + * @param string $data Data to strip comments from + * @return string Comment stripped string + */ + function remove_rfc2822_comments($string) + { + $string = (string) $string; + $position = 0; + $length = strlen($string); + $depth = 0; + + $output = ''; + + while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) + { + $output .= substr($string, $position, $pos - $position); + $position = $pos + 1; + if ($string[$pos - 1] !== '\\') + { + $depth++; + while ($depth && $position < $length) + { + $position += strcspn($string, '()', $position); + if ($string[$position - 1] === '\\') + { + $position++; + continue; + } + elseif (isset($string[$position])) + { + switch ($string[$position]) + { + case '(': + $depth++; + break; + + case ')': + $depth--; + break; + } + $position++; + } + else + { + break; + } + } + } + else + { + $output .= '('; + } + } + $output .= substr($string, $position); + + return $output; + } + + /** + * Parse RFC2822's date format + * + * @access protected + * @return int Timestamp + */ + function date_rfc2822($date) + { + static $pcre; + if (!$pcre) + { + $wsp = '[\x09\x20]'; + $fws = '(?:' . $wsp . '+|' . $wsp . '*(?:\x0D\x0A' . $wsp . '+)+)'; + $optional_fws = $fws . '?'; + $day_name = $this->day_pcre; + $month = $this->month_pcre; + $day = '([0-9]{1,2})'; + $hour = $minute = $second = '([0-9]{2})'; + $year = '([0-9]{2,4})'; + $num_zone = '([+\-])([0-9]{2})([0-9]{2})'; + $character_zone = '([A-Z]{1,5})'; + $zone = '(?:' . $num_zone . '|' . $character_zone . ')'; + $pcre = '/(?:' . $optional_fws . $day_name . $optional_fws . ',)?' . $optional_fws . $day . $fws . $month . $fws . $year . $fws . $hour . $optional_fws . ':' . $optional_fws . $minute . '(?:' . $optional_fws . ':' . $optional_fws . $second . ')?' . $fws . $zone . '/i'; + } + if (preg_match($pcre, $this->remove_rfc2822_comments($date), $match)) + { + /* + Capturing subpatterns: + 1: Day name + 2: Day + 3: Month + 4: Year + 5: Hour + 6: Minute + 7: Second + 8: Timezone ± + 9: Timezone hours + 10: Timezone minutes + 11: Alphabetic timezone + */ + + // Find the month number + $month = $this->month[strtolower($match[3])]; + + // Numeric timezone + if ($match[8] !== '') + { + $timezone = $match[9] * 3600; + $timezone += $match[10] * 60; + if ($match[8] === '-') + { + $timezone = 0 - $timezone; + } + } + // Character timezone + elseif (isset($this->timezone[strtoupper($match[11])])) + { + $timezone = $this->timezone[strtoupper($match[11])]; + } + // Assume everything else to be -0000 + else + { + $timezone = 0; + } + + // Deal with 2/3 digit years + if ($match[4] < 50) + { + $match[4] += 2000; + } + elseif ($match[4] < 1000) + { + $match[4] += 1900; + } + + // Second is optional, if it is empty set it to zero + if ($match[7] !== '') + { + $second = $match[7]; + } + else + { + $second = 0; + } + + return gmmktime($match[5], $match[6], $second, $month, $match[2], $match[4]) - $timezone; + } + else + { + return false; + } + } + + /** + * Parse RFC850's date format + * + * @access protected + * @return int Timestamp + */ + function date_rfc850($date) + { + static $pcre; + if (!$pcre) + { + $space = '[\x09\x20]+'; + $day_name = $this->day_pcre; + $month = $this->month_pcre; + $day = '([0-9]{1,2})'; + $year = $hour = $minute = $second = '([0-9]{2})'; + $zone = '([A-Z]{1,5})'; + $pcre = '/^' . $day_name . ',' . $space . $day . '-' . $month . '-' . $year . $space . $hour . ':' . $minute . ':' . $second . $space . $zone . '$/i'; + } + if (preg_match($pcre, $date, $match)) + { + /* + Capturing subpatterns: + 1: Day name + 2: Day + 3: Month + 4: Year + 5: Hour + 6: Minute + 7: Second + 8: Timezone + */ + + // Month + $month = $this->month[strtolower($match[3])]; + + // Character timezone + if (isset($this->timezone[strtoupper($match[8])])) + { + $timezone = $this->timezone[strtoupper($match[8])]; + } + // Assume everything else to be -0000 + else + { + $timezone = 0; + } + + // Deal with 2 digit year + if ($match[4] < 50) + { + $match[4] += 2000; + } + else + { + $match[4] += 1900; + } + + return gmmktime($match[5], $match[6], $match[7], $month, $match[2], $match[4]) - $timezone; + } + else + { + return false; + } + } + + /** + * Parse C99's asctime()'s date format + * + * @access protected + * @return int Timestamp + */ + function date_asctime($date) + { + static $pcre; + if (!$pcre) + { + $space = '[\x09\x20]+'; + $wday_name = $this->day_pcre; + $mon_name = $this->month_pcre; + $day = '([0-9]{1,2})'; + $hour = $sec = $min = '([0-9]{2})'; + $year = '([0-9]{4})'; + $terminator = '\x0A?\x00?'; + $pcre = '/^' . $wday_name . $space . $mon_name . $space . $day . $space . $hour . ':' . $min . ':' . $sec . $space . $year . $terminator . '$/i'; + } + if (preg_match($pcre, $date, $match)) + { + /* + Capturing subpatterns: + 1: Day name + 2: Month + 3: Day + 4: Hour + 5: Minute + 6: Second + 7: Year + */ + + $month = $this->month[strtolower($match[2])]; + return gmmktime($match[4], $match[5], $match[6], $month, $match[3], $match[7]); + } + else + { + return false; + } + } + + /** + * Parse dates using strtotime() + * + * @access protected + * @return int Timestamp + */ + function date_strtotime($date) + { + $strtotime = strtotime($date); + if ($strtotime === -1 || $strtotime === false) + { + return false; + } + else + { + return $strtotime; + } + } +} + +/** + * Content-type sniffing + * + * @package SimplePie + */ +class SimplePie_Content_Type_Sniffer +{ + /** + * File object + * + * @var SimplePie_File + * @access private + */ + var $file; + + /** + * Create an instance of the class with the input file + * + * @access public + * @param SimplePie_Content_Type_Sniffer $file Input file + */ + function SimplePie_Content_Type_Sniffer($file) + { + $this->file = $file; + } + + /** + * Get the Content-Type of the specified file + * + * @access public + * @return string Actual Content-Type + */ + function get_type() + { + if (isset($this->file->headers['content-type'])) + { + if (!isset($this->file->headers['content-encoding']) + && ($this->file->headers['content-type'] === 'text/plain' + || $this->file->headers['content-type'] === 'text/plain; charset=ISO-8859-1' + || $this->file->headers['content-type'] === 'text/plain; charset=iso-8859-1')) + { + return $this->text_or_binary(); + } + + if (($pos = strpos($this->file->headers['content-type'], ';')) !== false) + { + $official = substr($this->file->headers['content-type'], 0, $pos); + } + else + { + $official = $this->file->headers['content-type']; + } + $official = strtolower($official); + + if ($official === 'unknown/unknown' + || $official === 'application/unknown') + { + return $this->unknown(); + } + elseif (substr($official, -4) === '+xml' + || $official === 'text/xml' + || $official === 'application/xml') + { + return $official; + } + elseif (substr($official, 0, 6) === 'image/') + { + if ($return = $this->image()) + { + return $return; + } + else + { + return $official; + } + } + elseif ($official === 'text/html') + { + return $this->feed_or_html(); + } + else + { + return $official; + } + } + else + { + return $this->unknown(); + } + } + + /** + * Sniff text or binary + * + * @access private + * @return string Actual Content-Type + */ + function text_or_binary() + { + if (substr($this->file->body, 0, 2) === "\xFE\xFF" + || substr($this->file->body, 0, 2) === "\xFF\xFE" + || substr($this->file->body, 0, 4) === "\x00\x00\xFE\xFF" + || substr($this->file->body, 0, 3) === "\xEF\xBB\xBF") + { + return 'text/plain'; + } + elseif (preg_match('/[\x00-\x08\x0E-\x1A\x1C-\x1F]/', $this->file->body)) + { + return 'application/octect-stream'; + } + else + { + return 'text/plain'; + } + } + + /** + * Sniff unknown + * + * @access private + * @return string Actual Content-Type + */ + function unknown() + { + $ws = strspn($this->file->body, "\x09\x0A\x0B\x0C\x0D\x20"); + if (strtolower(substr($this->file->body, $ws, 14)) === 'file->body, $ws, 5)) === 'file->body, $ws, 7)) === 'file->body, 0, 5) === '%PDF-') + { + return 'application/pdf'; + } + elseif (substr($this->file->body, 0, 11) === '%!PS-Adobe-') + { + return 'application/postscript'; + } + elseif (substr($this->file->body, 0, 6) === 'GIF87a' + || substr($this->file->body, 0, 6) === 'GIF89a') + { + return 'image/gif'; + } + elseif (substr($this->file->body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") + { + return 'image/png'; + } + elseif (substr($this->file->body, 0, 3) === "\xFF\xD8\xFF") + { + return 'image/jpeg'; + } + elseif (substr($this->file->body, 0, 2) === "\x42\x4D") + { + return 'image/bmp'; + } + else + { + return $this->text_or_binary(); + } + } + + /** + * Sniff images + * + * @access private + * @return string Actual Content-Type + */ + function image() + { + if (substr($this->file->body, 0, 6) === 'GIF87a' + || substr($this->file->body, 0, 6) === 'GIF89a') + { + return 'image/gif'; + } + elseif (substr($this->file->body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") + { + return 'image/png'; + } + elseif (substr($this->file->body, 0, 3) === "\xFF\xD8\xFF") + { + return 'image/jpeg'; + } + elseif (substr($this->file->body, 0, 2) === "\x42\x4D") + { + return 'image/bmp'; + } + else + { + return false; + } + } + + /** + * Sniff HTML + * + * @access private + * @return string Actual Content-Type + */ + function feed_or_html() + { + $len = strlen($this->file->body); + $pos = strspn($this->file->body, "\x09\x0A\x0D\x20"); + + while ($pos < $len) + { + switch ($this->file->body[$pos]) + { + case "\x09": + case "\x0A": + case "\x0D": + case "\x20": + $pos += strspn($this->file->body, "\x09\x0A\x0D\x20", $pos); + continue 2; + + case '<': + $pos++; + break; + + default: + return 'text/html'; + } + + if (substr($this->file->body, $pos, 3) === '!--') + { + $pos += 3; + if ($pos < $len && ($pos = strpos($this->file->body, '-->', $pos)) !== false) + { + $pos += 3; + } + else + { + return 'text/html'; + } + } + elseif (substr($this->file->body, $pos, 1) === '!') + { + if ($pos < $len && ($pos = strpos($this->file->body, '>', $pos)) !== false) + { + $pos++; + } + else + { + return 'text/html'; + } + } + elseif (substr($this->file->body, $pos, 1) === '?') + { + if ($pos < $len && ($pos = strpos($this->file->body, '?>', $pos)) !== false) + { + $pos += 2; + } + else + { + return 'text/html'; + } + } + elseif (substr($this->file->body, $pos, 3) === 'rss' + || substr($this->file->body, $pos, 7) === 'rdf:RDF') + { + return 'application/rss+xml'; + } + elseif (substr($this->file->body, $pos, 4) === 'feed') + { + return 'application/atom+xml'; + } + else + { + return 'text/html'; + } + } + + return 'text/html'; + } +} + +/** + * Parses the XML Declaration + * + * @package SimplePie + */ +class SimplePie_XML_Declaration_Parser +{ + /** + * XML Version + * + * @access public + * @var string + */ + var $version = '1.0'; + + /** + * Encoding + * + * @access public + * @var string + */ + var $encoding = 'UTF-8'; + + /** + * Standalone + * + * @access public + * @var bool + */ + var $standalone = false; + + /** + * Current state of the state machine + * + * @access private + * @var string + */ + var $state = 'before_version_name'; + + /** + * Input data + * + * @access private + * @var string + */ + var $data = ''; + + /** + * Input data length (to avoid calling strlen() everytime this is needed) + * + * @access private + * @var int + */ + var $data_length = 0; + + /** + * Current position of the pointer + * + * @var int + * @access private + */ + var $position = 0; + + /** + * Create an instance of the class with the input data + * + * @access public + * @param string $data Input data + */ + function SimplePie_XML_Declaration_Parser($data) + { + $this->data = $data; + $this->data_length = strlen($this->data); + } + + /** + * Parse the input data + * + * @access public + * @return bool true on success, false on failure + */ + function parse() + { + while ($this->state && $this->state !== 'emit' && $this->has_data()) + { + $state = $this->state; + $this->$state(); + } + $this->data = ''; + if ($this->state === 'emit') + { + return true; + } + else + { + $this->version = ''; + $this->encoding = ''; + $this->standalone = ''; + return false; + } + } + + /** + * Check whether there is data beyond the pointer + * + * @access private + * @return bool true if there is further data, false if not + */ + function has_data() + { + return (bool) ($this->position < $this->data_length); + } + + /** + * Advance past any whitespace + * + * @return int Number of whitespace characters passed + */ + function skip_whitespace() + { + $whitespace = strspn($this->data, "\x09\x0A\x0D\x20", $this->position); + $this->position += $whitespace; + return $whitespace; + } + + /** + * Read value + */ + function get_value() + { + $quote = substr($this->data, $this->position, 1); + if ($quote === '"' || $quote === "'") + { + $this->position++; + $len = strcspn($this->data, $quote, $this->position); + if ($this->has_data()) + { + $value = substr($this->data, $this->position, $len); + $this->position += $len + 1; + return $value; + } + } + return false; + } + + function before_version_name() + { + if ($this->skip_whitespace()) + { + $this->state = 'version_name'; + } + else + { + $this->state = false; + } + } + + function version_name() + { + if (substr($this->data, $this->position, 7) === 'version') + { + $this->position += 7; + $this->skip_whitespace(); + $this->state = 'version_equals'; + } + else + { + $this->state = false; + } + } + + function version_equals() + { + if (substr($this->data, $this->position, 1) === '=') + { + $this->position++; + $this->skip_whitespace(); + $this->state = 'version_value'; + } + else + { + $this->state = false; + } + } + + function version_value() + { + if ($this->version = $this->get_value()) + { + $this->skip_whitespace(); + if ($this->has_data()) + { + $this->state = 'encoding_name'; + } + else + { + $this->state = 'emit'; + } + } + else + { + $this->state = 'standalone_name'; + } + } + + function encoding_name() + { + if (substr($this->data, $this->position, 8) === 'encoding') + { + $this->position += 8; + $this->skip_whitespace(); + $this->state = 'encoding_equals'; + } + else + { + $this->state = false; + } + } + + function encoding_equals() + { + if (substr($this->data, $this->position, 1) === '=') + { + $this->position++; + $this->skip_whitespace(); + $this->state = 'encoding_value'; + } + else + { + $this->state = false; + } + } + + function encoding_value() + { + if ($this->encoding = $this->get_value()) + { + $this->skip_whitespace(); + if ($this->has_data()) + { + $this->state = 'standalone_name'; + } + else + { + $this->state = 'emit'; + } + } + else + { + $this->state = false; + } + } + + function standalone_name() + { + if (substr($this->data, $this->position, 10) === 'standalone') + { + $this->position += 10; + $this->skip_whitespace(); + $this->state = 'standalone_equals'; + } + else + { + $this->state = false; + } + } + + function standalone_equals() + { + if (substr($this->data, $this->position, 1) === '=') + { + $this->position++; + $this->skip_whitespace(); + $this->state = 'standalone_value'; + } + else + { + $this->state = false; + } + } + + function standalone_value() + { + if ($standalone = $this->get_value()) + { + switch ($standalone) + { + case 'yes': + $this->standalone = true; + break; + + case 'no': + $this->standalone = false; + break; + + default: + $this->state = false; + return; + } + + $this->skip_whitespace(); + if ($this->has_data()) + { + $this->state = false; + } + else + { + $this->state = 'emit'; + } + } + else + { + $this->state = false; + } + } +} + +class SimplePie_Locator +{ + var $useragent; + var $timeout; + var $file; + var $local = array(); + var $elsewhere = array(); + var $file_class = 'SimplePie_File'; + var $cached_entities = array(); + var $http_base; + var $base; + var $base_location = 0; + var $checked_feeds = 0; + var $max_checked_feeds = 10; + var $content_type_sniffer_class = 'SimplePie_Content_Type_Sniffer'; + + function SimplePie_Locator(&$file, $timeout = 10, $useragent = null, $file_class = 'SimplePie_File', $max_checked_feeds = 10, $content_type_sniffer_class = 'SimplePie_Content_Type_Sniffer') + { + $this->file =& $file; + $this->file_class = $file_class; + $this->useragent = $useragent; + $this->timeout = $timeout; + $this->max_checked_feeds = $max_checked_feeds; + $this->content_type_sniffer_class = $content_type_sniffer_class; + } + + function find($type = SIMPLEPIE_LOCATOR_ALL) + { + if ($this->is_feed($this->file)) + { + return $this->file; + } + + if ($this->file->method & SIMPLEPIE_FILE_SOURCE_REMOTE) + { + $sniffer =& new $this->content_type_sniffer_class($this->file); + if ($sniffer->get_type() !== 'text/html') + { + return null; + } + } + + if ($type & ~SIMPLEPIE_LOCATOR_NONE) + { + $this->get_base(); + } + + if ($type & SIMPLEPIE_LOCATOR_AUTODISCOVERY && $working = $this->autodiscovery()) + { + return $working; + } + + if ($type & (SIMPLEPIE_LOCATOR_LOCAL_EXTENSION | SIMPLEPIE_LOCATOR_LOCAL_BODY | SIMPLEPIE_LOCATOR_REMOTE_EXTENSION | SIMPLEPIE_LOCATOR_REMOTE_BODY) && $this->get_links()) + { + if ($type & SIMPLEPIE_LOCATOR_LOCAL_EXTENSION && $working = $this->extension($this->local)) + { + return $working; + } + + if ($type & SIMPLEPIE_LOCATOR_LOCAL_BODY && $working = $this->body($this->local)) + { + return $working; + } + + if ($type & SIMPLEPIE_LOCATOR_REMOTE_EXTENSION && $working = $this->extension($this->elsewhere)) + { + return $working; + } + + if ($type & SIMPLEPIE_LOCATOR_REMOTE_BODY && $working = $this->body($this->elsewhere)) + { + return $working; + } + } + return null; + } + + function is_feed(&$file) + { + if ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE) + { + $sniffer =& new $this->content_type_sniffer_class($file); + $sniffed = $sniffer->get_type(); + if (in_array($sniffed, array('application/rss+xml', 'application/rdf+xml', 'text/rdf', 'application/atom+xml', 'text/xml', 'application/xml'))) + { + return true; + } + else + { + return false; + } + } + elseif ($file->method & SIMPLEPIE_FILE_SOURCE_LOCAL) + { + return true; + } + else + { + return false; + } + } + + function get_base() + { + $this->http_base = $this->file->url; + $this->base = $this->http_base; + $elements = SimplePie_Misc::get_element('base', $this->file->body); + foreach ($elements as $element) + { + if ($element['attribs']['href']['data'] !== '') + { + $this->base = SimplePie_Misc::absolutize_url(trim($element['attribs']['href']['data']), $this->http_base); + $this->base_location = $element['offset']; + break; + } + } + } + + function autodiscovery() + { + $links = array_merge(SimplePie_Misc::get_element('link', $this->file->body), SimplePie_Misc::get_element('a', $this->file->body), SimplePie_Misc::get_element('area', $this->file->body)); + $done = array(); + foreach ($links as $link) + { + if ($this->checked_feeds == $this->max_checked_feeds) + { + break; + } + if (isset($link['attribs']['href']['data']) && isset($link['attribs']['rel']['data'])) + { + $rel = array_unique(SimplePie_Misc::space_seperated_tokens(strtolower($link['attribs']['rel']['data']))); + + if ($this->base_location < $link['offset']) + { + $href = SimplePie_Misc::absolutize_url(trim($link['attribs']['href']['data']), $this->base); + } + else + { + $href = SimplePie_Misc::absolutize_url(trim($link['attribs']['href']['data']), $this->http_base); + } + + if (!in_array($href, $done) && in_array('feed', $rel) || (in_array('alternate', $rel) && !empty($link['attribs']['type']['data']) && in_array(strtolower(SimplePie_Misc::parse_mime($link['attribs']['type']['data'])), array('application/rss+xml', 'application/atom+xml')))) + { + $this->checked_feeds++; + $feed =& new $this->file_class($href, $this->timeout, 5, null, $this->useragent); + if ($this->is_feed($feed)) + { + return $feed; + } + } + $done[] = $href; + } + } + return null; + } + + function get_links() + { + $links = SimplePie_Misc::get_element('a', $this->file->body); + foreach ($links as $link) + { + if (isset($link['attribs']['href']['data'])) + { + $href = trim($link['attribs']['href']['data']); + $parsed = SimplePie_Misc::parse_url($href); + if ($parsed['scheme'] === '' || preg_match('/^(http(s)|feed)?$/i', $parsed['scheme'])) + { + if ($this->base_location < $link['offset']) + { + $href = SimplePie_Misc::absolutize_url(trim($link['attribs']['href']['data']), $this->base); + } + else + { + $href = SimplePie_Misc::absolutize_url(trim($link['attribs']['href']['data']), $this->http_base); + } + + $current = SimplePie_Misc::parse_url($this->file->url); + + if ($parsed['authority'] === '' || $parsed['authority'] == $current['authority']) + { + $this->local[] = $href; + } + else + { + $this->elsewhere[] = $href; + } + } + } + } + $this->local = array_unique($this->local); + $this->elsewhere = array_unique($this->elsewhere); + if (!empty($this->local) || !empty($this->elsewhere)) + { + return true; + } + return null; + } + + function extension(&$array) + { + foreach ($array as $key => $value) + { + if ($this->checked_feeds == $this->max_checked_feeds) + { + break; + } + if (in_array(strtolower(strrchr($value, '.')), array('.rss', '.rdf', '.atom', '.xml'))) + { + $this->checked_feeds++; + $feed =& new $this->file_class($value, $this->timeout, 5, null, $this->useragent); + if ($this->is_feed($feed)) + { + return $feed; + } + else + { + unset($array[$key]); + } + } + } + return null; + } + + function body(&$array) + { + foreach ($array as $key => $value) + { + if ($this->checked_feeds == $this->max_checked_feeds) + { + break; + } + if (preg_match('/(rss|rdf|atom|xml)/i', $value)) + { + $this->checked_feeds++; + $feed =& new $this->file_class($value, $this->timeout, 5, null, $this->useragent); + if ($this->is_feed($feed)) + { + return $feed; + } + else + { + unset($array[$key]); + } + } + } + return null; + } +} + +class SimplePie_Parser +{ + var $error_code; + var $error_string; + var $current_line; + var $current_column; + var $current_byte; + var $separator = ' '; + var $feed = false; + var $namespace = array(''); + var $element = array(''); + var $xml_base = array(''); + var $xml_base_explicit = array(false); + var $xml_lang = array(''); + var $data = array(); + var $datas = array(array()); + var $current_xhtml_construct = -1; + var $encoding; + + function parse(&$data, $encoding) + { + // Use UTF-8 if we get passed US-ASCII, as every US-ASCII character is a UTF-8 character + if (strtoupper($encoding) == 'US-ASCII') + { + $this->encoding = 'UTF-8'; + } + else + { + $this->encoding = $encoding; + } + + // Strip BOM: + // UTF-32 Big Endian BOM + if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") + { + $data = substr($data, 4); + } + // UTF-32 Little Endian BOM + elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") + { + $data = substr($data, 4); + } + // UTF-16 Big Endian BOM + elseif (substr($data, 0, 2) === "\xFE\xFF") + { + $data = substr($data, 2); + } + // UTF-16 Little Endian BOM + elseif (substr($data, 0, 2) === "\xFF\xFE") + { + $data = substr($data, 2); + } + // UTF-8 BOM + elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") + { + $data = substr($data, 3); + } + + if (substr($data, 0, 5) === '')) !== false) + { + $declaration =& new SimplePie_XML_Declaration_Parser(substr($data, 5, $pos - 5)); + if ($declaration->parse()) + { + $data = substr($data, $pos + 2); + $data = 'version . '" encoding="' . $encoding . '" standalone="' . (($declaration->standalone) ? 'yes' : 'no') . '"?>' . $data; + } + else + { + $this->error_string = 'SimplePie bug! Please report this!'; + return false; + } + } + + // Work around libxml bug + $data = str_replace('<', '<', $data); + $data = str_replace('>', '>', $data); + $data = str_replace('&', '&', $data); + $data = str_replace(''', ''', $data); + $data = str_replace('"', '"', $data); + + $return = true; + + // Create the parser + $xml = xml_parser_create_ns($this->encoding, $this->separator); + xml_parser_set_option($xml, XML_OPTION_SKIP_WHITE, 1); + xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, 0); + xml_set_object($xml, $this); + xml_set_character_data_handler($xml, 'cdata'); + xml_set_element_handler($xml, 'tag_open', 'tag_close'); + + // Parse! + if (!xml_parse($xml, $data, true)) + { + $this->error_code = xml_get_error_code($xml); + $this->error_string = xml_error_string($this->error_code); + $return = false; + } + $this->current_line = xml_get_current_line_number($xml); + $this->current_column = xml_get_current_column_number($xml); + $this->current_byte = xml_get_current_byte_index($xml); + xml_parser_free($xml); + return $return; + } + + function get_error_code() + { + return $this->error_code; + } + + function get_error_string() + { + return $this->error_string; + } + + function get_current_line() + { + return $this->current_line; + } + + function get_current_column() + { + return $this->current_column; + } + + function get_current_byte() + { + return $this->current_byte; + } + + function get_data() + { + return $this->data; + } + + function tag_open($parser, $tag, $attributes) + { + if ($this->feed === 0) + { + return; + } + elseif ($this->feed == false) + { + if (in_array($tag, array( + SIMPLEPIE_NAMESPACE_ATOM_10 . $this->separator . 'feed', + SIMPLEPIE_NAMESPACE_ATOM_03 . $this->separator . 'feed', + 'rss', + SIMPLEPIE_NAMESPACE_RDF . $this->separator . 'RDF' + ))) + { + $this->feed = 1; + } + } + else + { + $this->feed++; + } + + list($this->namespace[], $this->element[]) = $this->split_ns($tag); + + $attribs = array(); + foreach ($attributes as $name => $value) + { + list($attrib_namespace, $attribute) = $this->split_ns($name); + $attribs[$attrib_namespace][$attribute] = $value; + } + + if (isset($attribs[SIMPLEPIE_NAMESPACE_XML]['base'])) + { + $this->xml_base[] = SimplePie_Misc::absolutize_url($attribs[SIMPLEPIE_NAMESPACE_XML]['base'], end($this->xml_base)); + $this->xml_base_explicit[] = true; + } + else + { + $this->xml_base[] = end($this->xml_base); + $this->xml_base_explicit[] = end($this->xml_base_explicit); + } + + if (isset($attribs[SIMPLEPIE_NAMESPACE_XML]['lang'])) + { + $this->xml_lang[] = $attribs[SIMPLEPIE_NAMESPACE_XML]['lang']; + } + else + { + $this->xml_lang[] = end($this->xml_lang); + } + + if ($this->current_xhtml_construct >= 0) + { + $this->current_xhtml_construct++; + if (end($this->namespace) == SIMPLEPIE_NAMESPACE_XHTML) + { + $this->data['data'] .= '<' . end($this->element); + if (isset($attribs[''])) + { + foreach ($attribs[''] as $name => $value) + { + $this->data['data'] .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT, $this->encoding) . '"'; + } + } + $this->data['data'] .= '>'; + } + } + else + { + $this->datas[] =& $this->data; + $this->data =& $this->data['child'][end($this->namespace)][end($this->element)][]; + $this->data = array('data' => '', 'attribs' => $attribs, 'xml_base' => end($this->xml_base), 'xml_base_explicit' => end($this->xml_base_explicit), 'xml_lang' => end($this->xml_lang)); + if ((end($this->namespace) == SIMPLEPIE_NAMESPACE_ATOM_03 && in_array(end($this->element), array('title', 'tagline', 'copyright', 'info', 'summary', 'content')) && isset($attribs['']['mode']) && $attribs['']['mode'] == 'xml') + || (end($this->namespace) == SIMPLEPIE_NAMESPACE_ATOM_10 && in_array(end($this->element), array('rights', 'subtitle', 'summary', 'info', 'title', 'content')) && isset($attribs['']['type']) && $attribs['']['type'] == 'xhtml')) + { + $this->current_xhtml_construct = 0; + } + } + } + + function cdata($parser, $cdata) + { + if ($this->current_xhtml_construct >= 0) + { + $this->data['data'] .= htmlspecialchars($cdata, ENT_QUOTES, $this->encoding); + } + elseif ($this->feed > 1) + { + $this->data['data'] .= $cdata; + } + } + + function tag_close($parser, $tag) + { + if (!$this->feed) + { + return; + } + + if ($this->current_xhtml_construct >= 0) + { + $this->current_xhtml_construct--; + if (end($this->namespace) == SIMPLEPIE_NAMESPACE_XHTML && !in_array(end($this->element), array('area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param'))) + { + $this->data['data'] .= 'element) . '>'; + } + } + if ($this->current_xhtml_construct == -1) + { + $this->data =& $this->datas[$this->feed]; + array_pop($this->datas); + } + + array_pop($this->element); + array_pop($this->namespace); + array_pop($this->xml_base); + array_pop($this->xml_base_explicit); + array_pop($this->xml_lang); + $this->feed--; + } + + function split_ns($string) + { + static $cache = array(); + if (!isset($cache[$string])) + { + if ($pos = strpos($string, $this->separator)) + { + static $separator_length; + if (!$separator_length) + { + $separator_length = strlen($this->separator); + } + $namespace = substr($string, 0, $pos); + $local_name = substr($string, $pos + $separator_length); + if (strtolower($namespace) === SIMPLEPIE_NAMESPACE_ITUNES) + { + $namespace = SIMPLEPIE_NAMESPACE_ITUNES; + } + + // Normalize the Media RSS namespaces + if ($namespace === SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG) + { + $namespace = SIMPLEPIE_NAMESPACE_MEDIARSS; + } + $cache[$string] = array($namespace, $local_name); + } + else + { + $cache[$string] = array('', $string); + } + } + return $cache[$string]; + } +} + +/** + * @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags + */ +class SimplePie_Sanitize +{ + // Private vars + var $base; + + // Options + var $remove_div = true; + var $image_handler = ''; + var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'); + var $encode_instead_of_strip = false; + var $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'); + var $strip_comments = false; + var $output_encoding = 'UTF-8'; + var $enable_cache = true; + var $cache_location = './cache'; + var $cache_name_function = 'md5'; + var $cache_class = 'SimplePie_Cache'; + var $file_class = 'SimplePie_File'; + var $timeout = 10; + var $useragent = ''; + var $force_fsockopen = false; + + var $replace_url_attributes = array( + 'a' => 'href', + 'area' => 'href', + 'blockquote' => 'cite', + 'del' => 'cite', + 'form' => 'action', + 'img' => array('longdesc', 'src'), + 'input' => 'src', + 'ins' => 'cite', + 'q' => 'cite' + ); + + function remove_div($enable = true) + { + $this->remove_div = (bool) $enable; + } + + function set_image_handler($page = false) + { + if ($page) + { + $this->image_handler = (string) $page; + } + else + { + $this->image_handler = false; + } + } + + function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie_Cache') + { + if (isset($enable_cache)) + { + $this->enable_cache = (bool) $enable_cache; + } + + if ($cache_location) + { + $this->cache_location = (string) $cache_location; + } + + if ($cache_name_function) + { + $this->cache_name_function = (string) $cache_name_function; + } + + if ($cache_class) + { + $this->cache_class = (string) $cache_class; + } + } + + function pass_file_data($file_class = 'SimplePie_File', $timeout = 10, $useragent = '', $force_fsockopen = false) + { + if ($file_class) + { + $this->file_class = (string) $file_class; + } + + if ($timeout) + { + $this->timeout = (string) $timeout; + } + + if ($useragent) + { + $this->useragent = (string) $useragent; + } + + if ($force_fsockopen) + { + $this->force_fsockopen = (string) $force_fsockopen; + } + } + + function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style')) + { + if ($tags) + { + if (is_array($tags)) + { + $this->strip_htmltags = $tags; + } + else + { + $this->strip_htmltags = explode(',', $tags); + } + } + else + { + $this->strip_htmltags = false; + } + } + + function encode_instead_of_strip($encode = false) + { + $this->encode_instead_of_strip = (bool) $encode; + } + + function strip_attributes($attribs = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc')) + { + if ($attribs) + { + if (is_array($attribs)) + { + $this->strip_attributes = $attribs; + } + else + { + $this->strip_attributes = explode(',', $attribs); + } + } + else + { + $this->strip_attributes = false; + } + } + + function strip_comments($strip = false) + { + $this->strip_comments = (bool) $strip; + } + + function set_output_encoding($encoding = 'UTF-8') + { + $this->output_encoding = (string) $encoding; + } + + /** + * Set element/attribute key/value pairs of HTML attributes + * containing URLs that need to be resolved relative to the feed + * + * @access public + * @since 1.0 + * @param array $element_attribute Element/attribute key/value pairs + */ + function set_url_replacements($element_attribute = array('a' => 'href', 'area' => 'href', 'blockquote' => 'cite', 'del' => 'cite', 'form' => 'action', 'img' => array('longdesc', 'src'), 'input' => 'src', 'ins' => 'cite', 'q' => 'cite')) + { + $this->replace_url_attributes = (array) $element_attribute; + } + + function sanitize($data, $type, $base = '') + { + $data = trim($data); + if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI) + { + if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML) + { + if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data)) + { + $type |= SIMPLEPIE_CONSTRUCT_HTML; + } + else + { + $type |= SIMPLEPIE_CONSTRUCT_TEXT; + } + } + + if ($type & SIMPLEPIE_CONSTRUCT_BASE64) + { + $data = base64_decode($data); + } + + if ($type & SIMPLEPIE_CONSTRUCT_XHTML) + { + if ($this->remove_div) + { + $data = preg_replace('/^/', '', $data); + $data = preg_replace('/<\/div>$/', '', $data); + } + else + { + $data = preg_replace('/^/', '
    ', $data); + } + } + + if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML)) + { + // Strip comments + if ($this->strip_comments) + { + $data = SimplePie_Misc::strip_comments($data); + } + + // Strip out HTML tags and attributes that might cause various security problems. + // Based on recommendations by Mark Pilgrim at: + // http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely + if ($this->strip_htmltags) + { + foreach ($this->strip_htmltags as $tag) + { + $pcre = "/<($tag)" . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . "(>(.*)<\/$tag" . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>|(\/)?>)/siU'; + while (preg_match($pcre, $data)) + { + $data = preg_replace_callback($pcre, array(&$this, 'do_strip_htmltags'), $data); + } + } + } + + if ($this->strip_attributes) + { + foreach ($this->strip_attributes as $attrib) + { + $data = preg_replace('/(<[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*)' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . trim($attrib) . '(?:\s*=\s*(?:"(?:[^"]*)"|\'(?:[^\']*)\'|(?:[^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>/', '\1\2\3>', $data); + } + } + + // Replace relative URLs + $this->base = $base; + foreach ($this->replace_url_attributes as $element => $attributes) + { + $data = $this->replace_urls($data, $element, $attributes); + } + + // If image handling (caching, etc.) is enabled, cache and rewrite all the image tags. + if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache) + { + $images = SimplePie_Misc::get_element('img', $data); + foreach ($images as $img) + { + if (isset($img['attribs']['src']['data'])) + { + $image_url = call_user_func($this->cache_name_function, $img['attribs']['src']['data']); + $cache = call_user_func(array($this->cache_class, 'create'), $this->cache_location, $image_url, 'spi'); + + if ($cache->load()) + { + $img['attribs']['src']['data'] = $this->image_handler . $image_url; + $data = str_replace($img['full'], SimplePie_Misc::element_implode($img), $data); + } + else + { + $file =& new $this->file_class($img['attribs']['src']['data'], $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen); + $headers = $file->headers; + + if ($file->success && ($file->status_code == 200 || ($file->status_code > 206 && $file->status_code < 300))) + { + if ($cache->save(array('headers' => $file->headers, 'body' => $file->body))) + { + $img['attribs']['src']['data'] = $this->image_handler . $image_url; + $data = str_replace($img['full'], SimplePie_Misc::element_implode($img), $data); + } + else + { + trigger_error("$cache->name is not writeable", E_USER_WARNING); + } + } + } + } + } + } + + // Having (possibly) taken stuff out, there may now be whitespace at the beginning/end of the data + $data = trim($data); + } + + if ($type & SIMPLEPIE_CONSTRUCT_IRI) + { + $data = SimplePie_Misc::absolutize_url($data, $base); + } + + if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI)) + { + $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8'); + } + + if ($this->output_encoding != 'UTF-8') + { + $data = SimplePie_Misc::change_encoding($data, 'UTF-8', $this->output_encoding); + } + } + return $data; + } + + function replace_urls($data, $tag, $attributes) + { + if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags)) + { + $elements = SimplePie_Misc::get_element($tag, $data); + foreach ($elements as $element) + { + if (is_array($attributes)) + { + foreach ($attributes as $attribute) + { + if (isset($element['attribs'][$attribute]['data'])) + { + $element['attribs'][$attribute]['data'] = SimplePie_Misc::absolutize_url($element['attribs'][$attribute]['data'], $this->base); + $new_element = SimplePie_Misc::element_implode($element); + $data = str_replace($element['full'], $new_element, $data); + $element['full'] = $new_element; + } + } + } + elseif (isset($element['attribs'][$attributes]['data'])) + { + $element['attribs'][$attributes]['data'] = SimplePie_Misc::absolutize_url($element['attribs'][$attributes]['data'], $this->base); + $data = str_replace($element['full'], SimplePie_Misc::element_implode($element), $data); + } + } + } + return $data; + } + + function do_strip_htmltags($match) + { + if ($this->encode_instead_of_strip) + { + if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style'))) + { + $match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8'); + $match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8'); + return "<$match[1]$match[2]>$match[3]</$match[1]>"; + } + else + { + return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8'); + } + } + elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style'))) + { + return $match[4]; + } + else + { + return ''; + } + } +} + +?> diff --git a/wp-includes/class-smtp.php b/wp-includes/class-smtp.php new file mode 100644 index 0000000..250153c --- /dev/null +++ b/wp-includes/class-smtp.php @@ -0,0 +1,1062 @@ +smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } + + /************************************************************* + * CONNECTION FUNCTIONS * + ***********************************************************/ + + /** + * Connect to the server specified on the port specified. + * If the port is not specified use the default SMTP_PORT. + * If tval is specified then a connection will try and be + * established with the server for that number of seconds. + * If tval is not specified the default is 30 seconds to + * try on the connection. + * + * SMTP CODE SUCCESS: 220 + * SMTP CODE FAILURE: 421 + * @access public + * @return bool + */ + function Connect($host,$port=0,$tval=30) { + # set the error val to null so there is no confusion + $this->error = null; + + # make sure we are __not__ connected + if($this->connected()) { + # ok we are connected! what should we do? + # for now we will just give an error saying we + # are already connected + $this->error = array("error" => "Already connected to a server"); + return false; + } + + if(empty($port)) { + $port = $this->SMTP_PORT; + } + + #connect to the smtp server + $this->smtp_conn = fsockopen($host, # the host of the server + $port, # the port to use + $errno, # error number if any + $errstr, # error message if any + $tval); # give up after ? secs + # verify we connected properly + if(empty($this->smtp_conn)) { + $this->error = array("error" => "Failed to connect to server", + "errno" => $errno, + "errstr" => $errstr); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": $errstr ($errno)" . $this->CRLF; + } + return false; + } + + # sometimes the SMTP server takes a little longer to respond + # so we will give it a longer timeout for the first read + // Windows still does not have support for this timeout function + if(substr(PHP_OS, 0, 3) != "WIN") + socket_set_timeout($this->smtp_conn, $tval, 0); + + # get any announcement stuff + $announce = $this->get_lines(); + + # set the timeout of any socket functions at 1/10 of a second + //if(function_exists("socket_set_timeout")) + // socket_set_timeout($this->smtp_conn, 0, 100000); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $announce; + } + + return true; + } + + /** + * Performs SMTP authentication. Must be run after running the + * Hello() method. Returns true if successfully authenticated. + * @access public + * @return bool + */ + function Authenticate($username, $password) { + // Start authentication + fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "AUTH not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + // Send encoded username + fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 334) { + $this->error = + array("error" => "Username not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + // Send encoded password + fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($code != 235) { + $this->error = + array("error" => "Password not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + return true; + } + + /** + * Returns true if connected to a server otherwise false + * @access private + * @return bool + */ + function Connected() { + if(!empty($this->smtp_conn)) { + $sock_status = socket_get_status($this->smtp_conn); + if($sock_status["eof"]) { + # hmm this is an odd situation... the socket is + # valid but we are not connected anymore + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE:" . $this->CRLF . + "EOF caught while checking if connected"; + } + $this->Close(); + return false; + } + return true; # everything looks good + } + return false; + } + + /** + * Closes the socket and cleans up the state of the class. + * It is not considered good to use this function without + * first trying to use QUIT. + * @access public + * @return void + */ + function Close() { + $this->error = null; # so there is no confusion + $this->helo_rply = null; + if(!empty($this->smtp_conn)) { + # close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } + } + + /*************************************************************** + * SMTP COMMANDS * + *************************************************************/ + + /** + * Issues a data command and sends the msg_data to the server + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being seperated by and additional . + * + * Implements rfc 821: DATA + * + * SMTP CODE INTERMEDIATE: 354 + * [data] + * . + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 552,554,451,452 + * SMTP CODE FAILURE: 451,554 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + function Data($msg_data) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Data() without being connected"); + return false; + } + + fputs($this->smtp_conn,"DATA" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 354) { + $this->error = + array("error" => "DATA command not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + # the server is ready to accept data! + # according to rfc 821 we should not send more than 1000 + # including the CRLF + # characters on a single line so we will break the data up + # into lines by \r and/or \n then if needed we will break + # each of those into smaller lines to fit within the limit. + # in addition we will be looking for lines that start with + # a period '.' and append and additional period '.' to that + # line. NOTE: this does not count towards are limit. + + # normalize the line breaks so we know the explode works + $msg_data = str_replace("\r\n","\n",$msg_data); + $msg_data = str_replace("\r","\n",$msg_data); + $lines = explode("\n",$msg_data); + + # we need to find a good way to determine is headers are + # in the msg_data or if it is a straight msg body + # currently I am assuming rfc 822 definitions of msg headers + # and if the first field of the first line (':' sperated) + # does not contain a space then it _should_ be a header + # and we can process all lines before a blank "" line as + # headers. + $field = substr($lines[0],0,strpos($lines[0],":")); + $in_headers = false; + if(!empty($field) && !strstr($field," ")) { + $in_headers = true; + } + + $max_line_length = 998; # used below; set here for ease in change + + while(list(,$line) = @each($lines)) { + $lines_out = null; + if($line == "" && $in_headers) { + $in_headers = false; + } + # ok we need to break this line up into several + # smaller lines + while(strlen($line) > $max_line_length) { + $pos = strrpos(substr($line,0,$max_line_length)," "); + + # Patch to fix DOS attack + if(!$pos) { + $pos = $max_line_length - 1; + } + + $lines_out[] = substr($line,0,$pos); + $line = substr($line,$pos + 1); + # if we are processing headers we need to + # add a LWSP-char to the front of the new line + # rfc 822 on long msg headers + if($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + # now send the lines to the server + while(list(,$line_out) = @each($lines_out)) { + if(strlen($line_out) > 0) + { + if(substr($line_out, 0, 1) == ".") { + $line_out = "." . $line_out; + } + } + fputs($this->smtp_conn,$line_out . $this->CRLF); + } + } + + # ok all the message data has been sent so lets get this + # over with aleady + fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "DATA not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Expand takes the name and asks the server to list all the + * people who are members of the _list_. Expand will return + * back and array of the result or false if an error occurs. + * Each value in the array returned has the format of: + * [ ] + * The definition of is defined in rfc 821 + * + * Implements rfc 821: EXPN + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 550 + * SMTP CODE ERROR : 500,501,502,504,421 + * @access public + * @return string array + */ + function Expand($name) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Expand() without being connected"); + return false; + } + + fputs($this->smtp_conn,"EXPN " . $name . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "EXPN not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + # parse the reply and place in our array to return to user + $entries = explode($this->CRLF,$rply); + while(list(,$l) = @each($entries)) { + $list[] = substr($l,4); + } + + return $list; + } + + /** + * Sends the HELO command to the smtp server. + * This makes sure that we and the server are in + * the same known state. + * + * Implements from rfc 821: HELO + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 501, 504, 421 + * @access public + * @return bool + */ + function Hello($host="") { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Hello() without being connected"); + return false; + } + + # if a hostname for the HELO was not specified determine + # a suitable one to send + if(empty($host)) { + # we need to determine some sort of appopiate default + # to send to the server + $host = "localhost"; + } + + // Send extended hello first (RFC 2821) + if(!$this->SendHello("EHLO", $host)) + { + if(!$this->SendHello("HELO", $host)) + return false; + } + + return true; + } + + /** + * Sends a HELO/EHLO command. + * @access private + * @return bool + */ + function SendHello($hello, $host) { + fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER: " . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => $hello . " not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + $this->helo_rply = $rply; + + return true; + } + + /** + * Gets help information on the keyword specified. If the keyword + * is not specified then returns generic help, ussually contianing + * A list of keywords that help is available on. This function + * returns the results back to the user. It is up to the user to + * handle the returned data. If an error occurs then false is + * returned with $this->error set appropiately. + * + * Implements rfc 821: HELP [ ] + * + * SMTP CODE SUCCESS: 211,214 + * SMTP CODE ERROR : 500,501,502,504,421 + * @access public + * @return string + */ + function Help($keyword="") { + $this->error = null; # to avoid confusion + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Help() without being connected"); + return false; + } + + $extra = ""; + if(!empty($keyword)) { + $extra = " " . $keyword; + } + + fputs($this->smtp_conn,"HELP" . $extra . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 211 && $code != 214) { + $this->error = + array("error" => "HELP not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + return $rply; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. + * + * Implements rfc 821: MAIL FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,421 + * @access public + * @return bool + */ + function Mail($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Mail() without being connected"); + return false; + } + + $useVerp = ($this->do_verp ? "XVERP" : ""); + fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "MAIL not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Sends the command NOOP to the SMTP server. + * + * Implements from rfc 821: NOOP + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 421 + * @access public + * @return bool + */ + function Noop() { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Noop() without being connected"); + return false; + } + + fputs($this->smtp_conn,"NOOP" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "NOOP not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Sends the quit command to the server and then closes the socket + * if there is no error or the $close_on_error argument is true. + * + * Implements from rfc 821: QUIT + * + * SMTP CODE SUCCESS: 221 + * SMTP CODE ERROR : 500 + * @access public + * @return bool + */ + function Quit($close_on_error=true) { + $this->error = null; # so there is no confusion + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Quit() without being connected"); + return false; + } + + # send the quit command to the server + fputs($this->smtp_conn,"quit" . $this->CRLF); + + # get any good-bye messages + $byemsg = $this->get_lines(); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $byemsg; + } + + $rval = true; + $e = null; + + $code = substr($byemsg,0,3); + if($code != 221) { + # use e as a tmp var cause Close will overwrite $this->error + $e = array("error" => "SMTP server rejected quit command", + "smtp_code" => $code, + "smtp_rply" => substr($byemsg,4)); + $rval = false; + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $e["error"] . ": " . + $byemsg . $this->CRLF; + } + } + + if(empty($e) || $close_on_error) { + $this->Close(); + } + + return $rval; + } + + /** + * Sends the command RCPT to the SMTP server with the TO: argument of $to. + * Returns true if the recipient was accepted false if it was rejected. + * + * Implements from rfc 821: RCPT TO: + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,552,553,450,451,452 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + function Recipient($to) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Recipient() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250 && $code != 251) { + $this->error = + array("error" => "RCPT not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Sends the RSET command to abort and transaction that is + * currently in progress. Returns true if successful false + * otherwise. + * + * Implements rfc 821: RSET + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500,501,504,421 + * @access public + * @return bool + */ + function Reset() { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Reset() without being connected"); + return false; + } + + fputs($this->smtp_conn,"RSET" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "RSET failed", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the users terminal if they are logged + * in. + * + * Implements rfc 821: SEND FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + function Send($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Send() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SEND FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "SEND not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * + * Implements rfc 821: SAML FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + function SendAndMail($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called SendAndMail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "SAML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the users terminal if they are logged + * in or mail it to them if they are not. + * + * Implements rfc 821: SOML FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + function SendOrMail($from) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called SendOrMail() without being connected"); + return false; + } + + fputs($this->smtp_conn,"SOML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250) { + $this->error = + array("error" => "SOML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return true; + } + + /** + * This is an optional command for SMTP that this class does not + * support. This method is here to make the RFC821 Definition + * complete for this class and __may__ be implimented in the future + * + * Implements from rfc 821: TURN + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 502 + * SMTP CODE ERROR : 500, 503 + * @access public + * @return bool + */ + function Turn() { + $this->error = array("error" => "This method, TURN, of the SMTP ". + "is not implemented"); + if($this->do_debug >= 1) { + echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF; + } + return false; + } + + /** + * Verifies that the name is recognized by the server. + * Returns false if the name could not be verified otherwise + * the response from the server is returned. + * + * Implements rfc 821: VRFY + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,553 + * SMTP CODE ERROR : 500,501,502,421 + * @access public + * @return int + */ + function Verify($name) { + $this->error = null; # so no confusion is caused + + if(!$this->connected()) { + $this->error = array( + "error" => "Called Verify() without being connected"); + return false; + } + + fputs($this->smtp_conn,"VRFY " . $name . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply,0,3); + + if($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply; + } + + if($code != 250 && $code != 251) { + $this->error = + array("error" => "VRFY failed on name '$name'", + "smtp_code" => $code, + "smtp_msg" => substr($rply,4)); + if($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . + ": " . $rply . $this->CRLF; + } + return false; + } + return $rply; + } + + /******************************************************************* + * INTERNAL FUNCTIONS * + ******************************************************************/ + + /** + * Read in as many lines as possible + * either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access private + * @return string + */ + function get_lines() { + $data = ""; + while($str = @fgets($this->smtp_conn,515)) { + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data was \"$data\"" . + $this->CRLF; + echo "SMTP -> get_lines(): \$str is \"$str\"" . + $this->CRLF; + } + $data .= $str; + if($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF; + } + # if the 4th character is a space then we are done reading + # so just break the loop + if(substr($str,3,1) == " ") { break; } + } + return $data; + } + +} + + + ?> diff --git a/wp-includes/class-snoopy.php b/wp-includes/class-snoopy.php new file mode 100644 index 0000000..b1b32d2 --- /dev/null +++ b/wp-includes/class-snoopy.php @@ -0,0 +1,1250 @@ + +Copyright (c): 1999-2008 New Digital Group, all rights reserved +Version: 1.2.4 + + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +You may contact the author of Snoopy by e-mail at: +monte@ohrt.com + +The latest version of Snoopy can be obtained from: +http://snoopy.sourceforge.net/ + +*************************************************/ + +class Snoopy +{ + /**** Public variables ****/ + + /* user definable vars */ + + var $host = "www.php.net"; // host name we are connecting to + var $port = 80; // port we are connecting to + var $proxy_host = ""; // proxy host to use + var $proxy_port = ""; // proxy port to use + var $proxy_user = ""; // proxy user to use + var $proxy_pass = ""; // proxy password to use + + var $agent = "Snoopy v1.2.4"; // agent we masquerade as + var $referer = ""; // referer info to pass + var $cookies = array(); // array of cookies to pass + // $cookies["username"]="joe"; + var $rawheaders = array(); // array of raw headers to send + // $rawheaders["Content-type"]="text/html"; + + var $maxredirs = 5; // http redirection depth maximum. 0 = disallow + var $lastredirectaddr = ""; // contains address of last redirected address + var $offsiteok = true; // allows redirection off-site + var $maxframes = 0; // frame content depth maximum. 0 = disallow + var $expandlinks = true; // expand links to fully qualified URLs. + // this only applies to fetchlinks() + // submitlinks(), and submittext() + var $passcookies = true; // pass set cookies back through redirects + // NOTE: this currently does not respect + // dates, domains or paths. + + var $user = ""; // user for http authentication + var $pass = ""; // password for http authentication + + // http accept types + var $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; + + var $results = ""; // where the content is put + + var $error = ""; // error messages sent here + var $response_code = ""; // response code returned from server + var $headers = array(); // headers returned from server sent here + var $maxlength = 500000; // max return data length (body) + var $read_timeout = 0; // timeout on read operations, in seconds + // supported only since PHP 4 Beta 4 + // set to 0 to disallow timeouts + var $timed_out = false; // if a read operation timed out + var $status = 0; // http request status + + var $temp_dir = "/tmp"; // temporary directory that the webserver + // has permission to write to. + // under Windows, this should be C:\temp + + var $curl_path = "/usr/local/bin/curl"; + // Snoopy will use cURL for fetching + // SSL content if a full system path to + // the cURL binary is supplied here. + // set to false if you do not have + // cURL installed. See http://curl.haxx.se + // for details on installing cURL. + // Snoopy does *not* use the cURL + // library functions built into php, + // as these functions are not stable + // as of this Snoopy release. + + /**** Private variables ****/ + + var $_maxlinelen = 4096; // max line length (headers) + + var $_httpmethod = "GET"; // default http request method + var $_httpversion = "HTTP/1.0"; // default http request version + var $_submit_method = "POST"; // default submit method + var $_submit_type = "application/x-www-form-urlencoded"; // default submit type + var $_mime_boundary = ""; // MIME boundary for multipart/form-data submit type + var $_redirectaddr = false; // will be set if page fetched is a redirect + var $_redirectdepth = 0; // increments on an http redirect + var $_frameurls = array(); // frame src urls + var $_framedepth = 0; // increments on frame depth + + var $_isproxy = false; // set if using a proxy server + var $_fp_timeout = 30; // timeout for socket connection + +/*======================================================================*\ + Function: fetch + Purpose: fetch the contents of a web page + (and possibly other protocols in the + future like ftp, nntp, gopher, etc.) + Input: $URI the location of the page to fetch + Output: $this->results the output text from the fetch +\*======================================================================*/ + + function fetch($URI) + { + + //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS); + $URI_PARTS = parse_url($URI); + if (!empty($URI_PARTS["user"])) + $this->user = $URI_PARTS["user"]; + if (!empty($URI_PARTS["pass"])) + $this->pass = $URI_PARTS["pass"]; + if (empty($URI_PARTS["query"])) + $URI_PARTS["query"] = ''; + if (empty($URI_PARTS["path"])) + $URI_PARTS["path"] = ''; + + switch(strtolower($URI_PARTS["scheme"])) + { + case "http": + $this->host = $URI_PARTS["host"]; + if(!empty($URI_PARTS["port"])) + $this->port = $URI_PARTS["port"]; + if($this->_connect($fp)) + { + if($this->_isproxy) + { + // using proxy, send entire URI + $this->_httprequest($URI,$fp,$URI,$this->_httpmethod); + } + else + { + $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); + // no proxy, send only the path + $this->_httprequest($path, $fp, $URI, $this->_httpmethod); + } + + $this->_disconnect($fp); + + if($this->_redirectaddr) + { + /* url was redirected, check if we've hit the max depth */ + if($this->maxredirs > $this->_redirectdepth) + { + // only follow redirect if it's on this site, or offsiteok is true + if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) + { + /* follow the redirect */ + $this->_redirectdepth++; + $this->lastredirectaddr=$this->_redirectaddr; + $this->fetch($this->_redirectaddr); + } + } + } + + if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) + { + $frameurls = $this->_frameurls; + $this->_frameurls = array(); + + while(list(,$frameurl) = each($frameurls)) + { + if($this->_framedepth < $this->maxframes) + { + $this->fetch($frameurl); + $this->_framedepth++; + } + else + break; + } + } + } + else + { + return false; + } + return true; + break; + case "https": + if(!$this->curl_path) + return false; + if(function_exists("is_executable")) + if (!is_executable($this->curl_path)) + return false; + $this->host = $URI_PARTS["host"]; + if(!empty($URI_PARTS["port"])) + $this->port = $URI_PARTS["port"]; + if($this->_isproxy) + { + // using proxy, send entire URI + $this->_httpsrequest($URI,$URI,$this->_httpmethod); + } + else + { + $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); + // no proxy, send only the path + $this->_httpsrequest($path, $URI, $this->_httpmethod); + } + + if($this->_redirectaddr) + { + /* url was redirected, check if we've hit the max depth */ + if($this->maxredirs > $this->_redirectdepth) + { + // only follow redirect if it's on this site, or offsiteok is true + if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) + { + /* follow the redirect */ + $this->_redirectdepth++; + $this->lastredirectaddr=$this->_redirectaddr; + $this->fetch($this->_redirectaddr); + } + } + } + + if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) + { + $frameurls = $this->_frameurls; + $this->_frameurls = array(); + + while(list(,$frameurl) = each($frameurls)) + { + if($this->_framedepth < $this->maxframes) + { + $this->fetch($frameurl); + $this->_framedepth++; + } + else + break; + } + } + return true; + break; + default: + // not a valid protocol + $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; + return false; + break; + } + return true; + } + +/*======================================================================*\ + Function: submit + Purpose: submit an http form + Input: $URI the location to post the data + $formvars the formvars to use. + format: $formvars["var"] = "val"; + $formfiles an array of files to submit + format: $formfiles["var"] = "/dir/filename.ext"; + Output: $this->results the text output from the post +\*======================================================================*/ + + function submit($URI, $formvars="", $formfiles="") + { + unset($postdata); + + $postdata = $this->_prepare_post_body($formvars, $formfiles); + + $URI_PARTS = parse_url($URI); + if (!empty($URI_PARTS["user"])) + $this->user = $URI_PARTS["user"]; + if (!empty($URI_PARTS["pass"])) + $this->pass = $URI_PARTS["pass"]; + if (empty($URI_PARTS["query"])) + $URI_PARTS["query"] = ''; + if (empty($URI_PARTS["path"])) + $URI_PARTS["path"] = ''; + + switch(strtolower($URI_PARTS["scheme"])) + { + case "http": + $this->host = $URI_PARTS["host"]; + if(!empty($URI_PARTS["port"])) + $this->port = $URI_PARTS["port"]; + if($this->_connect($fp)) + { + if($this->_isproxy) + { + // using proxy, send entire URI + $this->_httprequest($URI,$fp,$URI,$this->_submit_method,$this->_submit_type,$postdata); + } + else + { + $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); + // no proxy, send only the path + $this->_httprequest($path, $fp, $URI, $this->_submit_method, $this->_submit_type, $postdata); + } + + $this->_disconnect($fp); + + if($this->_redirectaddr) + { + /* url was redirected, check if we've hit the max depth */ + if($this->maxredirs > $this->_redirectdepth) + { + if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr)) + $this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]); + + // only follow redirect if it's on this site, or offsiteok is true + if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) + { + /* follow the redirect */ + $this->_redirectdepth++; + $this->lastredirectaddr=$this->_redirectaddr; + if( strpos( $this->_redirectaddr, "?" ) > 0 ) + $this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get + else + $this->submit($this->_redirectaddr,$formvars, $formfiles); + } + } + } + + if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) + { + $frameurls = $this->_frameurls; + $this->_frameurls = array(); + + while(list(,$frameurl) = each($frameurls)) + { + if($this->_framedepth < $this->maxframes) + { + $this->fetch($frameurl); + $this->_framedepth++; + } + else + break; + } + } + + } + else + { + return false; + } + return true; + break; + case "https": + if(!$this->curl_path) + return false; + if(function_exists("is_executable")) + if (!is_executable($this->curl_path)) + return false; + $this->host = $URI_PARTS["host"]; + if(!empty($URI_PARTS["port"])) + $this->port = $URI_PARTS["port"]; + if($this->_isproxy) + { + // using proxy, send entire URI + $this->_httpsrequest($URI, $URI, $this->_submit_method, $this->_submit_type, $postdata); + } + else + { + $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); + // no proxy, send only the path + $this->_httpsrequest($path, $URI, $this->_submit_method, $this->_submit_type, $postdata); + } + + if($this->_redirectaddr) + { + /* url was redirected, check if we've hit the max depth */ + if($this->maxredirs > $this->_redirectdepth) + { + if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr)) + $this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]); + + // only follow redirect if it's on this site, or offsiteok is true + if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) + { + /* follow the redirect */ + $this->_redirectdepth++; + $this->lastredirectaddr=$this->_redirectaddr; + if( strpos( $this->_redirectaddr, "?" ) > 0 ) + $this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get + else + $this->submit($this->_redirectaddr,$formvars, $formfiles); + } + } + } + + if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) + { + $frameurls = $this->_frameurls; + $this->_frameurls = array(); + + while(list(,$frameurl) = each($frameurls)) + { + if($this->_framedepth < $this->maxframes) + { + $this->fetch($frameurl); + $this->_framedepth++; + } + else + break; + } + } + return true; + break; + + default: + // not a valid protocol + $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; + return false; + break; + } + return true; + } + +/*======================================================================*\ + Function: fetchlinks + Purpose: fetch the links from a web page + Input: $URI where you are fetching from + Output: $this->results an array of the URLs +\*======================================================================*/ + + function fetchlinks($URI) + { + if ($this->fetch($URI)) + { + if($this->lastredirectaddr) + $URI = $this->lastredirectaddr; + if(is_array($this->results)) + { + for($x=0;$xresults);$x++) + $this->results[$x] = $this->_striplinks($this->results[$x]); + } + else + $this->results = $this->_striplinks($this->results); + + if($this->expandlinks) + $this->results = $this->_expandlinks($this->results, $URI); + return true; + } + else + return false; + } + +/*======================================================================*\ + Function: fetchform + Purpose: fetch the form elements from a web page + Input: $URI where you are fetching from + Output: $this->results the resulting html form +\*======================================================================*/ + + function fetchform($URI) + { + + if ($this->fetch($URI)) + { + + if(is_array($this->results)) + { + for($x=0;$xresults);$x++) + $this->results[$x] = $this->_stripform($this->results[$x]); + } + else + $this->results = $this->_stripform($this->results); + + return true; + } + else + return false; + } + + +/*======================================================================*\ + Function: fetchtext + Purpose: fetch the text from a web page, stripping the links + Input: $URI where you are fetching from + Output: $this->results the text from the web page +\*======================================================================*/ + + function fetchtext($URI) + { + if($this->fetch($URI)) + { + if(is_array($this->results)) + { + for($x=0;$xresults);$x++) + $this->results[$x] = $this->_striptext($this->results[$x]); + } + else + $this->results = $this->_striptext($this->results); + return true; + } + else + return false; + } + +/*======================================================================*\ + Function: submitlinks + Purpose: grab links from a form submission + Input: $URI where you are submitting from + Output: $this->results an array of the links from the post +\*======================================================================*/ + + function submitlinks($URI, $formvars="", $formfiles="") + { + if($this->submit($URI,$formvars, $formfiles)) + { + if($this->lastredirectaddr) + $URI = $this->lastredirectaddr; + if(is_array($this->results)) + { + for($x=0;$xresults);$x++) + { + $this->results[$x] = $this->_striplinks($this->results[$x]); + if($this->expandlinks) + $this->results[$x] = $this->_expandlinks($this->results[$x],$URI); + } + } + else + { + $this->results = $this->_striplinks($this->results); + if($this->expandlinks) + $this->results = $this->_expandlinks($this->results,$URI); + } + return true; + } + else + return false; + } + +/*======================================================================*\ + Function: submittext + Purpose: grab text from a form submission + Input: $URI where you are submitting from + Output: $this->results the text from the web page +\*======================================================================*/ + + function submittext($URI, $formvars = "", $formfiles = "") + { + if($this->submit($URI,$formvars, $formfiles)) + { + if($this->lastredirectaddr) + $URI = $this->lastredirectaddr; + if(is_array($this->results)) + { + for($x=0;$xresults);$x++) + { + $this->results[$x] = $this->_striptext($this->results[$x]); + if($this->expandlinks) + $this->results[$x] = $this->_expandlinks($this->results[$x],$URI); + } + } + else + { + $this->results = $this->_striptext($this->results); + if($this->expandlinks) + $this->results = $this->_expandlinks($this->results,$URI); + } + return true; + } + else + return false; + } + + + +/*======================================================================*\ + Function: set_submit_multipart + Purpose: Set the form submission content type to + multipart/form-data +\*======================================================================*/ + function set_submit_multipart() + { + $this->_submit_type = "multipart/form-data"; + } + + +/*======================================================================*\ + Function: set_submit_normal + Purpose: Set the form submission content type to + application/x-www-form-urlencoded +\*======================================================================*/ + function set_submit_normal() + { + $this->_submit_type = "application/x-www-form-urlencoded"; + } + + + + +/*======================================================================*\ + Private functions +\*======================================================================*/ + + +/*======================================================================*\ + Function: _striplinks + Purpose: strip the hyperlinks from an html document + Input: $document document to strip. + Output: $match an array of the links +\*======================================================================*/ + + function _striplinks($document) + { + preg_match_all("'<\s*a\s.*?href\s*=\s* # find ]+)) # if quote found, match up to next matching + # quote, otherwise match up to next space + 'isx",$document,$links); + + + // catenate the non-empty matches from the conditional subpattern + + while(list($key,$val) = each($links[2])) + { + if(!empty($val)) + $match[] = $val; + } + + while(list($key,$val) = each($links[3])) + { + if(!empty($val)) + $match[] = $val; + } + + // return the links + return $match; + } + +/*======================================================================*\ + Function: _stripform + Purpose: strip the form elements from an html document + Input: $document document to strip. + Output: $match an array of the links +\*======================================================================*/ + + function _stripform($document) + { + preg_match_all("'<\/?(FORM|INPUT|SELECT|TEXTAREA|(OPTION))[^<>]*>(?(2)(.*(?=<\/?(option|select)[^<>]*>[\r\n]*)|(?=[\r\n]*))|(?=[\r\n]*))'Usi",$document,$elements); + + // catenate the matches + $match = implode("\r\n",$elements[0]); + + // return the links + return $match; + } + + + +/*======================================================================*\ + Function: _striptext + Purpose: strip the text from an html document + Input: $document document to strip. + Output: $text the resulting text +\*======================================================================*/ + + function _striptext($document) + { + + // I didn't use preg eval (//e) since that is only available in PHP 4.0. + // so, list your entities one by one here. I included some of the + // more common ones. + + $search = array("']*?>.*?'si", // strip out javascript + "'<[\/\!]*?[^<>]*?>'si", // strip out html tags + "'([\r\n])[\s]+'", // strip out white space + "'&(quot|#34|#034|#x22);'i", // replace html entities + "'&(amp|#38|#038|#x26);'i", // added hexadecimal values + "'&(lt|#60|#060|#x3c);'i", + "'&(gt|#62|#062|#x3e);'i", + "'&(nbsp|#160|#xa0);'i", + "'&(iexcl|#161);'i", + "'&(cent|#162);'i", + "'&(pound|#163);'i", + "'&(copy|#169);'i", + "'&(reg|#174);'i", + "'&(deg|#176);'i", + "'&(#39|#039|#x27);'", + "'&(euro|#8364);'i", // europe + "'&a(uml|UML);'", // german + "'&o(uml|UML);'", + "'&u(uml|UML);'", + "'&A(uml|UML);'", + "'&O(uml|UML);'", + "'&U(uml|UML);'", + "'ß'i", + ); + $replace = array( "", + "", + "\\1", + "\"", + "&", + "<", + ">", + " ", + chr(161), + chr(162), + chr(163), + chr(169), + chr(174), + chr(176), + chr(39), + chr(128), + "ä", + "ö", + "ü", + "Ä", + "Ö", + "Ü", + "ß", + ); + + $text = preg_replace($search,$replace,$document); + + return $text; + } + +/*======================================================================*\ + Function: _expandlinks + Purpose: expand each link into a fully qualified URL + Input: $links the links to qualify + $URI the full URI to get the base from + Output: $expandedLinks the expanded links +\*======================================================================*/ + + function _expandlinks($links,$URI) + { + + preg_match("/^[^\?]+/",$URI,$match); + + $match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]); + $match = preg_replace("|/$|","",$match); + $match_part = parse_url($match); + $match_root = + $match_part["scheme"]."://".$match_part["host"]; + + $search = array( "|^http://".preg_quote($this->host)."|i", + "|^(\/)|i", + "|^(?!http://)(?!mailto:)|i", + "|/\./|", + "|/[^\/]+/\.\./|" + ); + + $replace = array( "", + $match_root."/", + $match."/", + "/", + "/" + ); + + $expandedLinks = preg_replace($search,$replace,$links); + + return $expandedLinks; + } + +/*======================================================================*\ + Function: _httprequest + Purpose: go get the http data from the server + Input: $url the url to fetch + $fp the current open file pointer + $URI the full URI + $body body contents to send if any (POST) + Output: +\*======================================================================*/ + + function _httprequest($url,$fp,$URI,$http_method,$content_type="",$body="") + { + $cookie_headers = ''; + if($this->passcookies && $this->_redirectaddr) + $this->setcookies(); + + $URI_PARTS = parse_url($URI); + if(empty($url)) + $url = "/"; + $headers = $http_method." ".$url." ".$this->_httpversion."\r\n"; + if(!empty($this->agent)) + $headers .= "User-Agent: ".$this->agent."\r\n"; + if(!empty($this->host) && !isset($this->rawheaders['Host'])) { + $headers .= "Host: ".$this->host; + if(!empty($this->port) && $this->port != 80) + $headers .= ":".$this->port; + $headers .= "\r\n"; + } + if(!empty($this->accept)) + $headers .= "Accept: ".$this->accept."\r\n"; + if(!empty($this->referer)) + $headers .= "Referer: ".$this->referer."\r\n"; + if(!empty($this->cookies)) + { + if(!is_array($this->cookies)) + $this->cookies = (array)$this->cookies; + + reset($this->cookies); + if ( count($this->cookies) > 0 ) { + $cookie_headers .= 'Cookie: '; + foreach ( $this->cookies as $cookieKey => $cookieVal ) { + $cookie_headers .= $cookieKey."=".urlencode($cookieVal)."; "; + } + $headers .= substr($cookie_headers,0,-2) . "\r\n"; + } + } + if(!empty($this->rawheaders)) + { + if(!is_array($this->rawheaders)) + $this->rawheaders = (array)$this->rawheaders; + while(list($headerKey,$headerVal) = each($this->rawheaders)) + $headers .= $headerKey.": ".$headerVal."\r\n"; + } + if(!empty($content_type)) { + $headers .= "Content-type: $content_type"; + if ($content_type == "multipart/form-data") + $headers .= "; boundary=".$this->_mime_boundary; + $headers .= "\r\n"; + } + if(!empty($body)) + $headers .= "Content-length: ".strlen($body)."\r\n"; + if(!empty($this->user) || !empty($this->pass)) + $headers .= "Authorization: Basic ".base64_encode($this->user.":".$this->pass)."\r\n"; + + //add proxy auth headers + if(!empty($this->proxy_user)) + $headers .= 'Proxy-Authorization: ' . 'Basic ' . base64_encode($this->proxy_user . ':' . $this->proxy_pass)."\r\n"; + + + $headers .= "\r\n"; + + // set the read timeout if needed + if ($this->read_timeout > 0) + socket_set_timeout($fp, $this->read_timeout); + $this->timed_out = false; + + fwrite($fp,$headers.$body,strlen($headers.$body)); + + $this->_redirectaddr = false; + unset($this->headers); + + while($currentHeader = fgets($fp,$this->_maxlinelen)) + { + if ($this->read_timeout > 0 && $this->_check_timeout($fp)) + { + $this->status=-100; + return false; + } + + if($currentHeader == "\r\n") + break; + + // if a header begins with Location: or URI:, set the redirect + if(preg_match("/^(Location:|URI:)/i",$currentHeader)) + { + // get URL portion of the redirect + preg_match("/^(Location:|URI:)[ ]+(.*)/i",chop($currentHeader),$matches); + // look for :// in the Location header to see if hostname is included + if(!preg_match("|\:\/\/|",$matches[2])) + { + // no host in the path, so prepend + $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; + // eliminate double slash + if(!preg_match("|^/|",$matches[2])) + $this->_redirectaddr .= "/".$matches[2]; + else + $this->_redirectaddr .= $matches[2]; + } + else + $this->_redirectaddr = $matches[2]; + } + + if(preg_match("|^HTTP/|",$currentHeader)) + { + if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status)) + { + $this->status= $status[1]; + } + $this->response_code = $currentHeader; + } + + $this->headers[] = $currentHeader; + } + + $results = ''; + do { + $_data = fread($fp, $this->maxlength); + if (strlen($_data) == 0) { + break; + } + $results .= $_data; + } while(true); + + if ($this->read_timeout > 0 && $this->_check_timeout($fp)) + { + $this->status=-100; + return false; + } + + // check if there is a a redirect meta tag + + if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]*URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) + + { + $this->_redirectaddr = $this->_expandlinks($match[1],$URI); + } + + // have we hit our frame depth and is there frame src to fetch? + if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) + { + $this->results[] = $results; + for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); + } + // have we already fetched framed content? + elseif(is_array($this->results)) + $this->results[] = $results; + // no framed content + else + $this->results = $results; + + return true; + } + +/*======================================================================*\ + Function: _httpsrequest + Purpose: go get the https data from the server using curl + Input: $url the url to fetch + $URI the full URI + $body body contents to send if any (POST) + Output: +\*======================================================================*/ + + function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") + { + if($this->passcookies && $this->_redirectaddr) + $this->setcookies(); + + $headers = array(); + + $URI_PARTS = parse_url($URI); + if(empty($url)) + $url = "/"; + // GET ... header not needed for curl + //$headers[] = $http_method." ".$url." ".$this->_httpversion; + if(!empty($this->agent)) + $headers[] = "User-Agent: ".$this->agent; + if(!empty($this->host)) + if(!empty($this->port)) + $headers[] = "Host: ".$this->host.":".$this->port; + else + $headers[] = "Host: ".$this->host; + if(!empty($this->accept)) + $headers[] = "Accept: ".$this->accept; + if(!empty($this->referer)) + $headers[] = "Referer: ".$this->referer; + if(!empty($this->cookies)) + { + if(!is_array($this->cookies)) + $this->cookies = (array)$this->cookies; + + reset($this->cookies); + if ( count($this->cookies) > 0 ) { + $cookie_str = 'Cookie: '; + foreach ( $this->cookies as $cookieKey => $cookieVal ) { + $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; "; + } + $headers[] = substr($cookie_str,0,-2); + } + } + if(!empty($this->rawheaders)) + { + if(!is_array($this->rawheaders)) + $this->rawheaders = (array)$this->rawheaders; + while(list($headerKey,$headerVal) = each($this->rawheaders)) + $headers[] = $headerKey.": ".$headerVal; + } + if(!empty($content_type)) { + if ($content_type == "multipart/form-data") + $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary; + else + $headers[] = "Content-type: $content_type"; + } + if(!empty($body)) + $headers[] = "Content-length: ".strlen($body); + if(!empty($this->user) || !empty($this->pass)) + $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass); + + for($curr_header = 0; $curr_header < count($headers); $curr_header++) { + $safer_header = strtr( $headers[$curr_header], "\"", " " ); + $cmdline_params .= " -H \"".$safer_header."\""; + } + + if(!empty($body)) + $cmdline_params .= " -d \"$body\""; + + if($this->read_timeout > 0) + $cmdline_params .= " -m ".$this->read_timeout; + + $headerfile = tempnam($temp_dir, "sno"); + + exec($this->curl_path." -k -D \"$headerfile\"".$cmdline_params." \"".escapeshellcmd($URI)."\"",$results,$return); + + if($return) + { + $this->error = "Error: cURL could not retrieve the document, error $return."; + return false; + } + + + $results = implode("\r\n",$results); + + $result_headers = file("$headerfile"); + + $this->_redirectaddr = false; + unset($this->headers); + + for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) + { + + // if a header begins with Location: or URI:, set the redirect + if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader])) + { + // get URL portion of the redirect + preg_match("/^(Location: |URI:)\s+(.*)/",chop($result_headers[$currentHeader]),$matches); + // look for :// in the Location header to see if hostname is included + if(!preg_match("|\:\/\/|",$matches[2])) + { + // no host in the path, so prepend + $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host.":".$this->port; + // eliminate double slash + if(!preg_match("|^/|",$matches[2])) + $this->_redirectaddr .= "/".$matches[2]; + else + $this->_redirectaddr .= $matches[2]; + } + else + $this->_redirectaddr = $matches[2]; + } + + if(preg_match("|^HTTP/|",$result_headers[$currentHeader])) + $this->response_code = $result_headers[$currentHeader]; + + $this->headers[] = $result_headers[$currentHeader]; + } + + // check if there is a a redirect meta tag + + if(preg_match("']*?content[\s]*=[\s]*[\"\']?\d+;[\s]*URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) + { + $this->_redirectaddr = $this->_expandlinks($match[1],$URI); + } + + // have we hit our frame depth and is there frame src to fetch? + if(($this->_framedepth < $this->maxframes) && preg_match_all("']+)'i",$results,$match)) + { + $this->results[] = $results; + for($x=0; $x_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); + } + // have we already fetched framed content? + elseif(is_array($this->results)) + $this->results[] = $results; + // no framed content + else + $this->results = $results; + + unlink("$headerfile"); + + return true; + } + +/*======================================================================*\ + Function: setcookies() + Purpose: set cookies for a redirection +\*======================================================================*/ + + function setcookies() + { + for($x=0; $xheaders); $x++) + { + if(preg_match('/^set-cookie:[\s]+([^=]+)=([^;]+)/i', $this->headers[$x],$match)) + $this->cookies[$match[1]] = urldecode($match[2]); + } + } + + +/*======================================================================*\ + Function: _check_timeout + Purpose: checks whether timeout has occurred + Input: $fp file pointer +\*======================================================================*/ + + function _check_timeout($fp) + { + if ($this->read_timeout > 0) { + $fp_status = socket_get_status($fp); + if ($fp_status["timed_out"]) { + $this->timed_out = true; + return true; + } + } + return false; + } + +/*======================================================================*\ + Function: _connect + Purpose: make a socket connection + Input: $fp file pointer +\*======================================================================*/ + + function _connect(&$fp) + { + if(!empty($this->proxy_host) && !empty($this->proxy_port)) + { + $this->_isproxy = true; + + $host = $this->proxy_host; + $port = $this->proxy_port; + } + else + { + $host = $this->host; + $port = $this->port; + } + + $this->status = 0; + + if($fp = fsockopen( + $host, + $port, + $errno, + $errstr, + $this->_fp_timeout + )) + { + // socket connection succeeded + + return true; + } + else + { + // socket connection failed + $this->status = $errno; + switch($errno) + { + case -3: + $this->error="socket creation failed (-3)"; + case -4: + $this->error="dns lookup failure (-4)"; + case -5: + $this->error="connection refused or timed out (-5)"; + default: + $this->error="connection failed (".$errno.")"; + } + return false; + } + } +/*======================================================================*\ + Function: _disconnect + Purpose: disconnect a socket connection + Input: $fp file pointer +\*======================================================================*/ + + function _disconnect($fp) + { + return(fclose($fp)); + } + + +/*======================================================================*\ + Function: _prepare_post_body + Purpose: Prepare post body according to encoding type + Input: $formvars - form variables + $formfiles - form upload files + Output: post body +\*======================================================================*/ + + function _prepare_post_body($formvars, $formfiles) + { + settype($formvars, "array"); + settype($formfiles, "array"); + $postdata = ''; + + if (count($formvars) == 0 && count($formfiles) == 0) + return; + + switch ($this->_submit_type) { + case "application/x-www-form-urlencoded": + reset($formvars); + while(list($key,$val) = each($formvars)) { + if (is_array($val) || is_object($val)) { + while (list($cur_key, $cur_val) = each($val)) { + $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&"; + } + } else + $postdata .= urlencode($key)."=".urlencode($val)."&"; + } + break; + + case "multipart/form-data": + $this->_mime_boundary = "Snoopy".md5(uniqid(microtime())); + + reset($formvars); + while(list($key,$val) = each($formvars)) { + if (is_array($val) || is_object($val)) { + while (list($cur_key, $cur_val) = each($val)) { + $postdata .= "--".$this->_mime_boundary."\r\n"; + $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n"; + $postdata .= "$cur_val\r\n"; + } + } else { + $postdata .= "--".$this->_mime_boundary."\r\n"; + $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n"; + $postdata .= "$val\r\n"; + } + } + + reset($formfiles); + while (list($field_name, $file_names) = each($formfiles)) { + settype($file_names, "array"); + while (list(, $file_name) = each($file_names)) { + if (!is_readable($file_name)) continue; + + $fp = fopen($file_name, "r"); + $file_content = fread($fp, filesize($file_name)); + fclose($fp); + $base_name = basename($file_name); + + $postdata .= "--".$this->_mime_boundary."\r\n"; + $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\n\r\n"; + $postdata .= "$file_content\r\n"; + } + } + $postdata .= "--".$this->_mime_boundary."--\r\n"; + break; + } + + return $postdata; + } +} +endif; +?> diff --git a/wp-includes/class.wp-dependencies.php b/wp-includes/class.wp-dependencies.php new file mode 100644 index 0000000..af3808b --- /dev/null +++ b/wp-includes/class.wp-dependencies.php @@ -0,0 +1,239 @@ +queue : (array) $handles; + $this->all_deps( $handles ); + + foreach( $this->to_do as $key => $handle ) { + if ( !in_array($handle, $this->done) && isset($this->registered[$handle]) ) { + + if ( ! $this->registered[$handle]->src ) { // Defines a group. + $this->done[] = $handle; + continue; + } + + if ( $this->do_item( $handle, $group ) ) + $this->done[] = $handle; + + unset( $this->to_do[$key] ); + } + } + + return $this->done; + } + + function do_item( $handle ) { + return isset($this->registered[$handle]); + } + + /** + * Determines dependencies + * + * Recursively builds array of items to process taking dependencies into account. Does NOT catch infinite loops. + * + + * @param mixed handles Accepts (string) dep name or (array of strings) dep names + * @param bool recursion Used internally when function calls itself + */ + function all_deps( $handles, $recursion = false, $group = false ) { + if ( !$handles = (array) $handles ) + return false; + + foreach ( $handles as $handle ) { + $handle_parts = explode('?', $handle); + $handle = $handle_parts[0]; + $queued = in_array($handle, $this->to_do, true); + + if ( in_array($handle, $this->done, true) ) // Already done + continue; + + $moved = $this->set_group( $handle, $recursion, $group ); + + if ( $queued && !$moved ) // already queued and in the right group + continue; + + $keep_going = true; + if ( !isset($this->registered[$handle]) ) + $keep_going = false; // Script doesn't exist + elseif ( $this->registered[$handle]->deps && array_diff($this->registered[$handle]->deps, array_keys($this->registered)) ) + $keep_going = false; // Script requires deps which don't exist (not a necessary check. efficiency?) + elseif ( $this->registered[$handle]->deps && !$this->all_deps( $this->registered[$handle]->deps, true, $group ) ) + $keep_going = false; // Script requires deps which don't exist + + if ( !$keep_going ) { // Either script or its deps don't exist. + if ( $recursion ) + return false; // Abort this branch. + else + continue; // We're at the top level. Move on to the next one. + } + + if ( $queued ) // Already grobbed it and its deps + continue; + + if ( isset($handle_parts[1]) ) + $this->args[$handle] = $handle_parts[1]; + + $this->to_do[] = $handle; + } + + return true; + } + + /** + * Adds item + * + * Adds the item only if no item of that name already exists + * + * @param string handle Script name + * @param string src Script url + * @param array deps (optional) Array of script names on which this script depends + * @param string ver (optional) Script version (used for cache busting) + * @return array Hierarchical array of dependencies + */ + function add( $handle, $src, $deps = array(), $ver = false, $args = null ) { + if ( isset($this->registered[$handle]) ) + return false; + $this->registered[$handle] = new _WP_Dependency( $handle, $src, $deps, $ver, $args ); + return true; + } + + /** + * Adds extra data + * + * Adds data only if script has already been added + * + * @param string handle Script name + * @param string data_name Name of object in which to store extra data + * @param array data Array of extra data + * @return bool success + */ + function add_data( $handle, $data_name, $data ) { + if ( !isset($this->registered[$handle]) ) + return false; + return $this->registered[$handle]->add_data( $data_name, $data ); + } + + function remove( $handles ) { + foreach ( (array) $handles as $handle ) + unset($this->registered[$handle]); + } + + function enqueue( $handles ) { + foreach ( (array) $handles as $handle ) { + $handle = explode('?', $handle); + if ( !in_array($handle[0], $this->queue) && isset($this->registered[$handle[0]]) ) { + $this->queue[] = $handle[0]; + if ( isset($handle[1]) ) + $this->args[$handle[0]] = $handle[1]; + } + } + } + + function dequeue( $handles ) { + foreach ( (array) $handles as $handle ) + unset( $this->queue[$handle] ); + } + + function query( $handle, $list = 'registered' ) { // registered, queue, done, to_do + switch ( $list ) : + case 'registered': + case 'scripts': // back compat + if ( isset($this->registered[$handle]) ) + return $this->registered[$handle]; + break; + case 'to_print': // back compat + case 'printed': // back compat + if ( 'to_print' == $list ) + $list = 'to_do'; + else + $list = 'printed'; + default: + if ( in_array($handle, $this->$list) ) + return true; + break; + endswitch; + return false; + } + + function set_group( $handle, $recursion, $group ) { + $group = (int) $group; + + if ( $recursion ) + $group = min($this->group, $group); + else + $this->group = $group; + + if ( isset($this->groups[$handle]) && $this->groups[$handle] <= $group ) + return false; + + $this->groups[$handle] = $group; + return true; + } + +} + +class _WP_Dependency { + var $handle; + var $src; + var $deps = array(); + var $ver = false; + var $args = null; + + var $extra = array(); + + function _WP_Dependency() { + @list($this->handle, $this->src, $this->deps, $this->ver, $this->args) = func_get_args(); + if ( !is_array($this->deps) ) + $this->deps = array(); + if ( !$this->ver ) + $this->ver = false; + } + + function add_data( $name, $data ) { + if ( !is_scalar($name) ) + return false; + $this->extra[$name] = $data; + return true; + } +} diff --git a/wp-includes/class.wp-scripts.php b/wp-includes/class.wp-scripts.php new file mode 100644 index 0000000..9fa96e9 --- /dev/null +++ b/wp-includes/class.wp-scripts.php @@ -0,0 +1,197 @@ +do_items( $handles, $group ); + } + + function print_scripts_l10n( $handle, $echo = true ) { + if ( empty($this->registered[$handle]->extra['l10n']) || empty($this->registered[$handle]->extra['l10n'][0]) || !is_array($this->registered[$handle]->extra['l10n'][1]) ) + return false; + + $object_name = $this->registered[$handle]->extra['l10n'][0]; + + $data = "var $object_name = {\n"; + $eol = ''; + foreach ( $this->registered[$handle]->extra['l10n'][1] as $var => $val ) { + if ( 'l10n_print_after' == $var ) { + $after = $val; + continue; + } + $data .= "$eol\t$var: \"" . esc_js( $val ) . '"'; + $eol = ",\n"; + } + $data .= "\n};\n"; + $data .= isset($after) ? "$after\n" : ''; + + if ( $echo ) { + echo "\n"; + return true; + } else { + return $data; + } + } + + function do_item( $handle, $group = false ) { + if ( !parent::do_item($handle) ) + return false; + + if ( 0 === $group && $this->groups[$handle] > 0 ) { + $this->in_footer[] = $handle; + return false; + } + + if ( false === $group && in_array($handle, $this->in_footer, true) ) + $this->in_footer = array_diff( $this->in_footer, (array) $handle ); + + $ver = $this->registered[$handle]->ver ? $this->registered[$handle]->ver : $this->default_version; + if ( isset($this->args[$handle]) ) + $ver .= '&' . $this->args[$handle]; + + $src = $this->registered[$handle]->src; + + if ( $this->do_concat ) { + $srce = apply_filters( 'script_loader_src', $src, $handle ); + if ( $this->in_default_dir($srce) ) { + $this->print_code .= $this->print_scripts_l10n( $handle, false ); + $this->concat .= "$handle,"; + $this->concat_version .= "$handle$ver"; + return true; + } else { + $this->ext_handles .= "$handle,"; + $this->ext_version .= "$handle$ver"; + } + } + + $this->print_scripts_l10n( $handle ); + if ( !preg_match('|^https?://|', $src) && ! ( $this->content_url && 0 === strpos($src, $this->content_url) ) ) { + $src = $this->base_url . $src; + } + + $src = add_query_arg('ver', $ver, $src); + $src = esc_url(apply_filters( 'script_loader_src', $src, $handle )); + + if ( $this->do_concat ) + $this->print_html .= "\n"; + else + echo "\n"; + + return true; + } + + /** + * Localizes a script + * + * Localizes only if script has already been added + * + * @param string handle Script name + * @param string object_name Name of JS object to hold l10n info + * @param array l10n Array of JS var name => localized string + * @return bool Successful localization + */ + function localize( $handle, $object_name, $l10n ) { + if ( !$object_name || !$l10n ) + return false; + return $this->add_data( $handle, 'l10n', array( $object_name, $l10n ) ); + } + + function set_group( $handle, $recursion, $group = false ) { + $grp = isset($this->registered[$handle]->extra['group']) ? (int) $this->registered[$handle]->extra['group'] : 0; + if ( false !== $group && $grp > $group ) + $grp = $group; + + return parent::set_group( $handle, $recursion, $grp ); + } + + function all_deps( $handles, $recursion = false, $group = false ) { + $r = parent::all_deps( $handles, $recursion ); + if ( !$recursion ) + $this->to_do = apply_filters( 'print_scripts_array', $this->to_do ); + return $r; + } + + function do_head_items() { + $this->do_items(false, 0); + return $this->done; + } + + function do_footer_items() { + if ( !empty($this->in_footer) ) { + foreach( $this->in_footer as $key => $handle ) { + if ( !in_array($handle, $this->done, true) && isset($this->registered[$handle]) ) { + $this->do_item($handle); + $this->done[] = $handle; + unset( $this->in_footer[$key] ); + } + } + } + return $this->done; + } + + function in_default_dir($src) { + if ( ! $this->default_dirs ) + return true; + + foreach ( (array) $this->default_dirs as $test ) { + if ( 0 === strpos($src, $test) ) + return true; + } + return false; + } + + function reset() { + $this->do_concat = false; + $this->print_code = ''; + $this->concat = ''; + $this->concat_version = ''; + $this->print_html = ''; + $this->ext_version = ''; + $this->ext_handles = ''; + } +} diff --git a/wp-includes/class.wp-styles.php b/wp-includes/class.wp-styles.php new file mode 100644 index 0000000..731ae39 --- /dev/null +++ b/wp-includes/class.wp-styles.php @@ -0,0 +1,119 @@ +registered[$handle]->ver ? $this->registered[$handle]->ver : $this->default_version; + if ( isset($this->args[$handle]) ) + $ver .= '&' . $this->args[$handle]; + + if ( $this->do_concat ) { + if ( $this->in_default_dir($this->registered[$handle]->src) && !isset($this->registered[$handle]->extra['conditional']) && !isset($this->registered[$handle]->extra['alt']) ) { + $this->concat .= "$handle,"; + $this->concat_version .= "$handle$ver"; + return true; + } + } + + if ( isset($this->registered[$handle]->args) ) + $media = esc_attr( $this->registered[$handle]->args ); + else + $media = 'all'; + + $href = $this->_css_href( $this->registered[$handle]->src, $ver, $handle ); + $rel = isset($this->registered[$handle]->extra['alt']) && $this->registered[$handle]->extra['alt'] ? 'alternate stylesheet' : 'stylesheet'; + $title = isset($this->registered[$handle]->extra['title']) ? "title='" . esc_attr( $this->registered[$handle]->extra['title'] ) . "'" : ''; + + $end_cond = $tag = ''; + if ( isset($this->registered[$handle]->extra['conditional']) && $this->registered[$handle]->extra['conditional'] ) { + $tag .= "\n"; + } + + $tag .= apply_filters( 'style_loader_tag', "\n", $handle ); + if ( 'rtl' === $this->text_direction && isset($this->registered[$handle]->extra['rtl']) && $this->registered[$handle]->extra['rtl'] ) { + if ( is_bool( $this->registered[$handle]->extra['rtl'] ) ) + $rtl_href = str_replace( '.css', '-rtl.css', $this->_css_href( $this->registered[$handle]->src , $ver, "$handle-rtl" )); + else + $rtl_href = $this->_css_href( $this->registered[$handle]->extra['rtl'], $ver, "$handle-rtl" ); + + $tag .= apply_filters( 'style_loader_tag', "\n", $handle ); + } + + $tag .= $end_cond; + + if ( $this->do_concat ) + $this->print_html .= $tag; + else + echo $tag; + + // Could do something with $this->registered[$handle]->extra here to print out extra CSS rules +// echo "\n"; + + return true; + } + + function all_deps( $handles, $recursion = false, $group = false ) { + $r = parent::all_deps( $handles, $recursion ); + if ( !$recursion ) + $this->to_do = apply_filters( 'print_styles_array', $this->to_do ); + return $r; + } + + function _css_href( $src, $ver, $handle ) { + if ( !preg_match('|^https?://|', $src) && ! ( $this->content_url && 0 === strpos($src, $this->content_url) ) ) { + $src = $this->base_url . $src; + } + + $src = add_query_arg('ver', $ver, $src); + $src = apply_filters( 'style_loader_src', $src, $handle ); + return esc_url( $src ); + } + + function in_default_dir($src) { + if ( ! $this->default_dirs ) + return true; + + foreach ( (array) $this->default_dirs as $test ) { + if ( 0 === strpos($src, $test) ) + return true; + } + return false; + } + +} diff --git a/wp-includes/classes.php b/wp-includes/classes.php new file mode 100644 index 0000000..29c3753 --- /dev/null +++ b/wp-includes/classes.php @@ -0,0 +1,1595 @@ +public_query_vars) ) + $this->public_query_vars[] = $qv; + } + + /** + * Set the value of a query variable. + * + * @since 2.3.0 + * + * @param string $key Query variable name. + * @param mixed $value Query variable value. + */ + function set_query_var($key, $value) { + $this->query_vars[$key] = $value; + } + + /** + * Parse request to find correct WordPress query. + * + * Sets up the query variables based on the request. There are also many + * filters and actions that can be used to further manipulate the result. + * + * @since 2.0.0 + * + * @param array|string $extra_query_vars Set the extra query variables. + */ + function parse_request($extra_query_vars = '') { + global $wp_rewrite; + + $this->query_vars = array(); + $taxonomy_query_vars = array(); + + if ( is_array($extra_query_vars) ) + $this->extra_query_vars = & $extra_query_vars; + else if (! empty($extra_query_vars)) + parse_str($extra_query_vars, $this->extra_query_vars); + + // Process PATH_INFO, REQUEST_URI, and 404 for permalinks. + + // Fetch the rewrite rules. + $rewrite = $wp_rewrite->wp_rewrite_rules(); + + if (! empty($rewrite)) { + // If we match a rewrite rule, this will be cleared. + $error = '404'; + $this->did_permalink = true; + + if ( isset($_SERVER['PATH_INFO']) ) + $pathinfo = $_SERVER['PATH_INFO']; + else + $pathinfo = ''; + $pathinfo_array = explode('?', $pathinfo); + $pathinfo = str_replace("%", "%25", $pathinfo_array[0]); + $req_uri = $_SERVER['REQUEST_URI']; + $req_uri_array = explode('?', $req_uri); + $req_uri = $req_uri_array[0]; + $self = $_SERVER['PHP_SELF']; + $home_path = parse_url(get_option('home')); + if ( isset($home_path['path']) ) + $home_path = $home_path['path']; + else + $home_path = ''; + $home_path = trim($home_path, '/'); + + // Trim path info from the end and the leading home path from the + // front. For path info requests, this leaves us with the requesting + // filename, if any. For 404 requests, this leaves us with the + // requested permalink. + $req_uri = str_replace($pathinfo, '', rawurldecode($req_uri)); + $req_uri = trim($req_uri, '/'); + $req_uri = preg_replace("|^$home_path|", '', $req_uri); + $req_uri = trim($req_uri, '/'); + $pathinfo = trim($pathinfo, '/'); + $pathinfo = preg_replace("|^$home_path|", '', $pathinfo); + $pathinfo = trim($pathinfo, '/'); + $self = trim($self, '/'); + $self = preg_replace("|^$home_path|", '', $self); + $self = trim($self, '/'); + + // The requested permalink is in $pathinfo for path info requests and + // $req_uri for other requests. + if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) { + $request = $pathinfo; + } else { + // If the request uri is the index, blank it out so that we don't try to match it against a rule. + if ( $req_uri == $wp_rewrite->index ) + $req_uri = ''; + $request = $req_uri; + } + + $this->request = $request; + + // Look for matches. + $request_match = $request; + foreach ( (array) $rewrite as $match => $query) { + // Don't try to match against AtomPub calls + if ( $req_uri == 'wp-app.php' ) + break; + + // If the requesting file is the anchor of the match, prepend it + // to the path info. + if ((! empty($req_uri)) && (strpos($match, $req_uri) === 0) && ($req_uri != $request)) { + $request_match = $req_uri . '/' . $request; + } + + if (preg_match("#^$match#", $request_match, $matches) || + preg_match("#^$match#", urldecode($request_match), $matches)) { + // Got a match. + $this->matched_rule = $match; + + // Trim the query of everything up to the '?'. + $query = preg_replace("!^.+\?!", '', $query); + + // Substitute the substring matches into the query. + eval("@\$query = \"" . addslashes($query) . "\";"); + + $this->matched_query = $query; + + // Parse the query. + parse_str($query, $perma_query_vars); + + // If we're processing a 404 request, clear the error var + // since we found something. + if (isset($_GET['error'])) + unset($_GET['error']); + + if (isset($error)) + unset($error); + + break; + } + } + + // If req_uri is empty or if it is a request for ourself, unset error. + if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) { + if (isset($_GET['error'])) + unset($_GET['error']); + + if (isset($error)) + unset($error); + + if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) + unset($perma_query_vars); + + $this->did_permalink = false; + } + } + + $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars); + + foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) + if ( $t->query_var ) + $taxonomy_query_vars[$t->query_var] = $taxonomy; + + for ($i=0; $ipublic_query_vars); $i += 1) { + $wpvar = $this->public_query_vars[$i]; + if (isset($this->extra_query_vars[$wpvar])) + $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar]; + elseif (isset($GLOBALS[$wpvar])) + $this->query_vars[$wpvar] = $GLOBALS[$wpvar]; + elseif (!empty($_POST[$wpvar])) + $this->query_vars[$wpvar] = $_POST[$wpvar]; + elseif (!empty($_GET[$wpvar])) + $this->query_vars[$wpvar] = $_GET[$wpvar]; + elseif (!empty($perma_query_vars[$wpvar])) + $this->query_vars[$wpvar] = $perma_query_vars[$wpvar]; + + if ( !empty( $this->query_vars[$wpvar] ) ) { + $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar]; + if ( in_array( $wpvar, $taxonomy_query_vars ) ) { + $this->query_vars['taxonomy'] = $taxonomy_query_vars[$wpvar]; + $this->query_vars['term'] = $this->query_vars[$wpvar]; + } + } + } + + foreach ( (array) $this->private_query_vars as $var) { + if (isset($this->extra_query_vars[$var])) + $this->query_vars[$var] = $this->extra_query_vars[$var]; + elseif (isset($GLOBALS[$var]) && '' != $GLOBALS[$var]) + $this->query_vars[$var] = $GLOBALS[$var]; + } + + if ( isset($error) ) + $this->query_vars['error'] = $error; + + $this->query_vars = apply_filters('request', $this->query_vars); + + do_action_ref_array('parse_request', array(&$this)); + } + + /** + * Send additional HTTP headers for caching, content type, etc. + * + * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing + * a feed, it will also send last-modified, etag, and 304 status if needed. + * + * @since 2.0.0 + */ + function send_headers() { + $headers = array('X-Pingback' => get_bloginfo('pingback_url')); + $status = null; + $exit_required = false; + + if ( is_user_logged_in() ) + $headers = array_merge($headers, wp_get_nocache_headers()); + if ( !empty($this->query_vars['error']) && '404' == $this->query_vars['error'] ) { + $status = 404; + if ( !is_user_logged_in() ) + $headers = array_merge($headers, wp_get_nocache_headers()); + $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset'); + } else if ( empty($this->query_vars['feed']) ) { + $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset'); + } else { + // We're showing a feed, so WP is indeed the only thing that last changed + if ( !empty($this->query_vars['withcomments']) + || ( empty($this->query_vars['withoutcomments']) + && ( !empty($this->query_vars['p']) + || !empty($this->query_vars['name']) + || !empty($this->query_vars['page_id']) + || !empty($this->query_vars['pagename']) + || !empty($this->query_vars['attachment']) + || !empty($this->query_vars['attachment_id']) + ) + ) + ) + $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT'; + else + $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT'; + $wp_etag = '"' . md5($wp_last_modified) . '"'; + $headers['Last-Modified'] = $wp_last_modified; + $headers['ETag'] = $wp_etag; + + // Support for Conditional GET + if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) + $client_etag = stripslashes(stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])); + else $client_etag = false; + + $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']); + // If string is empty, return 0. If not, attempt to parse into a timestamp + $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0; + + // Make a timestamp for our most recent modification... + $wp_modified_timestamp = strtotime($wp_last_modified); + + if ( ($client_last_modified && $client_etag) ? + (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) : + (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) { + $status = 304; + $exit_required = true; + } + } + + $headers = apply_filters('wp_headers', $headers, $this); + + if ( ! empty( $status ) ) + status_header( $status ); + foreach( (array) $headers as $name => $field_value ) + @header("{$name}: {$field_value}"); + + if ($exit_required) + exit(); + + do_action_ref_array('send_headers', array(&$this)); + } + + /** + * Sets the query string property based off of the query variable property. + * + * The 'query_string' filter is deprecated, but still works. Plugins should + * use the 'request' filter instead. + * + * @since 2.0.0 + */ + function build_query_string() { + $this->query_string = ''; + foreach ( (array) array_keys($this->query_vars) as $wpvar) { + if ( '' != $this->query_vars[$wpvar] ) { + $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&'; + if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars. + continue; + $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]); + } + } + + // query_string filter deprecated. Use request filter instead. + if ( has_filter('query_string') ) { // Don't bother filtering and parsing if no plugins are hooked in. + $this->query_string = apply_filters('query_string', $this->query_string); + parse_str($this->query_string, $this->query_vars); + } + } + + /** + * Setup the WordPress Globals. + * + * The query_vars property will be extracted to the GLOBALS. So care should + * be taken when naming global variables that might interfere with the + * WordPress environment. + * + * @global string $query_string Query string for the loop. + * @global int $more Only set, if single page or post. + * @global int $single If single page or post. Only set, if single page or post. + * + * @since 2.0.0 + */ + function register_globals() { + global $wp_query; + // Extract updated query vars back into global namespace. + foreach ( (array) $wp_query->query_vars as $key => $value) { + $GLOBALS[$key] = $value; + } + + $GLOBALS['query_string'] = $this->query_string; + $GLOBALS['posts'] = & $wp_query->posts; + $GLOBALS['post'] = $wp_query->post; + $GLOBALS['request'] = $wp_query->request; + + if ( is_single() || is_page() ) { + $GLOBALS['more'] = 1; + $GLOBALS['single'] = 1; + } + } + + /** + * Setup the current user. + * + * @since 2.0.0 + */ + function init() { + wp_get_current_user(); + } + + /** + * Setup the Loop based on the query variables. + * + * @uses WP::$query_vars + * @since 2.0.0 + */ + function query_posts() { + global $wp_the_query; + $this->build_query_string(); + $wp_the_query->query($this->query_vars); + } + + /** + * Set the Headers for 404, if permalink is not found. + * + * Issue a 404 if a permalink request doesn't match any posts. Don't issue + * a 404 if one was already issued, if the request was a search, or if the + * request was a regular query string request rather than a permalink + * request. Issues a 200, if not 404. + * + * @since 2.0.0 + */ + function handle_404() { + global $wp_query; + + if ( (0 == count($wp_query->posts)) && !is_404() && !is_search() && ( $this->did_permalink || (!empty($_SERVER['QUERY_STRING']) && (false === strpos($_SERVER['REQUEST_URI'], '?'))) ) ) { + // Don't 404 for these queries if they matched an object. + if ( ( is_tag() || is_category() || is_author() ) && $wp_query->get_queried_object() ) { + if ( !is_404() ) + status_header( 200 ); + return; + } + $wp_query->set_404(); + status_header( 404 ); + nocache_headers(); + } elseif ( !is_404() ) { + status_header( 200 ); + } + } + + /** + * Sets up all of the variables required by the WordPress environment. + * + * The action 'wp' has one parameter that references the WP object. It + * allows for accessing the properties and methods to further manipulate the + * object. + * + * @since 2.0.0 + * + * @param string|array $query_args Passed to {@link parse_request()} + */ + function main($query_args = '') { + $this->init(); + $this->parse_request($query_args); + $this->send_headers(); + $this->query_posts(); + $this->handle_404(); + $this->register_globals(); + do_action_ref_array('wp', array(&$this)); + } + + /** + * PHP4 Constructor - Does nothing. + * + * Call main() method when ready to run setup. + * + * @since 2.0.0 + * + * @return WP + */ + function WP() { + // Empty. + } +} + +/** + * WordPress Error class. + * + * Container for checking for WordPress errors and error messages. Return + * WP_Error and use {@link is_wp_error()} to check if this class is returned. + * Many core WordPress functions pass this class in the event of an error and + * if not handled properly will result in code errors. + * + * @package WordPress + * @since 2.1.0 + */ +class WP_Error { + /** + * Stores the list of errors. + * + * @since 2.1.0 + * @var array + * @access private + */ + var $errors = array(); + + /** + * Stores the list of data for error codes. + * + * @since 2.1.0 + * @var array + * @access private + */ + var $error_data = array(); + + /** + * PHP4 Constructor - Sets up error message. + * + * If code parameter is empty then nothing will be done. It is possible to + * add multiple messages to the same code, but with other methods in the + * class. + * + * All parameters are optional, but if the code parameter is set, then the + * data parameter is optional. + * + * @since 2.1.0 + * + * @param string|int $code Error code + * @param string $message Error message + * @param mixed $data Optional. Error data. + * @return WP_Error + */ + function WP_Error($code = '', $message = '', $data = '') { + if ( empty($code) ) + return; + + $this->errors[$code][] = $message; + + if ( ! empty($data) ) + $this->error_data[$code] = $data; + } + + /** + * Retrieve all error codes. + * + * @since 2.1.0 + * @access public + * + * @return array List of error codes, if avaiable. + */ + function get_error_codes() { + if ( empty($this->errors) ) + return array(); + + return array_keys($this->errors); + } + + /** + * Retrieve first error code available. + * + * @since 2.1.0 + * @access public + * + * @return string|int Empty string, if no error codes. + */ + function get_error_code() { + $codes = $this->get_error_codes(); + + if ( empty($codes) ) + return ''; + + return $codes[0]; + } + + /** + * Retrieve all error messages or error messages matching code. + * + * @since 2.1.0 + * + * @param string|int $code Optional. Retrieve messages matching code, if exists. + * @return array Error strings on success, or empty array on failure (if using codee parameter). + */ + function get_error_messages($code = '') { + // Return all messages if no code specified. + if ( empty($code) ) { + $all_messages = array(); + foreach ( (array) $this->errors as $code => $messages ) + $all_messages = array_merge($all_messages, $messages); + + return $all_messages; + } + + if ( isset($this->errors[$code]) ) + return $this->errors[$code]; + else + return array(); + } + + /** + * Get single error message. + * + * This will get the first message available for the code. If no code is + * given then the first code available will be used. + * + * @since 2.1.0 + * + * @param string|int $code Optional. Error code to retrieve message. + * @return string + */ + function get_error_message($code = '') { + if ( empty($code) ) + $code = $this->get_error_code(); + $messages = $this->get_error_messages($code); + if ( empty($messages) ) + return ''; + return $messages[0]; + } + + /** + * Retrieve error data for error code. + * + * @since 2.1.0 + * + * @param string|int $code Optional. Error code. + * @return mixed Null, if no errors. + */ + function get_error_data($code = '') { + if ( empty($code) ) + $code = $this->get_error_code(); + + if ( isset($this->error_data[$code]) ) + return $this->error_data[$code]; + return null; + } + + /** + * Append more error messages to list of error messages. + * + * @since 2.1.0 + * @access public + * + * @param string|int $code Error code. + * @param string $message Error message. + * @param mixed $data Optional. Error data. + */ + function add($code, $message, $data = '') { + $this->errors[$code][] = $message; + if ( ! empty($data) ) + $this->error_data[$code] = $data; + } + + /** + * Add data for error code. + * + * The error code can only contain one error data. + * + * @since 2.1.0 + * + * @param mixed $data Error data. + * @param string|int $code Error code. + */ + function add_data($data, $code = '') { + if ( empty($code) ) + $code = $this->get_error_code(); + + $this->error_data[$code] = $data; + } +} + +/** + * Check whether variable is a WordPress Error. + * + * Looks at the object and if a WP_Error class. Does not check to see if the + * parent is also WP_Error, so can't inherit WP_Error and still use this + * function. + * + * @since 2.1.0 + * + * @param mixed $thing Check if unknown variable is WordPress Error object. + * @return bool True, if WP_Error. False, if not WP_Error. + */ +function is_wp_error($thing) { + if ( is_object($thing) && is_a($thing, 'WP_Error') ) + return true; + return false; +} + +/** + * A class for displaying various tree-like structures. + * + * Extend the Walker class to use it, see examples at the below. Child classes + * do not need to implement all of the abstract methods in the class. The child + * only needs to implement the methods that are needed. Also, the methods are + * not strictly abstract in that the parameter definition needs to be followed. + * The child classes can have additional parameters. + * + * @package WordPress + * @since 2.1.0 + * @abstract + */ +class Walker { + /** + * What the class handles. + * + * @since 2.1.0 + * @var string + * @access public + */ + var $tree_type; + + /** + * DB fields to use. + * + * @since 2.1.0 + * @var array + * @access protected + */ + var $db_fields; + + /** + * Max number of pages walked by the paged walker + * + * @since 2.7.0 + * @var int + * @access protected + */ + var $max_pages = 1; + + /** + * Starts the list before the elements are added. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. This + * method is called at the start of the output list. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function start_lvl(&$output) {} + + /** + * Ends the list of after the elements are added. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. This + * method finishes the list at the end of output of the elements. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function end_lvl(&$output) {} + + /** + * Start the element output. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. Includes + * the element output also. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function start_el(&$output) {} + + /** + * Ends the element output, if needed. + * + * Additional parameters are used in child classes. The args parameter holds + * additional values that may be used with the child class methods. + * + * @since 2.1.0 + * @abstract + * + * @param string $output Passed by reference. Used to append additional content. + */ + function end_el(&$output) {} + + /** + * Traverse elements to create list from elements. + * + * Display one element if the element doesn't have any children otherwise, + * display the element and its children. Will only traverse up to the max + * depth and no ignore elements under that depth. It is possible to set the + * max depth to include all depths, see walk() method. + * + * This method shouldn't be called directly, use the walk() method instead. + * + * @since 2.5.0 + * + * @param object $element Data object + * @param array $children_elements List of elements to continue traversing. + * @param int $max_depth Max depth to traverse. + * @param int $depth Depth of current element. + * @param array $args + * @param string $output Passed by reference. Used to append additional content. + * @return null Null on failure with no changes to parameters. + */ + function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { + + if ( !$element ) + return; + + $id_field = $this->db_fields['id']; + + //display this element + if ( is_array( $args[0] ) ) + $args[0]['has_children'] = ! empty( $children_elements[$element->$id_field] ); + $cb_args = array_merge( array(&$output, $element, $depth), $args); + call_user_func_array(array(&$this, 'start_el'), $cb_args); + + $id = $element->$id_field; + + // descend only when the depth is right and there are childrens for this element + if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) { + + foreach( $children_elements[ $id ] as $child ){ + + if ( !isset($newlevel) ) { + $newlevel = true; + //start the child delimiter + $cb_args = array_merge( array(&$output, $depth), $args); + call_user_func_array(array(&$this, 'start_lvl'), $cb_args); + } + $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output ); + } + unset( $children_elements[ $id ] ); + } + + if ( isset($newlevel) && $newlevel ){ + //end the child delimiter + $cb_args = array_merge( array(&$output, $depth), $args); + call_user_func_array(array(&$this, 'end_lvl'), $cb_args); + } + + //end this element + $cb_args = array_merge( array(&$output, $element, $depth), $args); + call_user_func_array(array(&$this, 'end_el'), $cb_args); + } + + /** + * Display array of elements hierarchically. + * + * It is a generic function which does not assume any existing order of + * elements. max_depth = -1 means flatly display every element. max_depth = + * 0 means display all levels. max_depth > 0 specifies the number of + * display levels. + * + * @since 2.1.0 + * + * @param array $elements + * @param int $max_depth + * @return string + */ + function walk( $elements, $max_depth) { + + $args = array_slice(func_get_args(), 2); + $output = ''; + + if ($max_depth < -1) //invalid parameter + return $output; + + if (empty($elements)) //nothing to walk + return $output; + + $id_field = $this->db_fields['id']; + $parent_field = $this->db_fields['parent']; + + // flat display + if ( -1 == $max_depth ) { + $empty_array = array(); + foreach ( $elements as $e ) + $this->display_element( $e, $empty_array, 1, 0, $args, $output ); + return $output; + } + + /* + * need to display in hierarchical order + * seperate elements into two buckets: top level and children elements + * children_elements is two dimensional array, eg. + * children_elements[10][] contains all sub-elements whose parent is 10. + */ + $top_level_elements = array(); + $children_elements = array(); + foreach ( $elements as $e) { + if ( 0 == $e->$parent_field ) + $top_level_elements[] = $e; + else + $children_elements[ $e->$parent_field ][] = $e; + } + + /* + * when none of the elements is top level + * assume the first one must be root of the sub elements + */ + if ( empty($top_level_elements) ) { + + $first = array_slice( $elements, 0, 1 ); + $root = $first[0]; + + $top_level_elements = array(); + $children_elements = array(); + foreach ( $elements as $e) { + if ( $root->$parent_field == $e->$parent_field ) + $top_level_elements[] = $e; + else + $children_elements[ $e->$parent_field ][] = $e; + } + } + + foreach ( $top_level_elements as $e ) + $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); + + /* + * if we are displaying all levels, and remaining children_elements is not empty, + * then we got orphans, which should be displayed regardless + */ + if ( ( $max_depth == 0 ) && count( $children_elements ) > 0 ) { + $empty_array = array(); + foreach ( $children_elements as $orphans ) + foreach( $orphans as $op ) + $this->display_element( $op, $empty_array, 1, 0, $args, $output ); + } + + return $output; + } + + /** + * paged_walk() - produce a page of nested elements + * + * Given an array of hierarchical elements, the maximum depth, a specific page number, + * and number of elements per page, this function first determines all top level root elements + * belonging to that page, then lists them and all of their children in hierarchical order. + * + * @package WordPress + * @since 2.7 + * @param $max_depth = 0 means display all levels; $max_depth > 0 specifies the number of display levels. + * @param $page_num the specific page number, beginning with 1. + * @return XHTML of the specified page of elements + */ + function paged_walk( $elements, $max_depth, $page_num, $per_page ) { + + /* sanity check */ + if ( empty($elements) || $max_depth < -1 ) + return ''; + + $args = array_slice( func_get_args(), 4 ); + $output = ''; + + $id_field = $this->db_fields['id']; + $parent_field = $this->db_fields['parent']; + + $count = -1; + if ( -1 == $max_depth ) + $total_top = count( $elements ); + if ( $page_num < 1 || $per_page < 0 ) { + // No paging + $paging = false; + $start = 0; + if ( -1 == $max_depth ) + $end = $total_top; + $this->max_pages = 1; + } else { + $paging = true; + $start = ( (int)$page_num - 1 ) * (int)$per_page; + $end = $start + $per_page; + if ( -1 == $max_depth ) + $this->max_pages = ceil($total_top / $per_page); + } + + // flat display + if ( -1 == $max_depth ) { + if ( !empty($args[0]['reverse_top_level']) ) { + $elements = array_reverse( $elements ); + $oldstart = $start; + $start = $total_top - $end; + $end = $total_top - $oldstart; + } + + $empty_array = array(); + foreach ( $elements as $e ) { + $count++; + if ( $count < $start ) + continue; + if ( $count >= $end ) + break; + $this->display_element( $e, $empty_array, 1, 0, $args, $output ); + } + return $output; + } + + /* + * seperate elements into two buckets: top level and children elements + * children_elements is two dimensional array, eg. + * children_elements[10][] contains all sub-elements whose parent is 10. + */ + $top_level_elements = array(); + $children_elements = array(); + foreach ( $elements as $e) { + if ( 0 == $e->$parent_field ) + $top_level_elements[] = $e; + else + $children_elements[ $e->$parent_field ][] = $e; + } + + $total_top = count( $top_level_elements ); + if ( $paging ) + $this->max_pages = ceil($total_top / $per_page); + else + $end = $total_top; + + if ( !empty($args[0]['reverse_top_level']) ) { + $top_level_elements = array_reverse( $top_level_elements ); + $oldstart = $start; + $start = $total_top - $end; + $end = $total_top - $oldstart; + } + if ( !empty($args[0]['reverse_children']) ) { + foreach ( $children_elements as $parent => $children ) + $children_elements[$parent] = array_reverse( $children ); + } + + foreach ( $top_level_elements as $e ) { + $count++; + + //for the last page, need to unset earlier children in order to keep track of orphans + if ( $end >= $total_top && $count < $start ) + $this->unset_children( $e, $children_elements ); + + if ( $count < $start ) + continue; + + if ( $count >= $end ) + break; + + $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); + } + + if ( $end >= $total_top && count( $children_elements ) > 0 ) { + $empty_array = array(); + foreach ( $children_elements as $orphans ) + foreach( $orphans as $op ) + $this->display_element( $op, $empty_array, 1, 0, $args, $output ); + } + + return $output; + } + + function get_number_of_root_elements( $elements ){ + + $num = 0; + $parent_field = $this->db_fields['parent']; + + foreach ( $elements as $e) { + if ( 0 == $e->$parent_field ) + $num++; + } + return $num; + } + + // unset all the children for a given top level element + function unset_children( $e, &$children_elements ){ + + if ( !$e || !$children_elements ) + return; + + $id_field = $this->db_fields['id']; + $id = $e->$id_field; + + if ( !empty($children_elements[$id]) && is_array($children_elements[$id]) ) + foreach ( (array) $children_elements[$id] as $child ) + $this->unset_children( $child, $children_elements ); + + if ( isset($children_elements[$id]) ) + unset( $children_elements[$id] ); + + } +} + +/** + * Create HTML list of pages. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_Page extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'page'; + + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this. + * @var array + */ + var $db_fields = array ('parent' => 'post_parent', 'id' => 'ID'); + + /** + * @see Walker::start_lvl() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of page. Used for padding. + */ + function start_lvl(&$output, $depth) { + $indent = str_repeat("\t", $depth); + $output .= "\n$indent
      \n"; + } + + /** + * @see Walker::end_lvl() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of page. Used for padding. + */ + function end_lvl(&$output, $depth) { + $indent = str_repeat("\t", $depth); + $output .= "$indent
    \n"; + } + + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Page data object. + * @param int $depth Depth of page. Used for padding. + * @param int $current_page Page ID. + * @param array $args + */ + function start_el(&$output, $page, $depth, $args, $current_page) { + if ( $depth ) + $indent = str_repeat("\t", $depth); + else + $indent = ''; + + extract($args, EXTR_SKIP); + $css_class = array('page_item', 'page-item-'.$page->ID); + if ( !empty($current_page) ) { + $_current_page = get_page( $current_page ); + if ( isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors) ) + $css_class[] = 'current_page_ancestor'; + if ( $page->ID == $current_page ) + $css_class[] = 'current_page_item'; + elseif ( $_current_page && $page->ID == $_current_page->post_parent ) + $css_class[] = 'current_page_parent'; + } elseif ( $page->ID == get_option('page_for_posts') ) { + $css_class[] = 'current_page_parent'; + } + + $css_class = implode(' ', apply_filters('page_css_class', $css_class, $page)); + + $output .= $indent . '
  • ' . $link_before . apply_filters('the_title', $page->post_title) . $link_after . ''; + + if ( !empty($show_date) ) { + if ( 'modified' == $show_date ) + $time = $page->post_modified; + else + $time = $page->post_date; + + $output .= " " . mysql2date($date_format, $time); + } + } + + /** + * @see Walker::end_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Page data object. Not used. + * @param int $depth Depth of page. Not Used. + */ + function end_el(&$output, $page, $depth) { + $output .= "
  • \n"; + } + +} + +/** + * Create HTML dropdown list of pages. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_PageDropdown extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'page'; + + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this + * @var array + */ + var $db_fields = array ('parent' => 'post_parent', 'id' => 'ID'); + + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Page data object. + * @param int $depth Depth of page in reference to parent pages. Used for padding. + * @param array $args Uses 'selected' argument for selected page to set selected HTML attribute for option element. + */ + function start_el(&$output, $page, $depth, $args) { + $pad = str_repeat(' ', $depth * 3); + + $output .= "\t\n"; + } +} + +/** + * Create HTML list of categories. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_Category extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'category'; + + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this + * @var array + */ + var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); + + /** + * @see Walker::start_lvl() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of category. Used for tab indentation. + * @param array $args Will only append content if style argument value is 'list'. + */ + function start_lvl(&$output, $depth, $args) { + if ( 'list' != $args['style'] ) + return; + + $indent = str_repeat("\t", $depth); + $output .= "$indent
      \n"; + } + + /** + * @see Walker::end_lvl() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of category. Used for tab indentation. + * @param array $args Will only append content if style argument value is 'list'. + */ + function end_lvl(&$output, $depth, $args) { + if ( 'list' != $args['style'] ) + return; + + $indent = str_repeat("\t", $depth); + $output .= "$indent
    \n"; + } + + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $category Category data object. + * @param int $depth Depth of category in reference to parents. + * @param array $args + */ + function start_el(&$output, $category, $depth, $args) { + extract($args); + + $cat_name = esc_attr( $category->name); + $cat_name = apply_filters( 'list_cats', $cat_name, $category ); + $link = 'description) ) + $link .= 'title="' . sprintf(__( 'View all posts filed under %s' ), $cat_name) . '"'; + else + $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"'; + $link .= '>'; + $link .= $cat_name . ''; + + if ( (! empty($feed_image)) || (! empty($feed)) ) { + $link .= ' '; + + if ( empty($feed_image) ) + $link .= '('; + + $link .= ''; + $link .= ''; + if ( empty($feed_image) ) + $link .= ')'; + } + + if ( isset($show_count) && $show_count ) + $link .= ' (' . intval($category->count) . ')'; + + if ( isset($show_date) && $show_date ) { + $link .= ' ' . gmdate('Y-m-d', $category->last_update_timestamp); + } + + if ( isset($current_category) && $current_category ) + $_current_category = get_category( $current_category ); + + if ( 'list' == $args['style'] ) { + $output .= "\tterm_id; + if ( isset($current_category) && $current_category && ($category->term_id == $current_category) ) + $class .= ' current-cat'; + elseif ( isset($_current_category) && $_current_category && ($category->term_id == $_current_category->parent) ) + $class .= ' current-cat-parent'; + $output .= ' class="'.$class.'"'; + $output .= ">$link\n"; + } else { + $output .= "\t$link
    \n"; + } + } + + /** + * @see Walker::end_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $page Not used. + * @param int $depth Depth of category. Not used. + * @param array $args Only uses 'list' for whether should append to output. + */ + function end_el(&$output, $page, $depth, $args) { + if ( 'list' != $args['style'] ) + return; + + $output .= "\n"; + } + +} + +/** + * Create HTML dropdown list of Categories. + * + * @package WordPress + * @since 2.1.0 + * @uses Walker + */ +class Walker_CategoryDropdown extends Walker { + /** + * @see Walker::$tree_type + * @since 2.1.0 + * @var string + */ + var $tree_type = 'category'; + + /** + * @see Walker::$db_fields + * @since 2.1.0 + * @todo Decouple this + * @var array + */ + var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); + + /** + * @see Walker::start_el() + * @since 2.1.0 + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $category Category data object. + * @param int $depth Depth of category. Used for padding. + * @param array $args Uses 'selected', 'show_count', and 'show_last_update' keys, if they exist. + */ + function start_el(&$output, $category, $depth, $args) { + $pad = str_repeat(' ', $depth * 3); + + $cat_name = apply_filters('list_cats', $category->name, $category); + $output .= "\t\n"; + } +} + +/** + * Send XML response back to AJAX request. + * + * @package WordPress + * @since 2.1.0 + */ +class WP_Ajax_Response { + /** + * Store XML responses to send. + * + * @since 2.1.0 + * @var array + * @access private + */ + var $responses = array(); + + /** + * PHP4 Constructor - Passes args to {@link WP_Ajax_Response::add()}. + * + * @since 2.1.0 + * @see WP_Ajax_Response::add() + * + * @param string|array $args Optional. Will be passed to add() method. + * @return WP_Ajax_Response + */ + function WP_Ajax_Response( $args = '' ) { + if ( !empty($args) ) + $this->add($args); + } + + /** + * Append to XML response based on given arguments. + * + * The arguments that can be passed in the $args parameter are below. It is + * also possible to pass a WP_Error object in either the 'id' or 'data' + * argument. The parameter isn't actually optional, content should be given + * in order to send the correct response. + * + * 'what' argument is a string that is the XMLRPC response type. + * 'action' argument is a boolean or string that acts like a nonce. + * 'id' argument can be WP_Error or an integer. + * 'old_id' argument is false by default or an integer of the previous ID. + * 'position' argument is an integer or a string with -1 = top, 1 = bottom, + * html ID = after, -html ID = before. + * 'data' argument is a string with the content or message. + * 'supplemental' argument is an array of strings that will be children of + * the supplemental element. + * + * @since 2.1.0 + * + * @param string|array $args Override defaults. + * @return string XML response. + */ + function add( $args = '' ) { + $defaults = array( + 'what' => 'object', 'action' => false, + 'id' => '0', 'old_id' => false, + 'position' => 1, + 'data' => '', 'supplemental' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + $position = preg_replace( '/[^a-z0-9:_-]/i', '', $position ); + + if ( is_wp_error($id) ) { + $data = $id; + $id = 0; + } + + $response = ''; + if ( is_wp_error($data) ) { + foreach ( (array) $data->get_error_codes() as $code ) { + $response .= "get_error_message($code) . "]]>"; + if ( !$error_data = $data->get_error_data($code) ) + continue; + $class = ''; + if ( is_object($error_data) ) { + $class = ' class="' . get_class($error_data) . '"'; + $error_data = get_object_vars($error_data); + } + + $response .= ""; + + if ( is_scalar($error_data) ) { + $response .= ""; + } elseif ( is_array($error_data) ) { + foreach ( $error_data as $k => $v ) + $response .= "<$k>"; + } + + $response .= ""; + } + } else { + $response = ""; + } + + $s = ''; + if ( is_array($supplemental) ) { + foreach ( $supplemental as $k => $v ) + $s .= "<$k>"; + $s = "$s"; + } + + if ( false === $action ) + $action = $_POST['action']; + + $x = ''; + $x .= ""; // The action attribute in the xml output is formatted like a nonce action + $x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>"; + $x .= $response; + $x .= $s; + $x .= ""; + $x .= ""; + + $this->responses[] = $x; + return $x; + } + + /** + * Display XML formatted responses. + * + * Sets the content type header to text/xml. + * + * @since 2.1.0 + */ + function send() { + header('Content-Type: text/xml'); + echo ""; + foreach ( (array) $this->responses as $response ) + echo $response; + echo ''; + die(); + } +} + +?> diff --git a/wp-includes/comment-template.php b/wp-includes/comment-template.php new file mode 100644 index 0000000..e87801b --- /dev/null +++ b/wp-includes/comment-template.php @@ -0,0 +1,1397 @@ +comment_author) ) { + if (!empty($comment->user_id)){ + $user=get_userdata($comment->user_id); + $author=$user->user_login; + } else { + $author = __('Anonymous'); + } + } else { + $author = $comment->comment_author; + } + return apply_filters('get_comment_author', $author); +} + +/** + * Displays the author of the current comment. + * + * @since 0.71 + * @uses apply_filters() Calls 'comment_author' on comment author before displaying + */ +function comment_author() { + $author = apply_filters('comment_author', get_comment_author() ); + echo $author; +} + +/** + * Retrieve the email of the author of the current comment. + * + * @since 1.5.0 + * @uses apply_filters() Calls the 'get_comment_author_email' hook on the comment author email + * @uses $comment + * + * @return string The current comment author's email + */ +function get_comment_author_email() { + global $comment; + return apply_filters('get_comment_author_email', $comment->comment_author_email); +} + +/** + * Display the email of the author of the current global $comment. + * + * Care should be taken to protect the email address and assure that email + * harvesters do not capture your commentors' email address. Most assume that + * their email address will not appear in raw form on the blog. Doing so will + * enable anyone, including those that people don't want to get the email + * address and use it for their own means good and bad. + * + * @since 0.71 + * @uses apply_filters() Calls 'author_email' hook on the author email + */ +function comment_author_email() { + echo apply_filters('author_email', get_comment_author_email() ); +} + +/** + * Display the html email link to the author of the current comment. + * + * Care should be taken to protect the email address and assure that email + * harvesters do not capture your commentors' email address. Most assume that + * their email address will not appear in raw form on the blog. Doing so will + * enable anyone, including those that people don't want to get the email + * address and use it for their own means good and bad. + * + * @since 0.71 + * @uses apply_filters() Calls 'comment_email' hook for the display of the comment author's email + * @uses get_comment_author_email_link() For generating the link + * @global object $comment The current Comment row object + * + * @param string $linktext The text to display instead of the comment author's email address + * @param string $before The text or HTML to display before the email link. + * @param string $after The text or HTML to display after the email link. + */ +function comment_author_email_link($linktext='', $before='', $after='') { + if ( $link = get_comment_author_email_link( $linktext, $before, $after ) ) + echo $link; +} + +/** + * Return the html email link to the author of the current comment. + * + * Care should be taken to protect the email address and assure that email + * harvesters do not capture your commentors' email address. Most assume that + * their email address will not appear in raw form on the blog. Doing so will + * enable anyone, including those that people don't want to get the email + * address and use it for their own means good and bad. + * + * @since 2.7 + * @uses apply_filters() Calls 'comment_email' hook for the display of the comment author's email + * @global object $comment The current Comment row object + * + * @param string $linktext The text to display instead of the comment author's email address + * @param string $before The text or HTML to display before the email link. + * @param string $after The text or HTML to display after the email link. + */ +function get_comment_author_email_link($linktext='', $before='', $after='') { + global $comment; + $email = apply_filters('comment_email', $comment->comment_author_email); + if ((!empty($email)) && ($email != '@')) { + $display = ($linktext != '') ? $linktext : $email; + $return = $before; + $return .= "$display"; + $return .= $after; + return $return; + } else { + return ''; + } +} + +/** + * Retrieve the html link to the url of the author of the current comment. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'get_comment_author_link' hook on the complete link HTML or author + * + * @return string Comment Author name or HTML link for author's URL + */ +function get_comment_author_link() { + /** @todo Only call these functions when they are needed. Include in if... else blocks */ + $url = get_comment_author_url(); + $author = get_comment_author(); + + if ( empty( $url ) || 'http://' == $url ) + $return = $author; + else + $return = "$author"; + return apply_filters('get_comment_author_link', $return); +} + +/** + * Display the html link to the url of the author of the current comment. + * + * @since 0.71 + * @see get_comment_author_link() Echos result + */ +function comment_author_link() { + echo get_comment_author_link(); +} + +/** + * Retrieve the IP address of the author of the current comment. + * + * @since 1.5.0 + * @uses $comment + * @uses apply_filters() + * + * @return unknown + */ +function get_comment_author_IP() { + global $comment; + return apply_filters('get_comment_author_IP', $comment->comment_author_IP); +} + +/** + * Display the IP address of the author of the current comment. + * + * @since 0.71 + * @see get_comment_author_IP() Echos Result + */ +function comment_author_IP() { + echo get_comment_author_IP(); +} + +/** + * Retrieve the url of the author of the current comment. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'get_comment_author_url' hook on the comment author's URL + * + * @return string + */ +function get_comment_author_url() { + global $comment; + $url = ('http://' == $comment->comment_author_url) ? '' : $comment->comment_author_url; + $url = esc_url( $url, array('http', 'https') ); + return apply_filters('get_comment_author_url', $url); +} + +/** + * Display the url of the author of the current comment. + * + * @since 0.71 + * @uses apply_filters() + * @uses get_comment_author_url() Retrieves the comment author's URL + */ +function comment_author_url() { + echo apply_filters('comment_url', get_comment_author_url()); +} + +/** + * Retrieves the HTML link of the url of the author of the current comment. + * + * $linktext parameter is only used if the URL does not exist for the comment + * author. If the URL does exist then the URL will be used and the $linktext + * will be ignored. + * + * Encapsulate the HTML link between the $before and $after. So it will appear + * in the order of $before, link, and finally $after. + * + * @since 1.5.0 + * @uses apply_filters() Calls the 'get_comment_author_url_link' on the complete HTML before returning. + * + * @param string $linktext The text to display instead of the comment author's email address + * @param string $before The text or HTML to display before the email link. + * @param string $after The text or HTML to display after the email link. + * @return string The HTML link between the $before and $after parameters + */ +function get_comment_author_url_link( $linktext = '', $before = '', $after = '' ) { + $url = get_comment_author_url(); + $display = ($linktext != '') ? $linktext : $url; + $display = str_replace( 'http://www.', '', $display ); + $display = str_replace( 'http://', '', $display ); + if ( '/' == substr($display, -1) ) + $display = substr($display, 0, -1); + $return = "$before$display$after"; + return apply_filters('get_comment_author_url_link', $return); +} + +/** + * Displays the HTML link of the url of the author of the current comment. + * + * @since 0.71 + * @see get_comment_author_url_link() Echos result + * + * @param string $linktext The text to display instead of the comment author's email address + * @param string $before The text or HTML to display before the email link. + * @param string $after The text or HTML to display after the email link. + */ +function comment_author_url_link( $linktext = '', $before = '', $after = '' ) { + echo get_comment_author_url_link( $linktext, $before, $after ); +} + +/** + * Generates semantic classes for each comment element + * + * @since 2.7.0 + * + * @param string|array $class One or more classes to add to the class list + * @param int $comment_id An optional comment ID + * @param int $post_id An optional post ID + * @param bool $echo Whether comment_class should echo or return + */ +function comment_class( $class = '', $comment_id = null, $post_id = null, $echo = true ) { + // Separates classes with a single space, collates classes for comment DIV + $class = 'class="' . join( ' ', get_comment_class( $class, $comment_id, $post_id ) ) . '"'; + if ( $echo) + echo $class; + else + return $class; +} + +/** + * Returns the classes for the comment div as an array + * + * @since 2.7.0 + * + * @param string|array $class One or more classes to add to the class list + * @param int $comment_id An optional comment ID + * @param int $post_id An optional post ID + * @return array Array of classes + */ +function get_comment_class( $class = '', $comment_id = null, $post_id = null ) { + global $comment_alt, $comment_depth, $comment_thread_alt; + + $comment = get_comment($comment_id); + + $classes = array(); + + // Get the comment type (comment, trackback), + $classes[] = ( empty( $comment->comment_type ) ) ? 'comment' : $comment->comment_type; + + // If the comment author has an id (registered), then print the log in name + if ( $comment->user_id > 0 && $user = get_userdata($comment->user_id) ) { + // For all registered users, 'byuser' + $classes[] = 'byuser'; + $classes[] = 'comment-author-' . sanitize_html_class($user->user_nicename, $comment->user_id); + // For comment authors who are the author of the post + if ( $post = get_post($post_id) ) { + if ( $comment->user_id === $post->post_author ) + $classes[] = 'bypostauthor'; + } + } + + if ( empty($comment_alt) ) + $comment_alt = 0; + if ( empty($comment_depth) ) + $comment_depth = 1; + if ( empty($comment_thread_alt) ) + $comment_thread_alt = 0; + + if ( $comment_alt % 2 ) { + $classes[] = 'odd'; + $classes[] = 'alt'; + } else { + $classes[] = 'even'; + } + + $comment_alt++; + + // Alt for top-level comments + if ( 1 == $comment_depth ) { + if ( $comment_thread_alt % 2 ) { + $classes[] = 'thread-odd'; + $classes[] = 'thread-alt'; + } else { + $classes[] = 'thread-even'; + } + $comment_thread_alt++; + } + + $classes[] = "depth-$comment_depth"; + + if ( !empty($class) ) { + if ( !is_array( $class ) ) + $class = preg_split('#\s+#', $class); + $classes = array_merge($classes, $class); + } + + return apply_filters('comment_class', $classes, $class, $comment_id, $post_id); +} + +/** + * Retrieve the comment date of the current comment. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'get_comment_date' hook with the formated date and the $d parameter respectively + * @uses $comment + * + * @param string $d The format of the date (defaults to user's config) + * @return string The comment's date + */ +function get_comment_date( $d = '' ) { + global $comment; + if ( '' == $d ) + $date = mysql2date(get_option('date_format'), $comment->comment_date); + else + $date = mysql2date($d, $comment->comment_date); + return apply_filters('get_comment_date', $date, $d); +} + +/** + * Display the comment date of the current comment. + * + * @since 0.71 + * + * @param string $d The format of the date (defaults to user's config) + */ +function comment_date( $d = '' ) { + echo get_comment_date( $d ); +} + +/** + * Retrieve the excerpt of the current comment. + * + * Will cut each word and only output the first 20 words with '...' at the end. + * If the word count is less than 20, then no truncating is done and no '...' + * will appear. + * + * @since 1.5.0 + * @uses $comment + * @uses apply_filters() Calls 'get_comment_excerpt' on truncated comment + * + * @return string The maybe truncated comment with 20 words or less + */ +function get_comment_excerpt() { + global $comment; + $comment_text = strip_tags($comment->comment_content); + $blah = explode(' ', $comment_text); + if (count($blah) > 20) { + $k = 20; + $use_dotdotdot = 1; + } else { + $k = count($blah); + $use_dotdotdot = 0; + } + $excerpt = ''; + for ($i=0; $i<$k; $i++) { + $excerpt .= $blah[$i] . ' '; + } + $excerpt .= ($use_dotdotdot) ? '...' : ''; + return apply_filters('get_comment_excerpt', $excerpt); +} + +/** + * Display the excerpt of the current comment. + * + * @since 1.2.0 + * @uses apply_filters() Calls 'comment_excerpt' hook before displaying excerpt + */ +function comment_excerpt() { + echo apply_filters('comment_excerpt', get_comment_excerpt() ); +} + +/** + * Retrieve the comment id of the current comment. + * + * @since 1.5.0 + * @uses $comment + * @uses apply_filters() Calls the 'get_comment_ID' hook for the comment ID + * + * @return int The comment ID + */ +function get_comment_ID() { + global $comment; + return apply_filters('get_comment_ID', $comment->comment_ID); +} + +/** + * Displays the comment id of the current comment. + * + * @since 0.71 + * @see get_comment_ID() Echos Result + */ +function comment_ID() { + echo get_comment_ID(); +} + +/** + * Retrieve the link to a given comment. + * + * @since 1.5.0 + * @uses $comment + * + * @param object|string|int $comment Comment to retrieve. + * @param array $args Optional args. + * @return string The permalink to the given comment. + */ +function get_comment_link( $comment = null, $args = array() ) { + global $wp_rewrite, $in_comment_loop; + + $comment = get_comment($comment); + + // Backwards compat + if ( !is_array($args) ) { + $page = $args; + $args = array(); + $args['page'] = $page; + } + + $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' ); + $args = wp_parse_args( $args, $defaults ); + + if ( '' === $args['per_page'] && get_option('page_comments') ) + $args['per_page'] = get_option('comments_per_page'); + + if ( empty($args['per_page']) ) { + $args['per_page'] = 0; + $args['page'] = 0; + } + + if ( $args['per_page'] ) { + if ( '' == $args['page'] ) + $args['page'] = ( !empty($in_comment_loop) ) ? get_query_var('cpage') : get_page_of_comment( $comment->comment_ID, $args ); + + if ( $wp_rewrite->using_permalinks() ) + $link = user_trailingslashit( trailingslashit( get_permalink( $comment->comment_post_ID ) ) . 'comment-page-' . $args['page'], 'comment' ); + else + $link = add_query_arg( 'cpage', $args['page'], get_permalink( $comment->comment_post_ID ) ); + } else { + $link = get_permalink( $comment->comment_post_ID ); + } + + return apply_filters( 'get_comment_link', $link . '#comment-' . $comment->comment_ID, $comment, $args ); +} + +/** + * Retrieves the link to the current post comments. + * + * @since 1.5.0 + * + * @return string The link to the comments + */ +function get_comments_link() { + return get_permalink() . '#comments'; +} + +/** + * Displays the link to the current post comments. + * + * @since 0.71 + * + * @param string $deprecated Not Used + * @param bool $deprecated Not Used + */ +function comments_link( $deprecated = '', $deprecated = '' ) { + echo get_comments_link(); +} + +/** + * Retrieve the amount of comments a post has. + * + * @since 1.5.0 + * @uses apply_filters() Calls the 'get_comments_number' hook on the number of comments + * + * @param int $post_id The Post ID + * @return int The number of comments a post has + */ +function get_comments_number( $post_id = 0 ) { + global $id; + $post_id = (int) $post_id; + + if ( !$post_id ) + $post_id = (int) $id; + + $post = get_post($post_id); + if ( ! isset($post->comment_count) ) + $count = 0; + else + $count = $post->comment_count; + + return apply_filters('get_comments_number', $count); +} + +/** + * Display the language string for the number of comments the current post has. + * + * @since 0.71 + * @uses $id + * @uses apply_filters() Calls the 'comments_number' hook on the output and number of comments respectively. + * + * @param string $zero Text for no comments + * @param string $one Text for one comment + * @param string $more Text for more than one comment + * @param string $deprecated Not used. + */ +function comments_number( $zero = false, $one = false, $more = false, $deprecated = '' ) { + global $id; + $number = get_comments_number($id); + + if ( $number > 1 ) + $output = str_replace('%', number_format_i18n($number), ( false === $more ) ? __('% Comments') : $more); + elseif ( $number == 0 ) + $output = ( false === $zero ) ? __('No Comments') : $zero; + else // must be one + $output = ( false === $one ) ? __('1 Comment') : $one; + + echo apply_filters('comments_number', $output, $number); +} + +/** + * Retrieve the text of the current comment. + * + * @since 1.5.0 + * @uses $comment + * + * @return string The comment content + */ +function get_comment_text() { + global $comment; + return apply_filters('get_comment_text', $comment->comment_content); +} + +/** + * Displays the text of the current comment. + * + * @since 0.71 + * @uses apply_filters() Passes the comment content through the 'comment_text' hook before display + * @uses get_comment_text() Gets the comment content + */ +function comment_text() { + echo apply_filters('comment_text', get_comment_text() ); +} + +/** + * Retrieve the comment time of the current comment. + * + * @since 1.5.0 + * @uses $comment + * @uses apply_filter() Calls 'get_comment_time' hook with the formatted time, the $d parameter, and $gmt parameter passed. + * + * @param string $d Optional. The format of the time (defaults to user's config) + * @param bool $gmt Whether to use the GMT date + * @param bool $translate Whether to translate the time (for use in feeds) + * @return string The formatted time + */ +function get_comment_time( $d = '', $gmt = false, $translate = true ) { + global $comment; + $comment_date = $gmt? $comment->comment_date_gmt : $comment->comment_date; + if ( '' == $d ) + $date = mysql2date(get_option('time_format'), $comment_date, $translate); + else + $date = mysql2date($d, $comment_date, $translate); + return apply_filters('get_comment_time', $date, $d, $gmt); +} + +/** + * Display the comment time of the current comment. + * + * @since 0.71 + * + * @param string $d Optional. The format of the time (defaults to user's config) + */ +function comment_time( $d = '' ) { + echo get_comment_time($d); +} + +/** + * Retrieve the comment type of the current comment. + * + * @since 1.5.0 + * @uses $comment + * @uses apply_filters() Calls the 'get_comment_type' hook on the comment type + * + * @return string The comment type + */ +function get_comment_type() { + global $comment; + + if ( '' == $comment->comment_type ) + $comment->comment_type = 'comment'; + + return apply_filters('get_comment_type', $comment->comment_type); +} + +/** + * Display the comment type of the current comment. + * + * @since 0.71 + * + * @param string $commenttxt The string to display for comment type + * @param string $trackbacktxt The string to display for trackback type + * @param string $pingbacktxt The string to display for pingback type + */ +function comment_type($commenttxt = false, $trackbacktxt = false, $pingbacktxt = false) { + if ( false === $commenttxt ) $commenttxt = _x( 'Comment', 'noun' ); + if ( false === $trackbacktxt ) $trackbacktxt = __( 'Trackback' ); + if ( false === $pingbacktxt ) $pingbacktxt = __( 'Pingback' ); + $type = get_comment_type(); + switch( $type ) { + case 'trackback' : + echo $trackbacktxt; + break; + case 'pingback' : + echo $pingbacktxt; + break; + default : + echo $commenttxt; + } +} + +/** + * Retrieve The current post's trackback URL. + * + * There is a check to see if permalink's have been enabled and if so, will + * retrieve the pretty path. If permalinks weren't enabled, the ID of the + * current post is used and appended to the correct page to go to. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'trackback_url' on the resulting trackback URL + * @uses $id + * + * @return string The trackback URL after being filtered + */ +function get_trackback_url() { + global $id; + if ( '' != get_option('permalink_structure') ) { + $tb_url = trailingslashit(get_permalink()) . user_trailingslashit('trackback', 'single_trackback'); + } else { + $tb_url = get_option('siteurl') . '/wp-trackback.php?p=' . $id; + } + return apply_filters('trackback_url', $tb_url); +} + +/** + * Displays the current post's trackback URL. + * + * @since 0.71 + * @uses get_trackback_url() Gets the trackback url for the current post + * + * @param bool $deprecated Remove backwards compat in 2.5 + * @return void|string Should only be used to echo the trackback URL, use get_trackback_url() for the result instead. + */ +function trackback_url($deprecated = true) { + if ($deprecated) echo get_trackback_url(); + else return get_trackback_url(); +} + +/** + * Generates and displays the RDF for the trackback information of current post. + * + * @since 0.71 + * + * @param int $deprecated Not used (Was $timezone = 0) + */ +function trackback_rdf($deprecated = '') { + if (stripos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') === false) { + echo ' + \n"; + echo ''; + } +} + +/** + * Whether the current post is open for comments. + * + * @since 1.5.0 + * @uses $post + * + * @param int $post_id An optional post ID to check instead of the current post. + * @return bool True if the comments are open + */ +function comments_open( $post_id=NULL ) { + + $_post = get_post($post_id); + + $open = ( 'open' == $_post->comment_status ); + return apply_filters( 'comments_open', $open, $post_id ); +} + +/** + * Whether the current post is open for pings. + * + * @since 1.5.0 + * @uses $post + * + * @param int $post_id An optional post ID to check instead of the current post. + * @return bool True if pings are accepted + */ +function pings_open( $post_id = NULL ) { + + $_post = get_post($post_id); + + $open = ( 'open' == $_post->ping_status ); + return apply_filters( 'pings_open', $open, $post_id ); +} + +/** + * Displays form token for unfiltered comments. + * + * Will only display nonce token if the current user has permissions for + * unfiltered html. Won't display the token for other users. + * + * The function was backported to 2.0.10 and was added to versions 2.1.3 and + * above. Does not exist in versions prior to 2.0.10 in the 2.0 branch and in + * the 2.1 branch, prior to 2.1.3. Technically added in 2.2.0. + * + * Backported to 2.0.10. + * + * @since 2.1.3 + * @uses $post Gets the ID of the current post for the token + */ +function wp_comment_form_unfiltered_html_nonce() { + global $post; + + $post_id = 0; + if ( !empty($post) ) + $post_id = $post->ID; + + if ( current_user_can('unfiltered_html') ) + wp_nonce_field('unfiltered-html-comment_' . $post_id, '_wp_unfiltered_html_comment', false); +} + +/** + * Loads the comment template specified in $file. + * + * Will not display the comments template if not on single post or page, or if + * the post does not have comments. + * + * Uses the WordPress database object to query for the comments. The comments + * are passed through the 'comments_array' filter hook with the list of comments + * and the post ID respectively. + * + * The $file path is passed through a filter hook called, 'comments_template' + * which includes the TEMPLATEPATH and $file combined. Tries the $filtered path + * first and if it fails it will require the default comment themplate from the + * default theme. If either does not exist, then the WordPress process will be + * halted. It is advised for that reason, that the default theme is not deleted. + * + * @since 1.5.0 + * @global array $comment List of comment objects for the current post + * @uses $wpdb + * @uses $id + * @uses $post + * @uses $withcomments Will not try to get the comments if the post has none. + * + * @param string $file Optional, default '/comments.php'. The file to load + * @param bool $separate_comments Optional, whether to separate the comments by comment type. Default is false. + * @return null Returns null if no comments appear + */ +function comments_template( $file = '/comments.php', $separate_comments = false ) { + global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity, $overridden_cpage; + + if ( ! (is_single() || is_page() || $withcomments) ) + return; + + if ( empty($file) ) + $file = '/comments.php'; + + $req = get_option('require_name_email'); + + /** + * Comment author information fetched from the comment cookies. + * + * @uses wp_get_current_commenter() + */ + $commenter = wp_get_current_commenter(); + + /** + * The name of the current comment author escaped for use in attributes. + */ + $comment_author = $commenter['comment_author']; // Escaped by sanitize_comment_cookies() + + /** + * The email address of the current comment author escaped for use in attributes. + */ + $comment_author_email = $commenter['comment_author_email']; // Escaped by sanitize_comment_cookies() + + /** + * The url of the current comment author escaped for use in attributes. + */ + $comment_author_url = esc_url($commenter['comment_author_url']); + + /** @todo Use API instead of SELECTs. */ + if ( $user_ID) { + $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND (comment_approved = '1' OR ( user_id = %d AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, $user_ID)); + } else if ( empty($comment_author) ) { + $comments = get_comments( array('post_id' => $post->ID, 'status' => 'approve', 'order' => 'ASC') ); + } else { + $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND ( comment_approved = '1' OR ( comment_author = %s AND comment_author_email = %s AND comment_approved = '0' ) ) ORDER BY comment_date_gmt", $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES), $comment_author_email)); + } + + // keep $comments for legacy's sake + $wp_query->comments = apply_filters( 'comments_array', $comments, $post->ID ); + $comments = &$wp_query->comments; + $wp_query->comment_count = count($wp_query->comments); + update_comment_cache($wp_query->comments); + + if ( $separate_comments ) { + $wp_query->comments_by_type = &separate_comments($comments); + $comments_by_type = &$wp_query->comments_by_type; + } + + $overridden_cpage = FALSE; + if ( '' == get_query_var('cpage') && get_option('page_comments') ) { + set_query_var( 'cpage', 'newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1 ); + $overridden_cpage = TRUE; + } + + if ( !defined('COMMENTS_TEMPLATE') || !COMMENTS_TEMPLATE) + define('COMMENTS_TEMPLATE', true); + + $include = apply_filters('comments_template', STYLESHEETPATH . $file ); + if ( file_exists( $include ) ) + require( $include ); + elseif ( file_exists( TEMPLATEPATH . $file ) ) + require( TEMPLATEPATH . $file ); + else + require( get_theme_root() . '/default/comments.php'); +} + +/** + * Displays the JS popup script to show a comment. + * + * If the $file parameter is empty, then the home page is assumed. The defaults + * for the window are 400px by 400px. + * + * For the comment link popup to work, this function has to be called or the + * normal comment link will be assumed. + * + * @since 0.71 + * @global string $wpcommentspopupfile The URL to use for the popup window + * @global int $wpcommentsjavascript Whether to use JavaScript or not. Set when function is called + * + * @param int $width Optional. The width of the popup window + * @param int $height Optional. The height of the popup window + * @param string $file Optional. Sets the location of the popup window + */ +function comments_popup_script($width=400, $height=400, $file='') { + global $wpcommentspopupfile, $wpcommentsjavascript; + + if (empty ($file)) { + $wpcommentspopupfile = ''; // Use the index. + } else { + $wpcommentspopupfile = $file; + } + + $wpcommentsjavascript = 1; + $javascript = "\n"; + echo $javascript; +} + +/** + * Displays the link to the comments popup window for the current post ID. + * + * Is not meant to be displayed on single posts and pages. Should be used on the + * lists of posts + * + * @since 0.71 + * @uses $id + * @uses $wpcommentspopupfile + * @uses $wpcommentsjavascript + * @uses $post + * + * @param string $zero The string to display when no comments + * @param string $one The string to display when only one comment is available + * @param string $more The string to display when there are more than one comment + * @param string $css_class The CSS class to use for comments + * @param string $none The string to display when comments have been turned off + * @return null Returns null on single posts and pages. + */ +function comments_popup_link( $zero = false, $one = false, $more = false, $css_class = '', $none = false ) { + global $id, $wpcommentspopupfile, $wpcommentsjavascript, $post; + + if ( false === $zero ) $zero = __( 'No Comments' ); + if ( false === $one ) $one = __( '1 Comment' ); + if ( false === $more ) $more = __( '% Comments' ); + if ( false === $none ) $none = __( 'Comments Off' ); + + $number = get_comments_number( $id ); + + if ( 0 == $number && !comments_open() && !pings_open() ) { + echo '' . $none . ''; + return; + } + + if ( post_password_required() ) { + echo __('Enter your password to view comments'); + return; + } + + echo ''; + comments_number( $zero, $one, $more, $number ); + echo ''; +} + +/** + * Retrieve HTML content for reply to comment link. + * + * The default arguments that can be override are 'add_below', 'respond_id', + * 'reply_text', 'login_text', and 'depth'. The 'login_text' argument will be + * used, if the user must log in or register first before posting a comment. The + * 'reply_text' will be used, if they can post a reply. The 'add_below' and + * 'respond_id' arguments are for the JavaScript moveAddCommentForm() function + * parameters. + * + * @since 2.7.0 + * + * @param array $args Optional. Override default options. + * @param int $comment Optional. Comment being replied to. + * @param int $post Optional. Post that the comment is going to be displayed on. + * @return string|bool|null Link to show comment form, if successful. False, if comments are closed. + */ +function get_comment_reply_link($args = array(), $comment = null, $post = null) { + global $user_ID; + + $defaults = array('add_below' => 'comment', 'respond_id' => 'respond', 'reply_text' => __('Reply'), + 'login_text' => __('Log in to Reply'), 'depth' => 0, 'before' => '', 'after' => ''); + + $args = wp_parse_args($args, $defaults); + + if ( 0 == $args['depth'] || $args['max_depth'] <= $args['depth'] ) + return; + + extract($args, EXTR_SKIP); + + $comment = get_comment($comment); + $post = get_post($post); + + if ( !comments_open($post->ID) ) + return false; + + $link = ''; + + if ( get_option('comment_registration') && !$user_ID ) + $link = ''; + else + $link = "comment_ID ) ) . "#" . $respond_id . "' onclick='return addComment.moveForm(\"$add_below-$comment->comment_ID\", \"$comment->comment_ID\", \"$respond_id\", \"$post->ID\")'>$reply_text"; + return apply_filters('comment_reply_link', $before . $link . $after, $args, $comment, $post); +} + +/** + * Displays the HTML content for reply to comment link. + * + * @since 2.7.0 + * @see get_comment_reply_link() Echoes result + * + * @param array $args Optional. Override default options. + * @param int $comment Optional. Comment being replied to. + * @param int $post Optional. Post that the comment is going to be displayed on. + * @return string|bool|null Link to show comment form, if successful. False, if comments are closed. + */ +function comment_reply_link($args = array(), $comment = null, $post = null) { + echo get_comment_reply_link($args, $comment, $post); +} + +/** + * Retrieve HTML content for reply to post link. + * + * The default arguments that can be override are 'add_below', 'respond_id', + * 'reply_text', 'login_text', and 'depth'. The 'login_text' argument will be + * used, if the user must log in or register first before posting a comment. The + * 'reply_text' will be used, if they can post a reply. The 'add_below' and + * 'respond_id' arguments are for the JavaScript moveAddCommentForm() function + * parameters. + * + * @since 2.7.0 + * + * @param array $args Optional. Override default options. + * @param int|object $post Optional. Post that the comment is going to be displayed on. Defaults to current post. + * @return string|bool|null Link to show comment form, if successful. False, if comments are closed. + */ +function get_post_reply_link($args = array(), $post = null) { + global $user_ID; + + $defaults = array('add_below' => 'post', 'respond_id' => 'respond', 'reply_text' => __('Leave a Comment'), + 'login_text' => __('Log in to leave a Comment'), 'before' => '', 'after' => ''); + + $args = wp_parse_args($args, $defaults); + extract($args, EXTR_SKIP); + $post = get_post($post); + + if ( !comments_open($post->ID) ) + return false; + + if ( get_option('comment_registration') && !$user_ID ) { + $link = '' . $login_text . ''; + } else { + $link = "$reply_text"; + } + return apply_filters('post_comments_link', $before . $link . $after, $post); +} + +/** + * Displays the HTML content for reply to post link. + * @since 2.7.0 + * @see get_post_reply_link() + * + * @param array $args Optional. Override default options. + * @param int|object $post Optional. Post that the comment is going to be displayed on. + * @return string|bool|null Link to show comment form, if successful. False, if comments are closed. + */ +function post_reply_link($args = array(), $post = null) { + echo get_post_reply_link($args, $post); +} + +/** + * Retrieve HTML content for cancel comment reply link. + * + * @since 2.7.0 + * + * @param string $text Optional. Text to display for cancel reply link. + */ +function get_cancel_comment_reply_link($text = '') { + if ( empty($text) ) + $text = __('Click here to cancel reply.'); + + $style = isset($_GET['replytocom']) ? '' : ' style="display:none;"'; + $link = esc_html( remove_query_arg('replytocom') ) . '#respond'; + return apply_filters('cancel_comment_reply_link', '' . $text . '', $link, $text); +} + +/** + * Display HTML content for cancel comment reply link. + * + * @since 2.7.0 + * + * @param string $text Optional. Text to display for cancel reply link. + */ +function cancel_comment_reply_link($text = '') { + echo get_cancel_comment_reply_link($text); +} + +/** + * Output hidden input HTML for replying to comments. + * + * @since 2.7.0 + */ +function comment_id_fields() { + global $id; + + $replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0; + echo "\n"; + echo "\n"; +} + +/** + * Display text based on comment reply status. Only affects users with Javascript disabled. + * + * @since 2.7.0 + * + * @param string $noreplytext Optional. Text to display when not replying to a comment. + * @param string $replytext Optional. Text to display when replying to a comment. Accepts "%s" for the author of the comment being replied to. + * @param string $linktoparent Optional. Boolean to control making the author's name a link to their comment. + */ +function comment_form_title( $noreplytext = false, $replytext = false, $linktoparent = TRUE ) { + global $comment; + + if ( false === $noreplytext ) $noreplytext = __( 'Leave a Reply' ); + if ( false === $replytext ) $replytext = __( 'Leave a Reply to %s' ); + + $replytoid = isset($_GET['replytocom']) ? (int) $_GET['replytocom'] : 0; + + if ( 0 == $replytoid ) + echo $noreplytext; + else { + $comment = get_comment($replytoid); + $author = ( $linktoparent ) ? '' . get_comment_author() . '' : get_comment_author(); + printf( $replytext, $author ); + } +} + +/** + * HTML comment list class. + * + * @package WordPress + * @uses Walker + * @since unknown + */ +class Walker_Comment extends Walker { + /** + * @see Walker::$tree_type + * @since unknown + * @var string + */ + var $tree_type = 'comment'; + + /** + * @see Walker::$db_fields + * @since unknown + * @var array + */ + var $db_fields = array ('parent' => 'comment_parent', 'id' => 'comment_ID'); + + /** + * @see Walker::start_lvl() + * @since unknown + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of comment. + * @param array $args Uses 'style' argument for type of HTML list. + */ + function start_lvl(&$output, $depth, $args) { + $GLOBALS['comment_depth'] = $depth + 1; + + switch ( $args['style'] ) { + case 'div': + break; + case 'ol': + echo "
      \n"; + break; + default: + case 'ul': + echo "
        \n"; + break; + } + } + + /** + * @see Walker::end_lvl() + * @since unknown + * + * @param string $output Passed by reference. Used to append additional content. + * @param int $depth Depth of comment. + * @param array $args Will only append content if style argument value is 'ol' or 'ul'. + */ + function end_lvl(&$output, $depth, $args) { + $GLOBALS['comment_depth'] = $depth + 1; + + switch ( $args['style'] ) { + case 'div': + break; + case 'ol': + echo "
    \n"; + break; + default: + case 'ul': + echo "\n"; + break; + } + } + + /** + * @see Walker::start_el() + * @since unknown + * + * @param string $output Passed by reference. Used to append additional content. + * @param object $comment Comment data object. + * @param int $depth Depth of comment in reference to parents. + * @param array $args + */ + function start_el(&$output, $comment, $depth, $args) { + $depth++; + $GLOBALS['comment_depth'] = $depth; + + if ( !empty($args['callback']) ) { + call_user_func($args['callback'], $comment, $args, $depth); + return; + } + + $GLOBALS['comment'] = $comment; + extract($args, EXTR_SKIP); + + if ( 'div' == $args['style'] ) { + $tag = 'div'; + $add_below = 'comment'; + } else { + $tag = 'li'; + $add_below = 'div-comment'; + } +?> + < id="comment-"> + +
    + +
    + + %s says:'), get_comment_author_link()) ?> +
    +comment_approved == '0') : ?> + +
    + + + + + + +
    + $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?> +
    + +
    + +\n"; + else + echo "\n"; + } + +} + +/** + * List comments + * + * Used in the comments.php template to list comments for a particular post + * + * @since 2.7.0 + * @uses Walker_Comment + * + * @param string|array $args Formatting options + * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments + */ +function wp_list_comments($args = array(), $comments = null ) { + global $wp_query, $comment_alt, $comment_depth, $comment_thread_alt, $overridden_cpage, $in_comment_loop; + + $in_comment_loop = true; + + $comment_alt = $comment_thread_alt = 0; + $comment_depth = 1; + + $defaults = array('walker' => null, 'max_depth' => '', 'style' => 'ul', 'callback' => null, 'end-callback' => null, 'type' => 'all', + 'page' => '', 'per_page' => '', 'avatar_size' => 32, 'reverse_top_level' => null, 'reverse_children' => ''); + + $r = wp_parse_args( $args, $defaults ); + + // Figure out what comments we'll be looping through ($_comments) + if ( null !== $comments ) { + $comments = (array) $comments; + if ( empty($comments) ) + return; + if ( 'all' != $r['type'] ) { + $comments_by_type = &separate_comments($comments); + if ( empty($comments_by_type[$r['type']]) ) + return; + $_comments = $comments_by_type[$r['type']]; + } else { + $_comments = $comments; + } + } else { + if ( empty($wp_query->comments) ) + return; + if ( 'all' != $r['type'] ) { + if ( empty($wp_query->comments_by_type) ) + $wp_query->comments_by_type = &separate_comments($wp_query->comments); + if ( empty($wp_query->comments_by_type[$r['type']]) ) + return; + $_comments = $wp_query->comments_by_type[$r['type']]; + } else { + $_comments = $wp_query->comments; + } + } + + if ( '' === $r['per_page'] && get_option('page_comments') ) + $r['per_page'] = get_query_var('comments_per_page'); + + if ( empty($r['per_page']) ) { + $r['per_page'] = 0; + $r['page'] = 0; + } + + if ( '' === $r['max_depth'] ) { + if ( get_option('thread_comments') ) + $r['max_depth'] = get_option('thread_comments_depth'); + else + $r['max_depth'] = -1; + } + + if ( '' === $r['page'] ) { + if ( empty($overridden_cpage) ) { + $r['page'] = get_query_var('cpage'); + } else { + $threaded = ( -1 == $r['max_depth'] ) ? false : true; + $r['page'] = ( 'newest' == get_option('default_comments_page') ) ? get_comment_pages_count($_comments, $r['per_page'], $threaded) : 1; + set_query_var( 'cpage', $r['page'] ); + } + } + // Validation check + $r['page'] = intval($r['page']); + if ( 0 == $r['page'] && 0 != $r['per_page'] ) + $r['page'] = 1; + + if ( null === $r['reverse_top_level'] ) + $r['reverse_top_level'] = ( 'desc' == get_option('comment_order') ) ? TRUE : FALSE; + + extract( $r, EXTR_SKIP ); + + if ( empty($walker) ) + $walker = new Walker_Comment; + + $walker->paged_walk($_comments, $max_depth, $page, $per_page, $r); + $wp_query->max_num_comment_pages = $walker->max_pages; + + $in_comment_loop = false; +} + +?> diff --git a/wp-includes/comment.php b/wp-includes/comment.php new file mode 100644 index 0000000..77b59d7 --- /dev/null +++ b/wp-includes/comment.php @@ -0,0 +1,1645 @@ +]*[Hh][Rr][Ee][Ff]=['\"]([^\"'>]+)[^>]*>/", apply_filters('comment_text',$comment), $out) >= get_option('comment_max_links') ) + return false; // Check # of external links + + $mod_keys = trim(get_option('moderation_keys')); + if ( !empty($mod_keys) ) { + $words = explode("\n", $mod_keys ); + + foreach ( (array) $words as $word) { + $word = trim($word); + + // Skip empty lines + if ( empty($word) ) + continue; + + // Do some escaping magic so that '#' chars in the + // spam words don't break things: + $word = preg_quote($word, '#'); + + $pattern = "#$word#i"; + if ( preg_match($pattern, $author) ) return false; + if ( preg_match($pattern, $email) ) return false; + if ( preg_match($pattern, $url) ) return false; + if ( preg_match($pattern, $comment) ) return false; + if ( preg_match($pattern, $user_ip) ) return false; + if ( preg_match($pattern, $user_agent) ) return false; + } + } + + // Comment whitelisting: + if ( 1 == get_option('comment_whitelist')) { + if ( 'trackback' == $comment_type || 'pingback' == $comment_type ) { // check if domain is in blogroll + $uri = parse_url($url); + $domain = $uri['host']; + $uri = parse_url( get_option('home') ); + $home_domain = $uri['host']; + if ( $wpdb->get_var($wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_url LIKE (%s) LIMIT 1", '%'.$domain.'%')) || $domain == $home_domain ) + return true; + else + return false; + } elseif ( $author != '' && $email != '' ) { + // expected_slashed ($author, $email) + $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1"); + if ( ( 1 == $ok_to_comment ) && + ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) ) + return true; + else + return false; + } else { + return false; + } + } + return true; +} + +/** + * Retrieve the approved comments for post $post_id. + * + * @since 2.0.0 + * @uses $wpdb + * + * @param int $post_id The ID of the post + * @return array $comments The approved comments + */ +function get_approved_comments($post_id) { + global $wpdb; + return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id)); +} + +/** + * Retrieves comment data given a comment ID or comment object. + * + * If an object is passed then the comment data will be cached and then returned + * after being passed through a filter. If the comment is empty, then the global + * comment variable will be used, if it is set. + * + * If the comment is empty, then the global comment variable will be used, if it + * is set. + * + * @since 2.0.0 + * @uses $wpdb + * + * @param object|string|int $comment Comment to retrieve. + * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants. + * @return object|array|null Depends on $output value. + */ +function &get_comment(&$comment, $output = OBJECT) { + global $wpdb; + + if ( empty($comment) ) { + if ( isset($GLOBALS['comment']) ) + $_comment = & $GLOBALS['comment']; + else + $_comment = null; + } elseif ( is_object($comment) ) { + wp_cache_add($comment->comment_ID, $comment, 'comment'); + $_comment = $comment; + } else { + if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) { + $_comment = & $GLOBALS['comment']; + } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) { + $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment)); + wp_cache_add($_comment->comment_ID, $_comment, 'comment'); + } + } + + $_comment = apply_filters('get_comment', $_comment); + + if ( $output == OBJECT ) { + return $_comment; + } elseif ( $output == ARRAY_A ) { + $__comment = get_object_vars($_comment); + return $__comment; + } elseif ( $output == ARRAY_N ) { + $__comment = array_values(get_object_vars($_comment)); + return $__comment; + } else { + return $_comment; + } +} + +/** + * Retrieve a list of comments. + * + * The comment list can be for the blog as a whole or for an individual post. + * + * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt', + * 'order', 'number', 'offset', and 'post_id'. + * + * @since 2.7.0 + * @uses $wpdb + * + * @param mixed $args Optional. Array or string of options to override defaults. + * @return array List of comments. + */ +function get_comments( $args = '' ) { + global $wpdb; + + $defaults = array('status' => '', 'orderby' => 'comment_date_gmt', 'order' => 'DESC', 'number' => '', 'offset' => '', 'post_id' => 0); + + $args = wp_parse_args( $args, $defaults ); + extract( $args, EXTR_SKIP ); + + // $args can be whatever, only use the args defined in defaults to compute the key + $key = md5( serialize( compact(array_keys($defaults)) ) ); + $last_changed = wp_cache_get('last_changed', 'comment'); + if ( !$last_changed ) { + $last_changed = time(); + wp_cache_set('last_changed', $last_changed, 'comment'); + } + $cache_key = "get_comments:$key:$last_changed"; + + if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) { + return $cache; + } + + $post_id = absint($post_id); + + if ( 'hold' == $status ) + $approved = "comment_approved = '0'"; + elseif ( 'approve' == $status ) + $approved = "comment_approved = '1'"; + elseif ( 'spam' == $status ) + $approved = "comment_approved = 'spam'"; + else + $approved = "( comment_approved = '0' OR comment_approved = '1' )"; + + $order = ( 'ASC' == $order ) ? 'ASC' : 'DESC'; + + $orderby = 'comment_date_gmt'; // Hard code for now + + $number = absint($number); + $offset = absint($offset); + + if ( !empty($number) ) { + if ( $offset ) + $number = 'LIMIT ' . $offset . ',' . $number; + else + $number = 'LIMIT ' . $number; + + } else { + $number = ''; + } + + if ( ! empty($post_id) ) + $post_where = $wpdb->prepare( 'comment_post_ID = %d AND', $post_id ); + else + $post_where = ''; + + $comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE $post_where $approved ORDER BY $orderby $order $number" ); + wp_cache_add( $cache_key, $comments, 'comment' ); + + return $comments; +} + +/** + * Retrieve all of the WordPress supported comment statuses. + * + * Comments have a limited set of valid status values, this provides the comment + * status values and descriptions. + * + * @package WordPress + * @subpackage Post + * @since 2.7.0 + * + * @return array List of comment statuses. + */ +function get_comment_statuses( ) { + $status = array( + 'hold' => __('Unapproved'), + /* translators: comment status */ + 'approve' => _x('Approved', 'adjective'), + /* translators: comment status */ + 'spam' => _x('Spam', 'adjective'), + ); + + return $status; +} + + +/** + * The date the last comment was modified. + * + * @since 1.5.0 + * @uses $wpdb + * @global array $cache_lastcommentmodified + * + * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', + * or 'server' locations. + * @return string Last comment modified date. + */ +function get_lastcommentmodified($timezone = 'server') { + global $cache_lastcommentmodified, $wpdb; + + if ( isset($cache_lastcommentmodified[$timezone]) ) + return $cache_lastcommentmodified[$timezone]; + + $add_seconds_server = date('Z'); + + switch ( strtolower($timezone)) { + case 'gmt': + $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1"); + break; + case 'blog': + $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1"); + break; + case 'server': + $lastcommentmodified = $wpdb->get_var($wpdb->prepare("SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server)); + break; + } + + $cache_lastcommentmodified[$timezone] = $lastcommentmodified; + + return $lastcommentmodified; +} + +/** + * The amount of comments in a post or total comments. + * + * A lot like {@link wp_count_comments()}, in that they both return comment + * stats (albeit with different types). The {@link wp_count_comments()} actual + * caches, but this function does not. + * + * @since 2.0.0 + * @uses $wpdb + * + * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide. + * @return array The amount of spam, approved, awaiting moderation, and total comments. + */ +function get_comment_count( $post_id = 0 ) { + global $wpdb; + + $post_id = (int) $post_id; + + $where = ''; + if ( $post_id > 0 ) { + $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id); + } + + $totals = (array) $wpdb->get_results(" + SELECT comment_approved, COUNT( * ) AS total + FROM {$wpdb->comments} + {$where} + GROUP BY comment_approved + ", ARRAY_A); + + $comment_count = array( + "approved" => 0, + "awaiting_moderation" => 0, + "spam" => 0, + "total_comments" => 0 + ); + + foreach ( $totals as $row ) { + switch ( $row['comment_approved'] ) { + case 'spam': + $comment_count['spam'] = $row['total']; + $comment_count["total_comments"] += $row['total']; + break; + case 1: + $comment_count['approved'] = $row['total']; + $comment_count['total_comments'] += $row['total']; + break; + case 0: + $comment_count['awaiting_moderation'] = $row['total']; + $comment_count['total_comments'] += $row['total']; + break; + default: + break; + } + } + + return $comment_count; +} + +/** + * Sanitizes the cookies sent to the user already. + * + * Will only do anything if the cookies have already been created for the user. + * Mostly used after cookies had been sent to use elsewhere. + * + * @since 2.0.4 + */ +function sanitize_comment_cookies() { + if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) { + $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]); + $comment_author = stripslashes($comment_author); + $comment_author = esc_attr($comment_author); + $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author; + } + + if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) { + $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]); + $comment_author_email = stripslashes($comment_author_email); + $comment_author_email = esc_attr($comment_author_email); + $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email; + } + + if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) { + $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]); + $comment_author_url = stripslashes($comment_author_url); + $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url; + } +} + +/** + * Validates whether this comment is allowed to be made or not. + * + * @since 2.0.0 + * @uses $wpdb + * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment + * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt + * + * @param array $commentdata Contains information on the comment + * @return mixed Signifies the approval status (0|1|'spam') + */ +function wp_allow_comment($commentdata) { + global $wpdb; + extract($commentdata, EXTR_SKIP); + + // Simple duplicate check + // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content) + $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' "; + if ( $comment_author_email ) + $dupe .= "OR comment_author_email = '$comment_author_email' "; + $dupe .= ") AND comment_content = '$comment_content' LIMIT 1"; + if ( $wpdb->get_var($dupe) ) { + if ( defined('DOING_AJAX') ) + die( __('Duplicate comment detected; it looks as though you’ve already said that!') ); + + wp_die( __('Duplicate comment detected; it looks as though you’ve already said that!') ); + } + + do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt ); + + if ( $user_id ) { + $userdata = get_userdata($user_id); + $user = new WP_User($user_id); + $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID)); + } + + if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) { + // The author and the admins get respect. + $approved = 1; + } else { + // Everyone else's comments will be checked. + if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) ) + $approved = 1; + else + $approved = 0; + if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) ) + $approved = 'spam'; + } + + $approved = apply_filters('pre_comment_approved', $approved); + return $approved; +} + +/** + * Check whether comment flooding is occurring. + * + * Won't run, if current user can manage options, so to not block + * administrators. + * + * @since 2.3.0 + * @uses $wpdb + * @uses apply_filters() Calls 'comment_flood_filter' filter with first + * parameter false, last comment timestamp, new comment timestamp. + * @uses do_action() Calls 'comment_flood_trigger' action with parameters with + * last comment timestamp and new comment timestamp. + * + * @param string $ip Comment IP. + * @param string $email Comment author email address. + * @param string $date MySQL time string. + */ +function check_comment_flood_db( $ip, $email, $date ) { + global $wpdb; + if ( current_user_can( 'manage_options' ) ) + return; // don't throttle admins + if ( $lasttime = $wpdb->get_var( $wpdb->prepare("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author_IP = %s OR comment_author_email = %s ORDER BY comment_date DESC LIMIT 1", $ip, $email) ) ) { + $time_lastcomment = mysql2date('U', $lasttime, false); + $time_newcomment = mysql2date('U', $date, false); + $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment); + if ( $flood_die ) { + do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment); + + if ( defined('DOING_AJAX') ) + die( __('You are posting comments too quickly. Slow down.') ); + + wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) ); + } + } +} + +/** + * Separates an array of comments into an array keyed by comment_type. + * + * @since 2.7.0 + * + * @param array $comments Array of comments + * @return array Array of comments keyed by comment_type. + */ +function &separate_comments(&$comments) { + $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array()); + $count = count($comments); + for ( $i = 0; $i < $count; $i++ ) { + $type = $comments[$i]->comment_type; + if ( empty($type) ) + $type = 'comment'; + $comments_by_type[$type][] = &$comments[$i]; + if ( 'trackback' == $type || 'pingback' == $type ) + $comments_by_type['pings'][] = &$comments[$i]; + } + + return $comments_by_type; +} + +/** + * Calculate the total number of comment pages. + * + * @since 2.7.0 + * @uses get_query_var() Used to fill in the default for $per_page parameter. + * @uses get_option() Used to fill in defaults for parameters. + * @uses Walker_Comment + * + * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments + * @param int $per_page Optional comments per page. + * @param boolean $threaded Optional control over flat or threaded comments. + * @return int Number of comment pages. + */ +function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) { + global $wp_query; + + if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) ) + return $wp_query->max_num_comment_pages; + + if ( !$comments || !is_array($comments) ) + $comments = $wp_query->comments; + + if ( empty($comments) ) + return 0; + + if ( !isset($per_page) ) + $per_page = (int) get_query_var('comments_per_page'); + if ( 0 === $per_page ) + $per_page = (int) get_option('comments_per_page'); + if ( 0 === $per_page ) + return 1; + + if ( !isset($threaded) ) + $threaded = get_option('thread_comments'); + + if ( $threaded ) { + $walker = new Walker_Comment; + $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page ); + } else { + $count = ceil( count( $comments ) / $per_page ); + } + + return $count; +} + +/** + * Calculate what page number a comment will appear on for comment paging. + * + * @since 2.7.0 + * @uses get_comment() Gets the full comment of the $comment_ID parameter. + * @uses get_option() Get various settings to control function and defaults. + * @uses get_page_of_comment() Used to loop up to top level comment. + * + * @param int $comment_ID Comment ID. + * @param array $args Optional args. + * @return int|null Comment page number or null on error. + */ +function get_page_of_comment( $comment_ID, $args = array() ) { + global $wpdb; + + if ( !$comment = get_comment( $comment_ID ) ) + return; + + $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' ); + $args = wp_parse_args( $args, $defaults ); + + if ( '' === $args['per_page'] && get_option('page_comments') ) + $args['per_page'] = get_query_var('comments_per_page'); + if ( empty($args['per_page']) ) { + $args['per_page'] = 0; + $args['page'] = 0; + } + if ( $args['per_page'] < 1 ) + return 1; + + if ( '' === $args['max_depth'] ) { + if ( get_option('thread_comments') ) + $args['max_depth'] = get_option('thread_comments_depth'); + else + $args['max_depth'] = -1; + } + + // Find this comment's top level parent if threading is enabled + if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent ) + return get_page_of_comment( $comment->comment_parent, $args ); + + $allowedtypes = array( + 'comment' => '', + 'pingback' => 'pingback', + 'trackback' => 'trackback', + ); + + $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : ''; + + // Count comments older than this one + $oldercoms = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = 0 AND comment_approved = '1' AND comment_date_gmt < '%s'" . $comtypewhere, $comment->comment_post_ID, $comment->comment_date_gmt ) ); + + // No older comments? Then it's page #1. + if ( 0 == $oldercoms ) + return 1; + + // Divide comments older than this one by comments per page to get this comment's page number + return ceil( ( $oldercoms + 1 ) / $args['per_page'] ); +} + +/** + * Does comment contain blacklisted characters or words. + * + * @since 1.5.0 + * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters. + * + * @param string $author The author of the comment + * @param string $email The email of the comment + * @param string $url The url used in the comment + * @param string $comment The comment content + * @param string $user_ip The comment author IP address + * @param string $user_agent The author's browser user agent + * @return bool True if comment contains blacklisted content, false if comment does not + */ +function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) { + do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent); + + if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) { + foreach ( (array) $chars[1] as $char ) { + // If it's an encoded char in the normal ASCII set, reject + if ( 38 == $char ) + continue; // Unless it's & + if ( $char < 128 ) + return true; + } + } + + $mod_keys = trim( get_option('blacklist_keys') ); + if ( '' == $mod_keys ) + return false; // If moderation keys are empty + $words = explode("\n", $mod_keys ); + + foreach ( (array) $words as $word ) { + $word = trim($word); + + // Skip empty lines + if ( empty($word) ) { continue; } + + // Do some escaping magic so that '#' chars in the + // spam words don't break things: + $word = preg_quote($word, '#'); + + $pattern = "#$word#i"; + if ( + preg_match($pattern, $author) + || preg_match($pattern, $email) + || preg_match($pattern, $url) + || preg_match($pattern, $comment) + || preg_match($pattern, $user_ip) + || preg_match($pattern, $user_agent) + ) + return true; + } + return false; +} + +/** + * Retrieve total comments for blog or single post. + * + * The properties of the returned object contain the 'moderated', 'approved', + * and spam comments for either the entire blog or single post. Those properties + * contain the amount of comments that match the status. The 'total_comments' + * property contains the integer of total comments. + * + * The comment stats are cached and then retrieved, if they already exist in the + * cache. + * + * @since 2.5.0 + * + * @param int $post_id Optional. Post ID. + * @return object Comment stats. + */ +function wp_count_comments( $post_id = 0 ) { + global $wpdb; + + $post_id = (int) $post_id; + + $stats = apply_filters('wp_count_comments', array(), $post_id); + if ( !empty($stats) ) + return $stats; + + $count = wp_cache_get("comments-{$post_id}", 'counts'); + + if ( false !== $count ) + return $count; + + $where = ''; + if( $post_id > 0 ) + $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id ); + + $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A ); + + $total = 0; + $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam'); + $known_types = array_keys( $approved ); + foreach( (array) $count as $row_num => $row ) { + $total += $row['num_comments']; + if ( in_array( $row['comment_approved'], $known_types ) ) + $stats[$approved[$row['comment_approved']]] = $row['num_comments']; + } + + $stats['total_comments'] = $total; + foreach ( $approved as $key ) { + if ( empty($stats[$key]) ) + $stats[$key] = 0; + } + + $stats = (object) $stats; + wp_cache_set("comments-{$post_id}", $stats, 'counts'); + + return $stats; +} + +/** + * Removes comment ID and maybe updates post comment count. + * + * The post comment count will be updated if the comment was approved and has a + * post ID available. + * + * @since 2.0.0 + * @uses $wpdb + * @uses do_action() Calls 'delete_comment' hook on comment ID + * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter + * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object + * + * @param int $comment_id Comment ID + * @return bool False if delete comment query failure, true on success. + */ +function wp_delete_comment($comment_id) { + global $wpdb; + do_action('delete_comment', $comment_id); + + $comment = get_comment($comment_id); + + if ( ! $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id) ) ) + return false; + + // Move children up a level. + $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) ); + if ( !empty($children) ) { + $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id)); + clean_comment_cache($children); + } + + $post_id = $comment->comment_post_ID; + if ( $post_id && $comment->comment_approved == 1 ) + wp_update_comment_count($post_id); + + clean_comment_cache($comment_id); + + do_action('wp_set_comment_status', $comment_id, 'delete'); + wp_transition_comment_status('delete', $comment->comment_approved, $comment); + return true; +} + +/** + * The status of a comment by ID. + * + * @since 1.0.0 + * + * @param int $comment_id Comment ID + * @return string|bool Status might be 'deleted', 'approved', 'unapproved', 'spam'. False on failure. + */ +function wp_get_comment_status($comment_id) { + $comment = get_comment($comment_id); + if ( !$comment ) + return false; + + $approved = $comment->comment_approved; + + if ( $approved == NULL ) + return 'deleted'; + elseif ( $approved == '1' ) + return 'approved'; + elseif ( $approved == '0' ) + return 'unapproved'; + elseif ( $approved == 'spam' ) + return 'spam'; + else + return false; +} + +/** + * Call hooks for when a comment status transition occurs. + * + * Calls hooks for comment status transitions. If the new comment status is not the same + * as the previous comment status, then two hooks will be ran, the first is + * 'transition_comment_status' with new status, old status, and comment data. The + * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the + * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the + * comment data. + * + * The final action will run whether or not the comment statuses are the same. The + * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status + * parameter and COMMENTTYPE is comment_type comment data. + * + * @since 2.7.0 + * + * @param string $new_status New comment status. + * @param string $old_status Previous comment status. + * @param object $comment Comment data. + */ +function wp_transition_comment_status($new_status, $old_status, $comment) { + // Translate raw statuses to human readable formats for the hooks + // This is not a complete list of comment status, it's only the ones that need to be renamed + $comment_statuses = array( + 0 => 'unapproved', + 'hold' => 'unapproved', // wp_set_comment_status() uses "hold" + 1 => 'approved', + 'approve' => 'approved', // wp_set_comment_status() uses "approve" + ); + if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status]; + if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status]; + + // Call the hooks + if ( $new_status != $old_status ) { + do_action('transition_comment_status', $new_status, $old_status, $comment); + do_action("comment_${old_status}_to_$new_status", $comment); + } + do_action("comment_${new_status}_$comment->comment_type", $comment->comment_ID, $comment); +} + +/** + * Get current commenter's name, email, and URL. + * + * Expects cookies content to already be sanitized. User of this function might + * wish to recheck the returned array for validity. + * + * @see sanitize_comment_cookies() Use to sanitize cookies + * + * @since 2.0.4 + * + * @return array Comment author, email, url respectively. + */ +function wp_get_current_commenter() { + // Cookies should already be sanitized. + + $comment_author = ''; + if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) + $comment_author = $_COOKIE['comment_author_'.COOKIEHASH]; + + $comment_author_email = ''; + if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) + $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH]; + + $comment_author_url = ''; + if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) + $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH]; + + return compact('comment_author', 'comment_author_email', 'comment_author_url'); +} + +/** + * Inserts a comment to the database. + * + * The available comment data key names are 'comment_author_IP', 'comment_date', + * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'. + * + * @since 2.0.0 + * @uses $wpdb + * + * @param array $commentdata Contains information on the comment. + * @return int The new comment's ID. + */ +function wp_insert_comment($commentdata) { + global $wpdb; + extract(stripslashes_deep($commentdata), EXTR_SKIP); + + if ( ! isset($comment_author_IP) ) + $comment_author_IP = ''; + if ( ! isset($comment_date) ) + $comment_date = current_time('mysql'); + if ( ! isset($comment_date_gmt) ) + $comment_date_gmt = get_gmt_from_date($comment_date); + if ( ! isset($comment_parent) ) + $comment_parent = 0; + if ( ! isset($comment_approved) ) + $comment_approved = 1; + if ( ! isset($comment_karma) ) + $comment_karma = 0; + if ( ! isset($user_id) ) + $user_id = 0; + if ( ! isset($comment_type) ) + $comment_type = ''; + + $data = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id'); + $wpdb->insert($wpdb->comments, $data); + + $id = (int) $wpdb->insert_id; + + if ( $comment_approved == 1 ) + wp_update_comment_count($comment_post_ID); + + $comment = get_comment($id); + do_action('wp_insert_comment', $id, $comment); + + return $id; +} + +/** + * Filters and sanitizes comment data. + * + * Sets the comment data 'filtered' field to true when finished. This can be + * checked as to whether the comment should be filtered and to keep from + * filtering the same comment more than once. + * + * @since 2.0.0 + * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID + * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent + * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name + * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content + * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP + * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL + * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address + * + * @param array $commentdata Contains information on the comment. + * @return array Parsed comment information. + */ +function wp_filter_comment($commentdata) { + $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']); + $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', $commentdata['comment_agent']); + $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']); + $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']); + $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']); + $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']); + $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']); + $commentdata['filtered'] = true; + return $commentdata; +} + +/** + * Whether comment should be blocked because of comment flood. + * + * @since 2.1.0 + * + * @param bool $block Whether plugin has already blocked comment. + * @param int $time_lastcomment Timestamp for last comment. + * @param int $time_newcomment Timestamp for new comment. + * @return bool Whether comment should be blocked. + */ +function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) { + if ( $block ) // a plugin has already blocked... we'll let that decision stand + return $block; + if ( ($time_newcomment - $time_lastcomment) < 15 ) + return true; + return false; +} + +/** + * Adds a new comment to the database. + * + * Filters new comment to ensure that the fields are sanitized and valid before + * inserting comment into database. Calls 'comment_post' action with comment ID + * and whether comment is approved by WordPress. Also has 'preprocess_comment' + * filter for processing the comment data before the function handles it. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing + * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved. + * @uses wp_filter_comment() Used to filter comment before adding comment. + * @uses wp_allow_comment() checks to see if comment is approved. + * @uses wp_insert_comment() Does the actual comment insertion to the database. + * + * @param array $commentdata Contains information on the comment. + * @return int The ID of the comment after adding. + */ +function wp_new_comment( $commentdata ) { + $commentdata = apply_filters('preprocess_comment', $commentdata); + + $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID']; + $commentdata['user_ID'] = (int) $commentdata['user_ID']; + + $commentdata['comment_parent'] = absint($commentdata['comment_parent']); + $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : ''; + $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0; + + $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] ); + $commentdata['comment_agent'] = $_SERVER['HTTP_USER_AGENT']; + + $commentdata['comment_date'] = current_time('mysql'); + $commentdata['comment_date_gmt'] = current_time('mysql', 1); + + $commentdata = wp_filter_comment($commentdata); + + $commentdata['comment_approved'] = wp_allow_comment($commentdata); + + $comment_ID = wp_insert_comment($commentdata); + + do_action('comment_post', $comment_ID, $commentdata['comment_approved']); + + if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching + if ( '0' == $commentdata['comment_approved'] ) + wp_notify_moderator($comment_ID); + + $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment + + if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] ) + wp_notify_postauthor($comment_ID, $commentdata['comment_type']); + } + + return $comment_ID; +} + +/** + * Sets the status of a comment. + * + * The 'wp_set_comment_status' action is called after the comment is handled and + * will only be called, if the comment status is either 'hold', 'approve', or + * 'spam'. If the comment status is not in the list, then false is returned and + * if the status is 'delete', then the comment is deleted without calling the + * action. + * + * @since 1.0.0 + * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object + * + * @param int $comment_id Comment ID. + * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'. + * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false. + * @return bool False on failure or deletion and true on success. + */ +function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) { + global $wpdb; + + $status = '0'; + switch ( $comment_status ) { + case 'hold': + $status = '0'; + break; + case 'approve': + $status = '1'; + if ( get_option('comments_notify') ) { + $comment = get_comment($comment_id); + wp_notify_postauthor($comment_id, $comment->comment_type); + } + break; + case 'spam': + $status = 'spam'; + break; + case 'delete': + return wp_delete_comment($comment_id); + break; + default: + return false; + } + + if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) { + if ( $wp_error ) + return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error); + else + return false; + } + + clean_comment_cache($comment_id); + + $comment = get_comment($comment_id); + + do_action('wp_set_comment_status', $comment_id, $comment_status); + wp_transition_comment_status($comment_status, $comment->comment_approved, $comment); + + wp_update_comment_count($comment->comment_post_ID); + + return true; +} + +/** + * Updates an existing comment in the database. + * + * Filters the comment and makes sure certain fields are valid before updating. + * + * @since 2.0.0 + * @uses $wpdb + * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object + * + * @param array $commentarr Contains information on the comment. + * @return int Comment was updated if value is 1, or was not updated if value is 0. + */ +function wp_update_comment($commentarr) { + global $wpdb; + + // First, get all of the original fields + $comment = get_comment($commentarr['comment_ID'], ARRAY_A); + + // Escape data pulled from DB. + $comment = $wpdb->escape($comment); + + $old_status = $comment['comment_approved']; + + // Merge old and new fields with new fields overwriting old ones. + $commentarr = array_merge($comment, $commentarr); + + $commentarr = wp_filter_comment( $commentarr ); + + // Now extract the merged array. + extract(stripslashes_deep($commentarr), EXTR_SKIP); + + $comment_content = apply_filters('comment_save_pre', $comment_content); + + $comment_date_gmt = get_gmt_from_date($comment_date); + + if ( !isset($comment_approved) ) + $comment_approved = 1; + else if ( 'hold' == $comment_approved ) + $comment_approved = 0; + else if ( 'approve' == $comment_approved ) + $comment_approved = 1; + + $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt'); + $wpdb->update($wpdb->comments, $data, compact('comment_ID')); + + $rval = $wpdb->rows_affected; + + clean_comment_cache($comment_ID); + wp_update_comment_count($comment_post_ID); + do_action('edit_comment', $comment_ID); + $comment = get_comment($comment_ID); + wp_transition_comment_status($comment->comment_approved, $old_status, $comment); + return $rval; +} + +/** + * Whether to defer comment counting. + * + * When setting $defer to true, all post comment counts will not be updated + * until $defer is set to false. When $defer is set to false, then all + * previously deferred updated post comment counts will then be automatically + * updated without having to call wp_update_comment_count() after. + * + * @since 2.5.0 + * @staticvar bool $_defer + * + * @param bool $defer + * @return unknown + */ +function wp_defer_comment_counting($defer=null) { + static $_defer = false; + + if ( is_bool($defer) ) { + $_defer = $defer; + // flush any deferred counts + if ( !$defer ) + wp_update_comment_count( null, true ); + } + + return $_defer; +} + +/** + * Updates the comment count for post(s). + * + * When $do_deferred is false (is by default) and the comments have been set to + * be deferred, the post_id will be added to a queue, which will be updated at a + * later date and only updated once per post ID. + * + * If the comments have not be set up to be deferred, then the post will be + * updated. When $do_deferred is set to true, then all previous deferred post + * IDs will be updated along with the current $post_id. + * + * @since 2.1.0 + * @see wp_update_comment_count_now() For what could cause a false return value + * + * @param int $post_id Post ID + * @param bool $do_deferred Whether to process previously deferred post comment counts + * @return bool True on success, false on failure + */ +function wp_update_comment_count($post_id, $do_deferred=false) { + static $_deferred = array(); + + if ( $do_deferred ) { + $_deferred = array_unique($_deferred); + foreach ( $_deferred as $i => $_post_id ) { + wp_update_comment_count_now($_post_id); + unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */ + } + } + + if ( wp_defer_comment_counting() ) { + $_deferred[] = $post_id; + return true; + } + elseif ( $post_id ) { + return wp_update_comment_count_now($post_id); + } + +} + +/** + * Updates the comment count for the post. + * + * @since 2.5.0 + * @uses $wpdb + * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old + * @uses do_action() Calls 'edit_posts' hook on $post_id and $post + * + * @param int $post_id Post ID + * @return bool False on '0' $post_id or if post with ID does not exist. True on success. + */ +function wp_update_comment_count_now($post_id) { + global $wpdb; + $post_id = (int) $post_id; + if ( !$post_id ) + return false; + if ( !$post = get_post($post_id) ) + return false; + + $old = (int) $post->comment_count; + $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) ); + $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) ); + + if ( 'page' == $post->post_type ) + clean_page_cache( $post_id ); + else + clean_post_cache( $post_id ); + + do_action('wp_update_comment_count', $post_id, $new, $old); + do_action('edit_post', $post_id, $post); + + return true; +} + +// +// Ping and trackback functions. +// + +/** + * Finds a pingback server URI based on the given URL. + * + * Checks the HTML for the rel="pingback" link and x-pingback headers. It does + * a check for the x-pingback headers first and returns that, if available. The + * check for the rel="pingback" has more overhead than just the header. + * + * @since 1.5.0 + * + * @param string $url URL to ping. + * @param int $deprecated Not Used. + * @return bool|string False on failure, string containing URI on success. + */ +function discover_pingback_server_uri($url, $deprecated = 2048) { + + $pingback_str_dquote = 'rel="pingback"'; + $pingback_str_squote = 'rel=\'pingback\''; + + /** @todo Should use Filter Extension or custom preg_match instead. */ + $parsed_url = parse_url($url); + + if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen. + return false; + + //Do not search for a pingback server on our own uploads + $uploads_dir = wp_upload_dir(); + if ( 0 === strpos($url, $uploads_dir['baseurl']) ) + return false; + + $response = wp_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) ); + + if ( is_wp_error( $response ) ) + return false; + + if ( isset( $response['headers']['x-pingback'] ) ) + return $response['headers']['x-pingback']; + + // Not an (x)html, sgml, or xml page, no use going further. + if ( isset( $response['headers']['content-type'] ) && preg_match('#(image|audio|video|model)/#is', $response['headers']['content-type']) ) + return false; + + // Now do a GET since we're going to look in the html headers (and we're sure its not a binary file) + $response = wp_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) ); + + if ( is_wp_error( $response ) ) + return false; + + $contents = $response['body']; + + $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote); + $pingback_link_offset_squote = strpos($contents, $pingback_str_squote); + if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) { + $quote = ($pingback_link_offset_dquote) ? '"' : '\''; + $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote; + $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset); + $pingback_href_start = $pingback_href_pos+6; + $pingback_href_end = @strpos($contents, $quote, $pingback_href_start); + $pingback_server_url_len = $pingback_href_end - $pingback_href_start; + $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len); + + // We may find rel="pingback" but an incomplete pingback URL + if ( $pingback_server_url_len > 0 ) { // We got it! + return $pingback_server_url; + } + } + + return false; +} + +/** + * Perform all pingbacks, enclosures, trackbacks, and send to pingback services. + * + * @since 2.1.0 + * @uses $wpdb + */ +function do_all_pings() { + global $wpdb; + + // Do pingbacks + while ($ping = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) { + $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme';"); + pingback($ping->post_content, $ping->ID); + } + + // Do Enclosures + while ($enclosure = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) { + $wpdb->query( $wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_encloseme';", $enclosure->ID) ); + do_enclose($enclosure->post_content, $enclosure->ID); + } + + // Do Trackbacks + $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'"); + if ( is_array($trackbacks) ) + foreach ( $trackbacks as $trackback ) + do_trackbacks($trackback); + + //Do Update Services/Generic Pings + generic_ping(); +} + +/** + * Perform trackbacks. + * + * @since 1.5.0 + * @uses $wpdb + * + * @param int $post_id Post ID to do trackbacks on. + */ +function do_trackbacks($post_id) { + global $wpdb; + + $post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ); + $to_ping = get_to_ping($post_id); + $pinged = get_pung($post_id); + if ( empty($to_ping) ) { + $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) ); + return; + } + + if ( empty($post->post_excerpt) ) + $excerpt = apply_filters('the_content', $post->post_content); + else + $excerpt = apply_filters('the_excerpt', $post->post_excerpt); + $excerpt = str_replace(']]>', ']]>', $excerpt); + $excerpt = wp_html_excerpt($excerpt, 252) . '...'; + + $post_title = apply_filters('the_title', $post->post_title); + $post_title = strip_tags($post_title); + + if ( $to_ping ) { + foreach ( (array) $to_ping as $tb_ping ) { + $tb_ping = trim($tb_ping); + if ( !in_array($tb_ping, $pinged) ) { + trackback($tb_ping, $post_title, $excerpt, $post_id); + $pinged[] = $tb_ping; + } else { + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = %d", $post_id) ); + } + } + } +} + +/** + * Sends pings to all of the ping site services. + * + * @since 1.2.0 + * + * @param int $post_id Post ID. Not actually used. + * @return int Same as Post ID from parameter + */ +function generic_ping($post_id = 0) { + $services = get_option('ping_sites'); + + $services = explode("\n", $services); + foreach ( (array) $services as $service ) { + $service = trim($service); + if ( '' != $service ) + weblog_ping($service); + } + + return $post_id; +} + +/** + * Pings back the links found in a post. + * + * @since 0.71 + * @uses $wp_version + * @uses IXR_Client + * + * @param string $content Post content to check for links. + * @param int $post_ID Post ID. + */ +function pingback($content, $post_ID) { + global $wp_version; + include_once(ABSPATH . WPINC . '/class-IXR.php'); + + // original code by Mort (http://mort.mine.nu:8080) + $post_links = array(); + + $pung = get_pung($post_ID); + + // Variables + $ltrs = '\w'; + $gunk = '/#~:.?+=&%@!\-'; + $punc = '.:?\-'; + $any = $ltrs . $gunk . $punc; + + // Step 1 + // Parsing the post, external links (if any) are stored in the $post_links array + // This regexp comes straight from phpfreaks.com + // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php + preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp); + + // Step 2. + // Walking thru the links array + // first we get rid of links pointing to sites, not to specific files + // Example: + // http://dummy-weblog.org + // http://dummy-weblog.org/ + // http://dummy-weblog.org/post.php + // We don't wanna ping first and second types, even if they have a valid + + foreach ( (array) $post_links_temp[0] as $link_test ) : + if ( !in_array($link_test, $pung) && (url_to_postid($link_test) != $post_ID) // If we haven't pung it already and it isn't a link to itself + && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments. + if ( $test = @parse_url($link_test) ) { + if ( isset($test['query']) ) + $post_links[] = $link_test; + elseif ( ($test['path'] != '/') && ($test['path'] != '') ) + $post_links[] = $link_test; + } + endif; + endforeach; + + do_action_ref_array('pre_ping', array(&$post_links, &$pung)); + + foreach ( (array) $post_links as $pagelinkedto ) { + $pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048); + + if ( $pingback_server_url ) { + @ set_time_limit( 60 ); + // Now, the RPC call + $pagelinkedfrom = get_permalink($post_ID); + + // using a timeout of 3 seconds should be enough to cover slow servers + $client = new IXR_Client($pingback_server_url); + $client->timeout = 3; + $client->useragent .= ' -- WordPress/' . $wp_version; + + // when set to true, this outputs debug messages by itself + $client->debug = false; + + if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered + add_ping( $post_ID, $pagelinkedto ); + } + } +} + +/** + * Check whether blog is public before returning sites. + * + * @since 2.1.0 + * + * @param mixed $sites Will return if blog is public, will not return if not public. + * @return mixed Empty string if blog is not public, returns $sites, if site is public. + */ +function privacy_ping_filter($sites) { + if ( '0' != get_option('blog_public') ) + return $sites; + else + return ''; +} + +/** + * Send a Trackback. + * + * Updates database when sending trackback to prevent duplicates. + * + * @since 0.71 + * @uses $wpdb + * + * @param string $trackback_url URL to send trackbacks. + * @param string $title Title of post. + * @param string $excerpt Excerpt of post. + * @param int $ID Post ID. + * @return mixed Database query from update. + */ +function trackback($trackback_url, $title, $excerpt, $ID) { + global $wpdb; + + if ( empty($trackback_url) ) + return; + + $options = array(); + $options['timeout'] = 4; + $options['body'] = array( + 'title' => $title, + 'url' => get_permalink($ID), + 'blog_name' => get_option('blogname'), + 'excerpt' => $excerpt + ); + + $response = wp_remote_post($trackback_url, $options); + + if ( is_wp_error( $response ) ) + return; + + $tb_url = addslashes( $trackback_url ); + $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = %d", $ID) ); + return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_url', '')) WHERE ID = %d", $ID) ); +} + +/** + * Send a pingback. + * + * @since 1.2.0 + * @uses $wp_version + * @uses IXR_Client + * + * @param string $server Host of blog to connect to. + * @param string $path Path to send the ping. + */ +function weblog_ping($server = '', $path = '') { + global $wp_version; + include_once(ABSPATH . WPINC . '/class-IXR.php'); + + // using a timeout of 3 seconds should be enough to cover slow servers + $client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path)); + $client->timeout = 3; + $client->useragent .= ' -- WordPress/'.$wp_version; + + // when set to true, this outputs debug messages by itself + $client->debug = false; + $home = trailingslashit( get_option('home') ); + if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping + $client->query('weblogUpdates.ping', get_option('blogname'), $home); +} + +// +// Cache +// + +/** + * Removes comment ID from the comment cache. + * + * @since 2.3.0 + * @package WordPress + * @subpackage Cache + * + * @param int|array $id Comment ID or array of comment IDs to remove from cache + */ +function clean_comment_cache($ids) { + foreach ( (array) $ids as $id ) + wp_cache_delete($id, 'comment'); +} + +/** + * Updates the comment cache of given comments. + * + * Will add the comments in $comments to the cache. If comment ID already exists + * in the comment cache then it will not be updated. The comment is added to the + * cache using the comment group with the key using the ID of the comments. + * + * @since 2.3.0 + * @package WordPress + * @subpackage Cache + * + * @param array $comments Array of comment row objects + */ +function update_comment_cache($comments) { + foreach ( (array) $comments as $comment ) + wp_cache_add($comment->comment_ID, $comment, 'comment'); +} + +// +// Internal +// + +/** + * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts. + * + * @access private + * @since 2.7.0 + * + * @param object $posts Post data object. + * @return object + */ +function _close_comments_for_old_posts( $posts ) { + if ( empty($posts) || !is_singular() || !get_option('close_comments_for_old_posts') ) + return $posts; + + $days_old = (int) get_option('close_comments_days_old'); + if ( !$days_old ) + return $posts; + + if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) ) { + $posts[0]->comment_status = 'closed'; + $posts[0]->ping_status = 'closed'; + } + + return $posts; +} + +/** + * Close comments on an old post. Hooked to comments_open and pings_open. + * + * @access private + * @since 2.7.0 + * + * @param bool $open Comments open or closed + * @param int $post_id Post ID + * @return bool $open + */ +function _close_comments_for_old_post( $open, $post_id ) { + if ( ! $open ) + return $open; + + if ( !get_option('close_comments_for_old_posts') ) + return $open; + + $days_old = (int) get_option('close_comments_days_old'); + if ( !$days_old ) + return $open; + + $post = get_post($post_id); + + if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) ) + return false; + + return $open; +} + +?> diff --git a/wp-includes/compat.php b/wp-includes/compat.php new file mode 100644 index 0000000..0043865 --- /dev/null +++ b/wp-includes/compat.php @@ -0,0 +1,118 @@ + $v ) { + if ( $urlencode) + $k = urlencode($k); + if ( is_int($k) && $prefix != null ) + $k = $prefix.$k; + if ( !empty($key) ) + $k = $key . '%5B' . $k . '%5D'; + if ( $v === NULL ) + continue; + elseif ( $v === FALSE ) + $v = '0'; + + if ( is_array($v) || is_object($v) ) + array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode)); + elseif ( $urlencode ) + array_push($ret, $k.'='.urlencode($v)); + else + array_push($ret, $k.'='.$v); + } + + if ( NULL === $sep ) + $sep = ini_get('arg_separator.output'); + + return implode($sep, $ret); +} + +if ( !function_exists('_') ) { + function _($string) { + return $string; + } +} + +if (!function_exists('stripos')) { + function stripos($haystack, $needle, $offset = 0) { + return strpos(strtolower($haystack), strtolower($needle), $offset); + } +} + +if ( ! function_exists('hash_hmac') ): +function hash_hmac($algo, $data, $key, $raw_output = false) { + $packs = array('md5' => 'H32', 'sha1' => 'H40'); + + if ( !isset($packs[$algo]) ) + return false; + + $pack = $packs[$algo]; + + if (strlen($key) > 64) + $key = pack($pack, $algo($key)); + else if (strlen($key) < 64) + $key = str_pad($key, 64, chr(0)); + + $ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64)); + $opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64)); + + return $algo($opad . pack($pack, $algo($ipad . $data))); +} +endif; + +if ( ! function_exists('mb_substr') ): + function mb_substr( $str, $start, $length=null, $encoding=null ) { + return _mb_substr($str, $start, $length, $encoding); + } +endif; + +function _mb_substr( $str, $start, $length=null, $encoding=null ) { + // the solution below, works only for utf-8, so in case of a different + // charset, just use built-in substr + $charset = get_option( 'blog_charset' ); + if ( !in_array( $charset, array('utf8', 'utf-8', 'UTF8', 'UTF-8') ) ) { + return is_null( $length )? substr( $str, $start ) : substr( $str, $start, $length); + } + // use the regex unicode support to separate the UTF-8 characters into an array + preg_match_all( '/./us', $str, $match ); + $chars = is_null( $length )? array_slice( $match[0], $start ) : array_slice( $match[0], $start, $length ); + return implode( '', $chars ); +} + +if ( !function_exists( 'htmlspecialchars_decode' ) ) { + // Added in PHP 5.1.0 + // Error checks from PEAR::PHP_Compat + function htmlspecialchars_decode( $string, $quote_style = ENT_COMPAT ) + { + if ( !is_scalar( $string ) ) { + trigger_error( 'htmlspecialchars_decode() expects parameter 1 to be string, ' . gettype( $string ) . ' given', E_USER_WARNING ); + return; + } + + if ( !is_int( $quote_style ) && $quote_style !== null ) { + trigger_error( 'htmlspecialchars_decode() expects parameter 2 to be integer, ' . gettype( $quote_style ) . ' given', E_USER_WARNING ); + return; + } + + return wp_specialchars_decode( $string, $quote_style ); + } +} + +?> diff --git a/wp-includes/cron.php b/wp-includes/cron.php new file mode 100644 index 0000000..be9ea67 --- /dev/null +++ b/wp-includes/cron.php @@ -0,0 +1,397 @@ + false, 'args' => $args ); + uksort( $crons, "strnatcasecmp" ); + _set_cron_array( $crons ); +} + +/** + * Schedule a periodic event. + * + * Schedules a hook which will be executed by the WordPress actions core on a + * specific interval, specified by you. The action will trigger when someone + * visits your WordPress site, if the scheduled time has passed. + * + * Valid values for the recurrence are hourly, daily and twicedaily. These can + * be extended using the cron_schedules filter in wp_get_schedules(). + * + * @since 2.1.0 + * + * @param int $timestamp Timestamp for when to run the event. + * @param string $recurrence How often the event should recur. + * @param string $hook Action hook to execute when cron is run. + * @param array $args Optional. Arguments to pass to the hook's callback function. + * @return bool|null False on failure, null when complete with scheduling event. + */ +function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) { + $crons = _get_cron_array(); + $schedules = wp_get_schedules(); + $key = md5(serialize($args)); + if ( !isset( $schedules[$recurrence] ) ) + return false; + $crons[$timestamp][$hook][$key] = array( 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] ); + uksort( $crons, "strnatcasecmp" ); + _set_cron_array( $crons ); +} + +/** + * Reschedule a recurring event. + * + * @since 2.1.0 + * + * @param int $timestamp Timestamp for when to run the event. + * @param string $recurrence How often the event should recur. + * @param string $hook Action hook to execute when cron is run. + * @param array $args Optional. Arguments to pass to the hook's callback function. + * @return bool|null False on failure. Null when event is rescheduled. + */ +function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) { + $crons = _get_cron_array(); + $schedules = wp_get_schedules(); + $key = md5(serialize($args)); + $interval = 0; + + // First we try to get it from the schedule + if ( 0 == $interval ) + $interval = $schedules[$recurrence]['interval']; + // Now we try to get it from the saved interval in case the schedule disappears + if ( 0 == $interval ) + $interval = $crons[$timestamp][$hook][$key]['interval']; + // Now we assume something is wrong and fail to schedule + if ( 0 == $interval ) + return false; + + $now = time(); + + if ( $timestamp >= $now ) + $timestamp = $now + $interval; + else + $timestamp = $now + ($interval - (($now - $timestamp) % $interval)); + + wp_schedule_event( $timestamp, $recurrence, $hook, $args ); +} + +/** + * Unschedule a previously scheduled cron job. + * + * The $timestamp and $hook parameters are required, so that the event can be + * identified. + * + * @since 2.1.0 + * + * @param int $timestamp Timestamp for when to run the event. + * @param string $hook Action hook, the execution of which will be unscheduled. + * @param array $args Arguments to pass to the hook's callback function. + * Although not passed to a callback function, these arguments are used + * to uniquely identify the scheduled event, so they should be the same + * as those used when originally scheduling the event. + */ +function wp_unschedule_event( $timestamp, $hook, $args = array() ) { + $crons = _get_cron_array(); + $key = md5(serialize($args)); + unset( $crons[$timestamp][$hook][$key] ); + if ( empty($crons[$timestamp][$hook]) ) + unset( $crons[$timestamp][$hook] ); + if ( empty($crons[$timestamp]) ) + unset( $crons[$timestamp] ); + _set_cron_array( $crons ); +} + +/** + * Unschedule all cron jobs attached to a specific hook. + * + * @since 2.1.0 + * + * @param string $hook Action hook, the execution of which will be unscheduled. + * @param mixed $args,... Optional. Event arguments. + */ +function wp_clear_scheduled_hook( $hook ) { + $args = array_slice( func_get_args(), 1 ); + + while ( $timestamp = wp_next_scheduled( $hook, $args ) ) + wp_unschedule_event( $timestamp, $hook, $args ); +} + +/** + * Retrieve the next timestamp for a cron event. + * + * @since 2.1.0 + * + * @param string $hook Action hook to execute when cron is run. + * @param array $args Optional. Arguments to pass to the hook's callback function. + * @return bool|int The UNIX timestamp of the next time the scheduled event will occur. + */ +function wp_next_scheduled( $hook, $args = array() ) { + $crons = _get_cron_array(); + $key = md5(serialize($args)); + if ( empty($crons) ) + return false; + foreach ( $crons as $timestamp => $cron ) { + if ( isset( $cron[$hook][$key] ) ) + return $timestamp; + } + return false; +} + +/** + * Send request to run cron through HTTP request that doesn't halt page loading. + * + * @since 2.1.0 + * + * @return null Cron could not be spawned, because it is not needed to run. + */ +function spawn_cron( $local_time = 0 ) { + + if ( !$local_time ) + $local_time = time(); + + if ( defined('DOING_CRON') || isset($_GET['doing_wp_cron']) ) + return; + + /* + * do not even start the cron if local server timer has drifted + * such as due to power failure, or misconfiguration + */ + $timer_accurate = check_server_timer( $local_time ); + if ( !$timer_accurate ) + return; + + /* + * multiple processes on multiple web servers can run this code concurrently + * try to make this as atomic as possible by setting doing_cron switch + */ + $flag = get_transient('doing_cron'); + + if ( $flag > $local_time + 10*60 ) + $flag = 0; + + // don't run if another process is currently running it or more than once every 60 sec. + if ( $flag + 60 > $local_time ) + return; + + //sanity check + $crons = _get_cron_array(); + if ( !is_array($crons) ) + return; + + $keys = array_keys( $crons ); + if ( isset($keys[0]) && $keys[0] > $local_time ) + return; + + if ( defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ) { + if ( !empty($_POST) || defined('DOING_AJAX') ) + return; + + set_transient( 'doing_cron', $local_time ); + + ob_start(); + wp_redirect( add_query_arg('doing_wp_cron', '', stripslashes($_SERVER['REQUEST_URI'])) ); + echo ' '; + + // flush any buffers and send the headers + while ( @ob_end_flush() ); + flush(); + + @include_once(ABSPATH . 'wp-cron.php'); + return; + } + + set_transient( 'doing_cron', $local_time ); + + $cron_url = get_option( 'siteurl' ) . '/wp-cron.php?doing_wp_cron'; + wp_remote_post( $cron_url, array('timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters('https_local_ssl_verify', true)) ); +} + +/** + * Run scheduled callbacks or spawn cron for all scheduled events. + * + * @since 2.1.0 + * + * @return null When doesn't need to run Cron. + */ +function wp_cron() { + + // Prevent infinite loops caused by lack of wp-cron.php + if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false || ( defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ) ) + return; + + if ( false === $crons = _get_cron_array() ) + return; + + $local_time = time(); + $keys = array_keys( $crons ); + if ( isset($keys[0]) && $keys[0] > $local_time ) + return; + + $schedules = wp_get_schedules(); + foreach ( $crons as $timestamp => $cronhooks ) { + if ( $timestamp > $local_time ) break; + foreach ( (array) $cronhooks as $hook => $args ) { + if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) ) + continue; + spawn_cron( $local_time ); + break 2; + } + } +} + +/** + * Retrieve supported and filtered Cron recurrences. + * + * The supported recurrences are 'hourly' and 'daily'. A plugin may add more by + * hooking into the 'cron_schedules' filter. The filter accepts an array of + * arrays. The outer array has a key that is the name of the schedule or for + * example 'weekly'. The value is an array with two keys, one is 'interval' and + * the other is 'display'. + * + * The 'interval' is a number in seconds of when the cron job should run. So for + * 'hourly', the time is 3600 or 60*60. For weekly, the value would be + * 60*60*24*7 or 604800. The value of 'interval' would then be 604800. + * + * The 'display' is the description. For the 'weekly' key, the 'display' would + * be __('Once Weekly'). + * + * For your plugin, you will be passed an array. you can easily add your + * schedule by doing the following. + * + * // filter parameter variable name is 'array' + * $array['weekly'] = array( + * 'interval' => 604800, + * 'display' => __('Once Weekly') + * ); + * + * + * @since 2.1.0 + * + * @return array + */ +function wp_get_schedules() { + $schedules = array( + 'hourly' => array( 'interval' => 3600, 'display' => __('Once Hourly') ), + 'twicedaily' => array( 'interval' => 43200, 'display' => __('Twice Daily') ), + 'daily' => array( 'interval' => 86400, 'display' => __('Once Daily') ), + ); + return array_merge( apply_filters( 'cron_schedules', array() ), $schedules ); +} + +/** + * Retrieve Cron schedule for hook with arguments. + * + * @since 2.1.0 + * + * @param string $hook Action hook to execute when cron is run. + * @param array $args Optional. Arguments to pass to the hook's callback function. + * @return string|bool False, if no schedule. Schedule on success. + */ +function wp_get_schedule($hook, $args = array()) { + $crons = _get_cron_array(); + $key = md5(serialize($args)); + if ( empty($crons) ) + return false; + foreach ( $crons as $timestamp => $cron ) { + if ( isset( $cron[$hook][$key] ) ) + return $cron[$hook][$key]['schedule']; + } + return false; +} + +// +// Private functions +// + +/** + * Retrieve cron info array option. + * + * @since 2.1.0 + * @access private + * + * @return array CRON info array. + */ +function _get_cron_array() { + $cron = get_option('cron'); + if ( ! is_array($cron) ) + return false; + + if ( !isset($cron['version']) ) + $cron = _upgrade_cron_array($cron); + + unset($cron['version']); + + return $cron; +} + +/** + * Updates the CRON option with the new CRON array. + * + * @since 2.1.0 + * @access private + * + * @param array $cron Cron info array from {@link _get_cron_array()}. + */ +function _set_cron_array($cron) { + $cron['version'] = 2; + update_option( 'cron', $cron ); +} + +/** + * Upgrade a Cron info array. + * + * This function upgrades the Cron info array to version 2. + * + * @since 2.1.0 + * @access private + * + * @param array $cron Cron info array from {@link _get_cron_array()}. + * @return array An upgraded Cron info array. + */ +function _upgrade_cron_array($cron) { + if ( isset($cron['version']) && 2 == $cron['version']) + return $cron; + + $new_cron = array(); + + foreach ( (array) $cron as $timestamp => $hooks) { + foreach ( (array) $hooks as $hook => $args ) { + $key = md5(serialize($args['args'])); + $new_cron[$timestamp][$hook][$key] = $args; + } + } + + $new_cron['version'] = 2; + update_option( 'cron', $new_cron ); + return $new_cron; +} + +// stub for checking server timer accuracy, using outside standard time sources +function check_server_timer( $local_time ) { + return true; +} + +?> diff --git a/wp-includes/default-filters.php b/wp-includes/default-filters.php new file mode 100644 index 0000000..2519d7a --- /dev/null +++ b/wp-includes/default-filters.php @@ -0,0 +1,212 @@ + diff --git a/wp-includes/default-widgets.php b/wp-includes/default-widgets.php new file mode 100644 index 0000000..54d1d40 --- /dev/null +++ b/wp-includes/default-widgets.php @@ -0,0 +1,1032 @@ + 'widget_pages', 'description' => __( 'Your blog’s WordPress Pages') ); + $this->WP_Widget('pages', __('Pages'), $widget_ops); + } + + function widget( $args, $instance ) { + extract( $args ); + + $title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Pages' ) : $instance['title']); + $sortby = empty( $instance['sortby'] ) ? 'menu_order' : $instance['sortby']; + $exclude = empty( $instance['exclude'] ) ? '' : $instance['exclude']; + + if ( $sortby == 'menu_order' ) + $sortby = 'menu_order, post_title'; + + $out = wp_list_pages( apply_filters('widget_pages_args', array('title_li' => '', 'echo' => 0, 'sort_column' => $sortby, 'exclude' => $exclude) ) ); + + if ( !empty( $out ) ) { + echo $before_widget; + if ( $title) + echo $before_title . $title . $after_title; + ?> +
      + +
    + 'post_title', 'title' => '', 'exclude' => '') ); + $title = esc_attr( $instance['title'] ); + $exclude = esc_attr( $instance['exclude'] ); + ?> +

    +

    + + +

    +

    + +
    + +

    + __( "Your blogroll" ) ); + $this->WP_Widget('links', __('Links'), $widget_ops); + } + + function widget( $args, $instance ) { + extract($args, EXTR_SKIP); + + $show_description = isset($instance['description']) ? $instance['description'] : false; + $show_name = isset($instance['name']) ? $instance['name'] : false; + $show_rating = isset($instance['rating']) ? $instance['rating'] : false; + $show_images = isset($instance['images']) ? $instance['images'] : true; + $category = isset($instance['category']) ? $instance['category'] : false; + + if ( is_admin() && !$category ) { + // Display All Links widget as such in the widgets screen + echo $before_widget . $before_title. __('All Links') . $after_title . $after_widget; + return; + } + + $before_widget = preg_replace('/id="[^"]*"/','id="%id"', $before_widget); + wp_list_bookmarks(apply_filters('widget_links_args', array( + 'title_before' => $before_title, 'title_after' => $after_title, + 'category_before' => $before_widget, 'category_after' => $after_widget, + 'show_images' => $show_images, 'show_description' => $show_description, + 'show_name' => $show_name, 'show_rating' => $show_rating, + 'category' => $category, 'class' => 'linkcat widget' + ))); + } + + function update( $new_instance, $old_instance ) { + $new_instance = (array) $new_instance; + $instance = array( 'images' => 0, 'name' => 0, 'description' => 0, 'rating' => 0); + foreach ( $instance as $field => $val ) { + if ( isset($new_instance[$field]) ) + $instance[$field] = 1; + } + $instance['category'] = intval($new_instance['category']); + + return $instance; + } + + function form( $instance ) { + + //Defaults + $instance = wp_parse_args( (array) $instance, array( 'images' => true, 'name' => true, 'description' => false, 'rating' => false, 'category' => false ) ); + $link_cats = get_terms( 'link_category'); +?> +

    + +

    +

    + id="get_field_id('images'); ?>" name="get_field_name('images'); ?>" /> +
    + id="get_field_id('name'); ?>" name="get_field_name('name'); ?>" /> +
    + id="get_field_id('description'); ?>" name="get_field_name('description'); ?>" /> +
    + id="get_field_id('rating'); ?>" name="get_field_name('rating'); ?>" /> + +

    + 'widget_search', 'description' => __( "A search form for your blog") ); + $this->WP_Widget('search', __('Search'), $widget_ops); + } + + function widget( $args, $instance ) { + extract($args); + $title = apply_filters('widget_title', $instance['title']); + + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; + + // Use current theme search form if it exists + get_search_form(); + + echo $after_widget; + } + + function form( $instance ) { + $instance = wp_parse_args( (array) $instance, array( 'title' => '') ); + $title = $instance['title']; +?> +

    + '')); + $instance['title'] = strip_tags($new_instance['title']); + return $instance; + } + +} + +/** + * Archives widget class + * + * @since 2.8.0 + */ +class WP_Widget_Archives extends WP_Widget { + + function WP_Widget_Archives() { + $widget_ops = array('classname' => 'widget_archive', 'description' => __( 'A monthly archive of your blog’s posts') ); + $this->WP_Widget('archives', __('Archives'), $widget_ops); + } + + function widget( $args, $instance ) { + extract($args); + $c = $instance['count'] ? '1' : '0'; + $d = $instance['dropdown'] ? '1' : '0'; + $title = apply_filters('widget_title', empty($instance['title']) ? __('Archives') : $instance['title']); + + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; + + if ( $d ) { +?> + + +
      + 'monthly', 'show_post_count' => $c))); ?> +
    + '', 'count' => 0, 'dropdown' => '') ); + $instance['title'] = strip_tags($new_instance['title']); + $instance['count'] = $new_instance['count'] ? 1 : 0; + $instance['dropdown'] = $new_instance['dropdown'] ? 1 : 0; + + return $instance; + } + + function form( $instance ) { + $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'count' => 0, 'dropdown' => '') ); + $title = strip_tags($instance['title']); + $count = $instance['count'] ? 'checked="checked"' : ''; + $dropdown = $instance['dropdown'] ? 'checked="checked"' : ''; +?> +

    +

    + id="get_field_id('count'); ?>" name="get_field_name('count'); ?>" /> +
    + id="get_field_id('dropdown'); ?>" name="get_field_name('dropdown'); ?>" /> +

    + 'widget_meta', 'description' => __( "Log in/out, admin, feed and WordPress links") ); + $this->WP_Widget('meta', __('Meta'), $widget_ops); + } + + function widget( $args, $instance ) { + extract($args); + $title = apply_filters('widget_title', empty($instance['title']) ? __('Meta') : $instance['title']); + + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; +?> + + '' ) ); + $title = strip_tags($instance['title']); +?> +

    + 'widget_calendar', 'description' => __( 'A calendar of your blog’s posts') ); + $this->WP_Widget('calendar', __('Calendar'), $widget_ops); + } + + function widget( $args, $instance ) { + extract($args); + $title = apply_filters('widget_title', empty($instance['title']) ? ' ' : $instance['title']); + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; + echo '
    '; + get_calendar(); + echo '
    '; + echo $after_widget; + } + + function update( $new_instance, $old_instance ) { + $instance = $old_instance; + $instance['title'] = strip_tags($new_instance['title']); + + return $instance; + } + + function form( $instance ) { + $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); + $title = strip_tags($instance['title']); +?> +

    +

    + 'widget_text', 'description' => __('Arbitrary text or HTML')); + $control_ops = array('width' => 400, 'height' => 350); + $this->WP_Widget('text', __('Text'), $widget_ops, $control_ops); + } + + function widget( $args, $instance ) { + extract($args); + $title = apply_filters('widget_title', empty($instance['title']) ? '' : $instance['title']); + $text = apply_filters( 'widget_text', $instance['text'] ); + echo $before_widget; + if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?> +
    + '', 'text' => '' ) ); + $title = strip_tags($instance['title']); + $text = format_to_edit($instance['text']); +?> +

    +

    + + + +

    /> 

    + 'widget_categories', 'description' => __( "A list or dropdown of categories" ) ); + $this->WP_Widget('categories', __('Categories'), $widget_ops); + } + + function widget( $args, $instance ) { + extract( $args ); + + $title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Categories' ) : $instance['title']); + $c = $instance['count'] ? '1' : '0'; + $h = $instance['hierarchical'] ? '1' : '0'; + $d = $instance['dropdown'] ? '1' : '0'; + + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; + + $cat_args = array('orderby' => 'name', 'show_count' => $c, 'hierarchical' => $h); + + if ( $d ) { + $cat_args['show_option_none'] = __('Select Category'); + wp_dropdown_categories(apply_filters('widget_categories_dropdown_args', $cat_args)); +?> + + + + +
      + +
    + '') ); + $title = esc_attr( $instance['title'] ); + $count = (bool) $instance['count']; + $hierarchical = (bool) $instance['hierarchical']; + $dropdown = (bool) $instance['dropdown']; +?> +

    +

    + +

    /> +
    + + /> +
    + + /> +

    + 'widget_recent_entries', 'description' => __( "The most recent posts on your blog") ); + $this->WP_Widget('recent-posts', __('Recent Posts'), $widget_ops); + $this->alt_option_name = 'widget_recent_entries'; + + add_action( 'save_post', array(&$this, 'flush_widget_cache') ); + add_action( 'deleted_post', array(&$this, 'flush_widget_cache') ); + add_action( 'switch_theme', array(&$this, 'flush_widget_cache') ); + } + + function widget($args, $instance) { + $cache = wp_cache_get('widget_recent_posts', 'widget'); + + if ( !is_array($cache) ) + $cache = array(); + + if ( isset($cache[$args['widget_id']]) ) { + echo $cache[$args['widget_id']]; + return; + } + + ob_start(); + extract($args); + + $title = apply_filters('widget_title', empty($instance['title']) ? __('Recent Posts') : $instance['title']); + if ( !$number = (int) $instance['number'] ) + $number = 10; + else if ( $number < 1 ) + $number = 1; + else if ( $number > 15 ) + $number = 15; + + $r = new WP_Query(array('showposts' => $number, 'nopaging' => 0, 'post_status' => 'publish', 'caller_get_posts' => 1)); + if ($r->have_posts()) : +?> + + +
      + have_posts()) : $r->the_post(); ?> +
    • + +
    + +flush_widget_cache(); + + $alloptions = wp_cache_get( 'alloptions', 'options' ); + if ( isset($alloptions['widget_recent_entries']) ) + delete_option('widget_recent_entries'); + + return $instance; + } + + function flush_widget_cache() { + wp_cache_delete('widget_recent_posts', 'widget'); + } + + function form( $instance ) { + $title = esc_attr($instance['title']); + if ( !$number = (int) $instance['number'] ) + $number = 5; +?> +

    +

    + +

    +
    +

    + 'widget_recent_comments', 'description' => __( 'The most recent comments' ) ); + $this->WP_Widget('recent-comments', __('Recent Comments'), $widget_ops); + $this->alt_option_name = 'widget_recent_comments'; + + if ( is_active_widget(false, false, $this->id_base) ) + add_action( 'wp_head', array(&$this, 'recent_comments_style') ); + + add_action( 'comment_post', array(&$this, 'flush_widget_cache') ); + add_action( 'wp_set_comment_status', array(&$this, 'flush_widget_cache') ); + } + + function recent_comments_style() { ?> + + 15 ) + $number = 15; + + if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) { + $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 15"); + wp_cache_add( 'recent_comments', $comments, 'widget' ); + } + + $comments = array_slice( (array) $comments, 0, $number ); +?> + + + + +flush_widget_cache(); + + $alloptions = wp_cache_get( 'alloptions', 'options' ); + if ( isset($alloptions['widget_recent_comments']) ) + delete_option('widget_recent_comments'); + + return $instance; + } + + function form( $instance ) { + $title = isset($instance['title']) ? esc_attr($instance['title']) : ''; + $number = isset($instance['number']) ? absint($instance['number']) : 5; +?> +

    +

    + +

    +
    +

    + __('Entries from any RSS or Atom feed') ); + $control_ops = array( 'width' => 400, 'height' => 200 ); + $this->WP_Widget( 'rss', __('RSS'), $widget_ops, $control_ops ); + } + + function widget($args, $instance) { + + if ( isset($instance['error']) && $instance['error'] ) + return; + + extract($args, EXTR_SKIP); + + $url = $instance['url']; + while ( stristr($url, 'http') != $url ) + $url = substr($url, 1); + + if ( empty($url) ) + return; + + $rss = fetch_feed($url); + $title = $instance['title']; + $desc = ''; + $link = ''; + + if ( ! is_wp_error($rss) ) { + $desc = esc_attr(strip_tags(@html_entity_decode($rss->get_description(), ENT_QUOTES, get_option('blog_charset')))); + if ( empty($title) ) + $title = esc_html(strip_tags($rss->get_title())); + $link = esc_url(strip_tags($rss->get_permalink())); + while ( stristr($link, 'http') != $link ) + $link = substr($link, 1); + } + + if ( empty($title) ) + $title = empty($desc) ? __('Unknown Feed') : $desc; + + $title = apply_filters('widget_title', $title ); + $url = esc_url(strip_tags($url)); + $icon = includes_url('images/rss.png'); + if ( $title ) + $title = "RSS $title"; + + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; + wp_widget_rss_output( $rss, $instance ); + echo $after_widget; + } + + function update($new_instance, $old_instance) { + $testurl = $new_instance['url'] != $old_instance['url']; + return wp_widget_rss_process( $new_instance, $testurl ); + } + + function form($instance) { + + if ( empty($instance) ) + $instance = array( 'title' => '', 'url' => '', 'items' => 10, 'error' => false, 'show_summary' => 0, 'show_author' => 0, 'show_date' => 0 ); + $instance['number'] = $this->number; + + wp_widget_rss_form( $instance ); + } +} + +/** + * Display the RSS entries in a list. + * + * @since 2.5.0 + * + * @param string|array|object $rss RSS url. + * @param array $args Widget arguments. + */ +function wp_widget_rss_output( $rss, $args = array() ) { + if ( is_string( $rss ) ) { + $rss = fetch_feed($rss); + } elseif ( is_array($rss) && isset($rss['url']) ) { + $args = $rss; + $rss = fetch_feed($rss['url']); + } elseif ( !is_object($rss) ) { + return; + } + + if ( is_wp_error($rss) ) { + if ( is_admin() || current_user_can('manage_options') ) + echo '

    ' . sprintf( __('RSS Error: %s'), $rss->get_error_message() ) . '

    '; + + return; + } + + $default_args = array( 'show_author' => 0, 'show_date' => 0, 'show_summary' => 0 ); + $args = wp_parse_args( $args, $default_args ); + extract( $args, EXTR_SKIP ); + + $items = (int) $items; + if ( $items < 1 || 20 < $items ) + $items = 10; + $show_summary = (int) $show_summary; + $show_author = (int) $show_author; + $show_date = (int) $show_date; + + if ( !$rss->get_item_quantity() ) { + echo '
    • ' . __( 'An error has occurred; the feed is probably down. Try again later.' ) . '
    '; + return; + } + + echo '
      '; + foreach ( $rss->get_items(0, $items) as $item ) { + $link = $item->get_link(); + while ( stristr($link, 'http') != $link ) + $link = substr($link, 1); + $link = esc_url(strip_tags($link)); + $title = esc_attr(strip_tags($item->get_title())); + if ( empty($title) ) + $title = __('Untitled'); + + $desc = str_replace(array("\n", "\r"), ' ', esc_attr(strip_tags(@html_entity_decode($item->get_description(), ENT_QUOTES, get_option('blog_charset'))))); + $desc = wp_html_excerpt( $desc, 360 ) . ' […]'; + $desc = esc_html( $desc ); + + if ( $show_summary ) { + $summary = "
      $desc
      "; + } else { + $summary = ''; + } + + $date = ''; + if ( $show_date ) { + $date = $item->get_date(); + + if ( $date ) { + if ( $date_stamp = strtotime( $date ) ) + $date = ' ' . date_i18n( get_option( 'date_format' ), $date_stamp ) . ''; + else + $date = ''; + } + } + + $author = ''; + if ( $show_author ) { + $author = $item->get_author(); + if ( is_object($author) ) { + $author = $author->get_name(); + $author = ' ' . esc_html( strip_tags( $author ) ) . ''; + } + } + + if ( $link == '' ) { + echo "
    • $title{$date}{$summary}{$author}
    • "; + } else { + echo "
    • $title{$date}{$summary}{$author}
    • "; + } + } + echo '
    '; +} + + + +/** + * Display RSS widget options form. + * + * The options for what fields are displayed for the RSS form are all booleans + * and are as follows: 'url', 'title', 'items', 'show_summary', 'show_author', + * 'show_date'. + * + * @since 2.5.0 + * + * @param array|string $args Values for input fields. + * @param array $inputs Override default display options. + */ +function wp_widget_rss_form( $args, $inputs = null ) { + + $default_inputs = array( 'url' => true, 'title' => true, 'items' => true, 'show_summary' => true, 'show_author' => true, 'show_date' => true ); + $inputs = wp_parse_args( $inputs, $default_inputs ); + extract( $args ); + extract( $inputs, EXTR_SKIP); + + $number = esc_attr( $number ); + $title = esc_attr( $title ); + $url = esc_url( $url ); + $items = (int) $items; + if ( $items < 1 || 20 < $items ) + $items = 10; + $show_summary = (int) $show_summary; + $show_author = (int) $show_author; + $show_date = (int) $show_date; + + if ( !empty($error) ) + echo '

    ' . sprintf( __('RSS Error: %s'), $error) . '

    '; + + if ( $inputs['url'] ) : +?> +

    +

    + +

    +

    + +

    +

    + +

    /> +

    + +

    /> +

    + +

    /> +

    + + +get_error_message(); + } else { + $link = esc_url(strip_tags($rss->get_permalink())); + while ( stristr($link, 'http') != $link ) + $link = substr($link, 1); + } + } + + return compact( 'title', 'url', 'link', 'items', 'error', 'show_summary', 'show_author', 'show_date' ); +} + +/** + * Tag cloud widget class + * + * @since 2.8.0 + */ +class WP_Widget_Tag_Cloud extends WP_Widget { + + function WP_Widget_Tag_Cloud() { + $widget_ops = array( 'description' => __( "Your most used tags in cloud format") ); + $this->WP_Widget('tag_cloud', __('Tag Cloud'), $widget_ops); + } + + function widget( $args, $instance ) { + extract($args); + $title = apply_filters('widget_title', empty($instance['title']) ? __('Tags') : $instance['title']); + + echo $before_widget; + if ( $title ) + echo $before_title . $title . $after_title; + echo '
    '; + wp_tag_cloud(apply_filters('widget_tag_cloud_args', array())); + echo "
    \n"; + echo $after_widget; + } + + function update( $new_instance, $old_instance ) { + $instance['title'] = strip_tags(stripslashes($new_instance['title'])); + return $instance; + } + + function form( $instance ) { +?> +

    +

    +posts + */ +$tableposts = $wpdb->posts; + +/** + * The name of the Users table + * @global string $tableusers + * @deprecated Use $wpdb->users + */ +$tableusers = $wpdb->users; + +/** + * The name of the Categories table + * @global string $tablecategories + * @deprecated Use $wpdb->categories + */ +$tablecategories = $wpdb->categories; + +/** + * The name of the post to category table + * @global string $tablepost2cat + * @deprecated Use $wpdb->post2cat; + */ +$tablepost2cat = $wpdb->post2cat; + +/** + * The name of the comments table + * @global string $tablecomments + * @deprecated Use $wpdb->comments; + */ +$tablecomments = $wpdb->comments; + +/** + * The name of the links table + * @global string $tablelinks + * @deprecated Use $wpdb->links; + */ +$tablelinks = $wpdb->links; + +/** + * @global string $tablelinkcategories + * @deprecated Not used anymore; + */ +$tablelinkcategories = 'linkcategories_is_gone'; + +/** + * The name of the options table + * @global string $tableoptions + * @deprecated Use $wpdb->options; + */ +$tableoptions = $wpdb->options; + +/** + * The name of the postmeta table + * @global string $tablepostmeta + * @deprecated Use $wpdb->postmeta; + */ +$tablepostmeta = $wpdb->postmeta; + +/* + * Deprecated functions come here to die. + */ + +/** + * Entire Post data. + * + * @since 0.71 + * @deprecated Use get_post() + * @see get_post() + * + * @param int $postid + * @return array + */ +function get_postdata($postid) { + _deprecated_function(__FUNCTION__, '0.0', 'get_post()'); + + $post = &get_post($postid); + + $postdata = array ( + 'ID' => $post->ID, + 'Author_ID' => $post->post_author, + 'Date' => $post->post_date, + 'Content' => $post->post_content, + 'Excerpt' => $post->post_excerpt, + 'Title' => $post->post_title, + 'Category' => $post->post_category, + 'post_status' => $post->post_status, + 'comment_status' => $post->comment_status, + 'ping_status' => $post->ping_status, + 'post_password' => $post->post_password, + 'to_ping' => $post->to_ping, + 'pinged' => $post->pinged, + 'post_type' => $post->post_type, + 'post_name' => $post->post_name + ); + + return $postdata; +} + +/** + * Sets up the WordPress Loop. + * + * @since 1.0.1 + * @deprecated Since 1.5 - {@link http://codex.wordpress.org/The_Loop Use new WordPress Loop} + */ +function start_wp() { + global $wp_query, $post; + + _deprecated_function(__FUNCTION__, '1.5', __('new WordPress Loop') ); + + // Since the old style loop is being used, advance the query iterator here. + $wp_query->next_post(); + + setup_postdata($post); +} + +/** + * Return or Print Category ID. + * + * @since 0.71 + * @deprecated use get_the_category() + * @see get_the_category() + * + * @param bool $echo + * @return null|int + */ +function the_category_ID($echo = true) { + _deprecated_function(__FUNCTION__, '0.0', 'get_the_category()'); + + // Grab the first cat in the list. + $categories = get_the_category(); + $cat = $categories[0]->term_id; + + if ( $echo ) + echo $cat; + + return $cat; +} + +/** + * Print category with optional text before and after. + * + * @since 0.71 + * @deprecated use get_the_category_by_ID() + * @see get_the_category_by_ID() + * + * @param string $before + * @param string $after + */ +function the_category_head($before='', $after='') { + global $currentcat, $previouscat; + + _deprecated_function(__FUNCTION__, '0.0', 'get_the_category_by_ID()'); + + // Grab the first cat in the list. + $categories = get_the_category(); + $currentcat = $categories[0]->category_id; + if ( $currentcat != $previouscat ) { + echo $before; + echo get_the_category_by_ID($currentcat); + echo $after; + $previouscat = $currentcat; + } +} + +/** + * Prints link to the previous post. + * + * @since 1.5 + * @deprecated Use previous_post_link() + * @see previous_post_link() + * + * @param string $format + * @param string $previous + * @param string $title + * @param string $in_same_cat + * @param int $limitprev + * @param string $excluded_categories + */ +function previous_post($format='%', $previous='previous post: ', $title='yes', $in_same_cat='no', $limitprev=1, $excluded_categories='') { + + _deprecated_function(__FUNCTION__, '0.0', 'previous_post_link()'); + + if ( empty($in_same_cat) || 'no' == $in_same_cat ) + $in_same_cat = false; + else + $in_same_cat = true; + + $post = get_previous_post($in_same_cat, $excluded_categories); + + if ( !$post ) + return; + + $string = ''.$previous; + if ( 'yes' == $title ) + $string .= apply_filters('the_title', $post->post_title, $post); + $string .= ''; + $format = str_replace('%', $string, $format); + echo $format; +} + +/** + * Prints link to the next post. + * + * @since 0.71 + * @deprecated Use next_post_link() + * @see next_post_link() + * + * @param string $format + * @param string $previous + * @param string $title + * @param string $in_same_cat + * @param int $limitprev + * @param string $excluded_categories + */ +function next_post($format='%', $next='next post: ', $title='yes', $in_same_cat='no', $limitnext=1, $excluded_categories='') { + _deprecated_function(__FUNCTION__, '0.0', 'next_post_link()'); + + if ( empty($in_same_cat) || 'no' == $in_same_cat ) + $in_same_cat = false; + else + $in_same_cat = true; + + $post = get_next_post($in_same_cat, $excluded_categories); + + if ( !$post ) + return; + + $string = ''.$next; + if ( 'yes' == $title ) + $string .= apply_filters('the_title', $post->post_title, $nextpost); + $string .= ''; + $format = str_replace('%', $string, $format); + echo $format; +} + +/** + * Whether user can create a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $blog_id Not Used + * @param int $category_id Not Used + * @return bool + */ +function user_can_create_post($user_id, $blog_id = 1, $category_id = 'None') { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + $author_data = get_userdata($user_id); + return ($author_data->user_level > 1); +} + +/** + * Whether user can create a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $blog_id Not Used + * @param int $category_id Not Used + * @return bool + */ +function user_can_create_draft($user_id, $blog_id = 1, $category_id = 'None') { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + $author_data = get_userdata($user_id); + return ($author_data->user_level >= 1); +} + +/** + * Whether user can edit a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $post_id + * @param int $blog_id Not Used + * @return bool + */ +function user_can_edit_post($user_id, $post_id, $blog_id = 1) { + _deprecated_function(__FUNCTION__, '0', 'current_user_can()'); + + $author_data = get_userdata($user_id); + $post = get_post($post_id); + $post_author_data = get_userdata($post->post_author); + + if ( (($user_id == $post_author_data->ID) && !($post->post_status == 'publish' && $author_data->user_level < 2)) + || ($author_data->user_level > $post_author_data->user_level) + || ($author_data->user_level >= 10) ) { + return true; + } else { + return false; + } +} + +/** + * Whether user can delete a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $post_id + * @param int $blog_id Not Used + * @return bool + */ +function user_can_delete_post($user_id, $post_id, $blog_id = 1) { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + // right now if one can edit, one can delete + return user_can_edit_post($user_id, $post_id, $blog_id); +} + +/** + * Whether user can set new posts' dates. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $blog_id Not Used + * @param int $category_id Not Used + * @return bool + */ +function user_can_set_post_date($user_id, $blog_id = 1, $category_id = 'None') { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + $author_data = get_userdata($user_id); + return (($author_data->user_level > 4) && user_can_create_post($user_id, $blog_id, $category_id)); +} + +/** + * Whether user can delete a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $post_id + * @param int $blog_id Not Used + * @return bool returns true if $user_id can edit $post_id's date + */ +function user_can_edit_post_date($user_id, $post_id, $blog_id = 1) { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + $author_data = get_userdata($user_id); + return (($author_data->user_level > 4) && user_can_edit_post($user_id, $post_id, $blog_id)); +} + +/** + * Whether user can delete a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $post_id + * @param int $blog_id Not Used + * @return bool returns true if $user_id can edit $post_id's comments + */ +function user_can_edit_post_comments($user_id, $post_id, $blog_id = 1) { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + // right now if one can edit a post, one can edit comments made on it + return user_can_edit_post($user_id, $post_id, $blog_id); +} + +/** + * Whether user can delete a post. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $post_id + * @param int $blog_id Not Used + * @return bool returns true if $user_id can delete $post_id's comments + */ +function user_can_delete_post_comments($user_id, $post_id, $blog_id = 1) { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + // right now if one can edit comments, one can delete comments + return user_can_edit_post_comments($user_id, $post_id, $blog_id); +} + +/** + * Can user can edit other user. + * + * @since 1.5 + * @deprecated Use current_user_can() + * @see current_user_can() + * + * @param int $user_id + * @param int $other_user + * @return bool + */ +function user_can_edit_user($user_id, $other_user) { + _deprecated_function(__FUNCTION__, '0.0', 'current_user_can()'); + + $user = get_userdata($user_id); + $other = get_userdata($other_user); + if ( $user->user_level > $other->user_level || $user->user_level > 8 || $user->ID == $other->ID ) + return true; + else + return false; +} + +/** + * Gets the links associated with category $cat_name. + * + * @since 0.71 + * @deprecated Use get_links() + * @see get_links() + * + * @param string $cat_name Optional. The category name to use. If no match is found uses all. + * @param string $before Optional. The html to output before the link. + * @param string $after Optional. The html to output after the link. + * @param string $between Optional. The html to output between the link/image and it's description. Not used if no image or $show_images is true. + * @param bool $show_images Optional. Whether to show images (if defined). + * @param string $orderby Optional. The order to output the links. E.g. 'id', 'name', 'url', 'description' or 'rating'. Or maybe owner. + * If you start the name with an underscore the order will be reversed. You can also specify 'rand' as the order which will return links in a + * random order. + * @param bool $show_description Optional. Whether to show the description if show_images=false/not defined. + * @param bool $show_rating Optional. Show rating stars/chars. + * @param int $limit Optional. Limit to X entries. If not specified, all entries are shown. + * @param int $show_updated Optional. Whether to show last updated timestamp + */ +function get_linksbyname($cat_name = "noname", $before = '', $after = '
    ', $between = " ", $show_images = true, $orderby = 'id', + $show_description = true, $show_rating = false, + $limit = -1, $show_updated = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'get_links()'); + + $cat_id = -1; + $cat = get_term_by('name', $cat_name, 'link_category'); + if ( $cat ) + $cat_id = $cat->term_id; + + get_links($cat_id, $before, $after, $between, $show_images, $orderby, $show_description, $show_rating, $limit, $show_updated); +} + +/** + * Gets the links associated with the named category. + * + * @since 1.0.1 + * @deprecated Use wp_get_links() + * @see wp_get_links() + * + * @param string $category The category to use. + * @param string $args + * @return bool|null + */ +function wp_get_linksbyname($category, $args = '') { + _deprecated_function(__FUNCTION__, '0.0', 'wp_get_links()'); + + $cat = get_term_by('name', $category, 'link_category'); + if ( !$cat ) + return false; + $cat_id = $cat->term_id; + + $args = add_query_arg('category', $cat_id, $args); + wp_get_links($args); +} + +/** + * Gets an array of link objects associated with category $cat_name. + * + * + * $links = get_linkobjectsbyname('fred'); + * foreach ($links as $link) { + * echo '
  • '.$link->link_name.'
  • '; + * } + *
    + * + * @since 1.0.1 + * @deprecated Use get_linkobjects() + * @see get_linkobjects() + * + * @param string $cat_name The category name to use. If no match is found uses all. + * @param string $orderby The order to output the links. E.g. 'id', 'name', 'url', 'description', or 'rating'. + * Or maybe owner. If you start the name with an underscore the order will be reversed. You can also + * specify 'rand' as the order which will return links in a random order. + * @param int $limit Limit to X entries. If not specified, all entries are shown. + * @return unknown + */ +function get_linkobjectsbyname($cat_name = "noname" , $orderby = 'name', $limit = -1) { + _deprecated_function(__FUNCTION__, '0.0', 'get_linkobjects()'); + + $cat_id = -1; + $cat = get_term_by('name', $cat_name, 'link_category'); + if ( $cat ) + $cat_id = $cat->term_id; + + return get_linkobjects($cat_id, $orderby, $limit); +} + +/** + * Gets an array of link objects associated with category n. + * + * Usage: + * + * $links = get_linkobjects(1); + * if ($links) { + * foreach ($links as $link) { + * echo '
  • '.$link->link_name.'
    '.$link->link_description.'
  • '; + * } + * } + *
    + * + * Fields are: + *
      + *
    1. link_id
    2. + *
    3. link_url
    4. + *
    5. link_name
    6. + *
    7. link_image
    8. + *
    9. link_target
    10. + *
    11. link_category
    12. + *
    13. link_description
    14. + *
    15. link_visible
    16. + *
    17. link_owner
    18. + *
    19. link_rating
    20. + *
    21. link_updated
    22. + *
    23. link_rel
    24. + *
    25. link_notes
    26. + *
    + * + * @since 1.0.1 + * @deprecated Use get_bookmarks() + * @see get_bookmarks() + * + * @param int $category The category to use. If no category supplied uses all + * @param string $orderby the order to output the links. E.g. 'id', 'name', 'url', + * 'description', or 'rating'. Or maybe owner. If you start the name with an + * underscore the order will be reversed. You can also specify 'rand' as the + * order which will return links in a random order. + * @param int $limit Limit to X entries. If not specified, all entries are shown. + * @return unknown + */ +function get_linkobjects($category = 0, $orderby = 'name', $limit = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'get_bookmarks()'); + + $links = get_bookmarks("category=$category&orderby=$orderby&limit=$limit"); + + $links_array = array(); + foreach ($links as $link) + $links_array[] = $link; + + return $links_array; +} + +/** + * Gets the links associated with category 'cat_name' and display rating stars/chars. + * + * @since 0.71 + * @deprecated Use get_bookmarks() + * @see get_bookmarks() + * + * @param string $cat_name The category name to use. If no match is found uses all + * @param string $before The html to output before the link + * @param string $after The html to output after the link + * @param string $between The html to output between the link/image and it's description. Not used if no image or show_images is true + * @param bool $show_images Whether to show images (if defined). + * @param string $orderby the order to output the links. E.g. 'id', 'name', 'url', + * 'description', or 'rating'. Or maybe owner. If you start the name with an + * underscore the order will be reversed. You can also specify 'rand' as the + * order which will return links in a random order. + * @param bool $show_description Whether to show the description if show_images=false/not defined + * @param int $limit Limit to X entries. If not specified, all entries are shown. + * @param int $show_updated Whether to show last updated timestamp + */ +function get_linksbyname_withrating($cat_name = "noname", $before = '', $after = '
    ', $between = " ", + $show_images = true, $orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'get_bookmarks()'); + + get_linksbyname($cat_name, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated); +} + +/** + * Gets the links associated with category n and display rating stars/chars. + * + * @since 0.71 + * @deprecated Use get_bookmarks() + * @see get_bookmarks() + * + * @param int $category The category to use. If no category supplied uses all + * @param string $before The html to output before the link + * @param string $after The html to output after the link + * @param string $between The html to output between the link/image and it's description. Not used if no image or show_images == true + * @param bool $show_images Whether to show images (if defined). + * @param string $orderby The order to output the links. E.g. 'id', 'name', 'url', + * 'description', or 'rating'. Or maybe owner. If you start the name with an + * underscore the order will be reversed. You can also specify 'rand' as the + * order which will return links in a random order. + * @param bool $show_description Whether to show the description if show_images=false/not defined. + * @param string $limit Limit to X entries. If not specified, all entries are shown. + * @param int $show_updated Whether to show last updated timestamp + */ +function get_links_withrating($category = -1, $before = '', $after = '
    ', $between = " ", $show_images = true, + $orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'get_bookmarks()'); + + get_links($category, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated); +} + +/** + * Gets the auto_toggle setting. + * + * @since 0.71 + * @deprecated No alternative function available + * + * @param int $id The category to get. If no category supplied uses 0 + * @return int Only returns 0. + */ +function get_autotoggle($id = 0) { + _deprecated_function(__FUNCTION__, '0.0' ); + return 0; +} + +/** + * @since 0.71 + * @deprecated Use wp_list_categories() + * @see wp_list_categories() + * + * @param int $optionall + * @param string $all + * @param string $sort_column + * @param string $sort_order + * @param string $file + * @param bool $list + * @param int $optiondates + * @param int $optioncount + * @param int $hide_empty + * @param int $use_desc_for_title + * @param bool $children + * @param int $child_of + * @param int $categories + * @param int $recurse + * @param string $feed + * @param string $feed_image + * @param string $exclude + * @param bool $hierarchical + * @return unknown + */ +function list_cats($optionall = 1, $all = 'All', $sort_column = 'ID', $sort_order = 'asc', $file = '', $list = true, $optiondates = 0, + $optioncount = 0, $hide_empty = 1, $use_desc_for_title = 1, $children=false, $child_of=0, $categories=0, + $recurse=0, $feed = '', $feed_image = '', $exclude = '', $hierarchical=false) { + _deprecated_function(__FUNCTION__, '0.0', 'wp_list_categories()'); + + $query = compact('optionall', 'all', 'sort_column', 'sort_order', 'file', 'list', 'optiondates', 'optioncount', 'hide_empty', 'use_desc_for_title', 'children', + 'child_of', 'categories', 'recurse', 'feed', 'feed_image', 'exclude', 'hierarchical'); + return wp_list_cats($query); +} + +/** + * @since 1.2 + * @deprecated Use wp_list_categories() + * @see wp_list_categories() + * + * @param string|array $args + * @return unknown + */ +function wp_list_cats($args = '') { + _deprecated_function(__FUNCTION__, '0.0', 'wp_list_categories()'); + + $r = wp_parse_args( $args ); + + // Map to new names. + if ( isset($r['optionall']) && isset($r['all'])) + $r['show_option_all'] = $r['all']; + if ( isset($r['sort_column']) ) + $r['orderby'] = $r['sort_column']; + if ( isset($r['sort_order']) ) + $r['order'] = $r['sort_order']; + if ( isset($r['optiondates']) ) + $r['show_last_update'] = $r['optiondates']; + if ( isset($r['optioncount']) ) + $r['show_count'] = $r['optioncount']; + if ( isset($r['list']) ) + $r['style'] = $r['list'] ? 'list' : 'break'; + $r['title_li'] = ''; + + return wp_list_categories($r); +} + +/** + * @since 0.71 + * @deprecated Use wp_dropdown_categories() + * @see wp_dropdown_categories() + * + * @param int $optionall + * @param string $all + * @param string $orderby + * @param string $order + * @param int $show_last_update + * @param int $show_count + * @param int $hide_empty + * @param bool $optionnone + * @param int $selected + * @param int $exclude + * @return unknown + */ +function dropdown_cats($optionall = 1, $all = 'All', $orderby = 'ID', $order = 'asc', + $show_last_update = 0, $show_count = 0, $hide_empty = 1, $optionnone = false, + $selected = 0, $exclude = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'wp_dropdown_categories()'); + + $show_option_all = ''; + if ( $optionall ) + $show_option_all = $all; + + $show_option_none = ''; + if ( $optionnone ) + $show_option_none = __('None'); + + $vars = compact('show_option_all', 'show_option_none', 'orderby', 'order', + 'show_last_update', 'show_count', 'hide_empty', 'selected', 'exclude'); + $query = add_query_arg($vars, ''); + return wp_dropdown_categories($query); +} + +/** + * @since 2.1 + * @deprecated Use wp_tiny_mce(). + * @see wp_tiny_mce() + */ +function tinymce_include() { + _deprecated_function(__FUNCTION__, '0.0', 'wp_tiny_mce()'); + + wp_tiny_mce(); +} + +/** + * @since 1.2 + * @deprecated Use wp_list_authors() + * @see wp_list_authors() + * + * @param bool $optioncount + * @param bool $exclude_admin + * @param bool $show_fullname + * @param bool $hide_empty + * @param string $feed + * @param string $feed_image + * @return unknown + */ +function list_authors($optioncount = false, $exclude_admin = true, $show_fullname = false, $hide_empty = true, $feed = '', $feed_image = '') { + _deprecated_function(__FUNCTION__, '0.0', 'wp_list_authors()'); + + $args = compact('optioncount', 'exclude_admin', 'show_fullname', 'hide_empty', 'feed', 'feed_image'); + return wp_list_authors($args); +} + +/** + * @since 1.0.1 + * @deprecated Use wp_get_post_categories() + * @see wp_get_post_categories() + * + * @param int $blogid Not Used + * @param int $post_ID + * @return unknown + */ +function wp_get_post_cats($blogid = '1', $post_ID = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'wp_get_post_categories()'); + return wp_get_post_categories($post_ID); +} + +/** + * Sets the categories that the post id belongs to. + * + * @since 1.0.1 + * @deprecated Use wp_set_post_categories() + * @see wp_set_post_categories() + * + * @param int $blogid Not used + * @param int $post_ID + * @param array $post_categories + * @return unknown + */ +function wp_set_post_cats($blogid = '1', $post_ID = 0, $post_categories = array()) { + _deprecated_function(__FUNCTION__, '0.0', 'wp_set_post_categories()'); + return wp_set_post_categories($post_ID, $post_categories); +} + +/** + * @since 0.71 + * @deprecated Use wp_get_archives() + * @see wp_get_archives() + * + * @param string $type + * @param string $limit + * @param string $format + * @param string $before + * @param string $after + * @param bool $show_post_count + * @return unknown + */ +function get_archives($type='', $limit='', $format='html', $before = '', $after = '', $show_post_count = false) { + _deprecated_function(__FUNCTION__, '0.0', 'wp_get_archives()'); + $args = compact('type', 'limit', 'format', 'before', 'after', 'show_post_count'); + return wp_get_archives($args); +} + +/** + * Returns or Prints link to the author's posts. + * + * @since 1.2 + * @deprecated Use get_author_posts_url() + * @see get_author_posts_url() + * + * @param bool $echo Optional. + * @param int $author_id Required. + * @param string $author_nicename Optional. + * @return string|null + */ +function get_author_link($echo = false, $author_id, $author_nicename = '') { + _deprecated_function(__FUNCTION__, '0.0', 'get_author_posts_url()'); + + $link = get_author_posts_url($author_id, $author_nicename); + + if ( $echo ) + echo $link; + return $link; +} + +/** + * Print list of pages based on arguments. + * + * @since 0.71 + * @deprecated Use wp_link_pages() + * @see wp_link_pages() + * + * @param string $before + * @param string $after + * @param string $next_or_number + * @param string $nextpagelink + * @param string $previouspagelink + * @param string $pagelink + * @param string $more_file + * @return string + */ +function link_pages($before='
    ', $after='
    ', $next_or_number='number', $nextpagelink='next page', $previouspagelink='previous page', + $pagelink='%', $more_file='') { + _deprecated_function(__FUNCTION__, '0.0', 'wp_link_pages()'); + + $args = compact('before', 'after', 'next_or_number', 'nextpagelink', 'previouspagelink', 'pagelink', 'more_file'); + return wp_link_pages($args); +} + +/** + * Get value based on option. + * + * @since 0.71 + * @deprecated Use get_option() + * @see get_option() + * + * @param string $option + * @return string + */ +function get_settings($option) { + _deprecated_function(__FUNCTION__, '0.0', 'get_option()'); + + return get_option($option); +} + +/** + * Print the permalink of the current post in the loop. + * + * @since 0.71 + * @deprecated Use the_permalink() + * @see the_permalink() + */ +function permalink_link() { + _deprecated_function(__FUNCTION__, '0.0', 'the_permalink()'); + the_permalink(); +} + +/** + * Print the permalink to the RSS feed. + * + * @since 0.71 + * @deprecated Use the_permalink_rss() + * @see the_permalink_rss() + * + * @param string $file + */ +function permalink_single_rss($deprecated = '') { + _deprecated_function(__FUNCTION__, '0.0', 'the_permalink_rss()'); + the_permalink_rss(); +} + +/** + * Gets the links associated with category. + * + * @see get_links() for argument information that can be used in $args + * @since 1.0.1 + * @deprecated Use get_bookmarks() + * @see get_bookmarks() + * + * @param string $args a query string + * @return null|string + */ +function wp_get_links($args = '') { + _deprecated_function(__FUNCTION__, '0.0', 'get_bookmarks()'); + + if ( strpos( $args, '=' ) === false ) { + $cat_id = $args; + $args = add_query_arg( 'category', $cat_id, $args ); + } + + $defaults = array( + 'category' => -1, 'before' => '', + 'after' => '
    ', 'between' => ' ', + 'show_images' => true, 'orderby' => 'name', + 'show_description' => true, 'show_rating' => false, + 'limit' => -1, 'show_updated' => true, + 'echo' => true + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + return get_links($category, $before, $after, $between, $show_images, $orderby, $show_description, $show_rating, $limit, $show_updated, $echo); +} + +/** + * Gets the links associated with category by id. + * + * @since 0.71 + * @deprecated Use get_bookmarks() + * @see get_bookmarks() + * + * @param int $category The category to use. If no category supplied uses all + * @param string $before the html to output before the link + * @param string $after the html to output after the link + * @param string $between the html to output between the link/image and its description. + * Not used if no image or show_images == true + * @param bool $show_images whether to show images (if defined). + * @param string $orderby the order to output the links. E.g. 'id', 'name', 'url', + * 'description', or 'rating'. Or maybe owner. If you start the name with an + * underscore the order will be reversed. You can also specify 'rand' as the order + * which will return links in a random order. + * @param bool $show_description whether to show the description if show_images=false/not defined. + * @param bool $show_rating show rating stars/chars + * @param int $limit Limit to X entries. If not specified, all entries are shown. + * @param int $show_updated whether to show last updated timestamp + * @param bool $echo whether to echo the results, or return them instead + * @return null|string + */ +function get_links($category = -1, $before = '', $after = '
    ', $between = ' ', $show_images = true, $orderby = 'name', + $show_description = true, $show_rating = false, $limit = -1, $show_updated = 1, $echo = true) { + _deprecated_function(__FUNCTION__, '0.0', 'get_bookmarks()'); + + $order = 'ASC'; + if ( substr($orderby, 0, 1) == '_' ) { + $order = 'DESC'; + $orderby = substr($orderby, 1); + } + + if ( $category == -1 ) //get_bookmarks uses '' to signify all categories + $category = ''; + + $results = get_bookmarks("category=$category&orderby=$orderby&order=$order&show_updated=$show_updated&limit=$limit"); + + if ( !$results ) + return; + + $output = ''; + + foreach ( (array) $results as $row ) { + if ( !isset($row->recently_updated) ) + $row->recently_updated = false; + $output .= $before; + if ( $show_updated && $row->recently_updated ) + $output .= get_option('links_recently_updated_prepend'); + $the_link = '#'; + if ( !empty($row->link_url) ) + $the_link = esc_url($row->link_url); + $rel = $row->link_rel; + if ( '' != $rel ) + $rel = ' rel="' . $rel . '"'; + + $desc = esc_attr(sanitize_bookmark_field('link_description', $row->link_description, $row->link_id, 'display')); + $name = esc_attr(sanitize_bookmark_field('link_name', $row->link_name, $row->link_id, 'display')); + $title = $desc; + + if ( $show_updated ) + if (substr($row->link_updated_f, 0, 2) != '00') + $title .= ' ('.__('Last updated') . ' ' . date(get_option('links_updated_date_format'), $row->link_updated_f + (get_option('gmt_offset') * 3600)) . ')'; + + if ( '' != $title ) + $title = ' title="' . $title . '"'; + + $alt = ' alt="' . $name . '"'; + + $target = $row->link_target; + if ( '' != $target ) + $target = ' target="' . $target . '"'; + + $output .= ''; + + if ( $row->link_image != null && $show_images ) { + if ( strpos($row->link_image, 'http') !== false ) + $output .= "link_image\" $alt $title />"; + else // If it's a relative path + $output .= "link_image\" $alt $title />"; + } else { + $output .= $name; + } + + $output .= ''; + + if ( $show_updated && $row->recently_updated ) + $output .= get_option('links_recently_updated_append'); + + if ( $show_description && '' != $desc ) + $output .= $between . $desc; + + if ($show_rating) { + $output .= $between . get_linkrating($row); + } + + $output .= "$after\n"; + } // end while + + if ( !$echo ) + return $output; + echo $output; +} + +/** + * Output entire list of links by category. + * + * Output a list of all links, listed by category, using the settings in + * $wpdb->linkcategories and output it as a nested HTML unordered list. + * + * @author Dougal + * @since 1.0.1 + * @deprecated Use wp_list_bookmarks() + * @see wp_list_bookmarks() + * + * @param string $order Sort link categories by 'name' or 'id' + * @param string $$deprecated Not Used + */ +function get_links_list($order = 'name', $deprecated = '') { + _deprecated_function(__FUNCTION__, '0.0', 'wp_list_bookmarks()'); + + $order = strtolower($order); + + // Handle link category sorting + $direction = 'ASC'; + if ( '_' == substr($order,0,1) ) { + $direction = 'DESC'; + $order = substr($order,1); + } + + if ( !isset($direction) ) + $direction = ''; + + $cats = get_categories("type=link&orderby=$order&order=$direction&hierarchical=0"); + + // Display each category + if ( $cats ) { + foreach ( (array) $cats as $cat ) { + // Handle each category. + + // Display the category name + echo '
  • ' . apply_filters('link_category', $cat->name ) . "

    \n\t
      \n"; + // Call get_links() with all the appropriate params + get_links($cat->term_id, '
    • ', "
    • ", "\n", true, 'name', false); + + // Close the last category + echo "\n\t
    \n
  • \n"; + } + } +} + +/** + * Show the link to the links popup and the number of links. + * + * @author Fullo + * @link http://sprite.csr.unibo.it/fullo/ + * + * @since 0.71 + * @deprecated {@internal Use function instead is unknown}} + * + * @param string $text the text of the link + * @param int $width the width of the popup window + * @param int $height the height of the popup window + * @param string $file the page to open in the popup window + * @param bool $count the number of links in the db + */ +function links_popup_script($text = 'Links', $width=400, $height=400, $file='links.all.php', $count = true) { + _deprecated_function(__FUNCTION__, '0.0' ); + + if ( $count ) + $counts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->links"); + + $javascript = ""; + $javascript .= $text; + + if ( $count ) + $javascript .= " ($counts)"; + + $javascript .= "\n\n"; + echo $javascript; +} + +/** + * @since 1.0.1 + * @deprecated Use sanitize_bookmark_field() + * @see sanitize_bookmark_field() + * + * @param object $link + * @return unknown + */ +function get_linkrating($link) { + _deprecated_function(__FUNCTION__, '0.0', 'sanitize_bookmark_field()'); + return sanitize_bookmark_field('link_rating', $link->link_rating, $link->link_id, 'display'); +} + +/** + * Gets the name of category by id. + * + * @since 0.71 + * @deprecated Use get_category() + * @see get_category() + * + * @param int $id The category to get. If no category supplied uses 0 + * @return string + */ +function get_linkcatname($id = 0) { + _deprecated_function(__FUNCTION__, '0.0', 'get_category()'); + + $id = (int) $id; + + if ( empty($id) ) + return ''; + + $cats = wp_get_link_cats($id); + + if ( empty($cats) || ! is_array($cats) ) + return ''; + + $cat_id = (int) $cats[0]; // Take the first cat. + + $cat = get_category($cat_id); + return $cat->name; +} + +/** + * Print RSS comment feed link. + * + * @since 1.0.1 + * @deprecated Use post_comments_feed_link() + * @see post_comments_feed_link() + * + * @param string $link_text + * @param string $deprecated Not used + */ +function comments_rss_link($link_text = 'Comments RSS', $deprecated = '') { + _deprecated_function(__FUNCTION__, '0.0', 'post_comments_feed_link()'); + post_comments_feed_link($link_text); +} + +/** + * Print/Return link to category RSS2 feed. + * + * @since 1.2 + * @deprecated Use get_category_feed_link() + * @see get_category_feed_link() + * + * @param bool $echo + * @param int $cat_ID + * @param string $deprecated Not used + * @return string|null + */ +function get_category_rss_link($echo = false, $cat_ID = 1, $deprecated = '') { + _deprecated_function(__FUNCTION__, '0.0', 'get_category_feed_link()'); + + $link = get_category_feed_link($cat_ID, 'rss2'); + + if ( $echo ) + echo $link; + return $link; +} + +/** + * Print/Return link to author RSS feed. + * + * @since 1.2 + * @deprecated Use get_author_feed_link() + * @see get_author_feed_link() + * + * @param bool $echo + * @param int $author_id + * @param string $deprecated Not used + * @return string|null + */ +function get_author_rss_link($echo = false, $author_id = 1, $deprecated = '') { + _deprecated_function(__FUNCTION__, '0.0', 'get_author_feed_link()'); + + $link = get_author_feed_link($author_id); + if ( $echo ) + echo $link; + return $link; +} + +/** + * Return link to the post RSS feed. + * + * @since 1.5 + * @deprecated Use get_post_comments_feed_link() + * @see get_post_comments_feed_link() + * + * @param string $deprecated Not used + * @return string + */ +function comments_rss($deprecated = '') { + _deprecated_function(__FUNCTION__, '2.2', 'get_post_comments_feed_link()'); + return get_post_comments_feed_link(); +} + +/** + * An alias of wp_create_user(). + * + * @param string $username The user's username. + * @param string $password The user's password. + * @param string $email The user's email (optional). + * @return int The new user's ID. + * @deprecated Use wp_create_user() + * @see wp_create_user() + */ +function create_user($username, $password, $email) { + _deprecated_function( __FUNCTION__, '2.0', 'wp_create_user()' ); + return wp_create_user($username, $password, $email); +} + +/** + * Unused Admin function. + * + * @since 2.0 + * @param string $deprecated Unknown + * @deprecated 2.5 + */ +function documentation_link( $deprecated = '' ) { + _deprecated_function( __FUNCTION__, '2.5', '' ); + return; +} + +/** + * Unused function. + * + * @deprecated 2.5 +*/ +function gzip_compression() { + return false; +} + +/** + * Retrieve an array of comment data about comment $comment_ID. + * + * @deprecated Use get_comment() + * @see get_comment() + * @since 0.71 + * + * @uses $id + * @uses $wpdb Database Object + * + * @param int $comment_ID The ID of the comment + * @param int $no_cache Whether to use the cache or not (casted to bool) + * @param bool $include_unapproved Whether to include unapproved comments or not + * @return array The comment data + */ +function get_commentdata( $comment_ID, $no_cache = 0, $include_unapproved = false ) { + _deprecated_function( __FUNCTION__, '2.7', 'get_comment()' ); + return get_comment($comment_ID, ARRAY_A); +} + +/** + * Retrieve the category name by the category ID. + * + * @since 0.71 + * @deprecated Use get_cat_name() + * @see get_cat_name() get_catname() is deprecated in favor of get_cat_name(). + * + * @param int $cat_ID Category ID + * @return string category name + */ +function get_catname( $cat_ID ) { + _deprecated_function(__FUNCTION__, '2.8', 'get_cat_name()'); + return get_cat_name( $cat_ID ); +} + +/** + * Retrieve category children list separated before and after the term IDs. + * + * @since 1.2.0 + * + * @param int $id Category ID to retrieve children. + * @param string $before Optional. Prepend before category term ID. + * @param string $after Optional, default is empty string. Append after category term ID. + * @param array $visited Optional. Category Term IDs that have already been added. + * @return string + */ +function get_category_children( $id, $before = '/', $after = '', $visited = array() ) { + _deprecated_function(__FUNCTION__, '2.8', 'get_term_children()'); + if ( 0 == $id ) + return ''; + + $chain = ''; + /** TODO: consult hierarchy */ + $cat_ids = get_all_category_ids(); + foreach ( (array) $cat_ids as $cat_id ) { + if ( $cat_id == $id ) + continue; + + $category = get_category( $cat_id ); + if ( is_wp_error( $category ) ) + return $category; + if ( $category->parent == $id && !in_array( $category->term_id, $visited ) ) { + $visited[] = $category->term_id; + $chain .= $before.$category->term_id.$after; + $chain .= get_category_children( $category->term_id, $before, $after ); + } + } + return $chain; +} + +/** + * Retrieve the description of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's description. + * @deprecated Use the_author_meta('description') + */ +function get_the_author_description() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'description\')' ); + return get_the_author_meta('description'); +} + +/** + * Display the description of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_description + * @since 1.0.0 + * @deprecated 2.8 + * @deprecated Use the_author_meta('description') + */ +function the_author_description() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'description\')' ); + the_author_meta('description'); +} + +/** + * Retrieve the login name of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's login name (username). + * @deprecated Use the_author_meta('login') + */ +function get_the_author_login() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'login\')' ); + return get_the_author_meta('login'); +} + +/** + * Display the login name of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_login + * @since 0.71 + * @deprecated 2.8 + * @deprecated Use the_author_meta('login') + */ +function the_author_login() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'login\')' ); + the_author_meta('login'); +} + +/** + * Retrieve the first name of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's first name. + * @deprecated Use the_author_meta('first_name') + */ +function get_the_author_firstname() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'first_name\')' ); + return get_the_author_meta('first_name'); +} + +/** + * Display the first name of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_firstname + * @since 0.71 + * @deprecated 2.8 + * @deprecated Use the_author_meta('first_name') + */ +function the_author_firstname() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'first_name\')' ); + the_author_meta('first_name'); +} + +/** + * Retrieve the last name of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's last name. + * @deprecated Use the_author_meta('last_name') + */ +function get_the_author_lastname() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'last_name\')' ); + return get_the_author_meta('last_name'); +} + +/** + * Display the last name of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_lastname + * @since 0.71 + * @deprecated 2.8 + * @deprecated Use the_author_meta('last_name') + */ +function the_author_lastname() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'last_name\')' ); + the_author_meta('last_name'); +} + +/** + * Retrieve the nickname of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's nickname. + * @deprecated Use the_author_meta('nickname') + */ +function get_the_author_nickname() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'nickname\')' ); + return get_the_author_meta('nickname'); +} + +/** + * Display the nickname of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_nickname + * @since 0.71 + * @deprecated 2.8 + * @deprecated Use the_author_meta('nickname') + */ +function the_author_nickname() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'nickname\')' ); + the_author_meta('nickname'); +} + +/** + * Retrieve the email of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's username. + * @deprecated Use the_author_meta('email') + */ +function get_the_author_email() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'email\')' ); + return get_the_author_meta('email'); +} + +/** + * Display the email of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_email + * @since 0.71 + * @deprecated 2.8 + * @deprecated Use the_author_meta('email') + */ +function the_author_email() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'email\')' ); + the_author_meta('email'); +} + +/** + * Retrieve the ICQ number of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's ICQ number. + * @deprecated Use the_author_meta('icq') + */ +function get_the_author_icq() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'icq\')' ); + return get_the_author_meta('icq'); +} + +/** + * Display the ICQ number of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_icq + * @since 0.71 + * @deprecated 2.8 + * @see get_the_author_icq() + * @deprecated Use the_author_meta('icq') + */ +function the_author_icq() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'icq\')' ); + the_author_meta('icq'); +} + +/** + * Retrieve the Yahoo! IM name of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's Yahoo! IM name. + * @deprecated Use the_author_meta('yim') + */ +function get_the_author_yim() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'yim\')' ); + return get_the_author_meta('yim'); +} + +/** + * Display the Yahoo! IM name of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_yim + * @since 0.71 + * @deprecated 2.8 + * @deprecated Use the_author_meta('yim') + */ +function the_author_yim() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'yim\')' ); + the_author_meta('yim'); +} + +/** + * Retrieve the MSN address of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's MSN address. + * @deprecated Use the_author_meta('msn') + */ +function get_the_author_msn() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'msn\')' ); + return get_the_author_meta('msn'); +} + +/** + * Display the MSN address of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_msn + * @since 0.71 + * @deprecated 2.8 + * @see get_the_author_msn() + * @deprecated Use the_author_meta('msn') + */ +function the_author_msn() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'msn\')' ); + the_author_meta('msn'); +} + +/** + * Retrieve the AIM address of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The author's AIM address. + * @deprecated Use the_author_meta('aim') + */ +function get_the_author_aim() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'aim\')' ); + return get_the_author_meta('aim'); +} + +/** + * Display the AIM address of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_aim + * @since 0.71 + * @deprecated 2.8 + * @see get_the_author_aim() + * @deprecated Use the_author_meta('aim') + */ +function the_author_aim() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'aim\')' ); + the_author_meta('aim'); +} + +/** + * Retrieve the specified author's preferred display name. + * + * @since 1.0.0 + * @deprecated 2.8 + * @param int $auth_id The ID of the author. + * @return string The author's display name. + * @deprecated Use the_author_meta('display_name') + */ +function get_author_name( $auth_id = false ) { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'display_name\')' ); + return get_the_author_meta('display_name', $auth_id); +} + +/** + * Retrieve the URL to the home page of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @uses $authordata The current author's DB object. + * @return string The URL to the author's page. + */ +function get_the_author_url() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'url\')' ); + return get_the_author_meta('url'); +} + +/** + * Display the URL to the home page of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_url + * @since 0.71 + * @deprecated 2.8 + */ +function the_author_url() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'url\')' ); + the_author_meta('url'); +} + +/** + * Retrieve the ID of the author of the current post. + * + * @since 1.5 + * @deprecated 2.8 + * @return int The author's ID. + */ +function get_the_author_ID() { + _deprecated_function(__FUNCTION__, '2.8', 'get_the_author_meta(\'ID\')' ); + return get_the_author_meta('ID'); +} + +/** + * Display the ID of the author of the current post. + * + * @link http://codex.wordpress.org/Template_Tags/the_author_ID + * @since 0.71 + * @deprecated 2.8 + * @uses get_the_author_ID() +*/ +function the_author_ID() { + _deprecated_function(__FUNCTION__, '2.8', 'the_author_meta(\'ID\')' ); + the_author_meta('ID'); +} + +?> \ No newline at end of file diff --git a/wp-includes/feed-atom-comments.php b/wp-includes/feed-atom-comments.php new file mode 100644 index 0000000..7f7e6f5 --- /dev/null +++ b/wp-includes/feed-atom-comments.php @@ -0,0 +1,88 @@ +'; +?> + +> + <?php + if ( is_singular() ) + printf(ent2ncr(__('Comments on: %s')), get_the_title_rss()); + elseif ( is_search() ) + printf(ent2ncr(__('Comments for %1$s searching on %2$s')), get_bloginfo_rss( 'name' ), esc_attr(get_search_query())); + else + printf(ent2ncr(__('Comments for %s')), get_bloginfo_rss( 'name' ) . get_wp_title_rss()); + ?> + + + + + + + + + + + + + + + + + + + +comment_post_ID); + get_post_custom($comment_post->ID); +?> + + <?php + if ( !is_singular() ) { + $title = get_the_title($comment_post->ID); + $title = apply_filters('the_title_rss', $title); + printf(ent2ncr(__('Comment on %1$s by %2$s')), $title, get_comment_author_rss()); + } else { + printf(ent2ncr(__('By: %s')), get_comment_author_rss()); + } + ?> + + + + + ' . get_comment_author_url() . ''; ?> + + + + + + + + ]]> + + ]]> +comment_parent == 0 ) : // This comment is top level ?> + +comment_parent); + // The rel attribute below and the id tag above should be GUIDs, but WP doesn't create them for comments (unlike posts). Either way, its more important that they both use the same system +?> + +comment_ID, $comment_post->ID); +?> + + + diff --git a/wp-includes/feed-atom.php b/wp-includes/feed-atom.php new file mode 100644 index 0000000..17b7833 --- /dev/null +++ b/wp-includes/feed-atom.php @@ -0,0 +1,55 @@ +'; ?> + + > + <?php bloginfo_rss('name'); wp_title_rss(); ?> + + + + + + + + + + + + + + + + + + + <![CDATA[<?php the_title_rss() ?>]]> + + + + + + ]]> + + ]]> + + + + + + + + + diff --git a/wp-includes/feed-rdf.php b/wp-includes/feed-rdf.php new file mode 100644 index 0000000..eee132e --- /dev/null +++ b/wp-includes/feed-rdf.php @@ -0,0 +1,55 @@ +'; ?> + +> +"> + <?php bloginfo_rss('name'); wp_title_rss(); ?> + + + + + + 1 + 2000-01-01T12:00+00:00 + + + + + + + + + + + + <?php the_title_rss() ?> + + post_date_gmt, false); ?> + + + + + + + ]]> + + + + + diff --git a/wp-includes/feed-rss.php b/wp-includes/feed-rss.php new file mode 100644 index 0000000..e5c2fe8 --- /dev/null +++ b/wp-includes/feed-rss.php @@ -0,0 +1,36 @@ +'; ?> + + + + <?php bloginfo_rss('name'); wp_title_rss(); ?> + + + + http://backend.userland.com/rss092 + + + + + + <?php the_title_rss() ?> + + ]]> + + + + + + + + + diff --git a/wp-includes/feed-rss2-comments.php b/wp-includes/feed-rss2-comments.php new file mode 100644 index 0000000..8232a0f --- /dev/null +++ b/wp-includes/feed-rss2-comments.php @@ -0,0 +1,67 @@ +'; +?> + + > + + <?php + if ( is_singular() ) + printf(ent2ncr(__('Comments on: %s')), get_the_title_rss()); + elseif ( is_search() ) + printf(ent2ncr(__('Comments for %s searching on %s')), get_bloginfo_rss( 'name' ), esc_attr($wp_query->query_vars['s'])); + else + printf(ent2ncr(__('Comments for %s')), get_bloginfo_rss( 'name' ) . get_wp_title_rss()); + ?> + + + + + + + + +comment_post_ID); + get_post_custom($comment_post->ID); +?> + + <?php + if ( !is_singular() ) { + $title = get_the_title($comment_post->ID); + $title = apply_filters('the_title_rss', $title); + printf(ent2ncr(__('Comment on %1$s by %2$s')), $title, get_comment_author_rss()); + } else { + printf(ent2ncr(__('By: %s')), get_comment_author_rss()); + } + ?> + + + + + + + ]]> + + + ]]> +comment_ID, $comment_post->ID); +?> + + + + diff --git a/wp-includes/feed-rss2.php b/wp-includes/feed-rss2.php new file mode 100644 index 0000000..c4299cb --- /dev/null +++ b/wp-includes/feed-rss2.php @@ -0,0 +1,61 @@ +'; ?> + + +> + + + <?php bloginfo_rss('name'); wp_title_rss(); ?> + + + + + + + + + + + + <?php the_title_rss() ?> + + + + + + + + + ]]> + + ]]> + post_content ) > 0 ) : ?> + ]]> + + ]]> + + + + + + + + + + diff --git a/wp-includes/feed.php b/wp-includes/feed.php new file mode 100644 index 0000000..0226356 --- /dev/null +++ b/wp-includes/feed.php @@ -0,0 +1,561 @@ +get_error_message(); + $title = apply_filters('get_wp_title_rss', $title); + return $title; +} + +/** + * Display the blog title for display of the feed title. + * + * @package WordPress + * @subpackage Feed + * @since 2.2.0 + * @uses apply_filters() Calls 'wp_title_rss' on the blog title. + * @see wp_title() $sep parameter usage. + * + * @param string $sep Optional. + */ +function wp_title_rss($sep = '»') { + echo apply_filters('wp_title_rss', get_wp_title_rss($sep)); +} + +/** + * Retrieve the current post title for the feed. + * + * @package WordPress + * @subpackage Feed + * @since 2.0.0 + * @uses apply_filters() Calls 'the_title_rss' on the post title. + * + * @return string Current post title. + */ +function get_the_title_rss() { + $title = get_the_title(); + $title = apply_filters('the_title_rss', $title); + return $title; +} + +/** + * Display the post title in the feed. + * + * @package WordPress + * @subpackage Feed + * @since 0.71 + * @uses get_the_title_rss() Used to retrieve current post title. + */ +function the_title_rss() { + echo get_the_title_rss(); +} + +/** + * Display the post content for the feed. + * + * For encoding the html or the $encode_html parameter, there are three possible + * values. '0' will make urls footnotes and use make_url_footnote(). '1' will + * encode special characters and automatically display all of the content. The + * value of '2' will strip all HTML tags from the content. + * + * Also note that you cannot set the amount of words and not set the html + * encoding. If that is the case, then the html encoding will default to 2, + * which will strip all HTML tags. + * + * To restrict the amount of words of the content, you can use the cut + * parameter. If the content is less than the amount, then there won't be any + * dots added to the end. If there is content left over, then dots will be added + * and the rest of the content will be removed. + * + * @package WordPress + * @subpackage Feed + * @since 0.71 + * @uses apply_filters() Calls 'the_content_rss' on the content before processing. + * @see get_the_content() For the $more_link_text, $stripteaser, and $more_file + * parameters. + * + * @param string $more_link_text Optional. Text to display when more content is available but not displayed. + * @param int|bool $stripteaser Optional. Default is 0. + * @param string $more_file Optional. + * @param int $cut Optional. Amount of words to keep for the content. + * @param int $encode_html Optional. How to encode the content. + */ +function the_content_rss($more_link_text='(more...)', $stripteaser=0, $more_file='', $cut = 0, $encode_html = 0) { + $content = get_the_content($more_link_text, $stripteaser, $more_file); + $content = apply_filters('the_content_rss', $content); + if ( $cut && !$encode_html ) + $encode_html = 2; + if ( 1== $encode_html ) { + $content = esc_html($content); + $cut = 0; + } elseif ( 0 == $encode_html ) { + $content = make_url_footnote($content); + } elseif ( 2 == $encode_html ) { + $content = strip_tags($content); + } + if ( $cut ) { + $blah = explode(' ', $content); + if ( count($blah) > $cut ) { + $k = $cut; + $use_dotdotdot = 1; + } else { + $k = count($blah); + $use_dotdotdot = 0; + } + + /** @todo Check performance, might be faster to use array slice instead. */ + for ( $i=0; $i<$k; $i++ ) + $excerpt .= $blah[$i].' '; + $excerpt .= ($use_dotdotdot) ? '...' : ''; + $content = $excerpt; + } + $content = str_replace(']]>', ']]>', $content); + echo $content; +} + +/** + * Display the post excerpt for the feed. + * + * @package WordPress + * @subpackage Feed + * @since 0.71 + * @uses apply_filters() Calls 'the_excerpt_rss' hook on the excerpt. + */ +function the_excerpt_rss() { + $output = get_the_excerpt(); + echo apply_filters('the_excerpt_rss', $output); +} + +/** + * Display the permalink to the post for use in feeds. + * + * @package WordPress + * @subpackage Feed + * @since 2.3.0 + * @uses apply_filters() Call 'the_permalink_rss' on the post permalink + */ +function the_permalink_rss() { + echo apply_filters('the_permalink_rss', get_permalink()); +} + +/** + * Display the feed GUID for the current comment. + * + * @package WordPress + * @subpackage Feed + * @since unknown + * + * @param int|object $comment_id Optional comment object or id. Defaults to global comment object. + */ +function comment_guid($comment_id = null) { + echo get_comment_guid($comment_id); +} + +/** + * Retrieve the feed GUID for the current comment. + * + * @package WordPress + * @subpackage Feed + * @since unknown + * + * @param int|object $comment_id Optional comment object or id. Defaults to global comment object. + * @return bool|string false on failure or guid for comment on success. + */ +function get_comment_guid($comment_id = null) { + $comment = get_comment($comment_id); + + if ( !is_object($comment) ) + return false; + + return get_the_guid($comment->comment_post_ID) . '#comment-' . $comment->comment_ID; +} + +/** + * Display the link to the comments. + * + * @since 1.5.0 + */ +function comment_link() { + echo esc_url( get_comment_link() ); +} + +/** + * Retrieve the current comment author for use in the feeds. + * + * @package WordPress + * @subpackage Feed + * @since 2.0.0 + * @uses apply_filters() Calls 'comment_author_rss' hook on comment author. + * @uses get_comment_author() + * + * @return string Comment Author + */ +function get_comment_author_rss() { + return apply_filters('comment_author_rss', get_comment_author() ); +} + +/** + * Display the current comment author in the feed. + * + * @package WordPress + * @subpackage Feed + * @since 1.0.0 + */ +function comment_author_rss() { + echo get_comment_author_rss(); +} + +/** + * Display the current comment content for use in the feeds. + * + * @package WordPress + * @subpackage Feed + * @since 1.0.0 + * @uses apply_filters() Calls 'comment_text_rss' filter on comment content. + * @uses get_comment_text() + */ +function comment_text_rss() { + $comment_text = get_comment_text(); + $comment_text = apply_filters('comment_text_rss', $comment_text); + echo $comment_text; +} + +/** + * Retrieve all of the post categories, formatted for use in feeds. + * + * All of the categories for the current post in the feed loop, will be + * retrieved and have feed markup added, so that they can easily be added to the + * RSS2, Atom, or RSS1 and RSS0.91 RDF feeds. + * + * @package WordPress + * @subpackage Feed + * @since 2.1.0 + * @uses apply_filters() + * + * @param string $type Optional, default is 'rss'. Either 'rss', 'atom', or 'rdf'. + * @return string All of the post categories for displaying in the feed. + */ +function get_the_category_rss($type = 'rss') { + $categories = get_the_category(); + $tags = get_the_tags(); + $the_list = ''; + $cat_names = array(); + + $filter = 'rss'; + if ( 'atom' == $type ) + $filter = 'raw'; + + if ( !empty($categories) ) foreach ( (array) $categories as $category ) { + $cat_names[] = sanitize_term_field('name', $category->name, $category->term_id, 'category', $filter); + } + + if ( !empty($tags) ) foreach ( (array) $tags as $tag ) { + $cat_names[] = sanitize_term_field('name', $tag->name, $tag->term_id, 'post_tag', $filter); + } + + $cat_names = array_unique($cat_names); + + foreach ( $cat_names as $cat_name ) { + if ( 'rdf' == $type ) + $the_list .= "\t\t\n"; + elseif ( 'atom' == $type ) + $the_list .= sprintf( '', esc_attr( apply_filters( 'get_bloginfo_rss', get_bloginfo( 'url' ) ) ), esc_attr( $cat_name ) ); + else + $the_list .= "\t\t\n"; + } + + return apply_filters('the_category_rss', $the_list, $type); +} + +/** + * Display the post categories in the feed. + * + * @package WordPress + * @subpackage Feed + * @since 0.71 + * @see get_the_category_rss() For better explanation. + * + * @param string $type Optional, default is 'rss'. Either 'rss', 'atom', or 'rdf'. + */ +function the_category_rss($type = 'rss') { + echo get_the_category_rss($type); +} + +/** + * Display the HTML type based on the blog setting. + * + * The two possible values are either 'xhtml' or 'html'. + * + * @package WordPress + * @subpackage Feed + * @since 2.2.0 + */ +function html_type_rss() { + $type = get_bloginfo('html_type'); + if (strpos($type, 'xhtml') !== false) + $type = 'xhtml'; + else + $type = 'html'; + echo $type; +} + +/** + * Display the rss enclosure for the current post. + * + * Uses the global $post to check whether the post requires a password and if + * the user has the password for the post. If not then it will return before + * displaying. + * + * Also uses the function get_post_custom() to get the post's 'enclosure' + * metadata field and parses the value to display the enclosure(s). The + * enclosure(s) consist of enclosure HTML tag(s) with a URI and other + * attributes. + * + * @package WordPress + * @subpackage Template + * @since 1.5.0 + * @uses apply_filters() Calls 'rss_enclosure' hook on rss enclosure. + * @uses get_post_custom() To get the current post enclosure metadata. + */ +function rss_enclosure() { + if ( post_password_required() ) + return; + + foreach ( (array) get_post_custom() as $key => $val) { + if ($key == 'enclosure') { + foreach ( (array) $val as $enc ) { + $enclosure = explode("\n", $enc); + + //only get the the first element eg, audio/mpeg from 'audio/mpeg mpga mp2 mp3' + $t = preg_split('/[ \t]/', trim($enclosure[2]) ); + $type = $t[0]; + + echo apply_filters('rss_enclosure', '' . "\n"); + } + } + } +} + +/** + * Display the atom enclosure for the current post. + * + * Uses the global $post to check whether the post requires a password and if + * the user has the password for the post. If not then it will return before + * displaying. + * + * Also uses the function get_post_custom() to get the post's 'enclosure' + * metadata field and parses the value to display the enclosure(s). The + * enclosure(s) consist of link HTML tag(s) with a URI and other attributes. + * + * @package WordPress + * @subpackage Template + * @since 2.2.0 + * @uses apply_filters() Calls 'atom_enclosure' hook on atom enclosure. + * @uses get_post_custom() To get the current post enclosure metadata. + */ +function atom_enclosure() { + if ( post_password_required() ) + return; + + foreach ( (array) get_post_custom() as $key => $val ) { + if ($key == 'enclosure') { + foreach ( (array) $val as $enc ) { + $enclosure = split("\n", $enc); + echo apply_filters('atom_enclosure', '' . "\n"); + } + } + } +} + +/** + * Determine the type of a string of data with the data formatted. + * + * Tell whether the type is text, html, or xhtml, per RFC 4287 section 3.1. + * + * In the case of WordPress, text is defined as containing no markup, + * xhtml is defined as "well formed", and html as tag soup (i.e., the rest). + * + * Container div tags are added to xhtml values, per section 3.1.1.3. + * + * @link http://www.atomenabled.org/developers/syndication/atom-format-spec.php#rfc.section.3.1 + * + * @package WordPress + * @subpackage Feed + * @since 2.5 + * + * @param string $data Input string + * @return array array(type, value) + */ +function prep_atom_text_construct($data) { + if (strpos($data, '<') === false && strpos($data, '&') === false) { + return array('text', $data); + } + + $parser = xml_parser_create(); + xml_parse($parser, '
    ' . $data . '
    ', true); + $code = xml_get_error_code($parser); + xml_parser_free($parser); + + if (!$code) { + if (strpos($data, '<') === false) { + return array('text', $data); + } else { + $data = "
    $data
    "; + return array('xhtml', $data); + } + } + + if (strpos($data, ']]>') == false) { + return array('html', ""); + } else { + return array('html', htmlspecialchars($data)); + } +} + +/** + * Display the link for the currently displayed feed in a XSS safe way. + * + * Generate a correct link for the atom:self element. + * + * @package WordPress + * @subpackage Feed + * @since 2.5 + */ +function self_link() { + $host = @parse_url(get_option('home')); + $host = $host['host']; + echo esc_url( + 'http' + . ( (isset($_SERVER['https']) && $_SERVER['https'] == 'on') ? 's' : '' ) . '://' + . $host + . stripslashes($_SERVER['REQUEST_URI']) + ); +} + +/** + * Return the content type for specified feed type. + * + * @package WordPress + * @subpackage Feed + * @since 2.8.0 + */ +function feed_content_type( $type = '' ) { + if ( empty($type) ) + $type = get_default_feed(); + + $types = array( + 'rss' => 'application/rss+xml', + 'rss2' => 'application/rss+xml', + 'rss-http' => 'text/xml', + 'atom' => 'application/atom+xml', + 'rdf' => 'application/rdf+xml' + ); + + $content_type = ( !empty($types[$type]) ) ? $types[$type] : 'application/octet-stream'; + + return apply_filters( 'feed_content_type', $content_type, $type ); +} + +/** + * Build SimplePie object based on RSS or Atom feed from URL. + * + * @since 2.8 + * + * @param string $url URL to retrieve feed + * @return WP_Error|SimplePie WP_Error object on failure or SimplePie object on success + */ +function fetch_feed($url) { + require_once (ABSPATH . WPINC . '/class-feed.php'); + + $feed = new SimplePie(); + $feed->set_feed_url($url); + $feed->set_cache_class('WP_Feed_Cache'); + $feed->set_file_class('WP_SimplePie_File'); + $feed->set_cache_duration(apply_filters('wp_feed_cache_transient_lifetime', 43200)); + $feed->init(); + $feed->handle_content_type(); + + if ( $feed->error() ) + return new WP_Error('simplepie-error', $feed->error()); + + return $feed; +} diff --git a/wp-includes/formatting.php b/wp-includes/formatting.php new file mode 100644 index 0000000..53cfeea --- /dev/null +++ b/wp-includes/formatting.php @@ -0,0 +1,2676 @@ + + * 'cause today's effort makes it worth tomorrow's "holiday"... + * + * Becomes: + * + * ’cause today’s effort makes it worth tomorrow’s “holiday”… + * + * Code within certain html blocks are skipped. + * + * @since 0.71 + * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases + * + * @param string $text The text to be formatted + * @return string The string replaced with html entities + */ +function wptexturize($text) { + global $wp_cockneyreplace; + $output = ''; + $curl = ''; + $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE); + $stop = count($textarr); + + /* translators: opening curly quote */ + $opening_quote = _x('“', 'opening curly quote'); + /* translators: closing curly quote */ + $closing_quote = _x('”', 'closing curly quote'); + + $no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt')); + $no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code')); + $no_texturize_tags_stack = array(); + $no_texturize_shortcodes_stack = array(); + + // if a plugin has provided an autocorrect array, use it + if ( isset($wp_cockneyreplace) ) { + $cockney = array_keys($wp_cockneyreplace); + $cockneyreplace = array_values($wp_cockneyreplace); + } else { + $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause"); + $cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause"); + } + + $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney); + $static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace); + + $dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/'); + $dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2'); + + for ( $i = 0; $i < $stop; $i++ ) { + $curl = $textarr[$i]; + + if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0} + && empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag + // static strings + $curl = str_replace($static_characters, $static_replacements, $curl); + // regular expressions + $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl); + } else { + wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>'); + wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']'); + } + + $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl); + $output .= $curl; + } + + return $output; +} + +function wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') { + $o = preg_quote($opening, '/'); + $c = preg_quote($closing, '/'); + foreach($disabled_elements as $element) { + if (preg_match('/^'.$o.$element.'\b/', $text)) array_push($stack, $element); + if (preg_match('/^'.$o.'\/'.$element.$c.'/', $text)) { + $last = array_pop($stack); + // disable texturize until we find a closing tag of our type (e.g.
    )
    +			// even if there was invalid nesting before that
    +			// Example: in the case 
    sadsadasd"baba"
    "baba" won't be texturized + if ($last != $element) array_push($stack, $last); + } + } +} + +/** + * Accepts matches array from preg_replace_callback in wpautop() or a string. + * + * Ensures that the contents of a <
    >...<
    > HTML block are not + * converted into paragraphs or line-breaks. + * + * @since 1.2.0 + * + * @param array|string $matches The array or string + * @return string The pre block without paragraph/line-break conversion. + */ +function clean_pre($matches) { + if ( is_array($matches) ) + $text = $matches[1] . $matches[2] . "
    "; + else + $text = $matches; + + $text = str_replace('
    ', '', $text); + $text = str_replace('

    ', "\n", $text); + $text = str_replace('

    ', '', $text); + + return $text; +} + +/** + * Replaces double line-breaks with paragraph elements. + * + * A group of regex replaces used to identify text formatted with newlines and + * replace double line-breaks with HTML paragraph tags. The remaining + * line-breaks after conversion become <
    > tags, unless $br is set to '0' + * or 'false'. + * + * @since 0.71 + * + * @param string $pee The text which has to be formatted. + * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true. + * @return string Text which has been converted into correct paragraph tags. + */ +function wpautop($pee, $br = 1) { + if ( trim($pee) === '' ) + return ''; + $pee = $pee . "\n"; // just to make things a little easier, pad the end + $pee = preg_replace('|
    \s*
    |', "\n\n", $pee); + // Space things out a little + $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)'; + $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee); + $pee = preg_replace('!()!', "$1\n\n", $pee); + $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines + if ( strpos($pee, ']*)>\s*|', "", $pee); // no pee inside object/embed + $pee = preg_replace('|\s*\s*|', '', $pee); + } + $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates + // make paragraphs, including one at the end + $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY); + $pee = ''; + foreach ( $pees as $tinkle ) + $pee .= '

    ' . trim($tinkle, "\n") . "

    \n"; + $pee = preg_replace('|

    \s*

    |', '', $pee); // under certain strange conditions it could create a P of entirely whitespace + $pee = preg_replace('!

    ([^<]+)!', "

    $1

    ", $pee); + $pee = preg_replace('!

    \s*(]*>)\s*

    !', "$1", $pee); // don't pee all over a tag + $pee = preg_replace("|

    (|", "$1", $pee); // problem with nested lists + $pee = preg_replace('|

    ]*)>|i', "

    ", $pee); + $pee = str_replace('

    ', '

    ', $pee); + $pee = preg_replace('!

    \s*(]*>)!', "$1", $pee); + $pee = preg_replace('!(]*>)\s*

    !', "$1", $pee); + if ($br) { + $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "", $matches[0]);'), $pee); + $pee = preg_replace('|(?)\s*\n|', "
    \n", $pee); // optionally make line breaks + $pee = str_replace('', "\n", $pee); + } + $pee = preg_replace('!(]*>)\s*
    !', "$1", $pee); + $pee = preg_replace('!
    (\s*]*>)!', '$1', $pee); + if (strpos($pee, ']*>)(.*?)!is', 'clean_pre', $pee ); + $pee = preg_replace( "|\n

    $|", '

    ', $pee ); + $pee = preg_replace('/

    \s*?(' . get_shortcode_regex() . ')\s*<\/p>/s', '$1', $pee); // don't auto-p wrap shortcodes that stand alone + + return $pee; +} + +/** + * Checks to see if a string is utf8 encoded. + * + * NOTE: This function checks for 5-Byte sequences, UTF8 + * has Bytes Sequences with a maximum length of 4. + * + * @author bmorel at ssi dot fr (modified) + * @since 1.2.1 + * + * @param string $str The string to be checked + * @return bool True if $str fits a UTF-8 model, false otherwise. + */ +function seems_utf8($str) { + $length = strlen($str); + for ($i=0; $i < $length; $i++) { + $c = ord($str[$i]); + if ($c < 0x80) $n = 0; # 0bbbbbbb + elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb + elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb + elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb + elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb + elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b + else return false; # Does not match any model + for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ? + if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80)) + return false; + } + } + return true; +} + +/** + * Converts a number of special characters into their HTML entities. + * + * Specifically deals with: &, <, >, ", and '. + * + * $quote_style can be set to ENT_COMPAT to encode " to + * ", or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded. + * + * @since 1.2.2 + * + * @param string $string The text which is to be encoded. + * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES. + * @param string $charset Optional. The character encoding of the string. Default is false. + * @param boolean $double_encode Optional. Whether or not to encode existing html entities. Default is false. + * @return string The encoded text with HTML entities. + */ +function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) { + $string = (string) $string; + + if ( 0 === strlen( $string ) ) { + return ''; + } + + // Don't bother if there are no specialchars - saves some processing + if ( !preg_match( '/[&<>"\']/', $string ) ) { + return $string; + } + + // Account for the previous behaviour of the function when the $quote_style is not an accepted value + if ( empty( $quote_style ) ) { + $quote_style = ENT_NOQUOTES; + } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) { + $quote_style = ENT_QUOTES; + } + + // Store the site charset as a static to avoid multiple calls to wp_load_alloptions() + if ( !$charset ) { + static $_charset; + if ( !isset( $_charset ) ) { + $alloptions = wp_load_alloptions(); + $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : ''; + } + $charset = $_charset; + } + if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) { + $charset = 'UTF-8'; + } + + $_quote_style = $quote_style; + + if ( $quote_style === 'double' ) { + $quote_style = ENT_COMPAT; + $_quote_style = ENT_COMPAT; + } elseif ( $quote_style === 'single' ) { + $quote_style = ENT_NOQUOTES; + } + + // Handle double encoding ourselves + if ( !$double_encode ) { + $string = wp_specialchars_decode( $string, $_quote_style ); + $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string ); + } + + $string = @htmlspecialchars( $string, $quote_style, $charset ); + + // Handle double encoding ourselves + if ( !$double_encode ) { + $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string ); + } + + // Backwards compatibility + if ( 'single' === $_quote_style ) { + $string = str_replace( "'", ''', $string ); + } + + return $string; +} + +/** + * Converts a number of HTML entities into their special characters. + * + * Specifically deals with: &, <, >, ", and '. + * + * $quote_style can be set to ENT_COMPAT to decode " entities, + * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded. + * + * @since 2.8 + * + * @param string $string The text which is to be decoded. + * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES. + * @return string The decoded text without HTML entities. + */ +function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) { + $string = (string) $string; + + if ( 0 === strlen( $string ) ) { + return ''; + } + + // Don't bother if there are no entities - saves a lot of processing + if ( strpos( $string, '&' ) === false ) { + return $string; + } + + // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value + if ( empty( $quote_style ) ) { + $quote_style = ENT_NOQUOTES; + } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) { + $quote_style = ENT_QUOTES; + } + + // More complete than get_html_translation_table( HTML_SPECIALCHARS ) + $single = array( ''' => '\'', ''' => '\'' ); + $single_preg = array( '/�*39;/' => ''', '/�*27;/i' => ''' ); + $double = array( '"' => '"', '"' => '"', '"' => '"' ); + $double_preg = array( '/�*34;/' => '"', '/�*22;/i' => '"' ); + $others = array( '<' => '<', '<' => '<', '>' => '>', '>' => '>', '&' => '&', '&' => '&', '&' => '&' ); + $others_preg = array( '/�*60;/' => '<', '/�*62;/' => '>', '/�*38;/' => '&', '/�*26;/i' => '&' ); + + if ( $quote_style === ENT_QUOTES ) { + $translation = array_merge( $single, $double, $others ); + $translation_preg = array_merge( $single_preg, $double_preg, $others_preg ); + } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) { + $translation = array_merge( $double, $others ); + $translation_preg = array_merge( $double_preg, $others_preg ); + } elseif ( $quote_style === 'single' ) { + $translation = array_merge( $single, $others ); + $translation_preg = array_merge( $single_preg, $others_preg ); + } elseif ( $quote_style === ENT_NOQUOTES ) { + $translation = $others; + $translation_preg = $others_preg; + } + + // Remove zero padding on numeric entities + $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string ); + + // Replace characters according to translation table + return strtr( $string, $translation ); +} + +/** + * Checks for invalid UTF8 in a string. + * + * @since 2.8 + * + * @param string $string The text which is to be checked. + * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false. + * @return string The checked text. + */ +function wp_check_invalid_utf8( $string, $strip = false ) { + $string = (string) $string; + + if ( 0 === strlen( $string ) ) { + return ''; + } + + // Store the site charset as a static to avoid multiple calls to get_option() + static $is_utf8; + if ( !isset( $is_utf8 ) ) { + $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ); + } + if ( !$is_utf8 ) { + return $string; + } + + // Check for support for utf8 in the installed PCRE library once and store the result in a static + static $utf8_pcre; + if ( !isset( $utf8_pcre ) ) { + $utf8_pcre = @preg_match( '/^./u', 'a' ); + } + // We can't demand utf8 in the PCRE installation, so just return the string in those cases + if ( !$utf8_pcre ) { + return $string; + } + + // preg_match fails when it encounters invalid UTF8 in $string + if ( 1 === @preg_match( '/^./us', $string ) ) { + return $string; + } + + // Attempt to strip the bad chars if requested (not recommended) + if ( $strip && function_exists( 'iconv' ) ) { + return iconv( 'utf-8', 'utf-8', $string ); + } + + return ''; +} + +/** + * Encode the Unicode values to be used in the URI. + * + * @since 1.5.0 + * + * @param string $utf8_string + * @param int $length Max length of the string + * @return string String with Unicode encoded for URI. + */ +function utf8_uri_encode( $utf8_string, $length = 0 ) { + $unicode = ''; + $values = array(); + $num_octets = 1; + $unicode_length = 0; + + $string_length = strlen( $utf8_string ); + for ($i = 0; $i < $string_length; $i++ ) { + + $value = ord( $utf8_string[ $i ] ); + + if ( $value < 128 ) { + if ( $length && ( $unicode_length >= $length ) ) + break; + $unicode .= chr($value); + $unicode_length++; + } else { + if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3; + + $values[] = $value; + + if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length ) + break; + if ( count( $values ) == $num_octets ) { + if ($num_octets == 3) { + $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]); + $unicode_length += 9; + } else { + $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]); + $unicode_length += 6; + } + + $values = array(); + $num_octets = 1; + } + } + } + + return $unicode; +} + +/** + * Converts all accent characters to ASCII characters. + * + * If there are no accent characters, then the string given is just returned. + * + * @since 1.2.1 + * + * @param string $string Text that might have accent characters + * @return string Filtered string with replaced "nice" characters. + */ +function remove_accents($string) { + if ( !preg_match('/[\x80-\xff]/', $string) ) + return $string; + + if (seems_utf8($string)) { + $chars = array( + // Decompositions for Latin-1 Supplement + chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', + chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', + chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', + chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', + chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', + chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', + chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', + chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', + chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', + chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', + chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', + chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', + chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', + chr(195).chr(159) => 's', chr(195).chr(160) => 'a', + chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', + chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', + chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', + chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', + chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', + chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', + chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', + chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', + chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', + chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', + chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', + chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', + chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', + chr(195).chr(191) => 'y', + // Decompositions for Latin Extended-A + chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', + chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', + chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', + chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', + chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', + chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', + chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', + chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', + chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', + chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', + chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', + chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', + chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', + chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', + chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', + chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', + chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', + chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', + chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', + chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', + chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', + chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', + chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', + chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', + chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', + chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', + chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', + chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', + chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', + chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', + chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', + chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', + chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', + chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', + chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', + chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', + chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', + chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', + chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', + chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', + chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', + chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', + chr(197).chr(148) => 'R',chr(197).chr(149) => 'r', + chr(197).chr(150) => 'R',chr(197).chr(151) => 'r', + chr(197).chr(152) => 'R',chr(197).chr(153) => 'r', + chr(197).chr(154) => 'S',chr(197).chr(155) => 's', + chr(197).chr(156) => 'S',chr(197).chr(157) => 's', + chr(197).chr(158) => 'S',chr(197).chr(159) => 's', + chr(197).chr(160) => 'S', chr(197).chr(161) => 's', + chr(197).chr(162) => 'T', chr(197).chr(163) => 't', + chr(197).chr(164) => 'T', chr(197).chr(165) => 't', + chr(197).chr(166) => 'T', chr(197).chr(167) => 't', + chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', + chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', + chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', + chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', + chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', + chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', + chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', + chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', + chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', + chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', + chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', + chr(197).chr(190) => 'z', chr(197).chr(191) => 's', + // Euro Sign + chr(226).chr(130).chr(172) => 'E', + // GBP (Pound) Sign + chr(194).chr(163) => ''); + + $string = strtr($string, $chars); + } else { + // Assume ISO-8859-1 if not UTF-8 + $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) + .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) + .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) + .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) + .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) + .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) + .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) + .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) + .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) + .chr(252).chr(253).chr(255); + + $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy"; + + $string = strtr($string, $chars['in'], $chars['out']); + $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); + $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); + $string = str_replace($double_chars['in'], $double_chars['out'], $string); + } + + return $string; +} + +/** + * Sanitizes a filename replacing whitespace with dashes + * + * Removes special characters that are illegal in filenames on certain + * operating systems and special characters requiring special escaping + * to manipulate at the command line. Replaces spaces and consecutive + * dashes with a single dash. Trim period, dash and underscore from beginning + * and end of filename. + * + * @since 2.1.0 + * + * @param string $filename The filename to be sanitized + * @return string The sanitized filename + */ +function sanitize_file_name( $filename ) { + $filename_raw = $filename; + $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}"); + $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw); + $filename = str_replace($special_chars, '', $filename); + $filename = preg_replace('/[\s-]+/', '-', $filename); + $filename = trim($filename, '.-_'); + return apply_filters('sanitize_file_name', $filename, $filename_raw); +} + +/** + * Sanitize username stripping out unsafe characters. + * + * If $strict is true, only alphanumeric characters (as well as _, space, ., -, + * @) are returned. + * Removes tags, octets, entities, and if strict is enabled, will remove all + * non-ASCII characters. After sanitizing, it passes the username, raw username + * (the username in the parameter), and the strict parameter as parameters for + * the filter. + * + * @since 2.0.0 + * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username, + * and $strict parameter. + * + * @param string $username The username to be sanitized. + * @param bool $strict If set limits $username to specific characters. Default false. + * @return string The sanitized username, after passing through filters. + */ +function sanitize_user( $username, $strict = false ) { + $raw_username = $username; + $username = strip_tags($username); + // Kill octets + $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username); + $username = preg_replace('/&.+?;/', '', $username); // Kill entities + + // If strict, reduce to ASCII for max portability. + if ( $strict ) + $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username); + + // Consolidate contiguous whitespace + $username = preg_replace('|\s+|', ' ', $username); + + return apply_filters('sanitize_user', $username, $raw_username, $strict); +} + +/** + * Sanitizes title or use fallback title. + * + * Specifically, HTML and PHP tags are stripped. Further actions can be added + * via the plugin API. If $title is empty and $fallback_title is set, the latter + * will be used. + * + * @since 1.0.0 + * + * @param string $title The string to be sanitized. + * @param string $fallback_title Optional. A title to use if $title is empty. + * @return string The sanitized string. + */ +function sanitize_title($title, $fallback_title = '') { + $raw_title = $title; + $title = strip_tags($title); + $title = apply_filters('sanitize_title', $title, $raw_title); + + if ( '' === $title || false === $title ) + $title = $fallback_title; + + return $title; +} + +/** + * Sanitizes title, replacing whitespace with dashes. + * + * Limits the output to alphanumeric characters, underscore (_) and dash (-). + * Whitespace becomes a dash. + * + * @since 1.2.0 + * + * @param string $title The title to be sanitized. + * @return string The sanitized title. + */ +function sanitize_title_with_dashes($title) { + $title = strip_tags($title); + // Preserve escaped octets. + $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title); + // Remove percent signs that are not part of an octet. + $title = str_replace('%', '', $title); + // Restore octets. + $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title); + + $title = remove_accents($title); + if (seems_utf8($title)) { + if (function_exists('mb_strtolower')) { + $title = mb_strtolower($title, 'UTF-8'); + } + $title = utf8_uri_encode($title, 200); + } + + $title = strtolower($title); + $title = preg_replace('/&.+?;/', '', $title); // kill entities + $title = str_replace('.', '-', $title); + $title = preg_replace('/[^%a-z0-9 _-]/', '', $title); + $title = preg_replace('/\s+/', '-', $title); + $title = preg_replace('|-+|', '-', $title); + $title = trim($title, '-'); + + return $title; +} + +/** + * Ensures a string is a valid SQL order by clause. + * + * Accepts one or more columns, with or without ASC/DESC, and also accepts + * RAND(). + * + * @since 2.5.1 + * + * @param string $orderby Order by string to be checked. + * @return string|false Returns the order by clause if it is a match, false otherwise. + */ +function sanitize_sql_orderby( $orderby ){ + preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches); + if ( !$obmatches ) + return false; + return $orderby; +} + +/** + * Santizes a html classname to ensure it only contains valid characters + * + * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty + * string then it will return the alternative value supplied. + * + * @todo Expand to support the full range of CDATA that a class attribute can contain. + * + * @since 2.8.0 + * + * @param string $class The classname to be sanitized + * @param string $fallback The value to return if the sanitization end's up as an empty string. + * @return string The sanitized value + */ +function sanitize_html_class($class, $fallback){ + //Strip out any % encoded octets + $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class); + + //Limit to A-Z,a-z,0-9,'-' + $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized); + + if ('' == $sanitized) + $sanitized = $fallback; + + return apply_filters('sanitize_html_class',$sanitized, $class, $fallback); +} + +/** + * Converts a number of characters from a string. + * + * Metadata tags <> and <<category>> are removed, <<br>> and <<hr>> are + * converted into correct XHTML and Unicode characters are converted to the + * valid range. + * + * @since 0.71 + * + * @param string $content String of characters to be converted. + * @param string $deprecated Not used. + * @return string Converted string. + */ +function convert_chars($content, $deprecated = '') { + // Translation of invalid Unicode references range to valid range + $wp_htmltranswinuni = array( + '€' => '€', // the Euro sign + '' => '', + '‚' => '‚', // these are Windows CP1252 specific characters + 'ƒ' => 'ƒ', // they would look weird on non-Windows browsers + '„' => '„', + '…' => '…', + '†' => '†', + '‡' => '‡', + 'ˆ' => 'ˆ', + '‰' => '‰', + 'Š' => 'Š', + '‹' => '‹', + 'Œ' => 'Œ', + '' => '', + 'Ž' => 'ž', + '' => '', + '' => '', + '‘' => '‘', + '’' => '’', + '“' => '“', + '”' => '”', + '•' => '•', + '–' => '–', + '—' => '—', + '˜' => '˜', + '™' => '™', + 'š' => 'š', + '›' => '›', + 'œ' => 'œ', + '' => '', + 'ž' => '', + 'Ÿ' => 'Ÿ' + ); + + // Remove metadata tags + $content = preg_replace('/<title>(.+?)<\/title>/','',$content); + $content = preg_replace('/<category>(.+?)<\/category>/','',$content); + + // Converts lone & characters into & (a.k.a. &) + $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&$1', $content); + + // Fix Word pasting + $content = strtr($content, $wp_htmltranswinuni); + + // Just a little XHTML help + $content = str_replace('<br>', '<br />', $content); + $content = str_replace('<hr>', '<hr />', $content); + + return $content; +} + +/** + * Callback used to change %uXXXX to &#YYY; syntax + * + * @since 2.8? + * + * @param array $matches Single Match + * @return string An HTML entity + */ +function funky_javascript_callback($matches) { + return "&#".base_convert($matches[1],16,10).";"; +} + +/** + * Fixes javascript bugs in browsers. + * + * Converts unicode characters to HTML numbered entities. + * + * @since 1.5.0 + * @uses $is_macIE + * @uses $is_winIE + * + * @param string $text Text to be made safe. + * @return string Fixed text. + */ +function funky_javascript_fix($text) { + // Fixes for browsers' javascript bugs + global $is_macIE, $is_winIE; + + if ( $is_winIE || $is_macIE ) + $text = preg_replace_callback("/\%u([0-9A-F]{4,4})/", + "funky_javascript_callback", + $text); + + return $text; +} + +/** + * Will only balance the tags if forced to and the option is set to balance tags. + * + * The option 'use_balanceTags' is used for whether the tags will be balanced. + * Both the $force parameter and 'use_balanceTags' option will have to be true + * before the tags will be balanced. + * + * @since 0.71 + * + * @param string $text Text to be balanced + * @param bool $force Forces balancing, ignoring the value of the option. Default false. + * @return string Balanced text + */ +function balanceTags( $text, $force = false ) { + if ( !$force && get_option('use_balanceTags') == 0 ) + return $text; + return force_balance_tags( $text ); +} + +/** + * Balances tags of string using a modified stack. + * + * @since 2.0.4 + * + * @author Leonard Lin <leonard@acm.org> + * @license GPL v2.0 + * @copyright November 4, 2001 + * @version 1.1 + * @todo Make better - change loop condition to $text in 1.2 + * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004 + * 1.1 Fixed handling of append/stack pop order of end text + * Added Cleaning Hooks + * 1.0 First Version + * + * @param string $text Text to be balanced. + * @return string Balanced text. + */ +function force_balance_tags( $text ) { + $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = ''; + $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags + $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves + + # WP bug fix for comments - in case you REALLY meant to type '< !--' + $text = str_replace('< !--', '< !--', $text); + # WP bug fix for LOVE <3 (and other situations with '<' before a number) + $text = preg_replace('#<([0-9]{1})#', '<$1', $text); + + while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) { + $newtext .= $tagqueue; + + $i = strpos($text,$regex[0]); + $l = strlen($regex[0]); + + // clear the shifter + $tagqueue = ''; + // Pop or Push + if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag + $tag = strtolower(substr($regex[1],1)); + // if too many closing tags + if($stacksize <= 0) { + $tag = ''; + //or close to be safe $tag = '/' . $tag; + } + // if stacktop value = tag close value then pop + else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag + $tag = '</' . $tag . '>'; // Close Tag + // Pop + array_pop ($tagstack); + $stacksize--; + } else { // closing tag not at top, search for it + for ($j=$stacksize-1;$j>=0;$j--) { + if ($tagstack[$j] == $tag) { + // add tag to tagqueue + for ($k=$stacksize-1;$k>=$j;$k--){ + $tagqueue .= '</' . array_pop ($tagstack) . '>'; + $stacksize--; + } + break; + } + } + $tag = ''; + } + } else { // Begin Tag + $tag = strtolower($regex[1]); + + // Tag Cleaning + + // If self-closing or '', don't do anything. + if((substr($regex[2],-1) == '/') || ($tag == '')) { + } + // ElseIf it's a known single-entity tag but it doesn't close itself, do so + elseif ( in_array($tag, $single_tags) ) { + $regex[2] .= '/'; + } else { // Push the tag onto the stack + // If the top of the stack is the same as the tag we want to push, close previous tag + if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) { + $tagqueue = '</' . array_pop ($tagstack) . '>'; + $stacksize--; + } + $stacksize = array_push ($tagstack, $tag); + } + + // Attributes + $attributes = $regex[2]; + if($attributes) { + $attributes = ' '.$attributes; + } + $tag = '<'.$tag.$attributes.'>'; + //If already queuing a close tag, then put this tag on, too + if ($tagqueue) { + $tagqueue .= $tag; + $tag = ''; + } + } + $newtext .= substr($text,0,$i) . $tag; + $text = substr($text,$i+$l); + } + + // Clear Tag Queue + $newtext .= $tagqueue; + + // Add Remaining text + $newtext .= $text; + + // Empty Stack + while($x = array_pop($tagstack)) { + $newtext .= '</' . $x . '>'; // Add remaining tags to close + } + + // WP fix for the bug with HTML comments + $newtext = str_replace("< !--","<!--",$newtext); + $newtext = str_replace("< !--","< !--",$newtext); + + return $newtext; +} + +/** + * Acts on text which is about to be edited. + * + * Unless $richedit is set, it is simply a holder for the 'format_to_edit' + * filter. If $richedit is set true htmlspecialchars() will be run on the + * content, converting special characters to HTMl entities. + * + * @since 0.71 + * + * @param string $content The text about to be edited. + * @param bool $richedit Whether or not the $content should pass through htmlspecialchars(). Default false. + * @return string The text after the filter (and possibly htmlspecialchars()) has been run. + */ +function format_to_edit($content, $richedit = false) { + $content = apply_filters('format_to_edit', $content); + if (! $richedit ) + $content = htmlspecialchars($content); + return $content; +} + +/** + * Holder for the 'format_to_post' filter. + * + * @since 0.71 + * + * @param string $content The text to pass through the filter. + * @return string Text returned from the 'format_to_post' filter. + */ +function format_to_post($content) { + $content = apply_filters('format_to_post', $content); + return $content; +} + +/** + * Add leading zeros when necessary. + * + * If you set the threshold to '4' and the number is '10', then you will get + * back '0010'. If you set the number to '4' and the number is '5000', then you + * will get back '5000'. + * + * Uses sprintf to append the amount of zeros based on the $threshold parameter + * and the size of the number. If the number is large enough, then no zeros will + * be appended. + * + * @since 0.71 + * + * @param mixed $number Number to append zeros to if not greater than threshold. + * @param int $threshold Digit places number needs to be to not have zeros added. + * @return string Adds leading zeros to number if needed. + */ +function zeroise($number, $threshold) { + return sprintf('%0'.$threshold.'s', $number); +} + +/** + * Adds backslashes before letters and before a number at the start of a string. + * + * @since 0.71 + * + * @param string $string Value to which backslashes will be added. + * @return string String with backslashes inserted. + */ +function backslashit($string) { + $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string); + $string = preg_replace('/([a-z])/i', '\\\\\1', $string); + return $string; +} + +/** + * Appends a trailing slash. + * + * Will remove trailing slash if it exists already before adding a trailing + * slash. This prevents double slashing a string or path. + * + * The primary use of this is for paths and thus should be used for paths. It is + * not restricted to paths and offers no specific path support. + * + * @since 1.2.0 + * @uses untrailingslashit() Unslashes string if it was slashed already. + * + * @param string $string What to add the trailing slash to. + * @return string String with trailing slash added. + */ +function trailingslashit($string) { + return untrailingslashit($string) . '/'; +} + +/** + * Removes trailing slash if it exists. + * + * The primary use of this is for paths and thus should be used for paths. It is + * not restricted to paths and offers no specific path support. + * + * @since 2.2.0 + * + * @param string $string What to remove the trailing slash from. + * @return string String without the trailing slash. + */ +function untrailingslashit($string) { + return rtrim($string, '/'); +} + +/** + * Adds slashes to escape strings. + * + * Slashes will first be removed if magic_quotes_gpc is set, see {@link + * http://www.php.net/magic_quotes} for more details. + * + * @since 0.71 + * + * @param string $gpc The string returned from HTTP request data. + * @return string Returns a string escaped with slashes. + */ +function addslashes_gpc($gpc) { + global $wpdb; + + if (get_magic_quotes_gpc()) { + $gpc = stripslashes($gpc); + } + + return $wpdb->escape($gpc); +} + +/** + * Navigates through an array and removes slashes from the values. + * + * If an array is passed, the array_map() function causes a callback to pass the + * value back to the function. The slashes from this value will removed. + * + * @since 2.0.0 + * + * @param array|string $value The array or string to be striped. + * @return array|string Stripped array (or string in the callback). + */ +function stripslashes_deep($value) { + $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); + return $value; +} + +/** + * Navigates through an array and encodes the values to be used in a URL. + * + * Uses a callback to pass the value of the array back to the function as a + * string. + * + * @since 2.2.0 + * + * @param array|string $value The array or string to be encoded. + * @return array|string $value The encoded array (or string from the callback). + */ +function urlencode_deep($value) { + $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value); + return $value; +} + +/** + * Converts email addresses characters to HTML entities to block spam bots. + * + * @since 0.71 + * + * @param string $emailaddy Email address. + * @param int $mailto Optional. Range from 0 to 1. Used for encoding. + * @return string Converted email address. + */ +function antispambot($emailaddy, $mailto=0) { + $emailNOSPAMaddy = ''; + srand ((float) microtime() * 1000000); + for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) { + $j = floor(rand(0, 1+$mailto)); + if ($j==0) { + $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';'; + } elseif ($j==1) { + $emailNOSPAMaddy .= substr($emailaddy,$i,1); + } elseif ($j==2) { + $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2); + } + } + $emailNOSPAMaddy = str_replace('@','@',$emailNOSPAMaddy); + return $emailNOSPAMaddy; +} + +/** + * Callback to convert URI match to HTML A element. + * + * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link + * make_clickable()}. + * + * @since 2.3.2 + * @access private + * + * @param array $matches Single Regex Match. + * @return string HTML A element with URI address. + */ +function _make_url_clickable_cb($matches) { + $url = $matches[2]; + $url = esc_url($url); + if ( empty($url) ) + return $matches[0]; + return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>"; +} + +/** + * Callback to convert URL match to HTML A element. + * + * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link + * make_clickable()}. + * + * @since 2.3.2 + * @access private + * + * @param array $matches Single Regex Match. + * @return string HTML A element with URL address. + */ +function _make_web_ftp_clickable_cb($matches) { + $ret = ''; + $dest = $matches[2]; + $dest = 'http://' . $dest; + $dest = esc_url($dest); + if ( empty($dest) ) + return $matches[0]; + // removed trailing [,;:] from URL + if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) { + $ret = substr($dest, -1); + $dest = substr($dest, 0, strlen($dest)-1); + } + return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret; +} + +/** + * Callback to convert email address match to HTML A element. + * + * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link + * make_clickable()}. + * + * @since 2.3.2 + * @access private + * + * @param array $matches Single Regex Match. + * @return string HTML A element with email address. + */ +function _make_email_clickable_cb($matches) { + $email = $matches[2] . '@' . $matches[3]; + return $matches[1] . "<a href=\"mailto:$email\">$email</a>"; +} + +/** + * Convert plaintext URI to HTML links. + * + * Converts URI, www and ftp, and email addresses. Finishes by fixing links + * within links. + * + * @since 0.71 + * + * @param string $ret Content to convert URIs. + * @return string Content with converted URIs. + */ +function make_clickable($ret) { + $ret = ' ' . $ret; + // in testing, using arrays here was found to be faster + $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))+)#is', '_make_url_clickable_cb', $ret); + $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret); + $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret); + // this one is not in an array because we need it to run last, for cleanup of accidental links within links + $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret); + $ret = trim($ret); + return $ret; +} + +/** + * Adds rel nofollow string to all HTML A elements in content. + * + * @since 1.5.0 + * + * @param string $text Content that may contain HTML A elements. + * @return string Converted content. + */ +function wp_rel_nofollow( $text ) { + global $wpdb; + // This is a pre save filter, so text is already escaped. + $text = stripslashes($text); + $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text); + $text = $wpdb->escape($text); + return $text; +} + +/** + * Callback to used to add rel=nofollow string to HTML A element. + * + * Will remove already existing rel="nofollow" and rel='nofollow' from the + * string to prevent from invalidating (X)HTML. + * + * @since 2.3.0 + * + * @param array $matches Single Match + * @return string HTML A Element with rel nofollow. + */ +function wp_rel_nofollow_callback( $matches ) { + $text = $matches[1]; + $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text); + return "<a $text rel=\"nofollow\">"; +} + + +/** + * Convert one smiley code to the icon graphic file equivalent. + * + * Looks up one smiley code in the $wpsmiliestrans global array and returns an + * <img> string for that smiley. + * + * @global array $wpsmiliestrans + * @since 2.8.0 + * + * @param string $smiley Smiley code to convert to image. + * @return string Image string for smiley. + */ +function translate_smiley($smiley) { + global $wpsmiliestrans; + + if (count($smiley) == 0) { + return ''; + } + + $siteurl = get_option( 'siteurl' ); + + $smiley = trim(reset($smiley)); + $img = $wpsmiliestrans[$smiley]; + $smiley_masked = esc_attr($smiley); + + return " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> "; +} + + +/** + * Convert text equivalent of smilies to images. + * + * Will only convert smilies if the option 'use_smilies' is true and the global + * used in the function isn't empty. + * + * @since 0.71 + * @uses $wp_smiliessearch + * + * @param string $text Content to convert smilies from text. + * @return string Converted content with text smilies replaced with images. + */ +function convert_smilies($text) { + global $wp_smiliessearch; + $output = ''; + if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) { + // HTML loop taken from texturize function, could possible be consolidated + $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between + $stop = count($textarr);// loop stuff + for ($i = 0; $i < $stop; $i++) { + $content = $textarr[$i]; + if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag + $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content); + } + $output .= $content; + } + } else { + // return default text. + $output = $text; + } + return $output; +} + +/** + * Verifies that an email is valid. + * + * Does not grok i18n domains. Not RFC compliant. + * + * @since 0.71 + * + * @param string $email Email address to verify. + * @param boolean $check_dns Whether to check the DNS for the domain using checkdnsrr(). + * @return string|bool Either false or the valid email address. + */ +function is_email( $email, $check_dns = false ) { + // Test for the minimum length the email can be + if ( strlen( $email ) < 3 ) { + return apply_filters( 'is_email', false, $email, 'email_too_short' ); + } + + // Test for an @ character after the first position + if ( strpos( $email, '@', 1 ) === false ) { + return apply_filters( 'is_email', false, $email, 'email_no_at' ); + } + + // Split out the local and domain parts + list( $local, $domain ) = explode( '@', $email, 2 ); + + // LOCAL PART + // Test for invalid characters + if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) { + return apply_filters( 'is_email', false, $email, 'local_invalid_chars' ); + } + + // DOMAIN PART + // Test for sequences of periods + if ( preg_match( '/\.{2,}/', $domain ) ) { + return apply_filters( 'is_email', false, $email, 'domain_period_sequence' ); + } + + // Test for leading and trailing periods and whitespace + if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) { + return apply_filters( 'is_email', false, $email, 'domain_period_limits' ); + } + + // Split the domain into subs + $subs = explode( '.', $domain ); + + // Assume the domain will have at least two subs + if ( 2 > count( $subs ) ) { + return apply_filters( 'is_email', false, $email, 'domain_no_periods' ); + } + + // Loop through each sub + foreach ( $subs as $sub ) { + // Test for leading and trailing hyphens and whitespace + if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) { + return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' ); + } + + // Test for invalid characters + if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) { + return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' ); + } + } + + // DNS + // Check the domain has a valid MX and A resource record + if ( $check_dns && function_exists( 'checkdnsrr' ) && !( checkdnsrr( $domain . '.', 'MX' ) || checkdnsrr( $domain . '.', 'A' ) ) ) { + return apply_filters( 'is_email', false, $email, 'dns_no_rr' ); + } + + // Congratulations your email made it! + return apply_filters( 'is_email', $email, $email, null ); +} + +/** + * Convert to ASCII from email subjects. + * + * @since 1.2.0 + * @usedby wp_mail() handles charsets in email subjects + * + * @param string $string Subject line + * @return string Converted string to ASCII + */ +function wp_iso_descrambler($string) { + /* this may only work with iso-8859-1, I'm afraid */ + if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) { + return $string; + } else { + $subject = str_replace('_', ' ', $matches[2]); + $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', create_function('$match', 'return chr(hexdec(strtolower($match[1])));'), $subject); + return $subject; + } +} + +/** + * Returns a date in the GMT equivalent. + * + * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the + * value of the 'gmt_offset' option. + * + * @since 1.2.0 + * + * @uses get_option() to retrieve the the value of 'gmt_offset'. + * @param string $string The date to be converted. + * @return string GMT version of the date provided. + */ +function get_gmt_from_date($string) { + preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches); + $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); + $string_gmt = gmdate('Y-m-d H:i:s', $string_time - get_option('gmt_offset') * 3600); + return $string_gmt; +} + +/** + * Converts a GMT date into the correct format for the blog. + * + * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of + * gmt_offset. + * + * @since 1.2.0 + * + * @param string $string The date to be converted. + * @return string Formatted date relative to the GMT offset. + */ +function get_date_from_gmt($string) { + preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches); + $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); + $string_localtime = gmdate('Y-m-d H:i:s', $string_time + get_option('gmt_offset')*3600); + return $string_localtime; +} + +/** + * Computes an offset in seconds from an iso8601 timezone. + * + * @since 1.5.0 + * + * @param string $timezone Either 'Z' for 0 offset or '±hhmm'. + * @return int|float The offset in seconds. + */ +function iso8601_timezone_to_offset($timezone) { + // $timezone is either 'Z' or '[+|-]hhmm' + if ($timezone == 'Z') { + $offset = 0; + } else { + $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1; + $hours = intval(substr($timezone, 1, 2)); + $minutes = intval(substr($timezone, 3, 4)) / 60; + $offset = $sign * 3600 * ($hours + $minutes); + } + return $offset; +} + +/** + * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt]. + * + * @since 1.5.0 + * + * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}. + * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'. + * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s. + */ +function iso8601_to_datetime($date_string, $timezone = 'user') { + $timezone = strtolower($timezone); + + if ($timezone == 'gmt') { + + preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits); + + if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset + $offset = iso8601_timezone_to_offset($date_bits[7]); + } else { // we don't have a timezone, so we assume user local timezone (not server's!) + $offset = 3600 * get_option('gmt_offset'); + } + + $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]); + $timestamp -= $offset; + + return gmdate('Y-m-d H:i:s', $timestamp); + + } else if ($timezone == 'user') { + return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string); + } +} + +/** + * Adds a element attributes to open links in new windows. + * + * Comment text in popup windows should be filtered through this. Right now it's + * a moderately dumb function, ideally it would detect whether a target or rel + * attribute was already there and adjust its actions accordingly. + * + * @since 0.71 + * + * @param string $text Content to replace links to open in a new window. + * @return string Content that has filtered links. + */ +function popuplinks($text) { + $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text); + return $text; +} + +/** + * Strips out all characters that are not allowable in an email. + * + * @since 1.5.0 + * + * @param string $email Email address to filter. + * @return string Filtered email address. + */ +function sanitize_email( $email ) { + // Test for the minimum length the email can be + if ( strlen( $email ) < 3 ) { + return apply_filters( 'sanitize_email', '', $email, 'email_too_short' ); + } + + // Test for an @ character after the first position + if ( strpos( $email, '@', 1 ) === false ) { + return apply_filters( 'sanitize_email', '', $email, 'email_no_at' ); + } + + // Split out the local and domain parts + list( $local, $domain ) = explode( '@', $email, 2 ); + + // LOCAL PART + // Test for invalid characters + $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local ); + if ( '' === $local ) { + return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' ); + } + + // DOMAIN PART + // Test for sequences of periods + $domain = preg_replace( '/\.{2,}/', '', $domain ); + if ( '' === $domain ) { + return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' ); + } + + // Test for leading and trailing periods and whitespace + $domain = trim( $domain, " \t\n\r\0\x0B." ); + if ( '' === $domain ) { + return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' ); + } + + // Split the domain into subs + $subs = explode( '.', $domain ); + + // Assume the domain will have at least two subs + if ( 2 > count( $subs ) ) { + return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' ); + } + + // Create an array that will contain valid subs + $new_subs = array(); + + // Loop through each sub + foreach ( $subs as $sub ) { + // Test for leading and trailing hyphens + $sub = trim( $sub, " \t\n\r\0\x0B-" ); + + // Test for invalid characters + $sub = preg_replace( '/^[^a-z0-9-]+$/i', '', $sub ); + + // If there's anything left, add it to the valid subs + if ( '' !== $sub ) { + $new_subs[] = $sub; + } + } + + // If there aren't 2 or more valid subs + if ( 2 > count( $new_subs ) ) { + return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' ); + } + + // Join valid subs into the new domain + $domain = join( '.', $new_subs ); + + // Put the email back together + $email = $local . '@' . $domain; + + // Congratulations your email made it! + return apply_filters( 'sanitize_email', $email, $email, null ); +} + +/** + * Determines the difference between two timestamps. + * + * The difference is returned in a human readable format such as "1 hour", + * "5 mins", "2 days". + * + * @since 1.5.0 + * + * @param int $from Unix timestamp from which the difference begins. + * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set. + * @return string Human readable time difference. + */ +function human_time_diff( $from, $to = '' ) { + if ( empty($to) ) + $to = time(); + $diff = (int) abs($to - $from); + if ($diff <= 3600) { + $mins = round($diff / 60); + if ($mins <= 1) { + $mins = 1; + } + $since = sprintf(_n('%s min', '%s mins', $mins), $mins); + } else if (($diff <= 86400) && ($diff > 3600)) { + $hours = round($diff / 3600); + if ($hours <= 1) { + $hours = 1; + } + $since = sprintf(_n('%s hour', '%s hours', $hours), $hours); + } elseif ($diff >= 86400) { + $days = round($diff / 86400); + if ($days <= 1) { + $days = 1; + } + $since = sprintf(_n('%s day', '%s days', $days), $days); + } + return $since; +} + +/** + * Generates an excerpt from the content, if needed. + * + * The excerpt word amount will be 55 words and if the amount is greater than + * that, then the string '[...]' will be appended to the excerpt. If the string + * is less than 55 words, then the content will be returned as is. + * + * @since 1.5.0 + * + * @param string $text The exerpt. If set to empty an excerpt is generated. + * @return string The excerpt. + */ +function wp_trim_excerpt($text) { + $raw_excerpt = $text; + if ( '' == $text ) { + $text = get_the_content(''); + + $text = strip_shortcodes( $text ); + + $text = apply_filters('the_content', $text); + $text = str_replace(']]>', ']]>', $text); + $text = strip_tags($text); + $excerpt_length = apply_filters('excerpt_length', 55); + $words = explode(' ', $text, $excerpt_length + 1); + if (count($words) > $excerpt_length) { + array_pop($words); + array_push($words, '[...]'); + $text = implode(' ', $words); + } + } + return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); +} + +/** + * Converts named entities into numbered entities. + * + * @since 1.5.1 + * + * @param string $text The text within which entities will be converted. + * @return string Text with converted entities. + */ +function ent2ncr($text) { + $to_ncr = array( + '"' => '"', + '&' => '&', + '⁄' => '/', + '<' => '<', + '>' => '>', + '|' => '|', + ' ' => ' ', + '¡' => '¡', + '¢' => '¢', + '£' => '£', + '¤' => '¤', + '¥' => '¥', + '¦' => '¦', + '&brkbar;' => '¦', + '§' => '§', + '¨' => '¨', + '¨' => '¨', + '©' => '©', + 'ª' => 'ª', + '«' => '«', + '¬' => '¬', + '­' => '­', + '®' => '®', + '¯' => '¯', + '&hibar;' => '¯', + '°' => '°', + '±' => '±', + '²' => '²', + '³' => '³', + '´' => '´', + 'µ' => 'µ', + '¶' => '¶', + '·' => '·', + '¸' => '¸', + '¹' => '¹', + 'º' => 'º', + '»' => '»', + '¼' => '¼', + '½' => '½', + '¾' => '¾', + '¿' => '¿', + 'À' => 'À', + 'Á' => 'Á', + 'Â' => 'Â', + 'Ã' => 'Ã', + 'Ä' => 'Ä', + 'Å' => 'Å', + 'Æ' => 'Æ', + 'Ç' => 'Ç', + 'È' => 'È', + 'É' => 'É', + 'Ê' => 'Ê', + 'Ë' => 'Ë', + 'Ì' => 'Ì', + 'Í' => 'Í', + 'Î' => 'Î', + 'Ï' => 'Ï', + 'Ð' => 'Ð', + 'Ñ' => 'Ñ', + 'Ò' => 'Ò', + 'Ó' => 'Ó', + 'Ô' => 'Ô', + 'Õ' => 'Õ', + 'Ö' => 'Ö', + '×' => '×', + 'Ø' => 'Ø', + 'Ù' => 'Ù', + 'Ú' => 'Ú', + 'Û' => 'Û', + 'Ü' => 'Ü', + 'Ý' => 'Ý', + 'Þ' => 'Þ', + 'ß' => 'ß', + 'à' => 'à', + 'á' => 'á', + 'â' => 'â', + 'ã' => 'ã', + 'ä' => 'ä', + 'å' => 'å', + 'æ' => 'æ', + 'ç' => 'ç', + 'è' => 'è', + 'é' => 'é', + 'ê' => 'ê', + 'ë' => 'ë', + 'ì' => 'ì', + 'í' => 'í', + 'î' => 'î', + 'ï' => 'ï', + 'ð' => 'ð', + 'ñ' => 'ñ', + 'ò' => 'ò', + 'ó' => 'ó', + 'ô' => 'ô', + 'õ' => 'õ', + 'ö' => 'ö', + '÷' => '÷', + 'ø' => 'ø', + 'ù' => 'ù', + 'ú' => 'ú', + 'û' => 'û', + 'ü' => 'ü', + 'ý' => 'ý', + 'þ' => 'þ', + 'ÿ' => 'ÿ', + 'Œ' => 'Œ', + 'œ' => 'œ', + 'Š' => 'Š', + 'š' => 'š', + 'Ÿ' => 'Ÿ', + 'ƒ' => 'ƒ', + 'ˆ' => 'ˆ', + '˜' => '˜', + 'Α' => 'Α', + 'Β' => 'Β', + 'Γ' => 'Γ', + 'Δ' => 'Δ', + 'Ε' => 'Ε', + 'Ζ' => 'Ζ', + 'Η' => 'Η', + 'Θ' => 'Θ', + 'Ι' => 'Ι', + 'Κ' => 'Κ', + 'Λ' => 'Λ', + 'Μ' => 'Μ', + 'Ν' => 'Ν', + 'Ξ' => 'Ξ', + 'Ο' => 'Ο', + 'Π' => 'Π', + 'Ρ' => 'Ρ', + 'Σ' => 'Σ', + 'Τ' => 'Τ', + 'Υ' => 'Υ', + 'Φ' => 'Φ', + 'Χ' => 'Χ', + 'Ψ' => 'Ψ', + 'Ω' => 'Ω', + 'α' => 'α', + 'β' => 'β', + 'γ' => 'γ', + 'δ' => 'δ', + 'ε' => 'ε', + 'ζ' => 'ζ', + 'η' => 'η', + 'θ' => 'θ', + 'ι' => 'ι', + 'κ' => 'κ', + 'λ' => 'λ', + 'μ' => 'μ', + 'ν' => 'ν', + 'ξ' => 'ξ', + 'ο' => 'ο', + 'π' => 'π', + 'ρ' => 'ρ', + 'ς' => 'ς', + 'σ' => 'σ', + 'τ' => 'τ', + 'υ' => 'υ', + 'φ' => 'φ', + 'χ' => 'χ', + 'ψ' => 'ψ', + 'ω' => 'ω', + 'ϑ' => 'ϑ', + 'ϒ' => 'ϒ', + 'ϖ' => 'ϖ', + ' ' => ' ', + ' ' => ' ', + ' ' => ' ', + '‌' => '‌', + '‍' => '‍', + '‎' => '‎', + '‏' => '‏', + '–' => '–', + '—' => '—', + '‘' => '‘', + '’' => '’', + '‚' => '‚', + '“' => '“', + '”' => '”', + '„' => '„', + '†' => '†', + '‡' => '‡', + '•' => '•', + '…' => '…', + '‰' => '‰', + '′' => '′', + '″' => '″', + '‹' => '‹', + '›' => '›', + '‾' => '‾', + '⁄' => '⁄', + '€' => '€', + 'ℑ' => 'ℑ', + '℘' => '℘', + 'ℜ' => 'ℜ', + '™' => '™', + 'ℵ' => 'ℵ', + '↵' => '↵', + '⇐' => '⇐', + '⇑' => '⇑', + '⇒' => '⇒', + '⇓' => '⇓', + '⇔' => '⇔', + '∀' => '∀', + '∂' => '∂', + '∃' => '∃', + '∅' => '∅', + '∇' => '∇', + '∈' => '∈', + '∉' => '∉', + '∋' => '∋', + '∏' => '∏', + '∑' => '∑', + '−' => '−', + '∗' => '∗', + '√' => '√', + '∝' => '∝', + '∞' => '∞', + '∠' => '∠', + '∧' => '∧', + '∨' => '∨', + '∩' => '∩', + '∪' => '∪', + '∫' => '∫', + '∴' => '∴', + '∼' => '∼', + '≅' => '≅', + '≈' => '≈', + '≠' => '≠', + '≡' => '≡', + '≤' => '≤', + '≥' => '≥', + '⊂' => '⊂', + '⊃' => '⊃', + '⊄' => '⊄', + '⊆' => '⊆', + '⊇' => '⊇', + '⊕' => '⊕', + '⊗' => '⊗', + '⊥' => '⊥', + '⋅' => '⋅', + '⌈' => '⌈', + '⌉' => '⌉', + '⌊' => '⌊', + '⌋' => '⌋', + '⟨' => '〈', + '⟩' => '〉', + '←' => '←', + '↑' => '↑', + '→' => '→', + '↓' => '↓', + '↔' => '↔', + '◊' => '◊', + '♠' => '♠', + '♣' => '♣', + '♥' => '♥', + '♦' => '♦' + ); + + return str_replace( array_keys($to_ncr), array_values($to_ncr), $text ); +} + +/** + * Formats text for the rich text editor. + * + * The filter 'richedit_pre' is applied here. If $text is empty the filter will + * be applied to an empty string. + * + * @since 2.0.0 + * + * @param string $text The text to be formatted. + * @return string The formatted text after filter is applied. + */ +function wp_richedit_pre($text) { + // Filtering a blank results in an annoying <br />\n + if ( empty($text) ) return apply_filters('richedit_pre', ''); + + $output = convert_chars($text); + $output = wpautop($output); + $output = htmlspecialchars($output, ENT_NOQUOTES); + + return apply_filters('richedit_pre', $output); +} + +/** + * Formats text for the HTML editor. + * + * Unless $output is empty it will pass through htmlspecialchars before the + * 'htmledit_pre' filter is applied. + * + * @since 2.5.0 + * + * @param string $output The text to be formatted. + * @return string Formatted text after filter applied. + */ +function wp_htmledit_pre($output) { + if ( !empty($output) ) + $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > & + + return apply_filters('htmledit_pre', $output); +} + +/** + * Checks and cleans a URL. + * + * A number of characters are removed from the URL. If the URL is for displaying + * (the default behaviour) amperstands are also replaced. The 'esc_url' filter + * is applied to the returned cleaned URL. + * + * @since 1.2.0 + * @uses wp_kses_bad_protocol() To only permit protocols in the URL set + * via $protocols or the common ones set in the function. + * + * @param string $url The URL to be cleaned. + * @param array $protocols Optional. An array of acceptable protocols. + * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set. + * @param string $context Optional. How the URL will be used. Default is 'display'. + * @return string The cleaned $url after the 'cleaned_url' filter is applied. + */ +function clean_url( $url, $protocols = null, $context = 'display' ) { + $original_url = $url; + + if ('' == $url) return $url; + $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url); + $strip = array('%0d', '%0a', '%0D', '%0A'); + $url = _deep_replace($strip, $url); + $url = str_replace(';//', '://', $url); + /* If the URL doesn't appear to contain a scheme, we + * presume it needs http:// appended (unless a relative + * link starting with / or a php file). + */ + if ( strpos($url, ':') === false && + substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) ) + $url = 'http://' . $url; + + // Replace ampersands and single quotes only when displaying. + if ( 'display' == $context ) { + $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&$1', $url); + $url = str_replace( "'", ''', $url ); + } + + if ( !is_array($protocols) ) + $protocols = array('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet'); + if ( wp_kses_bad_protocol( $url, $protocols ) != $url ) + return ''; + + return apply_filters('clean_url', $url, $original_url, $context); +} + +/** + * Perform a deep string replace operation to ensure the values in $search are no longer present + * + * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values + * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that + * str_replace would return + * + * @since 2.8.1 + * @access private + * + * @param string|array $search + * @param string $subject + * @return string The processed string + */ +function _deep_replace($search, $subject){ + $found = true; + while($found) { + $found = false; + foreach( (array) $search as $val ) { + while(strpos($subject, $val) !== false) { + $found = true; + $subject = str_replace($val, '', $subject); + } + } + } + + return $subject; +} + +/** + * Escapes data for use in a MySQL query + * + * This is just a handy shortcut for $wpdb->escape(), for completeness' sake + * + * @since 2.8.0 + * @param string $sql Unescaped SQL data + * @return string The cleaned $sql + */ +function esc_sql( $sql ) { + global $wpdb; + return $wpdb->escape( $sql ); +} + + +/** + * Checks and cleans a URL. + * + * A number of characters are removed from the URL. If the URL is for displaying + * (the default behaviour) amperstands are also replaced. The 'esc_url' filter + * is applied to the returned cleaned URL. + * + * @since 2.8.0 + * @uses esc_url() + * @uses wp_kses_bad_protocol() To only permit protocols in the URL set + * via $protocols or the common ones set in the function. + * + * @param string $url The URL to be cleaned. + * @param array $protocols Optional. An array of acceptable protocols. + * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set. + * @return string The cleaned $url after the 'cleaned_url' filter is applied. + */ +function esc_url( $url, $protocols = null ) { + return clean_url( $url, $protocols, 'display' ); +} + +/** + * Performs esc_url() for database usage. + * + * @see esc_url() + * @see esc_url() + * + * @since 2.8.0 + * + * @param string $url The URL to be cleaned. + * @param array $protocols An array of acceptable protocols. + * @return string The cleaned URL. + */ +function esc_url_raw( $url, $protocols = null ) { + return clean_url( $url, $protocols, 'db' ); +} + +/** + * Performs esc_url() for database or redirect usage. + * + * @see esc_url() + * @deprecated 2.8.0 + * + * @since 2.3.1 + * + * @param string $url The URL to be cleaned. + * @param array $protocols An array of acceptable protocols. + * @return string The cleaned URL. + */ +function sanitize_url( $url, $protocols = null ) { + return clean_url( $url, $protocols, 'db' ); +} + +/** + * Convert entities, while preserving already-encoded entities. + * + * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes. + * + * @since 1.2.2 + * + * @param string $myHTML The text to be converted. + * @return string Converted text. + */ +function htmlentities2($myHTML) { + $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES ); + $translation_table[chr(38)] = '&'; + return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&", strtr($myHTML, $translation_table) ); +} + +/** + * Escape single quotes, specialchar double quotes, and fix line endings. + * + * The filter 'js_escape' is also applied here. + * + * @since 2.8.0 + * + * @param string $text The text to be escaped. + * @return string Escaped text. + */ +function esc_js( $text ) { + $safe_text = wp_check_invalid_utf8( $text ); + $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT ); + $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) ); + $safe_text = preg_replace( "/\r?\n/", "\\n", addslashes( $safe_text ) ); + return apply_filters( 'js_escape', $safe_text, $text ); +} + +/** + * Escape single quotes, specialchar double quotes, and fix line endings. + * + * The filter 'js_escape' is also applied by esc_js() + * + * @since 2.0.4 + * + * @deprecated 2.8.0 + * @see esc_js() + * + * @param string $text The text to be escaped. + * @return string Escaped text. + */ +function js_escape( $text ) { + return esc_js( $text ); +} + +/** + * Escaping for HTML blocks. + * + * @since 2.8.0 + * + * @param string $text + * @return string + */ +function esc_html( $text ) { + $safe_text = wp_check_invalid_utf8( $text ); + $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES ); + return apply_filters( 'esc_html', $safe_text, $text ); + return $text; +} + +/** + * Escaping for HTML blocks + * @deprecated 2.8.0 + * @see esc_html() + */ +function wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) { + if ( func_num_args() > 1 ) { // Maintain backwards compat for people passing additional args + $args = func_get_args(); + return call_user_func_array( '_wp_specialchars', $args ); + } else { + return esc_html( $string ); + } +} + +/** + * Escaping for HTML attributes. + * + * @since 2.8.0 + * + * @param string $text + * @return string + */ +function esc_attr( $text ) { + $safe_text = wp_check_invalid_utf8( $text ); + $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES ); + return apply_filters( 'attribute_escape', $safe_text, $text ); +} + +/** + * Escaping for HTML attributes. + * + * @since 2.0.6 + * + * @deprecated 2.8.0 + * @see esc_attr() + * + * @param string $text + * @return string + */ +function attribute_escape( $text ) { + return esc_attr( $text ); +} + +/** + * Escape a HTML tag name. + * + * @since 2.5.0 + * + * @param string $tag_name + * @return string + */ +function tag_escape($tag_name) { + $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) ); + return apply_filters('tag_escape', $safe_tag, $tag_name); +} + +/** + * Escapes text for SQL LIKE special characters % and _. + * + * @since 2.5.0 + * + * @param string $text The text to be escaped. + * @return string text, safe for inclusion in LIKE query. + */ +function like_escape($text) { + return str_replace(array("%", "_"), array("\\%", "\\_"), $text); +} + +/** + * Convert full URL paths to absolute paths. + * + * Removes the http or https protocols and the domain. Keeps the path '/' at the + * beginning, so it isn't a true relative link, but from the web root base. + * + * @since 2.1.0 + * + * @param string $link Full URL path. + * @return string Absolute path. + */ +function wp_make_link_relative( $link ) { + return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link ); +} + +/** + * Sanitises various option values based on the nature of the option. + * + * This is basically a switch statement which will pass $value through a number + * of functions depending on the $option. + * + * @since 2.0.5 + * + * @param string $option The name of the option. + * @param string $value The unsanitised value. + * @return string Sanitized value. + */ +function sanitize_option($option, $value) { + + switch ($option) { + case 'admin_email': + $value = sanitize_email($value); + break; + + case 'thumbnail_size_w': + case 'thumbnail_size_h': + case 'medium_size_w': + case 'medium_size_h': + case 'large_size_w': + case 'large_size_h': + case 'default_post_edit_rows': + case 'mailserver_port': + case 'comment_max_links': + case 'page_on_front': + case 'rss_excerpt_length': + case 'default_category': + case 'default_email_category': + case 'default_link_category': + case 'close_comments_days_old': + case 'comments_per_page': + case 'thread_comments_depth': + $value = abs((int) $value); + break; + + case 'posts_per_page': + case 'posts_per_rss': + $value = (int) $value; + if ( empty($value) ) $value = 1; + if ( $value < -1 ) $value = abs($value); + break; + + case 'default_ping_status': + case 'default_comment_status': + // Options that if not there have 0 value but need to be something like "closed" + if ( $value == '0' || $value == '') + $value = 'closed'; + break; + + case 'blogdescription': + case 'blogname': + $value = addslashes($value); + $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes + $value = stripslashes($value); + $value = esc_html( $value ); + break; + + case 'blog_charset': + $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes + break; + + case 'date_format': + case 'time_format': + case 'mailserver_url': + case 'mailserver_login': + case 'mailserver_pass': + case 'ping_sites': + case 'upload_path': + $value = strip_tags($value); + $value = addslashes($value); + $value = wp_filter_kses($value); // calls stripslashes then addslashes + $value = stripslashes($value); + break; + + case 'gmt_offset': + $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes + break; + + case 'siteurl': + case 'home': + $value = stripslashes($value); + $value = esc_url($value); + break; + default : + $value = apply_filters("sanitize_option_{$option}", $value, $option); + break; + } + + return $value; +} + +/** + * Parses a string into variables to be stored in an array. + * + * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if + * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on. + * + * @since 2.2.1 + * @uses apply_filters() for the 'wp_parse_str' filter. + * + * @param string $string The string to be parsed. + * @param array $array Variables will be stored in this array. + */ +function wp_parse_str( $string, &$array ) { + parse_str( $string, $array ); + if ( get_magic_quotes_gpc() ) + $array = stripslashes_deep( $array ); + $array = apply_filters( 'wp_parse_str', $array ); +} + +/** + * Convert lone less than signs. + * + * KSES already converts lone greater than signs. + * + * @uses wp_pre_kses_less_than_callback in the callback function. + * @since 2.3.0 + * + * @param string $text Text to be converted. + * @return string Converted text. + */ +function wp_pre_kses_less_than( $text ) { + return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text); +} + +/** + * Callback function used by preg_replace. + * + * @uses esc_html to format the $matches text. + * @since 2.3.0 + * + * @param array $matches Populated by matches to preg_replace. + * @return string The text returned after esc_html if needed. + */ +function wp_pre_kses_less_than_callback( $matches ) { + if ( false === strpos($matches[0], '>') ) + return esc_html($matches[0]); + return $matches[0]; +} + +/** + * WordPress implementation of PHP sprintf() with filters. + * + * @since 2.5.0 + * @link http://www.php.net/sprintf + * + * @param string $pattern The string which formatted args are inserted. + * @param mixed $args,... Arguments to be formatted into the $pattern string. + * @return string The formatted string. + */ +function wp_sprintf( $pattern ) { + $args = func_get_args( ); + $len = strlen($pattern); + $start = 0; + $result = ''; + $arg_index = 0; + while ( $len > $start ) { + // Last character: append and break + if ( strlen($pattern) - 1 == $start ) { + $result .= substr($pattern, -1); + break; + } + + // Literal %: append and continue + if ( substr($pattern, $start, 2) == '%%' ) { + $start += 2; + $result .= '%'; + continue; + } + + // Get fragment before next % + $end = strpos($pattern, '%', $start + 1); + if ( false === $end ) + $end = $len; + $fragment = substr($pattern, $start, $end - $start); + + // Fragment has a specifier + if ( $pattern{$start} == '%' ) { + // Find numbered arguments or take the next one in order + if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) { + $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : ''; + $fragment = str_replace("%{$matches[1]}$", '%', $fragment); + } else { + ++$arg_index; + $arg = isset($args[$arg_index]) ? $args[$arg_index] : ''; + } + + // Apply filters OR sprintf + $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg ); + if ( $_fragment != $fragment ) + $fragment = $_fragment; + else + $fragment = sprintf($fragment, strval($arg) ); + } + + // Append to result and move to next fragment + $result .= $fragment; + $start = $end; + } + return $result; +} + +/** + * Localize list items before the rest of the content. + * + * The '%l' must be at the first characters can then contain the rest of the + * content. The list items will have ', ', ', and', and ' and ' added depending + * on the amount of list items in the $args parameter. + * + * @since 2.5.0 + * + * @param string $pattern Content containing '%l' at the beginning. + * @param array $args List items to prepend to the content and replace '%l'. + * @return string Localized list items and rest of the content. + */ +function wp_sprintf_l($pattern, $args) { + // Not a match + if ( substr($pattern, 0, 2) != '%l' ) + return $pattern; + + // Nothing to work with + if ( empty($args) ) + return ''; + + // Translate and filter the delimiter set (avoid ampersands and entities here) + $l = apply_filters('wp_sprintf_l', array( + /* translators: used between list items, there is a space after the coma */ + 'between' => __(', '), + /* translators: used between list items, there is a space after the and */ + 'between_last_two' => __(', and '), + /* translators: used between only two list items, there is a space after the and */ + 'between_only_two' => __(' and '), + )); + + $args = (array) $args; + $result = array_shift($args); + if ( count($args) == 1 ) + $result .= $l['between_only_two'] . array_shift($args); + // Loop when more than two args + $i = count($args); + while ( $i ) { + $arg = array_shift($args); + $i--; + if ( 0 == $i ) + $result .= $l['between_last_two'] . $arg; + else + $result .= $l['between'] . $arg; + } + return $result . substr($pattern, 2); +} + +/** + * Safely extracts not more than the first $count characters from html string. + * + * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT* + * be counted as one character. For example & will be counted as 4, < as + * 3, etc. + * + * @since 2.5.0 + * + * @param integer $str String to get the excerpt from. + * @param integer $count Maximum number of characters to take. + * @return string The excerpt. + */ +function wp_html_excerpt( $str, $count ) { + $str = strip_tags( $str ); + $str = mb_substr( $str, 0, $count ); + // remove part of an entity at the end + $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str ); + return $str; +} + +/** + * Add a Base url to relative links in passed content. + * + * By default it supports the 'src' and 'href' attributes. However this can be + * changed via the 3rd param. + * + * @since 2.7.0 + * + * @param string $content String to search for links in. + * @param string $base The base URL to prefix to links. + * @param array $attrs The attributes which should be processed. + * @return string The processed content. + */ +function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) { + $attrs = implode('|', (array)$attrs); + return preg_replace_callback("!($attrs)=(['\"])(.+?)\\2!i", + create_function('$m', 'return _links_add_base($m, "' . $base . '");'), + $content); +} + +/** + * Callback to add a base url to relative links in passed content. + * + * @since 2.7.0 + * @access private + * + * @param string $m The matched link. + * @param string $base The base URL to prefix to links. + * @return string The processed link. + */ +function _links_add_base($m, $base) { + //1 = attribute name 2 = quotation mark 3 = URL + return $m[1] . '=' . $m[2] . + (strpos($m[3], 'http://') === false ? + path_join($base, $m[3]) : + $m[3]) + . $m[2]; +} + +/** + * Adds a Target attribute to all links in passed content. + * + * This function by default only applies to <a> tags, however this can be + * modified by the 3rd param. + * + * <b>NOTE:</b> Any current target attributed will be striped and replaced. + * + * @since 2.7.0 + * + * @param string $content String to search for links in. + * @param string $target The Target to add to the links. + * @param array $tags An array of tags to apply to. + * @return string The processed content. + */ +function links_add_target( $content, $target = '_blank', $tags = array('a') ) { + $tags = implode('|', (array)$tags); + return preg_replace_callback("!<($tags)(.+?)>!i", + create_function('$m', 'return _links_add_target($m, "' . $target . '");'), + $content); +} +/** + * Callback to add a target attribute to all links in passed content. + * + * @since 2.7.0 + * @access private + * + * @param string $m The matched link. + * @param string $target The Target to add to the links. + * @return string The processed link. + */ +function _links_add_target( $m, $target ) { + $tag = $m[1]; + $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]); + return '<' . $tag . $link . ' target="' . $target . '">'; +} + +// normalize EOL characters and strip duplicate whitespace +function normalize_whitespace( $str ) { + $str = trim($str); + $str = str_replace("\r", "\n", $str); + $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str ); + return $str; +} + +?> diff --git a/wp-includes/functions.php b/wp-includes/functions.php new file mode 100644 index 0000000..3984a31 --- /dev/null +++ b/wp-includes/functions.php @@ -0,0 +1,3342 @@ +<?php +/** + * Main WordPress API + * + * @package WordPress + */ + +/** + * Converts MySQL DATETIME field to user specified date format. + * + * If $dateformatstring has 'G' value, then gmmktime() function will be used to + * make the time. If $dateformatstring is set to 'U', then mktime() function + * will be used to make the time. + * + * The $translate will only be used, if it is set to true and it is by default + * and if the $wp_locale object has the month and weekday set. + * + * @since 0.71 + * + * @param string $dateformatstring Either 'G', 'U', or php date format. + * @param string $mysqlstring Time from mysql DATETIME field. + * @param bool $translate Optional. Default is true. Will switch format to locale. + * @return string Date formated by $dateformatstring or locale (if available). + */ +function mysql2date( $dateformatstring, $mysqlstring, $translate = true ) { + global $wp_locale; + $m = $mysqlstring; + if ( empty( $m ) ) + return false; + + if( 'G' == $dateformatstring ) { + return strtotime( $m . ' +0000' ); + } + + $i = strtotime( $m ); + + if( 'U' == $dateformatstring ) + return $i; + + if ( $translate) + return date_i18n( $dateformatstring, $i ); + else + return date( $dateformatstring, $i ); +} + +/** + * Retrieve the current time based on specified type. + * + * The 'mysql' type will return the time in the format for MySQL DATETIME field. + * The 'timestamp' type will return the current timestamp. + * + * If $gmt is set to either '1' or 'true', then both types will use GMT time. + * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option. + * + * @since 1.0.0 + * + * @param string $type Either 'mysql' or 'timestamp'. + * @param int|bool $gmt Optional. Whether to use GMT timezone. Default is false. + * @return int|string String if $type is 'gmt', int if $type is 'timestamp'. + */ +function current_time( $type, $gmt = 0 ) { + switch ( $type ) { + case 'mysql': + return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * 3600 ) ) ); + break; + case 'timestamp': + return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * 3600 ); + break; + } +} + +/** + * Retrieve the date in localized format, based on timestamp. + * + * If the locale specifies the locale month and weekday, then the locale will + * take over the format for the date. If it isn't, then the date format string + * will be used instead. + * + * @since 0.71 + * + * @param string $dateformatstring Format to display the date. + * @param int $unixtimestamp Optional. Unix timestamp. + * @param bool $gmt Optional, default is false. Whether to convert to GMT for time. + * @return string The date, translated if locale specifies it. + */ +function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) { + global $wp_locale; + $i = $unixtimestamp; + // Sanity check for PHP 5.1.0- + if ( false === $i || intval($i) < 0 ) { + if ( ! $gmt ) + $i = current_time( 'timestamp' ); + else + $i = time(); + // we should not let date() interfere with our + // specially computed timestamp + $gmt = true; + } + + // store original value for language with untypical grammars + // see http://core.trac.wordpress.org/ticket/9396 + $req_format = $dateformatstring; + + $datefunc = $gmt? 'gmdate' : 'date'; + + if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) { + $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) ); + $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth ); + $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) ); + $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday ); + $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) ); + $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) ); + $dateformatstring = ' '.$dateformatstring; + $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring ); + $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring ); + $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring ); + $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring ); + $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring ); + $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring ); + + $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 ); + } + $j = @$datefunc( $dateformatstring, $i ); + // allow plugins to redo this entirely for languages with untypical grammars + $j = apply_filters('date_i18n', $j, $req_format, $i, $gmt); + return $j; +} + +/** + * Convert number to format based on the locale. + * + * @since 2.3.0 + * + * @param mixed $number The number to convert based on locale. + * @param int $decimals Precision of the number of decimal places. + * @return string Converted number in string format. + */ +function number_format_i18n( $number, $decimals = null ) { + global $wp_locale; + // let the user override the precision only + $decimals = ( is_null( $decimals ) ) ? $wp_locale->number_format['decimals'] : intval( $decimals ); + + $num = number_format( $number, $decimals, $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] ); + + // let the user translate digits from latin to localized language + return apply_filters( 'number_format_i18n', $num ); +} + +/** + * Convert number of bytes largest unit bytes will fit into. + * + * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts + * number of bytes to human readable number by taking the number of that unit + * that the bytes will go into it. Supports TB value. + * + * Please note that integers in PHP are limited to 32 bits, unless they are on + * 64 bit architecture, then they have 64 bit size. If you need to place the + * larger size then what PHP integer type will hold, then use a string. It will + * be converted to a double, which should always have 64 bit length. + * + * Technically the correct unit names for powers of 1024 are KiB, MiB etc. + * @link http://en.wikipedia.org/wiki/Byte + * + * @since 2.3.0 + * + * @param int|string $bytes Number of bytes. Note max integer size for integers. + * @param int $decimals Precision of number of decimal places. + * @return bool|string False on failure. Number string on success. + */ +function size_format( $bytes, $decimals = null ) { + $quant = array( + // ========================= Origin ==== + 'TB' => 1099511627776, // pow( 1024, 4) + 'GB' => 1073741824, // pow( 1024, 3) + 'MB' => 1048576, // pow( 1024, 2) + 'kB' => 1024, // pow( 1024, 1) + 'B ' => 1, // pow( 1024, 0) + ); + + foreach ( $quant as $unit => $mag ) + if ( doubleval($bytes) >= $mag ) + return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit; + + return false; +} + +/** + * Get the week start and end from the datetime or date string from mysql. + * + * @since 0.71 + * + * @param string $mysqlstring Date or datetime field type from mysql. + * @param int $start_of_week Optional. Start of the week as an integer. + * @return array Keys are 'start' and 'end'. + */ +function get_weekstartend( $mysqlstring, $start_of_week = '' ) { + $my = substr( $mysqlstring, 0, 4 ); // Mysql string Year + $mm = substr( $mysqlstring, 8, 2 ); // Mysql string Month + $md = substr( $mysqlstring, 5, 2 ); // Mysql string day + $day = mktime( 0, 0, 0, $md, $mm, $my ); // The timestamp for mysqlstring day. + $weekday = date( 'w', $day ); // The day of the week from the timestamp + $i = 86400; // One day + if( !is_numeric($start_of_week) ) + $start_of_week = get_option( 'start_of_week' ); + + if ( $weekday < $start_of_week ) + $weekday = 7 - $start_of_week - $weekday; + + while ( $weekday > $start_of_week ) { + $weekday = date( 'w', $day ); + if ( $weekday < $start_of_week ) + $weekday = 7 - $start_of_week - $weekday; + + $day -= 86400; + $i = 0; + } + $week['start'] = $day + 86400 - $i; + $week['end'] = $week['start'] + 604799; + return $week; +} + +/** + * Unserialize value only if it was serialized. + * + * @since 2.0.0 + * + * @param string $original Maybe unserialized original, if is needed. + * @return mixed Unserialized data can be any type. + */ +function maybe_unserialize( $original ) { + if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in + return @unserialize( $original ); + return $original; +} + +/** + * Check value to find if it was serialized. + * + * If $data is not an string, then returned value will always be false. + * Serialized data is always a string. + * + * @since 2.0.5 + * + * @param mixed $data Value to check to see if was serialized. + * @return bool False if not serialized and true if it was. + */ +function is_serialized( $data ) { + // if it isn't a string, it isn't serialized + if ( !is_string( $data ) ) + return false; + $data = trim( $data ); + if ( 'N;' == $data ) + return true; + if ( !preg_match( '/^([adObis]):/', $data, $badions ) ) + return false; + switch ( $badions[1] ) { + case 'a' : + case 'O' : + case 's' : + if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) ) + return true; + break; + case 'b' : + case 'i' : + case 'd' : + if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) ) + return true; + break; + } + return false; +} + +/** + * Check whether serialized data is of string type. + * + * @since 2.0.5 + * + * @param mixed $data Serialized data + * @return bool False if not a serialized string, true if it is. + */ +function is_serialized_string( $data ) { + // if it isn't a string, it isn't a serialized string + if ( !is_string( $data ) ) + return false; + $data = trim( $data ); + if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings + return true; + return false; +} + +/** + * Retrieve option value based on setting name. + * + * If the option does not exist or does not have a value, then the return value + * will be false. This is useful to check whether you need to install an option + * and is commonly used during installation of plugin options and to test + * whether upgrading is required. + * + * You can "short-circuit" the retrieval of the option from the database for + * your plugin or core options that aren't protected. You can do so by hooking + * into the 'pre_option_$option' with the $option being replaced by the option + * name. You should not try to override special options, but you will not be + * prevented from doing so. + * + * There is a second filter called 'option_$option' with the $option being + * replaced with the option name. This gives the value as the only parameter. + * + * If the option was serialized, when the option was added and, or updated, then + * it will be unserialized, when it is returned. + * + * @since 1.5.0 + * @package WordPress + * @subpackage Option + * @uses apply_filters() Calls 'pre_option_$optionname' false to allow + * overwriting the option value in a plugin. + * @uses apply_filters() Calls 'option_$optionname' with the option name value. + * + * @param string $setting Name of option to retrieve. Should already be SQL-escaped + * @return mixed Value set for the option. + */ +function get_option( $setting, $default = false ) { + global $wpdb; + + // Allow plugins to short-circuit options. + $pre = apply_filters( 'pre_option_' . $setting, false ); + if ( false !== $pre ) + return $pre; + + // prevent non-existent options from triggering multiple queries + $notoptions = wp_cache_get( 'notoptions', 'options' ); + if ( isset( $notoptions[$setting] ) ) + return $default; + + $alloptions = wp_load_alloptions(); + + if ( isset( $alloptions[$setting] ) ) { + $value = $alloptions[$setting]; + } else { + $value = wp_cache_get( $setting, 'options' ); + + if ( false === $value ) { + if ( defined( 'WP_INSTALLING' ) ) + $suppress = $wpdb->suppress_errors(); + // expected_slashed ($setting) + $row = $wpdb->get_row( "SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1" ); + if ( defined( 'WP_INSTALLING' ) ) + $wpdb->suppress_errors($suppress); + + if ( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values + $value = $row->option_value; + wp_cache_add( $setting, $value, 'options' ); + } else { // option does not exist, so we must cache its non-existence + $notoptions[$setting] = true; + wp_cache_set( 'notoptions', $notoptions, 'options' ); + return $default; + } + } + } + + // If home is not set use siteurl. + if ( 'home' == $setting && '' == $value ) + return get_option( 'siteurl' ); + + if ( in_array( $setting, array('siteurl', 'home', 'category_base', 'tag_base') ) ) + $value = untrailingslashit( $value ); + + return apply_filters( 'option_' . $setting, maybe_unserialize( $value ) ); +} + +/** + * Protect WordPress special option from being modified. + * + * Will die if $option is in protected list. Protected options are 'alloptions' + * and 'notoptions' options. + * + * @since 2.2.0 + * @package WordPress + * @subpackage Option + * + * @param string $option Option name. + */ +function wp_protect_special_option( $option ) { + $protected = array( 'alloptions', 'notoptions' ); + if ( in_array( $option, $protected ) ) + die( sprintf( __( '%s is a protected WP option and may not be modified' ), esc_html( $option ) ) ); +} + +/** + * Print option value after sanitizing for forms. + * + * @uses attr Sanitizes value. + * @since 1.5.0 + * @package WordPress + * @subpackage Option + * + * @param string $option Option name. + */ +function form_option( $option ) { + echo esc_attr(get_option( $option ) ); +} + +/** + * Retrieve all autoload options or all options, if no autoloaded ones exist. + * + * This is different from wp_load_alloptions() in that this function does not + * cache its results and will retrieve all options from the database every time + * + * it is called. + * + * @since 1.0.0 + * @package WordPress + * @subpackage Option + * @uses apply_filters() Calls 'pre_option_$optionname' hook with option value as parameter. + * @uses apply_filters() Calls 'all_options' on options list. + * + * @return array List of all options. + */ +function get_alloptions() { + global $wpdb; + $show = $wpdb->hide_errors(); + if ( !$options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) ) + $options = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ); + $wpdb->show_errors($show); + + foreach ( (array) $options as $option ) { + // "When trying to design a foolproof system, + // never underestimate the ingenuity of the fools :)" -- Dougal + if ( in_array( $option->option_name, array( 'siteurl', 'home', 'category_base', 'tag_base' ) ) ) + $option->option_value = untrailingslashit( $option->option_value ); + $value = maybe_unserialize( $option->option_value ); + $all_options->{$option->option_name} = apply_filters( 'pre_option_' . $option->option_name, $value ); + } + return apply_filters( 'all_options', $all_options ); +} + +/** + * Loads and caches all autoloaded options, if available or all options. + * + * This is different from get_alloptions(), in that this function will cache the + * options and will return the cached options when called again. + * + * @since 2.2.0 + * @package WordPress + * @subpackage Option + * + * @return array List all options. + */ +function wp_load_alloptions() { + global $wpdb; + + $alloptions = wp_cache_get( 'alloptions', 'options' ); + + if ( !$alloptions ) { + $suppress = $wpdb->suppress_errors(); + if ( !$alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'" ) ) + $alloptions_db = $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options" ); + $wpdb->suppress_errors($suppress); + $alloptions = array(); + foreach ( (array) $alloptions_db as $o ) + $alloptions[$o->option_name] = $o->option_value; + wp_cache_add( 'alloptions', $alloptions, 'options' ); + } + return $alloptions; +} + +/** + * Update the value of an option that was already added. + * + * You do not need to serialize values, if the value needs to be serialize, then + * it will be serialized before it is inserted into the database. Remember, + * resources can not be serialized or added as an option. + * + * If the option does not exist, then the option will be added with the option + * value, but you will not be able to set whether it is autoloaded. If you want + * to set whether an option autoloaded, then you need to use the add_option(). + * + * Before the option is updated, then the filter named + * 'pre_update_option_$option_name', with the $option_name as the $option_name + * parameter value, will be called. The hook should accept two parameters, the + * first is the new value and the second is the old value. Whatever is + * returned will be used as the new value. + * + * After the value has been updated the action named 'update_option_$option_name' + * will be called. This action receives two parameters the first being the old + * value and the second the new value. + * + * @since 1.0.0 + * @package WordPress + * @subpackage Option + * + * @param string $option_name Option name. Expected to not be SQL-escaped + * @param mixed $newvalue Option value. + * @return bool False if value was not updated and true if value was updated. + */ +function update_option( $option_name, $newvalue ) { + global $wpdb; + + wp_protect_special_option( $option_name ); + + $safe_option_name = $wpdb->escape( $option_name ); + $newvalue = sanitize_option( $option_name, $newvalue ); + + $oldvalue = get_option( $safe_option_name ); + + $newvalue = apply_filters( 'pre_update_option_' . $option_name, $newvalue, $oldvalue ); + + // If the new and old values are the same, no need to update. + if ( $newvalue === $oldvalue ) + return false; + + if ( false === $oldvalue ) { + add_option( $option_name, $newvalue ); + return true; + } + + $notoptions = wp_cache_get( 'notoptions', 'options' ); + if ( is_array( $notoptions ) && isset( $notoptions[$option_name] ) ) { + unset( $notoptions[$option_name] ); + wp_cache_set( 'notoptions', $notoptions, 'options' ); + } + + $_newvalue = $newvalue; + $newvalue = maybe_serialize( $newvalue ); + + $alloptions = wp_load_alloptions(); + if ( isset( $alloptions[$option_name] ) ) { + $alloptions[$option_name] = $newvalue; + wp_cache_set( 'alloptions', $alloptions, 'options' ); + } else { + wp_cache_set( $option_name, $newvalue, 'options' ); + } + + $wpdb->update($wpdb->options, array('option_value' => $newvalue), array('option_name' => $option_name) ); + + if ( $wpdb->rows_affected == 1 ) { + do_action( "update_option_{$option_name}", $oldvalue, $_newvalue ); + return true; + } + return false; +} + +/** + * Add a new option. + * + * You do not need to serialize values, if the value needs to be serialize, then + * it will be serialized before it is inserted into the database. Remember, + * resources can not be serialized or added as an option. + * + * You can create options without values and then add values later. Does not + * check whether the option has already been added, but does check that you + * aren't adding a protected WordPress option. Care should be taken to not name + * options, the same as the ones which are protected and to not add options + * that were already added. + * + * The filter named 'add_option_$optionname', with the $optionname being + * replaced with the option's name, will be called. The hook should accept two + * parameters, the first is the option name, and the second is the value. + * + * @package WordPress + * @subpackage Option + * @since 1.0.0 + * @link http://alex.vort-x.net/blog/ Thanks Alex Stapleton + * + * @param string $name Option name to add. Expects to NOT be SQL escaped. + * @param mixed $value Optional. Option value, can be anything. + * @param mixed $deprecated Optional. Description. Not used anymore. + * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up. + * @return null returns when finished. + */ +function add_option( $name, $value = '', $deprecated = '', $autoload = 'yes' ) { + global $wpdb; + + wp_protect_special_option( $name ); + $safe_name = $wpdb->escape( $name ); + $value = sanitize_option( $name, $value ); + + // Make sure the option doesn't already exist. We can check the 'notoptions' cache before we ask for a db query + $notoptions = wp_cache_get( 'notoptions', 'options' ); + if ( !is_array( $notoptions ) || !isset( $notoptions[$name] ) ) + if ( false !== get_option( $safe_name ) ) + return; + + $value = maybe_serialize( $value ); + $autoload = ( 'no' === $autoload ) ? 'no' : 'yes'; + + if ( 'yes' == $autoload ) { + $alloptions = wp_load_alloptions(); + $alloptions[$name] = $value; + wp_cache_set( 'alloptions', $alloptions, 'options' ); + } else { + wp_cache_set( $name, $value, 'options' ); + } + + // This option exists now + $notoptions = wp_cache_get( 'notoptions', 'options' ); // yes, again... we need it to be fresh + if ( is_array( $notoptions ) && isset( $notoptions[$name] ) ) { + unset( $notoptions[$name] ); + wp_cache_set( 'notoptions', $notoptions, 'options' ); + } + + $wpdb->insert($wpdb->options, array('option_name' => $name, 'option_value' => $value, 'autoload' => $autoload) ); + + do_action( "add_option_{$name}", $name, $value ); + return; +} + +/** + * Removes option by name and prevents removal of protected WordPress options. + * + * @package WordPress + * @subpackage Option + * @since 1.2.0 + * + * @param string $name Option name to remove. + * @return bool True, if succeed. False, if failure. + */ +function delete_option( $name ) { + global $wpdb; + + wp_protect_special_option( $name ); + + // Get the ID, if no ID then return + // expected_slashed ($name) + $option = $wpdb->get_row( "SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'" ); + if ( is_null($option) || !$option->option_id ) + return false; + // expected_slashed ($name) + $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = '$name'" ); + if ( 'yes' == $option->autoload ) { + $alloptions = wp_load_alloptions(); + if ( isset( $alloptions[$name] ) ) { + unset( $alloptions[$name] ); + wp_cache_set( 'alloptions', $alloptions, 'options' ); + } + } else { + wp_cache_delete( $name, 'options' ); + } + return true; +} + +/** + * Delete a transient + * + * @since 2.8.0 + * @package WordPress + * @subpackage Transient + * + * @param string $transient Transient name. Expected to not be SQL-escaped + * @return bool true if successful, false otherwise + */ +function delete_transient($transient) { + global $_wp_using_ext_object_cache, $wpdb; + + if ( $_wp_using_ext_object_cache ) { + return wp_cache_delete($transient, 'transient'); + } else { + $transient = '_transient_' . $wpdb->escape($transient); + return delete_option($transient); + } +} + +/** + * Get the value of a transient + * + * If the transient does not exist or does not have a value, then the return value + * will be false. + * + * @since 2.8.0 + * @package WordPress + * @subpackage Transient + * + * @param string $transient Transient name. Expected to not be SQL-escaped + * @return mixed Value of transient + */ +function get_transient($transient) { + global $_wp_using_ext_object_cache, $wpdb; + + $pre = apply_filters( 'pre_transient_' . $transient, false ); + if ( false !== $pre ) + return $pre; + + if ( $_wp_using_ext_object_cache ) { + $value = wp_cache_get($transient, 'transient'); + } else { + $transient_option = '_transient_' . $wpdb->escape($transient); + // If option is not in alloptions, it is not autoloaded and thus has a timeout + $alloptions = wp_load_alloptions(); + if ( !isset( $alloptions[$transient_option] ) ) { + $transient_timeout = '_transient_timeout_' . $wpdb->escape($transient); + if ( get_option($transient_timeout) < time() ) { + delete_option($transient_option); + delete_option($transient_timeout); + return false; + } + } + + $value = get_option($transient_option); + } + + return apply_filters('transient_' . $transient, $value); +} + +/** + * Set/update the value of a transient + * + * You do not need to serialize values, if the value needs to be serialize, then + * it will be serialized before it is set. + * + * @since 2.8.0 + * @package WordPress + * @subpackage Transient + * + * @param string $transient Transient name. Expected to not be SQL-escaped + * @param mixed $value Transient value. + * @param int $expiration Time until expiration in seconds, default 0 + * @return bool False if value was not set and true if value was set. + */ +function set_transient($transient, $value, $expiration = 0) { + global $_wp_using_ext_object_cache, $wpdb; + + if ( $_wp_using_ext_object_cache ) { + return wp_cache_set($transient, $value, 'transient', $expiration); + } else { + $transient_timeout = '_transient_timeout_' . $transient; + $transient = '_transient_' . $transient; + $safe_transient = $wpdb->escape($transient); + if ( false === get_option( $safe_transient ) ) { + $autoload = 'yes'; + if ( 0 != $expiration ) { + $autoload = 'no'; + add_option($transient_timeout, time() + $expiration, '', 'no'); + } + return add_option($transient, $value, '', $autoload); + } else { + if ( 0 != $expiration ) + update_option($transient_timeout, time() + $expiration); + return update_option($transient, $value); + } + } +} + +/** + * Saves and restores user interface settings stored in a cookie. + * + * Checks if the current user-settings cookie is updated and stores it. When no + * cookie exists (different browser used), adds the last saved cookie restoring + * the settings. + * + * @package WordPress + * @subpackage Option + * @since 2.7.0 + */ +function wp_user_settings() { + + if ( ! is_admin() ) + return; + + if ( defined('DOING_AJAX') ) + return; + + if ( ! $user = wp_get_current_user() ) + return; + + $settings = get_user_option( 'user-settings', $user->ID, false ); + + if ( isset( $_COOKIE['wp-settings-' . $user->ID] ) ) { + $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] ); + + if ( ! empty( $cookie ) && strpos( $cookie, '=' ) ) { + if ( $cookie == $settings ) + return; + + $last_time = (int) get_user_option( 'user-settings-time', $user->ID, false ); + $saved = isset( $_COOKIE['wp-settings-time-' . $user->ID]) ? preg_replace( '/[^0-9]/', '', $_COOKIE['wp-settings-time-' . $user->ID] ) : 0; + + if ( $saved > $last_time ) { + update_user_option( $user->ID, 'user-settings', $cookie, false ); + update_user_option( $user->ID, 'user-settings-time', time() - 5, false ); + return; + } + } + } + + setcookie( 'wp-settings-' . $user->ID, $settings, time() + 31536000, SITECOOKIEPATH ); + setcookie( 'wp-settings-time-' . $user->ID, time(), time() + 31536000, SITECOOKIEPATH ); + $_COOKIE['wp-settings-' . $user->ID] = $settings; +} + +/** + * Retrieve user interface setting value based on setting name. + * + * @package WordPress + * @subpackage Option + * @since 2.7.0 + * + * @param string $name The name of the setting. + * @param string $default Optional default value to return when $name is not set. + * @return mixed the last saved user setting or the default value/false if it doesn't exist. + */ +function get_user_setting( $name, $default = false ) { + + $all = get_all_user_settings(); + + return isset($all[$name]) ? $all[$name] : $default; +} + +/** + * Add or update user interface setting. + * + * Both $name and $value can contain only ASCII letters, numbers and underscores. + * This function has to be used before any output has started as it calls setcookie(). + * + * @package WordPress + * @subpackage Option + * @since 2.8.0 + * + * @param string $name The name of the setting. + * @param string $value The value for the setting. + * @return bool true if set successfully/false if not. + */ +function set_user_setting( $name, $value ) { + + if ( headers_sent() ) + return false; + + $all = get_all_user_settings(); + $name = preg_replace( '/[^A-Za-z0-9_]+/', '', $name ); + + if ( empty($name) ) + return false; + + $all[$name] = $value; + + return wp_set_all_user_settings($all); +} + +/** + * Delete user interface settings. + * + * Deleting settings would reset them to the defaults. + * This function has to be used before any output has started as it calls setcookie(). + * + * @package WordPress + * @subpackage Option + * @since 2.7.0 + * + * @param mixed $names The name or array of names of the setting to be deleted. + * @return bool true if deleted successfully/false if not. + */ +function delete_user_setting( $names ) { + + if ( headers_sent() ) + return false; + + $all = get_all_user_settings(); + $names = (array) $names; + + foreach ( $names as $name ) { + if ( isset($all[$name]) ) { + unset($all[$name]); + $deleted = true; + } + } + + if ( isset($deleted) ) + return wp_set_all_user_settings($all); + + return false; +} + +/** + * Retrieve all user interface settings. + * + * @package WordPress + * @subpackage Option + * @since 2.7.0 + * + * @return array the last saved user settings or empty array. + */ +function get_all_user_settings() { + global $_updated_user_settings; + + if ( ! $user = wp_get_current_user() ) + return array(); + + if ( isset($_updated_user_settings) && is_array($_updated_user_settings) ) + return $_updated_user_settings; + + $all = array(); + if ( isset($_COOKIE['wp-settings-' . $user->ID]) ) { + $cookie = preg_replace( '/[^A-Za-z0-9=&_]/', '', $_COOKIE['wp-settings-' . $user->ID] ); + + if ( $cookie && strpos($cookie, '=') ) // the '=' cannot be 1st char + parse_str($cookie, $all); + + } else { + $option = get_user_option('user-settings', $user->ID); + if ( $option && is_string($option) ) + parse_str( $option, $all ); + } + + return $all; +} + +/** + * Private. Set all user interface settings. + * + * @package WordPress + * @subpackage Option + * @since 2.8.0 + * + */ +function wp_set_all_user_settings($all) { + global $_updated_user_settings; + + if ( ! $user = wp_get_current_user() ) + return false; + + $_updated_user_settings = $all; + $settings = ''; + foreach ( $all as $k => $v ) { + $v = preg_replace( '/[^A-Za-z0-9_]+/', '', $v ); + $settings .= $k . '=' . $v . '&'; + } + + $settings = rtrim($settings, '&'); + + update_user_option( $user->ID, 'user-settings', $settings, false ); + update_user_option( $user->ID, 'user-settings-time', time(), false ); + + return true; +} + +/** + * Delete the user settings of the current user. + * + * @package WordPress + * @subpackage Option + * @since 2.7.0 + */ +function delete_all_user_settings() { + if ( ! $user = wp_get_current_user() ) + return; + + update_user_option( $user->ID, 'user-settings', '', false ); + setcookie('wp-settings-' . $user->ID, ' ', time() - 31536000, SITECOOKIEPATH); +} + +/** + * Serialize data, if needed. + * + * @since 2.0.5 + * + * @param mixed $data Data that might be serialized. + * @return mixed A scalar data + */ +function maybe_serialize( $data ) { + if ( is_array( $data ) || is_object( $data ) ) + return serialize( $data ); + + if ( is_serialized( $data ) ) + return serialize( $data ); + + return $data; +} + +/** + * Strip HTML and put links at the bottom of stripped content. + * + * Searches for all of the links, strips them out of the content, and places + * them at the bottom of the content with numbers. + * + * @since 0.71 + * + * @param string $content Content to get links + * @return string HTML stripped out of content with links at the bottom. + */ +function make_url_footnote( $content ) { + preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches ); + $links_summary = "\n"; + for ( $i=0; $i<count($matches[0]); $i++ ) { + $link_match = $matches[0][$i]; + $link_number = '['.($i+1).']'; + $link_url = $matches[2][$i]; + $link_text = $matches[4][$i]; + $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content ); + $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url; + $links_summary .= "\n" . $link_number . ' ' . $link_url; + } + $content = strip_tags( $content ); + $content .= $links_summary; + return $content; +} + +/** + * Retrieve post title from XMLRPC XML. + * + * If the title element is not part of the XML, then the default post title from + * the $post_default_title will be used instead. + * + * @package WordPress + * @subpackage XMLRPC + * @since 0.71 + * + * @global string $post_default_title Default XMLRPC post title. + * + * @param string $content XMLRPC XML Request content + * @return string Post title + */ +function xmlrpc_getposttitle( $content ) { + global $post_default_title; + if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) { + $post_title = $matchtitle[1]; + } else { + $post_title = $post_default_title; + } + return $post_title; +} + +/** + * Retrieve the post category or categories from XMLRPC XML. + * + * If the category element is not found, then the default post category will be + * used. The return type then would be what $post_default_category. If the + * category is found, then it will always be an array. + * + * @package WordPress + * @subpackage XMLRPC + * @since 0.71 + * + * @global string $post_default_category Default XMLRPC post category. + * + * @param string $content XMLRPC XML Request content + * @return string|array List of categories or category name. + */ +function xmlrpc_getpostcategory( $content ) { + global $post_default_category; + if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) { + $post_category = trim( $matchcat[1], ',' ); + $post_category = explode( ',', $post_category ); + } else { + $post_category = $post_default_category; + } + return $post_category; +} + +/** + * XMLRPC XML content without title and category elements. + * + * @package WordPress + * @subpackage XMLRPC + * @since 0.71 + * + * @param string $content XMLRPC XML Request content + * @return string XMLRPC XML Request content without title and category elements. + */ +function xmlrpc_removepostdata( $content ) { + $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content ); + $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content ); + $content = trim( $content ); + return $content; +} + +/** + * Open the file handle for debugging. + * + * This function is used for XMLRPC feature, but it is general purpose enough + * to be used in anywhere. + * + * @see fopen() for mode options. + * @package WordPress + * @subpackage Debug + * @since 0.71 + * @uses $debug Used for whether debugging is enabled. + * + * @param string $filename File path to debug file. + * @param string $mode Same as fopen() mode parameter. + * @return bool|resource File handle. False on failure. + */ +function debug_fopen( $filename, $mode ) { + global $debug; + if ( 1 == $debug ) { + $fp = fopen( $filename, $mode ); + return $fp; + } else { + return false; + } +} + +/** + * Write contents to the file used for debugging. + * + * Technically, this can be used to write to any file handle when the global + * $debug is set to 1 or true. + * + * @package WordPress + * @subpackage Debug + * @since 0.71 + * @uses $debug Used for whether debugging is enabled. + * + * @param resource $fp File handle for debugging file. + * @param string $string Content to write to debug file. + */ +function debug_fwrite( $fp, $string ) { + global $debug; + if ( 1 == $debug ) + fwrite( $fp, $string ); +} + +/** + * Close the debugging file handle. + * + * Technically, this can be used to close any file handle when the global $debug + * is set to 1 or true. + * + * @package WordPress + * @subpackage Debug + * @since 0.71 + * @uses $debug Used for whether debugging is enabled. + * + * @param resource $fp Debug File handle. + */ +function debug_fclose( $fp ) { + global $debug; + if ( 1 == $debug ) + fclose( $fp ); +} + +/** + * Check content for video and audio links to add as enclosures. + * + * Will not add enclosures that have already been added and will + * remove enclosures that are no longer in the post. This is called as + * pingbacks and trackbacks. + * + * @package WordPress + * @since 1.5.0 + * + * @uses $wpdb + * + * @param string $content Post Content + * @param int $post_ID Post ID + */ +function do_enclose( $content, $post_ID ) { + global $wpdb; + include_once( ABSPATH . WPINC . '/class-IXR.php' ); + + $log = debug_fopen( ABSPATH . 'enclosures.log', 'a' ); + $post_links = array(); + debug_fwrite( $log, 'BEGIN ' . date( 'YmdHis', time() ) . "\n" ); + + $pung = get_enclosed( $post_ID ); + + $ltrs = '\w'; + $gunk = '/#~:.?+=&%@!\-'; + $punc = '.:?\-'; + $any = $ltrs . $gunk . $punc; + + preg_match_all( "{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp ); + + debug_fwrite( $log, 'Post contents:' ); + debug_fwrite( $log, $content . "\n" ); + + foreach ( $pung as $link_test ) { + if ( !in_array( $link_test, $post_links_temp[0] ) ) { // link no longer in post + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $link_test . '%') ); + } + } + + foreach ( (array) $post_links_temp[0] as $link_test ) { + if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already + $test = parse_url( $link_test ); + if ( isset( $test['query'] ) ) + $post_links[] = $link_test; + elseif ( $test['path'] != '/' && $test['path'] != '' ) + $post_links[] = $link_test; + } + } + + foreach ( (array) $post_links as $url ) { + if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE (%s)", $post_ID, $url . '%' ) ) ) { + if ( $headers = wp_get_http_headers( $url) ) { + $len = (int) $headers['content-length']; + $type = $headers['content-type']; + $allowed_types = array( 'video', 'audio' ); + if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) { + $meta_value = "$url\n$len\n$type\n"; + $wpdb->insert($wpdb->postmeta, array('post_id' => $post_ID, 'meta_key' => 'enclosure', 'meta_value' => $meta_value) ); + } + } + } + } +} + +/** + * Perform a HTTP HEAD or GET request. + * + * If $file_path is a writable filename, this will do a GET request and write + * the file to that path. + * + * @since 2.5.0 + * + * @param string $url URL to fetch. + * @param string|bool $file_path Optional. File path to write request to. + * @param bool $deprecated Deprecated. Not used. + * @return bool|string False on failure and string of headers if HEAD request. + */ +function wp_get_http( $url, $file_path = false, $deprecated = false ) { + @set_time_limit( 60 ); + + $options = array(); + $options['redirection'] = 5; + + if ( false == $file_path ) + $options['method'] = 'HEAD'; + else + $options['method'] = 'GET'; + + $response = wp_remote_request($url, $options); + + if ( is_wp_error( $response ) ) + return false; + + $headers = wp_remote_retrieve_headers( $response ); + $headers['response'] = $response['response']['code']; + + if ( false == $file_path ) + return $headers; + + // GET request - write it to the supplied filename + $out_fp = fopen($file_path, 'w'); + if ( !$out_fp ) + return $headers; + + fwrite( $out_fp, $response['body']); + fclose($out_fp); + + return $headers; +} + +/** + * Retrieve HTTP Headers from URL. + * + * @since 1.5.1 + * + * @param string $url + * @param bool $deprecated Not Used. + * @return bool|string False on failure, headers on success. + */ +function wp_get_http_headers( $url, $deprecated = false ) { + $response = wp_remote_head( $url ); + + if ( is_wp_error( $response ) ) + return false; + + return wp_remote_retrieve_headers( $response ); +} + +/** + * Whether today is a new day. + * + * @since 0.71 + * @uses $day Today + * @uses $previousday Previous day + * + * @return int 1 when new day, 0 if not a new day. + */ +function is_new_day() { + global $day, $previousday; + if ( $day != $previousday ) + return 1; + else + return 0; +} + +/** + * Build URL query based on an associative and, or indexed array. + * + * This is a convenient function for easily building url queries. It sets the + * separator to '&' and uses _http_build_query() function. + * + * @see _http_build_query() Used to build the query + * @link http://us2.php.net/manual/en/function.http-build-query.php more on what + * http_build_query() does. + * + * @since 2.3.0 + * + * @param array $data URL-encode key/value pairs. + * @return string URL encoded string + */ +function build_query( $data ) { + return _http_build_query( $data, null, '&', '', false ); +} + +/** + * Retrieve a modified URL query string. + * + * You can rebuild the URL and append a new query variable to the URL query by + * using this function. You can also retrieve the full URL with query data. + * + * Adding a single key & value or an associative array. Setting a key value to + * emptystring removes the key. Omitting oldquery_or_uri uses the $_SERVER + * value. + * + * @since 1.5.0 + * + * @param mixed $param1 Either newkey or an associative_array + * @param mixed $param2 Either newvalue or oldquery or uri + * @param mixed $param3 Optional. Old query or uri + * @return string New URL query string. + */ +function add_query_arg() { + $ret = ''; + if ( is_array( func_get_arg(0) ) ) { + if ( @func_num_args() < 2 || false === @func_get_arg( 1 ) ) + $uri = $_SERVER['REQUEST_URI']; + else + $uri = @func_get_arg( 1 ); + } else { + if ( @func_num_args() < 3 || false === @func_get_arg( 2 ) ) + $uri = $_SERVER['REQUEST_URI']; + else + $uri = @func_get_arg( 2 ); + } + + if ( $frag = strstr( $uri, '#' ) ) + $uri = substr( $uri, 0, -strlen( $frag ) ); + else + $frag = ''; + + if ( preg_match( '|^https?://|i', $uri, $matches ) ) { + $protocol = $matches[0]; + $uri = substr( $uri, strlen( $protocol ) ); + } else { + $protocol = ''; + } + + if ( strpos( $uri, '?' ) !== false ) { + $parts = explode( '?', $uri, 2 ); + if ( 1 == count( $parts ) ) { + $base = '?'; + $query = $parts[0]; + } else { + $base = $parts[0] . '?'; + $query = $parts[1]; + } + } elseif ( !empty( $protocol ) || strpos( $uri, '=' ) === false ) { + $base = $uri . '?'; + $query = ''; + } else { + $base = ''; + $query = $uri; + } + + wp_parse_str( $query, $qs ); + $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string + if ( is_array( func_get_arg( 0 ) ) ) { + $kayvees = func_get_arg( 0 ); + $qs = array_merge( $qs, $kayvees ); + } else { + $qs[func_get_arg( 0 )] = func_get_arg( 1 ); + } + + foreach ( (array) $qs as $k => $v ) { + if ( $v === false ) + unset( $qs[$k] ); + } + + $ret = build_query( $qs ); + $ret = trim( $ret, '?' ); + $ret = preg_replace( '#=(&|$)#', '$1', $ret ); + $ret = $protocol . $base . $ret . $frag; + $ret = rtrim( $ret, '?' ); + return $ret; +} + +/** + * Removes an item or list from the query string. + * + * @since 1.5.0 + * + * @param string|array $key Query key or keys to remove. + * @param bool $query When false uses the $_SERVER value. + * @return string New URL query string. + */ +function remove_query_arg( $key, $query=false ) { + if ( is_array( $key ) ) { // removing multiple keys + foreach ( $key as $k ) + $query = add_query_arg( $k, false, $query ); + return $query; + } + return add_query_arg( $key, false, $query ); +} + +/** + * Walks the array while sanitizing the contents. + * + * @uses $wpdb Used to sanitize values + * @since 0.71 + * + * @param array $array Array to used to walk while sanitizing contents. + * @return array Sanitized $array. + */ +function add_magic_quotes( $array ) { + global $wpdb; + + foreach ( (array) $array as $k => $v ) { + if ( is_array( $v ) ) { + $array[$k] = add_magic_quotes( $v ); + } else { + $array[$k] = $wpdb->escape( $v ); + } + } + return $array; +} + +/** + * HTTP request for URI to retrieve content. + * + * @since 1.5.1 + * @uses wp_remote_get() + * + * @param string $uri URI/URL of web page to retrieve. + * @return bool|string HTTP content. False on failure. + */ +function wp_remote_fopen( $uri ) { + $parsed_url = @parse_url( $uri ); + + if ( !$parsed_url || !is_array( $parsed_url ) ) + return false; + + $options = array(); + $options['timeout'] = 10; + + $response = wp_remote_get( $uri, $options ); + + if ( is_wp_error( $response ) ) + return false; + + return $response['body']; +} + +/** + * Setup the WordPress query. + * + * @since 2.0.0 + * + * @param string $query_vars Default WP_Query arguments. + */ +function wp( $query_vars = '' ) { + global $wp, $wp_query, $wp_the_query; + $wp->main( $query_vars ); + + if( !isset($wp_the_query) ) + $wp_the_query = $wp_query; +} + +/** + * Retrieve the description for the HTTP status. + * + * @since 2.3.0 + * + * @param int $code HTTP status code. + * @return string Empty string if not found, or description if found. + */ +function get_status_header_desc( $code ) { + global $wp_header_to_desc; + + $code = absint( $code ); + + if ( !isset( $wp_header_to_desc ) ) { + $wp_header_to_desc = array( + 100 => 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', + 226 => 'IM Used', + + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Reserved', + 307 => 'Temporary Redirect', + + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 426 => 'Upgrade Required', + + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 510 => 'Not Extended' + ); + } + + if ( isset( $wp_header_to_desc[$code] ) ) + return $wp_header_to_desc[$code]; + else + return ''; +} + +/** + * Set HTTP status header. + * + * @since 2.0.0 + * @uses apply_filters() Calls 'status_header' on status header string, HTTP + * HTTP code, HTTP code description, and protocol string as separate + * parameters. + * + * @param int $header HTTP status code + * @return null Does not return anything. + */ +function status_header( $header ) { + $text = get_status_header_desc( $header ); + + if ( empty( $text ) ) + return false; + + $protocol = $_SERVER["SERVER_PROTOCOL"]; + if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol ) + $protocol = 'HTTP/1.0'; + $status_header = "$protocol $header $text"; + if ( function_exists( 'apply_filters' ) ) + $status_header = apply_filters( 'status_header', $status_header, $header, $text, $protocol ); + + return @header( $status_header, true, $header ); +} + +/** + * Gets the header information to prevent caching. + * + * The several different headers cover the different ways cache prevention is handled + * by different browsers + * + * @since 2.8 + * + * @uses apply_filters() + * @return array The associative array of header names and field values. + */ +function wp_get_nocache_headers() { + $headers = array( + 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT', + 'Last-Modified' => gmdate( 'D, d M Y H:i:s' ) . ' GMT', + 'Cache-Control' => 'no-cache, must-revalidate, max-age=0', + 'Pragma' => 'no-cache', + ); + + if ( function_exists('apply_filters') ) { + $headers = apply_filters('nocache_headers', $headers); + } + return $headers; +} + +/** + * Sets the headers to prevent caching for the different browsers. + * + * Different browsers support different nocache headers, so several headers must + * be sent so that all of them get the point that no caching should occur. + * + * @since 2.0.0 + * @uses wp_get_nocache_headers() + */ +function nocache_headers() { + $headers = wp_get_nocache_headers(); + foreach( (array) $headers as $name => $field_value ) + @header("{$name}: {$field_value}"); +} + +/** + * Set the headers for caching for 10 days with JavaScript content type. + * + * @since 2.1.0 + */ +function cache_javascript_headers() { + $expiresOffset = 864000; // 10 days + header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) ); + header( "Vary: Accept-Encoding" ); // Handle proxies + header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" ); +} + +/** + * Retrieve the number of database queries during the WordPress execution. + * + * @since 2.0.0 + * + * @return int Number of database queries + */ +function get_num_queries() { + global $wpdb; + return $wpdb->num_queries; +} + +/** + * Whether input is yes or no. Must be 'y' to be true. + * + * @since 1.0.0 + * + * @param string $yn Character string containing either 'y' or 'n' + * @return bool True if yes, false on anything else + */ +function bool_from_yn( $yn ) { + return ( strtolower( $yn ) == 'y' ); +} + +/** + * Loads the feed template from the use of an action hook. + * + * If the feed action does not have a hook, then the function will die with a + * message telling the visitor that the feed is not valid. + * + * It is better to only have one hook for each feed. + * + * @since 2.1.0 + * @uses $wp_query Used to tell if the use a comment feed. + * @uses do_action() Calls 'do_feed_$feed' hook, if a hook exists for the feed. + */ +function do_feed() { + global $wp_query; + + $feed = get_query_var( 'feed' ); + + // Remove the pad, if present. + $feed = preg_replace( '/^_+/', '', $feed ); + + if ( $feed == '' || $feed == 'feed' ) + $feed = get_default_feed(); + + $hook = 'do_feed_' . $feed; + if ( !has_action($hook) ) { + $message = sprintf( __( 'ERROR: %s is not a valid feed template' ), esc_html($feed)); + wp_die($message); + } + + do_action( $hook, $wp_query->is_comment_feed ); +} + +/** + * Load the RDF RSS 0.91 Feed template. + * + * @since 2.1.0 + */ +function do_feed_rdf() { + load_template( ABSPATH . WPINC . '/feed-rdf.php' ); +} + +/** + * Load the RSS 1.0 Feed Template + * + * @since 2.1.0 + */ +function do_feed_rss() { + load_template( ABSPATH . WPINC . '/feed-rss.php' ); +} + +/** + * Load either the RSS2 comment feed or the RSS2 posts feed. + * + * @since 2.1.0 + * + * @param bool $for_comments True for the comment feed, false for normal feed. + */ +function do_feed_rss2( $for_comments ) { + if ( $for_comments ) + load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' ); + else + load_template( ABSPATH . WPINC . '/feed-rss2.php' ); +} + +/** + * Load either Atom comment feed or Atom posts feed. + * + * @since 2.1.0 + * + * @param bool $for_comments True for the comment feed, false for normal feed. + */ +function do_feed_atom( $for_comments ) { + if ($for_comments) + load_template( ABSPATH . WPINC . '/feed-atom-comments.php'); + else + load_template( ABSPATH . WPINC . '/feed-atom.php' ); +} + +/** + * Display the robot.txt file content. + * + * The echo content should be with usage of the permalinks or for creating the + * robot.txt file. + * + * @since 2.1.0 + * @uses do_action() Calls 'do_robotstxt' hook for displaying robot.txt rules. + */ +function do_robots() { + header( 'Content-Type: text/plain; charset=utf-8' ); + + do_action( 'do_robotstxt' ); + + if ( '0' == get_option( 'blog_public' ) ) { + echo "User-agent: *\n"; + echo "Disallow: /\n"; + } else { + echo "User-agent: *\n"; + echo "Disallow:\n"; + } +} + +/** + * Test whether blog is already installed. + * + * The cache will be checked first. If you have a cache plugin, which saves the + * cache values, then this will work. If you use the default WordPress cache, + * and the database goes away, then you might have problems. + * + * Checks for the option siteurl for whether WordPress is installed. + * + * @since 2.1.0 + * @uses $wpdb + * + * @return bool Whether blog is already installed. + */ +function is_blog_installed() { + global $wpdb; + + // Check cache first. If options table goes away and we have true cached, oh well. + if ( wp_cache_get( 'is_blog_installed' ) ) + return true; + + $suppress = $wpdb->suppress_errors(); + $alloptions = wp_load_alloptions(); + // If siteurl is not set to autoload, check it specifically + if ( !isset( $alloptions['siteurl'] ) ) + $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" ); + else + $installed = $alloptions['siteurl']; + $wpdb->suppress_errors( $suppress ); + + $installed = !empty( $installed ); + wp_cache_set( 'is_blog_installed', $installed ); + + return $installed; +} + +/** + * Retrieve URL with nonce added to URL query. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @param string $actionurl URL to add nonce action + * @param string $action Optional. Nonce action name + * @return string URL with nonce action added. + */ +function wp_nonce_url( $actionurl, $action = -1 ) { + $actionurl = str_replace( '&', '&', $actionurl ); + return esc_html( add_query_arg( '_wpnonce', wp_create_nonce( $action ), $actionurl ) ); +} + +/** + * Retrieve or display nonce hidden field for forms. + * + * The nonce field is used to validate that the contents of the form came from + * the location on the current site and not somewhere else. The nonce does not + * offer absolute protection, but should protect against most cases. It is very + * important to use nonce field in forms. + * + * If you set $echo to true and set $referer to true, then you will need to + * retrieve the {@link wp_referer_field() wp referer field}. If you have the + * $referer set to true and are echoing the nonce field, it will also echo the + * referer field. + * + * The $action and $name are optional, but if you want to have better security, + * it is strongly suggested to set those two parameters. It is easier to just + * call the function without any parameters, because validation of the nonce + * doesn't require any parameters, but since crackers know what the default is + * it won't be difficult for them to find a way around your nonce and cause + * damage. + * + * The input name will be whatever $name value you gave. The input value will be + * the nonce creation value. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @param string $action Optional. Action name. + * @param string $name Optional. Nonce name. + * @param bool $referer Optional, default true. Whether to set the referer field for validation. + * @param bool $echo Optional, default true. Whether to display or return hidden form field. + * @return string Nonce field. + */ +function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) { + $name = esc_attr( $name ); + $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />'; + if ( $echo ) + echo $nonce_field; + + if ( $referer ) + wp_referer_field( $echo, 'previous' ); + + return $nonce_field; +} + +/** + * Retrieve or display referer hidden field for forms. + * + * The referer link is the current Request URI from the server super global. The + * input name is '_wp_http_referer', in case you wanted to check manually. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @param bool $echo Whether to echo or return the referer field. + * @return string Referer field. + */ +function wp_referer_field( $echo = true) { + $ref = esc_attr( $_SERVER['REQUEST_URI'] ); + $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. $ref . '" />'; + + if ( $echo ) + echo $referer_field; + return $referer_field; +} + +/** + * Retrieve or display original referer hidden field for forms. + * + * The input name is '_wp_original_http_referer' and will be either the same + * value of {@link wp_referer_field()}, if that was posted already or it will + * be the current page, if it doesn't exist. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @param bool $echo Whether to echo the original http referer + * @param string $jump_back_to Optional, default is 'current'. Can be 'previous' or page you want to jump back to. + * @return string Original referer field. + */ +function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) { + $jump_back_to = ( 'previous' == $jump_back_to ) ? wp_get_referer() : $_SERVER['REQUEST_URI']; + $ref = ( wp_get_original_referer() ) ? wp_get_original_referer() : $jump_back_to; + $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( stripslashes( $ref ) ) . '" />'; + if ( $echo ) + echo $orig_referer_field; + return $orig_referer_field; +} + +/** + * Retrieve referer from '_wp_http_referer', HTTP referer, or current page respectively. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @return string|bool False on failure. Referer URL on success. + */ +function wp_get_referer() { + $ref = ''; + if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) + $ref = $_REQUEST['_wp_http_referer']; + else if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) + $ref = $_SERVER['HTTP_REFERER']; + + if ( $ref !== $_SERVER['REQUEST_URI'] ) + return $ref; + return false; +} + +/** + * Retrieve original referer that was posted, if it exists. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @return string|bool False if no original referer or original referer if set. + */ +function wp_get_original_referer() { + if ( !empty( $_REQUEST['_wp_original_http_referer'] ) ) + return $_REQUEST['_wp_original_http_referer']; + return false; +} + +/** + * Recursive directory creation based on full path. + * + * Will attempt to set permissions on folders. + * + * @since 2.0.1 + * + * @param string $target Full path to attempt to create. + * @return bool Whether the path was created or not. True if path already exists. + */ +function wp_mkdir_p( $target ) { + // from php.net/mkdir user contributed notes + $target = str_replace( '//', '/', $target ); + if ( file_exists( $target ) ) + return @is_dir( $target ); + + // Attempting to create the directory may clutter up our display. + if ( @mkdir( $target ) ) { + $stat = @stat( dirname( $target ) ); + $dir_perms = $stat['mode'] & 0007777; // Get the permission bits. + @chmod( $target, $dir_perms ); + return true; + } elseif ( is_dir( dirname( $target ) ) ) { + return false; + } + + // If the above failed, attempt to create the parent node, then try again. + if ( ( $target != '/' ) && ( wp_mkdir_p( dirname( $target ) ) ) ) + return wp_mkdir_p( $target ); + + return false; +} + +/** + * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows'). + * + * @since 2.5.0 + * + * @param string $path File path + * @return bool True if path is absolute, false is not absolute. + */ +function path_is_absolute( $path ) { + // this is definitive if true but fails if $path does not exist or contains a symbolic link + if ( realpath($path) == $path ) + return true; + + if ( strlen($path) == 0 || $path{0} == '.' ) + return false; + + // windows allows absolute paths like this + if ( preg_match('#^[a-zA-Z]:\\\\#', $path) ) + return true; + + // a path starting with / or \ is absolute; anything else is relative + return (bool) preg_match('#^[/\\\\]#', $path); +} + +/** + * Join two filesystem paths together (e.g. 'give me $path relative to $base'). + * + * If the $path is absolute, then it the full path is returned. + * + * @since 2.5.0 + * + * @param string $base + * @param string $path + * @return string The path with the base or absolute path. + */ +function path_join( $base, $path ) { + if ( path_is_absolute($path) ) + return $path; + + return rtrim($base, '/') . '/' . ltrim($path, '/'); +} + +/** + * Get an array containing the current upload directory's path and url. + * + * Checks the 'upload_path' option, which should be from the web root folder, + * and if it isn't empty it will be used. If it is empty, then the path will be + * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will + * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path. + * + * The upload URL path is set either by the 'upload_url_path' option or by using + * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path. + * + * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in + * the administration settings panel), then the time will be used. The format + * will be year first and then month. + * + * If the path couldn't be created, then an error will be returned with the key + * 'error' containing the error message. The error suggests that the parent + * directory is not writable by the server. + * + * On success, the returned array will have many indices: + * 'path' - base directory and sub directory or full path to upload directory. + * 'url' - base url and sub directory or absolute URL to upload directory. + * 'subdir' - sub directory if uploads use year/month folders option is on. + * 'basedir' - path without subdir. + * 'baseurl' - URL path without subdir. + * 'error' - set to false. + * + * @since 2.0.0 + * @uses apply_filters() Calls 'upload_dir' on returned array. + * + * @param string $time Optional. Time formatted in 'yyyy/mm'. + * @return array See above for description. + */ +function wp_upload_dir( $time = null ) { + $siteurl = get_option( 'siteurl' ); + $upload_path = get_option( 'upload_path' ); + $upload_path = trim($upload_path); + if ( empty($upload_path) ) + $dir = WP_CONTENT_DIR . '/uploads'; + else + $dir = $upload_path; + + // $dir is absolute, $path is (maybe) relative to ABSPATH + $dir = path_join( ABSPATH, $dir ); + + if ( !$url = get_option( 'upload_url_path' ) ) { + if ( empty($upload_path) or ( $upload_path == $dir ) ) + $url = WP_CONTENT_URL . '/uploads'; + else + $url = trailingslashit( $siteurl ) . $upload_path; + } + + if ( defined('UPLOADS') ) { + $dir = ABSPATH . UPLOADS; + $url = trailingslashit( $siteurl ) . UPLOADS; + } + + $bdir = $dir; + $burl = $url; + + $subdir = ''; + if ( get_option( 'uploads_use_yearmonth_folders' ) ) { + // Generate the yearly and monthly dirs + if ( !$time ) + $time = current_time( 'mysql' ); + $y = substr( $time, 0, 4 ); + $m = substr( $time, 5, 2 ); + $subdir = "/$y/$m"; + } + + $dir .= $subdir; + $url .= $subdir; + + $uploads = apply_filters( 'upload_dir', array( 'path' => $dir, 'url' => $url, 'subdir' => $subdir, 'basedir' => $bdir, 'baseurl' => $burl, 'error' => false ) ); + + // Make sure we have an uploads dir + if ( ! wp_mkdir_p( $uploads['path'] ) ) { + $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $uploads['path'] ); + return array( 'error' => $message ); + } + + return $uploads; +} + +/** + * Get a filename that is sanitized and unique for the given directory. + * + * If the filename is not unique, then a number will be added to the filename + * before the extension, and will continue adding numbers until the filename is + * unique. + * + * The callback must accept two parameters, the first one is the directory and + * the second is the filename. The callback must be a function. + * + * @since 2.5 + * + * @param string $dir + * @param string $filename + * @param string $unique_filename_callback Function name, must be a function. + * @return string New filename, if given wasn't unique. + */ +function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) { + // sanitize the file name before we begin processing + $filename = sanitize_file_name($filename); + + // separate the filename into a name and extension + $info = pathinfo($filename); + $ext = !empty($info['extension']) ? $info['extension'] : ''; + $name = basename($filename, ".{$ext}"); + + // edge case: if file is named '.ext', treat as an empty name + if( $name === ".$ext" ) + $name = ''; + + // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied. + if ( $unique_filename_callback && function_exists( $unique_filename_callback ) ) { + $filename = $unique_filename_callback( $dir, $name ); + } else { + $number = ''; + + if ( !empty( $ext ) ) + $ext = ".$ext"; + + while ( file_exists( $dir . "/$filename" ) ) { + if ( '' == "$number$ext" ) + $filename = $filename . ++$number . $ext; + else + $filename = str_replace( "$number$ext", ++$number . $ext, $filename ); + } + } + + return $filename; +} + +/** + * Create a file in the upload folder with given content. + * + * If there is an error, then the key 'error' will exist with the error message. + * If success, then the key 'file' will have the unique file path, the 'url' key + * will have the link to the new file. and the 'error' key will be set to false. + * + * This function will not move an uploaded file to the upload folder. It will + * create a new file with the content in $bits parameter. If you move the upload + * file, read the content of the uploaded file, and then you can give the + * filename and content to this function, which will add it to the upload + * folder. + * + * The permissions will be set on the new file automatically by this function. + * + * @since 2.0.0 + * + * @param string $name + * @param null $deprecated Not used. Set to null. + * @param mixed $bits File content + * @param string $time Optional. Time formatted in 'yyyy/mm'. + * @return array + */ +function wp_upload_bits( $name, $deprecated, $bits, $time = null ) { + if ( empty( $name ) ) + return array( 'error' => __( 'Empty filename' ) ); + + $wp_filetype = wp_check_filetype( $name ); + if ( !$wp_filetype['ext'] ) + return array( 'error' => __( 'Invalid file type' ) ); + + $upload = wp_upload_dir( $time ); + + if ( $upload['error'] !== false ) + return $upload; + + $filename = wp_unique_filename( $upload['path'], $name ); + + $new_file = $upload['path'] . "/$filename"; + if ( ! wp_mkdir_p( dirname( $new_file ) ) ) { + $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), dirname( $new_file ) ); + return array( 'error' => $message ); + } + + $ifp = @ fopen( $new_file, 'wb' ); + if ( ! $ifp ) + return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) ); + + @fwrite( $ifp, $bits ); + fclose( $ifp ); + // Set correct file permissions + $stat = @ stat( dirname( $new_file ) ); + $perms = $stat['mode'] & 0007777; + $perms = $perms & 0000666; + @ chmod( $new_file, $perms ); + + // Compute the URL + $url = $upload['url'] . "/$filename"; + + return array( 'file' => $new_file, 'url' => $url, 'error' => false ); +} + +/** + * Retrieve the file type based on the extension name. + * + * @package WordPress + * @since 2.5.0 + * @uses apply_filters() Calls 'ext2type' hook on default supported types. + * + * @param string $ext The extension to search. + * @return string|null The file type, example: audio, video, document, spreadsheet, etc. Null if not found. + */ +function wp_ext2type( $ext ) { + $ext2type = apply_filters('ext2type', array( + 'audio' => array('aac','ac3','aif','aiff','mp1','mp2','mp3','m3a','m4a','m4b','ogg','ram','wav','wma'), + 'video' => array('asf','avi','divx','dv','mov','mpg','mpeg','mp4','mpv','ogm','qt','rm','vob','wmv', 'm4v'), + 'document' => array('doc','docx','pages','odt','rtf','pdf'), + 'spreadsheet' => array('xls','xlsx','numbers','ods'), + 'interactive' => array('ppt','pptx','key','odp','swf'), + 'text' => array('txt'), + 'archive' => array('tar','bz2','gz','cab','dmg','rar','sea','sit','sqx','zip'), + 'code' => array('css','html','php','js'), + )); + foreach ( $ext2type as $type => $exts ) + if ( in_array($ext, $exts) ) + return $type; +} + +/** + * Retrieve the file type from the file name. + * + * You can optionally define the mime array, if needed. + * + * @since 2.0.4 + * + * @param string $filename File name or path. + * @param array $mimes Optional. Key is the file extension with value as the mime type. + * @return array Values with extension first and mime type. + */ +function wp_check_filetype( $filename, $mimes = null ) { + // Accepted MIME types are set here as PCRE unless provided. + $mimes = ( is_array( $mimes ) ) ? $mimes : apply_filters( 'upload_mimes', array( + 'jpg|jpeg|jpe' => 'image/jpeg', + 'gif' => 'image/gif', + 'png' => 'image/png', + 'bmp' => 'image/bmp', + 'tif|tiff' => 'image/tiff', + 'ico' => 'image/x-icon', + 'asf|asx|wax|wmv|wmx' => 'video/asf', + 'avi' => 'video/avi', + 'divx' => 'video/divx', + 'mov|qt' => 'video/quicktime', + 'mpeg|mpg|mpe' => 'video/mpeg', + 'txt|c|cc|h' => 'text/plain', + 'rtx' => 'text/richtext', + 'css' => 'text/css', + 'htm|html' => 'text/html', + 'mp3|m4a' => 'audio/mpeg', + 'mp4|m4v' => 'video/mp4', + 'ra|ram' => 'audio/x-realaudio', + 'wav' => 'audio/wav', + 'ogg' => 'audio/ogg', + 'mid|midi' => 'audio/midi', + 'wma' => 'audio/wma', + 'rtf' => 'application/rtf', + 'js' => 'application/javascript', + 'pdf' => 'application/pdf', + 'doc|docx' => 'application/msword', + 'pot|pps|ppt|pptx' => 'application/vnd.ms-powerpoint', + 'wri' => 'application/vnd.ms-write', + 'xla|xls|xlsx|xlt|xlw' => 'application/vnd.ms-excel', + 'mdb' => 'application/vnd.ms-access', + 'mpp' => 'application/vnd.ms-project', + 'swf' => 'application/x-shockwave-flash', + 'class' => 'application/java', + 'tar' => 'application/x-tar', + 'zip' => 'application/zip', + 'gz|gzip' => 'application/x-gzip', + 'exe' => 'application/x-msdownload', + // openoffice formats + 'odt' => 'application/vnd.oasis.opendocument.text', + 'odp' => 'application/vnd.oasis.opendocument.presentation', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + 'odg' => 'application/vnd.oasis.opendocument.graphics', + 'odc' => 'application/vnd.oasis.opendocument.chart', + 'odb' => 'application/vnd.oasis.opendocument.database', + 'odf' => 'application/vnd.oasis.opendocument.formula', + ) + ); + + $type = false; + $ext = false; + + foreach ( $mimes as $ext_preg => $mime_match ) { + $ext_preg = '!\.(' . $ext_preg . ')$!i'; + if ( preg_match( $ext_preg, $filename, $ext_matches ) ) { + $type = $mime_match; + $ext = $ext_matches[1]; + break; + } + } + + return compact( 'ext', 'type' ); +} + +/** + * Retrieve nonce action "Are you sure" message. + * + * The action is split by verb and noun. The action format is as follows: + * verb-action_extra. The verb is before the first dash and has the format of + * letters and no spaces and numbers. The noun is after the dash and before the + * underscore, if an underscore exists. The noun is also only letters. + * + * The filter will be called for any action, which is not defined by WordPress. + * You may use the filter for your plugin to explain nonce actions to the user, + * when they get the "Are you sure?" message. The filter is in the format of + * 'explain_nonce_$verb-$noun' with the $verb replaced by the found verb and the + * $noun replaced by the found noun. The two parameters that are given to the + * hook are the localized "Are you sure you want to do this?" message with the + * extra text (the text after the underscore). + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @param string $action Nonce action. + * @return string Are you sure message. + */ +function wp_explain_nonce( $action ) { + if ( $action !== -1 && preg_match( '/([a-z]+)-([a-z]+)(_(.+))?/', $action, $matches ) ) { + $verb = $matches[1]; + $noun = $matches[2]; + + $trans = array(); + $trans['update']['attachment'] = array( __( 'Your attempt to edit this attachment: “%s” has failed.' ), 'get_the_title' ); + + $trans['add']['category'] = array( __( 'Your attempt to add this category has failed.' ), false ); + $trans['delete']['category'] = array( __( 'Your attempt to delete this category: “%s” has failed.' ), 'get_cat_name' ); + $trans['update']['category'] = array( __( 'Your attempt to edit this category: “%s” has failed.' ), 'get_cat_name' ); + + $trans['delete']['comment'] = array( __( 'Your attempt to delete this comment: “%s” has failed.' ), 'use_id' ); + $trans['unapprove']['comment'] = array( __( 'Your attempt to unapprove this comment: “%s” has failed.' ), 'use_id' ); + $trans['approve']['comment'] = array( __( 'Your attempt to approve this comment: “%s” has failed.' ), 'use_id' ); + $trans['update']['comment'] = array( __( 'Your attempt to edit this comment: “%s” has failed.' ), 'use_id' ); + $trans['bulk']['comments'] = array( __( 'Your attempt to bulk modify comments has failed.' ), false ); + $trans['moderate']['comments'] = array( __( 'Your attempt to moderate comments has failed.' ), false ); + + $trans['add']['bookmark'] = array( __( 'Your attempt to add this link has failed.' ), false ); + $trans['delete']['bookmark'] = array( __( 'Your attempt to delete this link: “%s” has failed.' ), 'use_id' ); + $trans['update']['bookmark'] = array( __( 'Your attempt to edit this link: “%s” has failed.' ), 'use_id' ); + $trans['bulk']['bookmarks'] = array( __( 'Your attempt to bulk modify links has failed.' ), false ); + + $trans['add']['page'] = array( __( 'Your attempt to add this page has failed.' ), false ); + $trans['delete']['page'] = array( __( 'Your attempt to delete this page: “%s” has failed.' ), 'get_the_title' ); + $trans['update']['page'] = array( __( 'Your attempt to edit this page: “%s” has failed.' ), 'get_the_title' ); + + $trans['edit']['plugin'] = array( __( 'Your attempt to edit this plugin file: “%s” has failed.' ), 'use_id' ); + $trans['activate']['plugin'] = array( __( 'Your attempt to activate this plugin: “%s” has failed.' ), 'use_id' ); + $trans['deactivate']['plugin'] = array( __( 'Your attempt to deactivate this plugin: “%s” has failed.' ), 'use_id' ); + $trans['upgrade']['plugin'] = array( __( 'Your attempt to upgrade this plugin: “%s” has failed.' ), 'use_id' ); + + $trans['add']['post'] = array( __( 'Your attempt to add this post has failed.' ), false ); + $trans['delete']['post'] = array( __( 'Your attempt to delete this post: “%s” has failed.' ), 'get_the_title' ); + $trans['update']['post'] = array( __( 'Your attempt to edit this post: “%s” has failed.' ), 'get_the_title' ); + + $trans['add']['user'] = array( __( 'Your attempt to add this user has failed.' ), false ); + $trans['delete']['users'] = array( __( 'Your attempt to delete users has failed.' ), false ); + $trans['bulk']['users'] = array( __( 'Your attempt to bulk modify users has failed.' ), false ); + $trans['update']['user'] = array( __( 'Your attempt to edit this user: “%s” has failed.' ), 'get_the_author_meta', 'display_name' ); + $trans['update']['profile'] = array( __( 'Your attempt to modify the profile for: “%s” has failed.' ), 'get_the_author_meta', 'display_name' ); + + $trans['update']['options'] = array( __( 'Your attempt to edit your settings has failed.' ), false ); + $trans['update']['permalink'] = array( __( 'Your attempt to change your permalink structure to: %s has failed.' ), 'use_id' ); + $trans['edit']['file'] = array( __( 'Your attempt to edit this file: “%s” has failed.' ), 'use_id' ); + $trans['edit']['theme'] = array( __( 'Your attempt to edit this theme file: “%s” has failed.' ), 'use_id' ); + $trans['switch']['theme'] = array( __( 'Your attempt to switch to this theme: “%s” has failed.' ), 'use_id' ); + + $trans['log']['out'] = array( sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'sitename' ) ), false ); + + if ( isset( $trans[$verb][$noun] ) ) { + if ( !empty( $trans[$verb][$noun][1] ) ) { + $lookup = $trans[$verb][$noun][1]; + if ( isset($trans[$verb][$noun][2]) ) + $lookup_value = $trans[$verb][$noun][2]; + $object = $matches[4]; + if ( 'use_id' != $lookup ) { + if ( isset( $lookup_value ) ) + $object = call_user_func( $lookup, $lookup_value, $object ); + else + $object = call_user_func( $lookup, $object ); + } + return sprintf( $trans[$verb][$noun][0], esc_html($object) ); + } else { + return $trans[$verb][$noun][0]; + } + } + + return apply_filters( 'explain_nonce_' . $verb . '-' . $noun, __( 'Are you sure you want to do this?' ), $matches[4] ); + } else { + return apply_filters( 'explain_nonce_' . $action, __( 'Are you sure you want to do this?' ) ); + } +} + +/** + * Display "Are You Sure" message to confirm the action being taken. + * + * If the action has the nonce explain message, then it will be displayed along + * with the "Are you sure?" message. + * + * @package WordPress + * @subpackage Security + * @since 2.0.4 + * + * @param string $action The nonce action. + */ +function wp_nonce_ays( $action ) { + $title = __( 'WordPress Failure Notice' ); + $html = esc_html( wp_explain_nonce( $action ) ); + if ( wp_get_referer() ) + $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>"; + elseif ( 'log-out' == $action ) + $html .= "</p><p>" . sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url() ); + + wp_die( $html, $title); +} + +/** + * Kill WordPress execution and display HTML message with error message. + * + * Call this function complements the die() PHP function. The difference is that + * HTML will be displayed to the user. It is recommended to use this function + * only, when the execution should not continue any further. It is not + * recommended to call this function very often and try to handle as many errors + * as possible siliently. + * + * @since 2.0.4 + * + * @param string $message Error message. + * @param string $title Error title. + * @param string|array $args Optional arguements to control behaviour. + */ +function wp_die( $message, $title = '', $args = array() ) { + global $wp_locale; + + $defaults = array( 'response' => 500 ); + $r = wp_parse_args($args, $defaults); + + $have_gettext = function_exists('__'); + + if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) { + if ( empty( $title ) ) { + $error_data = $message->get_error_data(); + if ( is_array( $error_data ) && isset( $error_data['title'] ) ) + $title = $error_data['title']; + } + $errors = $message->get_error_messages(); + switch ( count( $errors ) ) : + case 0 : + $message = ''; + break; + case 1 : + $message = "<p>{$errors[0]}</p>"; + break; + default : + $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>"; + break; + endswitch; + } elseif ( is_string( $message ) ) { + $message = "<p>$message</p>"; + } + + if ( isset( $r['back_link'] ) && $r['back_link'] ) { + $back_text = $have_gettext? __('« Back') : '« Back'; + $message .= "\n<p><a href='javascript:history.back()'>$back_text</p>"; + } + + if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL ) + $admin_dir = WP_SITEURL . '/wp-admin/'; + elseif ( function_exists( 'get_bloginfo' ) && '' != get_bloginfo( 'wpurl' ) ) + $admin_dir = get_bloginfo( 'wpurl' ) . '/wp-admin/'; + elseif ( strpos( $_SERVER['PHP_SELF'], 'wp-admin' ) !== false ) + $admin_dir = ''; + else + $admin_dir = 'wp-admin/'; + + if ( !function_exists( 'did_action' ) || !did_action( 'admin_head' ) ) : + if( !headers_sent() ){ + status_header( $r['response'] ); + nocache_headers(); + header( 'Content-Type: text/html; charset=utf-8' ); + } + + if ( empty($title) ) { + $title = $have_gettext? __('WordPress › Error') : 'WordPress › Error'; + } + + $text_direction = 'ltr'; + if ( isset($r['text_direction']) && $r['text_direction'] == 'rtl' ) $text_direction = 'rtl'; + if ( ( $wp_locale ) && ( 'rtl' == $wp_locale->text_direction ) ) $text_direction = 'rtl'; +?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) ) language_attributes(); ?>> +<head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> + <title><?php echo $title ?> + + + + + + + + + + + +text_direction ) { + $input['directionality'] = 'rtl'; + $input['plugins'] .= ',directionality'; + $input['theme_advanced_buttons1'] .= ',ltr'; + } + + return $input; +} + + +/** + * Convert smiley code to the icon graphic file equivalent. + * + * You can turn off smilies, by going to the write setting screen and unchecking + * the box, or by setting 'use_smilies' option to false or removing the option. + * + * Plugins may override the default smiley list by setting the $wpsmiliestrans + * to an array, with the key the code the blogger types in and the value the + * image file. + * + * The $wp_smiliessearch global is for the regular expression and is set each + * time the function is called. + * + * The full list of smilies can be found in the function and won't be listed in + * the description. Probably should create a Codex page for it, so that it is + * available. + * + * @global array $wpsmiliestrans + * @global array $wp_smiliessearch + * @since 2.2.0 + */ +function smilies_init() { + global $wpsmiliestrans, $wp_smiliessearch; + + // don't bother setting up smilies if they are disabled + if ( !get_option( 'use_smilies' ) ) + return; + + if ( !isset( $wpsmiliestrans ) ) { + $wpsmiliestrans = array( + ':mrgreen:' => 'icon_mrgreen.gif', + ':neutral:' => 'icon_neutral.gif', + ':twisted:' => 'icon_twisted.gif', + ':arrow:' => 'icon_arrow.gif', + ':shock:' => 'icon_eek.gif', + ':smile:' => 'icon_smile.gif', + ':???:' => 'icon_confused.gif', + ':cool:' => 'icon_cool.gif', + ':evil:' => 'icon_evil.gif', + ':grin:' => 'icon_biggrin.gif', + ':idea:' => 'icon_idea.gif', + ':oops:' => 'icon_redface.gif', + ':razz:' => 'icon_razz.gif', + ':roll:' => 'icon_rolleyes.gif', + ':wink:' => 'icon_wink.gif', + ':cry:' => 'icon_cry.gif', + ':eek:' => 'icon_surprised.gif', + ':lol:' => 'icon_lol.gif', + ':mad:' => 'icon_mad.gif', + ':sad:' => 'icon_sad.gif', + '8-)' => 'icon_cool.gif', + '8-O' => 'icon_eek.gif', + ':-(' => 'icon_sad.gif', + ':-)' => 'icon_smile.gif', + ':-?' => 'icon_confused.gif', + ':-D' => 'icon_biggrin.gif', + ':-P' => 'icon_razz.gif', + ':-o' => 'icon_surprised.gif', + ':-x' => 'icon_mad.gif', + ':-|' => 'icon_neutral.gif', + ';-)' => 'icon_wink.gif', + '8)' => 'icon_cool.gif', + '8O' => 'icon_eek.gif', + ':(' => 'icon_sad.gif', + ':)' => 'icon_smile.gif', + ':?' => 'icon_confused.gif', + ':D' => 'icon_biggrin.gif', + ':P' => 'icon_razz.gif', + ':o' => 'icon_surprised.gif', + ':x' => 'icon_mad.gif', + ':|' => 'icon_neutral.gif', + ';)' => 'icon_wink.gif', + ':!:' => 'icon_exclaim.gif', + ':?:' => 'icon_question.gif', + ); + } + + if (count($wpsmiliestrans) == 0) { + return; + } + + /* + * NOTE: we sort the smilies in reverse key order. This is to make sure + * we match the longest possible smilie (:???: vs :?) as the regular + * expression used below is first-match + */ + krsort($wpsmiliestrans); + + $wp_smiliessearch = '/(?:\s|^)'; + + $subchar = ''; + foreach ( (array) $wpsmiliestrans as $smiley => $img ) { + $firstchar = substr($smiley, 0, 1); + $rest = substr($smiley, 1); + + // new subpattern? + if ($firstchar != $subchar) { + if ($subchar != '') { + $wp_smiliessearch .= ')|(?:\s|^)'; + } + $subchar = $firstchar; + $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:'; + } else { + $wp_smiliessearch .= '|'; + } + $wp_smiliessearch .= preg_quote($rest, '/'); + } + + $wp_smiliessearch .= ')(?:\s|$)/m'; +} + +/** + * Merge user defined arguments into defaults array. + * + * This function is used throughout WordPress to allow for both string or array + * to be merged into another array. + * + * @since 2.2.0 + * + * @param string|array $args Value to merge with $defaults + * @param array $defaults Array that serves as the defaults. + * @return array Merged user defined values with defaults. + */ +function wp_parse_args( $args, $defaults = '' ) { + if ( is_object( $args ) ) + $r = get_object_vars( $args ); + elseif ( is_array( $args ) ) + $r =& $args; + else + wp_parse_str( $args, $r ); + + if ( is_array( $defaults ) ) + return array_merge( $defaults, $r ); + return $r; +} + +/** + * Determines if Widgets library should be loaded. + * + * Checks to make sure that the widgets library hasn't already been loaded. If + * it hasn't, then it will load the widgets library and run an action hook. + * + * @since 2.2.0 + * @uses add_action() Calls '_admin_menu' hook with 'wp_widgets_add_menu' value. + */ +function wp_maybe_load_widgets() { + if ( ! apply_filters('load_default_widgets', true) ) + return; + require_once( ABSPATH . WPINC . '/default-widgets.php' ); + add_action( '_admin_menu', 'wp_widgets_add_menu' ); +} + +/** + * Append the Widgets menu to the themes main menu. + * + * @since 2.2.0 + * @uses $submenu The administration submenu list. + */ +function wp_widgets_add_menu() { + global $submenu; + $submenu['themes.php'][7] = array( __( 'Widgets' ), 'switch_themes', 'widgets.php' ); + ksort( $submenu['themes.php'], SORT_NUMERIC ); +} + +/** + * Flush all output buffers for PHP 5.2. + * + * Make sure all output buffers are flushed before our singletons our destroyed. + * + * @since 2.2.0 + */ +function wp_ob_end_flush_all() { + $levels = ob_get_level(); + for ($i=0; $i<$levels; $i++) + ob_end_flush(); +} + +/** + * Load the correct database class file. + * + * This function is used to load the database class file either at runtime or by + * wp-admin/setup-config.php We must globalise $wpdb to ensure that it is + * defined globally by the inline code in wp-db.php. + * + * @since 2.5.0 + * @global $wpdb WordPress Database Object + */ +function require_wp_db() { + global $wpdb; + if ( file_exists( WP_CONTENT_DIR . '/db.php' ) ) + require_once( WP_CONTENT_DIR . '/db.php' ); + else + require_once( ABSPATH . WPINC . '/wp-db.php' ); +} + +/** + * Load custom DB error or display WordPress DB error. + * + * If a file exists in the wp-content directory named db-error.php, then it will + * be loaded instead of displaying the WordPress DB error. If it is not found, + * then the WordPress DB error will be displayed instead. + * + * The WordPress DB error sets the HTTP status header to 500 to try to prevent + * search engines from caching the message. Custom DB messages should do the + * same. + * + * This function was backported to the the WordPress 2.3.2, but originally was + * added in WordPress 2.5.0. + * + * @since 2.3.2 + * @uses $wpdb + */ +function dead_db() { + global $wpdb; + + // Load custom DB error template, if present. + if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) { + require_once( WP_CONTENT_DIR . '/db-error.php' ); + die(); + } + + // If installing or in the admin, provide the verbose message. + if ( defined('WP_INSTALLING') || defined('WP_ADMIN') ) + wp_die($wpdb->error); + + // Otherwise, be terse. + status_header( 500 ); + nocache_headers(); + header( 'Content-Type: text/html; charset=utf-8' ); +?> + +> + + + Database Error + + + +

    Error establishing a database connection

    + + +deprecated since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) ); + else + trigger_error( sprintf( __('%1$s is deprecated since version %2$s with no alternative available.'), $function, $version ) ); + } +} + +/** + * Marks a file as deprecated and informs when it has been used. + * + * There is a hook deprecated_file_included that will be called that can be used + * to get the backtrace up to what file and function included the deprecated + * file. + * + * The current behavior is to trigger an user error if WP_DEBUG is defined and + * is true. + * + * This function is to be used in every file that is depreceated + * + * @package WordPress + * @package Debug + * @since 2.5.0 + * @access private + * + * @uses do_action() Calls 'deprecated_file_included' and passes the file name and what to use instead. + * @uses apply_filters() Calls 'deprecated_file_trigger_error' and expects boolean value of true to do trigger or false to not trigger error. + * + * @param string $file The file that was included + * @param string $version The version of WordPress that deprecated the function + * @param string $replacement Optional. The function that should have been called + */ +function _deprecated_file($file, $version, $replacement=null) { + + do_action('deprecated_file_included', $file, $replacement); + + // Allow plugin to filter the output error trigger + if( defined('WP_DEBUG') && ( true === WP_DEBUG ) && apply_filters( 'deprecated_file_trigger_error', true )) { + if( !is_null($replacement) ) + trigger_error( sprintf( __('%1$s is deprecated since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) ); + else + trigger_error( sprintf( __('%1$s is deprecated since version %2$s with no alternative available.'), $file, $version ) ); + } +} + +/** + * Is the server running earlier than 1.5.0 version of lighttpd + * + * @since 2.5.0 + * + * @return bool Whether the server is running lighttpd < 1.5.0 + */ +function is_lighttpd_before_150() { + $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' ); + $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : ''; + return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' ); +} + +/** + * Does the specified module exist in the apache config? + * + * @since 2.5.0 + * + * @param string $mod e.g. mod_rewrite + * @param bool $default The default return value if the module is not found + * @return bool + */ +function apache_mod_loaded($mod, $default = false) { + global $is_apache; + + if ( !$is_apache ) + return false; + + if ( function_exists('apache_get_modules') ) { + $mods = apache_get_modules(); + if ( in_array($mod, $mods) ) + return true; + } elseif ( function_exists('phpinfo') ) { + ob_start(); + phpinfo(8); + $phpinfo = ob_get_clean(); + if ( false !== strpos($phpinfo, $mod) ) + return true; + } + return $default; +} + +/** + * File validates against allowed set of defined rules. + * + * A return value of '1' means that the $file contains either '..' or './'. A + * return value of '2' means that the $file contains ':' after the first + * character. A return value of '3' means that the file is not in the allowed + * files list. + * + * @since 1.2.0 + * + * @param string $file File path. + * @param array $allowed_files List of allowed files. + * @return int 0 means nothing is wrong, greater than 0 means something was wrong. + */ +function validate_file( $file, $allowed_files = '' ) { + if ( false !== strpos( $file, '..' )) + return 1; + + if ( false !== strpos( $file, './' )) + return 1; + + if (':' == substr( $file, 1, 1 )) + return 2; + + if (!empty ( $allowed_files ) && (!in_array( $file, $allowed_files ) ) ) + return 3; + + return 0; +} + +/** + * Determine if SSL is used. + * + * @since 2.6.0 + * + * @return bool True if SSL, false if not used. + */ +function is_ssl() { + if ( isset($_SERVER['HTTPS']) ) { + if ( 'on' == strtolower($_SERVER['HTTPS']) ) + return true; + if ( '1' == $_SERVER['HTTPS'] ) + return true; + } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) { + return true; + } + return false; +} + +/** + * Whether SSL login should be forced. + * + * @since 2.6.0 + * + * @param string|bool $force Optional. + * @return bool True if forced, false if not forced. + */ +function force_ssl_login($force = '') { + static $forced; + + if ( '' != $force ) { + $old_forced = $forced; + $forced = $force; + return $old_forced; + } + + return $forced; +} + +/** + * Whether to force SSL used for the Administration Panels. + * + * @since 2.6.0 + * + * @param string|bool $force + * @return bool True if forced, false if not forced. + */ +function force_ssl_admin($force = '') { + static $forced; + + if ( '' != $force ) { + $old_forced = $forced; + $forced = $force; + return $old_forced; + } + + return $forced; +} + +/** + * Guess the URL for the site. + * + * Will remove wp-admin links to retrieve only return URLs not in the wp-admin + * directory. + * + * @since 2.6.0 + * + * @return string + */ +function wp_guess_url() { + if ( defined('WP_SITEURL') && '' != WP_SITEURL ) { + $url = WP_SITEURL; + } else { + $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://'; + $url = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); + } + return $url; +} + +/** + * Suspend cache invalidation. + * + * Turns cache invalidation on and off. Useful during imports where you don't wont to do invalidations + * every time a post is inserted. Callers must be sure that what they are doing won't lead to an inconsistent + * cache when invalidation is suspended. + * + * @since 2.7.0 + * + * @param bool $suspend Whether to suspend or enable cache invalidation + * @return bool The current suspend setting + */ +function wp_suspend_cache_invalidation($suspend = true) { + global $_wp_suspend_cache_invalidation; + + $current_suspend = $_wp_suspend_cache_invalidation; + $_wp_suspend_cache_invalidation = $suspend; + return $current_suspend; +} + +function get_site_option( $key, $default = false, $use_cache = true ) { + return get_option($key, $default); +} + +// expects $key, $value not to be SQL escaped +function add_site_option( $key, $value ) { + return add_option($key, $value); +} + +// expects $key, $value not to be SQL escaped +function update_site_option( $key, $value ) { + return update_option($key, $value); +} + +/** + * gmt_offset modification for smart timezone handling + * + * Overrides the gmt_offset option if we have a timezone_string available + */ +function wp_timezone_override_offset() { + if ( !wp_timezone_supported() ) { + return false; + } + if ( !$timezone_string = get_option( 'timezone_string' ) ) { + return false; + } + + @date_default_timezone_set( $timezone_string ); + $timezone_object = timezone_open( $timezone_string ); + $datetime_object = date_create(); + if ( false === $timezone_object || false === $datetime_object ) { + return false; + } + return round( timezone_offset_get( $timezone_object, $datetime_object ) / 3600, 2 ); +} + +/** + * Check for PHP timezone support + */ +function wp_timezone_supported() { + $support = false; + if ( + function_exists( 'date_default_timezone_set' ) && + function_exists( 'timezone_identifiers_list' ) && + function_exists( 'timezone_open' ) && + function_exists( 'timezone_offset_get' ) + ) { + $support = true; + } + return apply_filters( 'timezone_support', $support ); +} + +function _wp_timezone_choice_usort_callback( $a, $b ) { + // Don't use translated versions of Etc + if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) { + // Make the order of these more like the old dropdown + if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) { + return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) ); + } + if ( 'UTC' === $a['city'] ) { + if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) { + return 1; + } + return -1; + } + if ( 'UTC' === $b['city'] ) { + if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) { + return -1; + } + return 1; + } + return strnatcasecmp( $a['city'], $b['city'] ); + } + if ( $a['t_continent'] == $b['t_continent'] ) { + if ( $a['t_city'] == $b['t_city'] ) { + return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] ); + } + return strnatcasecmp( $a['t_city'], $b['t_city'] ); + } else { + // Force Etc to the bottom of the list + if ( 'Etc' === $a['continent'] ) { + return 1; + } + if ( 'Etc' === $b['continent'] ) { + return -1; + } + return strnatcasecmp( $a['t_continent'], $b['t_continent'] ); + } +} + +/** + * Gives a nicely formatted list of timezone strings // temporary! Not in final + * + * @param $selected_zone string Selected Zone + * + */ +function wp_timezone_choice( $selected_zone ) { + static $mo_loaded = false; + + $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific', 'Etc' ); + + // Load translations for continents and cities + if ( !$mo_loaded ) { + $locale = get_locale(); + $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo'; + load_textdomain( 'continents-cities', $mofile ); + $mo_loaded = true; + } + + $zonen = array(); + foreach ( timezone_identifiers_list() as $zone ) { + $zone = explode( '/', $zone ); + if ( !in_array( $zone[0], $continents ) ) { + continue; + } + if ( 'Etc' === $zone[0] && in_array( $zone[1], array( 'UCT', 'GMT', 'GMT0', 'GMT+0', 'GMT-0', 'Greenwich', 'Universal', 'Zulu' ) ) ) { + continue; + } + + // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later + $exists = array( + 0 => ( isset( $zone[0] ) && $zone[0] ) ? true : false, + 1 => ( isset( $zone[1] ) && $zone[1] ) ? true : false, + 2 => ( isset( $zone[2] ) && $zone[2] ) ? true : false + ); + $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] ) ? true : false; + $exists[4] = ( $exists[1] && $exists[3] ) ? true : false; + $exists[5] = ( $exists[2] && $exists[3] ) ? true : false; + + $zonen[] = array( + 'continent' => ( $exists[0] ? $zone[0] : '' ), + 'city' => ( $exists[1] ? $zone[1] : '' ), + 'subcity' => ( $exists[2] ? $zone[2] : '' ), + 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ), + 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ), + 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' ) + ); + } + usort( $zonen, '_wp_timezone_choice_usort_callback' ); + + $structure = array(); + + if ( empty( $selected_zone ) ) { + $structure[] = ''; + } + + foreach ( $zonen as $key => $zone ) { + // Build value in an array to join later + $value = array( $zone['continent'] ); + + if ( empty( $zone['city'] ) ) { + // It's at the continent level (generally won't happen) + $display = $zone['t_continent']; + } else { + // It's inside a continent group + + // Continent optgroup + if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) { + $label = ( 'Etc' === $zone['continent'] ) ? __( 'Manual offsets' ) : $zone['t_continent']; + $structure[] = ''; + } + + // Add the city to the value + $value[] = $zone['city']; + if ( 'Etc' === $zone['continent'] ) { + if ( 'UTC' === $zone['city'] ) { + $display = ''; + } else { + $display = str_replace( 'GMT', '', $zone['city'] ); + $display = strtr( $display, '+-', '-+' ) . ':00'; + } + $display = sprintf( __( 'UTC %s' ), $display ); + } else { + $display = $zone['t_city']; + if ( !empty( $zone['subcity'] ) ) { + // Add the subcity to the value + $value[] = $zone['subcity']; + $display .= ' - ' . $zone['t_subcity']; + } + } + } + + // Build the value + $value = join( '/', $value ); + $selected = ''; + if ( $value === $selected_zone ) { + $selected = 'selected="selected" '; + } + $structure[] = '"; + + // Close continent optgroup + if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) { + $structure[] = ''; + } + } + + return join( "\n", $structure ); +} + + + +/** + * Strip close comment and close php tags from file headers used by WP + * See http://core.trac.wordpress.org/ticket/8497 + * + * @since 2.8 +**/ +function _cleanup_header_comment($str) { + return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str)); +} +?> diff --git a/wp-includes/functions.wp-scripts.php b/wp-includes/functions.wp-scripts.php new file mode 100644 index 0000000..0a60c96 --- /dev/null +++ b/wp-includes/functions.wp-scripts.php @@ -0,0 +1,128 @@ +do_items( $handles ); +} + +/** + * Register new JavaScript file. + * + * @since r16 + * @see WP_Dependencies::add() For parameter information. + */ +function wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false ) { + global $wp_scripts; + if ( !is_a($wp_scripts, 'WP_Scripts') ) + $wp_scripts = new WP_Scripts(); + + $wp_scripts->add( $handle, $src, $deps, $ver ); + if ( $in_footer ) + $wp_scripts->add_data( $handle, 'group', 1 ); +} + +/** + * Localizes a script. + * + * Localizes only if script has already been added. + * + * @since r16 + * @see WP_Script::localize() + */ +function wp_localize_script( $handle, $object_name, $l10n ) { + global $wp_scripts; + if ( !is_a($wp_scripts, 'WP_Scripts') ) + return false; + + return $wp_scripts->localize( $handle, $object_name, $l10n ); +} + +/** + * Remove a registered script. + * + * @since r16 + * @see WP_Scripts::remove() For parameter information. + */ +function wp_deregister_script( $handle ) { + global $wp_scripts; + if ( !is_a($wp_scripts, 'WP_Scripts') ) + $wp_scripts = new WP_Scripts(); + + $wp_scripts->remove( $handle ); +} + +/** + * Enqueues script. + * + * Registers the script if src provided (does NOT overwrite) and enqueues. + * + * @since r16 + * @see WP_Script::add(), WP_Script::enqueue() +*/ +function wp_enqueue_script( $handle, $src = false, $deps = array(), $ver = false, $in_footer = false ) { + global $wp_scripts; + if ( !is_a($wp_scripts, 'WP_Scripts') ) + $wp_scripts = new WP_Scripts(); + + if ( $src ) { + $_handle = explode('?', $handle); + $wp_scripts->add( $_handle[0], $src, $deps, $ver ); + if ( $in_footer ) + $wp_scripts->add_data( $_handle[0], 'group', 1 ); + } + $wp_scripts->enqueue( $handle ); +} + +/** + * Check whether script has been added to WordPress Scripts. + * + * The values for list defaults to 'queue', which is the same as enqueue for + * scripts. + * + * @since WP unknown; BP unknown + * + * @param string $handle Handle used to add script. + * @param string $list Optional, defaults to 'queue'. Others values are 'registered', 'queue', 'done', 'to_do' + * @return bool + */ +function wp_script_is( $handle, $list = 'queue' ) { + global $wp_scripts; + if ( !is_a($wp_scripts, 'WP_Scripts') ) + $wp_scripts = new WP_Scripts(); + + $query = $wp_scripts->query( $handle, $list ); + + if ( is_object( $query ) ) + return true; + + return $query; +} diff --git a/wp-includes/functions.wp-styles.php b/wp-includes/functions.wp-styles.php new file mode 100644 index 0000000..5251bda --- /dev/null +++ b/wp-includes/functions.wp-styles.php @@ -0,0 +1,104 @@ +do_items( $handles ); +} + +/** + * Register CSS style file. + * + * @since r79 + * @see WP_Styles::add() For parameter and additional information. + */ +function wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) { + global $wp_styles; + if ( !is_a($wp_styles, 'WP_Styles') ) + $wp_styles = new WP_Styles(); + + $wp_styles->add( $handle, $src, $deps, $ver, $media ); +} + +/** + * Remove a registered CSS file. + * + * @since r79 + * @see WP_Styles::remove() For parameter and additional information. + */ +function wp_deregister_style( $handle ) { + global $wp_styles; + if ( !is_a($wp_styles, 'WP_Styles') ) + $wp_styles = new WP_Styles(); + + $wp_styles->remove( $handle ); +} + +/** + * Enqueue a CSS style file. + * + * @since r79 + * @see WP_Styles::add(), WP_Styles::enqueue() + */ +function wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = false ) { + global $wp_styles; + if ( !is_a($wp_styles, 'WP_Styles') ) + $wp_styles = new WP_Styles(); + + if ( $src ) { + $_handle = explode('?', $handle); + $wp_styles->add( $_handle[0], $src, $deps, $ver, $media ); + } + $wp_styles->enqueue( $handle ); +} + +/** + * Check whether style has been added to WordPress Styles. + * + * The values for list defaults to 'queue', which is the same as enqueue for + * styles. + * + * @since WP unknown; BP unknown + * + * @param string $handle Handle used to add style. + * @param string $list Optional, defaults to 'queue'. Others values are 'registered', 'queue', 'done', 'to_do' + * @return bool + */ +function wp_style_is( $handle, $list = 'queue' ) { + global $wp_styles; + if ( !is_a($wp_styles, 'WP_Styles') ) + $wp_styles = new WP_Styles(); + + $query = $wp_styles->query( $handle, $list ); + + if ( is_object( $query ) ) + return true; + + return $query; +} diff --git a/wp-includes/general-template.php b/wp-includes/general-template.php new file mode 100644 index 0000000..68c73ce --- /dev/null +++ b/wp-includes/general-template.php @@ -0,0 +1,2048 @@ + +
    + + +
    + '; + + echo apply_filters('get_search_form', $form); +} + +/** + * Display the Log In/Out link. + * + * Displays a link, which allows the user to navigate to the Log In page to log in + * or log out depending on whether or not they are currently logged in. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'loginout' hook on HTML link content. + * + * @param string $redirect Optional path to redirect to on login/logout. + */ +function wp_loginout($redirect = '') { + if ( ! is_user_logged_in() ) + $link = '' . __('Log in') . ''; + else + $link = '' . __('Log out') . ''; + + echo apply_filters('loginout', $link); +} + +/** + * Returns the Log Out URL. + * + * Returns the URL that allows the user to log out of the site + * + * @since 2.7 + * @uses wp_nonce_url() To protect against CSRF + * @uses site_url() To generate the log in URL + * @uses apply_filters() calls 'logout_url' hook on final logout url + * + * @param string $redirect Path to redirect to on logout. + */ +function wp_logout_url($redirect = '') { + $args = array( 'action' => 'logout' ); + if ( !empty($redirect) ) { + $args['redirect_to'] = $redirect; + } + + $logout_url = add_query_arg($args, site_url('wp-login.php', 'login')); + $logout_url = wp_nonce_url( $logout_url, 'log-out' ); + + return apply_filters('logout_url', $logout_url, $redirect); +} + +/** + * Returns the Log In URL. + * + * Returns the URL that allows the user to log in to the site + * + * @since 2.7 + * @uses site_url() To generate the log in URL + * @uses apply_filters() calls 'login_url' hook on final login url + * + * @param string $redirect Path to redirect to on login. + */ +function wp_login_url($redirect = '') { + $login_url = site_url('wp-login.php', 'login'); + + if ( !empty($redirect) ) { + $login_url = add_query_arg('redirect_to', urlencode($redirect), $login_url); + } + + return apply_filters('login_url', $login_url, $redirect); +} + +/** + * Returns the Lost Password URL. + * + * Returns the URL that allows the user to retrieve the lost password + * + * @since 2.8.0 + * @uses site_url() To generate the lost password URL + * @uses apply_filters() calls 'lostpassword_url' hook on the lostpassword url + * + * @param string $redirect Path to redirect to on login. + */ +function wp_lostpassword_url($redirect = '') { + $args = array( 'action' => 'lostpassword' ); + if ( !empty($redirect) ) { + $args['redirect_to'] = $redirect; + } + + $lostpassword_url = add_query_arg($args, site_url('wp-login.php', 'login')); + return apply_filters('lostpassword_url', $lostpassword_url, $redirect); +} + +/** + * Display the Registration or Admin link. + * + * Display a link which allows the user to navigate to the registration page if + * not logged in and registration is enabled or to the dashboard if logged in. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'register' hook on register / admin link content. + * + * @param string $before Text to output before the link (defaults to
  • ). + * @param string $after Text to output after the link (defaults to
  • ). + */ +function wp_register( $before = '
  • ', $after = '
  • ' ) { + + if ( ! is_user_logged_in() ) { + if ( get_option('users_can_register') ) + $link = $before . '' . __('Register') . '' . $after; + else + $link = ''; + } else { + $link = $before . '' . __('Site Admin') . '' . $after; + } + + echo apply_filters('register', $link); +} + +/** + * Theme container function for the 'wp_meta' action. + * + * The 'wp_meta' action can have several purposes, depending on how you use it, + * but one purpose might have been to allow for theme switching. + * + * @since 1.5.0 + * @link http://trac.wordpress.org/ticket/1458 Explanation of 'wp_meta' action. + * @uses do_action() Calls 'wp_meta' hook. + */ +function wp_meta() { + do_action('wp_meta'); +} + +/** + * Display information about the blog. + * + * @see get_bloginfo() For possible values for the parameter. + * @since 0.71 + * + * @param string $show What to display. + */ +function bloginfo($show='') { + echo get_bloginfo($show, 'display'); +} + +/** + * Retrieve information about the blog. + * + * Some show parameter values are deprecated and will be removed in future + * versions. Care should be taken to check the function contents and know what + * the deprecated blog info options are. Options without "// DEPRECATED" are + * the preferred and recommended ways to get the information. + * + * The possible values for the 'show' parameter are listed below. + *
      + *
    1. url - Blog URI to homepage.
    2. + *
    3. wpurl - Blog URI path to WordPress.
    4. + *
    5. description - Secondary title
    6. + *
    + * + * The feed URL options can be retrieved from 'rdf_url' (RSS 0.91), + * 'rss_url' (RSS 1.0), 'rss2_url' (RSS 2.0), or 'atom_url' (Atom feed). The + * comment feeds can be retrieved from the 'comments_atom_url' (Atom comment + * feed) or 'comments_rss2_url' (RSS 2.0 comment feed). + * + * There are many other options and you should check the function contents: + * {@source 32 37} + * + * @since 0.71 + * + * @param string $show Blog info to retrieve. + * @param string $filter How to filter what is retrieved. + * @return string Mostly string values, might be empty. + */ +function get_bloginfo($show = '', $filter = 'raw') { + + switch($show) { + case 'url' : + case 'home' : // DEPRECATED + case 'siteurl' : // DEPRECATED + $output = get_option('home'); + break; + case 'wpurl' : + $output = get_option('siteurl'); + break; + case 'description': + $output = get_option('blogdescription'); + break; + case 'rdf_url': + $output = get_feed_link('rdf'); + break; + case 'rss_url': + $output = get_feed_link('rss'); + break; + case 'rss2_url': + $output = get_feed_link('rss2'); + break; + case 'atom_url': + $output = get_feed_link('atom'); + break; + case 'comments_atom_url': + $output = get_feed_link('comments_atom'); + break; + case 'comments_rss2_url': + $output = get_feed_link('comments_rss2'); + break; + case 'pingback_url': + $output = get_option('siteurl') .'/xmlrpc.php'; + break; + case 'stylesheet_url': + $output = get_stylesheet_uri(); + break; + case 'stylesheet_directory': + $output = get_stylesheet_directory_uri(); + break; + case 'template_directory': + case 'template_url': + $output = get_template_directory_uri(); + break; + case 'admin_email': + $output = get_option('admin_email'); + break; + case 'charset': + $output = get_option('blog_charset'); + if ('' == $output) $output = 'UTF-8'; + break; + case 'html_type' : + $output = get_option('html_type'); + break; + case 'version': + global $wp_version; + $output = $wp_version; + break; + case 'language': + $output = get_locale(); + $output = str_replace('_', '-', $output); + break; + case 'text_direction': + global $wp_locale; + $output = $wp_locale->text_direction; + break; + case 'name': + default: + $output = get_option('blogname'); + break; + } + + $url = true; + if (strpos($show, 'url') === false && + strpos($show, 'directory') === false && + strpos($show, 'home') === false) + $url = false; + + if ( 'display' == $filter ) { + if ( $url ) + $output = apply_filters('bloginfo_url', $output, $show); + else + $output = apply_filters('bloginfo', $output, $show); + } + + return $output; +} + +/** + * Display or retrieve page title for all areas of blog. + * + * By default, the page title will display the separator before the page title, + * so that the blog title will be before the page title. This is not good for + * title display, since the blog title shows up on most tabs and not what is + * important, which is the page that the user is looking at. + * + * There are also SEO benefits to having the blog title after or to the 'right' + * or the page title. However, it is mostly common sense to have the blog title + * to the right with most browsers supporting tabs. You can achieve this by + * using the seplocation parameter and setting the value to 'right'. This change + * was introduced around 2.5.0, in case backwards compatibility of themes is + * important. + * + * @since 1.0.0 + * + * @param string $sep Optional, default is '»'. How to separate the various items within the page title. + * @param bool $display Optional, default is true. Whether to display or retrieve title. + * @param string $seplocation Optional. Direction to display title, 'right'. + * @return string|null String on retrieve, null when displaying. + */ +function wp_title($sep = '»', $display = true, $seplocation = '') { + global $wpdb, $wp_locale, $wp_query; + + $cat = get_query_var('cat'); + $tag = get_query_var('tag_id'); + $category_name = get_query_var('category_name'); + $author = get_query_var('author'); + $author_name = get_query_var('author_name'); + $m = get_query_var('m'); + $year = get_query_var('year'); + $monthnum = get_query_var('monthnum'); + $day = get_query_var('day'); + $search = get_query_var('s'); + $title = ''; + + $t_sep = '%WP_TITILE_SEP%'; // Temporary separator, for accurate flipping, if necessary + + // If there's a category + if ( !empty($cat) ) { + // category exclusion + if ( !stristr($cat,'-') ) + $title = apply_filters('single_cat_title', get_the_category_by_ID($cat)); + } elseif ( !empty($category_name) ) { + if ( stristr($category_name,'/') ) { + $category_name = explode('/',$category_name); + if ( $category_name[count($category_name)-1] ) + $category_name = $category_name[count($category_name)-1]; // no trailing slash + else + $category_name = $category_name[count($category_name)-2]; // there was a trailling slash + } + $cat = get_term_by('slug', $category_name, 'category', OBJECT, 'display'); + if ( $cat ) + $title = apply_filters('single_cat_title', $cat->name); + } + + if ( !empty($tag) ) { + $tag = get_term($tag, 'post_tag', OBJECT, 'display'); + if ( is_wp_error( $tag ) ) + return $tag; + if ( ! empty($tag->name) ) + $title = apply_filters('single_tag_title', $tag->name); + } + + // If there's an author + if ( !empty($author) ) { + $title = get_userdata($author); + $title = $title->display_name; + } + if ( !empty($author_name) ) { + // We do a direct query here because we don't cache by nicename. + $title = $wpdb->get_var($wpdb->prepare("SELECT display_name FROM $wpdb->users WHERE user_nicename = %s", $author_name)); + } + + // If there's a month + if ( !empty($m) ) { + $my_year = substr($m, 0, 4); + $my_month = $wp_locale->get_month(substr($m, 4, 2)); + $my_day = intval(substr($m, 6, 2)); + $title = "$my_year" . ($my_month ? "$t_sep$my_month" : "") . ($my_day ? "$t_sep$my_day" : ""); + } + + if ( !empty($year) ) { + $title = $year; + if ( !empty($monthnum) ) + $title .= "$t_sep" . $wp_locale->get_month($monthnum); + if ( !empty($day) ) + $title .= "$t_sep" . zeroise($day, 2); + } + + // If there is a post + if ( is_single() || ( is_home() && !is_front_page() ) || ( is_page() && !is_front_page() ) ) { + $post = $wp_query->get_queried_object(); + $title = strip_tags( apply_filters( 'single_post_title', $post->post_title ) ); + } + + // If there's a taxonomy + if ( is_tax() ) { + $taxonomy = get_query_var( 'taxonomy' ); + $tax = get_taxonomy( $taxonomy ); + $tax = $tax->label; + $term = $wp_query->get_queried_object(); + $term = $term->name; + $title = "$tax$t_sep$term"; + } + + //If it's a search + if ( is_search() ) { + /* translators: 1: separator, 2: search phrase */ + $title = sprintf(__('Search Results %1$s %2$s'), $t_sep, strip_tags($search)); + } + + if ( is_404() ) { + $title = __('Page not found'); + } + + $prefix = ''; + if ( !empty($title) ) + $prefix = " $sep "; + + // Determines position of the separator and direction of the breadcrumb + if ( 'right' == $seplocation ) { // sep on right, so reverse the order + $title_array = explode( $t_sep, $title ); + $title_array = array_reverse( $title_array ); + $title = implode( " $sep ", $title_array ) . $prefix; + } else { + $title_array = explode( $t_sep, $title ); + $title = $prefix . implode( " $sep ", $title_array ); + } + + $title = apply_filters('wp_title', $title, $sep, $seplocation); + + // Send it out + if ( $display ) + echo $title; + else + return $title; + +} + +/** + * Display or retrieve page title for post. + * + * This is optimized for single.php template file for displaying the post title. + * Only useful for posts, does not support pages for example. + * + * It does not support placing the separator after the title, but by leaving the + * prefix parameter empty, you can set the title separator manually. The prefix + * does not automatically place a space between the prefix, so if there should + * be a space, the parameter value will need to have it at the end. + * + * @since 0.71 + * @uses $wpdb + * + * @param string $prefix Optional. What to display before the title. + * @param bool $display Optional, default is true. Whether to display or retrieve title. + * @return string|null Title when retrieving, null when displaying or failure. + */ +function single_post_title($prefix = '', $display = true) { + global $wpdb; + $p = get_query_var('p'); + $name = get_query_var('name'); + + if ( intval($p) || '' != $name ) { + if ( !$p ) + $p = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_name = %s", $name)); + $post = & get_post($p); + $title = $post->post_title; + $title = apply_filters('single_post_title', $title); + if ( $display ) + echo $prefix.strip_tags($title); + else + return strip_tags($title); + } +} + +/** + * Display or retrieve page title for category archive. + * + * This is useful for category template file or files, because it is optimized + * for category page title and with less overhead than {@link wp_title()}. + * + * It does not support placing the separator after the title, but by leaving the + * prefix parameter empty, you can set the title separator manually. The prefix + * does not automatically place a space between the prefix, so if there should + * be a space, the parameter value will need to have it at the end. + * + * @since 0.71 + * + * @param string $prefix Optional. What to display before the title. + * @param bool $display Optional, default is true. Whether to display or retrieve title. + * @return string|null Title when retrieving, null when displaying or failure. + */ +function single_cat_title($prefix = '', $display = true ) { + $cat = intval( get_query_var('cat') ); + if ( !empty($cat) && !(strtoupper($cat) == 'ALL') ) { + $my_cat_name = apply_filters('single_cat_title', get_the_category_by_ID($cat)); + if ( !empty($my_cat_name) ) { + if ( $display ) + echo $prefix.strip_tags($my_cat_name); + else + return strip_tags($my_cat_name); + } + } else if ( is_tag() ) { + return single_tag_title($prefix, $display); + } +} + +/** + * Display or retrieve page title for tag post archive. + * + * Useful for tag template files for displaying the tag page title. It has less + * overhead than {@link wp_title()}, because of its limited implementation. + * + * It does not support placing the separator after the title, but by leaving the + * prefix parameter empty, you can set the title separator manually. The prefix + * does not automatically place a space between the prefix, so if there should + * be a space, the parameter value will need to have it at the end. + * + * @since 2.3.0 + * + * @param string $prefix Optional. What to display before the title. + * @param bool $display Optional, default is true. Whether to display or retrieve title. + * @return string|null Title when retrieving, null when displaying or failure. + */ +function single_tag_title($prefix = '', $display = true ) { + if ( !is_tag() ) + return; + + $tag_id = intval( get_query_var('tag_id') ); + + if ( !empty($tag_id) ) { + $my_tag = &get_term($tag_id, 'post_tag', OBJECT, 'display'); + if ( is_wp_error( $my_tag ) ) + return false; + $my_tag_name = apply_filters('single_tag_title', $my_tag->name); + if ( !empty($my_tag_name) ) { + if ( $display ) + echo $prefix . $my_tag_name; + else + return $my_tag_name; + } + } +} + +/** + * Display or retrieve page title for post archive based on date. + * + * Useful for when the template only needs to display the month and year, if + * either are available. Optimized for just this purpose, so if it is all that + * is needed, should be better than {@link wp_title()}. + * + * It does not support placing the separator after the title, but by leaving the + * prefix parameter empty, you can set the title separator manually. The prefix + * does not automatically place a space between the prefix, so if there should + * be a space, the parameter value will need to have it at the end. + * + * @since 0.71 + * + * @param string $prefix Optional. What to display before the title. + * @param bool $display Optional, default is true. Whether to display or retrieve title. + * @return string|null Title when retrieving, null when displaying or failure. + */ +function single_month_title($prefix = '', $display = true ) { + global $wp_locale; + + $m = get_query_var('m'); + $year = get_query_var('year'); + $monthnum = get_query_var('monthnum'); + + if ( !empty($monthnum) && !empty($year) ) { + $my_year = $year; + $my_month = $wp_locale->get_month($monthnum); + } elseif ( !empty($m) ) { + $my_year = substr($m, 0, 4); + $my_month = $wp_locale->get_month(substr($m, 4, 2)); + } + + if ( empty($my_month) ) + return false; + + $result = $prefix . $my_month . $prefix . $my_year; + + if ( !$display ) + return $result; + echo $result; +} + +/** + * Retrieve archive link content based on predefined or custom code. + * + * The format can be one of four styles. The 'link' for head element, 'option' + * for use in the select element, 'html' for use in list (either ol or ul HTML + * elements). Custom content is also supported using the before and after + * parameters. + * + * The 'link' format uses the link HTML element with the archives + * relationship. The before and after parameters are not used. The text + * parameter is used to describe the link. + * + * The 'option' format uses the option HTML element for use in select element. + * The value is the url parameter and the before and after parameters are used + * between the text description. + * + * The 'html' format, which is the default, uses the li HTML element for use in + * the list HTML elements. The before parameter is before the link and the after + * parameter is after the closing link. + * + * The custom format uses the before parameter before the link ('a' HTML + * element) and the after parameter after the closing link tag. If the above + * three values for the format are not used, then custom format is assumed. + * + * @since 1.0.0 + * @author Orien + * @link http://icecode.com/ link navigation hack by Orien + * + * @param string $url URL to archive. + * @param string $text Archive text description. + * @param string $format Optional, default is 'html'. Can be 'link', 'option', 'html', or custom. + * @param string $before Optional. + * @param string $after Optional. + * @return string HTML link content for archive. + */ +function get_archives_link($url, $text, $format = 'html', $before = '', $after = '') { + $text = wptexturize($text); + $title_text = esc_attr($text); + $url = esc_url($url); + + if ('link' == $format) + $link_html = "\t\n"; + elseif ('option' == $format) + $link_html = "\t\n"; + elseif ('html' == $format) + $link_html = "\t
  • $before$text$after
  • \n"; + else // custom + $link_html = "\t$before$text$after\n"; + + $link_html = apply_filters( "get_archives_link", $link_html ); + + return $link_html; +} + +/** + * Display archive links based on type and format. + * + * The 'type' argument offers a few choices and by default will display monthly + * archive links. The other options for values are 'daily', 'weekly', 'monthly', + * 'yearly', 'postbypost' or 'alpha'. Both 'postbypost' and 'alpha' display the + * same archive link list, the difference between the two is that 'alpha' + * will order by post title and 'postbypost' will order by post date. + * + * The date archives will logically display dates with links to the archive post + * page. The 'postbypost' and 'alpha' values for 'type' argument will display + * the post titles. + * + * The 'limit' argument will only display a limited amount of links, specified + * by the 'limit' integer value. By default, there is no limit. The + * 'show_post_count' argument will show how many posts are within the archive. + * By default, the 'show_post_count' argument is set to false. + * + * For the 'format', 'before', and 'after' arguments, see {@link + * get_archives_link()}. The values of these arguments have to do with that + * function. + * + * @since 1.2.0 + * + * @param string|array $args Optional. Override defaults. + */ +function wp_get_archives($args = '') { + global $wpdb, $wp_locale; + + $defaults = array( + 'type' => 'monthly', 'limit' => '', + 'format' => 'html', 'before' => '', + 'after' => '', 'show_post_count' => false, + 'echo' => 1 + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + if ( '' == $type ) + $type = 'monthly'; + + if ( '' != $limit ) { + $limit = absint($limit); + $limit = ' LIMIT '.$limit; + } + + // this is what will separate dates on weekly archive links + $archive_week_separator = '–'; + + // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride + $archive_date_format_over_ride = 0; + + // options for daily archive (only if you over-ride the general date format) + $archive_day_date_format = 'Y/m/d'; + + // options for weekly archive (only if you over-ride the general date format) + $archive_week_start_date_format = 'Y/m/d'; + $archive_week_end_date_format = 'Y/m/d'; + + if ( !$archive_date_format_over_ride ) { + $archive_day_date_format = get_option('date_format'); + $archive_week_start_date_format = get_option('date_format'); + $archive_week_end_date_format = get_option('date_format'); + } + + //filters + $where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r ); + $join = apply_filters('getarchives_join', "", $r); + + $output = ''; + + if ( 'monthly' == $type ) { + $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC $limit"; + $key = md5($query); + $cache = wp_cache_get( 'wp_get_archives' , 'general'); + if ( !isset( $cache[ $key ] ) ) { + $arcresults = $wpdb->get_results($query); + $cache[ $key ] = $arcresults; + wp_cache_add( 'wp_get_archives', $cache, 'general' ); + } else { + $arcresults = $cache[ $key ]; + } + if ( $arcresults ) { + $afterafter = $after; + foreach ( (array) $arcresults as $arcresult ) { + $url = get_month_link( $arcresult->year, $arcresult->month ); + $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year); + if ( $show_post_count ) + $after = ' ('.$arcresult->posts.')' . $afterafter; + $output .= get_archives_link($url, $text, $format, $before, $after); + } + } + } elseif ('yearly' == $type) { + $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date) ORDER BY post_date DESC $limit"; + $key = md5($query); + $cache = wp_cache_get( 'wp_get_archives' , 'general'); + if ( !isset( $cache[ $key ] ) ) { + $arcresults = $wpdb->get_results($query); + $cache[ $key ] = $arcresults; + wp_cache_add( 'wp_get_archives', $cache, 'general' ); + } else { + $arcresults = $cache[ $key ]; + } + if ($arcresults) { + $afterafter = $after; + foreach ( (array) $arcresults as $arcresult) { + $url = get_year_link($arcresult->year); + $text = sprintf('%d', $arcresult->year); + if ($show_post_count) + $after = ' ('.$arcresult->posts.')' . $afterafter; + $output .= get_archives_link($url, $text, $format, $before, $after); + } + } + } elseif ( 'daily' == $type ) { + $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC $limit"; + $key = md5($query); + $cache = wp_cache_get( 'wp_get_archives' , 'general'); + if ( !isset( $cache[ $key ] ) ) { + $arcresults = $wpdb->get_results($query); + $cache[ $key ] = $arcresults; + wp_cache_add( 'wp_get_archives', $cache, 'general' ); + } else { + $arcresults = $cache[ $key ]; + } + if ( $arcresults ) { + $afterafter = $after; + foreach ( (array) $arcresults as $arcresult ) { + $url = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth); + $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $arcresult->year, $arcresult->month, $arcresult->dayofmonth); + $text = mysql2date($archive_day_date_format, $date); + if ($show_post_count) + $after = ' ('.$arcresult->posts.')'.$afterafter; + $output .= get_archives_link($url, $text, $format, $before, $after); + } + } + } elseif ( 'weekly' == $type ) { + $start_of_week = get_option('start_of_week'); + $query = "SELECT DISTINCT WEEK(post_date, $start_of_week) AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY WEEK(post_date, $start_of_week), YEAR(post_date) ORDER BY post_date DESC $limit"; + $key = md5($query); + $cache = wp_cache_get( 'wp_get_archives' , 'general'); + if ( !isset( $cache[ $key ] ) ) { + $arcresults = $wpdb->get_results($query); + $cache[ $key ] = $arcresults; + wp_cache_add( 'wp_get_archives', $cache, 'general' ); + } else { + $arcresults = $cache[ $key ]; + } + $arc_w_last = ''; + $afterafter = $after; + if ( $arcresults ) { + foreach ( (array) $arcresults as $arcresult ) { + if ( $arcresult->week != $arc_w_last ) { + $arc_year = $arcresult->yr; + $arc_w_last = $arcresult->week; + $arc_week = get_weekstartend($arcresult->yyyymmdd, get_option('start_of_week')); + $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']); + $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']); + $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', get_option('home'), '', '?', '=', $arc_year, '&', '=', $arcresult->week); + $text = $arc_week_start . $archive_week_separator . $arc_week_end; + if ($show_post_count) + $after = ' ('.$arcresult->posts.')'.$afterafter; + $output .= get_archives_link($url, $text, $format, $before, $after); + } + } + } + } elseif ( ( 'postbypost' == $type ) || ('alpha' == $type) ) { + $orderby = ('alpha' == $type) ? "post_title ASC " : "post_date DESC "; + $query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit"; + $key = md5($query); + $cache = wp_cache_get( 'wp_get_archives' , 'general'); + if ( !isset( $cache[ $key ] ) ) { + $arcresults = $wpdb->get_results($query); + $cache[ $key ] = $arcresults; + wp_cache_add( 'wp_get_archives', $cache, 'general' ); + } else { + $arcresults = $cache[ $key ]; + } + if ( $arcresults ) { + foreach ( (array) $arcresults as $arcresult ) { + if ( $arcresult->post_date != '0000-00-00 00:00:00' ) { + $url = get_permalink($arcresult); + $arc_title = $arcresult->post_title; + if ( $arc_title ) + $text = strip_tags(apply_filters('the_title', $arc_title)); + else + $text = $arcresult->ID; + $output .= get_archives_link($url, $text, $format, $before, $after); + } + } + } + } + if ( $echo ) + echo $output; + else + return $output; +} + +/** + * Get number of days since the start of the week. + * + * @since 1.5.0 + * @usedby get_calendar() + * + * @param int $num Number of day. + * @return int Days since the start of the week. + */ +function calendar_week_mod($num) { + $base = 7; + return ($num - $base*floor($num/$base)); +} + +/** + * Display calendar with days that have posts as links. + * + * The calendar is cached, which will be retrieved, if it exists. If there are + * no posts for the month, then it will not be displayed. + * + * @since 1.0.0 + * + * @param bool $initial Optional, default is true. Use initial calendar names. + */ +function get_calendar($initial = true) { + global $wpdb, $m, $monthnum, $year, $wp_locale, $posts; + + $cache = array(); + $key = md5( $m . $monthnum . $year ); + if ( $cache = wp_cache_get( 'get_calendar', 'calendar' ) ) { + if ( is_array($cache) && isset( $cache[ $key ] ) ) { + echo $cache[ $key ]; + return; + } + } + + if ( !is_array($cache) ) + $cache = array(); + + // Quick check. If we have no posts at all, abort! + if ( !$posts ) { + $gotsome = $wpdb->get_var("SELECT 1 as test FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 1"); + if ( !$gotsome ) { + $cache[ $key ] = ''; + wp_cache_set( 'get_calendar', $cache, 'calendar' ); + return; + } + } + + ob_start(); + if ( isset($_GET['w']) ) + $w = ''.intval($_GET['w']); + + // week_begins = 0 stands for Sunday + $week_begins = intval(get_option('start_of_week')); + + // Let's figure out when we are + if ( !empty($monthnum) && !empty($year) ) { + $thismonth = ''.zeroise(intval($monthnum), 2); + $thisyear = ''.intval($year); + } elseif ( !empty($w) ) { + // We need to get the month from MySQL + $thisyear = ''.intval(substr($m, 0, 4)); + $d = (($w - 1) * 7) + 6; //it seems MySQL's weeks disagree with PHP's + $thismonth = $wpdb->get_var("SELECT DATE_FORMAT((DATE_ADD('${thisyear}0101', INTERVAL $d DAY) ), '%m')"); + } elseif ( !empty($m) ) { + $thisyear = ''.intval(substr($m, 0, 4)); + if ( strlen($m) < 6 ) + $thismonth = '01'; + else + $thismonth = ''.zeroise(intval(substr($m, 4, 2)), 2); + } else { + $thisyear = gmdate('Y', current_time('timestamp')); + $thismonth = gmdate('m', current_time('timestamp')); + } + + $unixmonth = mktime(0, 0 , 0, $thismonth, 1, $thisyear); + + // Get the next and previous month and year with at least one post + $previous = $wpdb->get_row("SELECT DISTINCT MONTH(post_date) AS month, YEAR(post_date) AS year + FROM $wpdb->posts + WHERE post_date < '$thisyear-$thismonth-01' + AND post_type = 'post' AND post_status = 'publish' + ORDER BY post_date DESC + LIMIT 1"); + $next = $wpdb->get_row("SELECT DISTINCT MONTH(post_date) AS month, YEAR(post_date) AS year + FROM $wpdb->posts + WHERE post_date > '$thisyear-$thismonth-01' + AND MONTH( post_date ) != MONTH( '$thisyear-$thismonth-01' ) + AND post_type = 'post' AND post_status = 'publish' + ORDER BY post_date ASC + LIMIT 1"); + + /* translators: Calendar caption: 1: month name, 2: 4-digit year */ + $calendar_caption = _x('%1$s %2$s', 'calendar caption'); + echo ' + + + '; + + $myweek = array(); + + for ( $wdcount=0; $wdcount<=6; $wdcount++ ) { + $myweek[] = $wp_locale->get_weekday(($wdcount+$week_begins)%7); + } + + foreach ( $myweek as $wd ) { + $day_name = (true == $initial) ? $wp_locale->get_weekday_initial($wd) : $wp_locale->get_weekday_abbrev($wd); + echo "\n\t\t"; + } + + echo ' + + + + + '; + + if ( $previous ) { + echo "\n\t\t".''; + } else { + echo "\n\t\t".''; + } + + echo "\n\t\t".''; + + if ( $next ) { + echo "\n\t\t".''; + } else { + echo "\n\t\t".''; + } + + echo ' + + + + + '; + + // Get days with posts + $dayswithposts = $wpdb->get_results("SELECT DISTINCT DAYOFMONTH(post_date) + FROM $wpdb->posts WHERE MONTH(post_date) = '$thismonth' + AND YEAR(post_date) = '$thisyear' + AND post_type = 'post' AND post_status = 'publish' + AND post_date < '" . current_time('mysql') . '\'', ARRAY_N); + if ( $dayswithposts ) { + foreach ( (array) $dayswithposts as $daywith ) { + $daywithpost[] = $daywith[0]; + } + } else { + $daywithpost = array(); + } + + if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'camino') !== false || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'safari') !== false) + $ak_title_separator = "\n"; + else + $ak_title_separator = ', '; + + $ak_titles_for_day = array(); + $ak_post_titles = $wpdb->get_results("SELECT post_title, DAYOFMONTH(post_date) as dom " + ."FROM $wpdb->posts " + ."WHERE YEAR(post_date) = '$thisyear' " + ."AND MONTH(post_date) = '$thismonth' " + ."AND post_date < '".current_time('mysql')."' " + ."AND post_type = 'post' AND post_status = 'publish'" + ); + if ( $ak_post_titles ) { + foreach ( (array) $ak_post_titles as $ak_post_title ) { + + $post_title = esc_attr( apply_filters( 'the_title', $ak_post_title->post_title ) ); + + if ( empty($ak_titles_for_day['day_'.$ak_post_title->dom]) ) + $ak_titles_for_day['day_'.$ak_post_title->dom] = ''; + if ( empty($ak_titles_for_day["$ak_post_title->dom"]) ) // first one + $ak_titles_for_day["$ak_post_title->dom"] = $post_title; + else + $ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . $post_title; + } + } + + + // See how much we should pad in the beginning + $pad = calendar_week_mod(date('w', $unixmonth)-$week_begins); + if ( 0 != $pad ) + echo "\n\t\t".''; + + $daysinmonth = intval(date('t', $unixmonth)); + for ( $day = 1; $day <= $daysinmonth; ++$day ) { + if ( isset($newrow) && $newrow ) + echo "\n\t\n\t\n\t\t"; + $newrow = false; + + if ( $day == gmdate('j', (time() + (get_option('gmt_offset') * 3600))) && $thismonth == gmdate('m', time()+(get_option('gmt_offset') * 3600)) && $thisyear == gmdate('Y', time()+(get_option('gmt_offset') * 3600)) ) + echo ''; + + if ( 6 == calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins) ) + $newrow = true; + } + + $pad = 7 - calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins); + if ( $pad != 0 && $pad != 7 ) + echo "\n\t\t".''; + + echo "\n\t\n\t\n\t
    ' . sprintf($calendar_caption, $wp_locale->get_month($thismonth), date('Y', $unixmonth)) . '
    $day_name
    « ' . $wp_locale->get_month_abbrev($wp_locale->get_month($previous->month)) . '  ' . $wp_locale->get_month_abbrev($wp_locale->get_month($next->month)) . ' » 
     
    '; + else + echo ''; + + if ( in_array($day, $daywithpost) ) // any posts today? + echo '$day"; + else + echo $day; + echo ' 
    "; + + $output = ob_get_contents(); + ob_end_clean(); + echo $output; + $cache[ $key ] = $output; + wp_cache_set( 'get_calendar', $cache, 'calendar' ); +} + +/** + * Purge the cached results of get_calendar. + * + * @see get_calendar + * @since 2.1.0 + */ +function delete_get_calendar_cache() { + wp_cache_delete( 'get_calendar', 'calendar' ); +} +add_action( 'save_post', 'delete_get_calendar_cache' ); +add_action( 'delete_post', 'delete_get_calendar_cache' ); +add_action( 'update_option_start_of_week', 'delete_get_calendar_cache' ); +add_action( 'update_option_gmt_offset', 'delete_get_calendar_cache' ); +add_action( 'update_option_start_of_week', 'delete_get_calendar_cache' ); + +/** + * Display all of the allowed tags in HTML format with attributes. + * + * This is useful for displaying in the comment area, which elements and + * attributes are supported. As well as any plugins which want to display it. + * + * @since 1.0.1 + * @uses $allowedtags + * + * @return string HTML allowed tags entity encoded. + */ +function allowed_tags() { + global $allowedtags; + $allowed = ''; + foreach ( (array) $allowedtags as $tag => $attributes ) { + $allowed .= '<'.$tag; + if ( 0 < count($attributes) ) { + foreach ( $attributes as $attribute => $limits ) { + $allowed .= ' '.$attribute.'=""'; + } + } + $allowed .= '> '; + } + return htmlentities($allowed); +} + +/***** Date/Time tags *****/ + +/** + * Outputs the date in iso8601 format for xml files. + * + * @since 1.0.0 + */ +function the_date_xml() { + global $post; + echo mysql2date('Y-m-d', $post->post_date, false); +} + +/** + * Display or Retrieve the date the post was written. + * + * Will only output the date if the current post's date is different from the + * previous one output. + * + * @since 0.71 + * + * @param string $d Optional. PHP date format defaults to the date_format option if not specified. + * @param string $before Optional. Output before the date. + * @param string $after Optional. Output after the date. + * @param bool $echo Optional, default is display. Whether to echo the date or return it. + * @return string|null Null if displaying, string if retrieving. + */ +function the_date($d='', $before='', $after='', $echo = true) { + global $post, $day, $previousday; + $the_date = ''; + if ( $day != $previousday ) { + $the_date .= $before; + if ( $d=='' ) + $the_date .= mysql2date(get_option('date_format'), $post->post_date); + else + $the_date .= mysql2date($d, $post->post_date); + $the_date .= $after; + $previousday = $day; + + $the_date = apply_filters('the_date', $the_date, $d, $before, $after); + if ( $echo ) + echo $the_date; + else + return $the_date; + } +} + +/** + * Display the date on which the post was last modified. + * + * @since 2.1.0 + * + * @param string $d Optional. PHP date format. + * @return string + */ +function the_modified_date($d = '') { + echo apply_filters('the_modified_date', get_the_modified_date($d), $d); +} + +/** + * Retrieve the date on which the post was last modified. + * + * @since 2.1.0 + * + * @param string $d Optional. PHP date format. Defaults to the "date_format" option + * @return string + */ +function get_the_modified_date($d = '') { + if ( '' == $d ) + $the_time = get_post_modified_time(get_option('date_format'), null, null, true); + else + $the_time = get_post_modified_time($d, null, null, true); + return apply_filters('get_the_modified_date', $the_time, $d); +} + +/** + * Display the time at which the post was written. + * + * @since 0.71 + * + * @param string $d Either 'G', 'U', or php date format. + */ +function the_time( $d = '' ) { + echo apply_filters('the_time', get_the_time( $d ), $d); +} + +/** + * Retrieve the time at which the post was written. + * + * @since 1.5.0 + * + * @param string $d Either 'G', 'U', or php date format defaults to the value specified in the time_format option. + * @param int|object $post Optional post ID or object. Default is global $post object. + * @return string + */ +function get_the_time( $d = '', $post = null ) { + $post = get_post($post); + + if ( '' == $d ) + $the_time = get_post_time(get_option('time_format'), false, $post, true); + else + $the_time = get_post_time($d, false, $post, true); + return apply_filters('get_the_time', $the_time, $d, $post); +} + +/** + * Retrieve the time at which the post was written. + * + * @since 2.0.0 + * + * @param string $d Either 'G', 'U', or php date format. + * @param bool $gmt Whether of not to return the gmt time. + * @param int|object $post Optional post ID or object. Default is global $post object. + * @param bool $translate Whether to translate the time string or not + * @return string + */ +function get_post_time( $d = 'U', $gmt = false, $post = null, $translate = false ) { // returns timestamp + $post = get_post($post); + + if ( $gmt ) + $time = $post->post_date_gmt; + else + $time = $post->post_date; + + $time = mysql2date($d, $time, $translate); + return apply_filters('get_post_time', $time, $d, $gmt); +} + +/** + * Display the time at which the post was last modified. + * + * @since 2.0.0 + * + * @param string $d Either 'G', 'U', or php date format defaults to the value specified in the time_format option. + */ +function the_modified_time($d = '') { + echo apply_filters('the_modified_time', get_the_modified_time($d), $d); +} + +/** + * Retrieve the time at which the post was last modified. + * + * @since 2.0.0 + * + * @param string $d Either 'G', 'U', or php date format defaults to the value specified in the time_format option. + * @return string + */ +function get_the_modified_time($d = '') { + if ( '' == $d ) + $the_time = get_post_modified_time(get_option('time_format'), null, null, true); + else + $the_time = get_post_modified_time($d, null, null, true); + return apply_filters('get_the_modified_time', $the_time, $d); +} + +/** + * Retrieve the time at which the post was last modified. + * + * @since 2.0.0 + * + * @param string $d Either 'G', 'U', or php date format. + * @param bool $gmt Whether of not to return the gmt time. + * @param int|object $post A post_id or post object + * @param bool translate Whether to translate the result or not + * @return string Returns timestamp + */ +function get_post_modified_time( $d = 'U', $gmt = false, $post = null, $translate = false ) { + $post = get_post($post); + + if ( $gmt ) + $time = $post->post_modified_gmt; + else + $time = $post->post_modified; + $time = mysql2date($d, $time, $translate); + + return apply_filters('get_post_modified_time', $time, $d, $gmt); +} + +/** + * Display the weekday on which the post was written. + * + * @since 0.71 + * @uses $wp_locale + * @uses $post + */ +function the_weekday() { + global $wp_locale, $post; + $the_weekday = $wp_locale->get_weekday(mysql2date('w', $post->post_date, false)); + $the_weekday = apply_filters('the_weekday', $the_weekday); + echo $the_weekday; +} + +/** + * Display the weekday on which the post was written. + * + * Will only output the weekday if the current post's weekday is different from + * the previous one output. + * + * @since 0.71 + * + * @param string $before output before the date. + * @param string $after output after the date. + */ +function the_weekday_date($before='',$after='') { + global $wp_locale, $post, $day, $previousweekday; + $the_weekday_date = ''; + if ( $day != $previousweekday ) { + $the_weekday_date .= $before; + $the_weekday_date .= $wp_locale->get_weekday(mysql2date('w', $post->post_date, false)); + $the_weekday_date .= $after; + $previousweekday = $day; + } + $the_weekday_date = apply_filters('the_weekday_date', $the_weekday_date, $before, $after); + echo $the_weekday_date; +} + +/** + * Fire the wp_head action + * + * @since 1.2.0 + * @uses do_action() Calls 'wp_head' hook. + */ +function wp_head() { + do_action('wp_head'); +} + +/** + * Fire the wp_footer action + * + * @since 1.5.1 + * @uses do_action() Calls 'wp_footer' hook. + */ +function wp_footer() { + do_action('wp_footer'); +} + +/** + * Enable/disable automatic general feed link outputting. + * + * @since 2.8.0 + * + * @param boolean $add Add or remove links. Defaults to true. + */ +function automatic_feed_links( $add = true ) { + if ( $add ) + add_action( 'wp_head', 'feed_links', 2 ); + else { + remove_action( 'wp_head', 'feed_links', 2 ); + remove_action( 'wp_head', 'feed_links_extra', 3 ); + } +} + +/** + * Display the links to the general feeds. + * + * @since 2.8.0 + * + * @param array $args Optional arguments. + */ +function feed_links( $args ) { + $defaults = array( + /* translators: Separator between blog name and feed type in feed links */ + 'separator' => _x('»', 'feed link'), + /* translators: 1: blog title, 2: separator (raquo) */ + 'feedtitle' => __('%1$s %2$s Feed'), + /* translators: %s: blog title, 2: separator (raquo) */ + 'comstitle' => __('%1$s %2$s Comments Feed'), + ); + + $args = wp_parse_args( $args, $defaults ); + + echo '\n"; + echo '\n"; +} + +/** + * Display the links to the extra feeds such as category feeds. + * + * @since 2.8.0 + * + * @param array $args Optional arguments. + */ +function feed_links_extra( $args ) { + $defaults = array( + /* translators: Separator between blog name and feed type in feed links */ + 'separator' => _x('»', 'feed link'), + /* translators: 1: blog name, 2: separator(raquo), 3: post title */ + 'singletitle' => __('%1$s %2$s %3$s Comments Feed'), + /* translators: 1: blog name, 2: separator(raquo), 3: category name */ + 'cattitle' => __('%1$s %2$s %3$s Category Feed'), + /* translators: 1: blog name, 2: separator(raquo), 3: tag name */ + 'tagtitle' => __('%1$s %2$s %3$s Tag Feed'), + /* translators: 1: blog name, 2: separator(raquo), 3: author name */ + 'authortitle' => __('%1$s %2$s Posts by %3$s Feed'), + /* translators: 1: blog name, 2: separator(raquo), 3: search phrase */ + 'searchtitle' => __('%1$s %2$s Search Results for “%3$s” Feed'), + ); + + $args = wp_parse_args( $args, $defaults ); + + if ( is_single() || is_page() ) { + $post = &get_post( $id = 0 ); + + if ( comments_open() || pings_open() || $post->comment_count > 0 ) { + $title = esc_attr(sprintf( $args['singletitle'], get_bloginfo('name'), $args['separator'], esc_html( get_the_title() ) )); + $href = get_post_comments_feed_link( $post->ID ); + } + } elseif ( is_category() ) { + $cat_id = intval( get_query_var('cat') ); + + $title = esc_attr(sprintf( $args['cattitle'], get_bloginfo('name'), $args['separator'], get_cat_name( $cat_id ) )); + $href = get_category_feed_link( $cat_id ); + } elseif ( is_tag() ) { + $tag_id = intval( get_query_var('tag_id') ); + $tag = get_tag( $tag_id ); + + $title = esc_attr(sprintf( $args['tagtitle'], get_bloginfo('name'), $args['separator'], $tag->name )); + $href = get_tag_feed_link( $tag_id ); + } elseif ( is_author() ) { + $author_id = intval( get_query_var('author') ); + + $title = esc_attr(sprintf( $args['authortitle'], get_bloginfo('name'), $args['separator'], get_the_author_meta( 'display_name', $author_id ) )); + $href = get_author_feed_link( $author_id ); + } elseif ( is_search() ) { + $title = esc_attr(sprintf( $args['searchtitle'], get_bloginfo('name'), $args['separator'], get_search_query() )); + $href = get_search_feed_link(); + } + + if ( isset($title) && isset($href) ) + echo '' . "\n"; +} + +/** + * Display the link to the Really Simple Discovery service endpoint. + * + * @link http://archipelago.phrasewise.com/rsd + * @since 2.0.0 + */ +function rsd_link() { + echo '\n"; +} + +/** + * Display the link to the Windows Live Writer manifest file. + * + * @link http://msdn.microsoft.com/en-us/library/bb463265.aspx + * @since 2.3.1 + */ +function wlwmanifest_link() { + echo ' ' . "\n"; +} + +/** + * Display a noindex meta tag if required by the blog configuration. + * + * If a blog is marked as not being public then the noindex meta tag will be + * output to tell web robots not to index the page content. + * + * @since 2.1.0 + */ +function noindex() { + // If the blog is not public, tell robots to go away. + if ( '0' == get_option('blog_public') ) + echo "\n"; +} + +/** + * Determine if TinyMCE is available. + * + * Checks to see if the user has deleted the tinymce files to slim down there WordPress install. + * + * @since 2.1.0 + * + * @return bool Whether of not TinyMCE exists. + */ +function rich_edit_exists() { + global $wp_rich_edit_exists; + if ( !isset($wp_rich_edit_exists) ) + $wp_rich_edit_exists = file_exists(ABSPATH . WPINC . '/js/tinymce/tiny_mce.js'); + return $wp_rich_edit_exists; +} + +/** + * Whether or not the user should have a WYSIWIG editor. + * + * Checks that the user requires a WYSIWIG editor and that the editor is + * supported in the users browser. + * + * @since 2.0.0 + * + * @return bool + */ +function user_can_richedit() { + global $wp_rich_edit, $pagenow; + + if ( !isset( $wp_rich_edit) ) { + if ( get_user_option( 'rich_editing' ) == 'true' && + ( ( preg_match( '!AppleWebKit/(\d+)!', $_SERVER['HTTP_USER_AGENT'], $match ) && intval($match[1]) >= 420 ) || + !preg_match( '!opera[ /][2-8]|konqueror|safari!i', $_SERVER['HTTP_USER_AGENT'] ) ) + && 'comment.php' != $pagenow ) { + $wp_rich_edit = true; + } else { + $wp_rich_edit = false; + } + } + + return apply_filters('user_can_richedit', $wp_rich_edit); +} + +/** + * Find out which editor should be displayed by default. + * + * Works out which of the two editors to display as the current editor for a + * user. + * + * @since 2.5.0 + * + * @return string Either 'tinymce', or 'html', or 'test' + */ +function wp_default_editor() { + $r = user_can_richedit() ? 'tinymce' : 'html'; // defaults + if ( $user = wp_get_current_user() ) { // look for cookie + $ed = get_user_setting('editor', 'tinymce'); + $r = ( in_array($ed, array('tinymce', 'html', 'test') ) ) ? $ed : $r; + } + return apply_filters( 'wp_default_editor', $r ); // filter +} + +/** + * Display visual editor forms: TinyMCE, or HTML, or both. + * + * The amount of rows the text area will have for the content has to be between + * 3 and 100 or will default at 12. There is only one option used for all users, + * named 'default_post_edit_rows'. + * + * If the user can not use the rich editor (TinyMCE), then the switch button + * will not be displayed. + * + * @since 2.1.0 + * + * @param string $content Textarea content. + * @param string $id HTML ID attribute value. + * @param string $prev_id HTML ID name for switching back and forth between visual editors. + * @param bool $media_buttons Optional, default is true. Whether to display media buttons. + * @param int $tab_index Optional, default is 2. Tabindex for textarea element. + */ +function the_editor($content, $id = 'content', $prev_id = 'title', $media_buttons = true, $tab_index = 2) { + $rows = get_option('default_post_edit_rows'); + if (($rows < 3) || ($rows > 100)) + $rows = 12; + + if ( !current_user_can( 'upload_files' ) ) + $media_buttons = false; + + $richedit = user_can_richedit(); + $class = ''; + + if ( $richedit || $media_buttons ) { ?> +
    + +
    + + + + + + + +
    + +
    + +
    + +
    + +
    + +
    \n"); + $the_editor_content = apply_filters('the_editor_content', $content); + + printf($the_editor, $the_editor_content); + +?> + + '%_%', // http://example.com/all_posts.php%_% : %_% is replaced by format (below) + 'format' => '?page=%#%', // ?page=%#% : %#% is replaced by the page number + 'total' => 1, + 'current' => 0, + 'show_all' => false, + 'prev_next' => true, + 'prev_text' => __('« Previous'), + 'next_text' => __('Next »'), + 'end_size' => 1, + 'mid_size' => 2, + 'type' => 'plain', + 'add_args' => false, // array of query args to add + 'add_fragment' => '' + ); + + $args = wp_parse_args( $args, $defaults ); + extract($args, EXTR_SKIP); + + // Who knows what else people pass in $args + $total = (int) $total; + if ( $total < 2 ) + return; + $current = (int) $current; + $end_size = 0 < (int) $end_size ? (int) $end_size : 1; // Out of bounds? Make it the default. + $mid_size = 0 <= (int) $mid_size ? (int) $mid_size : 2; + $add_args = is_array($add_args) ? $add_args : false; + $r = ''; + $page_links = array(); + $n = 0; + $dots = false; + + if ( $prev_next && $current && 1 < $current ) : + $link = str_replace('%_%', 2 == $current ? '' : $format, $base); + $link = str_replace('%#%', $current - 1, $link); + if ( $add_args ) + $link = add_query_arg( $add_args, $link ); + $link .= $add_fragment; + $page_links[] = ""; + endif; + for ( $n = 1; $n <= $total; $n++ ) : + $n_display = number_format_i18n($n); + if ( $n == $current ) : + $page_links[] = "$n_display"; + $dots = true; + else : + if ( $show_all || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) : + $link = str_replace('%_%', 1 == $n ? '' : $format, $base); + $link = str_replace('%#%', $n, $link); + if ( $add_args ) + $link = add_query_arg( $add_args, $link ); + $link .= $add_fragment; + $page_links[] = "$n_display"; + $dots = true; + elseif ( $dots && !$show_all ) : + $page_links[] = "..."; + $dots = false; + endif; + endif; + endfor; + if ( $prev_next && $current && ( $current < $total || -1 == $total ) ) : + $link = str_replace('%_%', $format, $base); + $link = str_replace('%#%', $current + 1, $link); + if ( $add_args ) + $link = add_query_arg( $add_args, $link ); + $link .= $add_fragment; + $page_links[] = ""; + endif; + switch ( $type ) : + case 'array' : + return $page_links; + break; + case 'list' : + $r .= "
      \n\t
    • "; + $r .= join("
    • \n\t
    • ", $page_links); + $r .= "
    • \n
    \n"; + break; + default : + $r = join("\n", $page_links); + break; + endswitch; + return $r; +} + +/** + * Registers an admin colour scheme css file. + * + * Allows a plugin to register a new admin colour scheme. For example: + * + * wp_admin_css_color('classic', __('Classic'), admin_url("css/colors-classic.css"), + * array('#07273E', '#14568A', '#D54E21', '#2683AE')); + * + * + * @since 2.5.0 + * + * @param string $key The unique key for this theme. + * @param string $name The name of the theme. + * @param string $url The url of the css file containing the colour scheme. + * @param array @colors An array of CSS color definitions which are used to give the user a feel for the theme. + */ +function wp_admin_css_color($key, $name, $url, $colors = array()) { + global $_wp_admin_css_colors; + + if ( !isset($_wp_admin_css_colors) ) + $_wp_admin_css_colors = array(); + + $_wp_admin_css_colors[$key] = (object) array('name' => $name, 'url' => $url, 'colors' => $colors); +} + +/** + * Display the URL of a WordPress admin CSS file. + * + * @see WP_Styles::_css_href and its style_loader_src filter. + * + * @since 2.3.0 + * + * @param string $file file relative to wp-admin/ without its ".css" extension. + */ +function wp_admin_css_uri( $file = 'wp-admin' ) { + if ( defined('WP_INSTALLING') ) { + $_file = "./$file.css"; + } else { + $_file = admin_url("$file.css"); + } + $_file = add_query_arg( 'version', get_bloginfo( 'version' ), $_file ); + + return apply_filters( 'wp_admin_css_uri', $_file, $file ); +} + +/** + * Enqueues or directly prints a stylesheet link to the specified CSS file. + * + * "Intelligently" decides to enqueue or to print the CSS file. If the + * 'wp_print_styles' action has *not* yet been called, the CSS file will be + * enqueued. If the wp_print_styles action *has* been called, the CSS link will + * be printed. Printing may be forced by passing TRUE as the $force_echo + * (second) parameter. + * + * For backward compatibility with WordPress 2.3 calling method: If the $file + * (first) parameter does not correspond to a registered CSS file, we assume + * $file is a file relative to wp-admin/ without its ".css" extension. A + * stylesheet link to that generated URL is printed. + * + * @package WordPress + * @since 2.3.0 + * @uses $wp_styles WordPress Styles Object + * + * @param string $file Style handle name or file name (without ".css" extension) relative to wp-admin/ + * @param bool $force_echo Optional. Force the stylesheet link to be printed rather than enqueued. + */ +function wp_admin_css( $file = 'wp-admin', $force_echo = false ) { + global $wp_styles; + if ( !is_a($wp_styles, 'WP_Styles') ) + $wp_styles = new WP_Styles(); + + // For backward compatibility + $handle = 0 === strpos( $file, 'css/' ) ? substr( $file, 4 ) : $file; + + if ( $wp_styles->query( $handle ) ) { + if ( $force_echo || did_action( 'wp_print_styles' ) ) // we already printed the style queue. Print this one immediately + wp_print_styles( $handle ); + else // Add to style queue + wp_enqueue_style( $handle ); + return; + } + + echo apply_filters( 'wp_admin_css', "\n", $file ); + if ( 'rtl' == get_bloginfo( 'text_direction' ) ) + echo apply_filters( 'wp_admin_css', "\n", "$file-rtl" ); +} + +/** + * Enqueues the default ThickBox js and css. + * + * If any of the settings need to be changed, this can be done with another js + * file similar to media-upload.js and theme-preview.js. That file should + * require array('thickbox') to ensure it is loaded after. + * + * @since 2.5.0 + */ +function add_thickbox() { + wp_enqueue_script( 'thickbox' ); + wp_enqueue_style( 'thickbox' ); +} + +/** + * Display the XHTML generator that is generated on the wp_head hook. + * + * @since 2.5.0 + */ +function wp_generator() { + the_generator( apply_filters( 'wp_generator_type', 'xhtml' ) ); +} + +/** + * Display the generator XML or Comment for RSS, ATOM, etc. + * + * Returns the correct generator type for the requested output format. Allows + * for a plugin to filter generators overall the the_generator filter. + * + * @since 2.5.0 + * @uses apply_filters() Calls 'the_generator' hook. + * + * @param string $type The type of generator to output - (html|xhtml|atom|rss2|rdf|comment|export). + */ +function the_generator( $type ) { + echo apply_filters('the_generator', get_the_generator($type), $type) . "\n"; +} + +/** + * Creates the generator XML or Comment for RSS, ATOM, etc. + * + * Returns the correct generator type for the requested output format. Allows + * for a plugin to filter generators on an individual basis using the + * 'get_the_generator_{$type}' filter. + * + * @since 2.5.0 + * @uses apply_filters() Calls 'get_the_generator_$type' hook. + * + * @param string $type The type of generator to return - (html|xhtml|atom|rss2|rdf|comment|export). + * @return string The HTML content for the generator. + */ +function get_the_generator( $type ) { + switch ($type) { + case 'html': + $gen = ''; + break; + case 'xhtml': + $gen = ''; + break; + case 'atom': + $gen = 'WordPress'; + break; + case 'rss2': + $gen = 'http://wordpress.org/?v=' . get_bloginfo_rss( 'version' ) . ''; + break; + case 'rdf': + $gen = ''; + break; + case 'comment': + $gen = ''; + break; + case 'export': + $gen = ''; + break; + } + return apply_filters( "get_the_generator_{$type}", $gen, $type ); +} + +?> diff --git a/wp-includes/gettext.php b/wp-includes/gettext.php new file mode 100644 index 0000000..48e98b3 --- /dev/null +++ b/wp-includes/gettext.php @@ -0,0 +1,400 @@ +. + Copyright (c) 2005 Nico Kaiser + + This file is part of PHP-gettext. + + PHP-gettext 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. + + PHP-gettext 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 PHP-gettext; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +*/ + +/** + * Provides a simple gettext replacement that works independently from + * the system's gettext abilities. + * It can read MO files and use them for translating strings. + * The files are passed to gettext_reader as a Stream (see streams.php) + * + * This version has the ability to cache all strings and translations to + * speed up the string lookup. + * While the cache is enabled by default, it can be switched off with the + * second parameter in the constructor (e.g. whenusing very large MO files + * that you don't want to keep in memory) + */ +class gettext_reader { + //public: + var $error = 0; // public variable that holds error code (0 if no error) + + //private: + var $BYTEORDER = 0; // 0: low endian, 1: big endian + var $STREAM = NULL; + var $short_circuit = false; + var $enable_cache = false; + var $originals = NULL; // offset of original table + var $translations = NULL; // offset of translation table + var $pluralheader = NULL; // cache header field for plural forms + var $select_string_function = NULL; // cache function, which chooses plural forms + var $total = 0; // total string count + var $table_originals = NULL; // table for original strings (offsets) + var $table_translations = NULL; // table for translated strings (offsets) + var $cache_translations = NULL; // original -> translation mapping + + + /* Methods */ + + + /** + * Reads a 32bit Integer from the Stream + * + * @access private + * @return Integer from the Stream + */ + function readint() { + if ($this->BYTEORDER == 0) { + // low endian + $low_end = unpack('V', $this->STREAM->read(4)); + return array_shift($low_end); + } else { + // big endian + $big_end = unpack('N', $this->STREAM->read(4)); + return array_shift($big_end); + } + } + + /** + * Reads an array of Integers from the Stream + * + * @param int count How many elements should be read + * @return Array of Integers + */ + function readintarray($count) { + if ($this->BYTEORDER == 0) { + // low endian + return unpack('V'.$count, $this->STREAM->read(4 * $count)); + } else { + // big endian + return unpack('N'.$count, $this->STREAM->read(4 * $count)); + } + } + + /** + * Constructor + * + * @param object Reader the StreamReader object + * @param boolean enable_cache Enable or disable caching of strings (default on) + */ + function gettext_reader($Reader, $enable_cache = true) { + // If there isn't a StreamReader, turn on short circuit mode. + if (! $Reader || isset($Reader->error) ) { + $this->short_circuit = true; + return; + } + + // Caching can be turned off + $this->enable_cache = $enable_cache; + + // $MAGIC1 = (int)0x950412de; //bug in PHP 5.0.2, see https://savannah.nongnu.org/bugs/?func=detailitem&item_id=10565 + $MAGIC1 = (int) - 1794895138; + // $MAGIC2 = (int)0xde120495; //bug + $MAGIC2 = (int) - 569244523; + // 64-bit fix + $MAGIC3 = (int) 2500072158; + + $this->STREAM = $Reader; + $magic = $this->readint(); + if ($magic == $MAGIC1 || $magic == $MAGIC3) { // to make sure it works for 64-bit platforms + $this->BYTEORDER = 0; + } elseif ($magic == ($MAGIC2 & 0xFFFFFFFF)) { + $this->BYTEORDER = 1; + } else { + $this->error = 1; // not MO file + return false; + } + + // FIXME: Do we care about revision? We should. + $revision = $this->readint(); + + $this->total = $this->readint(); + $this->originals = $this->readint(); + $this->translations = $this->readint(); + } + + /** + * Loads the translation tables from the MO file into the cache + * If caching is enabled, also loads all strings into a cache + * to speed up translation lookups + * + * @access private + */ + function load_tables() { + if (is_array($this->cache_translations) && + is_array($this->table_originals) && + is_array($this->table_translations)) + return; + + /* get original and translations tables */ + $this->STREAM->seekto($this->originals); + $this->table_originals = $this->readintarray($this->total * 2); + $this->STREAM->seekto($this->translations); + $this->table_translations = $this->readintarray($this->total * 2); + + if ($this->enable_cache) { + $this->cache_translations = array (); + /* read all strings in the cache */ + for ($i = 0; $i < $this->total; $i++) { + $this->STREAM->seekto($this->table_originals[$i * 2 + 2]); + $original = $this->STREAM->read($this->table_originals[$i * 2 + 1]); + $this->STREAM->seekto($this->table_translations[$i * 2 + 2]); + $translation = $this->STREAM->read($this->table_translations[$i * 2 + 1]); + $this->cache_translations[$original] = $translation; + } + } + } + + /** + * Returns a string from the "originals" table + * + * @access private + * @param int num Offset number of original string + * @return string Requested string if found, otherwise '' + */ + function get_original_string($num) { + $length = $this->table_originals[$num * 2 + 1]; + $offset = $this->table_originals[$num * 2 + 2]; + if (! $length) + return ''; + $this->STREAM->seekto($offset); + $data = $this->STREAM->read($length); + return (string)$data; + } + + /** + * Returns a string from the "translations" table + * + * @access private + * @param int num Offset number of original string + * @return string Requested string if found, otherwise '' + */ + function get_translation_string($num) { + $length = $this->table_translations[$num * 2 + 1]; + $offset = $this->table_translations[$num * 2 + 2]; + if (! $length) + return ''; + $this->STREAM->seekto($offset); + $data = $this->STREAM->read($length); + return (string)$data; + } + + /** + * Binary search for string + * + * @access private + * @param string string + * @param int start (internally used in recursive function) + * @param int end (internally used in recursive function) + * @return int string number (offset in originals table) + */ + function find_string($string, $start = -1, $end = -1) { + if (($start == -1) or ($end == -1)) { + // find_string is called with only one parameter, set start end end + $start = 0; + $end = $this->total; + } + if (abs($start - $end) <= 1) { + // We're done, now we either found the string, or it doesn't exist + $txt = $this->get_original_string($start); + if ($string == $txt) + return $start; + else + return -1; + } else if ($start > $end) { + // start > end -> turn around and start over + return $this->find_string($string, $end, $start); + } else { + // Divide table in two parts + $half = (int)(($start + $end) / 2); + $cmp = strcmp($string, $this->get_original_string($half)); + if ($cmp == 0) + // string is exactly in the middle => return it + return $half; + else if ($cmp < 0) + // The string is in the upper half + return $this->find_string($string, $start, $half); + else + // The string is in the lower half + return $this->find_string($string, $half, $end); + } + } + + /** + * Translates a string + * + * @access public + * @param string string to be translated + * @return string translated string (or original, if not found) + */ + function translate($string) { + if ($this->short_circuit) + return $string; + $this->load_tables(); + + if ($this->enable_cache) { + // Caching enabled, get translated string from cache + if (array_key_exists($string, $this->cache_translations)) + return $this->cache_translations[$string]; + else + return $string; + } else { + // Caching not enabled, try to find string + $num = $this->find_string($string); + if ($num == -1) + return $string; + else + return $this->get_translation_string($num); + } + } + + /** + * Get possible plural forms from MO header + * + * @access private + * @return string plural form header + */ + function get_plural_forms() { + // lets assume message number 0 is header + // this is true, right? + $this->load_tables(); + + // cache header field for plural forms + if (! is_string($this->pluralheader)) { + if ($this->enable_cache) { + $header = $this->cache_translations[""]; + } else { + $header = $this->get_translation_string(0); + } + $header .= "\n"; //make sure our regex matches + if (eregi("plural-forms: ([^\n]*)\n", $header, $regs)) + $expr = $regs[1]; + else + $expr = "nplurals=2; plural=n == 1 ? 0 : 1;"; + + // add parentheses + // important since PHP's ternary evaluates from left to right + $expr.= ';'; + $res= ''; + $p= 0; + for ($i= 0; $i < strlen($expr); $i++) { + $ch= $expr[$i]; + switch ($ch) { + case '?': + $res.= ' ? ('; + $p++; + break; + case ':': + $res.= ') : ('; + break; + case ';': + $res.= str_repeat( ')', $p) . ';'; + $p= 0; + break; + default: + $res.= $ch; + } + } + $this->pluralheader = $res; + } + + return $this->pluralheader; + } + + /** + * Detects which plural form to take + * + * @access private + * @param n count + * @return int array index of the right plural form + */ + function select_string($n) { + if (is_null($this->select_string_function)) { + $string = $this->get_plural_forms(); + if (preg_match("/nplurals\s*=\s*(\d+)\s*\;\s*plural\s*=\s*(.*?)\;+/", $string, $matches)) { + $nplurals = $matches[1]; + $expression = $matches[2]; + $expression = str_replace("n", '$n', $expression); + } else { + $nplurals = 2; + $expression = ' $n == 1 ? 0 : 1 '; + } + $func_body = " + \$plural = ($expression); + return (\$plural <= $nplurals)? \$plural : \$plural - 1;"; + $this->select_string_function = create_function('$n', $func_body); + } + return call_user_func($this->select_string_function, $n); + } + + /** + * Plural version of gettext + * + * @access public + * @param string single + * @param string plural + * @param string number + * @return translated plural form + */ + function ngettext($single, $plural, $number) { + if ($this->short_circuit) { + if ($number != 1) + return $plural; + else + return $single; + } + + // find out the appropriate form + $select = $this->select_string($number); + + // this should contains all strings separated by NULLs + $key = $single.chr(0).$plural; + + + if ($this->enable_cache) { + if (! array_key_exists($key, $this->cache_translations)) { + return ($number != 1) ? $plural : $single; + } else { + $result = $this->cache_translations[$key]; + $list = explode(chr(0), $result); + return $list[$select]; + } + } else { + $num = $this->find_string($key); + if ($num == -1) { + return ($number != 1) ? $plural : $single; + } else { + $result = $this->get_translation_string($num); + $list = explode(chr(0), $result); + return $list[$select]; + } + } + } + +} + +?> \ No newline at end of file diff --git a/wp-includes/http.php b/wp-includes/http.php new file mode 100644 index 0000000..e431bd1 --- /dev/null +++ b/wp-includes/http.php @@ -0,0 +1,2054 @@ + + */ + +/** + * WordPress HTTP Class for managing HTTP Transports and making HTTP requests. + * + * This class is called for the functionality of making HTTP requests and should replace Snoopy + * functionality, eventually. There is no available functionality to add HTTP transport + * implementations, since most of the HTTP transports are added and available for use. + * + * The exception is that cURL is not available as a transport and lacking an implementation. It will + * be added later and should be a patch on the WordPress Trac. + * + * There are no properties, because none are needed and for performance reasons. Some of the + * functions are static and while they do have some overhead over functions in PHP4, the purpose is + * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword + * to the code. It is not as easy to convert a function to a method after enough code uses the old + * way. + * + * Debugging includes several actions, which pass different variables for debugging the HTTP API. + * + * http_transport_get_debug - gives working, nonblocking, and blocking transports. + * + * http_transport_post_debug - gives working, nonblocking, and blocking transports. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http { + + /** + * PHP4 style Constructor - Calls PHP5 Style Constructor + * + * @since 2.7.0 + * @return WP_Http + */ + function WP_Http() { + $this->__construct(); + } + + /** + * PHP5 style Constructor - Setup available transport if not available. + * + * PHP4 does not have the 'self' keyword and since WordPress supports PHP4, + * the class needs to be used for the static call. + * + * The transport are setup to save time. This should only be called once, so + * the overhead should be fine. + * + * @since 2.7.0 + * @return WP_Http + */ + function __construct() { + WP_Http::_getTransport(); + WP_Http::_postTransport(); + } + + /** + * Tests the WordPress HTTP objects for an object to use and returns it. + * + * Tests all of the objects and returns the object that passes. Also caches + * that object to be used later. + * + * The order for the GET/HEAD requests are Streams, HTTP Extension, Fopen, + * and finally Fsockopen. fsockopen() is used last, because it has the most + * overhead in its implementation. There isn't any real way around it, since + * redirects have to be supported, much the same way the other transports + * also handle redirects. + * + * There are currently issues with "localhost" not resolving correctly with + * DNS. This may cause an error "failed to open stream: A connection attempt + * failed because the connected party did not properly respond after a + * period of time, or established connection failed because connected host + * has failed to respond." + * + * @since 2.7.0 + * @access private + * + * @param array $args Request args, default us an empty array + * @return object|null Null if no transports are available, HTTP transport object. + */ + function &_getTransport( $args = array() ) { + static $working_transport, $blocking_transport, $nonblocking_transport; + + if ( is_null($working_transport) ) { + if ( true === WP_Http_ExtHttp::test($args) ) { + $working_transport['exthttp'] = new WP_Http_ExtHttp(); + $blocking_transport[] = &$working_transport['exthttp']; + } else if ( true === WP_Http_Curl::test($args) ) { + $working_transport['curl'] = new WP_Http_Curl(); + $blocking_transport[] = &$working_transport['curl']; + } else if ( true === WP_Http_Streams::test($args) ) { + $working_transport['streams'] = new WP_Http_Streams(); + $blocking_transport[] = &$working_transport['streams']; + } else if ( true === WP_Http_Fopen::test($args) ) { + $working_transport['fopen'] = new WP_Http_Fopen(); + $blocking_transport[] = &$working_transport['fopen']; + } else if ( true === WP_Http_Fsockopen::test($args) ) { + $working_transport['fsockopen'] = new WP_Http_Fsockopen(); + $blocking_transport[] = &$working_transport['fsockopen']; + } + + foreach ( array('curl', 'streams', 'fopen', 'fsockopen', 'exthttp') as $transport ) { + if ( isset($working_transport[$transport]) ) + $nonblocking_transport[] = &$working_transport[$transport]; + } + } + + if ( has_filter('http_transport_get_debug') ) + do_action('http_transport_get_debug', $working_transport, $blocking_transport, $nonblocking_transport); + + if ( isset($args['blocking']) && !$args['blocking'] ) + return $nonblocking_transport; + else + return $blocking_transport; + } + + /** + * Tests the WordPress HTTP objects for an object to use and returns it. + * + * Tests all of the objects and returns the object that passes. Also caches + * that object to be used later. This is for posting content to a URL and + * is used when there is a body. The plain Fopen Transport can not be used + * to send content, but the streams transport can. This is a limitation that + * is addressed here, by just not including that transport. + * + * @since 2.7.0 + * @access private + * + * @param array $args Request args, default us an empty array + * @return object|null Null if no transports are available, HTTP transport object. + */ + function &_postTransport( $args = array() ) { + static $working_transport, $blocking_transport, $nonblocking_transport; + + if ( is_null($working_transport) ) { + if ( true === WP_Http_ExtHttp::test($args) ) { + $working_transport['exthttp'] = new WP_Http_ExtHttp(); + $blocking_transport[] = &$working_transport['exthttp']; + } else if ( true === WP_Http_Curl::test($args) ) { + $working_transport['curl'] = new WP_Http_Curl(); + $blocking_transport[] = &$working_transport['curl']; + } else if ( true === WP_Http_Streams::test($args) ) { + $working_transport['streams'] = new WP_Http_Streams(); + $blocking_transport[] = &$working_transport['streams']; + } else if ( true === WP_Http_Fsockopen::test($args) ) { + $working_transport['fsockopen'] = new WP_Http_Fsockopen(); + $blocking_transport[] = &$working_transport['fsockopen']; + } + + foreach ( array('curl', 'streams', 'fsockopen', 'exthttp') as $transport ) { + if ( isset($working_transport[$transport]) ) + $nonblocking_transport[] = &$working_transport[$transport]; + } + } + + if ( has_filter('http_transport_post_debug') ) + do_action('http_transport_post_debug', $working_transport, $blocking_transport, $nonblocking_transport); + + if ( isset($args['blocking']) && !$args['blocking'] ) + return $nonblocking_transport; + else + return $blocking_transport; + } + + /** + * Send a HTTP request to a URI. + * + * The body and headers are part of the arguments. The 'body' argument is for the body and will + * accept either a string or an array. The 'headers' argument should be an array, but a string + * is acceptable. If the 'body' argument is an array, then it will automatically be escaped + * using http_build_query(). + * + * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS + * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send + * headers. Other protocols are unsupported and most likely will fail. + * + * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and + * 'user-agent'. + * + * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow + * others, but should not be assumed. The 'timeout' is used to sent how long the connection + * should stay open before failing when no response. 'redirection' is used to track how many + * redirects were taken and used to sent the amount for other transports, but not all transports + * accept setting that value. + * + * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and + * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The + * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is + * 'WordPress/WP_Version', where WP_Version is the value from $wp_version. + * + * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP + * while it performs the request or continue regardless. Actually, that isn't entirely correct. + * Blocking mode really just means whether the fread should just pull what it can whenever it + * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading + * the entire content. It doesn't actually always mean that PHP will continue going after making + * the request. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return array containing 'headers', 'body', 'response', 'cookies' + */ + function request( $url, $args = array() ) { + global $wp_version; + + $defaults = array( + 'method' => 'GET', + 'timeout' => apply_filters( 'http_request_timeout', 5), + 'redirection' => apply_filters( 'http_request_redirection_count', 5), + 'httpversion' => apply_filters( 'http_request_version', '1.0'), + 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ), + 'blocking' => true, + 'headers' => array(), + 'cookies' => array(), + 'body' => null, + 'compress' => false, + 'decompress' => true, + 'sslverify' => true + ); + + $r = wp_parse_args( $args, $defaults ); + $r = apply_filters( 'http_request_args', $r, $url ); + + $arrURL = parse_url($url); + + if ( $this->block_request( $url ) ) + return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.')); + + // Determine if this is a https call and pass that on to the transport functions + // so that we can blacklist the transports that do not support ssl verification + $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl'; + + // Determine if this request is to OUR install of WordPress + $homeURL = parse_url(get_bloginfo('url')); + $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host']; + unset($homeURL); + + if ( is_null( $r['headers'] ) ) + $r['headers'] = array(); + + if ( ! is_array($r['headers']) ) { + $processedHeaders = WP_Http::processHeaders($r['headers']); + $r['headers'] = $processedHeaders['headers']; + } + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } + + if ( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + if ( WP_Http_Encoding::is_available() ) + $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding(); + + if ( is_null($r['body']) ) { + // Some servers fail when sending content without the content-length + // header being set. + $r['headers']['Content-Length'] = 0; + $transports = WP_Http::_getTransport($r); + } else { + if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) { + if ( ! version_compare(phpversion(), '5.1.2', '>=') ) + $r['body'] = _http_build_query($r['body'], null, '&'); + else + $r['body'] = http_build_query($r['body'], null, '&'); + $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'); + $r['headers']['Content-Length'] = strlen($r['body']); + } + + if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) ) + $r['headers']['Content-Length'] = strlen($r['body']); + + $transports = WP_Http::_postTransport($r); + } + + if ( has_action('http_api_debug') ) + do_action('http_api_debug', $transports, 'transports_list'); + + $response = array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + foreach ( (array) $transports as $transport ) { + $response = $transport->request($url, $r); + + if ( has_action('http_api_debug') ) + do_action( 'http_api_debug', $response, 'response', get_class($transport) ); + + if ( ! is_wp_error($response) ) + return $response; + } + + return $response; + } + + /** + * Uses the POST HTTP method. + * + * Used for sending data that is expected to be in the body. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return boolean + */ + function post($url, $args = array()) { + $defaults = array('method' => 'POST'); + $r = wp_parse_args( $args, $defaults ); + return $this->request($url, $r); + } + + /** + * Uses the GET HTTP method. + * + * Used for sending data that is expected to be in the body. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return boolean + */ + function get($url, $args = array()) { + $defaults = array('method' => 'GET'); + $r = wp_parse_args( $args, $defaults ); + return $this->request($url, $r); + } + + /** + * Uses the HEAD HTTP method. + * + * Used for sending data that is expected to be in the body. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return boolean + */ + function head($url, $args = array()) { + $defaults = array('method' => 'HEAD'); + $r = wp_parse_args( $args, $defaults ); + return $this->request($url, $r); + } + + /** + * Parses the responses and splits the parts into headers and body. + * + * @access public + * @static + * @since 2.7.0 + * + * @param string $strResponse The full response string + * @return array Array with 'headers' and 'body' keys. + */ + function processResponse($strResponse) { + list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2); + return array('headers' => $theHeaders, 'body' => $theBody); + } + + /** + * Transform header string into an array. + * + * If an array is given then it is assumed to be raw header data with numeric keys with the + * headers as the values. No headers must be passed that were already processed. + * + * @access public + * @static + * @since 2.7.0 + * + * @param string|array $headers + * @return array Processed string headers. If duplicate headers are encountered, + * Then a numbered array is returned as the value of that header-key. + */ + function processHeaders($headers) { + // split headers, one per array element + if ( is_string($headers) ) { + // tolerate line terminator: CRLF = LF (RFC 2616 19.3) + $headers = str_replace("\r\n", "\n", $headers); + // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) , (RFC 2616 2.2) + $headers = preg_replace('/\n[ \t]/', ' ', $headers); + // create the headers array + $headers = explode("\n", $headers); + } + + $response = array('code' => 0, 'message' => ''); + + $cookies = array(); + $newheaders = array(); + foreach ( $headers as $tempheader ) { + if ( empty($tempheader) ) + continue; + + if ( false === strpos($tempheader, ':') ) { + list( , $iResponseCode, $strResponseMsg) = explode(' ', $tempheader, 3); + $response['code'] = $iResponseCode; + $response['message'] = $strResponseMsg; + continue; + } + + list($key, $value) = explode(':', $tempheader, 2); + + if ( !empty( $value ) ) { + $key = strtolower( $key ); + if ( isset( $newheaders[$key] ) ) { + $newheaders[$key] = array( $newheaders[$key], trim( $value ) ); + } else { + $newheaders[$key] = trim( $value ); + } + if ( 'set-cookie' == strtolower( $key ) ) + $cookies[] = new WP_Http_Cookie( $value ); + } + } + + return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies); + } + + /** + * Takes the arguments for a ::request() and checks for the cookie array. + * + * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed + * into strings and added to the Cookie: header (within the arguments array). Edits the array by + * reference. + * + * @access public + * @version 2.8.0 + * @static + * + * @param array $r Full array of args passed into ::request() + */ + function buildCookieHeader( &$r ) { + if ( ! empty($r['cookies']) ) { + $cookies_header = ''; + foreach ( (array) $r['cookies'] as $cookie ) { + $cookies_header .= $cookie->getHeaderValue() . '; '; + } + $cookies_header = substr( $cookies_header, 0, -2 ); + $r['headers']['cookie'] = $cookies_header; + } + } + + /** + * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. + * + * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support + * returning footer headers. Shouldn't be too difficult to support it though. + * + * @todo Add support for footer chunked headers. + * @access public + * @since 2.7.0 + * @static + * + * @param string $body Body content + * @return string Chunked decoded body on success or raw body on failure. + */ + function chunkTransferDecode($body) { + $body = str_replace(array("\r\n", "\r"), "\n", $body); + // The body is not chunked encoding or is malformed. + if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) ) + return $body; + + $parsedBody = ''; + //$parsedHeaders = array(); Unsupported + + while ( true ) { + $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match ); + + if ( $hasChunk ) { + if ( empty( $match[1] ) ) + return $body; + + $length = hexdec( $match[1] ); + $chunkLength = strlen( $match[0] ); + + $strBody = substr($body, $chunkLength, $length); + $parsedBody .= $strBody; + + $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n"); + + if ( "0" == trim($body) ) + return $parsedBody; // Ignore footer headers. + } else { + return $body; + } + } + } + + /** + * Block requests through the proxy. + * + * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will + * prevent plugins from working and core functionality, if you don't include api.wordpress.org. + * + * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL in your wp-config.php file + * and this will only allow localhost and your blog to make requests. The constant + * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the + * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow. + * + * @since 2.8.0 + * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests. + * + * @param string $uri URI of url. + * @return bool True to block, false to allow. + */ + function block_request($uri) { + // We don't need to block requests, because nothing is blocked. + if ( ! defined('WP_HTTP_BLOCK_EXTERNAL') || ( defined('WP_HTTP_BLOCK_EXTERNAL') && WP_HTTP_BLOCK_EXTERNAL == false ) ) + return false; + + // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure. + // This will be displayed on blogs, which is not reasonable. + $check = @parse_url($uri); + + /* Malformed URL, can not process, but this could mean ssl, so let through anyway. + * + * This isn't very security sound. There are instances where a hacker might attempt + * to bypass the proxy and this check. However, the reason for this behavior is that + * WordPress does not do any checking currently for non-proxy requests, so it is keeps with + * the default unsecure nature of the HTTP request. + */ + if ( $check === false ) + return false; + + $home = parse_url( get_option('siteurl') ); + + // Don't block requests back to ourselves by default + if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) + return apply_filters('block_local_requests', false); + + if ( !defined('WP_ACCESSIBLE_HOSTS') ) + return true; + + static $accessible_hosts; + if ( null == $accessible_hosts ) + $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS); + + return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it. + } +} + +/** + * HTTP request method uses fsockopen function to retrieve the url. + * + * This would be the preferred method, but the fsockopen implementation has the most overhead of all + * the HTTP transport implementations. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_Fsockopen { + /** + * Send a HTTP request to a URI using fsockopen(). + * + * Does not support non-blocking mode. + * + * @see WP_Http::request For default options descriptions. + * + * @since 2.7 + * @access public + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + $iError = null; // Store error number + $strError = null; // Store error string + + $arrURL = parse_url($url); + + $fsockopen_host = $arrURL['host']; + + $secure_transport = false; + + if ( ! isset( $arrURL['port'] ) ) { + if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) { + $fsockopen_host = "ssl://$fsockopen_host"; + $arrURL['port'] = 443; + $secure_transport = true; + } else { + $arrURL['port'] = 80; + } + } + + // There are issues with the HTTPS and SSL protocols that cause errors that can be safely + // ignored and should be ignored. + if ( true === $secure_transport ) + $error_reporting = error_reporting(0); + + $startDelay = time(); + + $proxy = new WP_HTTP_Proxy(); + + if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) { + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) + $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] ); + else + $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] ); + } else { + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) + $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] ); + else + $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] ); + } + + $endDelay = time(); + + // If the delay is greater than the timeout then fsockopen should't be used, because it will + // cause a long delay. + $elapseDelay = ($endDelay-$startDelay) > $r['timeout']; + if ( true === $elapseDelay ) + add_option( 'disable_fsockopen', $endDelay, null, true ); + + if ( false === $handle ) + return new WP_Error('http_request_failed', $iError . ': ' . $strError); + + stream_set_timeout($handle, $r['timeout'] ); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field. + $requestPath = $url; + else + $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' ); + + if ( empty($requestPath) ) + $requestPath .= '/'; + + $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n"; + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) + $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n"; + else + $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n"; + + if ( isset($r['user-agent']) ) + $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n"; + + if ( is_array($r['headers']) ) { + foreach ( (array) $r['headers'] as $header => $headerValue ) + $strHeaders .= $header . ': ' . $headerValue . "\r\n"; + } else { + $strHeaders .= $r['headers']; + } + + if ( $proxy->use_authentication() ) + $strHeaders .= $proxy->authentication_header() . "\r\n"; + + $strHeaders .= "\r\n"; + + if ( ! is_null($r['body']) ) + $strHeaders .= $r['body']; + + fwrite($handle, $strHeaders); + + if ( ! $r['blocking'] ) { + fclose($handle); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $strResponse = ''; + while ( ! feof($handle) ) + $strResponse .= fread($handle, 4096); + + fclose($handle); + + if ( true === $secure_transport ) + error_reporting($error_reporting); + + $process = WP_Http::processResponse($strResponse); + $arrHeaders = WP_Http::processHeaders($process['headers']); + + // Is the response code within the 400 range? + if ( (int) $arrHeaders['response']['code'] >= 400 && (int) $arrHeaders['response']['code'] < 500 ) + return new WP_Error('http_request_failed', $arrHeaders['response']['code'] . ': ' . $arrHeaders['response']['message']); + + // If location is found, then assume redirect and redirect to location. + if ( isset($arrHeaders['headers']['location']) ) { + if ( $r['redirection']-- > 0 ) { + return $this->request($arrHeaders['headers']['location'], $r); + } else { + return new WP_Error('http_request_failed', __('Too many redirects.')); + } + } + + // If the body was chunk encoded, then decode it. + if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] ) + $process['body'] = WP_Http::chunkTransferDecode($process['body']); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) ) + $process['body'] = WP_Http_Encoding::decompress( $process['body'] ); + + return array('headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @since 2.7.0 + * @static + * @return boolean False means this class can not be used, true means it can. + */ + function test( $args = array() ) { + if ( false !== ($option = get_option( 'disable_fsockopen' )) && time()-$option < 43200 ) // 12 hours + return false; + + $is_ssl = isset($args['ssl']) && $args['ssl']; + + if ( ! $is_ssl && function_exists( 'fsockopen' ) ) + $use = true; + elseif ( $is_ssl && extension_loaded('openssl') && function_exists( 'fsockopen' ) ) + $use = true; + else + $use = false; + + return apply_filters('use_fsockopen_transport', $use, $args); + } +} + +/** + * HTTP request method uses fopen function to retrieve the url. + * + * Requires PHP version greater than 4.3.0 for stream support. Does not allow for $context support, + * but should still be okay, to write the headers, before getting the response. Also requires that + * 'allow_url_fopen' to be enabled. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_Fopen { + /** + * Send a HTTP request to a URI using fopen(). + * + * This transport does not support sending of headers and body, therefore should not be used in + * the instances, where there is a body and headers. + * + * Notes: Does not support non-blocking mode. Ignores 'redirection' option. + * + * @see WP_Http::retrieve For default options descriptions. + * + * @access public + * @since 2.7.0 + * + * @param string $url URI resource. + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + $arrURL = parse_url($url); + + if ( false === $arrURL ) + return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url)); + + if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] ) + $url = str_replace($arrURL['scheme'], 'http', $url); + + if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) + $handle = @fopen($url, 'r'); + else + $handle = fopen($url, 'r'); + + if (! $handle) + return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url)); + + stream_set_timeout($handle, $r['timeout'] ); + + if ( ! $r['blocking'] ) { + fclose($handle); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $strResponse = ''; + while ( ! feof($handle) ) + $strResponse .= fread($handle, 4096); + + if ( function_exists('stream_get_meta_data') ) { + $meta = stream_get_meta_data($handle); + $theHeaders = $meta['wrapper_data']; + if ( isset( $meta['wrapper_data']['headers'] ) ) + $theHeaders = $meta['wrapper_data']['headers']; + } else { + //$http_response_header is a PHP reserved variable which is set in the current-scope when using the HTTP Wrapper + //see http://php.oregonstate.edu/manual/en/reserved.variables.httpresponseheader.php + $theHeaders = $http_response_header; + } + + fclose($handle); + + $processedHeaders = WP_Http::processHeaders($theHeaders); + + if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] ) + $strResponse = WP_Http::chunkTransferDecode($strResponse); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) ) + $strResponse = WP_Http_Encoding::decompress( $strResponse ); + + return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @since 2.7.0 + * @static + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) ) + return false; + + $use = true; + + //PHP does not verify SSL certs, We can only make a request via this transports if SSL Verification is turned off. + $is_ssl = isset($args['ssl']) && $args['ssl']; + if ( $is_ssl ) { + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local && true != apply_filters('https_local_ssl_verify', true) ) + $use = true; + elseif ( !$is_local && true != apply_filters('https_ssl_verify', true) ) + $use = true; + elseif ( !$ssl_verify ) + $use = true; + else + $use = false; + } + + return apply_filters('use_fopen_transport', $use, $args); + } +} + +/** + * HTTP request method uses Streams to retrieve the url. + * + * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting + * to be enabled. + * + * Second preferred method for getting the URL, for PHP 5. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_Streams { + /** + * Send a HTTP request to a URI using streams with fopen(). + * + * @access public + * @since 2.7.0 + * + * @param string $url + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + $arrURL = parse_url($url); + + if ( false === $arrURL ) + return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url)); + + if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] ) + $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url); + + // Convert Header array to string. + $strHeaders = ''; + if ( is_array( $r['headers'] ) ) + foreach ( $r['headers'] as $name => $value ) + $strHeaders .= "{$name}: $value\r\n"; + else if ( is_string( $r['headers'] ) ) + $strHeaders = $r['headers']; + + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local ) + $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); + elseif ( ! $is_local ) + $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); + + $arrContext = array('http' => + array( + 'method' => strtoupper($r['method']), + 'user_agent' => $r['user-agent'], + 'max_redirects' => $r['redirection'], + 'protocol_version' => (float) $r['httpversion'], + 'header' => $strHeaders, + 'timeout' => $r['timeout'], + 'ssl' => array( + 'verify_peer' => $ssl_verify, + 'verify_host' => $ssl_verify + ) + ) + ); + + $proxy = new WP_HTTP_Proxy(); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { + $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port(); + $arrContext['http']['request_fulluri'] = true; + + // We only support Basic authentication so this will only work if that is what your proxy supports. + if ( $proxy->use_authentication() ) + $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n"; + } + + if ( ! is_null($r['body']) && ! empty($r['body'] ) ) + $arrContext['http']['content'] = $r['body']; + + $context = stream_context_create($arrContext); + + if ( ! defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) + $handle = @fopen($url, 'r', false, $context); + else + $handle = fopen($url, 'r', false, $context); + + if ( ! $handle) + return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url)); + + // WordPress supports PHP 4.3, which has this function. Removed sanity checking for + // performance reasons. + stream_set_timeout($handle, $r['timeout'] ); + + if ( ! $r['blocking'] ) { + stream_set_blocking($handle, 0); + fclose($handle); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $strResponse = stream_get_contents($handle); + $meta = stream_get_meta_data($handle); + + fclose($handle); + + $processedHeaders = array(); + if ( isset( $meta['wrapper_data']['headers'] ) ) + $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']); + else + $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']); + + if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] ) + $strResponse = WP_Http::chunkTransferDecode($strResponse); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) ) + $strResponse = WP_Http_Encoding::decompress( $strResponse ); + + return array('headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @static + * @access public + * @since 2.7.0 + * + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + if ( ! function_exists('fopen') || (function_exists('ini_get') && true != ini_get('allow_url_fopen')) ) + return false; + + if ( version_compare(PHP_VERSION, '5.0', '<') ) + return false; + + //HTTPS via Proxy was added in 5.1.0 + $is_ssl = isset($args['ssl']) && $args['ssl']; + if ( $is_ssl && version_compare(PHP_VERSION, '5.1.0', '<') ) { + $proxy = new WP_HTTP_Proxy(); + /** + * No URL check, as its not currently passed to the ::test() function + * In the case where a Proxy is in use, Just bypass this transport for HTTPS. + */ + if ( $proxy->is_enabled() ) + return false; + } + + return apply_filters('use_streams_transport', true, $args); + } +} + +/** + * HTTP request method uses HTTP extension to retrieve the url. + * + * Requires the HTTP extension to be installed. This would be the preferred transport since it can + * handle a lot of the problems that forces the others to use the HTTP version 1.0. Even if PHP 5.2+ + * is being used, it doesn't mean that the HTTP extension will be enabled. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7.0 + */ +class WP_Http_ExtHTTP { + /** + * Send a HTTP request to a URI using HTTP extension. + * + * Does not support non-blocking. + * + * @access public + * @since 2.7 + * + * @param string $url + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set + WP_Http::buildCookieHeader( $r ); + + switch ( $r['method'] ) { + case 'POST': + $r['method'] = HTTP_METH_POST; + break; + case 'HEAD': + $r['method'] = HTTP_METH_HEAD; + break; + case 'GET': + default: + $r['method'] = HTTP_METH_GET; + } + + $arrURL = parse_url($url); + + if ( 'http' != $arrURL['scheme'] || 'https' != $arrURL['scheme'] ) + $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url); + + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local ) + $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); + elseif ( ! $is_local ) + $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); + + $options = array( + 'timeout' => $r['timeout'], + 'connecttimeout' => $r['timeout'], + 'redirect' => $r['redirection'], + 'useragent' => $r['user-agent'], + 'headers' => $r['headers'], + 'ssl' => array( + 'verifypeer' => $ssl_verify, + 'verifyhost' => $ssl_verify + ) + ); + + // The HTTP extensions offers really easy proxy support. + $proxy = new WP_HTTP_Proxy(); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { + $options['proxyhost'] = $proxy->host(); + $options['proxyport'] = $proxy->port(); + $options['proxytype'] = HTTP_PROXY_HTTP; + + if ( $proxy->use_authentication() ) { + $options['proxyauth'] = $proxy->authentication(); + $options['proxyauthtype'] = HTTP_AUTH_BASIC; + } + } + + if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) //Emits warning level notices for max redirects and timeouts + $strResponse = @http_request($r['method'], $url, $r['body'], $options, $info); + else + $strResponse = http_request($r['method'], $url, $r['body'], $options, $info); //Emits warning level notices for max redirects and timeouts + + // Error may still be set, Response may return headers or partial document, and error + // contains a reason the request was aborted, eg, timeout expired or max-redirects reached. + if ( false === $strResponse || ! empty($info['error']) ) + return new WP_Error('http_request_failed', $info['response_code'] . ': ' . $info['error']); + + if ( ! $r['blocking'] ) + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + + list($theHeaders, $theBody) = explode("\r\n\r\n", $strResponse, 2); + $theHeaders = WP_Http::processHeaders($theHeaders); + + if ( ! empty( $theBody ) && isset( $theHeaders['headers']['transfer-encoding'] ) && 'chunked' == $theHeaders['headers']['transfer-encoding'] ) { + if ( !defined('WP_DEBUG') || ( defined('WP_DEBUG') && false === WP_DEBUG ) ) + $theBody = @http_chunked_decode($theBody); + else + $theBody = http_chunked_decode($theBody); + } + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) ) + $theBody = http_inflate( $theBody ); + + $theResponse = array(); + $theResponse['code'] = $info['response_code']; + $theResponse['message'] = get_status_header_desc($info['response_code']); + + return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $theResponse, 'cookies' => $theHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @static + * @since 2.7.0 + * + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + return apply_filters('use_http_extension_transport', function_exists('http_request'), $args ); + } +} + +/** + * HTTP request method uses Curl extension to retrieve the url. + * + * Requires the Curl extension to be installed. + * + * @package WordPress + * @subpackage HTTP + * @since 2.7 + */ +class WP_Http_Curl { + + /** + * Send a HTTP request to a URI using cURL extension. + * + * @access public + * @since 2.7.0 + * + * @param string $url + * @param str|array $args Optional. Override the defaults. + * @return array 'headers', 'body', 'cookies' and 'response' keys. + */ + function request($url, $args = array()) { + $defaults = array( + 'method' => 'GET', 'timeout' => 5, + 'redirection' => 5, 'httpversion' => '1.0', + 'blocking' => true, + 'headers' => array(), 'body' => null, 'cookies' => array() + ); + + $r = wp_parse_args( $args, $defaults ); + + if ( isset($r['headers']['User-Agent']) ) { + $r['user-agent'] = $r['headers']['User-Agent']; + unset($r['headers']['User-Agent']); + } else if( isset($r['headers']['user-agent']) ) { + $r['user-agent'] = $r['headers']['user-agent']; + unset($r['headers']['user-agent']); + } + + // Construct Cookie: header if any cookies are set. + WP_Http::buildCookieHeader( $r ); + + // cURL extension will sometimes fail when the timeout is less than 1 as it may round down + // to 0, which gives it unlimited timeout. + if ( $r['timeout'] > 0 && $r['timeout'] < 1 ) + $r['timeout'] = 1; + + $handle = curl_init(); + + // cURL offers really easy proxy support. + $proxy = new WP_HTTP_Proxy(); + + if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { + + $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>='); + + if ( $isPHP5 ) { + curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP ); + curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() ); + curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() ); + } else { + curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() .':'. $proxy->port() ); + } + + if ( $proxy->use_authentication() ) { + if ( $isPHP5 ) + curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_BASIC ); + + curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() ); + } + } + + $is_local = isset($args['local']) && $args['local']; + $ssl_verify = isset($args['sslverify']) && $args['sslverify']; + if ( $is_local ) + $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); + elseif ( ! $is_local ) + $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); + + curl_setopt( $handle, CURLOPT_URL, $url); + curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify ); + curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify ); + curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] ); + curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $r['timeout'] ); + curl_setopt( $handle, CURLOPT_TIMEOUT, $r['timeout'] ); + curl_setopt( $handle, CURLOPT_MAXREDIRS, $r['redirection'] ); + + switch ( $r['method'] ) { + case 'HEAD': + curl_setopt( $handle, CURLOPT_NOBODY, true ); + break; + case 'POST': + curl_setopt( $handle, CURLOPT_POST, true ); + curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] ); + break; + } + + if ( true === $r['blocking'] ) + curl_setopt( $handle, CURLOPT_HEADER, true ); + else + curl_setopt( $handle, CURLOPT_HEADER, false ); + + // The option doesn't work with safe mode or when open_basedir is set. + if ( !ini_get('safe_mode') && !ini_get('open_basedir') ) + curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, true ); + + if ( !empty( $r['headers'] ) ) { + // cURL expects full header strings in each element + $headers = array(); + foreach ( $r['headers'] as $name => $value ) { + $headers[] = "{$name}: $value"; + } + curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers ); + } + + if ( $r['httpversion'] == '1.0' ) + curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 ); + else + curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 ); + + // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it + // themselves... Although, it is somewhat pointless without some reference. + do_action_ref_array( 'http_api_curl', array(&$handle) ); + + // We don't need to return the body, so don't. Just execute request and return. + if ( ! $r['blocking'] ) { + curl_exec( $handle ); + curl_close( $handle ); + return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); + } + + $theResponse = curl_exec( $handle ); + + if ( !empty($theResponse) ) { + $parts = explode("\r\n\r\n", $theResponse); + + $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE); + $theHeaders = trim( substr($theResponse, 0, $headerLength) ); + $theBody = substr( $theResponse, $headerLength ); + if ( false !== strrpos($theHeaders, "\r\n\r\n") ) { + $headerParts = explode("\r\n\r\n", $theHeaders); + $theHeaders = $headerParts[ count($headerParts) -1 ]; + } + $theHeaders = WP_Http::processHeaders($theHeaders); + } else { + if ( $curl_error = curl_error($handle) ) + return new WP_Error('http_request_failed', $curl_error); + if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array(301, 302) ) ) + return new WP_Error('http_request_failed', __('Too many redirects.')); + + $theHeaders = array( 'headers' => array(), 'cookies' => array() ); + $theBody = ''; + } + + $response = array(); + $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE ); + $response['message'] = get_status_header_desc($response['code']); + + curl_close( $handle ); + + if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) ) + $theBody = WP_Http_Encoding::decompress( $theBody ); + + return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']); + } + + /** + * Whether this class can be used for retrieving an URL. + * + * @static + * @since 2.7.0 + * + * @return boolean False means this class can not be used, true means it can. + */ + function test($args = array()) { + if ( function_exists('curl_init') && function_exists('curl_exec') ) + return apply_filters('use_curl_transport', true, $args); + + return false; + } +} + +/** + * Adds Proxy support to the WordPress HTTP API. + * + * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to + * enable proxy support. There are also a few filters that plugins can hook into for some of the + * constants. + * + * The constants are as follows: + *
      + *
    1. WP_PROXY_HOST - Enable proxy support and host for connecting.
    2. + *
    3. WP_PROXY_PORT - Proxy port for connection. No default, must be defined.
    4. + *
    5. WP_PROXY_USERNAME - Proxy username, if it requires authentication.
    6. + *
    7. WP_PROXY_PASSWORD - Proxy password, if it requires authentication.
    8. + *
    9. WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy. + * You do not need to have localhost and the blog host in this list, because they will not be passed + * through the proxy. The list should be presented in a comma separated list
    10. + *
    + * + * An example can be as seen below. + * + * define('WP_PROXY_HOST', '192.168.84.101'); + * define('WP_PROXY_PORT', '8080'); + * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com'); + * + * + * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress. + * @since 2.8 + */ +class WP_HTTP_Proxy { + + /** + * Whether proxy connection should be used. + * + * @since 2.8 + * @use WP_PROXY_HOST + * @use WP_PROXY_PORT + * + * @return bool + */ + function is_enabled() { + return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT'); + } + + /** + * Whether authentication should be used. + * + * @since 2.8 + * @use WP_PROXY_USERNAME + * @use WP_PROXY_PASSWORD + * + * @return bool + */ + function use_authentication() { + return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD'); + } + + /** + * Retrieve the host for the proxy server. + * + * @since 2.8 + * + * @return string + */ + function host() { + if ( defined('WP_PROXY_HOST') ) + return WP_PROXY_HOST; + + return ''; + } + + /** + * Retrieve the port for the proxy server. + * + * @since 2.8 + * + * @return string + */ + function port() { + if ( defined('WP_PROXY_PORT') ) + return WP_PROXY_PORT; + + return ''; + } + + /** + * Retrieve the username for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function username() { + if ( defined('WP_PROXY_USERNAME') ) + return WP_PROXY_USERNAME; + + return ''; + } + + /** + * Retrieve the password for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function password() { + if ( defined('WP_PROXY_PASSWORD') ) + return WP_PROXY_PASSWORD; + + return ''; + } + + /** + * Retrieve authentication string for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function authentication() { + return $this->username() . ':' . $this->password(); + } + + /** + * Retrieve header string for proxy authentication. + * + * @since 2.8 + * + * @return string + */ + function authentication_header() { + return 'Proxy-Authentication: Basic ' . base64_encode( $this->authentication() ); + } + + /** + * Whether URL should be sent through the proxy server. + * + * We want to keep localhost and the blog URL from being sent through the proxy server, because + * some proxies can not handle this. We also have the constant available for defining other + * hosts that won't be sent through the proxy. + * + * @uses WP_PROXY_BYPASS_HOSTS + * @since unknown + * + * @param string $uri URI to check. + * @return bool True, to send through the proxy and false if, the proxy should not be used. + */ + function send_through_proxy( $uri ) { + // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure. + // This will be displayed on blogs, which is not reasonable. + $check = @parse_url($uri); + + // Malformed URL, can not process, but this could mean ssl, so let through anyway. + if ( $check === false ) + return true; + + $home = parse_url( get_option('siteurl') ); + + if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) + return false; + + if ( !defined('WP_PROXY_BYPASS_HOSTS') ) + return true; + + static $bypass_hosts; + if ( null == $bypass_hosts ) + $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS); + + return !in_array( $check['host'], $bypass_hosts ); + } +} +/** + * Internal representation of a single cookie. + * + * Returned cookies are represented using this class, and when cookies are set, if they are not + * already a WP_Http_Cookie() object, then they are turned into one. + * + * @todo The WordPress convention is to use underscores instead of camelCase for function and method + * names. Need to switch to use underscores instead for the methods. + * + * @package WordPress + * @subpackage HTTP + * @since 2.8.0 + * @author Beau Lebens + */ +class WP_Http_Cookie { + + /** + * Cookie name. + * + * @since 2.8.0 + * @var string + */ + var $name; + + /** + * Cookie value. + * + * @since 2.8.0 + * @var string + */ + var $value; + + /** + * When the cookie expires. + * + * @since 2.8.0 + * @var string + */ + var $expires; + + /** + * Cookie URL path. + * + * @since 2.8.0 + * @var string + */ + var $path; + + /** + * Cookie Domain. + * + * @since 2.8.0 + * @var string + */ + var $domain; + + /** + * PHP4 style Constructor - Calls PHP5 Style Constructor. + * + * @access public + * @since 2.8.0 + * @param string|array $data Raw cookie data. + */ + function WP_Http_Cookie( $data ) { + $this->__construct( $data ); + } + + /** + * Sets up this cookie object. + * + * The parameter $data should be either an associative array containing the indices names below + * or a header string detailing it. + * + * If it's an array, it should include the following elements: + *
      + *
    1. Name
    2. + *
    3. Value - should NOT be urlencoded already.
    4. + *
    5. Expires - (optional) String or int (UNIX timestamp).
    6. + *
    7. Path (optional)
    8. + *
    9. Domain (optional)
    10. + *
    + * + * @access public + * @since 2.8.0 + * + * @param string|array $data Raw cookie data. + */ + function __construct( $data ) { + if ( is_string( $data ) ) { + // Assume it's a header string direct from a previous request + $pairs = explode( ';', $data ); + + // Special handling for first pair; name=value. Also be careful of "=" in value + $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) ); + $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 ); + $this->name = $name; + $this->value = urldecode( $value ); + array_shift( $pairs ); //Removes name=value from items. + + // Set everything else as a property + foreach ( $pairs as $pair ) { + if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair + continue; + + list( $key, $val ) = explode( '=', $pair ); + $key = strtolower( trim( $key ) ); + if ( 'expires' == $key ) + $val = strtotime( $val ); + $this->$key = $val; + } + } else { + if ( !isset( $data['name'] ) ) + return false; + + // Set properties based directly on parameters + $this->name = $data['name']; + $this->value = isset( $data['value'] ) ? $data['value'] : ''; + $this->path = isset( $data['path'] ) ? $data['path'] : ''; + $this->domain = isset( $data['domain'] ) ? $data['domain'] : ''; + + if ( isset( $data['expires'] ) ) + $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] ); + else + $this->expires = null; + } + } + + /** + * Confirms that it's OK to send this cookie to the URL checked against. + * + * Decision is based on RFC 2109/2965, so look there for details on validity. + * + * @access public + * @since 2.8.0 + * + * @param string $url URL you intend to send this cookie to + * @return boolean TRUE if allowed, FALSE otherwise. + */ + function test( $url ) { + // Expires - if expired then nothing else matters + if ( time() > $this->expires ) + return false; + + // Get details on the URL we're thinking about sending to + $url = parse_url( $url ); + $url['port'] = isset( $url['port'] ) ? $url['port'] : 80; + $url['path'] = isset( $url['path'] ) ? $url['path'] : '/'; + + // Values to use for comparison against the URL + $path = isset( $this->path ) ? $this->path : '/'; + $port = isset( $this->port ) ? $this->port : 80; + $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] ); + if ( false === stripos( $domain, '.' ) ) + $domain .= '.local'; + + // Host - very basic check that the request URL ends with the domain restriction (minus leading dot) + $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain; + if ( substr( $url['host'], -strlen( $domain ) ) != $domain ) + return false; + + // Port - supports "port-lists" in the format: "80,8000,8080" + if ( !in_array( $url['port'], explode( ',', $port) ) ) + return false; + + // Path - request path must start with path restriction + if ( substr( $url['path'], 0, strlen( $path ) ) != $path ) + return false; + + return true; + } + + /** + * Convert cookie name and value back to header string. + * + * @access public + * @since 2.8.0 + * + * @return string Header encoded cookie name and value. + */ + function getHeaderValue() { + if ( empty( $this->name ) || empty( $this->value ) ) + return ''; + + return $this->name . '=' . urlencode( $this->value ); + } + + /** + * Retrieve cookie header for usage in the rest of the WordPress HTTP API. + * + * @access public + * @since 2.8.0 + * + * @return string + */ + function getFullHeader() { + return 'Cookie: ' . $this->getHeaderValue(); + } +} + +/** + * Implementation for deflate and gzip transfer encodings. + * + * Includes RFC 1950, RFC 1951, and RFC 1952. + * + * @since 2.8 + * @package WordPress + * @subpackage HTTP + */ +class WP_Http_Encoding { + + /** + * Compress raw string using the deflate format. + * + * Supports the RFC 1951 standard. + * + * @since 2.8 + * + * @param string $raw String to compress. + * @param int $level Optional, default is 9. Compression level, 9 is highest. + * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports. + * @return string|bool False on failure. + */ + function compress( $raw, $level = 9, $supports = null ) { + return gzdeflate( $raw, $level ); + } + + /** + * Decompression of deflated string. + * + * Will attempt to decompress using the RFC 1950 standard, and if that fails + * then the RFC 1951 standard deflate will be attempted. Finally, the RFC + * 1952 standard gzip decode will be attempted. If all fail, then the + * original compressed string will be returned. + * + * @since 2.8 + * + * @param string $compressed String to decompress. + * @param int $length The optional length of the compressed data. + * @return string|bool False on failure. + */ + function decompress( $compressed, $length = null ) { + $decompressed = gzinflate( $compressed ); + + if ( false !== $decompressed ) + return $decompressed; + + $decompressed = gzuncompress( $compressed ); + + if ( false !== $decompressed ) + return $decompressed; + + if ( function_exists('gzdecode') ) { + $decompressed = gzdecode( $compressed ); + + if ( false !== $decompressed ) + return $decompressed; + } + + return $compressed; + } + + /** + * What encoding types to accept and their priority values. + * + * @since 2.8 + * + * @return string Types of encoding to accept. + */ + function accept_encoding() { + $type = array(); + if ( function_exists( 'gzinflate' ) ) + $type[] = 'deflate;q=1.0'; + + if ( function_exists( 'gzuncompress' ) ) + $type[] = 'compress;q=0.5'; + + if ( function_exists( 'gzdecode' ) ) + $type[] = 'gzip;q=0.5'; + + return implode(', ', $type); + } + + /** + * What enconding the content used when it was compressed to send in the headers. + * + * @since 2.8 + * + * @return string Content-Encoding string to send in the header. + */ + function content_encoding() { + return 'deflate'; + } + + /** + * Whether the content be decoded based on the headers. + * + * @since 2.8 + * + * @param array|string $headers All of the available headers. + * @return bool + */ + function should_decode($headers) { + if ( is_array( $headers ) ) { + if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) ) + return true; + } else if( is_string( $headers ) ) { + return ( stripos($headers, 'content-encoding:') !== false ); + } + + return false; + } + + /** + * Whether decompression and compression are supported by the PHP version. + * + * Each function is tested instead of checking for the zlib extension, to + * ensure that the functions all exist in the PHP version and aren't + * disabled. + * + * @since 2.8 + * + * @return bool + */ + function is_available() { + return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') ); + } +} + +/** + * Returns the initialized WP_Http Object + * + * @since 2.7.0 + * @access private + * + * @return WP_Http HTTP Transport object. + */ +function &_wp_http_get_object() { + static $http; + + if ( is_null($http) ) + $http = new WP_Http(); + + return $http; +} + +/** + * Retrieve the raw response from the HTTP request. + * + * The array structure is a little complex. + * + * + * $res = array( 'headers' => array(), 'response' => array('code' => int, 'message' => string) ); + * + * + * All of the headers in $res['headers'] are with the name as the key and the + * value as the value. So to get the User-Agent, you would do the following. + * + * + * $user_agent = $res['headers']['user-agent']; + * + * + * The body is the raw response content and can be retrieved from $res['body']. + * + * This function is called first to make the request and there are other API + * functions to abstract out the above convoluted setup. + * + * @since 2.7.0 + * + * @param string $url Site URL to retrieve. + * @param array $args Optional. Override the defaults. + * @return WP_Error|array The response or WP_Error on failure. + */ +function wp_remote_request($url, $args = array()) { + $objFetchSite = _wp_http_get_object(); + return $objFetchSite->request($url, $args); +} + +/** + * Retrieve the raw response from the HTTP request using the GET method. + * + * @see wp_remote_request() For more information on the response array format. + * + * @since 2.7.0 + * + * @param string $url Site URL to retrieve. + * @param array $args Optional. Override the defaults. + * @return WP_Error|array The response or WP_Error on failure. + */ +function wp_remote_get($url, $args = array()) { + $objFetchSite = _wp_http_get_object(); + return $objFetchSite->get($url, $args); +} + +/** + * Retrieve the raw response from the HTTP request using the POST method. + * + * @see wp_remote_request() For more information on the response array format. + * + * @since 2.7.0 + * + * @param string $url Site URL to retrieve. + * @param array $args Optional. Override the defaults. + * @return WP_Error|array The response or WP_Error on failure. + */ +function wp_remote_post($url, $args = array()) { + $objFetchSite = _wp_http_get_object(); + return $objFetchSite->post($url, $args); +} + +/** + * Retrieve the raw response from the HTTP request using the HEAD method. + * + * @see wp_remote_request() For more information on the response array format. + * + * @since 2.7.0 + * + * @param string $url Site URL to retrieve. + * @param array $args Optional. Override the defaults. + * @return WP_Error|array The response or WP_Error on failure. + */ +function wp_remote_head($url, $args = array()) { + $objFetchSite = _wp_http_get_object(); + return $objFetchSite->head($url, $args); +} + +/** + * Retrieve only the headers from the raw response. + * + * @since 2.7.0 + * + * @param array $response HTTP response. + * @return array The headers of the response. Empty array if incorrect parameter given. + */ +function wp_remote_retrieve_headers(&$response) { + if ( is_wp_error($response) || ! isset($response['headers']) || ! is_array($response['headers'])) + return array(); + + return $response['headers']; +} + +/** + * Retrieve a single header by name from the raw response. + * + * @since 2.7.0 + * + * @param array $response + * @param string $header Header name to retrieve value from. + * @return string The header value. Empty string on if incorrect parameter given, or if the header doesnt exist. + */ +function wp_remote_retrieve_header(&$response, $header) { + if ( is_wp_error($response) || ! isset($response['headers']) || ! is_array($response['headers'])) + return ''; + + if ( array_key_exists($header, $response['headers']) ) + return $response['headers'][$header]; + + return ''; +} + +/** + * Retrieve only the response code from the raw response. + * + * Will return an empty array if incorrect parameter value is given. + * + * @since 2.7.0 + * + * @param array $response HTTP response. + * @return string the response code. Empty string on incorrect parameter given. + */ +function wp_remote_retrieve_response_code(&$response) { + if ( is_wp_error($response) || ! isset($response['response']) || ! is_array($response['response'])) + return ''; + + return $response['response']['code']; +} + +/** + * Retrieve only the response message from the raw response. + * + * Will return an empty array if incorrect parameter value is given. + * + * @since 2.7.0 + * + * @param array $response HTTP response. + * @return string The response message. Empty string on incorrect parameter given. + */ +function wp_remote_retrieve_response_message(&$response) { + if ( is_wp_error($response) || ! isset($response['response']) || ! is_array($response['response'])) + return ''; + + return $response['response']['message']; +} + +/** + * Retrieve only the body from the raw response. + * + * @since 2.7.0 + * + * @param array $response HTTP response. + * @return string The body of the response. Empty string if no body or incorrect parameter given. + */ +function wp_remote_retrieve_body(&$response) { + if ( is_wp_error($response) || ! isset($response['body']) ) + return ''; + + return $response['body']; +} + +?> diff --git a/wp-includes/images/blank.gif b/wp-includes/images/blank.gif new file mode 100644 index 0000000..e565824 Binary files /dev/null and b/wp-includes/images/blank.gif differ diff --git a/wp-includes/images/crystal/archive.png b/wp-includes/images/crystal/archive.png new file mode 100644 index 0000000..670648a Binary files /dev/null and b/wp-includes/images/crystal/archive.png differ diff --git a/wp-includes/images/crystal/audio.png b/wp-includes/images/crystal/audio.png new file mode 100644 index 0000000..5a3d4d3 Binary files /dev/null and b/wp-includes/images/crystal/audio.png differ diff --git a/wp-includes/images/crystal/code.png b/wp-includes/images/crystal/code.png new file mode 100644 index 0000000..b67c600 Binary files /dev/null and b/wp-includes/images/crystal/code.png differ diff --git a/wp-includes/images/crystal/default.png b/wp-includes/images/crystal/default.png new file mode 100644 index 0000000..b1bbbc7 Binary files /dev/null and b/wp-includes/images/crystal/default.png differ diff --git a/wp-includes/images/crystal/document.png b/wp-includes/images/crystal/document.png new file mode 100644 index 0000000..3295ccd Binary files /dev/null and b/wp-includes/images/crystal/document.png differ diff --git a/wp-includes/images/crystal/interactive.png b/wp-includes/images/crystal/interactive.png new file mode 100644 index 0000000..fd6de7d Binary files /dev/null and b/wp-includes/images/crystal/interactive.png differ diff --git a/wp-includes/images/crystal/license.txt b/wp-includes/images/crystal/license.txt new file mode 100644 index 0000000..cdabd2f --- /dev/null +++ b/wp-includes/images/crystal/license.txt @@ -0,0 +1,9 @@ +Crystal Project Icons +by Everaldo Coelho +http://everaldo.com + +Released under LGPL + +Modified February 2008 +for WordPress +http://wordpress.org \ No newline at end of file diff --git a/wp-includes/images/crystal/spreadsheet.png b/wp-includes/images/crystal/spreadsheet.png new file mode 100644 index 0000000..f2c4d30 Binary files /dev/null and b/wp-includes/images/crystal/spreadsheet.png differ diff --git a/wp-includes/images/crystal/text.png b/wp-includes/images/crystal/text.png new file mode 100644 index 0000000..feaed5b Binary files /dev/null and b/wp-includes/images/crystal/text.png differ diff --git a/wp-includes/images/crystal/video.png b/wp-includes/images/crystal/video.png new file mode 100644 index 0000000..e1b879d Binary files /dev/null and b/wp-includes/images/crystal/video.png differ diff --git a/wp-includes/images/rss.png b/wp-includes/images/rss.png new file mode 100644 index 0000000..6e7b676 Binary files /dev/null and b/wp-includes/images/rss.png differ diff --git a/wp-includes/images/smilies/icon_arrow.gif b/wp-includes/images/smilies/icon_arrow.gif new file mode 100644 index 0000000..2880055 Binary files /dev/null and b/wp-includes/images/smilies/icon_arrow.gif differ diff --git a/wp-includes/images/smilies/icon_biggrin.gif b/wp-includes/images/smilies/icon_biggrin.gif new file mode 100644 index 0000000..d352772 Binary files /dev/null and b/wp-includes/images/smilies/icon_biggrin.gif differ diff --git a/wp-includes/images/smilies/icon_confused.gif b/wp-includes/images/smilies/icon_confused.gif new file mode 100644 index 0000000..0c49e06 Binary files /dev/null and b/wp-includes/images/smilies/icon_confused.gif differ diff --git a/wp-includes/images/smilies/icon_cool.gif b/wp-includes/images/smilies/icon_cool.gif new file mode 100644 index 0000000..cead030 Binary files /dev/null and b/wp-includes/images/smilies/icon_cool.gif differ diff --git a/wp-includes/images/smilies/icon_cry.gif b/wp-includes/images/smilies/icon_cry.gif new file mode 100644 index 0000000..7d54b1f Binary files /dev/null and b/wp-includes/images/smilies/icon_cry.gif differ diff --git a/wp-includes/images/smilies/icon_eek.gif b/wp-includes/images/smilies/icon_eek.gif new file mode 100644 index 0000000..5d39781 Binary files /dev/null and b/wp-includes/images/smilies/icon_eek.gif differ diff --git a/wp-includes/images/smilies/icon_evil.gif b/wp-includes/images/smilies/icon_evil.gif new file mode 100644 index 0000000..ab1aa8e Binary files /dev/null and b/wp-includes/images/smilies/icon_evil.gif differ diff --git a/wp-includes/images/smilies/icon_exclaim.gif b/wp-includes/images/smilies/icon_exclaim.gif new file mode 100644 index 0000000..6e50e2e Binary files /dev/null and b/wp-includes/images/smilies/icon_exclaim.gif differ diff --git a/wp-includes/images/smilies/icon_idea.gif b/wp-includes/images/smilies/icon_idea.gif new file mode 100644 index 0000000..a40ae0d Binary files /dev/null and b/wp-includes/images/smilies/icon_idea.gif differ diff --git a/wp-includes/images/smilies/icon_lol.gif b/wp-includes/images/smilies/icon_lol.gif new file mode 100644 index 0000000..374ba15 Binary files /dev/null and b/wp-includes/images/smilies/icon_lol.gif differ diff --git a/wp-includes/images/smilies/icon_mad.gif b/wp-includes/images/smilies/icon_mad.gif new file mode 100644 index 0000000..1f6c3c2 Binary files /dev/null and b/wp-includes/images/smilies/icon_mad.gif differ diff --git a/wp-includes/images/smilies/icon_mrgreen.gif b/wp-includes/images/smilies/icon_mrgreen.gif new file mode 100644 index 0000000..b54cd0f Binary files /dev/null and b/wp-includes/images/smilies/icon_mrgreen.gif differ diff --git a/wp-includes/images/smilies/icon_neutral.gif b/wp-includes/images/smilies/icon_neutral.gif new file mode 100644 index 0000000..4f31156 Binary files /dev/null and b/wp-includes/images/smilies/icon_neutral.gif differ diff --git a/wp-includes/images/smilies/icon_question.gif b/wp-includes/images/smilies/icon_question.gif new file mode 100644 index 0000000..9d07226 Binary files /dev/null and b/wp-includes/images/smilies/icon_question.gif differ diff --git a/wp-includes/images/smilies/icon_razz.gif b/wp-includes/images/smilies/icon_razz.gif new file mode 100644 index 0000000..29da2a2 Binary files /dev/null and b/wp-includes/images/smilies/icon_razz.gif differ diff --git a/wp-includes/images/smilies/icon_redface.gif b/wp-includes/images/smilies/icon_redface.gif new file mode 100644 index 0000000..ad76283 Binary files /dev/null and b/wp-includes/images/smilies/icon_redface.gif differ diff --git a/wp-includes/images/smilies/icon_rolleyes.gif b/wp-includes/images/smilies/icon_rolleyes.gif new file mode 100644 index 0000000..d7f5f2f Binary files /dev/null and b/wp-includes/images/smilies/icon_rolleyes.gif differ diff --git a/wp-includes/images/smilies/icon_sad.gif b/wp-includes/images/smilies/icon_sad.gif new file mode 100644 index 0000000..d2ac78c Binary files /dev/null and b/wp-includes/images/smilies/icon_sad.gif differ diff --git a/wp-includes/images/smilies/icon_smile.gif b/wp-includes/images/smilies/icon_smile.gif new file mode 100644 index 0000000..7b1f6d3 Binary files /dev/null and b/wp-includes/images/smilies/icon_smile.gif differ diff --git a/wp-includes/images/smilies/icon_surprised.gif b/wp-includes/images/smilies/icon_surprised.gif new file mode 100644 index 0000000..cb21424 Binary files /dev/null and b/wp-includes/images/smilies/icon_surprised.gif differ diff --git a/wp-includes/images/smilies/icon_twisted.gif b/wp-includes/images/smilies/icon_twisted.gif new file mode 100644 index 0000000..502fe24 Binary files /dev/null and b/wp-includes/images/smilies/icon_twisted.gif differ diff --git a/wp-includes/images/smilies/icon_wink.gif b/wp-includes/images/smilies/icon_wink.gif new file mode 100644 index 0000000..d148288 Binary files /dev/null and b/wp-includes/images/smilies/icon_wink.gif differ diff --git a/wp-includes/images/upload.png b/wp-includes/images/upload.png new file mode 100644 index 0000000..74c6f12 Binary files /dev/null and b/wp-includes/images/upload.png differ diff --git a/wp-includes/images/wlw/wp-comments.png b/wp-includes/images/wlw/wp-comments.png new file mode 100644 index 0000000..981b1af Binary files /dev/null and b/wp-includes/images/wlw/wp-comments.png differ diff --git a/wp-includes/images/wlw/wp-icon.png b/wp-includes/images/wlw/wp-icon.png new file mode 100644 index 0000000..cd94ee3 Binary files /dev/null and b/wp-includes/images/wlw/wp-icon.png differ diff --git a/wp-includes/images/wlw/wp-watermark.png b/wp-includes/images/wlw/wp-watermark.png new file mode 100644 index 0000000..c312a72 Binary files /dev/null and b/wp-includes/images/wlw/wp-watermark.png differ diff --git a/wp-includes/js/autosave.dev.js b/wp-includes/js/autosave.dev.js new file mode 100644 index 0000000..72a74a4 --- /dev/null +++ b/wp-includes/js/autosave.dev.js @@ -0,0 +1,261 @@ +var autosave, autosaveLast = '', autosavePeriodical, autosaveOldMessage = '', autosaveDelayPreview = false, notSaved = true; + +jQuery(document).ready( function($) { + var dotabkey = true; + + autosaveLast = $('#post #title').val() + $('#post #content').val(); + autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true}); + + //Disable autosave after the form has been submitted + $("#post").submit(function() { $.cancel(autosavePeriodical); }); + + $('.submitbox input[type="submit"], .submitbox a.submitdelete').click(function(){window.onbeforeunload = null;}); + + window.onbeforeunload = function(){ + var mce = typeof(tinyMCE) != 'undefined' ? tinyMCE.activeEditor : false, title, content; + + if ( mce && !mce.isHidden() ) { + if ( mce.isDirty() ) + return autosaveL10n.saveAlert; + } else { + title = $('#post #title').val(), content = $('#post #content').val(); + if ( ( title || content ) && title + content != autosaveLast ) + return autosaveL10n.saveAlert; + } + }; + + // preview + $('#post-preview').click(function(){ + if ( 1 > $('#post_ID').val() && notSaved ) { + autosaveDelayPreview = true; + autosave(); + return false; + } + doPreview(); + return false; + }); + + doPreview = function() { + $('input#wp-preview').val('dopreview'); + $('form#post').attr('target', 'wp-preview').submit().attr('target', ''); + $('input#wp-preview').val(''); + } + + // This code is meant to allow tabbing from Title to Post if tinyMCE is defined. + if ( typeof tinyMCE != 'undefined' ) { + $('#title')[$.browser.opera ? 'keypress' : 'keydown'](function (e) { + if ( e.which == 9 && !e.shiftKey && !e.controlKey && !e.altKey ) { + if ( ($("#post_ID").val() < 1) && ($("#title").val().length > 0) ) { autosave(); } + if ( tinyMCE.activeEditor && ! tinyMCE.activeEditor.isHidden() && dotabkey ) { + e.preventDefault(); + dotabkey = false; + tinyMCE.activeEditor.focus(); + return false; + } + } + }); + } +}); + +function autosave_parse_response(response) { + var res = wpAjax.parseAjaxResponse(response, 'autosave'), message = '', postID; + + if ( res && res.responses && res.responses.length ) { + message = res.responses[0].data; // The saved message or error. + // someone else is editing: disable autosave, set errors + if ( res.responses[0].supplemental ) { + if ( 'disable' == res.responses[0].supplemental['disable_autosave'] ) { + autosave = function() {}; + res = { errors: true }; + } + jQuery.each(res.responses[0].supplemental, function(selector, value) { + if ( selector.match(/^replace-/) ) { + jQuery('#'+selector.replace('replace-', '')).val(value); + } + }); + } + + // if no errors: add slug UI + if ( !res.errors ) { + postID = parseInt( res.responses[0].id, 10 ); + if ( !isNaN(postID) && postID > 0 ) { + autosave_update_slug(postID); + } + } + } + if ( message ) { jQuery('#autosave').html(message); } // update autosave message + else if ( autosaveOldMessage && res ) { jQuery('#autosave').html( autosaveOldMessage ); } + return res; +} + +// called when autosaving pre-existing post +function autosave_saved(response) { + autosave_parse_response(response); // parse the ajax response + autosave_enable_buttons(); // re-enable disabled form buttons +} + +// called when autosaving new post +function autosave_saved_new(response) { + var res = autosave_parse_response(response), tempID, postID; + // if no errors: update post_ID from the temporary value, grab new save-nonce for that new ID + if ( res && res.responses.length && !res.errors ) { + tempID = jQuery('#post_ID').val(); + postID = parseInt( res.responses[0].id, 10 ); + autosave_update_post_ID( postID ); // disabled form buttons are re-enabled here + if ( tempID < 0 && postID > 0 ) { // update media buttons + notSaved = false; + jQuery('#media-buttons a').each(function(){ + this.href = this.href.replace(tempID, postID); + }); + } + if ( autosaveDelayPreview ) { + autosaveDelayPreview = false; + doPreview(); + } + } else { + autosave_enable_buttons(); // re-enable disabled form buttons + } +} + +function autosave_update_post_ID( postID ) { + if ( !isNaN(postID) && postID > 0 ) { + if ( postID == parseInt(jQuery('#post_ID').val(), 10) ) { return; } // no need to do this more than once + jQuery('#post_ID').attr({name: "post_ID"}); + jQuery('#post_ID').val(postID); + // We need new nonces + jQuery.post(autosaveL10n.requestFile, { + action: "autosave-generate-nonces", + post_ID: postID, + autosavenonce: jQuery('#autosavenonce').val(), + post_type: jQuery('#post_type').val() + }, function(html) { + jQuery('#_wpnonce').val(html); + autosave_enable_buttons(); // re-enable disabled form buttons + }); + jQuery('#hiddenaction').val('editpost'); + } +} + +function autosave_update_slug(post_id) { + // create slug area only if not already there + if ( jQuery.isFunction(make_slugedit_clickable) && !jQuery('#edit-slug-box > *').size() ) { + jQuery.post( + slugL10n.requestFile, + { + action: 'sample-permalink', + post_id: post_id, + new_title: jQuery('#title').val(), + samplepermalinknonce: jQuery('#samplepermalinknonce').val() + }, + function(data) { + jQuery('#edit-slug-box').html(data); + make_slugedit_clickable(); + } + ); + } +} + +function autosave_loading() { + jQuery('#autosave').html(autosaveL10n.savingText); +} + +function autosave_enable_buttons() { + jQuery(".submitbox :button:disabled, .submitbox :submit:disabled").attr('disabled', ''); +} + +function autosave_disable_buttons() { + jQuery(".submitbox :button:enabled, .submitbox :submit:enabled").attr('disabled', 'disabled'); + // Re-enable 5 sec later. Just gives autosave a head start to avoid collisions. + setTimeout(autosave_enable_buttons, 5000); +} + +autosave = function() { + // (bool) is rich editor enabled and active + var rich = (typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden(), post_data, doAutoSave, ed, origStatus, successCallback; + + post_data = { + action: "autosave", + post_ID: jQuery("#post_ID").val() || 0, + post_title: jQuery("#title").val() || "", + autosavenonce: jQuery('#autosavenonce').val(), + //tags_input: jQuery("#tags-input").val() || "", + post_type: jQuery('#post_type').val() || "", + autosave: 1 + }; + + jQuery('.tags-input').each( function() { + post_data[this.name] = this.value; + } ); + + // We always send the ajax request in order to keep the post lock fresh. + // This (bool) tells whether or not to write the post to the DB during the ajax request. + doAutoSave = true; + + // No autosave while thickbox is open (media buttons) + if ( jQuery("#TB_window").css('display') == 'block' ) + doAutoSave = false; + + /* Gotta do this up here so we can check the length when tinyMCE is in use */ + if ( rich ) { + ed = tinyMCE.activeEditor; + if ( 'mce_fullscreen' == ed.id ) + tinyMCE.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'}); + tinyMCE.get('content').save(); + } + + post_data["content"] = jQuery("#content").val(); + if ( jQuery('#post_name').val() ) + post_data["post_name"] = jQuery('#post_name').val(); + + // Nothing to save or no change. + if( ( post_data["post_title"].length == 0 && post_data["content"].length == 0 ) || post_data["post_title"] + post_data["content"] == autosaveLast) { + doAutoSave = false; + } + + autosave_disable_buttons(); + + origStatus = jQuery('#original_post_status').val(); + + autosaveLast = jQuery("#title").val()+jQuery("#content").val(); + goodcats = ([]); + jQuery("[name='post_category[]']:checked").each( function(i) { + goodcats.push(this.value); + } ); + post_data["catslist"] = goodcats.join(","); + + if ( jQuery("#comment_status").attr("checked") ) + post_data["comment_status"] = 'open'; + if ( jQuery("#ping_status").attr("checked") ) + post_data["ping_status"] = 'open'; + if ( jQuery("#excerpt").size() ) + post_data["excerpt"] = jQuery("#excerpt").val(); + if ( jQuery("#post_author").size() ) + post_data["post_author"] = jQuery("#post_author").val(); + post_data["user_ID"] = jQuery("#user-id").val(); + + // Don't run while the TinyMCE spellcheck is on. It resets all found words. + if ( rich && tinyMCE.activeEditor.plugins.spellchecker && tinyMCE.activeEditor.plugins.spellchecker.active ) { + doAutoSave = false; + } + + if ( parseInt(post_data["post_ID"], 10) < 1 ) { + post_data["temp_ID"] = post_data["post_ID"]; + successCallback = autosave_saved_new; // new post + } else { + successCallback = autosave_saved; // pre-existing post + } + + if ( !doAutoSave ) { + post_data['autosave'] = 0; + } + + autosaveOldMessage = jQuery('#autosave').html(); + + jQuery.ajax({ + data: post_data, + beforeSend: doAutoSave ? autosave_loading : null, + type: "POST", + url: autosaveL10n.requestFile, + success: successCallback + }); +} diff --git a/wp-includes/js/autosave.js b/wp-includes/js/autosave.js new file mode 100644 index 0000000..a18063a --- /dev/null +++ b/wp-includes/js/autosave.js @@ -0,0 +1 @@ +var autosave,autosaveLast="",autosavePeriodical,autosaveOldMessage="",autosaveDelayPreview=false,notSaved=true;jQuery(document).ready(function(b){var a=true;autosaveLast=b("#post #title").val()+b("#post #content").val();autosavePeriodical=b.schedule({time:autosaveL10n.autosaveInterval*1000,func:function(){autosave()},repeat:true,protect:true});b("#post").submit(function(){b.cancel(autosavePeriodical)});b('.submitbox input[type="submit"], .submitbox a.submitdelete').click(function(){window.onbeforeunload=null});window.onbeforeunload=function(){var c=typeof(tinyMCE)!="undefined"?tinyMCE.activeEditor:false,e,d;if(c&&!c.isHidden()){if(c.isDirty()){return autosaveL10n.saveAlert}}else{e=b("#post #title").val(),d=b("#post #content").val();if((e||d)&&e+d!=autosaveLast){return autosaveL10n.saveAlert}}};b("#post-preview").click(function(){if(1>b("#post_ID").val()&¬Saved){autosaveDelayPreview=true;autosave();return false}doPreview();return false});doPreview=function(){b("input#wp-preview").val("dopreview");b("form#post").attr("target","wp-preview").submit().attr("target","");b("input#wp-preview").val("")};if(typeof tinyMCE!="undefined"){b("#title")[b.browser.opera?"keypress":"keydown"](function(c){if(c.which==9&&!c.shiftKey&&!c.controlKey&&!c.altKey){if((b("#post_ID").val()<1)&&(b("#title").val().length>0)){autosave()}if(tinyMCE.activeEditor&&!tinyMCE.activeEditor.isHidden()&&a){c.preventDefault();a=false;tinyMCE.activeEditor.focus();return false}}})}});function autosave_parse_response(b){var c=wpAjax.parseAjaxResponse(b,"autosave"),d="",a;if(c&&c.responses&&c.responses.length){d=c.responses[0].data;if(c.responses[0].supplemental){if("disable"==c.responses[0].supplemental.disable_autosave){autosave=function(){};c={errors:true}}jQuery.each(c.responses[0].supplemental,function(e,f){if(e.match(/^replace-/)){jQuery("#"+e.replace("replace-","")).val(f)}})}if(!c.errors){a=parseInt(c.responses[0].id,10);if(!isNaN(a)&&a>0){autosave_update_slug(a)}}}if(d){jQuery("#autosave").html(d)}else{if(autosaveOldMessage&&c){jQuery("#autosave").html(autosaveOldMessage)}}return c}function autosave_saved(a){autosave_parse_response(a);autosave_enable_buttons()}function autosave_saved_new(b){var d=autosave_parse_response(b),c,a;if(d&&d.responses.length&&!d.errors){c=jQuery("#post_ID").val();a=parseInt(d.responses[0].id,10);autosave_update_post_ID(a);if(c<0&&a>0){notSaved=false;jQuery("#media-buttons a").each(function(){this.href=this.href.replace(c,a)})}if(autosaveDelayPreview){autosaveDelayPreview=false;doPreview()}}else{autosave_enable_buttons()}}function autosave_update_post_ID(a){if(!isNaN(a)&&a>0){if(a==parseInt(jQuery("#post_ID").val(),10)){return}jQuery("#post_ID").attr({name:"post_ID"});jQuery("#post_ID").val(a);jQuery.post(autosaveL10n.requestFile,{action:"autosave-generate-nonces",post_ID:a,autosavenonce:jQuery("#autosavenonce").val(),post_type:jQuery("#post_type").val()},function(b){jQuery("#_wpnonce").val(b);autosave_enable_buttons()});jQuery("#hiddenaction").val("editpost")}}function autosave_update_slug(a){if(jQuery.isFunction(make_slugedit_clickable)&&!jQuery("#edit-slug-box > *").size()){jQuery.post(slugL10n.requestFile,{action:"sample-permalink",post_id:a,new_title:jQuery("#title").val(),samplepermalinknonce:jQuery("#samplepermalinknonce").val()},function(b){jQuery("#edit-slug-box").html(b);make_slugedit_clickable()})}}function autosave_loading(){jQuery("#autosave").html(autosaveL10n.savingText)}function autosave_enable_buttons(){jQuery(".submitbox :button:disabled, .submitbox :submit:disabled").attr("disabled","")}function autosave_disable_buttons(){jQuery(".submitbox :button:enabled, .submitbox :submit:enabled").attr("disabled","disabled");setTimeout(autosave_enable_buttons,5000)}autosave=function(){var c=(typeof tinyMCE!="undefined")&&tinyMCE.activeEditor&&!tinyMCE.activeEditor.isHidden(),d,f,b,e,a;d={action:"autosave",post_ID:jQuery("#post_ID").val()||0,post_title:jQuery("#title").val()||"",autosavenonce:jQuery("#autosavenonce").val(),post_type:jQuery("#post_type").val()||"",autosave:1};jQuery(".tags-input").each(function(){d[this.name]=this.value});f=true;if(jQuery("#TB_window").css("display")=="block"){f=false}if(c){b=tinyMCE.activeEditor;if("mce_fullscreen"==b.id){tinyMCE.get("content").setContent(b.getContent({format:"raw"}),{format:"raw"})}tinyMCE.get("content").save()}d.content=jQuery("#content").val();if(jQuery("#post_name").val()){d.post_name=jQuery("#post_name").val()}if((d.post_title.length==0&&d.content.length==0)||d.post_title+d.content==autosaveLast){f=false}autosave_disable_buttons();e=jQuery("#original_post_status").val();autosaveLast=jQuery("#title").val()+jQuery("#content").val();goodcats=([]);jQuery("[name='post_category[]']:checked").each(function(g){goodcats.push(this.value)});d.catslist=goodcats.join(",");if(jQuery("#comment_status").attr("checked")){d.comment_status="open"}if(jQuery("#ping_status").attr("checked")){d.ping_status="open"}if(jQuery("#excerpt").size()){d.excerpt=jQuery("#excerpt").val()}if(jQuery("#post_author").size()){d.post_author=jQuery("#post_author").val()}d.user_ID=jQuery("#user-id").val();if(c&&tinyMCE.activeEditor.plugins.spellchecker&&tinyMCE.activeEditor.plugins.spellchecker.active){f=false}if(parseInt(d.post_ID,10)<1){d.temp_ID=d.post_ID;a=autosave_saved_new}else{a=autosave_saved}if(!f){d.autosave=0}autosaveOldMessage=jQuery("#autosave").html();jQuery.ajax({data:d,beforeSend:f?autosave_loading:null,type:"POST",url:autosaveL10n.requestFile,success:a})}; \ No newline at end of file diff --git a/wp-includes/js/codepress/codepress.css b/wp-includes/js/codepress/codepress.css new file mode 100644 index 0000000..3a4a00a --- /dev/null +++ b/wp-includes/js/codepress/codepress.css @@ -0,0 +1,21 @@ +body { + margin-top:13px; + _margin-top:14px; + background:white; + margin-left:32px; + font-family:monospace; + font-size:13px; + white-space:pre; + background-image:url("images/line-numbers.png"); + background-repeat:repeat-y; + background-position:0 3px; + line-height:16px; + height:100%; +} +pre {margin:0;} +html>body{background-position:0 2px;} +P {margin:0;padding:0;border:0;outline:0;display:block;white-space:pre;} +b, i, s, u, a, em, tt, ins, big, cite, strong, var, dfn {text-decoration:none;font-weight:normal;font-style:normal;font-size:13px;} + +body.hide-line-numbers {background:white;margin-left:16px;} +body.show-line-numbers {background-image:url("images/line-numbers.png");margin-left:32px;} \ No newline at end of file diff --git a/wp-includes/js/codepress/codepress.html b/wp-includes/js/codepress/codepress.html new file mode 100644 index 0000000..d9711d6 --- /dev/null +++ b/wp-includes/js/codepress/codepress.html @@ -0,0 +1,35 @@ + + + + CodePress - Real Time Syntax Highlighting Editor written in JavaScript + + + + + + + + + diff --git a/wp-includes/js/codepress/codepress.js b/wp-includes/js/codepress/codepress.js new file mode 100644 index 0000000..804f29a --- /dev/null +++ b/wp-includes/js/codepress/codepress.js @@ -0,0 +1,137 @@ +/* + * CodePress - Real Time Syntax Highlighting Editor written in JavaScript - http://codepress.org/ + * + * Copyright (C) 2006 Fernando M.A.d.S. + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation. + * + * Read the full licence: http://www.opensource.org/licenses/lgpl-license.php + */ + +CodePress = function(obj) { + var self = document.createElement('iframe'); + self.textarea = obj; + self.textarea.disabled = true; + self.textarea.style.overflow = 'hidden'; + self.style.height = self.textarea.clientHeight +'px'; + self.style.width = self.textarea.clientWidth +'px'; + self.textarea.style.overflow = 'auto'; + self.style.border = '1px solid gray'; + self.frameBorder = 0; // remove IE internal iframe border + self.style.visibility = 'hidden'; + self.style.position = 'absolute'; + self.options = self.textarea.className; + + self.initialize = function() { + self.editor = self.contentWindow.CodePress; + self.editor.body = self.contentWindow.document.getElementsByTagName('body')[0]; + self.editor.setCode(self.textarea.value); + self.setOptions(); + self.editor.syntaxHighlight('init'); + self.textarea.style.display = 'none'; + self.style.position = 'static'; + self.style.visibility = 'visible'; + self.style.display = 'inline'; + } + + // obj can by a textarea id or a string (code) + self.edit = function(obj,language) { + if(obj) self.textarea.value = document.getElementById(obj) ? document.getElementById(obj).value : obj; + if(!self.textarea.disabled) return; + self.language = language ? language : self.getLanguage(); + self.src = CodePress.path+'codepress.html?language='+self.language+'&ts='+(new Date).getTime(); + if(self.attachEvent) self.attachEvent('onload',self.initialize); + else self.addEventListener('load',self.initialize,false); + } + + self.getLanguage = function() { + for (language in CodePress.languages) + if(self.options.match('\\b'+language+'\\b')) + return CodePress.languages[language] ? language : 'generic'; + } + + self.setOptions = function() { + if(self.options.match('autocomplete-off')) self.toggleAutoComplete(); + if(self.options.match('readonly-on')) self.toggleReadOnly(); + if(self.options.match('linenumbers-off')) self.toggleLineNumbers(); + } + + self.getCode = function() { + return self.textarea.disabled ? self.editor.getCode() : self.textarea.value; + } + + self.setCode = function(code) { + self.textarea.disabled ? self.editor.setCode(code) : self.textarea.value = code; + } + + self.toggleAutoComplete = function() { + self.editor.autocomplete = (self.editor.autocomplete) ? false : true; + } + + self.toggleReadOnly = function() { + self.textarea.readOnly = (self.textarea.readOnly) ? false : true; + if(self.style.display != 'none') // prevent exception on FF + iframe with display:none + self.editor.readOnly(self.textarea.readOnly ? true : false); + } + + self.toggleLineNumbers = function() { + var cn = self.editor.body.className; + self.editor.body.className = (cn==''||cn=='show-line-numbers') ? 'hide-line-numbers' : 'show-line-numbers'; + } + + self.toggleEditor = function() { + if(self.textarea.disabled) { + self.textarea.value = self.getCode(); + self.textarea.disabled = false; + self.style.display = 'none'; + self.textarea.style.display = 'inline'; + } + else { + self.textarea.disabled = true; + self.setCode(self.textarea.value); + self.editor.syntaxHighlight('init'); + self.style.display = 'inline'; + self.textarea.style.display = 'none'; + } + } + + self.edit(); + return self; +} + +CodePress.languages = { + csharp : 'C#', + css : 'CSS', + generic : 'Generic', + html : 'HTML', + java : 'Java', + javascript : 'JavaScript', + perl : 'Perl', + ruby : 'Ruby', + php : 'PHP', + text : 'Text', + sql : 'SQL', + vbscript : 'VBScript' +} + + +CodePress.run = function() { + // Modified for WordPress compat to prevent loading on webkit and to + // reference a codepress_path which is specified externally. + if (navigator.userAgent.toLowerCase().indexOf('webkit') != -1) + return; + CodePress.path = codepress_path; + var t = document.getElementsByTagName('textarea'), i, id; + for(i=0,n=t.length;i + * + * Developers: + * Fernando M.A.d.S. + * Michael Hurni + * Contributors: + * Martin D. Kirk + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation. + * + * Read the full licence: http://www.opensource.org/licenses/lgpl-license.php + */ + +CodePress = { + scrolling : false, + autocomplete : true, + + // set initial vars and start sh + initialize : function() { + if(typeof(editor)=='undefined' && !arguments[0]) return; + body = document.getElementsByTagName('body')[0]; + body.innerHTML = body.innerHTML.replace(/\n/g,""); + chars = '|32|46|62|8|'; // charcodes that trigger syntax highlighting + cc = '\u2009'; // carret char + editor = document.getElementsByTagName('pre')[0]; + document.designMode = 'on'; + document.addEventListener('keypress', this.keyHandler, true); + window.addEventListener('scroll', function() { if(!CodePress.scrolling) CodePress.syntaxHighlight('scroll') }, false); + completeChars = this.getCompleteChars(); + completeEndingChars = this.getCompleteEndingChars(); + }, + + // treat key bindings + keyHandler : function(evt) { + keyCode = evt.keyCode; + charCode = evt.charCode; + fromChar = String.fromCharCode(charCode); + + if((evt.ctrlKey || evt.metaKey) && evt.shiftKey && charCode!=90) { // shortcuts = ctrl||appleKey+shift+key!=z(undo) + CodePress.shortcuts(charCode?charCode:keyCode); + } + else if( (completeEndingChars.indexOf('|'+fromChar+'|')!= -1 || completeChars.indexOf('|'+fromChar+'|')!=-1) && CodePress.autocomplete) { // auto complete + if(!CodePress.completeEnding(fromChar)) + CodePress.complete(fromChar); + } + else if(chars.indexOf('|'+charCode+'|')!=-1||keyCode==13) { // syntax highlighting + top.setTimeout(function(){CodePress.syntaxHighlight('generic');},100); + } + else if(keyCode==9 || evt.tabKey) { // snippets activation (tab) + CodePress.snippets(evt); + } + else if(keyCode==46||keyCode==8) { // save to history when delete or backspace pressed + CodePress.actions.history[CodePress.actions.next()] = editor.innerHTML; + } + else if((charCode==122||charCode==121||charCode==90) && evt.ctrlKey) { // undo and redo + (charCode==121||evt.shiftKey) ? CodePress.actions.redo() : CodePress.actions.undo(); + evt.preventDefault(); + } + else if(charCode==118 && evt.ctrlKey) { // handle paste + top.setTimeout(function(){CodePress.syntaxHighlight('generic');},100); + } + else if(charCode==99 && evt.ctrlKey) { // handle cut + //alert(window.getSelection().getRangeAt(0).toString().replace(/\t/g,'FFF')); + } + + }, + + // put cursor back to its original position after every parsing + findString : function() { + if(self.find(cc)) + window.getSelection().getRangeAt(0).deleteContents(); + }, + + // split big files, highlighting parts of it + split : function(code,flag) { + if(flag=='scroll') { + this.scrolling = true; + return code; + } + else { + this.scrolling = false; + mid = code.indexOf(cc); + if(mid-2000<0) {ini=0;end=4000;} + else if(mid+2000>code.length) {ini=code.length-4000;end=code.length;} + else {ini=mid-2000;end=mid+2000;} + code = code.substring(ini,end); + return code; + } + }, + + getEditor : function() { + if(!document.getElementsByTagName('pre')[0]) { + body = document.getElementsByTagName('body')[0]; + if(!body.innerHTML) return body; + if(body.innerHTML=="
    ") body.innerHTML = "
     
    "; + else body.innerHTML = "
    "+body.innerHTML+"
    "; + } + return document.getElementsByTagName('pre')[0]; + }, + + // syntax highlighting parser + syntaxHighlight : function(flag) { + //if(document.designMode=='off') document.designMode='on' + if(flag != 'init') { window.getSelection().getRangeAt(0).insertNode(document.createTextNode(cc));} + editor = CodePress.getEditor(); + o = editor.innerHTML; + o = o.replace(/
    /g,'\n'); + o = o.replace(/<.*?>/g,''); + x = z = this.split(o,flag); + x = x.replace(/\n/g,'
    '); + + if(arguments[1]&&arguments[2]) x = x.replace(arguments[1],arguments[2]); + + for(i=0;i/g,'>'); + if(content.indexOf('$0')<0) content += cc; + else content = content.replace(/\$0/,cc); + content = content.replace(/\n/g,'
    '); + var pattern = new RegExp(trigger+cc,'gi'); + evt.preventDefault(); // prevent the tab key from being added + this.syntaxHighlight('snippets',pattern,content); + } + } + }, + + readOnly : function() { + document.designMode = (arguments[0]) ? 'off' : 'on'; + }, + + complete : function(trigger) { + window.getSelection().getRangeAt(0).deleteContents(); + var complete = Language.complete; + for (var i=0; i/g,'\n'); + code = code.replace(/\u2009/g,''); + code = code.replace(/<.*?>/g,''); + code = code.replace(/</g,'<'); + code = code.replace(/>/g,'>'); + code = code.replace(/&/gi,'&'); + return code; + }, + + // put code inside editor + setCode : function() { + var code = arguments[0]; + code = code.replace(/\u2009/gi,''); + code = code.replace(/&/gi,'&'); + code = code.replace(//g,'>'); + editor.innerHTML = code; + if (code == '') + document.getElementsByTagName('body')[0].innerHTML = ''; + }, + + // undo and redo methods + actions : { + pos : -1, // actual history position + history : [], // history vector + + undo : function() { + editor = CodePress.getEditor(); + if(editor.innerHTML.indexOf(cc)==-1){ + if(editor.innerHTML != " ") + window.getSelection().getRangeAt(0).insertNode(document.createTextNode(cc)); + this.history[this.pos] = editor.innerHTML; + } + this.pos --; + if(typeof(this.history[this.pos])=='undefined') this.pos ++; + editor.innerHTML = this.history[this.pos]; + if(editor.innerHTML.indexOf(cc)>-1) editor.innerHTML+=cc; + CodePress.findString(); + }, + + redo : function() { + // editor = CodePress.getEditor(); + this.pos++; + if(typeof(this.history[this.pos])=='undefined') this.pos--; + editor.innerHTML = this.history[this.pos]; + CodePress.findString(); + }, + + next : function() { // get next vector position and clean old ones + if(this.pos>20) this.history[this.pos-21] = undefined; + return ++this.pos; + } + } +} + +Language={}; +window.addEventListener('load', function() { CodePress.initialize('new'); }, true); \ No newline at end of file diff --git a/wp-includes/js/codepress/engines/khtml.js b/wp-includes/js/codepress/engines/khtml.js new file mode 100644 index 0000000..e69de29 diff --git a/wp-includes/js/codepress/engines/msie.js b/wp-includes/js/codepress/engines/msie.js new file mode 100644 index 0000000..2558c39 --- /dev/null +++ b/wp-includes/js/codepress/engines/msie.js @@ -0,0 +1,304 @@ +/* + * CodePress - Real Time Syntax Highlighting Editor written in JavaScript - http://codepress.org/ + * + * Copyright (C) 2007 Fernando M.A.d.S. + * + * Developers: + * Fernando M.A.d.S. + * Michael Hurni + * Contributors: + * Martin D. Kirk + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation. + * + * Read the full licence: http://www.opensource.org/licenses/lgpl-license.php + */ + +CodePress = { + scrolling : false, + autocomplete : true, + + // set initial vars and start sh + initialize : function() { + if(typeof(editor)=='undefined' && !arguments[0]) return; + chars = '|32|46|62|'; // charcodes that trigger syntax highlighting + cc = '\u2009'; // carret char + editor = document.getElementsByTagName('pre')[0]; + editor.contentEditable = 'true'; + document.getElementsByTagName('body')[0].onfocus = function() {editor.focus();} + document.attachEvent('onkeydown', this.metaHandler); + document.attachEvent('onkeypress', this.keyHandler); + window.attachEvent('onscroll', function() { if(!CodePress.scrolling) setTimeout(function(){CodePress.syntaxHighlight('scroll')},1)}); + completeChars = this.getCompleteChars(); + completeEndingChars = this.getCompleteEndingChars(); + setTimeout(function() { window.scroll(0,0) },50); // scroll IE to top + }, + + // treat key bindings + keyHandler : function(evt) { + charCode = evt.keyCode; + fromChar = String.fromCharCode(charCode); + + if( (completeEndingChars.indexOf('|'+fromChar+'|')!= -1 || completeChars.indexOf('|'+fromChar+'|')!=-1 )&& CodePress.autocomplete) { // auto complete + if(!CodePress.completeEnding(fromChar)) + CodePress.complete(fromChar); + } + else if(chars.indexOf('|'+charCode+'|')!=-1||charCode==13) { // syntax highlighting + CodePress.syntaxHighlight('generic'); + } + }, + + metaHandler : function(evt) { + keyCode = evt.keyCode; + + if(keyCode==9 || evt.tabKey) { + CodePress.snippets(); + } + else if((keyCode==122||keyCode==121||keyCode==90) && evt.ctrlKey) { // undo and redo + (keyCode==121||evt.shiftKey) ? CodePress.actions.redo() : CodePress.actions.undo(); + evt.returnValue = false; + } + else if(keyCode==34||keyCode==33) { // handle page up/down for IE + self.scrollBy(0, (keyCode==34) ? 200 : -200); + evt.returnValue = false; + } + else if(keyCode==46||keyCode==8) { // save to history when delete or backspace pressed + CodePress.actions.history[CodePress.actions.next()] = editor.innerHTML; + } + else if((evt.ctrlKey || evt.metaKey) && evt.shiftKey && keyCode!=90) { // shortcuts = ctrl||appleKey+shift+key!=z(undo) + CodePress.shortcuts(keyCode); + evt.returnValue = false; + } + else if(keyCode==86 && evt.ctrlKey) { // handle paste + window.clipboardData.setData('Text',window.clipboardData.getData('Text').replace(/\t/g,'\u2008')); + top.setTimeout(function(){CodePress.syntaxHighlight('paste');},10); + } + else if(keyCode==67 && evt.ctrlKey) { // handle cut + // window.clipboardData.setData('Text',x[0]); + // code = window.clipboardData.getData('Text'); + } + }, + + // put cursor back to its original position after every parsing + + + findString : function() { + range = self.document.body.createTextRange(); + if(range.findText(cc)){ + range.select(); + range.text = ''; + } + }, + + // split big files, highlighting parts of it + split : function(code,flag) { + if(flag=='scroll') { + this.scrolling = true; + return code; + } + else { + this.scrolling = false; + mid = code.indexOf(cc); + if(mid-2000<0) {ini=0;end=4000;} + else if(mid+2000>code.length) {ini=code.length-4000;end=code.length;} + else {ini=mid-2000;end=mid+2000;} + code = code.substring(ini,end); + return code.substring(code.indexOf('

    '),code.lastIndexOf('

    ')+4); + } + }, + + // syntax highlighting parser + syntaxHighlight : function(flag) { + if(flag!='init') document.selection.createRange().text = cc; + o = editor.innerHTML; + if(flag=='paste') { // fix pasted text + o = o.replace(/
    /g,'\r\n'); + o = o.replace(/\u2008/g,'\t'); + } + o = o.replace(/

    /g,'\n'); + o = o.replace(/<\/P>/g,'\r'); + o = o.replace(/<.*?>/g,''); + o = o.replace(/ /g,''); + o = '

    '+o+'

    '; + o = o.replace(/\n\r/g,'

    '); + o = o.replace(/\n/g,'

    '); + o = o.replace(/\r/g,'<\/P>'); + o = o.replace(/

    (

    )+/,'

    '); + o = o.replace(/<\/P>(<\/P>)+/,'

    '); + o = o.replace(/

    <\/P>/g,'


    '); + x = z = this.split(o,flag); + + if(arguments[1]&&arguments[2]) x = x.replace(arguments[1],arguments[2]); + + for(i=0;i/g,'>'); + if(content.indexOf('$0')<0) content += cc; + else content = content.replace(/\$0/,cc); + content = content.replace(/\n/g,'

    '); + var pattern = new RegExp(trigger+cc,"gi"); + this.syntaxHighlight('snippets',pattern,content); + } + } + }, + + readOnly : function() { + editor.contentEditable = (arguments[0]) ? 'false' : 'true'; + }, + + complete : function(trigger) { + var complete = Language.complete; + for (var i=0; i/g,'\n'); + code = code.replace(/<\/p>/gi,'\r'); + code = code.replace(/

    /i,''); // IE first line fix + code = code.replace(/

    /gi,'\n'); + code = code.replace(/ /gi,''); + code = code.replace(/\u2009/g,''); + code = code.replace(/<.*?>/g,''); + code = code.replace(/</g,'<'); + code = code.replace(/>/g,'>'); + code = code.replace(/&/gi,'&'); + return code; + }, + + // put code inside editor + setCode : function() { + var code = arguments[0]; + code = code.replace(/\u2009/gi,''); + code = code.replace(/&/gi,'&'); + code = code.replace(//g,'>'); + editor.innerHTML = '

    '+code+'
    '; + }, + + + // undo and redo methods + actions : { + pos : -1, // actual history position + history : [], // history vector + + undo : function() { + if(editor.innerHTML.indexOf(cc)==-1){ + document.selection.createRange().text = cc; + this.history[this.pos] = editor.innerHTML; + } + this.pos--; + if(typeof(this.history[this.pos])=='undefined') this.pos++; + editor.innerHTML = this.history[this.pos]; + CodePress.findString(); + }, + + redo : function() { + this.pos++; + if(typeof(this.history[this.pos])=='undefined') this.pos--; + editor.innerHTML = this.history[this.pos]; + CodePress.findString(); + }, + + next : function() { // get next vector position and clean old ones + if(this.pos>20) this.history[this.pos-21] = undefined; + return ++this.pos; + } + } +} + +Language={}; +window.attachEvent('onload', function() { CodePress.initialize('new');}); \ No newline at end of file diff --git a/wp-includes/js/codepress/engines/older.js b/wp-includes/js/codepress/engines/older.js new file mode 100644 index 0000000..e69de29 diff --git a/wp-includes/js/codepress/engines/opera.js b/wp-includes/js/codepress/engines/opera.js new file mode 100644 index 0000000..155bf09 --- /dev/null +++ b/wp-includes/js/codepress/engines/opera.js @@ -0,0 +1,260 @@ +/* + * CodePress - Real Time Syntax Highlighting Editor written in JavaScript - http://codepress.org/ + * + * Copyright (C) 2007 Fernando M.A.d.S. + * + * Contributors : + * + * Michael Hurni + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation. + * + * Read the full licence: http://www.opensource.org/licenses/lgpl-license.php + */ + + +CodePress = { + scrolling : false, + autocomplete : true, + + // set initial vars and start sh + initialize : function() { + if(typeof(editor)=='undefined' && !arguments[0]) return; + chars = '|32|46|62|'; // charcodes that trigger syntax highlighting + cc = '\u2009'; // control char + editor = document.getElementsByTagName('body')[0]; + document.designMode = 'on'; + document.addEventListener('keyup', this.keyHandler, true); + window.addEventListener('scroll', function() { if(!CodePress.scrolling) CodePress.syntaxHighlight('scroll') }, false); + completeChars = this.getCompleteChars(); +// CodePress.syntaxHighlight('init'); + }, + + // treat key bindings + keyHandler : function(evt) { + keyCode = evt.keyCode; + charCode = evt.charCode; + + if((evt.ctrlKey || evt.metaKey) && evt.shiftKey && charCode!=90) { // shortcuts = ctrl||appleKey+shift+key!=z(undo) + CodePress.shortcuts(charCode?charCode:keyCode); + } + else if(completeChars.indexOf('|'+String.fromCharCode(charCode)+'|')!=-1 && CodePress.autocomplete) { // auto complete + CodePress.complete(String.fromCharCode(charCode)); + } + else if(chars.indexOf('|'+charCode+'|')!=-1||keyCode==13) { // syntax highlighting + CodePress.syntaxHighlight('generic'); + } + else if(keyCode==9 || evt.tabKey) { // snippets activation (tab) + CodePress.snippets(evt); + } + else if(keyCode==46||keyCode==8) { // save to history when delete or backspace pressed + CodePress.actions.history[CodePress.actions.next()] = editor.innerHTML; + } + else if((charCode==122||charCode==121||charCode==90) && evt.ctrlKey) { // undo and redo + (charCode==121||evt.shiftKey) ? CodePress.actions.redo() : CodePress.actions.undo(); + evt.preventDefault(); + } + else if(keyCode==86 && evt.ctrlKey) { // paste + // TODO: pasted text should be parsed and highlighted + } + }, + + // put cursor back to its original position after every parsing + findString : function() { + var sel = window.getSelection(); + var range = window.document.createRange(); + var span = window.document.getElementsByTagName('span')[0]; + + range.selectNode(span); + sel.removeAllRanges(); + sel.addRange(range); + span.parentNode.removeChild(span); + //if(self.find(cc)) + //window.getSelection().getRangeAt(0).deleteContents(); + }, + + // split big files, highlighting parts of it + split : function(code,flag) { + if(flag=='scroll') { + this.scrolling = true; + return code; + } + else { + this.scrolling = false; + mid = code.indexOf(''); + if(mid-2000<0) {ini=0;end=4000;} + else if(mid+2000>code.length) {ini=code.length-4000;end=code.length;} + else {ini=mid-2000;end=mid+2000;} + code = code.substring(ini,end); + return code; + } + }, + + // syntax highlighting parser + syntaxHighlight : function(flag) { + //if(document.designMode=='off') document.designMode='on' + if(flag!='init') { + var span = document.createElement('span'); + window.getSelection().getRangeAt(0).insertNode(span); + } + + o = editor.innerHTML; +// o = o.replace(/
    /g,'\r\n'); +// o = o.replace(/<(b|i|s|u|a|em|tt|ins|big|cite|strong)?>/g,''); + //alert(o) + o = o.replace(/<(?!span|\/span|br).*?>/gi,''); +// alert(o) +// x = o; + x = z = this.split(o,flag); + //alert(z) +// x = x.replace(/\r\n/g,'
    '); + x = x.replace(/\t/g, ' '); + + + if(arguments[1]&&arguments[2]) x = x.replace(arguments[1],arguments[2]); + + for(i=0;i/g,'>'); + if(content.indexOf('$0')<0) content += cc; + else content = content.replace(/\$0/,cc); + content = content.replace(/\n/g,'
    '); + var pattern = new RegExp(trigger+cc,'gi'); + evt.preventDefault(); // prevent the tab key from being added + this.syntaxHighlight('snippets',pattern,content); + } + } + }, + + readOnly : function() { + document.designMode = (arguments[0]) ? 'off' : 'on'; + }, + + complete : function(trigger) { + window.getSelection().getRangeAt(0).deleteContents(); + var complete = Language.complete; + for (var i=0; i/g,'\n'); + code = code.replace(/\u2009/g,''); + code = code.replace(/<.*?>/g,''); + code = code.replace(/</g,'<'); + code = code.replace(/>/g,'>'); + code = code.replace(/&/gi,'&'); + return code; + }, + + // put code inside editor + setCode : function() { + var code = arguments[0]; + code = code.replace(/\u2009/gi,''); + code = code.replace(/&/gi,'&'); + code = code.replace(//g,'>'); + editor.innerHTML = code; + }, + + // undo and redo methods + actions : { + pos : -1, // actual history position + history : [], // history vector + + undo : function() { + if(editor.innerHTML.indexOf(cc)==-1){ + window.getSelection().getRangeAt(0).insertNode(document.createTextNode(cc)); + this.history[this.pos] = editor.innerHTML; + } + this.pos--; + if(typeof(this.history[this.pos])=='undefined') this.pos++; + editor.innerHTML = this.history[this.pos]; + CodePress.findString(); + }, + + redo : function() { + this.pos++; + if(typeof(this.history[this.pos])=='undefined') this.pos--; + editor.innerHTML = this.history[this.pos]; + CodePress.findString(); + }, + + next : function() { // get next vector position and clean old ones + if(this.pos>20) this.history[this.pos-21] = undefined; + return ++this.pos; + } + } +} + +Language={}; +window.addEventListener('load', function() { CodePress.initialize('new'); }, true); diff --git a/wp-includes/js/codepress/images/line-numbers.png b/wp-includes/js/codepress/images/line-numbers.png new file mode 100644 index 0000000..ffea4e6 Binary files /dev/null and b/wp-includes/js/codepress/images/line-numbers.png differ diff --git a/wp-includes/js/codepress/languages/asp.css b/wp-includes/js/codepress/languages/asp.css new file mode 100644 index 0000000..9a4c505 --- /dev/null +++ b/wp-includes/js/codepress/languages/asp.css @@ -0,0 +1,71 @@ +/* + * CodePress color styles for ASP-VB syntax highlighting + * By Martin D. Kirk + */ +/* tags */ + +b { + color:#000080; +} +/* comments */ +big, big b, big em, big ins, big s, strong i, strong i b, strong i s, strong i u, strong i a, strong i a u, strong i s u { + color:gray; + font-weight:normal; +} +/* ASP comments */ +strong dfn, strong dfn a,strong dfn var, strong dfn a u, strong dfn u{ + color:gray; + font-weight:normal; +} + /* attributes */ +s, s b, span s u, span s cite, strong span s { + color:#5656fa ; + font-weight:normal; +} + /* strings */ +strong s,strong s b, strong s u, strong s cite { + color:#009900; + font-weight:normal; +} +strong ins{ + color:#000000; + font-weight:bold; +} + /* Syntax */ +strong a, strong a u { + color:#0000FF; + font-weight:; +} + /* Native Keywords */ +strong u { + color:#990099; + font-weight:bold; +} +/* Numbers */ +strong var{ + color:#FF0000; +} +/* ASP Language */ +span{ + color:#990000; + font-weight:bold; +} +strong i,strong a i, strong u i { + color:#009999; +} +/* style */ +em { + color:#800080; + font-style:normal; +} + /* script */ +ins { + color:#800000; + font-weight:bold; +} + +/* */ +cite, s cite { + color:red; + font-weight:bold; +} \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/asp.js b/wp-includes/js/codepress/languages/asp.js new file mode 100644 index 0000000..21e78dd --- /dev/null +++ b/wp-includes/js/codepress/languages/asp.js @@ -0,0 +1,117 @@ +/* + * CodePress regular expressions for ASP-vbscript syntax highlighting + */ + +// ASP VBScript +Language.syntax = [ +// all tags + { input : /(<[^!%|!%@]*?>)/g, output : '$1' }, +// style tags + { input : /(<style.*?>)(.*?)(<\/style>)/g, output : '$1$2$3' }, +// script tags + { input : /(<script.*?>)(.*?)(<\/script>)/g, output : '$1$2$3' }, +// strings "" and attributes + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, +// ASP Comment + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2'}, +// <%.* + { input : /(<%)/g, output : '$1' }, +// .*%> + { input : /(%>)/g, output : '$1' }, +// <%@...%> + { input : /(<%@)(.+?)(%>)/gi, output : '$1$2$3' }, +//Numbers + { input : /\b([\d]+)\b/g, output : '$1' }, +// Reserved Words 1 (Blue) + { input : /\b(And|As|ByRef|ByVal|Call|Case|Class|Const|Dim|Do|Each|Else|ElseIf|Empty|End|Eqv|Exit|False|For|Function)\b/gi, output : '$1' }, + { input : /\b(Get|GoTo|If|Imp|In|Is|Let|Loop|Me|Mod|Enum|New|Next|Not|Nothing|Null|On|Option|Or|Private|Public|ReDim|Rem)\b/gi, output : '$1' }, + { input : /\b(Resume|Select|Set|Stop|Sub|Then|To|True|Until|Wend|While|With|Xor|Execute|Randomize|Erase|ExecuteGlobal|Explicit|step)\b/gi, output : '$1' }, +// Reserved Words 2 (Purple) + { input : /\b(Abandon|Abs|AbsolutePage|AbsolutePosition|ActiveCommand|ActiveConnection|ActualSize|AddHeader|AddNew|AppendChunk)\b/gi, output : '$1' }, + { input : /\b(AppendToLog|Application|Array|Asc|Atn|Attributes|BeginTrans|BinaryRead|BinaryWrite|BOF|Bookmark|Boolean|Buffer|Byte)\b/gi, output : '$1' }, + { input : /\b(CacheControl|CacheSize|Cancel|CancelBatch|CancelUpdate|CBool|CByte|CCur|CDate|CDbl|Charset|Chr|CInt|Clear)\b/gi, output : '$1' }, + { input : /\b(ClientCertificate|CLng|Clone|Close|CodePage|CommandText|CommandType|CommandTimeout|CommitTrans|CompareBookmarks|ConnectionString|ConnectionTimeout)\b/gi, output : '$1' }, + { input : /\b(Contents|ContentType|Cookies|Cos|CreateObject|CreateParameter|CSng|CStr|CursorLocation|CursorType|DataMember|DataSource|Date|DateAdd|DateDiff)\b/gi, output : '$1' }, + { input : /\b(DatePart|DateSerial|DateValue|Day|DefaultDatabase|DefinedSize|Delete|Description|Double|EditMode|Eof|EOF|err|Error)\b/gi, output : '$1' }, + { input : /\b(Exp|Expires|ExpiresAbsolute|Filter|Find|Fix|Flush|Form|FormatCurrency|FormatDateTime|FormatNumber|FormatPercent)\b/gi, output : '$1' }, + { input : /\b(GetChunk|GetLastError|GetRows|GetString|Global|HelpContext|HelpFile|Hex|Hour|HTMLEncode|IgnoreCase|Index|InStr|InStrRev)\b/gi, output : '$1' }, + { input : /\b(Int|Integer|IsArray|IsClientConnected|IsDate|IsolationLevel|Join|LBound|LCase|LCID|Left|Len|Lock|LockType|Log|Long|LTrim)\b/gi, output : '$1' }, + { input : /\b(MapPath|MarshalOptions|MaxRecords|Mid|Minute|Mode|Month|MonthName|Move|MoveFirst|MoveLast|MoveNext|MovePrevious|Name|NextRecordset)\b/gi, output : '$1' }, + { input : /\b(Now|Number|NumericScale|ObjectContext|Oct|Open|OpenSchema|OriginalValue|PageCount|PageSize|Pattern|PICS|Precision|Prepared|Property)\b/gi, output : '$1' }, + { input : /\b(Provider|QueryString|RecordCount|Redirect|RegExp|Remove|RemoveAll|Replace|Requery|Request|Response|Resync|Right|Rnd)\b/gi, output : '$1' }, + { input : /\b(RollbackTrans|RTrim|Save|ScriptTimeout|Second|Seek|Server|ServerVariables|Session|SessionID|SetAbort|SetComplete|Sgn)\b/gi, output : '$1' }, + { input : /\b(Sin|Size|Sort|Source|Space|Split|Sqr|State|StaticObjects|Status|StayInSync|StrComp|String|StrReverse|Supports|Tan|Time)\b/gi, output : '$1' }, + { input : /\b(Timeout|Timer|TimeSerial|TimeValue|TotalBytes|Transfer|Trim|Type|Type|UBound|UCase|UnderlyingValue|UnLock|Update|UpdateBatch)\b/gi, output : '$1' }, + { input : /\b(URLEncode|Value|Value|Version|Weekday|WeekdayName|Write|Year)\b/gi, output : '$1' }, +// Reserved Words 3 (Turquis) + { input : /\b(vbBlack|vbRed|vbGreen|vbYellow|vbBlue|vbMagenta|vbCyan|vbWhite|vbBinaryCompare|vbTextCompare)\b/gi, output : '$1' }, + { input : /\b(vbSunday|vbMonday|vbTuesday|vbWednesday|vbThursday|vbFriday|vbSaturday|vbUseSystemDayOfWeek)\b/gi, output : '$1' }, + { input : /\b(vbFirstJan1|vbFirstFourDays|vbFirstFullWeek|vbGeneralDate|vbLongDate|vbShortDate|vbLongTime|vbShortTime)\b/gi, output : '$1' }, + { input : /\b(vbObjectError|vbCr|VbCrLf|vbFormFeed|vbLf|vbNewLine|vbNullChar|vbNullString|vbTab|vbVerticalTab|vbUseDefault|vbTrue)\b/gi, output : '$1' }, + { input : /\b(vbFalse|vbEmpty|vbNull|vbInteger|vbLong|vbSingle|vbDouble|vbCurrency|vbDate|vbString|vbObject|vbError|vbBoolean|vbVariant)\b/gi, output : '$1' }, + { input : /\b(vbDataObject|vbDecimal|vbByte|vbArray)\b/gi, output : '$1' }, +// html comments + { input : /(<!--.*?-->.)/g, output : '$1' } +] + +Language.Functions = [ + // Output at index 0, must be the desired tagname surrounding a $1 + // Name is the index from the regex that marks the functionname + {input : /(function|sub)([ ]*?)(\w+)([ ]*?\()/gi , output : '$1', name : '$3'} +] + +Language.snippets = [ +//Conditional + { input : 'if', output : 'If $0 Then\n\t\nEnd If' }, + { input : 'ifelse', output : 'If $0 Then\n\t\n\nElse\n\t\nEnd If' }, + { input : 'case', output : 'Select Case $0\n\tCase ?\n\tCase Else\nEnd Select'}, +//Response + { input : 'rw', output : 'Response.Write( $0 )' }, + { input : 'resc', output : 'Response.Cookies( $0 )' }, + { input : 'resb', output : 'Response.Buffer'}, + { input : 'resflu', output : 'Response.Flush()'}, + { input : 'resend', output : 'Response.End'}, +//Request + { input : 'reqc', output : 'Request.Cookies( $0 )' }, + { input : 'rq', output : 'Request.Querystring("$0")' }, + { input : 'rf', output : 'Request.Form("$0")' }, +//FSO + { input : 'fso', output : 'Set fso = Server.CreateObject("Scripting.FileSystemObject")\n$0' }, + { input : 'setfo', output : 'Set fo = fso.getFolder($0)' }, + { input : 'setfi', output : 'Set fi = fso.getFile($0)' }, + { input : 'twr', output : 'Set f = fso.CreateTextFile($0,true)\'overwrite\nf.WriteLine()\nf.Close'}, + { input : 'tre', output : 'Set f = fso.OpenTextFile($0, 1)\nf.ReadAll\nf.Close'}, +//Server + { input : 'mapp', output : 'Server.Mappath($0)' }, +//Loops + { input : 'foreach', output : 'For Each $0 in ?\n\t\nNext' }, + { input : 'for', output : 'For $0 to ? step ?\n\t\nNext' }, + { input : 'do', output : 'Do While($0)\n\t\nLoop' }, + { input : 'untilrs', output : 'do until rs.eof\n\t\nrs.movenext\nloop' }, +//ADO + { input : 'adorec', output : 'Set rs = Server.CreateObject("ADODB.Recordset")' }, + { input : 'adocon', output : 'Set Conn = Server.CreateObject("ADODB.Connection")' }, + { input : 'adostr', output : 'Set oStr = Server.CreateObject("ADODB.Stream")' }, +//Http Request + { input : 'xmlhttp', output : 'Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")\nxmlHttp.open("GET", $0, false)\nxmlHttp.send()\n?=xmlHttp.responseText' }, + { input : 'xmldoc', output : 'Set xmldoc = Server.CreateObject("Microsoft.XMLDOM")\nxmldoc.async=false\nxmldoc.load(request)'}, +//Functions + { input : 'func', output : 'Function $0()\n\t\n\nEnd Function'}, + { input : 'sub', output : 'Sub $0()\n\t\nEnd Sub'} + +] + +Language.complete = [ + //{ input : '\'', output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [ + { input : '[space]', output : ' ' }, + { input : '[enter]', output : '
    ' } , + { input : '[j]', output : 'testing' }, + { input : '[7]', output : '&' } +] \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/autoit.css b/wp-includes/js/codepress/languages/autoit.css new file mode 100644 index 0000000..eb2b43b --- /dev/null +++ b/wp-includes/js/codepress/languages/autoit.css @@ -0,0 +1,13 @@ +/** + * CodePress color styles for AutoIt syntax highlighting + */ + +u {font-style:normal;color:#000090;font-weight:bold;font-family:Monospace;} +var {color:#AA0000;font-weight:bold;font-style:normal;} +em {color:#FF33FF;} +ins {color:#AC00A9;} +i {color:#F000FF;} +b {color:#FF0000;} +a {color:#0080FF;font-weight:bold;} +s, s u, s b {color:#9999CC;font-weight:normal;} +cite, cite *{color:#009933;font-weight:normal;} \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/autoit.js b/wp-includes/js/codepress/languages/autoit.js new file mode 100644 index 0000000..6f5c19d --- /dev/null +++ b/wp-includes/js/codepress/languages/autoit.js @@ -0,0 +1,32 @@ +/** + * CodePress regular expressions for AutoIt syntax highlighting + * @author: James Brooks, Michael HURNI + */ + +// AutoIt +Language.syntax = [ + { input : /({|}|\(|\))/g, output : '$1' }, // Brackets + { input : /(\*|\+|-)/g, output : '$1' }, // Operator + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : "\"$1$2" }, // strings double + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2' }, // strings single + { input : /\b([\d]+)\b/g, output : '$1' }, // Numbers + { input : /#(.*?)(
    |<\/P>)/g, output : '#$1$2' }, // Directives and Includes + { input : /(\$[\w\.]*)/g, output : '$1' }, // vars + { input : /(_[\w\.]*)/g, output : '$1' }, // underscored word + { input : /(\@[\w\.]*)/g, output : '$1' }, // Macros + { input : /\b(Abs|ACos|AdlibDisable|AdlibEnable|Asc|AscW|ASin|Assign|ATan|AutoItSetOption|AutoItWinGetTitle|AutoItWinSetTitle|Beep|Binary|BinaryLen|BinaryMid|BinaryToString|BitAND|BitNOT|BitOR|BitSHIFT|BitXOR|BlockInput|Break|Call|CDTray|Ceiling|Chr|ChrW|ClipGet|ClipPut|ConsoleRead|ConsoleWrite|ConsoleWriteError|ControlClick|ControlCommand|ControlDisable|ControlEnable|ControlFocus|ControlGetFocus|ControlGetHandle|ControlGetPos|ControlGetText|ControlHide|ControlListView|ControlMove|ControlSend|ControlSetText|ControlShow|Cos|Dec|DirCopy|DirCreate|DirGetSize|DirMove|DirRemove|DllCall|DllCall|DllClose|DllOpen|DllStructCreate|DllStructGetData|DllStructGetPtr|DllStructGetSize|DllStructSetData|DriveGetDrive|DriveGetFileSystem|DriveGetLabel|DriveGetSerial|DriveGetType|DriveMapAdd|DriveMapDel|DriveMapGet|DriveSetLabel|DriveSpaceFree|DriveSpaceTotal|DriveStatus|EnvGet|EnvSet|EnvUpdate|Eval|Execute|Exp|FileChangeDir|FileClose|FileCopy|FileCreateNTFS|FileCreateShortcut|FileDelete|FileExists|FileFindFirstFile|FileFindNextFile|FileGetAttrib|FileGetLongName|FileGetShortcut|FileGetShortName|FileGetSize|FileGetTime|FileGetVersion|FileInstall|FileMove|FileOpen|FileOpenDialog|FileRead|FileReadLine|FileRecycle|FileRecycleEmpty|FileSaveDialog|FileSelectFolder|FileSetAttrib|FileSetTime|FileWrite|FileWriteLine|Floor|FtpSetProxy|GuiCreate|GuiCtrlCreateAvi|GuiCtrlCreateButton|GuiCtrlCreateCheckbox|GuiCtrlCreateCombo|GuiCtrlCreateContextMenu|GuiCtrlCreateDate|GuiCtrlCreateDummy|GuiCtrlCreateEdit|GuiCtrlCreateGraphic|GuiCtrlCreateGroup|GuiCtrlCreateIcon|GuiCtrlCreateInput|GuiCtrlCreateLabel|GuiCtrlCreateList|GuiCtrlCreateListView|GuiCtrlCreateListViewItem|GuiCtrlCreateMenu|GuiCtrlCreateMenuItem|GuiCtrlCreateMonthCal|GuiCtrlCreateObj|GuiCtrlCreatePic|GuiCtrlCreateProgress|GuiCtrlCreateRadio|GuiCtrlCreateSlider|GuiCtrlCreateTab|GuiCtrlCreateTabItem|GuiCtrlCreateUpdown|GuiCtrlDelete|GuiCtrlGetHandle|GuiCtrlGetState|GuiCtrlRead|GuiCtrlRecvMsg|GuiCtrlSentMsg|GuiCtrlSendToDummy|GuiCtrlSetBkColor|GuiCtrlSetColor|GuiCtrlSetCursor|GuiCtrlSetData|GuiCtrlSetFont|GuiCtrlSetGraphic|GuiCtrlSetImage|GuiCtrlSetLimit|GuiCtrlSetOnEvent|GuiCtrlSetPos|GuiCtrlResizing|GuiCtrlSetState|GuiCtrlSetTip|GuiDelete|GuiGetCursorInfo|GuiGetMsg|GuiGetStyle|GuiRegisterMsg|GuiSetBkColor|GuiSetCoord|GuiSetCursor|GuiSetFont|GuiSetHelp|GuiSetIcon|GuiSetOnEvent|GuiSetStat|GuiSetStyle|GuiStartGroup|GuiSwitch|Hex|HotKeySet|HttpSetProxy|HWnd|InetGet|InetGetSize|IniDelete|IniRead|IniReadSection|IniReadSectionNames|IniRenameSection|IniWrite|IniWriteSection|InputBox|Int|IsAdmin|IsArray|IsBinary|IsBool|IsDeclared|IsDllStruct|IsFloat|IsHWnd|IsInt|IsKeyword|IsNumber|IsObj|IsString|Log|MemGetStats|Mod|MouseClick|MouseClickDrag|MouseDown|MouseGetCursor|MouseGetPos|MouseMove|MouseUp|MouseWheel|MsgBox|Number|ObjCreate|ObjEvent|ObjGet|ObjName|Ping|PixelCheckSum|PixelGetColor|PixelSearch|ProcessClose|ProcessExists|ProcessList|ProcessSetPriority|ProcessWait|ProcessWaitClose|ProgressOff|ProcessOn|ProgressSet|Random|RegDelete|RegEnumKey|RegEnumVal|RegRead|RegWrite|Round|Run|RunAsSet|RunWait|Send|SetError|SetExtended|ShellExecute|ShellExecuteWait|Shutdown|Sin|Sleep|SoundPlay|SoundSetWaveVolume|SplashImageOn|SplashOff|SplashTextOn|Sqrt|SRandom|StatusbarGetText|StderrRead|StdinWrite|StdoutRead|String|StringAddCR|StringCompare|StringFormat|StringInStr|StringIsAlNum|StringIsAlpha|StringIsASCII|StringIsDigit|StringIsFloat|StringIsInt|StringIsLower|StringIsSpace|StringIsUpper|StringIsXDigit|StringLeft|StringLen|StringLower|StringMid|StringRegExp|StringRegExpReplace|StringReplace|StringRight|StringSplit|StringStripCR|StringStripWS|StringToBinary|StringTrimLeft|StringTrimRight|StringUpper|Tan|TCPAccept|TCPCloseSocket|TCPConnect|TCPListen|TCPNameToIP|TCPrecv|TCPSend|TCPShutdown|TCPStartup|TimerDiff|TimerInit|ToolTip|TrayCreateItem|TrayCreateMenu|TrayGetMenu|TrayGetMsg|TrayItemDelete|TrayItemGetHandle|TrayItemGetState|TrayItemGetText|TrayItemSetOnEvent|TrayItemSetState|TrayItemSetText|TraySetClick|TraySetIcon|TraySetOnEvent|TraySetPauseIcon|TraySetState|TraySetToolTip|TrayTip|UBound|UDPBind|UDPCloseSocket|UDPOpen|UDPRecv|UDPSend|WinActivate|WinActive|WinClose|WinExists|WinFlash|WinGetCaretPos|WinGetClassList|WinGetClientSize|WinGetHandle|WinGetPos|WinGetProcess|WinGetState|WinGetText|WinGetTitle|WinKill|WinList|WinMenuSelectItem|WinMinimizeAll|WinMinimizeAllUndo|WinMove|WinSetOnTop|WinSetState|WinSetTitle|WinSetTrans|WinWait|WinWaitActive|WinWaitClose|WinWaitNotActive)\b/g, output : '$1' } ,// reserved words + { input : /\B;(.*?)(
    |<\/P>)/g, output : ';$1$2' }, // comments + { input : /#CS(.*?)#CE/g, output : '#CS$1#CE' } // Block Comments +] + +Language.snippets = [] + +Language.complete = [ +{ input : '\'',output : '\'$0\'' }, +{ input : '"', output : '"$0"' }, +{ input : '(', output : '\($0\)' }, +{ input : '[', output : '\[$0\]' }, +{ input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/csharp.css b/wp-includes/js/codepress/languages/csharp.css new file mode 100644 index 0000000..8464c5d --- /dev/null +++ b/wp-includes/js/codepress/languages/csharp.css @@ -0,0 +1,9 @@ +/* + * CodePress color styles for Java syntax highlighting + * By Edwin de Jonge + */ + +b {color:#7F0055;font-weight:bold;font-style:normal;} /* reserved words */ +a {color:#2A0088;font-weight:bold;font-style:normal;} /* types */ +i, i b, i s {color:#3F7F5F;font-weight:bold;} /* comments */ +s, s b {color:#2A00FF;font-weight:normal;} /* strings */ \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/csharp.js b/wp-includes/js/codepress/languages/csharp.js new file mode 100644 index 0000000..0a61fd5 --- /dev/null +++ b/wp-includes/js/codepress/languages/csharp.js @@ -0,0 +1,25 @@ +/* + * CodePress regular expressions for C# syntax highlighting + * By Edwin de Jonge + */ + +Language.syntax = [ // C# + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, // strings double quote + { input : /\'(.?)(\'|
    |<\/P>)/g, output : '\'$1$2' }, // strings single quote + { input : /\b(abstract|as|base|break|case|catch|checked|continue|default|delegate|do|else|event|explicit|extern|false|finally|fixed|for|foreach|get|goto|if|implicit|in|interface|internal|is|lock|namespace|new|null|object|operator|out|override|params|partial|private|protected|public|readonly|ref|return|set|sealed|sizeof|static|stackalloc|switch|this|throw|true|try|typeof|unchecked|unsafe|using|value|virtual|while)\b/g, output : '$1' }, // reserved words + { input : /\b(bool|byte|char|class|double|float|int|interface|long|string|struct|void)\b/g, output : '$1' }, // types + { input : /([^:]|^)\/\/(.*?)(//$2$3' }, // comments // + { input : /\/\*(.*?)\*\//g, output : '/*$1*/' } // comments /* */ +]; + +Language.snippets = []; + +Language.complete = [ // Auto complete only for 1 character + {input : '\'',output : '\'$0\'' }, + {input : '"', output : '"$0"' }, + {input : '(', output : '\($0\)' }, + {input : '[', output : '\[$0\]' }, + {input : '{', output : '{\n\t$0\n}' } +]; + +Language.shortcuts = []; \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/css.css b/wp-includes/js/codepress/languages/css.css new file mode 100644 index 0000000..49ba584 --- /dev/null +++ b/wp-includes/js/codepress/languages/css.css @@ -0,0 +1,10 @@ +/* + * CodePress color styles for CSS syntax highlighting + */ + +b, b a, b u {color:#000080;} /* tags, ids, classes */ +i, i b, i s, i a, i u {color:gray;} /* comments */ +s, s b {color:#a0a0dd;} /* parameters */ +a {color:#0000ff;} /* keys */ +u {color:red;} /* values */ + diff --git a/wp-includes/js/codepress/languages/css.js b/wp-includes/js/codepress/languages/css.js new file mode 100644 index 0000000..c29059b --- /dev/null +++ b/wp-includes/js/codepress/languages/css.js @@ -0,0 +1,23 @@ +/* + * CodePress regular expressions for CSS syntax highlighting + */ + +// CSS +Language.syntax = [ + { input : /(.*?){(.*?)}/g,output : '$1{$2}' }, // tags, ids, classes, values + { input : /([\w-]*?):([^\/])/g,output : '$1:$2' }, // keys + { input : /\((.*?)\)/g,output : '($1)' }, // parameters + { input : /\/\*(.*?)\*\//g,output : '/*$1*/'} // comments +] + +Language.snippets = [] + +Language.complete = [ + { input : '\'',output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/generic.css b/wp-includes/js/codepress/languages/generic.css new file mode 100644 index 0000000..712942f --- /dev/null +++ b/wp-includes/js/codepress/languages/generic.css @@ -0,0 +1,9 @@ +/* + * CodePress color styles for generic syntax highlighting + */ + +b {color:#7F0055;font-weight:bold;} /* reserved words */ +u {color:darkblue;font-weight:bold;} /* special words */ +i, i b, i s, i u, i em {color:green;font-weight:normal;} /* comments */ +s, s b, s em {color:#2A00FF;font-weight:normal;} /* strings */ +em {font-weight:bold;} /* special chars */ \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/generic.js b/wp-includes/js/codepress/languages/generic.js new file mode 100644 index 0000000..4c866de --- /dev/null +++ b/wp-includes/js/codepress/languages/generic.js @@ -0,0 +1,25 @@ +/* + * CodePress regular expressions for generic syntax highlighting + */ + +// generic languages +Language.syntax = [ + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, // strings double quote + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2' }, // strings single quote + { input : /\b(abstract|continue|for|new|switch|default|goto|boolean|do|if|private|this|break|double|protected|throw|byte|else|import|public|throws|case|return|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|const|float|while|function|label)\b/g, output : '$1' }, // reserved words + { input : /([\(\){}])/g, output : '$1' }, // special chars; + { input : /([^:]|^)\/\/(.*?)(//$2$3' }, // comments // + { input : /\/\*(.*?)\*\//g, output : '/*$1*/' } // comments /* */ +] + +Language.snippets = [] + +Language.complete = [ + { input : '\'', output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/html.css b/wp-includes/js/codepress/languages/html.css new file mode 100644 index 0000000..14882e5 --- /dev/null +++ b/wp-includes/js/codepress/languages/html.css @@ -0,0 +1,13 @@ +/* + * CodePress color styles for HTML syntax highlighting + */ + +b {color:#000080;} /* tags */ +ins, ins b, ins s, ins em {color:gray;} /* comments */ +s, s b {color:#7777e4;} /* attribute values */ +a {color:green;} /* links */ +u {color:#E67300;} /* forms */ +big {color:#db0000;} /* images */ +em, em b {color:#800080;} /* style */ +strong {color:#800000;} /* script */ +tt i {color:darkblue;font-weight:bold;} /* script reserved words */ diff --git a/wp-includes/js/codepress/languages/html.js b/wp-includes/js/codepress/languages/html.js new file mode 100644 index 0000000..4ead0b0 --- /dev/null +++ b/wp-includes/js/codepress/languages/html.js @@ -0,0 +1,59 @@ +/* + * CodePress regular expressions for HTML syntax highlighting + */ + +// HTML +Language.syntax = [ + { input : /(<[^!]*?>)/g, output : '$1' }, // all tags + { input : /(<a .*?>|<\/a>)/g, output : '$1' }, // links + { input : /(<img .*?>)/g, output : '$1' }, // images + { input : /(<\/?(button|textarea|form|input|select|option|label).*?>)/g, output : '$1' }, // forms + { input : /(<style.*?>)(.*?)(<\/style>)/g, output : '$1$2$3' }, // style tags + { input : /(<script.*?>)(.*?)(<\/script>)/g, output : '$1$2$3' }, // script tags + { input : /=(".*?")/g, output : '=$1' }, // atributes double quote + { input : /=('.*?')/g, output : '=$1' }, // atributes single quote + { input : /(<!--.*?-->.)/g, output : '$1' }, // comments + { input : /\b(alert|window|document|break|continue|do|for|new|this|void|case|default|else|function|return|typeof|while|if|label|switch|var|with|catch|boolean|int|try|false|throws|null|true|goto)\b/g, output : '$1' } // script reserved words +] + +Language.snippets = [ + { input : 'aref', output : '' }, + { input : 'h1', output : '

    $0

    ' }, + { input : 'h2', output : '

    $0

    ' }, + { input : 'h3', output : '

    $0

    ' }, + { input : 'h4', output : '

    $0

    ' }, + { input : 'h5', output : '
    $0
    ' }, + { input : 'h6', output : '
    $0
    ' }, + { input : 'html', output : '\n\t$0\n' }, + { input : 'head', output : '\n\t\n\t$0\n\t\n' }, + { input : 'img', output : '' }, + { input : 'input', output : '' }, + { input : 'label', output : '' }, + { input : 'legend', output : '\n\t$0\n' }, + { input : 'link', output : '' }, + { input : 'base', output : '' }, + { input : 'body', output : '\n\t$0\n' }, + { input : 'css', output : '' }, + { input : 'div', output : '
    \n\t$0\n
    ' }, + { input : 'divid', output : '
    \n\t\n
    ' }, + { input : 'dl', output : '
    \n\t
    \n\t\t$0\n\t
    \n\t
    \n
    ' }, + { input : 'fieldset', output : '
    \n\t$0\n
    ' }, + { input : 'form', output : '
    \n\t\n
    ' }, + { input : 'meta', output : '' }, + { input : 'p', output : '

    $0

    ' }, + { input : 'script', output : '' }, + { input : 'scriptsrc', output : '' }, + { input : 'span', output : '$0' }, + { input : 'table', output : '\n\t\n\t\n
    ' }, + { input : 'style', output : '' } +] + +Language.complete = [ + { input : '\'',output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/java.css b/wp-includes/js/codepress/languages/java.css new file mode 100644 index 0000000..b9c4441 --- /dev/null +++ b/wp-includes/js/codepress/languages/java.css @@ -0,0 +1,7 @@ +/* + * CodePress color styles for Java syntax highlighting + */ + +b {color:#7F0055;font-weight:bold;font-style:normal;} /* reserved words */ +i, i b, i s {color:#3F7F5F;font-weight:bold;} /* comments */ +s, s b {color:#2A00FF;font-weight:normal;} /* strings */ diff --git a/wp-includes/js/codepress/languages/java.js b/wp-includes/js/codepress/languages/java.js new file mode 100644 index 0000000..f0d620d --- /dev/null +++ b/wp-includes/js/codepress/languages/java.js @@ -0,0 +1,24 @@ +/* + * CodePress regular expressions for Java syntax highlighting + */ + +// Java +Language.syntax = [ + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2'}, // strings double quote + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2'}, // strings single quote + { input : /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/g, output : '$1'}, // reserved words + { input : /([^:]|^)\/\/(.*?)(//$2$3'}, // comments // + { input : /\/\*(.*?)\*\//g, output : '/*$1*/' }// comments /* */ +] + +Language.snippets = [] + +Language.complete = [ + { input : '\'',output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/javascript.css b/wp-includes/js/codepress/languages/javascript.css new file mode 100644 index 0000000..acbf49a --- /dev/null +++ b/wp-includes/js/codepress/languages/javascript.css @@ -0,0 +1,8 @@ +/* + * CodePress color styles for JavaScript syntax highlighting + */ + +b {color:#7F0055;font-weight:bold;} /* reserved words */ +u {color:darkblue;font-weight:bold;} /* special words */ +i, i b, i s, i u {color:green;font-weight:normal;} /* comments */ +s, s b, s u {color:#2A00FF;font-weight:normal;} /* strings */ diff --git a/wp-includes/js/codepress/languages/javascript.js b/wp-includes/js/codepress/languages/javascript.js new file mode 100644 index 0000000..66d0fc0 --- /dev/null +++ b/wp-includes/js/codepress/languages/javascript.js @@ -0,0 +1,30 @@ +/* + * CodePress regular expressions for JavaScript syntax highlighting + */ + +// JavaScript +Language.syntax = [ + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, // strings double quote + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2' }, // strings single quote + { input : /\b(break|continue|do|for|new|this|void|case|default|else|function|return|typeof|while|if|label|switch|var|with|catch|boolean|int|try|false|throws|null|true|goto)\b/g, output : '$1' }, // reserved words + { input : /\b(alert|isNaN|parent|Array|parseFloat|parseInt|blur|clearTimeout|prompt|prototype|close|confirm|length|Date|location|Math|document|element|name|self|elements|setTimeout|navigator|status|String|escape|Number|submit|eval|Object|event|onblur|focus|onerror|onfocus|onclick|top|onload|toString|onunload|unescape|open|valueOf|window|onmouseover)\b/g, output : '$1' }, // special words + { input : /([^:]|^)\/\/(.*?)(//$2$3' }, // comments // + { input : /\/\*(.*?)\*\//g, output : '/*$1*/' } // comments /* */ +] + +Language.snippets = [ + { input : 'dw', output : 'document.write(\'$0\');' }, + { input : 'getid', output : 'document.getElementById(\'$0\')' }, + { input : 'fun', output : 'function $0(){\n\t\n}' }, + { input : 'func', output : 'function $0(){\n\t\n}' } +] + +Language.complete = [ + { input : '\'',output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/perl.css b/wp-includes/js/codepress/languages/perl.css new file mode 100644 index 0000000..c2d6d56 --- /dev/null +++ b/wp-includes/js/codepress/languages/perl.css @@ -0,0 +1,11 @@ +/* + * CodePress color styles for Perl syntax highlighting + * By J. Nick Koston + */ + +b {color:#7F0055;font-weight:bold;} /* reserved words */ +i, i b, i s, i em, i a, i u {color:gray;font-weight:normal;} /* comments */ +s, s b, s a, s em, s u {color:#2A00FF;font-weight:normal;} /* strings */ +a {color:#006700;font-weight:bold;} /* variables */ +em {color:darkblue;font-weight:bold;} /* functions */ +u {font-weight:bold;} /* special chars */ \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/perl.js b/wp-includes/js/codepress/languages/perl.js new file mode 100644 index 0000000..06c380d --- /dev/null +++ b/wp-includes/js/codepress/languages/perl.js @@ -0,0 +1,27 @@ +/* + * CodePress regular expressions for Perl syntax highlighting + * By J. Nick Koston + */ + +// Perl +Language.syntax = [ + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, // strings double quote + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2' }, // strings single quote + { input : /([\$\@\%][\w\.]*)/g, output : '$1' }, // vars + { input : /(sub\s+)([\w\.]*)/g, output : '$1$2' }, // functions + { input : /\b(abs|accept|alarm|atan2|bind|binmode|bless|caller|chdir|chmod|chomp|chop|chown|chr|chroot|close|closedir|connect|continue|cos|crypt|dbmclose|dbmopen|defined|delete|die|do|dump|each|else|elsif|endgrent|endhostent|endnetent|endprotoent|endpwent|eof|eval|exec|exists|exit|fcntl|fileno|find|flock|for|foreach|fork|format|formlinegetc|getgrent|getgrgid|getgrnam|gethostbyaddr|gethostbyname|gethostent|getlogin|getnetbyaddr|getnetbyname|getnetent|getpeername|getpgrp|getppid|getpriority|getprotobyname|getprotobynumber|getprotoent|getpwent|getpwnam|getpwuid|getservbyaddr|getservbyname|getservbyport|getservent|getsockname|getsockopt|glob|gmtime|goto|grep|hex|hostname|if|import|index|int|ioctl|join|keys|kill|last|lc|lcfirst|length|link|listen|LoadExternals|local|localtime|log|lstat|map|mkdir|msgctl|msgget|msgrcv|msgsnd|my|next|no|oct|open|opendir|ordpack|package|pipe|pop|pos|print|printf|push|pwd|qq|quotemeta|qw|rand|read|readdir|readlink|recv|redo|ref|rename|require|reset|return|reverse|rewinddir|rindex|rmdir|scalar|seek|seekdir|select|semctl|semget|semop|send|setgrent|sethostent|setnetent|setpgrp|setpriority|setprotoent|setpwent|setservent|setsockopt|shift|shmctl|shmget|shmread|shmwrite|shutdown|sin|sleep|socket|socketpair|sort|splice|split|sprintf|sqrt|srand|stat|stty|study|sub|substr|symlink|syscall|sysopen|sysread|system|syswritetell|telldir|tie|tied|time|times|tr|truncate|uc|ucfirst|umask|undef|unless|unlink|until|unpack|unshift|untie|use|utime|values|vec|waitpid|wantarray|warn|while|write)\b/g, output : '$1' }, // reserved words + { input : /([\(\){}])/g, output : '$1' }, // special chars + { input : /#(.*?)(
    |<\/P>)/g, output : '#$1$2' } // comments +] + +Language.snippets = [] + +Language.complete = [ + { input : '\'',output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/php.css b/wp-includes/js/codepress/languages/php.css new file mode 100644 index 0000000..23fca5c --- /dev/null +++ b/wp-includes/js/codepress/languages/php.css @@ -0,0 +1,12 @@ +/* + * CodePress color styles for PHP syntax highlighting + */ + +b {color:#000080;} /* tags */ +big, big b, big em, big ins, big s, strong i, strong i b, strong i s, strong i u, strong i a, strong i a u, strong i s u {color:gray;font-weight:normal;} /* comments */ +s, s b, strong s u, strong s cite {color:#5656fa;font-weight:normal;} /* attributes and strings */ +strong a, strong a u {color:#006700;font-weight:bold;} /* variables */ +em {color:#800080;font-style:normal;} /* style */ +ins {color:#800000;} /* script */ +strong u {color:#7F0055;font-weight:bold;} /* reserved words */ +cite, s cite {color:red;font-weight:bold;} /* */ diff --git a/wp-includes/js/codepress/languages/php.js b/wp-includes/js/codepress/languages/php.js new file mode 100644 index 0000000..1689fba --- /dev/null +++ b/wp-includes/js/codepress/languages/php.js @@ -0,0 +1,61 @@ +/* + * CodePress regular expressions for PHP syntax highlighting + */ + +// PHP +Language.syntax = [ + { input : /(<[^!\?]*?>)/g, output : '$1' }, // all tags + { input : /(<style.*?>)(.*?)(<\/style>)/g, output : '$1$2$3' }, // style tags + { input : /(<script.*?>)(.*?)(<\/script>)/g, output : '$1$2$3' }, // script tags + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, // strings double quote + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2'}, // strings single quote + { input : /(<\?)/g, output : '$1' }, // ' }, // .*?> + { input : /(<\?php|<\?=|<\?|\?>)/g, output : '$1' }, // php tags + { input : /(\$[\w\.]*)/g, output : '$1' }, // vars + { input : /\b(false|true|and|or|xor|__FILE__|exception|__LINE__|array|as|break|case|class|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|eval|exit|extends|for|foreach|function|global|if|include|include_once|isset|list|new|print|require|require_once|return|static|switch|unset|use|while|__FUNCTION__|__CLASS__|__METHOD__|final|php_user_filter|interface|implements|extends|public|private|protected|abstract|clone|try|catch|throw|this)\b/g, output : '$1' }, // reserved words + { input : /([^:])\/\/(.*?)(//$2$3' }, // php comments // + { input : /([^:])#(.*?)(#$2$3' }, // php comments # + { input : /\/\*(.*?)\*\//g, output : '/*$1*/' }, // php comments /* */ + { input : /(<!--.*?-->.)/g, output : '$1' } // html comments +] + +Language.snippets = [ + { input : 'if', output : 'if($0){\n\t\n}' }, + { input : 'ifelse', output : 'if($0){\n\t\n}\nelse{\n\t\n}' }, + { input : 'else', output : '}\nelse {\n\t' }, + { input : 'elseif', output : '}\nelseif($0) {\n\t' }, + { input : 'do', output : 'do{\n\t$0\n}\nwhile();' }, + { input : 'inc', output : 'include_once("$0");' }, + { input : 'fun', output : 'function $0(){\n\t\n}' }, + { input : 'func', output : 'function $0(){\n\t\n}' }, + { input : 'while', output : 'while($0){\n\t\n}' }, + { input : 'for', output : 'for($0,,){\n\t\n}' }, + { input : 'fore', output : 'foreach($0 as ){\n\t\n}' }, + { input : 'foreach', output : 'foreach($0 as ){\n\t\n}' }, + { input : 'echo', output : 'echo \'$0\';' }, + { input : 'switch', output : 'switch($0) {\n\tcase "": break;\n\tdefault: ;\n}' }, + { input : 'case', output : 'case "$0" : break;' }, + { input : 'ret0', output : 'return false;' }, + { input : 'retf', output : 'return false;' }, + { input : 'ret1', output : 'return true;' }, + { input : 'rett', output : 'return true;' }, + { input : 'ret', output : 'return $0;' }, + { input : 'def', output : 'define(\'$0\',\'\');' }, + { input : '' } +] + +Language.complete = [ + { input : '\'', output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [ + { input : '[space]', output : ' ' }, + { input : '[enter]', output : '
    ' } , + { input : '[j]', output : 'testing' }, + { input : '[7]', output : '&' } +] \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/ruby.css b/wp-includes/js/codepress/languages/ruby.css new file mode 100644 index 0000000..edb9028 --- /dev/null +++ b/wp-includes/js/codepress/languages/ruby.css @@ -0,0 +1,10 @@ +/* + * CodePress color styles for Ruby syntax highlighting + */ + +b {color:#7F0055;font-weight:bold;} /* reserved words */ +i, i b, i s, i em, i a, i u {color:gray;font-weight:normal;} /* comments */ +s, s b, s a, s em, s u {color:#2A00FF;font-weight:normal;} /* strings */ +a {color:#006700;font-weight:bold;} /* variables */ +em {color:darkblue;font-weight:bold;} /* functions */ +u {font-weight:bold;} /* special chars */ \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/ruby.js b/wp-includes/js/codepress/languages/ruby.js new file mode 100644 index 0000000..207f23b --- /dev/null +++ b/wp-includes/js/codepress/languages/ruby.js @@ -0,0 +1,26 @@ +/* + * CodePress regular expressions for Perl syntax highlighting + */ + +// Ruby +Language.syntax = [ + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, // strings double quote + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2' }, // strings single quote + { input : /([\$\@\%]+)([\w\.]*)/g, output : '$1$2' }, // vars + { input : /(def\s+)([\w\.]*)/g, output : '$1$2' }, // functions + { input : /\b(alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|false|for|if|in|module|next|nil|not|or|redo|rescue|retry|return|self|super|then|true|undef|unless|until|when|while|yield)\b/g, output : '$1' }, // reserved words + { input : /([\(\){}])/g, output : '$1' }, // special chars + { input : /#(.*?)(
    |<\/P>)/g, output : '#$1$2' } // comments +]; + +Language.snippets = [] + +Language.complete = [ + { input : '\'',output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/sql.css b/wp-includes/js/codepress/languages/sql.css new file mode 100644 index 0000000..92c4b96 --- /dev/null +++ b/wp-includes/js/codepress/languages/sql.css @@ -0,0 +1,10 @@ +/* + * CodePress color styles for SQL syntax highlighting + * By Merlin Moncure + */ + +b {color:#0000FF;font-style:normal;font-weight:bold;} /* reserved words */ +u {color:#FF0000;font-style:normal;} /* types */ +a {color:#CD6600;font-style:normal;font-weight:bold;} /* commands */ +i, i b, i u, i a, i s {color:#A9A9A9;font-weight:normal;font-style:italic;} /* comments */ +s, s b, s u, s a, s i {color:#2A00FF;font-weight:normal;} /* strings */ diff --git a/wp-includes/js/codepress/languages/sql.js b/wp-includes/js/codepress/languages/sql.js new file mode 100644 index 0000000..1d4a21f --- /dev/null +++ b/wp-includes/js/codepress/languages/sql.js @@ -0,0 +1,30 @@ +/* + * CodePress regular expressions for SQL syntax highlighting + * By Merlin Moncure + */ + +// SQL +Language.syntax = [ + { input : /\'(.*?)(\')/g, output : '\'$1$2' }, // strings single quote + { input : /\b(add|after|aggregate|alias|all|and|as|authorization|between|by|cascade|cache|cache|called|case|check|column|comment|constraint|createdb|createuser|cycle|database|default|deferrable|deferred|diagnostics|distinct|domain|each|else|elseif|elsif|encrypted|except|exception|for|foreign|from|from|full|function|get|group|having|if|immediate|immutable|in|increment|initially|increment|index|inherits|inner|input|intersect|into|invoker|is|join|key|language|left|like|limit|local|loop|match|maxvalue|minvalue|natural|nextval|no|nocreatedb|nocreateuser|not|null|of|offset|oids|on|only|operator|or|order|outer|owner|partial|password|perform|plpgsql|primary|record|references|replace|restrict|return|returns|right|row|rule|schema|security|sequence|session|sql|stable|statistics|table|temp|temporary|then|time|to|transaction|trigger|type|unencrypted|union|unique|user|using|valid|value|values|view|volatile|when|where|with|without|zone)\b/gi, output : '$1' }, // reserved words + { input : /\b(bigint|bigserial|bit|boolean|box|bytea|char|character|cidr|circle|date|decimal|double|float4|float8|inet|int2|int4|int8|integer|interval|line|lseg|macaddr|money|numeric|oid|path|point|polygon|precision|real|refcursor|serial|serial4|serial8|smallint|text|timestamp|varbit|varchar)\b/gi, output : '$1' }, // types + { input : /\b(abort|alter|analyze|begin|checkpoint|close|cluster|comment|commit|copy|create|deallocate|declare|delete|drop|end|execute|explain|fetch|grant|insert|listen|load|lock|move|notify|prepare|reindex|reset|restart|revoke|rollback|select|set|show|start|truncate|unlisten|update)\b/gi, output : '$1' }, // commands + { input : /([^:]|^)\-\-(.*?)(--$2$3' } // comments // +] + +Language.snippets = [ + { input : 'select', output : 'select $0 from where ' } +] + +Language.complete = [ + { input : '\'', output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [] + + + diff --git a/wp-includes/js/codepress/languages/text.css b/wp-includes/js/codepress/languages/text.css new file mode 100644 index 0000000..474fe60 --- /dev/null +++ b/wp-includes/js/codepress/languages/text.css @@ -0,0 +1,5 @@ +/* + * CodePress color styles for Text syntax highlighting + */ + +/* do nothing as expected */ diff --git a/wp-includes/js/codepress/languages/text.js b/wp-includes/js/codepress/languages/text.js new file mode 100644 index 0000000..6534aaf --- /dev/null +++ b/wp-includes/js/codepress/languages/text.js @@ -0,0 +1,9 @@ +/* + * CodePress regular expressions for Text syntax highlighting + */ + +// plain text +Language.syntax = [] +Language.snippets = [] +Language.complete = [] +Language.shortcuts = [] diff --git a/wp-includes/js/codepress/languages/vbscript.css b/wp-includes/js/codepress/languages/vbscript.css new file mode 100644 index 0000000..e1465e9 --- /dev/null +++ b/wp-includes/js/codepress/languages/vbscript.css @@ -0,0 +1,71 @@ +/* + * CodePress color styles for ASP-VB syntax highlighting + * By Martin D. Kirk + */ + +/* tags */ +b { + color:#000080; +} +/* comments */ +big, big b, big em, big ins, big s, strong i, strong i b, strong i s, strong i u, strong i a, strong i a u, strong i s u { + color:gray; + font-weight:normal; +} +/* ASP comments */ +strong dfn, strong dfn a,strong dfn var, strong dfn a u, strong dfn u{ + color:gray; + font-weight:normal; +} + /* attributes */ +s, s b, span s u, span s cite, strong span s { + color:#5656fa ; + font-weight:normal; +} + /* strings */ +strong s,strong s b, strong s u, strong s cite { + color:#009900; + font-weight:normal; +} +strong ins{ + color:#000000; + font-weight:bold; +} + /* Syntax */ +strong a, strong a u { + color:#0000FF; + font-weight:; +} + /* Native Keywords */ +strong u { + color:#990099; + font-weight:bold; +} +/* Numbers */ +strong var{ + color:#FF0000; +} +/* ASP Language */ +span{ + color:#990000; + font-weight:bold; +} +strong i,strong a i, strong u i { + color:#009999; +} +/* style */ +em { + color:#800080; + font-style:normal; +} + /* script */ +ins { + color:#800000; + font-weight:bold; +} + +/* */ +cite, s cite { + color:red; + font-weight:bold; +} \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/vbscript.js b/wp-includes/js/codepress/languages/vbscript.js new file mode 100644 index 0000000..21e78dd --- /dev/null +++ b/wp-includes/js/codepress/languages/vbscript.js @@ -0,0 +1,117 @@ +/* + * CodePress regular expressions for ASP-vbscript syntax highlighting + */ + +// ASP VBScript +Language.syntax = [ +// all tags + { input : /(<[^!%|!%@]*?>)/g, output : '$1' }, +// style tags + { input : /(<style.*?>)(.*?)(<\/style>)/g, output : '$1$2$3' }, +// script tags + { input : /(<script.*?>)(.*?)(<\/script>)/g, output : '$1$2$3' }, +// strings "" and attributes + { input : /\"(.*?)(\"|
    |<\/P>)/g, output : '"$1$2' }, +// ASP Comment + { input : /\'(.*?)(\'|
    |<\/P>)/g, output : '\'$1$2'}, +// <%.* + { input : /(<%)/g, output : '$1' }, +// .*%> + { input : /(%>)/g, output : '$1' }, +// <%@...%> + { input : /(<%@)(.+?)(%>)/gi, output : '$1$2$3' }, +//Numbers + { input : /\b([\d]+)\b/g, output : '$1' }, +// Reserved Words 1 (Blue) + { input : /\b(And|As|ByRef|ByVal|Call|Case|Class|Const|Dim|Do|Each|Else|ElseIf|Empty|End|Eqv|Exit|False|For|Function)\b/gi, output : '$1' }, + { input : /\b(Get|GoTo|If|Imp|In|Is|Let|Loop|Me|Mod|Enum|New|Next|Not|Nothing|Null|On|Option|Or|Private|Public|ReDim|Rem)\b/gi, output : '$1' }, + { input : /\b(Resume|Select|Set|Stop|Sub|Then|To|True|Until|Wend|While|With|Xor|Execute|Randomize|Erase|ExecuteGlobal|Explicit|step)\b/gi, output : '$1' }, +// Reserved Words 2 (Purple) + { input : /\b(Abandon|Abs|AbsolutePage|AbsolutePosition|ActiveCommand|ActiveConnection|ActualSize|AddHeader|AddNew|AppendChunk)\b/gi, output : '$1' }, + { input : /\b(AppendToLog|Application|Array|Asc|Atn|Attributes|BeginTrans|BinaryRead|BinaryWrite|BOF|Bookmark|Boolean|Buffer|Byte)\b/gi, output : '$1' }, + { input : /\b(CacheControl|CacheSize|Cancel|CancelBatch|CancelUpdate|CBool|CByte|CCur|CDate|CDbl|Charset|Chr|CInt|Clear)\b/gi, output : '$1' }, + { input : /\b(ClientCertificate|CLng|Clone|Close|CodePage|CommandText|CommandType|CommandTimeout|CommitTrans|CompareBookmarks|ConnectionString|ConnectionTimeout)\b/gi, output : '$1' }, + { input : /\b(Contents|ContentType|Cookies|Cos|CreateObject|CreateParameter|CSng|CStr|CursorLocation|CursorType|DataMember|DataSource|Date|DateAdd|DateDiff)\b/gi, output : '$1' }, + { input : /\b(DatePart|DateSerial|DateValue|Day|DefaultDatabase|DefinedSize|Delete|Description|Double|EditMode|Eof|EOF|err|Error)\b/gi, output : '$1' }, + { input : /\b(Exp|Expires|ExpiresAbsolute|Filter|Find|Fix|Flush|Form|FormatCurrency|FormatDateTime|FormatNumber|FormatPercent)\b/gi, output : '$1' }, + { input : /\b(GetChunk|GetLastError|GetRows|GetString|Global|HelpContext|HelpFile|Hex|Hour|HTMLEncode|IgnoreCase|Index|InStr|InStrRev)\b/gi, output : '$1' }, + { input : /\b(Int|Integer|IsArray|IsClientConnected|IsDate|IsolationLevel|Join|LBound|LCase|LCID|Left|Len|Lock|LockType|Log|Long|LTrim)\b/gi, output : '$1' }, + { input : /\b(MapPath|MarshalOptions|MaxRecords|Mid|Minute|Mode|Month|MonthName|Move|MoveFirst|MoveLast|MoveNext|MovePrevious|Name|NextRecordset)\b/gi, output : '$1' }, + { input : /\b(Now|Number|NumericScale|ObjectContext|Oct|Open|OpenSchema|OriginalValue|PageCount|PageSize|Pattern|PICS|Precision|Prepared|Property)\b/gi, output : '$1' }, + { input : /\b(Provider|QueryString|RecordCount|Redirect|RegExp|Remove|RemoveAll|Replace|Requery|Request|Response|Resync|Right|Rnd)\b/gi, output : '$1' }, + { input : /\b(RollbackTrans|RTrim|Save|ScriptTimeout|Second|Seek|Server|ServerVariables|Session|SessionID|SetAbort|SetComplete|Sgn)\b/gi, output : '$1' }, + { input : /\b(Sin|Size|Sort|Source|Space|Split|Sqr|State|StaticObjects|Status|StayInSync|StrComp|String|StrReverse|Supports|Tan|Time)\b/gi, output : '$1' }, + { input : /\b(Timeout|Timer|TimeSerial|TimeValue|TotalBytes|Transfer|Trim|Type|Type|UBound|UCase|UnderlyingValue|UnLock|Update|UpdateBatch)\b/gi, output : '$1' }, + { input : /\b(URLEncode|Value|Value|Version|Weekday|WeekdayName|Write|Year)\b/gi, output : '$1' }, +// Reserved Words 3 (Turquis) + { input : /\b(vbBlack|vbRed|vbGreen|vbYellow|vbBlue|vbMagenta|vbCyan|vbWhite|vbBinaryCompare|vbTextCompare)\b/gi, output : '$1' }, + { input : /\b(vbSunday|vbMonday|vbTuesday|vbWednesday|vbThursday|vbFriday|vbSaturday|vbUseSystemDayOfWeek)\b/gi, output : '$1' }, + { input : /\b(vbFirstJan1|vbFirstFourDays|vbFirstFullWeek|vbGeneralDate|vbLongDate|vbShortDate|vbLongTime|vbShortTime)\b/gi, output : '$1' }, + { input : /\b(vbObjectError|vbCr|VbCrLf|vbFormFeed|vbLf|vbNewLine|vbNullChar|vbNullString|vbTab|vbVerticalTab|vbUseDefault|vbTrue)\b/gi, output : '$1' }, + { input : /\b(vbFalse|vbEmpty|vbNull|vbInteger|vbLong|vbSingle|vbDouble|vbCurrency|vbDate|vbString|vbObject|vbError|vbBoolean|vbVariant)\b/gi, output : '$1' }, + { input : /\b(vbDataObject|vbDecimal|vbByte|vbArray)\b/gi, output : '$1' }, +// html comments + { input : /(<!--.*?-->.)/g, output : '$1' } +] + +Language.Functions = [ + // Output at index 0, must be the desired tagname surrounding a $1 + // Name is the index from the regex that marks the functionname + {input : /(function|sub)([ ]*?)(\w+)([ ]*?\()/gi , output : '$1', name : '$3'} +] + +Language.snippets = [ +//Conditional + { input : 'if', output : 'If $0 Then\n\t\nEnd If' }, + { input : 'ifelse', output : 'If $0 Then\n\t\n\nElse\n\t\nEnd If' }, + { input : 'case', output : 'Select Case $0\n\tCase ?\n\tCase Else\nEnd Select'}, +//Response + { input : 'rw', output : 'Response.Write( $0 )' }, + { input : 'resc', output : 'Response.Cookies( $0 )' }, + { input : 'resb', output : 'Response.Buffer'}, + { input : 'resflu', output : 'Response.Flush()'}, + { input : 'resend', output : 'Response.End'}, +//Request + { input : 'reqc', output : 'Request.Cookies( $0 )' }, + { input : 'rq', output : 'Request.Querystring("$0")' }, + { input : 'rf', output : 'Request.Form("$0")' }, +//FSO + { input : 'fso', output : 'Set fso = Server.CreateObject("Scripting.FileSystemObject")\n$0' }, + { input : 'setfo', output : 'Set fo = fso.getFolder($0)' }, + { input : 'setfi', output : 'Set fi = fso.getFile($0)' }, + { input : 'twr', output : 'Set f = fso.CreateTextFile($0,true)\'overwrite\nf.WriteLine()\nf.Close'}, + { input : 'tre', output : 'Set f = fso.OpenTextFile($0, 1)\nf.ReadAll\nf.Close'}, +//Server + { input : 'mapp', output : 'Server.Mappath($0)' }, +//Loops + { input : 'foreach', output : 'For Each $0 in ?\n\t\nNext' }, + { input : 'for', output : 'For $0 to ? step ?\n\t\nNext' }, + { input : 'do', output : 'Do While($0)\n\t\nLoop' }, + { input : 'untilrs', output : 'do until rs.eof\n\t\nrs.movenext\nloop' }, +//ADO + { input : 'adorec', output : 'Set rs = Server.CreateObject("ADODB.Recordset")' }, + { input : 'adocon', output : 'Set Conn = Server.CreateObject("ADODB.Connection")' }, + { input : 'adostr', output : 'Set oStr = Server.CreateObject("ADODB.Stream")' }, +//Http Request + { input : 'xmlhttp', output : 'Set xmlHttp = Server.CreateObject("Microsoft.XMLHTTP")\nxmlHttp.open("GET", $0, false)\nxmlHttp.send()\n?=xmlHttp.responseText' }, + { input : 'xmldoc', output : 'Set xmldoc = Server.CreateObject("Microsoft.XMLDOM")\nxmldoc.async=false\nxmldoc.load(request)'}, +//Functions + { input : 'func', output : 'Function $0()\n\t\n\nEnd Function'}, + { input : 'sub', output : 'Sub $0()\n\t\nEnd Sub'} + +] + +Language.complete = [ + //{ input : '\'', output : '\'$0\'' }, + { input : '"', output : '"$0"' }, + { input : '(', output : '\($0\)' }, + { input : '[', output : '\[$0\]' }, + { input : '{', output : '{\n\t$0\n}' } +] + +Language.shortcuts = [ + { input : '[space]', output : ' ' }, + { input : '[enter]', output : '
    ' } , + { input : '[j]', output : 'testing' }, + { input : '[7]', output : '&' } +] \ No newline at end of file diff --git a/wp-includes/js/codepress/languages/xsl.css b/wp-includes/js/codepress/languages/xsl.css new file mode 100644 index 0000000..385eaab --- /dev/null +++ b/wp-includes/js/codepress/languages/xsl.css @@ -0,0 +1,15 @@ +/* + * CodePress color styles for HTML syntax highlighting + * By RJ Bruneel + */ + +b {color:#000080;} /* tags */ +ins, ins b, ins s, ins em {color:gray;} /* comments */ +s, s b {color:#7777e4;} /* attribute values */ +a {color:#E67300;} /* links */ +u {color:#CC66CC;} /* forms */ +big {color:#db0000;} /* images */ +em, em b {color:#800080;} /* style */ +strong {color:#800000;} /* script */ +tt i {color:darkblue;font-weight:bold;} /* script reserved words */ +xsl {color:green;} /* xsl */ diff --git a/wp-includes/js/codepress/languages/xsl.js b/wp-includes/js/codepress/languages/xsl.js new file mode 100644 index 0000000..e93932a --- /dev/null +++ b/wp-includes/js/codepress/languages/xsl.js @@ -0,0 +1,103 @@ +/* + * CodePress regular expressions for XSL syntax highlighting + * By RJ Bruneel + */ + +Language.syntax = [ // XSL + { + input : /(<[^!]*?>)/g, + output : '$1' // all tags + },{ + input : /(<a.*?>|<\/a>)/g, + output : '$1' // links + },{ + input : /(<img .*?>)/g, + output : '$1' // images + },{ + input : /(<\/?(button|textarea|form|input|select|option|label).*?>)/g, + output : '$1' // forms + },{ + input : /(<style.*?>)(.*?)(<\/style>)/g, + output : '$1$2$3' // style tags + },{ + input : /(<script.*?>)(.*?)(<\/script>)/g, + output : '$1$2$3' // script tags + },{ + input : /(<xsl.*?>|<\/xsl.*?>)/g, + output : '$1' // xsl + },{ + input : /=(".*?")/g, + output : '=$1' // atributes double quote + },{ + input : /=('.*?')/g, + output : '=$1' // atributes single quote + },{ + input : /(<!--.*?-->.)/g, + output : '$1' // comments + },{ + input : /\b(alert|window|document|break|continue|do|for|new|this|void|case|default|else|function|return|typeof|while|if|label|switch|var|with|catch|boolean|int|try|false|throws|null|true|goto)\b/g, + output : '$1' // script reserved words + } +]; + +Language.snippets = [ + {input : 'aref', output : '' }, + {input : 'h1', output : '

    $0

    ' }, + {input : 'h2', output : '

    $0

    ' }, + {input : 'h3', output : '

    $0

    ' }, + {input : 'h4', output : '

    $0

    ' }, + {input : 'h5', output : '
    $0
    ' }, + {input : 'h6', output : '
    $0
    ' }, + {input : 'html', output : '\n\t$0\n' }, + {input : 'head', output : '\n\t\n\t$0\n\t\n' }, + {input : 'img', output : '' }, + {input : 'input', output : '' }, + {input : 'label', output : '' }, + {input : 'legend', output : '\n\t$0\n' }, + {input : 'link', output : '' }, + {input : 'base', output : '' }, + {input : 'body', output : '\n\t$0\n' }, + {input : 'css', output : '' }, + {input : 'div', output : '
    \n\t$0\n
    ' }, + {input : 'divid', output : '
    \n\t\n
    ' }, + {input : 'dl', output : '
    \n\t
    \n\t\t$0\n\t
    \n\t
    \n
    ' }, + {input : 'fieldset', output : '
    \n\t$0\n
    ' }, + {input : 'form', output : '
    \n\t\n
    ' }, + {input : 'meta', output : '' }, + {input : 'p', output : '

    $0

    ' }, + {input : 'b', output : '$0' }, + {input : 'li', output : '
  • $0
  • ' }, + {input : 'ul', output : '
      $0
    ' }, + {input : 'ol', output : '
      $0
    ' }, + {input : 'strong', output : '$0' }, + {input : 'br', output : '
    ' }, + {input : 'script', output : '' }, + {input : 'scriptsrc', output : '' }, + {input : 'span', output : '$0' }, + {input : 'table', output : '\n\t\n\t\n
    ' }, + {input : 'style', output : '' }, + {input : 'xsl:stylesheet', output : '' }, + {input : 'xsl:template', output : '$0' }, + {input : 'xsl:for-each', output : '' }, + {input : 'xsl:choose', output : '$0<\xsl:choose>' }, + {input : 'xsl:param', output : '' }, + {input : 'xsl:variable', output : '' }, + {input : 'xsl:if', output : '' }, + {input : 'xsl:when', output : '' }, + {input : 'xsl:otherwise', output : '$0' }, + {input : 'xsl:attribute', output : '' }, + {input : 'xsl:value-of', output : '' }, + {input : 'xsl:with-param', output : '' }, + {input : 'xsl:call-template', output : '' } + +]; + +Language.complete = [ // Auto complete only for 1 character + {input : '\'',output : '\'$0\'' }, + {input : '"', output : '"$0"' }, + {input : '(', output : '\($0\)' }, + {input : '[', output : '\[$0\]' }, + {input : '{', output : '{\n\t$0\n}' } +]; + +Language.shortcuts = []; \ No newline at end of file diff --git a/wp-includes/js/codepress/license.txt b/wp-includes/js/codepress/license.txt new file mode 100644 index 0000000..e80ac68 --- /dev/null +++ b/wp-includes/js/codepress/license.txt @@ -0,0 +1,458 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +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 this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser 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 Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "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 +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY 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 +LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/wp-includes/js/colorpicker.dev.js b/wp-includes/js/colorpicker.dev.js new file mode 100644 index 0000000..1fc32cf --- /dev/null +++ b/wp-includes/js/colorpicker.dev.js @@ -0,0 +1,707 @@ +// =================================================================== +// Author: Matt Kruse +// WWW: http://www.mattkruse.com/ +// +// NOTICE: You may use this code for any purpose, commercial or +// private, without any further permission from the author. You may +// remove this notice from your final code if you wish, however it is +// appreciated by the author if at least my web site address is kept. +// +// You may *NOT* re-distribute this code in any way except through its +// use. That means, you can include it in your product, or your web +// site, or any other form where the code is actually being used. You +// may not put the plain javascript up on your site for download or +// include it in your javascript libraries for download. +// If you wish to share this code with others, please just point them +// to the URL instead. +// Please DO NOT link directly to my .js files from your site. Copy +// the files to your server and use them there. Thank you. +// =================================================================== + + +/* SOURCE FILE: AnchorPosition.js */ + +/* +AnchorPosition.js +Author: Matt Kruse +Last modified: 10/11/02 + +DESCRIPTION: These functions find the position of an tag in a document, +so other elements can be positioned relative to it. + +COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small +positioning errors - usually with Window positioning - occur on the +Macintosh platform. + +FUNCTIONS: +getAnchorPosition(anchorname) + Returns an Object() having .x and .y properties of the pixel coordinates + of the upper-left corner of the anchor. Position is relative to the PAGE. + +getAnchorWindowPosition(anchorname) + Returns an Object() having .x and .y properties of the pixel coordinates + of the upper-left corner of the anchor, relative to the WHOLE SCREEN. + +NOTES: + +1) For popping up separate browser windows, use getAnchorWindowPosition. + Otherwise, use getAnchorPosition + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. +*/ + +// getAnchorPosition(anchorname) +// This function returns an object having .x and .y properties which are the coordinates +// of the named anchor, relative to the page. +function getAnchorPosition(anchorname) { + // This function will return an Object with x and y properties + var useWindow=false; + var coordinates=new Object(); + var x=0,y=0; + // Browser capability sniffing + var use_gebi=false, use_css=false, use_layers=false; + if (document.getElementById) { use_gebi=true; } + else if (document.all) { use_css=true; } + else if (document.layers) { use_layers=true; } + // Logic to find position + if (use_gebi && document.all) { + x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); + y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); + } + else if (use_gebi) { + var o=document.getElementById(anchorname); + x=AnchorPosition_getPageOffsetLeft(o); + y=AnchorPosition_getPageOffsetTop(o); + } + else if (use_css) { + x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); + y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); + } + else if (use_layers) { + var found=0; + for (var i=0; i tags may cause errors. + +USAGE: +// Create an object for a WINDOW popup +var win = new PopupWindow(); + +// Create an object for a DIV window using the DIV named 'mydiv' +var win = new PopupWindow('mydiv'); + +// Set the window to automatically hide itself when the user clicks +// anywhere else on the page except the popup +win.autoHide(); + +// Show the window relative to the anchor name passed in +win.showPopup(anchorname); + +// Hide the popup +win.hidePopup(); + +// Set the size of the popup window (only applies to WINDOW popups +win.setSize(width,height); + +// Populate the contents of the popup window that will be shown. If you +// change the contents while it is displayed, you will need to refresh() +win.populate(string); + +// set the URL of the window, rather than populating its contents +// manually +win.setUrl("http://www.site.com/"); + +// Refresh the contents of the popup +win.refresh(); + +// Specify how many pixels to the right of the anchor the popup will appear +win.offsetX = 50; + +// Specify how many pixels below the anchor the popup will appear +win.offsetY = 100; + +NOTES: +1) Requires the functions in AnchorPosition.js + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. + +4) When a PopupWindow object is created, a handler for 'onmouseup' is + attached to any event handler you may have already defined. Do NOT define + an event handler for 'onmouseup' after you define a PopupWindow object or + the autoHide() will not work correctly. +*/ + +// Set the position of the popup window based on the anchor +function PopupWindow_getXYPosition(anchorname) { + var coordinates; + if (this.type == "WINDOW") { + coordinates = getAnchorWindowPosition(anchorname); + } + else { + coordinates = getAnchorPosition(anchorname); + } + this.x = coordinates.x; + this.y = coordinates.y; + } +// Set width/height of DIV/popup window +function PopupWindow_setSize(width,height) { + this.width = width; + this.height = height; + } +// Fill the window with contents +function PopupWindow_populate(contents) { + this.contents = contents; + this.populated = false; + } +// Set the URL to go to +function PopupWindow_setUrl(url) { + this.url = url; + } +// Set the window popup properties +function PopupWindow_setWindowProperties(props) { + this.windowProperties = props; + } +// Refresh the displayed contents of the popup +function PopupWindow_refresh() { + if (this.divName != null) { + // refresh the DIV object + if (this.use_gebi) { + document.getElementById(this.divName).innerHTML = this.contents; + } + else if (this.use_css) { + document.all[this.divName].innerHTML = this.contents; + } + else if (this.use_layers) { + var d = document.layers[this.divName]; + d.document.open(); + d.document.writeln(this.contents); + d.document.close(); + } + } + else { + if (this.popupWindow != null && !this.popupWindow.closed) { + if (this.url!="") { + this.popupWindow.location.href=this.url; + } + else { + this.popupWindow.document.open(); + this.popupWindow.document.writeln(this.contents); + this.popupWindow.document.close(); + } + this.popupWindow.focus(); + } + } + } +// Position and show the popup, relative to an anchor object +function PopupWindow_showPopup(anchorname) { + this.getXYPosition(anchorname); + this.x += this.offsetX; + this.y += this.offsetY; + if (!this.populated && (this.contents != "")) { + this.populated = true; + this.refresh(); + } + if (this.divName != null) { + // Show the DIV object + if (this.use_gebi) { + document.getElementById(this.divName).style.left = this.x + "px"; + document.getElementById(this.divName).style.top = this.y; + document.getElementById(this.divName).style.visibility = "visible"; + } + else if (this.use_css) { + document.all[this.divName].style.left = this.x; + document.all[this.divName].style.top = this.y; + document.all[this.divName].style.visibility = "visible"; + } + else if (this.use_layers) { + document.layers[this.divName].left = this.x; + document.layers[this.divName].top = this.y; + document.layers[this.divName].visibility = "visible"; + } + } + else { + if (this.popupWindow == null || this.popupWindow.closed) { + // If the popup window will go off-screen, move it so it doesn't + if (this.x<0) { this.x=0; } + if (this.y<0) { this.y=0; } + if (screen && screen.availHeight) { + if ((this.y + this.height) > screen.availHeight) { + this.y = screen.availHeight - this.height; + } + } + if (screen && screen.availWidth) { + if ((this.x + this.width) > screen.availWidth) { + this.x = screen.availWidth - this.width; + } + } + var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); + this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); + } + this.refresh(); + } + } +// Hide the popup +function PopupWindow_hidePopup() { + if (this.divName != null) { + if (this.use_gebi) { + document.getElementById(this.divName).style.visibility = "hidden"; + } + else if (this.use_css) { + document.all[this.divName].style.visibility = "hidden"; + } + else if (this.use_layers) { + document.layers[this.divName].visibility = "hidden"; + } + } + else { + if (this.popupWindow && !this.popupWindow.closed) { + this.popupWindow.close(); + this.popupWindow = null; + } + } + } +// Pass an event and return whether or not it was the popup DIV that was clicked +function PopupWindow_isClicked(e) { + if (this.divName != null) { + if (this.use_layers) { + var clickX = e.pageX; + var clickY = e.pageY; + var t = document.layers[this.divName]; + if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { + return true; + } + else { return false; } + } + else if (document.all) { // Need to hard-code this to trap IE for error-handling + var t = window.event.srcElement; + while (t.parentElement != null) { + if (t.id==this.divName) { + return true; + } + t = t.parentElement; + } + return false; + } + else if (this.use_gebi && e) { + var t = e.originalTarget; + while (t.parentNode != null) { + if (t.id==this.divName) { + return true; + } + t = t.parentNode; + } + return false; + } + return false; + } + return false; + } + +// Check an onMouseDown event to see if we should hide +function PopupWindow_hideIfNotClicked(e) { + if (this.autoHideEnabled && !this.isClicked(e)) { + this.hidePopup(); + } + } +// Call this to make the DIV disable automatically when mouse is clicked outside it +function PopupWindow_autoHide() { + this.autoHideEnabled = true; + } +// This global function checks all PopupWindow objects onmouseup to see if they should be hidden +function PopupWindow_hidePopupWindows(e) { + for (var i=0; i0) { + this.type="DIV"; + this.divName = arguments[0]; + } + else { + this.type="WINDOW"; + } + this.use_gebi = false; + this.use_css = false; + this.use_layers = false; + if (document.getElementById) { this.use_gebi = true; } + else if (document.all) { this.use_css = true; } + else if (document.layers) { this.use_layers = true; } + else { this.type = "WINDOW"; } + this.offsetX = 0; + this.offsetY = 0; + // Method mappings + this.getXYPosition = PopupWindow_getXYPosition; + this.populate = PopupWindow_populate; + this.setUrl = PopupWindow_setUrl; + this.setWindowProperties = PopupWindow_setWindowProperties; + this.refresh = PopupWindow_refresh; + this.showPopup = PopupWindow_showPopup; + this.hidePopup = PopupWindow_hidePopup; + this.setSize = PopupWindow_setSize; + this.isClicked = PopupWindow_isClicked; + this.autoHide = PopupWindow_autoHide; + this.hideIfNotClicked = PopupWindow_hideIfNotClicked; + } + +/* SOURCE FILE: ColorPicker2.js */ + +/* +Last modified: 02/24/2003 + +DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB +form. It uses a color "swatch" to display the standard 216-color web-safe +palette. The user can then click on a color to select it. + +COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js. +Only the latest DHTML-capable browsers will show the color and hex values +at the bottom as your mouse goes over them. + +USAGE: +// Create a new ColorPicker object using DHTML popup +var cp = new ColorPicker(); + +// Create a new ColorPicker object using Window Popup +var cp = new ColorPicker('window'); + +// Add a link in your page to trigger the popup. For example: +Pick + +// Or use the built-in "select" function to do the dirty work for you: +Pick + +// If using DHTML popup, write out the required DIV tag near the bottom +// of your page. + + +// Write the 'pickColor' function that will be called when the user clicks +// a color and do something with the value. This is only required if you +// want to do something other than simply populate a form field, which is +// what the 'select' function will give you. +function pickColor(color) { + field.value = color; + } + +NOTES: +1) Requires the functions in AnchorPosition.js and PopupWindow.js + +2) Your anchor tag MUST contain both NAME and ID attributes which are the + same. For example: + + +3) There must be at least a space between for IE5.5 to see the + anchor tag correctly. Do not do with no space. + +4) When a ColorPicker object is created, a handler for 'onmouseup' is + attached to any event handler you may have already defined. Do NOT define + an event handler for 'onmouseup' after you define a ColorPicker object or + the color picker will not hide itself correctly. +*/ +ColorPicker_targetInput = null; +function ColorPicker_writeDiv() { + document.writeln(""); + } + +function ColorPicker_show(anchorname) { + this.showPopup(anchorname); + } + +function ColorPicker_pickColor(color,obj) { + obj.hidePopup(); + pickColor(color); + } + +// A Default "pickColor" function to accept the color passed back from popup. +// User can over-ride this with their own function. +function pickColor(color) { + if (ColorPicker_targetInput==null) { + alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!"); + return; + } + ColorPicker_targetInput.value = color; + } + +// This function is the easiest way to popup the window, select a color, and +// have the value populate a form field, which is what most people want to do. +function ColorPicker_select(inputobj,linkname) { + if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { + alert("colorpicker.select: Input object passed is not a valid form input object"); + window.ColorPicker_targetInput=null; + return; + } + window.ColorPicker_targetInput = inputobj; + this.show(linkname); + } + +// This function runs when you move your mouse over a color block, if you have a newer browser +function ColorPicker_highlightColor(c) { + var thedoc = (arguments.length>1)?arguments[1]:window.document; + var d = thedoc.getElementById("colorPickerSelectedColor"); + d.style.backgroundColor = c; + d = thedoc.getElementById("colorPickerSelectedColorValue"); + d.innerHTML = c; + } + +function ColorPicker() { + var windowMode = false; + // Create a new PopupWindow object + if (arguments.length==0) { + var divname = "colorPickerDiv"; + } + else if (arguments[0] == "window") { + var divname = ''; + windowMode = true; + } + else { + var divname = arguments[0]; + } + + if (divname != "") { + var cp = new PopupWindow(divname); + } + else { + var cp = new PopupWindow(); + cp.setSize(225,250); + } + + // Object variables + cp.currentValue = "#FFFFFF"; + + // Method Mappings + cp.writeDiv = ColorPicker_writeDiv; + cp.highlightColor = ColorPicker_highlightColor; + cp.show = ColorPicker_show; + cp.select = ColorPicker_select; + + // Code to populate color picker window + var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099", + "#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099", + "#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099", + "#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF", + "#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F", + "#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000", + + "#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399", + "#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399", + "#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399", + "#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF", + "#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F", + "#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00", + + "#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699", + "#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699", + "#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699", + "#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F", + "#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F", + "#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F", + + "#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999", + "#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999", + "#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999", + "#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF", + "#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F", + "#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000", + + "#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99", + "#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99", + "#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99", + "#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF", + "#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F", + "#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00", + + "#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99", + "#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99", + "#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99", + "#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F", + "#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F", + "#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F", + + "#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666", + "#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000", + "#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000", + "#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999", + "#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF", + "#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF", + + "#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66", + "#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00", + "#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000", + "#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099", + "#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF", + "#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF", + + "#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF", + "#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC", + "#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000", + "#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900", + "#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33", + "#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF", + + "#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF", + "#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF", + "#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F", + "#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F", + "#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F", + "#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000"); + var total = colors.length; + var width = 72; + var cp_contents = ""; + var windowRef = (windowMode)?"window.opener.":""; + if (windowMode) { + cp_contents += "Select Color"; + cp_contents += ""; + } + cp_contents += ""; + var use_highlight = (document.getElementById || document.all)?true:false; + for (var i=0; i '; + if ( ((i+1)>=total) || (((i+1) % width) == 0)) { + cp_contents += ""; + } + } + // If the browser supports dynamically changing TD cells, add the fancy stuff + if (document.getElementById) { + var width1 = Math.floor(width/2); + var width2 = width = width1; + cp_contents += ""; + } + cp_contents += "
     #FFFFFF
    "; + if (windowMode) { + cp_contents += "
    "; + } + // end populate code + + // Write the contents to the popup object + cp.populate(cp_contents+"\n"); + // Move the table down a bit so you can see it + cp.offsetY = 25; + cp.autoHide(); + return cp; + } diff --git a/wp-includes/js/colorpicker.js b/wp-includes/js/colorpicker.js new file mode 100644 index 0000000..acd88a3 --- /dev/null +++ b/wp-includes/js/colorpicker.js @@ -0,0 +1 @@ +function getAnchorPosition(b){var e=false;var k=new Object();var j=0,g=0;var d=false,f=false,h=false;if(document.getElementById){d=true}else{if(document.all){f=true}else{if(document.layers){h=true}}}if(d&&document.all){j=AnchorPosition_getPageOffsetLeft(document.all[b]);g=AnchorPosition_getPageOffsetTop(document.all[b])}else{if(d){var a=document.getElementById(b);j=AnchorPosition_getPageOffsetLeft(a);g=AnchorPosition_getPageOffsetTop(a)}else{if(f){j=AnchorPosition_getPageOffsetLeft(document.all[b]);g=AnchorPosition_getPageOffsetTop(document.all[b])}else{if(h){var l=0;for(var c=0;cscreen.availHeight){this.y=screen.availHeight-this.height}}if(screen&&screen.availWidth){if((this.x+this.width)>screen.availWidth){this.x=screen.availWidth-this.width}}var b=window.opera||(document.layers&&!navigator.mimeTypes["*"])||navigator.vendor=="KDE"||(document.childNodes&&!document.all&&!navigator.taintEnabled);this.popupWindow=window.open(b?"":"about:blank","window_"+a,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+"")}this.refresh()}}function PopupWindow_hidePopup(){if(this.divName!=null){if(this.use_gebi){document.getElementById(this.divName).style.visibility="hidden"}else{if(this.use_css){document.all[this.divName].style.visibility="hidden"}else{if(this.use_layers){document.layers[this.divName].visibility="hidden"}}}}else{if(this.popupWindow&&!this.popupWindow.closed){this.popupWindow.close();this.popupWindow=null}}}function PopupWindow_isClicked(c){if(this.divName!=null){if(this.use_layers){var d=c.pageX;var b=c.pageY;var a=document.layers[this.divName];if((d>a.left)&&(da.top)&&(b0){this.type="DIV";this.divName=arguments[0]}else{this.type="WINDOW"}this.use_gebi=false;this.use_css=false;this.use_layers=false;if(document.getElementById){this.use_gebi=true}else{if(document.all){this.use_css=true}else{if(document.layers){this.use_layers=true}else{this.type="WINDOW"}}}this.offsetX=0;this.offsetY=0;this.getXYPosition=PopupWindow_getXYPosition;this.populate=PopupWindow_populate;this.setUrl=PopupWindow_setUrl;this.setWindowProperties=PopupWindow_setWindowProperties;this.refresh=PopupWindow_refresh;this.showPopup=PopupWindow_showPopup;this.hidePopup=PopupWindow_hidePopup;this.setSize=PopupWindow_setSize;this.isClicked=PopupWindow_isClicked;this.autoHide=PopupWindow_autoHide;this.hideIfNotClicked=PopupWindow_hideIfNotClicked}ColorPicker_targetInput=null;function ColorPicker_writeDiv(){document.writeln('')}function ColorPicker_show(a){this.showPopup(a)}function ColorPicker_pickColor(a,b){b.hidePopup();pickColor(a)}function pickColor(a){if(ColorPicker_targetInput==null){alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!");return}ColorPicker_targetInput.value=a}function ColorPicker_select(b,a){if(b.type!="text"&&b.type!="hidden"&&b.type!="textarea"){alert("colorpicker.select: Input object passed is not a valid form input object");window.ColorPicker_targetInput=null;return}window.ColorPicker_targetInput=b;this.show(a)}function ColorPicker_highlightColor(e){var a=(arguments.length>1)?arguments[1]:window.document;var b=a.getElementById("colorPickerSelectedColor");b.style.backgroundColor=e;b=a.getElementById("colorPickerSelectedColorValue");b.innerHTML=e}function ColorPicker(){var g=false;if(arguments.length==0){var e="colorPickerDiv"}else{if(arguments[0]=="window"){var e="";g=true}else{var e=arguments[0]}}if(e!=""){var m=new PopupWindow(e)}else{var m=new PopupWindow();m.setSize(225,250)}m.currentValue="#FFFFFF";m.writeDiv=ColorPicker_writeDiv;m.highlightColor=ColorPicker_highlightColor;m.show=ColorPicker_show;m.select=ColorPicker_select;var a=new Array("#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099","#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099","#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF","#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F","#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000","#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399","#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399","#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF","#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F","#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00","#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699","#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699","#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699","#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F","#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F","#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F","#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999","#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999","#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999","#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF","#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F","#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000","#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99","#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99","#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF","#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F","#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00","#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99","#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99","#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99","#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F","#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F","#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F","#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666","#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000","#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000","#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999","#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF","#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF","#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66","#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00","#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000","#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099","#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF","#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF","#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF","#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC","#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000","#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900","#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33","#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF","#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF","#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF","#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F","#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F","#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F","#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000");var n=a.length;var c=72;var k="";var j=(g)?"window.opener.":"";if(g){k+="Select Color";k+=""}k+="";var l=(document.getElementById||document.all)?true:false;for(var h=0;h"}if(l){var f='onMouseOver="'+j+"ColorPicker_highlightColor('"+a[h]+"',window.document)\""}else{f=""}k+='";if(((h+1)>=n)||(((h+1)%c)==0)){k+=""}}if(document.getElementById){var d=Math.floor(c/2);var b=c=d;k+=""}k+="
     
     #FFFFFF
    ";if(g){k+="
    "}m.populate(k+"\n");m.offsetY=25;m.autoHide();return m}; \ No newline at end of file diff --git a/wp-includes/js/comment-reply.dev.js b/wp-includes/js/comment-reply.dev.js new file mode 100644 index 0000000..2015425 --- /dev/null +++ b/wp-includes/js/comment-reply.dev.js @@ -0,0 +1,48 @@ + +addComment = { + moveForm : function(commId, parentId, respondId, postId) { + var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); + + if ( ! comm || ! respond || ! cancel || ! parent ) + return; + + t.respondId = respondId; + postId = postId || false; + + if ( ! t.I('wp-temp-form-div') ) { + div = document.createElement('div'); + div.id = 'wp-temp-form-div'; + div.style.display = 'none'; + respond.parentNode.insertBefore(div, respond); + } + + comm.parentNode.insertBefore(respond, comm.nextSibling); + if ( post && postId ) + post.value = postId; + parent.value = parentId; + cancel.style.display = ''; + + cancel.onclick = function() { + var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); + + if ( ! temp || ! respond ) + return; + + t.I('comment_parent').value = '0'; + temp.parentNode.insertBefore(respond, temp); + temp.parentNode.removeChild(temp); + this.style.display = 'none'; + this.onclick = null; + return false; + } + + try { t.I('comment').focus(); } + catch(e) {} + + return false; + }, + + I : function(e) { + return document.getElementById(e); + } +} diff --git a/wp-includes/js/comment-reply.js b/wp-includes/js/comment-reply.js new file mode 100644 index 0000000..524f2ed --- /dev/null +++ b/wp-includes/js/comment-reply.js @@ -0,0 +1 @@ +addComment={moveForm:function(d,f,i,c){var m=this,a,h=m.I(d),b=m.I(i),l=m.I("cancel-comment-reply-link"),j=m.I("comment_parent"),k=m.I("comment_post_ID");if(!h||!b||!l||!j){return}m.respondId=i;c=c||false;if(!m.I("wp-temp-form-div")){a=document.createElement("div");a.id="wp-temp-form-div";a.style.display="none";b.parentNode.insertBefore(a,b)}h.parentNode.insertBefore(b,h.nextSibling);if(k&&c){k.value=c}j.value=f;l.style.display="";l.onclick=function(){var n=addComment,e=n.I("wp-temp-form-div"),o=n.I(n.respondId);if(!e||!o){return}n.I("comment_parent").value="0";e.parentNode.insertBefore(o,e);e.parentNode.removeChild(e);this.style.display="none";this.onclick=null;return false};try{m.I("comment").focus()}catch(g){}return false},I:function(a){return document.getElementById(a)}}; \ No newline at end of file diff --git a/wp-includes/js/crop/cropper.css b/wp-includes/js/crop/cropper.css new file mode 100644 index 0000000..973f178 --- /dev/null +++ b/wp-includes/js/crop/cropper.css @@ -0,0 +1,165 @@ +.imgCrop_wrap { + /* width: 500px; @done_in_js */ + /* height: 375px; @done_in_js */ + position: relative; + cursor: crosshair; +} + +/* an extra classname is applied for Opera < 9.0 to fix it's lack of opacity support */ +.imgCrop_wrap.opera8 .imgCrop_overlay, +.imgCrop_wrap.opera8 .imgCrop_clickArea { + background-color: transparent; +} + +/* fix for IE displaying all boxes at line-height by default, although they are still 1 pixel high until we combine them with the pointless span */ +.imgCrop_wrap, +.imgCrop_wrap * { + font-size: 0; +} + +.imgCrop_overlay { + background-color: #000; + opacity: 0.5; + filter:alpha(opacity=50); + position: absolute; + width: 100%; + height: 100%; +} + +.imgCrop_selArea { + position: absolute; + /* @done_in_js + top: 20px; + left: 20px; + width: 200px; + height: 200px; + background: transparent url(castle.jpg) no-repeat -210px -110px; + */ + cursor: move; + z-index: 2; +} + +/* clickArea is all a fix for IE 5.5 & 6 to allow the user to click on the given area */ +.imgCrop_clickArea { + width: 100%; + height: 100%; + background-color: #FFF; + opacity: 0.01; + filter:alpha(opacity=01); +} + +.imgCrop_marqueeHoriz { + position: absolute; + width: 100%; + height: 1px; + background: transparent url(marqueeHoriz.gif) repeat-x 0 0; + z-index: 3; +} + +.imgCrop_marqueeVert { + position: absolute; + height: 100%; + width: 1px; + background: transparent url(marqueeVert.gif) repeat-y 0 0; + z-index: 3; +} + +.imgCrop_marqueeNorth { top: 0; left: 0; } +.imgCrop_marqueeEast { top: 0; right: 0; } +.imgCrop_marqueeSouth { bottom: 0px; left: 0; } +.imgCrop_marqueeWest { top: 0; left: 0; } + + +.imgCrop_handle { + position: absolute; + border: 1px solid #333; + width: 6px; + height: 6px; + background: #FFF; + opacity: 0.5; + filter:alpha(opacity=50); + z-index: 4; +} + +/* fix IE 5 box model */ +* html .imgCrop_handle { + width: 8px; + height: 8px; + wid\th: 6px; + hei\ght: 6px; +} + +.imgCrop_handleN { + top: -3px; + left: 0; + /* margin-left: 49%; @done_in_js */ + cursor: n-resize; +} + +.imgCrop_handleNE { + top: -3px; + right: -3px; + cursor: ne-resize; +} + +.imgCrop_handleE { + top: 0; + right: -3px; + /* margin-top: 49%; @done_in_js */ + cursor: e-resize; +} + +.imgCrop_handleSE { + right: -3px; + bottom: -3px; + cursor: se-resize; +} + +.imgCrop_handleS { + right: 0; + bottom: -3px; + /* margin-right: 49%; @done_in_js */ + cursor: s-resize; +} + +.imgCrop_handleSW { + left: -3px; + bottom: -3px; + cursor: sw-resize; +} + +.imgCrop_handleW { + top: 0; + left: -3px; + /* margin-top: 49%; @done_in_js */ + cursor: e-resize; +} + +.imgCrop_handleNW { + top: -3px; + left: -3px; + cursor: nw-resize; +} + +/** + * Create an area to click & drag around on as the default browser behaviour is to let you drag the image + */ +.imgCrop_dragArea { + width: 100%; + height: 100%; + z-index: 200; + position: absolute; + top: 0; + left: 0; +} + +.imgCrop_previewWrap { + /* width: 200px; @done_in_js */ + /* height: 200px; @done_in_js */ + overflow: hidden; + position: relative; +} + +.imgCrop_previewWrap img { + position: absolute; +} \ No newline at end of file diff --git a/wp-includes/js/crop/cropper.js b/wp-includes/js/crop/cropper.js new file mode 100644 index 0000000..d0cb8e4 --- /dev/null +++ b/wp-includes/js/crop/cropper.js @@ -0,0 +1,516 @@ +/** + * Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * http://www.opensource.org/licenses/bsd-license.php + * + * See scriptaculous.js for full scriptaculous licence + */ + +var CropDraggable=Class.create(); +Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){ +this.options=Object.extend({drawMethod:function(){ +}},arguments[1]||{}); +this.element=$(_1); +this.handle=this.element; +this.delta=this.currentDelta(); +this.dragging=false; +this.eventMouseDown=this.initDrag.bindAsEventListener(this); +Event.observe(this.handle,"mousedown",this.eventMouseDown); +Draggables.register(this); +},draw:function(_2){ +var _3=Position.cumulativeOffset(this.element); +var d=this.currentDelta(); +_3[0]-=d[0]; +_3[1]-=d[1]; +var p=[0,1].map(function(i){ +return (_2[i]-_3[i]-this.offset[i]); +}.bind(this)); +this.options.drawMethod(p); +}}); +var Cropper={}; +Cropper.Img=Class.create(); +Cropper.Img.prototype={initialize:function(_7,_8){ +this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{}); +if(this.options.minWidth>0&&this.options.minHeight>0){ +this.options.ratioDim.x=this.options.minWidth; +this.options.ratioDim.y=this.options.minHeight; +} +this.img=$(_7); +this.clickCoords={x:0,y:0}; +this.dragging=false; +this.resizing=false; +this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent); +this.isIE=/MSIE/.test(navigator.userAgent); +this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent); +this.ratioX=0; +this.ratioY=0; +this.attached=false; +$A(document.getElementsByTagName("script")).each(function(s){ +if(s.src.match(/cropper\.js/)){ +var _a=s.src.replace(/cropper\.js(.*)?/,""); +var _b=document.createElement("link"); +_b.rel="stylesheet"; +_b.type="text/css"; +_b.href=_a+"cropper.css"; +_b.media="screen"; +document.getElementsByTagName("head")[0].appendChild(_b); +} +}); +if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){ +var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y); +this.ratioX=this.options.ratioDim.x/_c; +this.ratioY=this.options.ratioDim.y/_c; +} +this.subInitialize(); +if(this.img.complete||this.isWebKit){ +this.onLoad(); +}else{ +Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this)); +} +},getGCD:function(a,b){return 1; +if(b==0){ +return a; +} +return this.getGCD(b,a%b); +},onLoad:function(){ +var _f="imgCrop_"; +var _10=this.img.parentNode; +var _11=""; +if(this.isOpera8){ +_11=" opera8"; +} +this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11}); +if(this.isIE){ +this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]); +this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]); +this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]); +this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]); +var _12=[this.north,this.east,this.south,this.west]; +}else{ +this.overlay=Builder.node("div",{"class":_f+"overlay"}); +var _12=[this.overlay]; +} +this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12); +this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"}); +this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"}); +this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"}); +this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"}); +this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"}); +this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"}); +this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"}); +this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"}); +this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]); +Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"}); +this.imgWrap.appendChild(this.img); +this.imgWrap.appendChild(this.dragArea); +this.dragArea.appendChild(this.selArea); +this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"})); +_10.appendChild(this.imgWrap); +Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this)); +Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this)); +Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this)); +var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW]; +for(var i=0;i<_13.length;i++){ +Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this)); +} +if(this.options.captureKeys){ +Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this)); +} +new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)}); +this.setParams(); +},setParams:function(){ +this.imgW=this.img.width; +this.imgH=this.img.height; +if(!this.isIE){ +Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"}); +Element.hide($(this.overlay)); +Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"}); +}else{ +Element.setStyle($(this.north),{height:0}); +Element.setStyle($(this.east),{width:0,height:0}); +Element.setStyle($(this.south),{height:0}); +Element.setStyle($(this.west),{width:0,height:0}); +} +Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"}); +Element.hide($(this.selArea)); +var _15=Position.positionedOffset(this.imgWrap); +this.wrapOffsets={"top":_15[1],"left":_15[0]}; +var _16={x1:0,y1:0,x2:0,y2:0}; +this.setAreaCoords(_16); +if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){ +_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2); +_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2); +_16.x2=_16.x1+this.options.ratioDim.x; +_16.y2=_16.y1+this.options.ratioDim.y; +Element.show(this.selArea); +this.drawArea(); +this.endCrop(); +} +this.attached=true; +},remove:function(){ +this.attached=false; +this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap); +this.imgWrap.parentNode.removeChild(this.imgWrap); +Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this)); +Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this)); +Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this)); +var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW]; +for(var i=0;i<_17.length;i++){ +Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this)); +} +if(this.options.captureKeys){ +Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this)); +} +},reset:function(){ +if(!this.attached){ +this.onLoad(); +}else{ +this.setParams(); +} +this.endCrop(); +},handleKeys:function(e){ +var dir={x:0,y:0}; +if(!this.dragging){ +switch(e.keyCode){ +case (37): +dir.x=-1; +break; +case (38): +dir.y=-1; +break; +case (39): +dir.x=1; +break; +case (40): +dir.y=1; +break; +} +if(dir.x!=0||dir.y!=0){ +if(e.shiftKey){ +dir.x*=10; +dir.y*=10; +} +this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]); +Event.stop(e); +} +} +},calcW:function(){ +return (this.areaCoords.x2-this.areaCoords.x1); +},calcH:function(){ +return (this.areaCoords.y2-this.areaCoords.y1); +},moveArea:function(_1b){ +this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true); +this.drawArea(); +},cloneCoords:function(_1c){ +return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2}; +},setAreaCoords:function(_1d,_1e,_1f,_20,_21){ +var _22=typeof _1e!="undefined"?_1e:false; +var _23=typeof _1f!="undefined"?_1f:false; +if(_1e){ +var _24=_1d.x2-_1d.x1; +var _25=_1d.y2-_1d.y1; +if(_1d.x1<0){ +_1d.x1=0; +_1d.x2=_24; +} +if(_1d.y1<0){ +_1d.y1=0; +_1d.y2=_25; +} +if(_1d.x2>this.imgW){ +_1d.x2=this.imgW; +_1d.x1=this.imgW-_24; +} +if(_1d.y2>this.imgH){ +_1d.y2=this.imgH; +_1d.y1=this.imgH-_25; +} +}else{ +if(_1d.x1<0){ +_1d.x1=0; +} +if(_1d.y1<0){ +_1d.y1=0; +} +if(_1d.x2>this.imgW){ +_1d.x2=this.imgW; +} +if(_1d.y2>this.imgH){ +_1d.y2=this.imgH; +} +if(typeof (_20)!="undefined"){ +if(this.ratioX>0){ +this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21); +}else{ +if(_23){ +this.applyRatio(_1d,{x:1,y:1},_20,_21); +} +} +var _26={a1:_1d.x1,a2:_1d.x2}; +var _27={a1:_1d.y1,a2:_1d.y2}; +var _28=this.options.minWidth; +var _29=this.options.minHeight; +if((_28==0||_29==0)&&_23){ +if(_28>0){ +_29=_28; +}else{ +if(_29>0){ +_28=_29; +} +} +} +this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW}); +this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH}); +_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2}; +} +} +this.areaCoords=_1d; +},applyMinDimension:function(_2a,_2b,_2c,_2d){ +if((_2a.a2-_2a.a1)<_2b){ +if(_2c==1){ +_2a.a2=_2a.a1+_2b; +}else{ +_2a.a1=_2a.a2-_2b; +} +if(_2a.a1<_2d.min){ +_2a.a1=_2d.min; +_2a.a2=_2b; +}else{ +if(_2a.a2>_2d.max){ +_2a.a1=_2d.max-_2b; +_2a.a2=_2d.max; +} +} +} +},applyRatio:function(_2e,_2f,_30,_31){ +var _32; +if(_31=="N"||_31=="S"){ +_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW}); +_2e.x1=_32.b1; +_2e.y1=_32.a1; +_2e.x2=_32.b2; +_2e.y2=_32.a2; +}else{ +_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH}); +_2e.x1=_32.a1; +_2e.y1=_32.b1; +_2e.x2=_32.a2; +_2e.y2=_32.b2; +} +},applyRatioToAxis:function(_33,_34,_35,_36){ +var _37=Object.extend(_33,{}); +var _38=_37.a2-_37.a1; +var _3a=Math.floor(_38*_34.b/_34.a); +var _3b; +var _3c; +var _3d=null; +if(_35.b==1){ +_3b=_37.b1+_3a; +if(_3b>_36.max){ +_3b=_36.max; +_3d=_3b-_37.b1; +} +_37.b2=_3b; +}else{ +_3b=_37.b2-_3a; +if(_3b<_36.min){ +_3b=_36.min; +_3d=_3b+_37.b2; +} +_37.b1=_3b; +} +if(_3d!=null){ +_3c=Math.floor(_3d*_34.a/_34.b); +if(_35.a==1){ +_37.a2=_37.a1+_3c; +}else{ +_37.a1=_37.a1=_37.a2-_3c; +} +} +return _37; +},drawArea:function(){ +if(!this.isIE){ +Element.show($(this.overlay)); +} +var _3e=this.calcW(); +var _3f=this.calcH(); +var _40=this.areaCoords.x2; +var _41=this.areaCoords.y2; +var _42=this.selArea.style; +_42.left=this.areaCoords.x1+"px"; +_42.top=this.areaCoords.y1+"px"; +_42.width=_3e+"px"; +_42.height=_3f+"px"; +var _43=Math.ceil((_3e-6)/2)+"px"; +var _44=Math.ceil((_3f-6)/2)+"px"; +this.handleN.style.left=_43; +this.handleE.style.top=_44; +this.handleS.style.left=_43; +this.handleW.style.top=_44; +if(this.isIE){ +this.north.style.height=this.areaCoords.y1+"px"; +var _45=this.east.style; +_45.top=this.areaCoords.y1+"px"; +_45.height=_3f+"px"; +_45.left=_40+"px"; +_45.width=(this.img.width-_40)+"px"; +var _46=this.south.style; +_46.top=_41+"px"; +_46.height=(this.img.height-_41)+"px"; +var _47=this.west.style; +_47.top=this.areaCoords.y1+"px"; +_47.height=_3f+"px"; +_47.width=this.areaCoords.x1+"px"; +}else{ +_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px"; +} +this.subDrawArea(); +this.forceReRender(); +},forceReRender:function(){ +if(this.isIE||this.isWebKit){ +var n=document.createTextNode(" "); +var d,el,fixEL,i; +if(this.isIE){ +fixEl=this.selArea; +}else{ +if(this.isWebKit){ +fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0]; +d=Builder.node("div",""); +d.style.visibility="hidden"; +var _4a=["SE","S","SW"]; +for(i=0;i<_4a.length;i++){ +el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0]; +if(el.childNodes.length){ +el.removeChild(el.childNodes[0]); +} +el.appendChild(d); +} +} +} +fixEl.appendChild(n); +fixEl.removeChild(n); +} +},startResize:function(e){ +this.startCoords=this.cloneCoords(this.areaCoords); +this.resizing=true; +this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,""); +Event.stop(e); +},startDrag:function(e){ +Element.show(this.selArea); +this.clickCoords=this.getCurPos(e); +this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y}); +this.dragging=true; +this.onDrag(e); +Event.stop(e); +},getCurPos:function(e){ +return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top}; +},onDrag:function(e){ +var _4f=null; +if(this.dragging||this.resizing){ +var _50=this.getCurPos(e); +var _51=this.cloneCoords(this.areaCoords); +var _52={x:1,y:1}; +} +if(this.dragging){ +if(_50.x0&&this.options.minHeight>0){ +this.previewWrap=$(this.options.previewWrap); +this.previewImg=this.img.cloneNode(false); +this.options.displayOnInit=true; +this.hasPreviewImg=true; +Element.addClassName(this.previewWrap,"imgCrop_previewWrap"); +Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"}); +this.previewWrap.appendChild(this.previewImg); +} +},subDrawArea:function(){ +if(this.hasPreviewImg){ +var _58=this.calcW(); +var _59=this.calcH(); +var _5a={x:this.imgW/_58,y:this.imgH/_59}; +var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight}; +var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"}; +var _5d=this.previewImg.style; +_5d.width=_5c.w; +_5d.height=_5c.h; +_5d.left=_5c.x; +_5d.top=_5c.y; +} +}}); diff --git a/wp-includes/js/crop/marqueeHoriz.gif b/wp-includes/js/crop/marqueeHoriz.gif new file mode 100644 index 0000000..25317e5 Binary files /dev/null and b/wp-includes/js/crop/marqueeHoriz.gif differ diff --git a/wp-includes/js/crop/marqueeVert.gif b/wp-includes/js/crop/marqueeVert.gif new file mode 100644 index 0000000..354070b Binary files /dev/null and b/wp-includes/js/crop/marqueeVert.gif differ diff --git a/wp-includes/js/hoverIntent.dev.js b/wp-includes/js/hoverIntent.dev.js new file mode 100644 index 0000000..5cbf978 --- /dev/null +++ b/wp-includes/js/hoverIntent.dev.js @@ -0,0 +1,128 @@ +/** +* hoverIntent is similar to jQuery's built-in "hover" function except that +* instead of firing the onMouseOver event immediately, hoverIntent checks +* to see if the user's mouse has slowed down (beneath the sensitivity +* threshold) before firing the onMouseOver event. +* +* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ +* +* +* hoverIntent is currently available for use in all personal or commercial +* projects under both MIT and GPL licenses. This means that you can choose +* the license that best suits your project, and use it accordingly. +* +* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions +* $("ul li").hoverIntent( showNav , hideNav ); +* +* // advanced usage receives configuration object only +* $("ul li").hoverIntent({ +* sensitivity: 7, // number = sensitivity threshold (must be 1 or higher) +* interval: 100, // number = milliseconds of polling interval +* over: showNav, // function = onMouseOver callback (required) +* timeout: 0, // number = milliseconds delay before onMouseOut function call +* out: hideNav // function = onMouseOut callback (required) +* }); +* +* @param f onMouseOver function || An object with configuration options +* @param g onMouseOut function || Nothing (use configuration options object) +* @author Brian Cherne +*/ +(function($) { + $.fn.hoverIntent = function(f,g) { + // default configuration options + var cfg = { + sensitivity: 7, + interval: 100, + timeout: 0 + }; + // override configuration options with user supplied object + cfg = $.extend(cfg, g ? { over: f, out: g } : f ); + + // instantiate variables + // cX, cY = current X and Y position of mouse, updated by mousemove event + // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval + var cX, cY, pX, pY; + + // A private function for getting mouse position + var track = function(ev) { + cX = ev.pageX; + cY = ev.pageY; + }; + + // A private function for comparing current and previous mouse position + var compare = function(ev,ob) { + ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); + // compare mouse positions to see if they've crossed the threshold + if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { + $(ob).unbind("mousemove",track); + // set hoverIntent state to true (so mouseOut can be called) + ob.hoverIntent_s = 1; + return cfg.over.apply(ob,[ev]); + } else { + // set previous coordinates for next time + pX = cX; pY = cY; + // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) + ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); + } + }; + + // A private function for delaying the mouseOut function + var delay = function(ev,ob) { + ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); + ob.hoverIntent_s = 0; + return cfg.out.apply(ob,[ev]); + }; + + // workaround for Mozilla bug: not firing mouseout/mouseleave on absolute positioned elements over textareas and input type="text" + var handleHover = function(e) { + var t = this; + + // next two lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut + var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; + while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } + if ( p == this ) { + if ( $.browser.mozilla ) { + if ( e.type == "mouseout" ) { + t.mtout = setTimeout( function(){doHover(e,t);}, 30 ); + } else { + if (t.mtout) { t.mtout = clearTimeout(t.mtout); } + } + } + return; + } else { + if (t.mtout) { t.mtout = clearTimeout(t.mtout); } + doHover(e,t); + } + }; + + // A private function for handling mouse 'hovering' + var doHover = function(e,ob) { + + // copy objects to be passed into t (required for event object to be passed in IE) + var ev = jQuery.extend({},e); + + // cancel hoverIntent timer if it exists + if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } + + // else e.type == "onmouseover" + if (e.type == "mouseover") { + // set "previous" X and Y position based on initial entry point + pX = ev.pageX; pY = ev.pageY; + // update "current" X and Y position based on mousemove + $(ob).bind("mousemove",track); + // start polling interval (self-calling timeout) to compare mouse coordinates over time + if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} + + // else e.type == "onmouseout" + } else { + // unbind expensive mousemove event + $(ob).unbind("mousemove",track); + // if hoverIntent state is true, then call the mouseOut function after the specified delay + if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} + } + }; + + // bind the function to the two event listeners + return this.mouseover(handleHover).mouseout(handleHover); + }; +})(jQuery); \ No newline at end of file diff --git a/wp-includes/js/hoverIntent.js b/wp-includes/js/hoverIntent.js new file mode 100644 index 0000000..bed4129 --- /dev/null +++ b/wp-includes/js/hoverIntent.js @@ -0,0 +1 @@ +(function(a){a.fn.hoverIntent=function(l,j){var m={sensitivity:7,interval:100,timeout:0};m=a.extend(m,j?{over:l,out:j}:l);var o,n,h,d;var e=function(f){o=f.pageX;n=f.pageY};var c=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);if((Math.abs(h-o)+Math.abs(d-n)) + * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{ + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + + * }}} + */ + +(function($) { + +$.Jcrop = function(obj,opt) +{ + // Initialization {{{ + + // Sanitize some options {{{ + var obj = obj, opt = opt; + + if (typeof(obj) !== 'object') obj = $(obj)[0]; + if (typeof(opt) !== 'object') opt = { }; + + // Some on-the-fly fixes for MSIE...sigh + if (!('trackDocument' in opt)) + { + opt.trackDocument = $.browser.msie ? false : true; + if ($.browser.msie && $.browser.version.split('.')[0] == '8') + opt.trackDocument = true; + } + + if (!('keySupport' in opt)) + opt.keySupport = $.browser.msie ? false : true; + + // }}} + // Extend the default options {{{ + var defaults = { + + // Basic Settings + trackDocument: false, + baseClass: 'jcrop', + addClass: null, + + // Styling Options + bgColor: 'black', + bgOpacity: .6, + borderOpacity: .4, + handleOpacity: .5, + + handlePad: 5, + handleSize: 9, + handleOffset: 5, + edgeMargin: 14, + + aspectRatio: 0, + keySupport: true, + cornerHandles: true, + sideHandles: true, + drawBorders: true, + dragEdges: true, + + boxWidth: 0, + boxHeight: 0, + + boundary: 8, + animationDelay: 20, + swingSpeed: 3, + + allowSelect: true, + allowMove: true, + allowResize: true, + + minSelect: [ 0, 0 ], + maxSize: [ 0, 0 ], + minSize: [ 0, 0 ], + + // Callbacks / Event Handlers + onChange: function() { }, + onSelect: function() { } + + }; + var options = defaults; + setOptions(opt); + + // }}} + // Initialize some jQuery objects {{{ + + var $origimg = $(obj); + var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' }); + + $img.width($origimg.width()); + $img.height($origimg.height()); + $origimg.after($img).hide(); + + presize($img,options.boxWidth,options.boxHeight); + + var boundx = $img.width(), + boundy = $img.height(), + + $div = $('
    ') + .width(boundx).height(boundy) + .addClass(cssClass('holder')) + .css({ + position: 'relative', + backgroundColor: options.bgColor + }).insertAfter($origimg).append($img); + ; + + if (options.addClass) $div.addClass(options.addClass); + //$img.wrap($div); + + var $img2 = $('')/*{{{*/ + .attr('src',$img.attr('src')) + .css('position','absolute') + .width(boundx).height(boundy) + ;/*}}}*/ + var $img_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css({ + zIndex: 310, + position: 'absolute', + overflow: 'hidden' + }) + .append($img2) + ;/*}}}*/ + var $hdl_holder = $('
    ')/*{{{*/ + .width(pct(100)).height(pct(100)) + .css('zIndex',320); + /*}}}*/ + var $sel = $('
    ')/*{{{*/ + .css({ + position: 'absolute', + zIndex: 300 + }) + .insertBefore($img) + .append($img_holder,$hdl_holder) + ;/*}}}*/ + + var bound = options.boundary; + var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2)) + .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 }) + .mousedown(newSelection); + + /* }}} */ + // Set more variables {{{ + + var xlimit, ylimit, xmin, ymin; + var xscale, yscale, enabled = true; + var docOffset = getPos($img), + // Internal states + btndown, lastcurs, dimmed, animating, + shift_down; + + // }}} + + + // }}} + // Internal Modules {{{ + + var Coords = function()/*{{{*/ + { + var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy; + + function setPressed(pos)/*{{{*/ + { + var pos = rebound(pos); + x2 = x1 = pos[0]; + y2 = y1 = pos[1]; + }; + /*}}}*/ + function setCurrent(pos)/*{{{*/ + { + var pos = rebound(pos); + ox = pos[0] - x2; + oy = pos[1] - y2; + x2 = pos[0]; + y2 = pos[1]; + }; + /*}}}*/ + function getOffset()/*{{{*/ + { + return [ ox, oy ]; + }; + /*}}}*/ + function moveOffset(offset)/*{{{*/ + { + var ox = offset[0], oy = offset[1]; + + if (0 > x1 + ox) ox -= ox + x1; + if (0 > y1 + oy) oy -= oy + y1; + + if (boundy < y2 + oy) oy += boundy - (y2 + oy); + if (boundx < x2 + ox) ox += boundx - (x2 + ox); + + x1 += ox; + x2 += ox; + y1 += oy; + y2 += oy; + }; + /*}}}*/ + function getCorner(ord)/*{{{*/ + { + var c = getFixed(); + switch(ord) + { + case 'ne': return [ c.x2, c.y ]; + case 'nw': return [ c.x, c.y ]; + case 'se': return [ c.x2, c.y2 ]; + case 'sw': return [ c.x, c.y2 ]; + } + }; + /*}}}*/ + function getFixed()/*{{{*/ + { + if (!options.aspectRatio) return getRect(); + // This function could use some optimization I think... + var aspect = options.aspectRatio, + min_x = options.minSize[0]/xscale, + min_y = options.minSize[1]/yscale, + max_x = options.maxSize[0]/xscale, + max_y = options.maxSize[1]/yscale, + rw = x2 - x1, + rh = y2 - y1, + rwa = Math.abs(rw), + rha = Math.abs(rh), + real_ratio = rwa / rha, + xx, yy + ; + if (max_x == 0) { max_x = boundx * 10 } + if (max_y == 0) { max_y = boundy * 10 } + if (real_ratio < aspect) + { + yy = y2; + w = rha * aspect; + xx = rw < 0 ? x1 - w : w + x1; + + if (xx < 0) + { + xx = 0; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h: h + y1; + } + else if (xx > boundx) + { + xx = boundx; + h = Math.abs((xx - x1) / aspect); + yy = rh < 0 ? y1 - h : h + y1; + } + } + else + { + xx = x2; + h = rwa / aspect; + yy = rh < 0 ? y1 - h : y1 + h; + if (yy < 0) + { + yy = 0; + w = Math.abs((yy - y1) * aspect); + xx = rw < 0 ? x1 - w : w + x1; + } + else if (yy > boundy) + { + yy = boundy; + w = Math.abs(yy - y1) * aspect; + xx = rw < 0 ? x1 - w : w + x1; + } + } + + // Magic %-) + if(xx > x1) { // right side + if(xx - x1 < min_x) { + xx = x1 + min_x; + } else if (xx - x1 > max_x) { + xx = x1 + max_x; + } + if(yy > y1) { + yy = y1 + (xx - x1)/aspect; + } else { + yy = y1 - (xx - x1)/aspect; + } + } else if (xx < x1) { // left side + if(x1 - xx < min_x) { + xx = x1 - min_x + } else if (x1 - xx > max_x) { + xx = x1 - max_x; + } + if(yy > y1) { + yy = y1 + (x1 - xx)/aspect; + } else { + yy = y1 - (x1 - xx)/aspect; + } + } + + if(xx < 0) { + x1 -= xx; + xx = 0; + } else if (xx > boundx) { + x1 -= xx - boundx; + xx = boundx; + } + + if(yy < 0) { + y1 -= yy; + yy = 0; + } else if (yy > boundy) { + y1 -= yy - boundy; + yy = boundy; + } + + return last = makeObj(flipCoords(x1,y1,xx,yy)); + }; + /*}}}*/ + function rebound(p)/*{{{*/ + { + if (p[0] < 0) p[0] = 0; + if (p[1] < 0) p[1] = 0; + + if (p[0] > boundx) p[0] = boundx; + if (p[1] > boundy) p[1] = boundy; + + return [ p[0], p[1] ]; + }; + /*}}}*/ + function flipCoords(x1,y1,x2,y2)/*{{{*/ + { + var xa = x1, xb = x2, ya = y1, yb = y2; + if (x2 < x1) + { + xa = x2; + xb = x1; + } + if (y2 < y1) + { + ya = y2; + yb = y1; + } + return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ]; + }; + /*}}}*/ + function getRect()/*{{{*/ + { + var xsize = x2 - x1; + var ysize = y2 - y1; + + if (xlimit && (Math.abs(xsize) > xlimit)) + x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit); + if (ylimit && (Math.abs(ysize) > ylimit)) + y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit); + + if (ymin && (Math.abs(ysize) < ymin)) + y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin); + if (xmin && (Math.abs(xsize) < xmin)) + x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin); + + if (x1 < 0) { x2 -= x1; x1 -= x1; } + if (y1 < 0) { y2 -= y1; y1 -= y1; } + if (x2 < 0) { x1 -= x2; x2 -= x2; } + if (y2 < 0) { y1 -= y2; y2 -= y2; } + if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; } + if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; } + if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; } + if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; } + + return makeObj(flipCoords(x1,y1,x2,y2)); + }; + /*}}}*/ + function makeObj(a)/*{{{*/ + { + return { x: a[0], y: a[1], x2: a[2], y2: a[3], + w: a[2] - a[0], h: a[3] - a[1] }; + }; + /*}}}*/ + + return { + flipCoords: flipCoords, + setPressed: setPressed, + setCurrent: setCurrent, + getOffset: getOffset, + moveOffset: moveOffset, + getCorner: getCorner, + getFixed: getFixed + }; + }(); + + /*}}}*/ + var Selection = function()/*{{{*/ + { + var start, end, dragmode, awake, hdep = 370; + var borders = { }; + var handle = { }; + var seehandles = false; + var hhs = options.handleOffset; + + /* Insert draggable elements {{{*/ + + // Insert border divs for outline + if (options.drawBorders) { + borders = { + top: insertBorder('hline') + .css('top',$.browser.msie?px(-1):px(0)), + bottom: insertBorder('hline'), + left: insertBorder('vline'), + right: insertBorder('vline') + }; + } + + // Insert handles on edges + if (options.dragEdges) { + handle.t = insertDragbar('n'); + handle.b = insertDragbar('s'); + handle.r = insertDragbar('e'); + handle.l = insertDragbar('w'); + } + + // Insert side handles + options.sideHandles && + createHandles(['n','s','e','w']); + + // Insert corner handles + options.cornerHandles && + createHandles(['sw','nw','ne','se']); + + /*}}}*/ + // Private Methods + function insertBorder(type)/*{{{*/ + { + var jq = $('
    ') + .css({position: 'absolute', opacity: options.borderOpacity }) + .addClass(cssClass(type)); + $img_holder.append(jq); + return jq; + }; + /*}}}*/ + function dragDiv(ord,zi)/*{{{*/ + { + var jq = $('
    ') + .mousedown(createDragger(ord)) + .css({ + cursor: ord+'-resize', + position: 'absolute', + zIndex: zi + }) + ; + $hdl_holder.append(jq); + return jq; + }; + /*}}}*/ + function insertHandle(ord)/*{{{*/ + { + return dragDiv(ord,hdep++) + .css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity }) + .addClass(cssClass('handle')); + }; + /*}}}*/ + function insertDragbar(ord)/*{{{*/ + { + var s = options.handleSize, + o = hhs, + h = s, w = s, + t = o, l = o; + + switch(ord) + { + case 'n': case 's': w = pct(100); break; + case 'e': case 'w': h = pct(100); break; + } + + return dragDiv(ord,hdep++).width(w).height(h) + .css({ top: px(-t+1), left: px(-l+1)}); + }; + /*}}}*/ + function createHandles(li)/*{{{*/ + { + for(i in li) handle[li[i]] = insertHandle(li[i]); + }; + /*}}}*/ + function moveHandles(c)/*{{{*/ + { + var midvert = Math.round((c.h / 2) - hhs), + midhoriz = Math.round((c.w / 2) - hhs), + north = west = -hhs+1, + east = c.w - hhs, + south = c.h - hhs, + x, y; + + 'e' in handle && + handle.e.css({ top: px(midvert), left: px(east) }) && + handle.w.css({ top: px(midvert) }) && + handle.s.css({ top: px(south), left: px(midhoriz) }) && + handle.n.css({ left: px(midhoriz) }); + + 'ne' in handle && + handle.ne.css({ left: px(east) }) && + handle.se.css({ top: px(south), left: px(east) }) && + handle.sw.css({ top: px(south) }); + + 'b' in handle && + handle.b.css({ top: px(south) }) && + handle.r.css({ left: px(east) }); + }; + /*}}}*/ + function moveto(x,y)/*{{{*/ + { + $img2.css({ top: px(-y), left: px(-x) }); + $sel.css({ top: px(y), left: px(x) }); + }; + /*}}}*/ + function resize(w,h)/*{{{*/ + { + $sel.width(w).height(h); + }; + /*}}}*/ + function refresh()/*{{{*/ + { + var c = Coords.getFixed(); + + Coords.setPressed([c.x,c.y]); + Coords.setCurrent([c.x2,c.y2]); + + updateVisible(); + }; + /*}}}*/ + + // Internal Methods + function updateVisible()/*{{{*/ + { if (awake) return update(); }; + /*}}}*/ + function update()/*{{{*/ + { + var c = Coords.getFixed(); + + resize(c.w,c.h); + moveto(c.x,c.y); + + options.drawBorders && + borders['right'].css({ left: px(c.w-1) }) && + borders['bottom'].css({ top: px(c.h-1) }); + + seehandles && moveHandles(c); + awake || show(); + + options.onChange(unscale(c)); + }; + /*}}}*/ + function show()/*{{{*/ + { + $sel.show(); + $img.css('opacity',options.bgOpacity); + awake = true; + }; + /*}}}*/ + function release()/*{{{*/ + { + disableHandles(); + $sel.hide(); + $img.css('opacity',1); + awake = false; + }; + /*}}}*/ + function showHandles()//{{{ + { + if (seehandles) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + } + }; + //}}} + function enableHandles()/*{{{*/ + { + seehandles = true; + if (options.allowResize) + { + moveHandles(Coords.getFixed()); + $hdl_holder.show(); + return true; + } + }; + /*}}}*/ + function disableHandles()/*{{{*/ + { + seehandles = false; + $hdl_holder.hide(); + }; + /*}}}*/ + function animMode(v)/*{{{*/ + { + (animating = v) ? disableHandles(): enableHandles(); + }; + /*}}}*/ + function done()/*{{{*/ + { + animMode(false); + refresh(); + }; + /*}}}*/ + + var $track = newTracker().mousedown(createDragger('move')) + .css({ cursor: 'move', position: 'absolute', zIndex: 360 }) + + $img_holder.append($track); + disableHandles(); + + return { + updateVisible: updateVisible, + update: update, + release: release, + refresh: refresh, + setCursor: function (cursor) { $track.css('cursor',cursor); }, + enableHandles: enableHandles, + enableOnly: function() { seehandles = true; }, + showHandles: showHandles, + disableHandles: disableHandles, + animMode: animMode, + done: done + }; + }(); + /*}}}*/ + var Tracker = function()/*{{{*/ + { + var onMove = function() { }, + onDone = function() { }, + trackDoc = options.trackDocument; + + if (!trackDoc) + { + $trk + .mousemove(trackMove) + .mouseup(trackUp) + .mouseout(trackUp) + ; + } + + function toFront()/*{{{*/ + { + $trk.css({zIndex:450}); + if (trackDoc) + { + $(document) + .mousemove(trackMove) + .mouseup(trackUp) + ; + } + } + /*}}}*/ + function toBack()/*{{{*/ + { + $trk.css({zIndex:290}); + if (trackDoc) + { + $(document) + .unbind('mousemove',trackMove) + .unbind('mouseup',trackUp) + ; + } + } + /*}}}*/ + function trackMove(e)/*{{{*/ + { + onMove(mouseAbs(e)); + }; + /*}}}*/ + function trackUp(e)/*{{{*/ + { + e.preventDefault(); + e.stopPropagation(); + + if (btndown) + { + btndown = false; + + onDone(mouseAbs(e)); + options.onSelect(unscale(Coords.getFixed())); + toBack(); + onMove = function() { }; + onDone = function() { }; + } + + return false; + }; + /*}}}*/ + + function activateHandlers(move,done)/* {{{ */ + { + btndown = true; + onMove = move; + onDone = done; + toFront(); + return false; + }; + /* }}} */ + + function setCursor(t) { $trk.css('cursor',t); }; + + $img.before($trk); + return { + activateHandlers: activateHandlers, + setCursor: setCursor + }; + }(); + /*}}}*/ + var KeyManager = function()/*{{{*/ + { + var $keymgr = $('') + .css({ position: 'absolute', left: '-30px' }) + .keypress(parseKey) + .blur(onBlur), + + $keywrap = $('
    ') + .css({ + position: 'absolute', + overflow: 'hidden' + }) + .append($keymgr) + ; + + function watchKeys()/*{{{*/ + { + if (options.keySupport) + { + $keymgr.show(); + $keymgr.focus(); + } + }; + /*}}}*/ + function onBlur(e)/*{{{*/ + { + $keymgr.hide(); + }; + /*}}}*/ + function doNudge(e,x,y)/*{{{*/ + { + if (options.allowMove) { + Coords.moveOffset([x,y]); + Selection.updateVisible(); + }; + e.preventDefault(); + e.stopPropagation(); + }; + /*}}}*/ + function parseKey(e)/*{{{*/ + { + if (e.ctrlKey) return true; + shift_down = e.shiftKey ? true : false; + var nudge = shift_down ? 10 : 1; + switch(e.keyCode) + { + case 37: doNudge(e,-nudge,0); break; + case 39: doNudge(e,nudge,0); break; + case 38: doNudge(e,0,-nudge); break; + case 40: doNudge(e,0,nudge); break; + + case 27: Selection.release(); break; + + case 9: return true; + } + + return nothing(e); + }; + /*}}}*/ + + if (options.keySupport) $keywrap.insertBefore($img); + return { + watchKeys: watchKeys + }; + }(); + /*}}}*/ + + // }}} + // Internal Methods {{{ + + function px(n) { return '' + parseInt(n) + 'px'; }; + function pct(n) { return '' + parseInt(n) + '%'; }; + function cssClass(cl) { return options.baseClass + '-' + cl; }; + function getPos(obj)/*{{{*/ + { + // Updated in v0.9.4 to use built-in dimensions plugin + var pos = $(obj).offset(); + return [ pos.left, pos.top ]; + }; + /*}}}*/ + function mouseAbs(e)/*{{{*/ + { + return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ]; + }; + /*}}}*/ + function myCursor(type)/*{{{*/ + { + if (type != lastcurs) + { + Tracker.setCursor(type); + //Handles.xsetCursor(type); + lastcurs = type; + } + }; + /*}}}*/ + function startDragMode(mode,pos)/*{{{*/ + { + docOffset = getPos($img); + Tracker.setCursor(mode=='move'?mode:mode+'-resize'); + + if (mode == 'move') + return Tracker.activateHandlers(createMover(pos), doneSelect); + + var fc = Coords.getFixed(); + var opp = oppLockCorner(mode); + var opc = Coords.getCorner(oppLockCorner(opp)); + + Coords.setPressed(Coords.getCorner(opp)); + Coords.setCurrent(opc); + + Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect); + }; + /*}}}*/ + function dragmodeHandler(mode,f)/*{{{*/ + { + return function(pos) { + if (!options.aspectRatio) switch(mode) + { + case 'e': pos[1] = f.y2; break; + case 'w': pos[1] = f.y2; break; + case 'n': pos[0] = f.x2; break; + case 's': pos[0] = f.x2; break; + } + else switch(mode) + { + case 'e': pos[1] = f.y+1; break; + case 'w': pos[1] = f.y+1; break; + case 'n': pos[0] = f.x+1; break; + case 's': pos[0] = f.x+1; break; + } + Coords.setCurrent(pos); + Selection.update(); + }; + }; + /*}}}*/ + function createMover(pos)/*{{{*/ + { + var lloc = pos; + KeyManager.watchKeys(); + + return function(pos) + { + Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]); + lloc = pos; + + Selection.update(); + }; + }; + /*}}}*/ + function oppLockCorner(ord)/*{{{*/ + { + switch(ord) + { + case 'n': return 'sw'; + case 's': return 'nw'; + case 'e': return 'nw'; + case 'w': return 'ne'; + case 'ne': return 'sw'; + case 'nw': return 'se'; + case 'se': return 'nw'; + case 'sw': return 'ne'; + }; + }; + /*}}}*/ + function createDragger(ord)/*{{{*/ + { + return function(e) { + if (options.disabled) return false; + if ((ord == 'move') && !options.allowMove) return false; + btndown = true; + startDragMode(ord,mouseAbs(e)); + e.stopPropagation(); + e.preventDefault(); + return false; + }; + }; + /*}}}*/ + function presize($obj,w,h)/*{{{*/ + { + var nw = $obj.width(), nh = $obj.height(); + if ((nw > w) && w > 0) + { + nw = w; + nh = (w/$obj.width()) * $obj.height(); + } + if ((nh > h) && h > 0) + { + nh = h; + nw = (h/$obj.height()) * $obj.width(); + } + xscale = $obj.width() / nw; + yscale = $obj.height() / nh; + $obj.width(nw).height(nh); + }; + /*}}}*/ + function unscale(c)/*{{{*/ + { + return { + x: parseInt(c.x * xscale), y: parseInt(c.y * yscale), + x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale), + w: parseInt(c.w * xscale), h: parseInt(c.h * yscale) + }; + }; + /*}}}*/ + function doneSelect(pos)/*{{{*/ + { + var c = Coords.getFixed(); + if (c.w > options.minSelect[0] && c.h > options.minSelect[1]) + { + Selection.enableHandles(); + Selection.done(); + } + else + { + Selection.release(); + } + Tracker.setCursor( options.allowSelect?'crosshair':'default' ); + }; + /*}}}*/ + function newSelection(e)/*{{{*/ + { + if (options.disabled) return false; + if (!options.allowSelect) return false; + btndown = true; + docOffset = getPos($img); + Selection.disableHandles(); + myCursor('crosshair'); + var pos = mouseAbs(e); + Coords.setPressed(pos); + Tracker.activateHandlers(selectDrag,doneSelect); + KeyManager.watchKeys(); + Selection.update(); + + e.stopPropagation(); + e.preventDefault(); + return false; + }; + /*}}}*/ + function selectDrag(pos)/*{{{*/ + { + Coords.setCurrent(pos); + Selection.update(); + }; + /*}}}*/ + function newTracker() + { + var trk = $('
    ').addClass(cssClass('tracker')); + $.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' }); + return trk; + }; + + // }}} + // API methods {{{ + + function animateTo(a)/*{{{*/ + { + var x1 = a[0] / xscale, + y1 = a[1] / yscale, + x2 = a[2] / xscale, + y2 = a[3] / yscale; + + if (animating) return; + + var animto = Coords.flipCoords(x1,y1,x2,y2); + var c = Coords.getFixed(); + var animat = initcr = [ c.x, c.y, c.x2, c.y2 ]; + var interv = options.animationDelay; + + var x = animat[0]; + var y = animat[1]; + var x2 = animat[2]; + var y2 = animat[3]; + var ix1 = animto[0] - initcr[0]; + var iy1 = animto[1] - initcr[1]; + var ix2 = animto[2] - initcr[2]; + var iy2 = animto[3] - initcr[3]; + var pcent = 0; + var velocity = options.swingSpeed; + + Selection.animMode(true); + + var animator = function() + { + return function() + { + pcent += (100 - pcent) / velocity; + + animat[0] = x + ((pcent / 100) * ix1); + animat[1] = y + ((pcent / 100) * iy1); + animat[2] = x2 + ((pcent / 100) * ix2); + animat[3] = y2 + ((pcent / 100) * iy2); + + if (pcent < 100) animateStart(); + else Selection.done(); + + if (pcent >= 99.8) pcent = 100; + + setSelectRaw(animat); + }; + }(); + + function animateStart() + { window.setTimeout(animator,interv); }; + + animateStart(); + }; + /*}}}*/ + function setSelect(rect)//{{{ + { + setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]); + }; + //}}} + function setSelectRaw(l) /*{{{*/ + { + Coords.setPressed([l[0],l[1]]); + Coords.setCurrent([l[2],l[3]]); + Selection.update(); + }; + /*}}}*/ + function setOptions(opt)/*{{{*/ + { + if (typeof(opt) != 'object') opt = { }; + options = $.extend(options,opt); + + if (typeof(options.onChange)!=='function') + options.onChange = function() { }; + + if (typeof(options.onSelect)!=='function') + options.onSelect = function() { }; + + }; + /*}}}*/ + function tellSelect()/*{{{*/ + { + return unscale(Coords.getFixed()); + }; + /*}}}*/ + function tellScaled()/*{{{*/ + { + return Coords.getFixed(); + }; + /*}}}*/ + function setOptionsNew(opt)/*{{{*/ + { + setOptions(opt); + interfaceUpdate(); + }; + /*}}}*/ + function disableCrop()//{{{ + { + options.disabled = true; + Selection.disableHandles(); + Selection.setCursor('default'); + Tracker.setCursor('default'); + }; + //}}} + function enableCrop()//{{{ + { + options.disabled = false; + interfaceUpdate(); + }; + //}}} + function cancelCrop()//{{{ + { + Selection.done(); + Tracker.activateHandlers(null,null); + }; + //}}} + function destroy()//{{{ + { + $div.remove(); + $origimg.show(); + }; + //}}} + + function interfaceUpdate(alt)//{{{ + // This method tweaks the interface based on options object. + // Called when options are changed and at end of initialization. + { + options.allowResize ? + alt?Selection.enableOnly():Selection.enableHandles(): + Selection.disableHandles(); + + Tracker.setCursor( options.allowSelect? 'crosshair': 'default' ); + Selection.setCursor( options.allowMove? 'move': 'default' ); + + $div.css('backgroundColor',options.bgColor); + + if ('setSelect' in options) { + setSelect(opt.setSelect); + Selection.done(); + delete(options.setSelect); + } + + if ('trueSize' in options) { + xscale = options.trueSize[0] / boundx; + yscale = options.trueSize[1] / boundy; + } + + xlimit = options.maxSize[0] || 0; + ylimit = options.maxSize[1] || 0; + xmin = options.minSize[0] || 0; + ymin = options.minSize[1] || 0; + + if ('outerImage' in options) + { + $img.attr('src',options.outerImage); + delete(options.outerImage); + } + + Selection.refresh(); + }; + //}}} + + // }}} + + $hdl_holder.hide(); + interfaceUpdate(true); + + var api = { + animateTo: animateTo, + setSelect: setSelect, + setOptions: setOptionsNew, + tellSelect: tellSelect, + tellScaled: tellScaled, + + disable: disableCrop, + enable: enableCrop, + cancel: cancelCrop, + + focus: KeyManager.watchKeys, + + getBounds: function() { return [ boundx * xscale, boundy * yscale ]; }, + getWidgetSize: function() { return [ boundx, boundy ]; }, + + release: Selection.release, + destroy: destroy + + }; + + $origimg.data('Jcrop',api); + return api; +}; + +$.fn.Jcrop = function(options)/*{{{*/ +{ + function attachWhenDone(from)/*{{{*/ + { + var loadsrc = options.useImg || from.src; + var img = new Image(); + img.onload = function() { $.Jcrop(from,options); }; + img.src = loadsrc; + }; + /*}}}*/ + if (typeof(options) !== 'object') options = { }; + + // Iterate over each object, attach Jcrop + this.each(function() + { + // If we've already attached to this object + if ($(this).data('Jcrop')) + { + // The API can be requested this way (undocumented) + if (options == 'api') return $(this).data('Jcrop'); + // Otherwise, we just reset the options... + else $(this).data('Jcrop').setOptions(options); + } + // If we haven't been attached, preload and attach + else attachWhenDone(this); + }); + + // Return "this" so we're chainable a la jQuery plugin-style! + return this; +}; +/*}}}*/ + +})(jQuery); diff --git a/wp-includes/js/jcrop/jquery.Jcrop.js b/wp-includes/js/jcrop/jquery.Jcrop.js new file mode 100644 index 0000000..9002b97 --- /dev/null +++ b/wp-includes/js/jcrop/jquery.Jcrop.js @@ -0,0 +1,163 @@ +/** + * Jcrop v.0.9.8 (minimized) + * (c) 2008 Kelly Hallman and DeepLiquid.com + * More information: http://deepliquid.com/content/Jcrop.html + * Released under MIT License - this header must remain with code + */ + + +(function($){$.Jcrop=function(obj,opt) +{var obj=obj,opt=opt;if(typeof(obj)!=='object')obj=$(obj)[0];if(typeof(opt)!=='object')opt={};if(!('trackDocument'in opt)) +{opt.trackDocument=$.browser.msie?false:true;if($.browser.msie&&$.browser.version.split('.')[0]=='8') +opt.trackDocument=true;} +if(!('keySupport'in opt)) +opt.keySupport=$.browser.msie?false:true;var defaults={trackDocument:false,baseClass:'jcrop',addClass:null,bgColor:'black',bgOpacity:.6,borderOpacity:.4,handleOpacity:.5,handlePad:5,handleSize:9,handleOffset:5,edgeMargin:14,aspectRatio:0,keySupport:true,cornerHandles:true,sideHandles:true,drawBorders:true,dragEdges:true,boxWidth:0,boxHeight:0,boundary:8,animationDelay:20,swingSpeed:3,allowSelect:true,allowMove:true,allowResize:true,minSelect:[0,0],maxSize:[0,0],minSize:[0,0],onChange:function(){},onSelect:function(){}};var options=defaults;setOptions(opt);var $origimg=$(obj);var $img=$origimg.clone().removeAttr('id').css({position:'absolute'});$img.width($origimg.width());$img.height($origimg.height());$origimg.after($img).hide();presize($img,options.boxWidth,options.boxHeight);var boundx=$img.width(),boundy=$img.height(),$div=$('
    ').width(boundx).height(boundy).addClass(cssClass('holder')).css({position:'relative',backgroundColor:options.bgColor}).insertAfter($origimg).append($img);;if(options.addClass)$div.addClass(options.addClass);var $img2=$('').attr('src',$img.attr('src')).css('position','absolute').width(boundx).height(boundy);var $img_holder=$('
    ').width(pct(100)).height(pct(100)).css({zIndex:310,position:'absolute',overflow:'hidden'}).append($img2);var $hdl_holder=$('
    ').width(pct(100)).height(pct(100)).css('zIndex',320);var $sel=$('
    ').css({position:'absolute',zIndex:300}).insertBefore($img).append($img_holder,$hdl_holder);var bound=options.boundary;var $trk=newTracker().width(boundx+(bound*2)).height(boundy+(bound*2)).css({position:'absolute',top:px(-bound),left:px(-bound),zIndex:290}).mousedown(newSelection);var xlimit,ylimit,xmin,ymin;var xscale,yscale,enabled=true;var docOffset=getPos($img),btndown,lastcurs,dimmed,animating,shift_down;var Coords=function() +{var x1=0,y1=0,x2=0,y2=0,ox,oy;function setPressed(pos) +{var pos=rebound(pos);x2=x1=pos[0];y2=y1=pos[1];};function setCurrent(pos) +{var pos=rebound(pos);ox=pos[0]-x2;oy=pos[1]-y2;x2=pos[0];y2=pos[1];};function getOffset() +{return[ox,oy];};function moveOffset(offset) +{var ox=offset[0],oy=offset[1];if(0>x1+ox)ox-=ox+x1;if(0>y1+oy)oy-=oy+y1;if(boundyboundx) +{xx=boundx;h=Math.abs((xx-x1)/aspect);yy=rh<0?y1-h:h+y1;}} +else +{xx=x2;h=rwa/aspect;yy=rh<0?y1-h:y1+h;if(yy<0) +{yy=0;w=Math.abs((yy-y1)*aspect);xx=rw<0?x1-w:w+x1;} +else if(yy>boundy) +{yy=boundy;w=Math.abs(yy-y1)*aspect;xx=rw<0?x1-w:w+x1;}} +if(xx>x1){if(xx-x1max_x){xx=x1+max_x;} +if(yy>y1){yy=y1+(xx-x1)/aspect;}else{yy=y1-(xx-x1)/aspect;}}else if(xxmax_x){xx=x1-max_x;} +if(yy>y1){yy=y1+(x1-xx)/aspect;}else{yy=y1-(x1-xx)/aspect;}} +if(xx<0){x1-=xx;xx=0;}else if(xx>boundx){x1-=xx-boundx;xx=boundx;} +if(yy<0){y1-=yy;yy=0;}else if(yy>boundy){y1-=yy-boundy;yy=boundy;} +return last=makeObj(flipCoords(x1,y1,xx,yy));};function rebound(p) +{if(p[0]<0)p[0]=0;if(p[1]<0)p[1]=0;if(p[0]>boundx)p[0]=boundx;if(p[1]>boundy)p[1]=boundy;return[p[0],p[1]];};function flipCoords(x1,y1,x2,y2) +{var xa=x1,xb=x2,ya=y1,yb=y2;if(x2xlimit)) +x2=(xsize>0)?(x1+xlimit):(x1-xlimit);if(ylimit&&(Math.abs(ysize)>ylimit)) +y2=(ysize>0)?(y1+ylimit):(y1-ylimit);if(ymin&&(Math.abs(ysize)0)?(y1+ymin):(y1-ymin);if(xmin&&(Math.abs(xsize)0)?(x1+xmin):(x1-xmin);if(x1<0){x2-=x1;x1-=x1;} +if(y1<0){y2-=y1;y1-=y1;} +if(x2<0){x1-=x2;x2-=x2;} +if(y2<0){y1-=y2;y2-=y2;} +if(x2>boundx){var delta=x2-boundx;x1-=delta;x2-=delta;} +if(y2>boundy){var delta=y2-boundy;y1-=delta;y2-=delta;} +if(x1>boundx){var delta=x1-boundy;y2-=delta;y1-=delta;} +if(y1>boundy){var delta=y1-boundy;y2-=delta;y1-=delta;} +return makeObj(flipCoords(x1,y1,x2,y2));};function makeObj(a) +{return{x:a[0],y:a[1],x2:a[2],y2:a[3],w:a[2]-a[0],h:a[3]-a[1]};};return{flipCoords:flipCoords,setPressed:setPressed,setCurrent:setCurrent,getOffset:getOffset,moveOffset:moveOffset,getCorner:getCorner,getFixed:getFixed};}();var Selection=function() +{var start,end,dragmode,awake,hdep=370;var borders={};var handle={};var seehandles=false;var hhs=options.handleOffset;if(options.drawBorders){borders={top:insertBorder('hline').css('top',$.browser.msie?px(-1):px(0)),bottom:insertBorder('hline'),left:insertBorder('vline'),right:insertBorder('vline')};} +if(options.dragEdges){handle.t=insertDragbar('n');handle.b=insertDragbar('s');handle.r=insertDragbar('e');handle.l=insertDragbar('w');} +options.sideHandles&&createHandles(['n','s','e','w']);options.cornerHandles&&createHandles(['sw','nw','ne','se']);function insertBorder(type) +{var jq=$('
    ').css({position:'absolute',opacity:options.borderOpacity}).addClass(cssClass(type));$img_holder.append(jq);return jq;};function dragDiv(ord,zi) +{var jq=$('
    ').mousedown(createDragger(ord)).css({cursor:ord+'-resize',position:'absolute',zIndex:zi});$hdl_holder.append(jq);return jq;};function insertHandle(ord) +{return dragDiv(ord,hdep++).css({top:px(-hhs+1),left:px(-hhs+1),opacity:options.handleOpacity}).addClass(cssClass('handle'));};function insertDragbar(ord) +{var s=options.handleSize,o=hhs,h=s,w=s,t=o,l=o;switch(ord) +{case'n':case's':w=pct(100);break;case'e':case'w':h=pct(100);break;} +return dragDiv(ord,hdep++).width(w).height(h).css({top:px(-t+1),left:px(-l+1)});};function createHandles(li) +{for(i in li)handle[li[i]]=insertHandle(li[i]);};function moveHandles(c) +{var midvert=Math.round((c.h/2)-hhs),midhoriz=Math.round((c.w/2)-hhs),north=west=-hhs+1,east=c.w-hhs,south=c.h-hhs,x,y;'e'in handle&&handle.e.css({top:px(midvert),left:px(east)})&&handle.w.css({top:px(midvert)})&&handle.s.css({top:px(south),left:px(midhoriz)})&&handle.n.css({left:px(midhoriz)});'ne'in handle&&handle.ne.css({left:px(east)})&&handle.se.css({top:px(south),left:px(east)})&&handle.sw.css({top:px(south)});'b'in handle&&handle.b.css({top:px(south)})&&handle.r.css({left:px(east)});};function moveto(x,y) +{$img2.css({top:px(-y),left:px(-x)});$sel.css({top:px(y),left:px(x)});};function resize(w,h) +{$sel.width(w).height(h);};function refresh() +{var c=Coords.getFixed();Coords.setPressed([c.x,c.y]);Coords.setCurrent([c.x2,c.y2]);updateVisible();};function updateVisible() +{if(awake)return update();};function update() +{var c=Coords.getFixed();resize(c.w,c.h);moveto(c.x,c.y);options.drawBorders&&borders['right'].css({left:px(c.w-1)})&&borders['bottom'].css({top:px(c.h-1)});seehandles&&moveHandles(c);awake||show();options.onChange(unscale(c));};function show() +{$sel.show();$img.css('opacity',options.bgOpacity);awake=true;};function release() +{disableHandles();$sel.hide();$img.css('opacity',1);awake=false;};function showHandles() +{if(seehandles) +{moveHandles(Coords.getFixed());$hdl_holder.show();}};function enableHandles() +{seehandles=true;if(options.allowResize) +{moveHandles(Coords.getFixed());$hdl_holder.show();return true;}};function disableHandles() +{seehandles=false;$hdl_holder.hide();};function animMode(v) +{(animating=v)?disableHandles():enableHandles();};function done() +{animMode(false);refresh();};var $track=newTracker().mousedown(createDragger('move')).css({cursor:'move',position:'absolute',zIndex:360}) +$img_holder.append($track);disableHandles();return{updateVisible:updateVisible,update:update,release:release,refresh:refresh,setCursor:function(cursor){$track.css('cursor',cursor);},enableHandles:enableHandles,enableOnly:function(){seehandles=true;},showHandles:showHandles,disableHandles:disableHandles,animMode:animMode,done:done};}();var Tracker=function() +{var onMove=function(){},onDone=function(){},trackDoc=options.trackDocument;if(!trackDoc) +{$trk.mousemove(trackMove).mouseup(trackUp).mouseout(trackUp);} +function toFront() +{$trk.css({zIndex:450});if(trackDoc) +{$(document).mousemove(trackMove).mouseup(trackUp);}} +function toBack() +{$trk.css({zIndex:290});if(trackDoc) +{$(document).unbind('mousemove',trackMove).unbind('mouseup',trackUp);}} +function trackMove(e) +{onMove(mouseAbs(e));};function trackUp(e) +{e.preventDefault();e.stopPropagation();if(btndown) +{btndown=false;onDone(mouseAbs(e));options.onSelect(unscale(Coords.getFixed()));toBack();onMove=function(){};onDone=function(){};} +return false;};function activateHandlers(move,done) +{btndown=true;onMove=move;onDone=done;toFront();return false;};function setCursor(t){$trk.css('cursor',t);};$img.before($trk);return{activateHandlers:activateHandlers,setCursor:setCursor};}();var KeyManager=function() +{var $keymgr=$('').css({position:'absolute',left:'-30px'}).keypress(parseKey).blur(onBlur),$keywrap=$('
    ').css({position:'absolute',overflow:'hidden'}).append($keymgr);function watchKeys() +{if(options.keySupport) +{$keymgr.show();$keymgr.focus();}};function onBlur(e) +{$keymgr.hide();};function doNudge(e,x,y) +{if(options.allowMove){Coords.moveOffset([x,y]);Selection.updateVisible();};e.preventDefault();e.stopPropagation();};function parseKey(e) +{if(e.ctrlKey)return true;shift_down=e.shiftKey?true:false;var nudge=shift_down?10:1;switch(e.keyCode) +{case 37:doNudge(e,-nudge,0);break;case 39:doNudge(e,nudge,0);break;case 38:doNudge(e,0,-nudge);break;case 40:doNudge(e,0,nudge);break;case 27:Selection.release();break;case 9:return true;} +return nothing(e);};if(options.keySupport)$keywrap.insertBefore($img);return{watchKeys:watchKeys};}();function px(n){return''+parseInt(n)+'px';};function pct(n){return''+parseInt(n)+'%';};function cssClass(cl){return options.baseClass+'-'+cl;};function getPos(obj) +{var pos=$(obj).offset();return[pos.left,pos.top];};function mouseAbs(e) +{return[(e.pageX-docOffset[0]),(e.pageY-docOffset[1])];};function myCursor(type) +{if(type!=lastcurs) +{Tracker.setCursor(type);lastcurs=type;}};function startDragMode(mode,pos) +{docOffset=getPos($img);Tracker.setCursor(mode=='move'?mode:mode+'-resize');if(mode=='move') +return Tracker.activateHandlers(createMover(pos),doneSelect);var fc=Coords.getFixed();var opp=oppLockCorner(mode);var opc=Coords.getCorner(oppLockCorner(opp));Coords.setPressed(Coords.getCorner(opp));Coords.setCurrent(opc);Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect);};function dragmodeHandler(mode,f) +{return function(pos){if(!options.aspectRatio)switch(mode) +{case'e':pos[1]=f.y2;break;case'w':pos[1]=f.y2;break;case'n':pos[0]=f.x2;break;case's':pos[0]=f.x2;break;} +else switch(mode) +{case'e':pos[1]=f.y+1;break;case'w':pos[1]=f.y+1;break;case'n':pos[0]=f.x+1;break;case's':pos[0]=f.x+1;break;} +Coords.setCurrent(pos);Selection.update();};};function createMover(pos) +{var lloc=pos;KeyManager.watchKeys();return function(pos) +{Coords.moveOffset([pos[0]-lloc[0],pos[1]-lloc[1]]);lloc=pos;Selection.update();};};function oppLockCorner(ord) +{switch(ord) +{case'n':return'sw';case's':return'nw';case'e':return'nw';case'w':return'ne';case'ne':return'sw';case'nw':return'se';case'se':return'nw';case'sw':return'ne';};};function createDragger(ord) +{return function(e){if(options.disabled)return false;if((ord=='move')&&!options.allowMove)return false;btndown=true;startDragMode(ord,mouseAbs(e));e.stopPropagation();e.preventDefault();return false;};};function presize($obj,w,h) +{var nw=$obj.width(),nh=$obj.height();if((nw>w)&&w>0) +{nw=w;nh=(w/$obj.width())*$obj.height();} +if((nh>h)&&h>0) +{nh=h;nw=(h/$obj.height())*$obj.width();} +xscale=$obj.width()/nw;yscale=$obj.height()/nh;$obj.width(nw).height(nh);};function unscale(c) +{return{x:parseInt(c.x*xscale),y:parseInt(c.y*yscale),x2:parseInt(c.x2*xscale),y2:parseInt(c.y2*yscale),w:parseInt(c.w*xscale),h:parseInt(c.h*yscale)};};function doneSelect(pos) +{var c=Coords.getFixed();if(c.w>options.minSelect[0]&&c.h>options.minSelect[1]) +{Selection.enableHandles();Selection.done();} +else +{Selection.release();} +Tracker.setCursor(options.allowSelect?'crosshair':'default');};function newSelection(e) +{if(options.disabled)return false;if(!options.allowSelect)return false;btndown=true;docOffset=getPos($img);Selection.disableHandles();myCursor('crosshair');var pos=mouseAbs(e);Coords.setPressed(pos);Tracker.activateHandlers(selectDrag,doneSelect);KeyManager.watchKeys();Selection.update();e.stopPropagation();e.preventDefault();return false;};function selectDrag(pos) +{Coords.setCurrent(pos);Selection.update();};function newTracker() +{var trk=$('
    ').addClass(cssClass('tracker'));$.browser.msie&&trk.css({opacity:0,backgroundColor:'white'});return trk;};function animateTo(a) +{var x1=a[0]/xscale,y1=a[1]/yscale,x2=a[2]/xscale,y2=a[3]/yscale;if(animating)return;var animto=Coords.flipCoords(x1,y1,x2,y2);var c=Coords.getFixed();var animat=initcr=[c.x,c.y,c.x2,c.y2];var interv=options.animationDelay;var x=animat[0];var y=animat[1];var x2=animat[2];var y2=animat[3];var ix1=animto[0]-initcr[0];var iy1=animto[1]-initcr[1];var ix2=animto[2]-initcr[2];var iy2=animto[3]-initcr[3];var pcent=0;var velocity=options.swingSpeed;Selection.animMode(true);var animator=function() +{return function() +{pcent+=(100-pcent)/velocity;animat[0]=x+((pcent/100)*ix1);animat[1]=y+((pcent/100)*iy1);animat[2]=x2+((pcent/100)*ix2);animat[3]=y2+((pcent/100)*iy2);if(pcent<100)animateStart();else Selection.done();if(pcent>=99.8)pcent=100;setSelectRaw(animat);};}();function animateStart() +{window.setTimeout(animator,interv);};animateStart();};function setSelect(rect) +{setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]);};function setSelectRaw(l) +{Coords.setPressed([l[0],l[1]]);Coords.setCurrent([l[2],l[3]]);Selection.update();};function setOptions(opt) +{if(typeof(opt)!='object')opt={};options=$.extend(options,opt);if(typeof(options.onChange)!=='function') +options.onChange=function(){};if(typeof(options.onSelect)!=='function') +options.onSelect=function(){};};function tellSelect() +{return unscale(Coords.getFixed());};function tellScaled() +{return Coords.getFixed();};function setOptionsNew(opt) +{setOptions(opt);interfaceUpdate();};function disableCrop() +{options.disabled=true;Selection.disableHandles();Selection.setCursor('default');Tracker.setCursor('default');};function enableCrop() +{options.disabled=false;interfaceUpdate();};function cancelCrop() +{Selection.done();Tracker.activateHandlers(null,null);};function destroy() +{$div.remove();$origimg.show();};function interfaceUpdate(alt) +{options.allowResize?alt?Selection.enableOnly():Selection.enableHandles():Selection.disableHandles();Tracker.setCursor(options.allowSelect?'crosshair':'default');Selection.setCursor(options.allowMove?'move':'default');$div.css('backgroundColor',options.bgColor);if('setSelect'in options){setSelect(opt.setSelect);Selection.done();delete(options.setSelect);} +if('trueSize'in options){xscale=options.trueSize[0]/boundx;yscale=options.trueSize[1]/boundy;} +xlimit=options.maxSize[0]||0;ylimit=options.maxSize[1]||0;xmin=options.minSize[0]||0;ymin=options.minSize[1]||0;if('outerImage'in options) +{$img.attr('src',options.outerImage);delete(options.outerImage);} +Selection.refresh();};$hdl_holder.hide();interfaceUpdate(true);var api={animateTo:animateTo,setSelect:setSelect,setOptions:setOptionsNew,tellSelect:tellSelect,tellScaled:tellScaled,disable:disableCrop,enable:enableCrop,cancel:cancelCrop,focus:KeyManager.watchKeys,getBounds:function(){return[boundx*xscale,boundy*yscale];},getWidgetSize:function(){return[boundx,boundy];},release:Selection.release,destroy:destroy};$origimg.data('Jcrop',api);return api;};$.fn.Jcrop=function(options) +{function attachWhenDone(from) +{var loadsrc=options.useImg||from.src;var img=new Image();img.onload=function(){$.Jcrop(from,options);};img.src=loadsrc;};if(typeof(options)!=='object')options={};this.each(function() +{if($(this).data('Jcrop')) +{if(options=='api')return $(this).data('Jcrop');else $(this).data('Jcrop').setOptions(options);} +else attachWhenDone(this);});return this;};})(jQuery); \ No newline at end of file diff --git a/wp-includes/js/jquery/interface.js b/wp-includes/js/jquery/interface.js new file mode 100644 index 0000000..6d00f2e --- /dev/null +++ b/wp-includes/js/jquery/interface.js @@ -0,0 +1,12 @@ +/** + * Interface Elements for jQuery + * + * http://interface.eyecon.ro + * + * Copyright (c) 2006 Stefan Petre + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * + */ +eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('A.cP={2l:C(c){G B.1y(C(){if(!c.8Y||!c.8P)G;F b=B;b.2a={9M:c.9M||bz,8Y:c.8Y,8P:c.8P,7R:c.7R||\'du\',9c:c.9c||\'du\',2K:c.2K&&28 c.2K==\'C\'?c.2K:H,2V:c.2K&&28 c.2V==\'C\'?c.2V:H,6D:c.6D&&28 c.6D==\'C\'?c.6D:H,8A:A(c.8Y,B),8a:A(c.8P,B),1l:c.1l||7n,5w:c.5w||0};b.2a.8a.2x().E(\'S\',\'9e\').eq(0).E({S:b.2a.9M+\'Q\',11:\'2v\'}).3m();b.2a.8A.1y(C(a){B.6L=a}).ht(C(){A(B).2H(b.2a.9c)},C(){A(B).3S(b.2a.9c)}).1C(\'4U\',C(e){if(b.2a.5w==B.6L)G;b.2a.8A.eq(b.2a.5w).3S(b.2a.7R).3m().eq(B.6L).2H(b.2a.7R).3m();b.2a.8a.eq(b.2a.5w).4S({S:0},b.2a.1l,C(){B.Y.11=\'1k\';if(b.2a.2V){b.2a.2V.1x(b,[B])}}).3m().eq(B.6L).1S().4S({S:b.2a.9M},b.2a.1l,C(){B.Y.11=\'2v\';if(b.2a.2K){b.2a.2K.1x(b,[B])}}).3m();if(b.2a.6D){b.2a.6D.1x(b,[B,b.2a.8a.I(B.6L),b.2a.8A.I(b.2a.5w),b.2a.8a.I(b.2a.5w)])}b.2a.5w=B.6L}).eq(0).2H(b.2a.7R).3m();A(B).E(\'S\',A(B).E(\'S\')).E(\'2N\',\'2B\')})}};A.fn.fe=A.cP.2l;A.8p={2l:C(h){G B.1y(C(){F c=B;F d=2*Z.2F/eD;F f=2*Z.2F;if(A(c).E(\'T\')!=\'2i\'&&A(c).E(\'T\')!=\'1J\'){A(c).E(\'T\',\'2i\')}c.1i={1M:A(h.1M,B),2y:h.2y,61:h.61,9l:h.9l,iu:f,1N:A.12.2f(B),T:A.12.3a(B),2b:Z.2F/2,b4:h.b4,7K:h.5U,5U:[],93:H,7G:2*Z.2F/eD};c.1i.d8=(c.1i.1N.w-c.1i.2y)/2;c.1i.6Y=(c.1i.1N.h-c.1i.61-c.1i.61*c.1i.7K)/2;c.1i.3f=2*Z.2F/c.1i.1M.1N();c.1i.aS=c.1i.1N.w/2;c.1i.aR=c.1i.1N.h/2-c.1i.61*c.1i.7K;F g=1c.3x(\'1W\');A(g).E({T:\'1J\',3j:1,O:0,M:0});A(c).1L(g);c.1i.1M.1y(C(a){8G=A(\'3O\',B).I(0);S=R(c.1i.61*c.1i.7K);if(A.2R.46){3u=1c.3x(\'3O\');A(3u).E(\'T\',\'1J\');3u.2E=8G.2E;3u.Y.4X=\'fu 9x:9C.9E.a6(1E=60, Y=1, fc=0, f9=0, f5=0, f3=0)\'}L{3u=1c.3x(\'3u\');if(3u.bZ){4j=3u.bZ("2d");3u.Y.T=\'1J\';3u.Y.S=S+\'Q\';3u.Y.V=c.1i.2y+\'Q\';3u.S=S;3u.V=c.1i.2y;4j.eR();4j.eM(0,S);4j.eJ(1,-1);4j.jm(8G,0,0,c.1i.2y,S);4j.bL();4j.jl="jh-3U";F b=4j.jf(0,0,0,S);b.es(1,"eg(1O, 1O, 1O, 1)");b.es(0,"eg(1O, 1O, 1O, 0.6)");4j.j9=b;if(j7.j5.3o(\'iX\')!=-1){4j.iV()}L{4j.iS(0,0,c.1i.2y,S)}}}c.1i.5U[a]=3u;A(g).1L(3u)}).1C(\'9r\',C(e){c.1i.93=14;c.1i.1l=c.1i.7G*0.1*c.1i.1l/Z.3B(c.1i.1l);G H}).1C(\'86\',C(e){c.1i.93=H;G H});A.8p.6z(c);c.1i.1l=c.1i.7G*0.2;c.1i.it=1P.5Y(C(){c.1i.2b+=c.1i.1l;if(c.1i.2b>f)c.1i.2b=0;A.8p.6z(c)},20);A(c).1C(\'86\',C(){c.1i.1l=c.1i.7G*0.2*c.1i.1l/Z.3B(c.1i.1l)}).1C(\'3t\',C(e){if(c.1i.93==H){1A=A.12.3W(e);dr=c.1i.1N.w-1A.x+c.1i.T.x;c.1i.1l=c.1i.b4*c.1i.7G*(c.1i.1N.w/2-dr)/(c.1i.1N.w/2)}})})},6z:C(b){b.1i.1M.1y(C(a){b8=b.1i.2b+a*b.1i.3f;x=b.1i.d8*Z.51(b8);y=b.1i.6Y*Z.7L(b8);do=R(1Y*(b.1i.6Y+y)/(2*b.1i.6Y));dm=(b.1i.6Y+y)/(2*b.1i.6Y);V=R((b.1i.2y-b.1i.9l)*dm+b.1i.9l);S=R(V*b.1i.61/b.1i.2y);B.Y.O=b.1i.aR+y-S/2+"Q";B.Y.M=b.1i.aS+x-V/2+"Q";B.Y.V=V+"Q";B.Y.S=S+"Q";B.Y.3j=do;b.1i.5U[a].Y.O=R(b.1i.aR+y+S-1-S/2)+"Q";b.1i.5U[a].Y.M=R(b.1i.aS+x-V/2)+"Q";b.1i.5U[a].Y.V=V+"Q";b.1i.5U[a].Y.S=R(S*b.1i.7K)+"Q"})}};A.fn.hL=A.8p.2l;A.1U({1e:{b1:C(p,n,a,b,c){G((-Z.51(p*Z.2F)/2)+0.5)*b+a},ho:C(p,n,a,b,c){G b*(n/=c)*n*n+a},d2:C(p,n,a,b,c){G-b*((n=n/c-1)*n*n*n-1)+a},hh:C(p,n,a,b,c){if((n/=c/2)<1)G b/2*n*n*n*n+a;G-b/2*((n-=2)*n*n*n-2)+a},7D:C(p,n,a,b,c){if((n/=c)<(1/2.75)){G b*(7.8W*n*n)+a}L if(n<(2/2.75)){G b*(7.8W*(n-=(1.5/2.75))*n+.75)+a}L if(n<(2.5/2.75)){G b*(7.8W*(n-=(2.25/2.75))*n+.gV)+a}L{G b*(7.8W*(n-=(2.gR/2.75))*n+.gN)+a}},aQ:C(p,n,a,b,c){if(A.1e.7D)G b-A.1e.7D(p,c-n,0,b,c)+a;G a+b},gE:C(p,n,a,b,c){if(A.1e.aQ&&A.1e.7D)if(ng.1z.6q?g.1z.6q:3J;3J=g.1z.6q-3J;bc=g.1z.5R*3J/g.1z.6q;B.Y.V=g.1z.2y+bc+\'Q\';B.Y.M=g.1z.2y*a+c+\'Q\';c+=bc});A.5K.8F(g,c)})})},8F:C(a,b){if(a.1z.4I)if(a.1z.4I==\'az\')a.1z.2q.I(0).Y.M=(a.3P-a.1z.2y*a.1z.1M.1N())/2-b/2+\'Q\';L if(a.1z.4I==\'M\')a.1z.2q.I(0).Y.M=-b/a.1z.1M.1N()+\'Q\';L if(a.1z.4I==\'2D\')a.1z.2q.I(0).Y.M=(a.3P-a.1z.2y*a.1z.1M.1N())-b/2+\'Q\';a.1z.2q.I(0).Y.V=a.1z.2y*a.1z.1M.1N()+b+\'Q\'},6z:C(b){b.1z.1M.1y(C(a){B.Y.V=b.1z.2y+\'Q\';B.Y.M=b.1z.2y*a+\'Q\'})}};A.fn.fz=A.5K.2l;A.K={18:P,7W:P,3q:P,2A:P,4b:P,af:P,2r:P,2h:P,1M:P,58:C(){A.K.7W.58();if(A.K.3q){A.K.3q.2x()}},4i:C(){A.K.1M=P;A.K.2h=P;A.K.4b=A.K.2r.2m;if(A.K.18.E(\'11\')==\'2v\'){if(A.K.2r.1a.fx){2X(A.K.2r.1a.fx.1K){19\'a4\':A.K.18.6d(A.K.2r.1a.fx.1H,A.K.58);1n;19\'1u\':A.K.18.c6(A.K.2r.1a.fx.1H,A.K.58);1n;19\'8o\':A.K.18.c3(A.K.2r.1a.fx.1H,A.K.58);1n}}L{A.K.18.2x()}if(A.K.2r.1a.2V)A.K.2r.1a.2V.1x(A.K.2r,[A.K.18,A.K.3q])}L{A.K.58()}1P.a2(A.K.2A)},c1:C(){F e=A.K.2r;F f=A.K.8C(e);if(e&&f.3w!=A.K.4b&&f.3w.1b>=e.1a.8N){A.K.4b=f.3w;A.K.af=f.3w;9V={bR:A(e).1m(\'eS\')||\'bR\',2m:f.3w};A.eQ({1K:\'eN\',9V:A.eL(9V),eK:C(b){e.1a.3X=A(\'3w\',b);1N=e.1a.3X.1N();if(1N>0){F c=\'\';e.1a.3X.1y(C(a){c+=\'<7b 4o="\'+A(\'2m\',B).3D()+\'" 8h="\'+a+\'" Y="7z: 8T;">\'+A(\'3D\',B).3D()+\'\'});if(e.1a.9K){F d=A(\'2m\',e.1a.3X.I(0)).3D();e.2m=f.30+d+e.1a.3y+f.5m;A.K.64(e,f.3w.1b!=d.1b?(f.30.1b+f.3w.1b):d.1b,f.3w.1b!=d.1b?(f.30.1b+d.1b):d.1b)}if(1N>0){A.K.aU(e,c)}L{A.K.4i()}}L{A.K.4i()}},5v:e.1a.96})}},aU:C(a,b){A.K.7W.3i(b);A.K.1M=A(\'7b\',A.K.7W.I(0));A.K.1M.9r(A.K.en).1C(\'4U\',A.K.ed);F c=A.12.3a(a);F d=A.12.2f(a);A.K.18.E(\'O\',c.y+d.hb+\'Q\').E(\'M\',c.x+\'Q\').2H(a.1a.9D);if(A.K.3q){A.K.3q.E(\'11\',\'2v\').E(\'O\',c.y+d.hb+\'Q\').E(\'M\',c.x+\'Q\').E(\'V\',A.K.18.E(\'V\')).E(\'S\',A.K.18.E(\'S\'))}A.K.2h=0;A.K.1M.I(0).2Z=a.1a.72;A.K.7I(a,a.1a.3X.I(0),\'6H\');if(A.K.18.E(\'11\')==\'1k\'){if(a.1a.bv){F e=A.12.9y(a,14);F f=A.12.6b(a,14);A.K.18.E(\'V\',a.3P-(A.e0?(e.l+e.r+f.l+f.r):0)+\'Q\')}if(a.1a.fx){2X(a.1a.fx.1K){19\'a4\':A.K.18.6U(a.1a.fx.1H);1n;19\'1u\':A.K.18.dR(a.1a.fx.1H);1n;19\'8o\':A.K.18.dP(a.1a.fx.1H);1n}}L{A.K.18.1S()}if(A.K.2r.1a.2K)A.K.2r.1a.2K.1x(A.K.2r,[A.K.18,A.K.3q])}},dM:C(){F b=B;if(b.1a.3X){A.K.4b=b.2m;A.K.af=b.2m;F c=\'\';b.1a.3X.1y(C(a){2m=A(\'2m\',B).3D().5u();dH=b.2m.5u();if(2m.3o(dH)==0){c+=\'<7b 4o="\'+A(\'2m\',B).3D()+\'" 8h="\'+a+\'" Y="7z: 8T;">\'+A(\'3D\',B).3D()+\'\'}});if(c!=\'\'){A.K.aU(b,c);B.1a.9s=14;G}}b.1a.3X=P;B.1a.9s=H},64:C(a,b,c){if(a.9q){F d=a.9q();d.iJ(14);d.dC("bh",b);d.iE("bh",-c+b);d.7Q()}L if(a.9m){a.9m(b,c)}L{if(a.88){a.88=b;a.dA=c}}a.6a()},dw:C(a){if(a.88)G a.88;L if(a.9q){F b=1c.64.dv();F c=b.il();G 0-c.dC(\'bh\',-ij)}},8C:C(a){F b={2m:a.2m,30:\'\',5m:\'\',3w:\'\'};if(a.1a.9k){F c=H;F d=A.K.dw(a)||0;F e=b.2m.6W(a.1a.3y);1V(F i=0;i=d||d==0)&&!c){if(b.30.1b<=d)b.3w=e[i];L b.5m+=e[i]+(e[i]!=\'\'?a.1a.3y:\'\');c=14}L if(c){b.5m+=e[i]+(e[i]!=\'\'?a.1a.3y:\'\')}if(!c){b.30+=e[i]+(e.1b>1?a.1a.3y:\'\')}}}L{b.3w=b.2m}G b},b9:C(e){1P.a2(A.K.2A);F a=A.K.8C(B);F b=e.6S||e.6R||-1;if(/13|27|35|36|38|40|9/.3M(b)&&A.K.1M){if(1P.3N){1P.3N.b6=14;1P.3N.b5=H}L{e.9b();e.99()}if(A.K.2h!=P)A.K.1M.I(A.K.2h||0).2Z=\'\';L A.K.2h=-1;2X(b){19 9:19 13:if(A.K.2h==-1)A.K.2h=0;F c=A.K.1M.I(A.K.2h||0);F d=c.4Z(\'4o\');B.2m=a.30+d+B.1a.3y+a.5m;A.K.4b=a.3w;A.K.64(B,a.30.1b+d.1b+B.1a.3y.1b,a.30.1b+d.1b+B.1a.3y.1b);A.K.4i();if(B.1a.5p){4E=R(c.4Z(\'8h\'))||0;A.K.7I(B,B.1a.3X.I(4E),\'5p\')}if(B.6O)B.6O(H);G b!=13;1n;19 27:B.2m=a.30+A.K.4b+B.1a.3y+a.5m;B.1a.3X=P;A.K.4i();if(B.6O)B.6O(H);G H;1n;19 35:A.K.2h=A.K.1M.1N()-1;1n;19 36:A.K.2h=0;1n;19 38:A.K.2h--;if(A.K.2h<0)A.K.2h=A.K.1M.1N()-1;1n;19 40:A.K.2h++;if(A.K.2h==A.K.1M.1N())A.K.2h=0;1n}A.K.7I(B,B.1a.3X.I(A.K.2h||0),\'6H\');A.K.1M.I(A.K.2h||0).2Z=B.1a.72;if(A.K.1M.I(A.K.2h||0).6O)A.K.1M.I(A.K.2h||0).6O(H);if(B.1a.9K){F f=A.K.1M.I(A.K.2h||0).4Z(\'4o\');B.2m=a.30+f+B.1a.3y+a.5m;if(A.K.4b.1b!=f.1b)A.K.64(B,a.30.1b+A.K.4b.1b,a.30.1b+f.1b)}G H}A.K.dM.1x(B);if(B.1a.9s==H){if(a.3w!=A.K.4b&&a.3w.1b>=B.1a.8N)A.K.2A=1P.97(A.K.c1,B.1a.4w);if(A.K.1M){A.K.4i()}}G 14},7I:C(a,b,c){if(a.1a[c]){F d={};94=b.dj(\'*\');1V(i=0;i<94.1b;i++){d[94[i].4D]=94[i].6M.hG}a.1a[c].1x(a,[d])}},en:C(e){if(A.K.1M){if(A.K.2h!=P)A.K.1M.I(A.K.2h||0).2Z=\'\';A.K.1M.I(A.K.2h||0).2Z=\'\';A.K.2h=R(B.4Z(\'8h\'))||0;A.K.1M.I(A.K.2h||0).2Z=A.K.2r.1a.72}},ed:C(a){1P.a2(A.K.2A);a=a||A.3N.hD(1P.3N);a.9b();a.99();F b=A.K.8C(A.K.2r);F c=B.4Z(\'4o\');A.K.2r.2m=b.30+c+A.K.2r.1a.3y+b.5m;A.K.4b=B.4Z(\'4o\');A.K.64(A.K.2r,b.30.1b+c.1b+A.K.2r.1a.3y.1b,b.30.1b+c.1b+A.K.2r.1a.3y.1b);A.K.4i();if(A.K.2r.1a.5p){4E=R(B.4Z(\'8h\'))||0;A.K.7I(A.K.2r,A.K.2r.1a.3X.I(4E),\'5p\')}G H},dh:C(e){6K=e.6S||e.6R||-1;if(/13|27|35|36|38|40/.3M(6K)&&A.K.1M){if(1P.3N){1P.3N.b6=14;1P.3N.b5=H}L{e.9b();e.99()}G H}},2l:C(a){if(!a.96||!A.12){G}if(!A.K.18){if(A.2R.46){A(\'23\',1c).1L(\'<3q Y="11:1k;T:1J;4X:9x:9C.9E.a6(1E=0);" id="df" 2E="dc:H;" da="0" d7="b0">\');A.K.3q=A(\'#df\')}A(\'23\',1c).1L(\'<1W id="d4" Y="T: 1J; O: 0; M: 0; z-aY: hj; 11: 1k;"><90 Y="5X: 0;7E: 0; h9-Y: 1k; z-aY: h8;">&6G;\');A.K.18=A(\'#d4\');A.K.7W=A(\'90\',A.K.18)}G B.1y(C(){if(B.4D!=\'aV\'&&B.4Z(\'1K\')!=\'3D\')G;B.1a={};B.1a.96=a.96;B.1a.8N=Z.3B(R(a.8N)||1);B.1a.9D=a.9D?a.9D:\'\';B.1a.72=a.72?a.72:\'\';B.1a.5p=a.5p&&a.5p.1F==2w?a.5p:P;B.1a.2K=a.2K&&a.2K.1F==2w?a.2K:P;B.1a.2V=a.2V&&a.2V.1F==2w?a.2V:P;B.1a.6H=a.6H&&a.6H.1F==2w?a.6H:P;B.1a.bv=a.bv||H;B.1a.9k=a.9k||H;B.1a.3y=B.1a.9k?(a.3y||\', \'):\'\';B.1a.9K=a.9K?14:H;B.1a.4w=Z.3B(R(a.4w)||8V);if(a.fx&&a.fx.1F==6E){if(!a.fx.1K||!/a4|1u|8o/.3M(a.fx.1K)){a.fx.1K=\'1u\'}if(a.fx.1K==\'1u\'&&!A.fx.1u)G;if(a.fx.1K==\'8o\'&&!A.fx.5l)G;a.fx.1H=Z.3B(R(a.fx.1H)||7n);if(a.fx.1H>B.1a.4w){a.fx.1H=B.1a.4w-1Y}B.1a.fx=a.fx}B.1a.3X=P;B.1a.9s=H;A(B).1m(\'b9\',\'cW\').6a(C(){A.K.2r=B;A.K.4b=B.2m}).cV(A.K.dh).5Q(A.K.b9).4W(C(){A.K.2A=1P.97(A.K.4i,gM)})})}};A.fn.gJ=A.K.2l;A.1t={2A:P,4k:P,1X:P,3f:10,2b:C(a,b,c,d){A.1t.4k=a;A.1t.1X=b;A.1t.3f=R(c)||10;A.1t.2A=1P.5Y(A.1t.cR,R(d)||40)},cR:C(){1V(i=0;i0&&A.1t.1X[i].2J.y+A.1t.1X[i].2J.t>5a.y){A.1t.1X[i].2T-=A.1t.3f}L if(A.1t.1X[i].2J.t<=A.1t.1X[i].2J.h&&A.1t.1X[i].2J.t+A.1t.1X[i].2J.hb<5a.y+5a.hb){A.1t.1X[i].2T+=A.1t.3f}if(A.1t.1X[i].2J.l>0&&A.1t.1X[i].2J.x+A.1t.1X[i].2J.l>5a.x){A.1t.1X[i].2P-=A.1t.3f}L if(A.1t.1X[i].2J.l<=A.1t.1X[i].2J.gf&&A.1t.1X[i].2J.l+A.1t.1X[i].2J.1D<5a.x+5a.1D){A.1t.1X[i].2P+=A.1t.3f}}},7w:C(){1P.5h(A.1t.2A);A.1t.4k=P;A.1t.1X=P;1V(i in A.1t.1X){A.1t.1X[i].2J=P}}};A.X={18:P,1g:P,4v:C(){G B.1y(C(){if(B.8L){B.D.cM.3h(\'4R\',A.X.aM);B.D=P;B.8L=H;if(A.2R.46){B.aI="cW"}L{B.Y.g0=\'\';B.Y.cJ=\'\';B.Y.cH=\'\'}}})},aM:C(e){if(A.X.1g!=P){A.X.8I(e);G H}F a=B.3H;A(1c).1C(\'3t\',A.X.aE).1C(\'5n\',A.X.8I);a.D.1A=A.12.3W(e);a.D.4d=a.D.1A;a.D.6g=H;a.D.fY=B!=B.3H;A.X.1g=a;if(a.D.4P&&B!=B.3H){aC=A.12.3a(a.2S);aZ=A.12.2f(a);ay={x:R(A.E(a,\'M\'))||0,y:R(A.E(a,\'O\'))||0};dx=a.D.4d.x-aC.x-aZ.1D/2-ay.x;dy=a.D.4d.y-aC.y-aZ.hb/2-ay.y;A.2Q.4s(a,[dx,dy])}G A.6J||H},cD:C(e){F a=A.X.1g;a.D.6g=14;F b=a.Y;a.D.6o=A.E(a,\'11\');a.D.49=A.E(a,\'T\');if(!a.D.av)a.D.av=a.D.49;a.D.22={x:R(A.E(a,\'M\'))||0,y:R(A.E(a,\'O\'))||0};a.D.8z=0;a.D.8y=0;if(A.2R.46){F c=A.12.6b(a,14);a.D.8z=c.l||0;a.D.8y=c.t||0}a.D.1w=A.1U(A.12.3a(a),A.12.2f(a));if(a.D.49!=\'2i\'&&a.D.49!=\'1J\'){b.T=\'2i\'}A.X.18.58();F d=A(a).cA(14).I(0);A(d).E({11:\'2v\',M:\'2G\',O:\'2G\'});d.Y.4M=\'0\';d.Y.53=\'0\';d.Y.4L=\'0\';d.Y.4K=\'0\';A.X.18.1L(d);F f=A.X.18.I(0).Y;if(a.D.ar){f.V=\'8x\';f.S=\'8x\'}L{f.S=a.D.1w.hb+\'Q\';f.V=a.D.1w.1D+\'Q\'}f.11=\'2v\';f.4M=\'2G\';f.53=\'2G\';f.4L=\'2G\';f.4K=\'2G\';A.1U(a.D.1w,A.12.2f(d));if(a.D.2M){if(a.D.2M.M){a.D.22.x+=a.D.1A.x-a.D.1w.x-a.D.2M.M;a.D.1w.x=a.D.1A.x-a.D.2M.M}if(a.D.2M.O){a.D.22.y+=a.D.1A.y-a.D.1w.y-a.D.2M.O;a.D.1w.y=a.D.1A.y-a.D.2M.O}if(a.D.2M.2D){a.D.22.x+=a.D.1A.x-a.D.1w.x-a.D.1w.hb+a.D.2M.2D;a.D.1w.x=a.D.1A.x-a.D.1w.1D+a.D.2M.2D}if(a.D.2M.4e){a.D.22.y+=a.D.1A.y-a.D.1w.y-a.D.1w.hb+a.D.2M.4e;a.D.1w.y=a.D.1A.y-a.D.1w.hb+a.D.2M.4e}}a.D.2n=a.D.22.x;a.D.2j=a.D.22.y;if(a.D.7V||a.D.2e==\'7X\'){7Z=A.12.6b(a.2S,14);a.D.1w.x=a.7Y+(A.2R.46?0:A.2R.6l?-7Z.l:7Z.l);a.D.1w.y=a.7t+(A.2R.46?0:A.2R.6l?-7Z.t:7Z.t);A(a.2S).1L(A.X.18.I(0))}if(a.D.2e){A.X.ah(a);a.D.4V.2e=A.X.ae}if(a.D.4P){A.2Q.ad(a)}f.M=a.D.1w.x-a.D.8z+\'Q\';f.O=a.D.1w.y-a.D.8y+\'Q\';f.V=a.D.1w.1D+\'Q\';f.S=a.D.1w.hb+\'Q\';A.X.1g.D.8w=H;if(a.D.gx){a.D.4V.5y=A.X.a9}if(a.D.3j!=H){A.X.18.E(\'3j\',a.D.3j)}if(a.D.1E){A.X.18.E(\'1E\',a.D.1E);if(1P.6j){A.X.18.E(\'4X\',\'7s(1E=\'+a.D.1E*1Y+\')\')}}if(a.D.6i){A.X.18.2H(a.D.6i);A.X.18.I(0).6M.Y.11=\'1k\'}if(a.D.4c)a.D.4c.1x(a,[d,a.D.22.x,a.D.22.y]);if(A.1s&&A.1s.7p>0){A.1s.ck(a)}if(a.D.3L==H){b.11=\'1k\'}G H},ah:C(a){if(a.D.2e.1F==8t){if(a.D.2e==\'7X\'){a.D.1Z=A.1U({x:0,y:0},A.12.2f(a.2S));F b=A.12.6b(a.2S,14);a.D.1Z.w=a.D.1Z.1D-b.l-b.r;a.D.1Z.h=a.D.1Z.hb-b.t-b.b}L if(a.D.2e==\'1c\'){F c=A.12.a5();a.D.1Z={x:0,y:0,w:c.w,h:c.h}}}L if(a.D.2e.1F==6h){a.D.1Z={x:R(a.D.2e[0])||0,y:R(a.D.2e[1])||0,w:R(a.D.2e[2])||0,h:R(a.D.2e[3])||0}}a.D.1Z.dx=a.D.1Z.x-a.D.1w.x;a.D.1Z.dy=a.D.1Z.y-a.D.1w.y},8r:C(a){if(a.D.7V||a.D.2e==\'7X\'){A(\'23\',1c).1L(A.X.18.I(0))}A.X.18.58().2x().E(\'1E\',1);if(1P.6j){A.X.18.E(\'4X\',\'7s(1E=1Y)\')}},8I:C(e){A(1c).3h(\'3t\',A.X.aE).3h(\'5n\',A.X.8I);if(A.X.1g==P){G}F a=A.X.1g;A.X.1g=P;if(a.D.6g==H){G H}if(a.D.3I==14){A(a).E(\'T\',a.D.49)}F b=a.Y;if(a.4P){A.X.18.E(\'7z\',\'7g\')}if(a.D.6i){A.X.18.3S(a.D.6i)}if(a.D.5B==H){if(a.D.fx>0){if(!a.D.2g||a.D.2g==\'3Z\'){F x=W A.fx(a,{1H:a.D.fx},\'M\');x.1G(a.D.22.x,a.D.7i)}if(!a.D.2g||a.D.2g==\'3K\'){F y=W A.fx(a,{1H:a.D.fx},\'O\');y.1G(a.D.22.y,a.D.7k)}}L{if(!a.D.2g||a.D.2g==\'3Z\')a.Y.M=a.D.7i+\'Q\';if(!a.D.2g||a.D.2g==\'3K\')a.Y.O=a.D.7k+\'Q\'}A.X.8r(a);if(a.D.3L==H){A(a).E(\'11\',a.D.6o)}}L if(a.D.fx>0){a.D.8w=14;F c=H;if(A.1s&&A.1p&&a.D.3I){c=A.12.3a(A.1p.18.I(0))}A.X.18.4S({M:c?c.x:a.D.1w.x,O:c?c.y:a.D.1w.y},a.D.fx,C(){a.D.8w=H;if(a.D.3L==H){a.Y.11=a.D.6o}A.X.8r(a)})}L{A.X.8r(a);if(a.D.3L==H){A(a).E(\'11\',a.D.6o)}}if(A.1s&&A.1s.7p>0){A.1s.c8(a)}if(A.1p&&a.D.3I){A.1p.c7(a)}if(a.D.2I&&(a.D.7i!=a.D.22.x||a.D.7k!=a.D.22.y)){a.D.2I.1x(a,a.D.aa||[0,0,a.D.7i,a.D.7k])}if(a.D.3C)a.D.3C.1x(a);G H},a9:C(x,y,a,b){if(a!=0)a=R((a+(B.D.gx*a/Z.3B(a))/2)/B.D.gx)*B.D.gx;if(b!=0)b=R((b+(B.D.gy*b/Z.3B(b))/2)/B.D.gy)*B.D.gy;G{dx:a,dy:b,x:0,y:0}},ae:C(x,y,a,b){a=Z.3k(Z.3g(a,B.D.1Z.dx),B.D.1Z.w+B.D.1Z.dx-B.D.1w.1D);b=Z.3k(Z.3g(b,B.D.1Z.dy),B.D.1Z.h+B.D.1Z.dy-B.D.1w.hb);G{dx:a,dy:b,x:0,y:0}},aE:C(e){if(A.X.1g==P||A.X.1g.D.8w==14){G}F a=A.X.1g;a.D.4d=A.12.3W(e);if(a.D.6g==H){3J=Z.cB(Z.5j(a.D.1A.x-a.D.4d.x,2)+Z.5j(a.D.1A.y-a.D.4d.y,2));if(3J0){A.1s.8n(a)}G H},2l:C(o){if(!A.X.18){A(\'23\',1c).1L(\'<1W id="bX">\');A.X.18=A(\'#bX\');F c=A.X.18.I(0);F d=c.Y;d.T=\'1J\';d.11=\'1k\';d.7z=\'7g\';d.bV=\'1k\';d.2N=\'2B\';if(1P.6j){c.aI="bU"}L{d.eZ=\'1k\';d.cH=\'1k\';d.cJ=\'1k\'}}if(!o){o={}}G B.1y(C(){if(B.8L||!A.12)G;if(1P.6j){B.eX=C(){G H};B.eW=C(){G H}}F a=B;F b=o.3c?A(B).eV(o.3c):A(B);if(A.2R.46){b.1y(C(){B.aI="bU"})}L{b.E(\'-eU-6f-7Q\',\'1k\');b.E(\'6f-7Q\',\'1k\');b.E(\'-eT-6f-7Q\',\'1k\')}B.D={cM:b,5B:o.5B?14:H,3L:o.3L?14:H,3I:o.3I?o.3I:H,4P:o.4P?o.4P:H,7V:o.7V?o.7V:H,3j:o.3j?R(o.3j)||0:H,1E:o.1E?2c(o.1E):H,fx:R(o.fx)||P,5z:o.5z?o.5z:H,4V:{},1A:{},4c:o.4c&&o.4c.1F==2w?o.4c:H,3C:o.3C&&o.3C.1F==2w?o.3C:H,2I:o.2I&&o.2I.1F==2w?o.2I:H,2g:/3K|3Z/.3M(o.2g)?o.2g:H,5D:o.5D?R(o.5D)||0:0,2M:o.2M?o.2M:H,ar:o.ar?14:H,6i:o.6i||H};if(o.4V&&o.4V.1F==2w)B.D.4V.6f=o.4V;if(o.4h&&o.4h.1F==2w)B.D.4h=o.4h;if(o.2e&&((o.2e.1F==8t&&(o.2e==\'7X\'||o.2e==\'1c\'))||(o.2e.1F==6h&&o.2e.1b==4))){B.D.2e=o.2e}if(o.2C){B.D.2C=o.2C}if(o.5y){if(28 o.5y==\'eO\'){B.D.gx=R(o.5y)||1;B.D.gy=R(o.5y)||1}L if(o.5y.1b==2){B.D.gx=R(o.5y[0])||1;B.D.gy=R(o.5y[1])||1}}if(o.3n&&o.3n.1F==2w){B.D.3n=o.3n}B.8L=14;b.1y(C(){B.3H=a});b.1C(\'4R\',A.X.aM)})}};A.fn.1U({8j:A.X.4v,6r:A.X.2l});A.1s={bP:C(a,b,c,d){G a<=A.X.1g.D.2n&&(a+c)>=(A.X.1g.D.2n+A.X.1g.D.1w.w)&&b<=A.X.1g.D.2j&&(b+d)>=(A.X.1g.D.2j+A.X.1g.D.1w.h)?14:H},9S:C(a,b,c,d){G!(a>(A.X.1g.D.2n+A.X.1g.D.1w.w)||(a+c)(A.X.1g.D.2j+A.X.1g.D.1w.h)||(b+d)A.X.1g.D.4d.x&&bA.X.1g.D.4d.y?14:H},4T:H,3z:{},7p:0,3p:{},ck:C(a){if(A.X.1g==P){G}F i;A.1s.3z={};F b=H;1V(i in A.1s.3p){if(A.1s.3p[i]!=P){F c=A.1s.3p[i].I(0);if(A(A.X.1g).is(\'.\'+c.1f.a)){if(c.1f.m==H){c.1f.p=A.1U(A.12.6x(c),A.12.6w(c));c.1f.m=14}if(c.1f.ac){A.1s.3p[i].2H(c.1f.ac)}A.1s.3z[i]=A.1s.3p[i];if(A.1p&&c.1f.s&&A.X.1g.D.3I){c.1f.el=A(\'.\'+c.1f.a,c);a.Y.11=\'1k\';A.1p.bM(c);c.1f.9P=A.1p.8g(A.1m(c,\'id\')).6A;a.Y.11=a.D.6o;b=14}if(c.1f.9O){c.1f.9O.1x(A.1s.3p[i].I(0),[A.X.1g])}}}}if(b){A.1p.2b()}},eF:C(){A.1s.3z={};1V(i in A.1s.3p){if(A.1s.3p[i]!=P){F a=A.1s.3p[i].I(0);if(A(A.X.1g).is(\'.\'+a.1f.a)){a.1f.p=A.1U(A.12.6x(a),A.12.6w(a));if(a.1f.ac){A.1s.3p[i].2H(a.1f.ac)}A.1s.3z[i]=A.1s.3p[i];if(A.1p&&a.1f.s&&A.X.1g.D.3I){a.1f.el=A(\'.\'+a.1f.a,a);bJ.Y.11=\'1k\';A.1p.bM(a);bJ.Y.11=bJ.D.6o}}}}},8n:C(e){if(A.X.1g==P){G}A.1s.4T=H;F i;F a=H;F b=0;1V(i in A.1s.3z){F c=A.1s.3z[i].I(0);if(A.1s.4T==H&&A.1s[c.1f.t](c.1f.p.x,c.1f.p.y,c.1f.p.1D,c.1f.p.hb)){if(c.1f.hc&&c.1f.h==H){A.1s.3z[i].2H(c.1f.hc)}if(c.1f.h==H&&c.1f.76){a=14}c.1f.h=14;A.1s.4T=c;if(A.1p&&c.1f.s&&A.X.1g.D.3I){A.1p.18.I(0).2Z=c.1f.eC;A.1p.8n(c)}b++}L if(c.1f.h==14){if(c.1f.6C){c.1f.6C.1x(c,[e,A.X.18.I(0).6M,c.1f.fx])}if(c.1f.hc){A.1s.3z[i].3S(c.1f.hc)}c.1f.h=H}}if(A.1p&&!A.1s.4T&&A.X.1g.3I){A.1p.18.I(0).Y.11=\'1k\'}if(a){A.1s.4T.1f.76.1x(A.1s.4T,[e,A.X.18.I(0).6M])}},c8:C(e){F i;1V(i in A.1s.3z){F a=A.1s.3z[i].I(0);if(a.1f.ac){A.1s.3z[i].3S(a.1f.ac)}if(a.1f.hc){A.1s.3z[i].3S(a.1f.hc)}if(a.1f.s){A.1p.73[A.1p.73.1b]=i}if(a.1f.9I&&a.1f.h==14){a.1f.h=H;a.1f.9I.1x(a,[e,a.1f.fx])}a.1f.m=H;a.1f.h=H}A.1s.3z={}},4v:C(){G B.1y(C(){if(B.8S){if(B.1f.s){id=A.1m(B,\'id\');A.1p.54[id]=P;A(\'.\'+B.1f.a,B).8j()}A.1s.3p[\'d\'+B.bG]=P;B.8S=H;B.f=P}})},2l:C(o){G B.1y(C(){if(B.8S==14||!o.3r||!A.12||!A.X){G}B.1f={a:o.3r,ac:o.9F||H,hc:o.8X||H,eC:o.4G||H,9I:o.je||o.9I||H,76:o.76||o.ev||H,6C:o.6C||o.er||H,9O:o.9O||H,t:o.5T&&(o.5T==\'bP\'||o.5T==\'9S\')?o.5T:\'1A\',fx:o.fx?o.fx:H,m:H,h:H};if(o.bC==14&&A.1p){id=A.1m(B,\'id\');A.1p.54[id]=B.1f.a;B.1f.s=14;if(o.2I){B.1f.2I=o.2I;B.1f.9P=A.1p.8g(id).6A}}B.8S=14;B.bG=R(Z.63()*aW);A.1s.3p[\'d\'+B.bG]=A(B);A.1s.7p++})}};A.fn.1U({ei:A.1s.4v,ee:A.1s.2l});A.jd=A.1s.eF;A.3l={18:P,89:C(){3D=B.2m;if(!3D)G;Y={eb:A(B).E(\'eb\')||\'\',4a:A(B).E(\'4a\')||\'\',87:A(B).E(\'87\')||\'\',e9:A(B).E(\'e9\')||\'\',e8:A(B).E(\'e8\')||\'\',e7:A(B).E(\'e7\')||\'\',bx:A(B).E(\'bx\')||\'\',e6:A(B).E(\'e6\')||\'\'};A.3l.18.E(Y);3i=A.3l.e5(3D);3i=3i.48(W bw("\\\\n","g"),"
    ");A.3l.18.3i(\'j6\');b3=A.3l.18.I(0).3P;A.3l.18.3i(3i);V=A.3l.18.I(0).3P+b3;if(B.66.65&&V>B.66.65[0]){V=B.66.65[0]}B.Y.V=V+\'Q\';if(B.4D==\'bs\'){S=A.3l.18.I(0).5r+b3;if(B.66.65&&S>B.66.65[1]){S=B.66.65[1]}B.Y.S=S+\'Q\'}},e5:C(a){bq={\'&\':\'&j1;\',\'<\':\'&j0;\',\'>\':\'>\',\'"\':\'&iZ;\'};1V(i in bq){a=a.48(W bw(i,\'g\'),bq[i])}G a},2l:C(a){if(A.3l.18==P){A(\'23\',1c).1L(\'<1W id="dX" Y="T: 1J; O: 0; M: 0; 2W: 2B;">\');A.3l.18=A(\'#dX\')}G B.1y(C(){if(/bs|aV/.3M(B.4D)){if(B.4D==\'aV\'){dT=B.4Z(\'1K\');if(!/3D|iW/.3M(dT)){G}}if(a&&(a.1F==bm||(a.1F==6h&&a.1b==2))){if(a.1F==bm)a=[a,a];L{a[0]=R(a[0])||7n;a[1]=R(a[1])||7n}B.66={65:a}}A(B).4W(A.3l.89).5Q(A.3l.89).cV(A.3l.89);A.3l.89.1x(B)}})}};A.fn.iU=A.3l.2l;A.fn.1U({c3:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.5l(B,a,b,\'4l\',c)})},dP:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.5l(B,a,b,\'41\',c)})},iQ:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.5l(B,a,b,\'dG\',c)})},iM:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.5l(B,a,b,\'M\',c)})},iL:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.5l(B,a,b,\'2D\',c)})},iK:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.5l(B,a,b,\'dF\',c)})}});A.fx.5l=C(e,a,b,c,d){if(!A.4n(e)){A.2z(e,\'1j\');G H}F z=B;z.el=A(e);z.1N=A.12.2f(e);z.1e=28 b==\'4B\'?b:d||P;if(!e.4f)e.4f=z.el.E(\'11\');if(c==\'dG\'){c=z.el.E(\'11\')==\'1k\'?\'41\':\'4l\'}L if(c==\'dF\'){c=z.el.E(\'11\')==\'1k\'?\'2D\':\'M\'}z.el.1S();z.1l=a;z.29=28 b==\'C\'?b:P;z.fx=A.fx.9u(e);z.6T=c;z.1T=C(){if(z.29&&z.29.1F==2w){z.29.1x(z.el.I(0))}if(z.6T==\'41\'||z.6T==\'2D\'){z.el.E(\'11\',z.el.I(0).4f==\'1k\'?\'2v\':z.el.I(0).4f)}L{z.el.2x()}A.fx.9n(z.fx.2Y.I(0),z.fx.U);A.2z(z.el.I(0),\'1j\')};2X(z.6T){19\'4l\':5q=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,z.1T),\'S\');5q.1G(z.fx.U.1o.hb,0);1n;19\'41\':z.fx.2Y.E(\'S\',\'9e\');z.el.1S();5q=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,z.1T),\'S\');5q.1G(0,z.fx.U.1o.hb);1n;19\'M\':5q=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,z.1T),\'V\');5q.1G(z.fx.U.1o.1D,0);1n;19\'2D\':z.fx.2Y.E(\'V\',\'9e\');z.el.1S();5q=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,z.1T),\'V\');5q.1G(0,z.fx.U.1o.1D);1n}};A.fn.iA=C(a,b){G B.1r(\'1j\',C(){if(!A.4n(B)){A.2z(B,\'1j\');G H}F e=W A.fx.eu(B,a,b);e.bE()})};A.fx.eu=C(e,a,b){F z=B;z.el=A(e);z.el.1S();z.29=b;z.8e=R(a)||40;z.U={};z.U.T=z.el.E(\'T\');z.U.O=R(z.el.E(\'O\'))||0;z.U.M=R(z.el.E(\'M\'))||0;if(z.U.T!=\'2i\'&&z.U.T!=\'1J\'){z.el.E(\'T\',\'2i\')}z.74=5;z.52=1;z.bE=C(){z.52++;z.e=W A.fx(z.el.I(0),{1H:io,1T:C(){z.e=W A.fx(z.el.I(0),{1H:80,1T:C(){z.8e=R(z.8e/2);if(z.52<=z.74)z.bE();L{z.el.E(\'T\',z.U.T).E(\'O\',z.U.O+\'Q\').E(\'M\',z.U.M+\'Q\');A.2z(z.el.I(0),\'1j\');if(z.29&&z.29.1F==2w){z.29.1x(z.el.I(0))}}}},\'O\');z.e.1G(z.U.O-z.8e,z.U.O)}},\'O\');z.e.1G(z.U.O,z.U.O-z.8e)}};A.fn.1U({im:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'41\',\'3U\',c)})},ik:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'41\',\'in\',c)})},ii:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'41\',\'3E\',c)})},ig:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'4l\',\'3U\',c)})},ie:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'4l\',\'in\',c)})},ic:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'4l\',\'3E\',c)})},ib:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'M\',\'3U\',c)})},ia:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'M\',\'in\',c)})},i9:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'M\',\'3E\',c)})},i8:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'2D\',\'3U\',c)})},i7:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'2D\',\'in\',c)})},i6:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.3Y(B,a,b,\'2D\',\'3E\',c)})}});A.fx.3Y=C(e,a,b,c,d,f){if(!A.4n(e)){A.2z(e,\'1j\');G H}F z=B;z.el=A(e);z.1e=28 b==\'4B\'?b:f||P;z.U={};z.U.T=z.el.E(\'T\');z.U.O=z.el.E(\'O\');z.U.M=z.el.E(\'M\');if(!e.4f)e.4f=z.el.E(\'11\');if(d==\'3E\'){d=z.el.E(\'11\')==\'1k\'?\'in\':\'3U\'}z.el.1S();if(z.U.T!=\'2i\'&&z.U.T!=\'1J\'){z.el.E(\'T\',\'2i\')}z.1K=d;b=28 b==\'C\'?b:P;7N=1;2X(c){19\'4l\':z.e=W A.fx(z.el.I(0),A.1l(a-15,z.1e,b),\'O\');z.5x=2c(z.U.O)||0;z.9i=z.dt;7N=-1;1n;19\'41\':z.e=W A.fx(z.el.I(0),A.1l(a-15,z.1e,b),\'O\');z.5x=2c(z.U.O)||0;z.9i=z.dt;1n;19\'2D\':z.e=W A.fx(z.el.I(0),A.1l(a-15,z.1e,b),\'M\');z.5x=2c(z.U.M)||0;z.9i=z.ds;1n;19\'M\':z.e=W A.fx(z.el.I(0),A.1l(a-15,z.1e,b),\'M\');z.5x=2c(z.U.M)||0;z.9i=z.ds;7N=-1;1n}z.e2=W A.fx(z.el.I(0),A.1l(a,z.1e,C(){z.el.E(z.U);if(z.1K==\'3U\'){z.el.E(\'11\',\'1k\')}L z.el.E(\'11\',z.el.I(0).4f==\'1k\'?\'2v\':z.el.I(0).4f);A.2z(z.el.I(0),\'1j\')}),\'1E\');if(d==\'in\'){z.e.1G(z.5x+1Y*7N,z.5x);z.e2.1G(0,1)}L{z.e.1G(z.5x,z.5x+1Y*7N);z.e2.1G(1,0)}};A.fn.1U({i5:C(a,b,c,d){G B.1r(\'1j\',C(){W A.fx.9h(B,a,b,c,\'dq\',d)})},i4:C(a,b,c,d){G B.1r(\'1j\',C(){W A.fx.9h(B,a,b,c,\'9g\',d)})},i3:C(a,b,c,d){G B.1r(\'1j\',C(){W A.fx.9h(B,a,b,c,\'3E\',d)})}});A.fx.9h=C(e,a,b,c,d,f){if(!A.4n(e)){A.2z(e,\'1j\');G H}F z=B;z.el=A(e);z.1e=28 c==\'4B\'?c:f||P;z.29=28 c==\'C\'?c:P;if(d==\'3E\'){d=z.el.E(\'11\')==\'1k\'?\'9g\':\'dq\'}z.1l=a;z.S=b&&b.1F==bm?b:20;z.fx=A.fx.9u(e);z.1K=d;z.1T=C(){if(z.29&&z.29.1F==2w){z.29.1x(z.el.I(0))}if(z.1K==\'9g\'){z.el.1S()}L{z.el.2x()}A.fx.9n(z.fx.2Y.I(0),z.fx.U);A.2z(z.el.I(0),\'1j\')};if(z.1K==\'9g\'){z.el.1S();z.fx.2Y.E(\'S\',z.S+\'Q\').E(\'V\',\'9e\');z.ef=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,C(){z.ef=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,z.1T),\'S\');z.ef.1G(z.S,z.fx.U.1o.hb)}),\'V\');z.ef.1G(0,z.fx.U.1o.1D)}L{z.ef=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,C(){z.ef=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e,z.1T),\'V\');z.ef.1G(z.fx.U.1o.1D,0)}),\'S\');z.ef.1G(z.fx.U.1o.hb,z.S)}};A.fn.i2=C(c,d,e,f){G B.1r(\'dp\',C(){B.6Q=A(B).1m("Y")||\'\';f=28 e==\'4B\'?e:f||P;e=28 e==\'C\'?e:P;F a=A(B).E(\'6P\');F b=B.2S;6k(a==\'b7\'&&b){a=A(b).E(\'6P\');b=b.2S}A(B).E(\'6P\',d);if(28 B.6Q==\'7M\')B.6Q=B.6Q["9d"];A(B).4S({\'6P\':a},c,f,C(){A.2z(B,\'dp\');if(28 A(B).1m("Y")==\'7M\'){A(B).1m("Y")["9d"]="";A(B).1m("Y")["9d"]=B.6Q}L{A(B).1m("Y",B.6Q)}if(e)e.1x(B)})})};A.4n=C(e){if(/^i1$|^i0$|^hZ$|^5W$|^hY$|^hX$|^hW$|^hV$|^hU$|^23$|^hT$|^hS$|^hR$|^hQ$|^hP$|^hO$|^hN$/i.3M(e.98))G H;L G 14};A.fx.9n=C(e,a){F c=e.6M;F b=c.Y;b.T=a.T;b.4M=a.3s.t;b.4K=a.3s.l;b.4L=a.3s.b;b.53=a.3s.r;b.O=a.O+\'Q\';b.M=a.M+\'Q\';e.2S.dn(c,e);e.2S.hM(e)};A.fx.9u=C(e){if(!A.4n(e))G H;F t=A(e);F a=e.Y;F b=H;if(t.E(\'11\')==\'1k\'){95=t.E(\'2W\');t.E(\'2W\',\'2B\').1S();b=14}F c={};c.T=t.E(\'T\');c.1o=A.12.2f(e);c.3s=A.12.b2(e);F d=e.4u?e.4u.dk:t.E(\'hK\');c.O=R(t.E(\'O\'))||0;c.M=R(t.E(\'M\'))||0;F f=\'hJ\'+R(Z.63()*aW);F g=1c.3x(/^3O$|^br$|^hI$|^hr$|^7Q$|^hH$|^7M$|^3q$|^hF$|^hE$|^hC$|^90$|^dl$|^hB$/i.3M(e.98)?\'1W\':e.98);A.1m(g,\'id\',f);F h=A(g).2H(\'hA\');F i=g.Y;F j=0;F k=0;if(c.T==\'2i\'||c.T==\'1J\'){j=c.O;k=c.M}i.O=j+\'Q\';i.M=k+\'Q\';i.T=c.T!=\'2i\'&&c.T!=\'1J\'?\'2i\':c.T;i.S=c.1o.hb+\'Q\';i.V=c.1o.1D+\'Q\';i.4M=c.3s.t;i.53=c.3s.r;i.4L=c.3s.b;i.4K=c.3s.l;i.2N=\'2B\';if(A.2R.46){i.dk=d}L{i.hz=d}if(A.2R=="46"){a.4X="7s(1E="+0.dg*1Y+")"}a.1E=0.dg;e.2S.dn(g,e);g.hy(e);a.4M=\'2G\';a.53=\'2G\';a.4L=\'2G\';a.4K=\'2G\';a.T=\'1J\';a.bV=\'1k\';a.O=\'2G\';a.M=\'2G\';if(b){t.2x();a.2W=95}G{U:c,2Y:A(g)}};A.fx.7H={hx:[0,1O,1O],hw:[dd,1O,1O],hv:[db,db,hu],hs:[0,0,0],hq:[0,0,1O],hp:[d6,42,42],hn:[0,1O,1O],hm:[0,0,6N],hl:[0,6N,6N],hk:[aX,aX,aX],hi:[0,1Y,0],hg:[hf,he,cZ],hd:[6N,0,6N],ha:[85,cZ,47],h7:[1O,cY,0],h6:[h5,50,h4],h3:[6N,0,0],h2:[h1,cX,h0],gZ:[gY,0,8U],gX:[1O,0,1O],gW:[1O,gU,0],gT:[0,67,0],gS:[75,0,gQ],gP:[dd,cU,cY],gO:[gL,gK,cU],gI:[cT,1O,1O],gH:[cS,gG,cS],gF:[8U,8U,8U],gD:[1O,gC,gB],gA:[1O,1O,cT],gw:[0,1O,0],gv:[1O,0,1O],gu:[67,0,0],gs:[0,0,67],gr:[67,67,0],gq:[1O,d6,0],gp:[1O,8R,gn],gm:[67,0,67],gl:[1O,0,0],gk:[8R,8R,8R],gj:[1O,1O,1O],gi:[1O,1O,0]};A.fx.5L=C(a,b){if(A.fx.7H[a])G{r:A.fx.7H[a][0],g:A.fx.7H[a][1],b:A.fx.7H[a][2]};L if(2L=/^6v\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*\\)$/.8Q(a))G{r:R(2L[1]),g:R(2L[2]),b:R(2L[3])};L if(2L=/6v\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*\\)$/.8Q(a))G{r:2c(2L[1])*2.55,g:2c(2L[2])*2.55,b:2c(2L[3])*2.55};L if(2L=/^#([a-fA-6t-9])([a-fA-6t-9])([a-fA-6t-9])$/.8Q(a))G{r:R("6s"+2L[1]+2L[1]),g:R("6s"+2L[2]+2L[2]),b:R("6s"+2L[3]+2L[3])};L if(2L=/^#([a-fA-6t-9]{2})([a-fA-6t-9]{2})([a-fA-6t-9]{2})$/.8Q(a))G{r:R("6s"+2L[1]),g:R("6s"+2L[2]),b:R("6s"+2L[3])};L G b==14?H:{r:1O,g:1O,b:1O}};A.fx.cQ={5d:1,4y:1,5i:1,4x:1,4e:1,4a:1,S:1,M:1,bx:1,gh:1,4L:1,4K:1,53:1,4M:1,7y:1,5R:1,7x:1,8O:1,1E:1,ge:1,gc:1,4Q:1,4F:1,5g:1,5b:1,2D:1,gb:1,O:1,V:1,3j:1};A.fx.cN={6P:1,ga:1,g9:1,g8:1,g7:1,g6:1,g5:1};A.fx.7v=[\'g4\',\'g3\',\'g2\',\'g1\'];A.fx.aL={\'aK\':[\'2u\',\'cK\'],\'8E\':[\'2u\',\'aH\'],\'5X\':[\'5X\',\'\'],\'7E\':[\'7E\',\'\']};A.fn.1U({4S:C(b,c,d,f){G B.1r(C(){F a=A.1l(c,d,f);F e=W A.cI(B,a,b)})},aG:C(b,c){G B.1r(C(){F a=A.1l(b,c);F e=W A.aG(B,a)})},7w:C(a){G B.1y(C(){if(B.5e)A.aF(B,a)})},fZ:C(a){G B.1y(C(){if(B.5e)A.aF(B,a);if(B.1r&&B.1r[\'fx\'])B.1r.fx=[]})}});A.1U({aG:C(a,b){F z=B,5f;z.3f=C(){if(A.cF(b.1T))b.1T.1x(a)};z.2A=5Y(C(){z.3f()},b.1H);a.5e=z},1e:{b1:C(p,n,a,b,c){G((-Z.51(p*Z.2F)/2)+0.5)*b+a}},cI:C(f,g,h){F z=B,5f;F y=f.Y;F k=A.E(f,"2N");F l=A.E(f,"11");F o={};z.9a=(W 6p()).6y();g.1e=g.1e&&A.1e[g.1e]?g.1e:\'b1\';z.8H=C(a,b){if(A.fx.cQ[a]){if(b==\'1S\'||b==\'2x\'||b==\'3E\'){if(!f.5I)f.5I={};F r=2c(A.5S(f,a));f.5I[a]=r&&r>-aW?r:(2c(A.E(f,a))||0);b=b==\'3E\'?(l==\'1k\'?\'1S\':\'2x\'):b;g[b]=14;o[a]=b==\'1S\'?[0,f.5I[a]]:[f.5I[a],0];if(a!=\'1E\')y[a]=o[a][0]+(a!=\'3j\'&&a!=\'87\'?\'Q\':\'\');L A.1m(y,"1E",o[a][0])}L{o[a]=[2c(A.5S(f,a)),2c(b)||0]}}L if(A.fx.cN[a])o[a]=[A.fx.5L(A.5S(f,a)),A.fx.5L(b)];L if(/^5X$|7E$|2u$|8E$|aK$/i.3M(a)){F m=b.48(/\\s+/g,\' \').48(/6v\\s*\\(\\s*/g,\'6v(\').48(/\\s*,\\s*/g,\',\').48(/\\s*\\)/g,\')\').aD(/([^\\s]+)/g);2X(a){19\'5X\':19\'7E\':19\'aK\':19\'8E\':m[3]=m[3]||m[1]||m[0];m[2]=m[2]||m[0];m[1]=m[1]||m[0];1V(F i=0;ig.1H+z.9a){5h(z.2A);z.2A=P;1V(p in o){if(p=="1E")A.1m(y,"1E",o[p][1]);L if(28 o[p][1]==\'7M\')y[p]=\'6v(\'+o[p][1].r+\',\'+o[p][1].g+\',\'+o[p][1].b+\')\';L y[p]=o[p][1]+(p!=\'3j\'&&p!=\'87\'?\'Q\':\'\')}if(g.2x||g.1S)1V(F p in f.5I)if(p=="1E")A.1m(y,p,f.5I[p]);L y[p]="";y.11=g.2x?\'1k\':(l!=\'1k\'?l:\'2v\');y.2N=k;f.5e=P;if(A.cF(g.1T))g.1T.1x(f)}L{F n=t-B.9a;F a=n/g.1H;1V(p in o){if(28 o[p][1]==\'7M\'){y[p]=\'6v(\'+R(A.1e[g.1e](a,n,o[p][0].r,(o[p][1].r-o[p][0].r),g.1H))+\',\'+R(A.1e[g.1e](a,n,o[p][0].g,(o[p][1].g-o[p][0].g),g.1H))+\',\'+R(A.1e[g.1e](a,n,o[p][0].b,(o[p][1].b-o[p][0].b),g.1H))+\')\'}L{F b=A.1e[g.1e](a,n,o[p][0],(o[p][1]-o[p][0]),g.1H);if(p=="1E")A.1m(y,"1E",b);L y[p]=b+(p!=\'3j\'&&p!=\'87\'?\'Q\':\'\')}}}};z.2A=5Y(C(){z.3f()},13);f.5e=z},aF:C(a,b){if(b)a.5e.9a-=fJ;L{1P.5h(a.5e.2A);a.5e=P;A.2z(a,"fx")}}});A.ax=C(a){F b={};if(28 a==\'4B\'){a=a.5u().6W(\';\');1V(F i=0;i0){z.cy=1o[i];z.4a=2c(z.U.4a)}if(z.U.4x.3o(1o[i])>0){z.cx=1o[i];z.aq=2c(z.U.4x)||0}if(z.U.5i.3o(1o[i])>0){z.cw=1o[i];z.ap=2c(z.U.5i)||0}if(z.U.5d.3o(1o[i])>0){z.cv=1o[i];z.ao=2c(z.U.5d)||0}if(z.U.4y.3o(1o[i])>0){z.cu=1o[i];z.an=2c(z.U.4y)||0}if(z.U.5b.3o(1o[i])>0){z.ct=1o[i];z.am=2c(z.U.5b)||0}if(z.U.5g.3o(1o[i])>0){z.cr=1o[i];z.al=2c(z.U.5g)||0}if(z.U.4Q.3o(1o[i])>0){z.cq=1o[i];z.ak=2c(z.U.4Q)||0}if(z.U.4F.3o(1o[i])>0){z.cp=1o[i];z.aj=2c(z.U.4F)||0}}if(z.U.T!=\'2i\'&&z.U.T!=\'1J\'){z.el.E(\'T\',\'2i\')}z.el.E(\'2N\',\'2B\');z.1K=m;2X(z.1K){19\'cz\':z.3V=z.O+z.26.h/2;z.4H=z.O;z.3Q=z.M+z.26.w/2;z.4r=z.M;1n;19\'as\':z.4H=z.O+z.26.h/2;z.3V=z.O;z.4r=z.M+z.26.w/2;z.3Q=z.M;1n;19\'5c\':z.4H=z.O-z.26.h/4;z.3V=z.O;z.4r=z.M-z.26.w/4;z.3Q=z.M;1n}z.ai=H;z.t=(W 6p).6y();z.4i=C(){5h(z.2A);z.2A=P};z.3f=C(){if(z.ai==H){z.el.1S();z.ai=14}F t=(W 6p).6y();F n=t-z.t;F p=n/z.1H;if(t>=z.1H+z.t){97(C(){o=1;if(z.1K){t=z.4H;l=z.4r;if(z.1K==\'5c\')o=0}z.ag(z.3v,l,t,14,o)},13);z.4i()}L{o=1;if(!A.1e||!A.1e[z.1e]){s=((-Z.51(p*Z.2F)/2)+0.5)*(z.3v-z.6m)+z.6m}L{s=A.1e[z.1e](p,n,z.6m,(z.3v-z.6m),z.1H)}if(z.1K){if(!A.1e||!A.1e[z.1e]){t=((-Z.51(p*Z.2F)/2)+0.5)*(z.4H-z.3V)+z.3V;l=((-Z.51(p*Z.2F)/2)+0.5)*(z.4r-z.3Q)+z.3Q;if(z.1K==\'5c\')o=((-Z.51(p*Z.2F)/2)+0.5)*(-0.9B)+0.9B}L{t=A.1e[z.1e](p,n,z.3V,(z.4H-z.3V),z.1H);l=A.1e[z.1e](p,n,z.3Q,(z.4r-z.3Q),z.1H);if(z.1K==\'5c\')o=A.1e[z.1e](p,n,0.9B,-0.9B,z.1H)}}z.ag(s,l,t,H,o)}};z.2A=5Y(C(){z.3f()},13);z.ag=C(a,b,c,d,e){z.el.E(\'S\',z.S*a/1Y+\'Q\').E(\'V\',z.V*a/1Y+\'Q\').E(\'M\',b+\'Q\').E(\'O\',c+\'Q\').E(\'4a\',z.4a*a/1Y+z.cy);if(z.aq)z.el.E(\'4x\',z.aq*a/1Y+z.cx);if(z.ap)z.el.E(\'5i\',z.ap*a/1Y+z.cw);if(z.ao)z.el.E(\'5d\',z.ao*a/1Y+z.cv);if(z.an)z.el.E(\'4y\',z.an*a/1Y+z.cu);if(z.am)z.el.E(\'5b\',z.am*a/1Y+z.ct);if(z.al)z.el.E(\'5g\',z.al*a/1Y+z.cr);if(z.ak)z.el.E(\'4Q\',z.ak*a/1Y+z.cq);if(z.aj)z.el.E(\'4F\',z.aj*a/1Y+z.cp);if(z.1K==\'5c\'){if(1P.6j)z.el.I(0).Y.4X="7s(1E="+e*1Y+")";z.el.I(0).Y.1E=e}if(d){if(z.bL){z.el.E(z.U)}if(z.1K==\'as\'||z.1K==\'5c\'){z.el.E(\'11\',\'1k\');if(z.1K==\'5c\'){if(1P.6j)z.el.I(0).Y.4X="7s(1E="+1Y+")";z.el.I(0).Y.1E=1}}L z.el.E(\'11\',\'2v\');if(z.29)z.29.1x(z.el.I(0));A.2z(z.el.I(0),\'1j\')}}};A.fn.1U({9A:C(a,b,c){o=A.1l(a);G B.1r(\'1j\',C(){W A.fx.9A(B,o,b,c)})},ft:C(a,b,c){G B.1y(C(){A(\'a[@2U*="#"]\',B).4U(C(e){co=B.2U.6W(\'#\');A(\'#\'+co[1]).9A(a,b,c);G H})})}});A.fx.9A=C(e,o,a,b){F z=B;z.o=o;z.e=e;z.2g=/cn|cm/.3M(a)?a:H;z.1e=b;p=A.12.3a(e);s=A.12.5O();z.4i=C(){5h(z.2A);z.2A=P;A.2z(z.e,\'1j\')};z.t=(W 6p).6y();s.h=s.h>s.ih?(s.h-s.ih):s.h;s.w=s.w>s.iw?(s.w-s.iw):s.w;z.4H=p.y>s.h?s.h:p.y;z.4r=p.x>s.w?s.w:p.x;z.3V=s.t;z.3Q=s.l;z.3f=C(){F t=(W 6p).6y();F n=t-z.t;F p=n/z.o.1H;if(t>=z.o.1H+z.t){z.4i();97(C(){z.ab(z.4H,z.4r)},13)}L{if(!z.2g||z.2g==\'cn\'){if(!A.1e||!A.1e[z.1e]){8v=((-Z.51(p*Z.2F)/2)+0.5)*(z.4H-z.3V)+z.3V}L{8v=A.1e[z.1e](p,n,z.3V,(z.4H-z.3V),z.o.1H)}}L{8v=z.3V}if(!z.2g||z.2g==\'cm\'){if(!A.1e||!A.1e[z.1e]){8u=((-Z.51(p*Z.2F)/2)+0.5)*(z.4r-z.3Q)+z.3Q}L{8u=A.1e[z.1e](p,n,z.3Q,(z.4r-z.3Q),z.o.1H)}}L{8u=z.3Q}z.ab(8v,8u)}};z.ab=C(t,l){1P.fs(l,t)};z.2A=5Y(C(){z.3f()},13)};A.fn.a8=C(a,b){G B.1r(\'1j\',C(){if(!A.4n(B)){A.2z(B,\'1j\');G H}F e=W A.fx.a8(B,a,b);e.a7()})};A.fx.a8=C(e,a,b){F z=B;z.el=A(e);z.el.1S();z.74=R(a)||3;z.29=b;z.52=1;z.U={};z.U.T=z.el.E(\'T\');z.U.O=R(z.el.E(\'O\'))||0;z.U.M=R(z.el.E(\'M\'))||0;if(z.U.T!=\'2i\'&&z.U.T!=\'1J\'){z.el.E(\'T\',\'2i\')}z.a7=C(){z.52++;z.e=W A.fx(z.el.I(0),{1H:60,1T:C(){z.e=W A.fx(z.el.I(0),{1H:60,1T:C(){z.e=W A.fx(e,{1H:60,1T:C(){if(z.52<=z.74)z.a7();L{z.el.E(\'T\',z.U.T).E(\'O\',z.U.O+\'Q\').E(\'M\',z.U.M+\'Q\');A.2z(z.el.I(0),\'1j\');if(z.29&&z.29.1F==2w){z.29.1x(z.el.I(0))}}}},\'M\');z.e.1G(z.U.M-20,z.U.M)}},\'M\');z.e.1G(z.U.M+20,z.U.M-20)}},\'M\');z.e.1G(z.U.M,z.U.M+20)}};A.fn.1U({dR:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'4l\',\'in\',c)})},c6:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'4l\',\'3U\',c)})},fr:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'4l\',\'3E\',c)})},fq:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'41\',\'in\',c)})},fp:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'41\',\'3U\',c)})},fo:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'41\',\'3E\',c)})},fm:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'M\',\'in\',c)})},fl:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'M\',\'3U\',c)})},fk:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'M\',\'3E\',c)})},fj:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'2D\',\'in\',c)})},fi:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'2D\',\'3U\',c)})},fh:C(a,b,c){G B.1r(\'1j\',C(){W A.fx.1u(B,a,b,\'2D\',\'3E\',c)})}});A.fx.1u=C(e,a,b,c,d,f){if(!A.4n(e)){A.2z(e,\'1j\');G H}F z=B;z.el=A(e);z.1e=28 b==\'4B\'?b:f||P;z.29=28 b==\'C\'?b:P;if(d==\'3E\'){d=z.el.E(\'11\')==\'1k\'?\'in\':\'3U\'}if(!e.4f)e.4f=z.el.E(\'11\');z.el.1S();z.1l=a;z.fx=A.fx.9u(e);z.1K=d;z.6T=c;z.1T=C(){if(z.1K==\'3U\')z.el.E(\'2W\',\'2B\');A.fx.9n(z.fx.2Y.I(0),z.fx.U);if(z.1K==\'in\'){z.el.E(\'11\',z.el.I(0).4f==\'1k\'?\'2v\':z.el.I(0).4f)}L{z.el.E(\'11\',\'1k\');z.el.E(\'2W\',\'cl\')}if(z.29&&z.29.1F==2w){z.29.1x(z.el.I(0))}A.2z(z.el.I(0),\'1j\')};2X(z.6T){19\'4l\':z.ef=W A.fx(z.el.I(0),A.1l(z.1l,z.1e,z.1T),\'O\');z.79=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e),\'S\');if(z.1K==\'in\'){z.ef.1G(-z.fx.U.1o.hb,0);z.79.1G(0,z.fx.U.1o.hb)}L{z.ef.1G(0,-z.fx.U.1o.hb);z.79.1G(z.fx.U.1o.hb,0)}1n;19\'41\':z.ef=W A.fx(z.el.I(0),A.1l(z.1l,z.1e,z.1T),\'O\');if(z.1K==\'in\'){z.ef.1G(z.fx.U.1o.hb,0)}L{z.ef.1G(0,z.fx.U.1o.hb)}1n;19\'M\':z.ef=W A.fx(z.el.I(0),A.1l(z.1l,z.1e,z.1T),\'M\');z.79=W A.fx(z.fx.2Y.I(0),A.1l(z.1l,z.1e),\'V\');if(z.1K==\'in\'){z.ef.1G(-z.fx.U.1o.1D,0);z.79.1G(0,z.fx.U.1o.1D)}L{z.ef.1G(0,-z.fx.U.1o.1D);z.79.1G(z.fx.U.1o.1D,0)}1n;19\'2D\':z.ef=W A.fx(z.el.I(0),A.1l(z.1l,z.1e,z.1T),\'M\');if(z.1K==\'in\'){z.ef.1G(z.fx.U.1o.1D,0)}L{z.ef.1G(0,z.fx.U.1o.1D)}1n}};A.2O=P;A.fn.fg=C(o){G B.1r(\'1j\',C(){W A.fx.cj(B,o)})};A.fx.cj=C(e,o){if(A.2O==P){A(\'23\',1c).1L(\'<1W id="2O">\');A.2O=A(\'#2O\')}A.2O.E(\'11\',\'2v\').E(\'T\',\'1J\');F z=B;z.el=A(e);if(!o||!o.3v){G}if(o.3v.1F==8t&&1c.7o(o.3v)){o.3v=1c.7o(o.3v)}L if(!o.3v.ci){G}if(!o.1H){o.1H=ch}z.1H=o.1H;z.3v=o.3v;z.7e=o.2Z;z.1T=o.1T;if(z.7e){A.2O.2H(z.7e)}z.8s=0;z.8i=0;if(A.e0){z.8s=(R(A.2O.E(\'4y\'))||0)+(R(A.2O.E(\'5i\'))||0)+(R(A.2O.E(\'4F\'))||0)+(R(A.2O.E(\'5g\'))||0);z.8i=(R(A.2O.E(\'4x\'))||0)+(R(A.2O.E(\'5d\'))||0)+(R(A.2O.E(\'5b\'))||0)+(R(A.2O.E(\'4Q\'))||0)}z.2b=A.1U(A.12.3a(z.el.I(0)),A.12.2f(z.el.I(0)));z.3m=A.1U(A.12.3a(z.3v),A.12.2f(z.3v));z.2b.1D-=z.8s;z.2b.hb-=z.8i;z.3m.1D-=z.8s;z.3m.hb-=z.8i;z.29=o.1T;A.2O.E(\'V\',z.2b.1D+\'Q\').E(\'S\',z.2b.hb+\'Q\').E(\'O\',z.2b.y+\'Q\').E(\'M\',z.2b.x+\'Q\').4S({O:z.3m.y,M:z.3m.x,V:z.3m.1D,S:z.3m.hb},z.1H,C(){if(z.7e)A.2O.3S(z.7e);A.2O.E(\'11\',\'1k\');if(z.1T&&z.1T.1F==2w){z.1T.1x(z.el.I(0),[z.3v])}A.2z(z.el.I(0),\'1j\')})};A.1q={24:{2u:10,cf:\'1R/ff.ce\',cd:\'<3O 2E="1R/5o.cc" />\',cb:0.8,ca:\'fb 8G\',c9:\'6m\',3F:7n},fa:H,f8:H,5A:P,7m:H,7l:H,a3:C(a){if(!A.1q.7l||A.1q.7m)G;F b=a.6S||a.6R||-1;2X(b){19 35:if(A.1q.5A)A.1q.2b(P,A(\'a[@4o=\'+A.1q.5A+\']:f7\').I(0));1n;19 36:if(A.1q.5A)A.1q.2b(P,A(\'a[@4o=\'+A.1q.5A+\']:f6\').I(0));1n;19 37:19 8:19 33:19 80:19 f4:F c=A(\'#7j\');if(c.I(0).4q!=P){c.I(0).4q.1x(c.I(0))}1n;19 38:1n;19 39:19 34:19 32:19 fd:19 78:F d=A(\'#7h\');if(d.I(0).4q!=P){d.I(0).4q.1x(d.I(0))}1n;19 40:1n;19 27:A.1q.8q();1n}},6g:C(a){if(a)A.1U(A.1q.24,a);if(1P.3N){A(\'23\',1c).1C(\'5Q\',A.1q.a3)}L{A(1c).1C(\'5Q\',A.1q.a3)}A(\'a\').1y(C(){el=A(B);c5=el.1m(\'4o\')||\'\';c4=el.1m(\'2U\')||\'\';cg=/\\.cc|\\.f2|\\.7q|\\.ce|\\.f1/g;if(c4.5u().aD(cg)!=P&&c5.5u().3o(\'c2\')==0){el.1C(\'4U\',A.1q.2b)}});if(A.2R.46){3q=1c.3x(\'3q\');A(3q).1m({id:\'a1\',2E:\'dc:H;\',da:\'b0\',d7:\'b0\'}).E({11:\'1k\',T:\'1J\',O:\'0\',M:\'0\',4X:\'9x:9C.9E.a6(1E=0)\'});A(\'23\').1L(3q)}7r=1c.3x(\'1W\');A(7r).1m(\'id\',\'a0\').E({T:\'1J\',11:\'1k\',O:\'0\',M:\'0\',1E:0}).1L(1c.8b(\' \')).1C(\'4U\',A.1q.8q);5C=1c.3x(\'1W\');A(5C).1m(\'id\',\'c0\').E({4F:A.1q.24.2u+\'Q\'}).1L(1c.8b(\' \'));9Z=1c.3x(\'1W\');A(9Z).1m(\'id\',\'bY\').E({4F:A.1q.24.2u+\'Q\',4Q:A.1q.24.2u+\'Q\'}).1L(1c.8b(\' \'));9Y=1c.3x(\'a\');A(9Y).1m({id:\'f0\',2U:\'#\'}).E({T:\'1J\',2D:A.1q.24.2u+\'Q\',O:\'0\'}).1L(A.1q.24.cd).1C(\'4U\',A.1q.8q);6Z=1c.3x(\'1W\');A(6Z).1m(\'id\',\'9X\').E({T:\'2i\',9W:\'M\',5X:\'0 8x\',3j:1}).1L(5C).1L(9Z).1L(9Y);21=1c.3x(\'3O\');21.2E=A.1q.24.cf;A(21).1m(\'id\',\'bW\').E({T:\'1J\'});5G=1c.3x(\'a\');A(5G).1m({id:\'7j\',2U:\'#\'}).E({T:\'1J\',11:\'1k\',2N:\'2B\',cC:\'1k\'}).1L(1c.8b(\' \'));5F=1c.3x(\'a\');A(5F).1m({id:\'7h\',2U:\'#\'}).E({T:\'1J\',2N:\'2B\',cC:\'1k\'}).1L(1c.8b(\' \'));2q=1c.3x(\'1W\');A(2q).1m(\'id\',\'bT\').E({11:\'1k\',T:\'2i\',2N:\'2B\',9W:\'M\',5X:\'0 8x\',O:\'0\',M:\'0\',3j:2}).1L([21,5G,5F]);5Z=1c.3x(\'1W\');A(5Z).1m(\'id\',\'8m\').E({11:\'1k\',T:\'1J\',2N:\'2B\',O:\'0\',M:\'0\',9W:\'az\',6P:\'b7\',eY:\'0\'}).1L([2q,6Z]);A(\'23\').1L(7r).1L(5Z)},2b:C(e,a){el=a?A(a):A(B);8J=el.1m(\'4o\');F b,4E,5G,5F;if(8J!=\'c2\'){A.1q.5A=8J;7F=A(\'a[@4o=\'+8J+\']\');b=7F.1N();4E=7F.aY(a?a:B);5G=7F.I(4E-1);5F=7F.I(4E+1)}aw=el.1m(\'2U\');5C=el.1m(\'3T\');3R=A.12.5O();7r=A(\'#a0\');if(!A.1q.7l){A.1q.7l=14;if(A.2R.46){A(\'#a1\').E(\'S\',Z.3g(3R.ih,3R.h)+\'Q\').E(\'V\',Z.3g(3R.iw,3R.w)+\'Q\').1S()}7r.E(\'S\',Z.3g(3R.ih,3R.h)+\'Q\').E(\'V\',Z.3g(3R.iw,3R.w)+\'Q\').1S().bS(bz,A.1q.24.cb,C(){A.1q.aB(aw,5C,3R,b,4E,5G,5F)});A(\'#8m\').E(\'V\',Z.3g(3R.iw,3R.w)+\'Q\')}L{A(\'#7j\').I(0).4q=P;A(\'#7h\').I(0).4q=P;A.1q.aB(aw,5C,3R,b,4E,5G,5F)}G H},aB:C(a,b,c,d,e,f,g){A(\'#aA\').9U();8l=A(\'#7j\');8l.2x();8k=A(\'#7h\');8k.2x();21=A(\'#bW\');2q=A(\'#bT\');5Z=A(\'#8m\');6Z=A(\'#9X\').E(\'2W\',\'2B\');A(\'#c0\').3i(5C);A.1q.7m=14;if(d)A(\'#bY\').3i(A.1q.24.ca+\' \'+(e+1)+\' \'+A.1q.24.c9+\' \'+d);if(f){8l.I(0).4q=C(){B.4W();A.1q.2b(P,f);G H}}if(g){8k.I(0).4q=C(){B.4W();A.1q.2b(P,g);G H}}21.1S();7u=A.12.2f(2q.I(0));4C=Z.3g(7u.1D,21.I(0).V+A.1q.24.2u*2);59=Z.3g(7u.hb,21.I(0).S+A.1q.24.2u*2);21.E({M:(4C-21.I(0).V)/2+\'Q\',O:(59-21.I(0).S)/2+\'Q\'});2q.E({V:4C+\'Q\',S:59+\'Q\'}).1S();bQ=A.12.a5();5Z.E(\'O\',c.t+(bQ.h/15)+\'Q\');if(5Z.E(\'11\')==\'1k\'){5Z.1S().6U(A.1q.24.3F)}5H=W 8M;A(5H).1m(\'id\',\'aA\').1C(\'eP\',C(){4C=5H.V+A.1q.24.2u*2;59=5H.S+A.1q.24.2u*2;21.2x();2q.4S({S:59},7u.hb!=59?A.1q.24.3F:1,C(){2q.4S({V:4C},7u.1D!=4C?A.1q.24.3F:1,C(){2q.aJ(5H);A(5H).E({T:\'1J\',M:A.1q.24.2u+\'Q\',O:A.1q.24.2u+\'Q\'}).6U(A.1q.24.3F,C(){cL=A.12.2f(6Z.I(0));if(f){8l.E({M:A.1q.24.2u+\'Q\',O:A.1q.24.2u+\'Q\',V:4C/2-A.1q.24.2u*3+\'Q\',S:59-A.1q.24.2u*2+\'Q\'}).1S()}if(g){8k.E({M:4C/2+A.1q.24.2u*2+\'Q\',O:A.1q.24.2u+\'Q\',V:4C/2-A.1q.24.2u*3+\'Q\',S:59-A.1q.24.2u*2+\'Q\'}).1S()}6Z.E({V:4C+\'Q\',O:-cL.hb+\'Q\',2W:\'cl\'}).4S({O:-1},A.1q.24.3F,C(){A.1q.7m=H})})})})});5H.2E=a},8q:C(){A(\'#aA\').9U();A(\'#8m\').2x();A(\'#9X\').E(\'2W\',\'2B\');A(\'#a0\').bS(bz,0,C(){A(B).2x();if(A.2R.46){A(\'#a1\').2x()}});A(\'#7j\').I(0).4q=P;A(\'#7h\').I(0).4q=P;A.1q.5A=P;A.1q.7l=H;A.1q.7m=H;G H}};A.N={1v:P,3A:P,1g:P,1A:P,1o:P,T:P,7f:C(e){A.N.1g=(B.9T)?B.9T:B;A.N.1A=A.12.3W(e);A.N.1o={V:R(A(A.N.1g).E(\'V\'))||0,S:R(A(A.N.1g).E(\'S\'))||0};A.N.T={O:R(A(A.N.1g).E(\'O\'))||0,M:R(A(A.N.1g).E(\'M\'))||0};A(1c).1C(\'3t\',A.N.aO).1C(\'5n\',A.N.aN);if(28 A.N.1g.1h.bO===\'C\'){A.N.1g.1h.bO.1x(A.N.1g)}G H},aN:C(e){A(1c).3h(\'3t\',A.N.aO).3h(\'5n\',A.N.aN);if(28 A.N.1g.1h.cO===\'C\'){A.N.1g.1h.cO.1x(A.N.1g)}A.N.1g=P},aO:C(e){if(!A.N.1g){G}1A=A.12.3W(e);6c=A.N.T.O-A.N.1A.y+1A.y;77=A.N.T.M-A.N.1A.x+1A.x;6c=Z.3g(Z.3k(6c,A.N.1g.1h.7d-A.N.1o.S),A.N.1g.1h.6F);77=Z.3g(Z.3k(77,A.N.1g.1h.7c-A.N.1o.V),A.N.1g.1h.6u);if(28 A.N.1g.1h.4h===\'C\'){F a=A.N.1g.1h.4h.1x(A.N.1g,[77,6c]);if(28 a==\'eI\'&&a.1b==2){77=a[0];6c=a[1]}}A.N.1g.Y.O=6c+\'Q\';A.N.1g.Y.M=77+\'Q\';G H},2b:C(e){A(1c).1C(\'3t\',A.N.7g).1C(\'5n\',A.N.7w);A.N.1v=B.1v;A.N.3A=B.3A;A.N.1A=A.12.3W(e);A.N.1o={V:R(A(B.1v).E(\'V\'))||0,S:R(A(B.1v).E(\'S\'))||0};A.N.T={O:R(A(B.1v).E(\'O\'))||0,M:R(A(B.1v).E(\'M\'))||0};if(A.N.1v.1h.4c){A.N.1v.1h.4c.1x(A.N.1v,[B])}G H},7w:C(){A(1c).3h(\'3t\',A.N.7g).3h(\'5n\',A.N.7w);if(A.N.1v.1h.3C){A.N.1v.1h.3C.1x(A.N.1v,[A.N.3A])}A.N.1v=P;A.N.3A=P},5N:C(a,b){G Z.3k(Z.3g(A.N.1o.V+a*b,A.N.1v.1h.8O),A.N.1v.1h.5R)},5M:C(a,b){G Z.3k(Z.3g(A.N.1o.S+a*b,A.N.1v.1h.7x),A.N.1v.1h.7y)},bN:C(a){G Z.3k(Z.3g(a,A.N.1v.1h.7x),A.N.1v.1h.7y)},7g:C(e){if(A.N.1v==P){G}1A=A.12.3W(e);dx=1A.x-A.N.1A.x;dy=1A.y-A.N.1A.y;1B={V:A.N.1o.V,S:A.N.1o.S};2s={O:A.N.T.O,M:A.N.T.M};2X(A.N.3A){19\'e\':1B.V=A.N.5N(dx,1);1n;19\'eH\':1B.V=A.N.5N(dx,1);1B.S=A.N.5M(dy,1);1n;19\'w\':1B.V=A.N.5N(dx,-1);2s.M=A.N.T.M-1B.V+A.N.1o.V;1n;19\'9R\':1B.V=A.N.5N(dx,-1);2s.M=A.N.T.M-1B.V+A.N.1o.V;1B.S=A.N.5M(dy,1);1n;19\'7a\':1B.S=A.N.5M(dy,-1);2s.O=A.N.T.O-1B.S+A.N.1o.S;1B.V=A.N.5N(dx,-1);2s.M=A.N.T.M-1B.V+A.N.1o.V;1n;19\'n\':1B.S=A.N.5M(dy,-1);2s.O=A.N.T.O-1B.S+A.N.1o.S;1n;19\'9Q\':1B.S=A.N.5M(dy,-1);2s.O=A.N.T.O-1B.S+A.N.1o.S;1B.V=A.N.5N(dx,1);1n;19\'s\':1B.S=A.N.5M(dy,1);1n}if(A.N.1v.1h.44){if(A.N.3A==\'n\'||A.N.3A==\'s\')43=1B.S*A.N.1v.1h.44;L 43=1B.V;4z=A.N.bN(43*A.N.1v.1h.44);43=4z/A.N.1v.1h.44;2X(A.N.3A){19\'n\':19\'7a\':19\'9Q\':2s.O+=1B.S-4z;1n}2X(A.N.3A){19\'7a\':19\'w\':19\'9R\':2s.M+=1B.V-43;1n}1B.S=4z;1B.V=43}if(2s.OA.N.1v.1h.7d){1B.S=A.N.1v.1h.7d-2s.O;if(A.N.1v.1h.44){1B.V=1B.S/A.N.1v.1h.44}}if(2s.M+1B.V>A.N.1v.1h.7c){1B.V=A.N.1v.1h.7c-2s.M;if(A.N.1v.1h.44){1B.S=1B.V*A.N.1v.1h.44}}F a=H;if(A.N.1v.1h.eG){a=A.N.1v.1h.eG.1x(A.N.1v,[1B,2s]);if(a){if(a.1o){A.1U(1B,a.1o)}if(a.T){A.1U(2s,a.T)}}}8f=A.N.1v.Y;8f.M=2s.M+\'Q\';8f.O=2s.O+\'Q\';8f.V=1B.V+\'Q\';8f.S=1B.S+\'Q\';G H},2l:C(b){if(!b||!b.3G||b.3G.1F!=6E){G}G B.1y(C(){F a=B;a.1h=b;a.1h.8O=b.8O||10;a.1h.7x=b.7x||10;a.1h.5R=b.5R||5P;a.1h.7y=b.7y||5P;a.1h.6F=b.6F||-8V;a.1h.6u=b.6u||-8V;a.1h.7c=b.7c||5P;a.1h.7d=b.7d||5P;bK=A(a).E(\'T\');if(!(bK==\'2i\'||bK==\'1J\')){a.Y.T=\'2i\'}eE=/n|9Q|e|eH|s|9R|w|7a/g;1V(i in a.1h.3G){if(i.5u().aD(eE)!=P){if(a.1h.3G[i].1F==8t){3c=A(a.1h.3G[i]);if(3c.1N()>0){a.1h.3G[i]=3c.I(0)}}if(a.1h.3G[i].4D){a.1h.3G[i].1v=a;a.1h.3G[i].3A=i;A(a.1h.3G[i]).1C(\'4R\',A.N.2b)}}}if(a.1h.5k){if(28 a.1h.5k===\'4B\'){9N=A(a.1h.5k);if(9N.1N()>0){9N.1y(C(){B.9T=a});9N.1C(\'4R\',A.N.7f)}}L if(a.1h.5k==14){A(B).1C(\'4R\',A.N.7f)}}})},4v:C(){G B.1y(C(){F a=B;1V(i in a.1h.3G){a.1h.3G[i].1v=P;a.1h.3G[i].3A=P;A(a.1h.3G[i]).3h(\'4R\',A.N.2b)}if(a.1h.5k){if(28 a.1h.5k===\'4B\'){3c=A(a.1h.5k);if(3c.1N()>0){3c.3h(\'4R\',A.N.7f)}}L if(a.1h.5k==14){A(B).3h(\'4R\',A.N.7f)}}a.1h=P})}};A.fn.1U({jk:A.N.2l,jj:A.N.4v});A.2t=P;A.6J=H;A.31=P;A.6B=[];A.9L=C(e){F a=e.6S||e.6R||-1;if(a==17||a==16){A.6J=14}};A.9J=C(e){A.6J=H};A.eB=C(e){B.f.1A=A.12.3W(e);B.f.1I=A.1U(A.12.3a(B),A.12.2f(B));B.f.4p=A.12.5O(B);B.f.1A.x-=B.f.1I.x;B.f.1A.y-=B.f.1I.y;A(B).1L(A.2t.I(0));if(B.f.hc)A.2t.2H(B.f.hc).E(\'11\',\'2v\');A.2t.E({11:\'2v\',V:\'2G\',S:\'2G\'});if(B.f.o){A.2t.E(\'1E\',B.f.o)}A.31=B;A.7A=H;A.6B=[];B.f.el.1y(C(){B.1I={x:B.7Y+(B.4u&&!A.2R.6l?R(B.4u.4y)||0:0)+(A.31.2P||0),y:B.7t+(B.4u&&!A.2R.6l?R(B.4u.4x)||0:0)+(A.31.2T||0),1D:B.3P,hb:B.5r};if(B.s==14){if(A.6J==H){B.s=H;A(B).3S(A.31.f.71)}L{A.7A=14;A.6B[A.6B.1b]=A.1m(B,\'id\')}}});A.9H.1x(B,[e]);A(1c).1C(\'3t\',A.9H).1C(\'5n\',A.bI);G H};A.9H=C(e){if(!A.31)G;A.eA.1x(A.31,[e])};A.eA=C(e){if(!A.31)G;F a=A.12.3W(e);F b=A.12.5O(A.31);a.x+=b.l-B.f.4p.l-B.f.1I.x;a.y+=b.t-B.f.4p.t-B.f.1I.y;F c=Z.3k(a.x,B.f.1A.x);F d=Z.3k(Z.3B(a.x-B.f.1A.x),Z.3B(B.f.4p.w-c));F f=Z.3k(a.y,B.f.1A.y);F g=Z.3k(Z.3B(a.y-B.f.1A.y),Z.3B(B.f.4p.h-f));if(B.2T>0&&a.y-20B.2T+B.f.1I.h){F h=Z.3k(B.f.4p.h-B.2T,10);B.2T+=h;if(B.2T!=b.t)g+=h}if(B.2P>0&&a.x-20B.2P+B.f.1I.w){F h=Z.3k(B.f.4p.w-B.2P,10);B.2P+=h;if(B.2P!=b.l)d+=h}A.2t.E({M:c+\'Q\',O:f+\'Q\',V:d+\'Q\',S:g+\'Q\'});A.2t.l=c+B.f.4p.l;A.2t.t=f+B.f.4p.t;A.2t.r=A.2t.l+d;A.2t.b=A.2t.t+g;A.7A=H;B.f.el.1y(C(){9G=A.6B.3o(A.1m(B,\'id\'));if(!(B.1I.x>A.2t.r||(B.1I.x+B.1I.1D)A.2t.b||(B.1I.y+B.1I.hb)0){h+=\'&\'}h+=s+\'[]=\'+A.1m(B,\'id\');o[o.1b]=A.1m(B,\'id\')}})}G{6A:h,o:o}};A.fn.jg=C(o){if(!A.2t){A(\'23\',1c).1L(\'<1W id="2t">\').1C(\'70\',A.9L).1C(\'5Q\',A.9J);A.2t=A(\'#2t\');A.2t.E({T:\'1J\',11:\'1k\'});if(1P.3N){A(\'23\',1c).1C(\'70\',A.9L).1C(\'5Q\',A.9J)}L{A(1c).1C(\'70\',A.9L).1C(\'5Q\',A.9J)}}if(!o){o={}}G B.1y(C(){if(B.ey)G;B.ey=14;B.f={a:o.3r,o:o.1E?2c(o.1E):H,71:o.ex?o.ex:H,hc:o.4G?o.4G:H,8d:o.8d?o.8d:H,8c:o.8c?o.8c:H};B.f.el=A(\'.\'+o.3r);A(B).1C(\'4R\',A.eB).E(\'T\',\'2i\')})};A.2Q={aT:1,ew:C(b){F b=b;G B.1y(C(){B.4g.69.1y(C(a){A.2Q.4s(B,b[a])})})},I:C(){F e=[];B.1y(C(b){if(B.bD){e[b]=[];F c=B;F d=A.12.2f(B);B.4g.69.1y(C(a){F x=B.7Y;F y=B.7t;7B=R(x*1Y/(d.w-B.3P));7C=R(y*1Y/(d.h-B.5r));e[b][a]=[7B||0,7C||0,x||0,y||0]})}});G e},ad:C(a){a.D.ep=a.D.1Z.w-a.D.1w.1D;a.D.eo=a.D.1Z.h-a.D.1w.hb;if(a.92.4g.bB){8Z=a.92.4g.69.I(a.bA+1);if(8Z){a.D.1Z.w=(R(A(8Z).E(\'M\'))||0)+a.D.1w.1D;a.D.1Z.h=(R(A(8Z).E(\'O\'))||0)+a.D.1w.hb}9f=a.92.4g.69.I(a.bA-1);if(9f){F b=R(A(9f).E(\'M\'))||0;F c=R(A(9f).E(\'M\'))||0;a.D.1Z.x+=b;a.D.1Z.y+=c;a.D.1Z.w-=b;a.D.1Z.h-=c}}a.D.ek=a.D.1Z.w-a.D.1w.1D;a.D.ej=a.D.1Z.h-a.D.1w.hb;if(a.D.2C){a.D.gx=((a.D.1Z.w-a.D.1w.1D)/a.D.2C)||1;a.D.gy=((a.D.1Z.h-a.D.1w.hb)/a.D.2C)||1;a.D.d1=a.D.ek/a.D.2C;a.D.d0=a.D.ej/a.D.2C}a.D.1Z.dx=a.D.1Z.x-a.D.22.x;a.D.1Z.dy=a.D.1Z.y-a.D.22.y;A.X.18.E(\'7z\',\'8T\')},3n:C(a,x,y){if(a.D.2C){d9=R(x/a.D.d1);7B=d9*1Y/a.D.2C;d5=R(y/a.D.d0);7C=d5*1Y/a.D.2C}L{7B=R(x*1Y/a.D.ep);7C=R(y*1Y/a.D.eo)}a.D.aa=[7B||0,7C||0,x||0,y||0];if(a.D.3n)a.D.3n.1x(a,a.D.aa)},d3:C(a){6K=a.6S||a.6R||-1;2X(6K){19 35:A.2Q.4s(B.3H,[91,91]);1n;19 36:A.2Q.4s(B.3H,[-91,-91]);1n;19 37:A.2Q.4s(B.3H,[-B.3H.D.gx||-1,0]);1n;19 38:A.2Q.4s(B.3H,[0,-B.3H.D.gy||-1]);1n;19 39:A.2Q.4s(B.3H,[B.3H.D.gx||1,0]);1n;19 40:A.X.4s(B.3H,[0,B.3H.D.gy||1]);1n}},4s:C(a,b){if(!a.D){G}a.D.1w=A.1U(A.12.3a(a),A.12.2f(a));a.D.22={x:R(A.E(a,\'M\'))||0,y:R(A.E(a,\'O\'))||0};a.D.49=A.E(a,\'T\');if(a.D.49!=\'2i\'&&a.D.49!=\'1J\'){a.Y.T=\'2i\'}A.X.ah(a);A.2Q.ad(a);dx=R(b[0])||0;dy=R(b[1])||0;2n=a.D.22.x+dx;2j=a.D.22.y+dy;if(a.D.2C){57=A.X.a9.1x(a,[2n,2j,dx,dy]);if(57.1F==6E){dx=57.dx;dy=57.dy}2n=a.D.22.x+dx;2j=a.D.22.y+dy}57=A.X.ae.1x(a,[2n,2j,dx,dy]);if(57&&57.1F==6E){dx=57.dx;dy=57.dy}2n=a.D.22.x+dx;2j=a.D.22.y+dy;if(a.D.4P&&(a.D.3n||a.D.2I)){A.2Q.3n(a,2n,2j)}2n=!a.D.2g||a.D.2g==\'3Z\'?2n:a.D.22.x||0;2j=!a.D.2g||a.D.2g==\'3K\'?2j:a.D.22.y||0;a.Y.M=2n+\'Q\';a.Y.O=2j+\'Q\'},2l:C(o){G B.1y(C(){if(B.bD==14||!o.3r||!A.12||!A.X||!A.1s){G}4Y=A(o.3r,B);if(4Y.1N()==0){G}F b={2e:\'7X\',4P:14,3n:o.3n&&o.3n.1F==2w?o.3n:P,2I:o.2I&&o.2I.1F==2w?o.2I:P,3c:B,1E:o.1E||H};if(o.2C&&R(o.2C)){b.2C=R(o.2C)||1;b.2C=b.2C>0?b.2C:1}if(4Y.1N()==1)4Y.6r(b);L{A(4Y.I(0)).6r(b);b.3c=P;4Y.6r(b)}4Y.70(A.2Q.d3);4Y.1m(\'aT\',A.2Q.aT++);B.bD=14;B.4g={};B.4g.ec=b.ec;B.4g.2C=b.2C;B.4g.69=4Y;B.4g.bB=o.bB?14:H;by=B;by.4g.69.1y(C(a){B.bA=a;B.92=by});if(o.5f&&o.5f.1F==6h){1V(i=o.5f.1b-1;i>=0;i--){if(o.5f[i].1F==6h&&o.5f[i].1b==2){el=B.4g.69.I(i);if(el.4D){A.2Q.4s(el,o.5f[i])}}}}})}};A.fn.1U({jc:A.2Q.2l,jb:A.2Q.ew,ja:A.2Q.I});A.2p={56:[],ea:C(){B.4W();1d=B.2S;id=A.1m(1d,\'id\');if(A.2p.56[id]!=P){1P.5h(A.2p.56[id])}1u=1d.J.3d+1;if(1d.J.1R.1b<1u){1u=1}1R=A(\'3O\',1d.J.4O);1d.J.3d=1u;if(1R.1N()>0){1R.6d(1d.J.3F,A.2p.7J)}},di:C(){B.4W();1d=B.2S;id=A.1m(1d,\'id\');if(A.2p.56[id]!=P){1P.5h(A.2p.56[id])}1u=1d.J.3d-1;1R=A(\'3O\',1d.J.4O);if(1u<1){1u=1d.J.1R.1b}1d.J.3d=1u;if(1R.1N()>0){1R.6d(1d.J.3F,A.2p.7J)}},2A:C(c){1d=1c.7o(c);if(1d.J.63){1u=1d.J.3d;6k(1u==1d.J.3d){1u=1+R(Z.63()*1d.J.1R.1b)}}L{1u=1d.J.3d+1;if(1d.J.1R.1b<1u){1u=1}}1R=A(\'3O\',1d.J.4O);1d.J.3d=1u;if(1R.1N()>0){1R.6d(1d.J.3F,A.2p.7J)}},go:C(o){F a;if(o&&o.1F==6E){if(o.21){a=1c.7o(o.21.1d);5v=1P.j8.2U.6W("#");o.21.5J=P;if(5v.1b==2){1u=R(5v[1]);1S=5v[1].48(1u,\'\');if(A.1m(a,\'id\')!=1S){1u=1}}L{1u=1}}if(o.84){o.84.4W();a=o.84.2S.2S;id=A.1m(a,\'id\');if(A.2p.56[id]!=P){1P.5h(A.2p.56[id])}5v=o.84.2U.6W("#");1u=R(5v[1]);1S=5v[1].48(1u,\'\');if(A.1m(a,\'id\')!=1S){1u=1}}if(a.J.1R.1b<1u||1u<1){1u=1}a.J.3d=1u;4t=A.12.2f(a);e4=A.12.9y(a);e3=A.12.6b(a);if(a.J.3e){a.J.3e.o.E(\'11\',\'1k\')}if(a.J.3b){a.J.3b.o.E(\'11\',\'1k\')}if(a.J.21){y=R(e4.t)+R(e3.t);if(a.J.1Q){if(a.J.1Q.4J==\'O\'){y+=a.J.1Q.45.hb}L{4t.h-=a.J.1Q.45.hb}}if(a.J.2o){if(a.J.2o&&a.J.2o.5V==\'O\'){y+=a.J.2o.45.hb}L{4t.h-=a.J.2o.45.hb}}if(!a.J.bu){a.J.e1=o.21?o.21.S:(R(a.J.21.E(\'S\'))||0);a.J.bu=o.21?o.21.V:(R(a.J.21.E(\'V\'))||0)}a.J.21.E(\'O\',y+(4t.h-a.J.e1)/2+\'Q\');a.J.21.E(\'M\',(4t.1D-a.J.bu)/2+\'Q\');a.J.21.E(\'11\',\'2v\')}1R=A(\'3O\',a.J.4O);if(1R.1N()>0){1R.6d(a.J.3F,A.2p.7J)}L{9w=A(\'a\',a.J.1Q.o).I(1u-1);A(9w).2H(a.J.1Q.5s);F b=W 8M();b.1d=A.1m(a,\'id\');b.1u=1u-1;b.2E=a.J.1R[a.J.3d-1].2E;if(b.1T){b.5J=P;A.2p.11.1x(b)}L{b.5J=A.2p.11}if(a.J.2o){a.J.2o.o.3i(a.J.1R[1u-1].5W)}}}},7J:C(){1d=B.2S.2S;1d.J.4O.E(\'11\',\'1k\');if(1d.J.1Q.5s){9w=A(\'a\',1d.J.1Q.o).3S(1d.J.1Q.5s).I(1d.J.3d-1);A(9w).2H(1d.J.1Q.5s)}F a=W 8M();a.1d=A.1m(1d,\'id\');a.1u=1d.J.3d-1;a.2E=1d.J.1R[1d.J.3d-1].2E;if(a.1T){a.5J=P;A.2p.11.1x(a)}L{a.5J=A.2p.11}if(1d.J.2o){1d.J.2o.o.3i(1d.J.1R[1d.J.3d-1].5W)}},11:C(){1d=1c.7o(B.1d);if(1d.J.3e){1d.J.3e.o.E(\'11\',\'1k\')}if(1d.J.3b){1d.J.3b.o.E(\'11\',\'1k\')}4t=A.12.2f(1d);y=0;if(1d.J.1Q){if(1d.J.1Q.4J==\'O\'){y+=1d.J.1Q.45.hb}L{4t.h-=1d.J.1Q.45.hb}}if(1d.J.2o){if(1d.J.2o&&1d.J.2o.5V==\'O\'){y+=1d.J.2o.45.hb}L{4t.h-=1d.J.2o.45.hb}}j4=A(\'.bt\',1d);y=y+(4t.h-B.S)/2;x=(4t.1D-B.V)/2;1d.J.4O.E(\'O\',y+\'Q\').E(\'M\',x+\'Q\').3i(\'<3O 2E="\'+B.2E+\'" />\');1d.J.4O.6U(1d.J.3F);3b=1d.J.3d+1;if(3b>1d.J.1R.1b){3b=1}3e=1d.J.3d-1;if(3e<1){3e=1d.J.1R.1b}1d.J.3b.o.E(\'11\',\'2v\').E(\'O\',y+\'Q\').E(\'M\',x+2*B.V/3+\'Q\').E(\'V\',B.V/3+\'Q\').E(\'S\',B.S+\'Q\').1m(\'3T\',1d.J.1R[3b-1].5W);1d.J.3b.o.I(0).2U=\'#\'+3b+A.1m(1d,\'id\');1d.J.3e.o.E(\'11\',\'2v\').E(\'O\',y+\'Q\').E(\'M\',x+\'Q\').E(\'V\',B.V/3+\'Q\').E(\'S\',B.S+\'Q\').1m(\'3T\',1d.J.1R[3e-1].5W);1d.J.3e.o.I(0).2U=\'#\'+3e+A.1m(1d,\'id\')},2l:C(o){if(!o||!o.2q||A.2p.56[o.2q])G;F a=A(\'#\'+o.2q);F c=a.I(0);if(c.Y.T!=\'1J\'&&c.Y.T!=\'2i\'){c.Y.T=\'2i\'}c.Y.2N=\'2B\';if(a.1N()==0)G;c.J={};c.J.1R=o.1R?o.1R:[];c.J.63=o.63&&o.63==14||H;7T=c.dj(\'j3\');1V(i=0;i<7T.1b;i++){6e=c.J.1R.1b;c.J.1R[6e]={2E:7T[i].2E,5W:7T[i].3T||7T[i].j2||\'\'}}if(c.J.1R.1b==0){G}c.J.49=A.1U(A.12.3a(c),A.12.2f(c));c.J.bp=A.12.9y(c);c.J.bo=A.12.6b(c);t=R(c.J.bp.t)+R(c.J.bo.t);b=R(c.J.bp.b)+R(c.J.bo.b);A(\'3O\',c).9U();c.J.3F=o.3F?o.3F:ch;if(o.4J||o.82||o.5s){c.J.1Q={};a.1L(\'<1W 68="dZ">\');c.J.1Q.o=A(\'.dZ\',c);if(o.82){c.J.1Q.82=o.82;c.J.1Q.o.2H(o.82)}if(o.5s){c.J.1Q.5s=o.5s}c.J.1Q.o.E(\'T\',\'1J\').E(\'V\',c.J.49.w+\'Q\');if(o.4J&&o.4J==\'O\'){c.J.1Q.4J=\'O\';c.J.1Q.o.E(\'O\',t+\'Q\')}L{c.J.1Q.4J=\'4e\';c.J.1Q.o.E(\'4e\',b+\'Q\')}c.J.1Q.9v=o.9v?o.9v:\' \';1V(F i=0;i\'+6e+\'\'+(6e!=c.J.1R.1b?c.J.1Q.9v:\'\'))}A(\'a\',c.J.1Q.o).1C(\'4U\',C(){A.2p.go({84:B})});c.J.1Q.45=A.12.2f(c.J.1Q.o.I(0))}if(o.5V||o.81){c.J.2o={};a.1L(\'<1W 68="dW">&6G;\');c.J.2o.o=A(\'.dW\',c);if(o.81){c.J.2o.81=o.81;c.J.2o.o.2H(o.81)}c.J.2o.o.E(\'T\',\'1J\').E(\'V\',c.J.49.w+\'Q\');if(o.5V&&o.5V==\'O\'){c.J.2o.5V=\'O\';c.J.2o.o.E(\'O\',(c.J.1Q&&c.J.1Q.4J==\'O\'?c.J.1Q.45.hb+t:t)+\'Q\')}L{c.J.2o.5V=\'4e\';c.J.2o.o.E(\'4e\',(c.J.1Q&&c.J.1Q.4J==\'4e\'?c.J.1Q.45.hb+b:b)+\'Q\')}c.J.2o.45=A.12.2f(c.J.2o.o.I(0))}if(o.9j){c.J.3b={9j:o.9j};a.1L(\'&6G;\');c.J.3b.o=A(\'.dV\',c);c.J.3b.o.E(\'T\',\'1J\').E(\'11\',\'1k\').E(\'2N\',\'2B\').E(\'4a\',\'dU\').2H(c.J.3b.9j);c.J.3b.o.1C(\'4U\',A.2p.ea)}if(o.9t){c.J.3e={9t:o.9t};a.1L(\'&6G;\');c.J.3e.o=A(\'.dS\',c);c.J.3e.o.E(\'T\',\'1J\').E(\'11\',\'1k\').E(\'2N\',\'2B\').E(\'4a\',\'dU\').2H(c.J.3e.9t);c.J.3e.o.1C(\'4U\',A.2p.di)}a.aJ(\'<1W 68="bt">\');c.J.4O=A(\'.bt\',c);c.J.4O.E(\'T\',\'1J\').E(\'O\',\'2G\').E(\'M\',\'2G\').E(\'11\',\'1k\');if(o.21){a.aJ(\'<1W 68="dz" Y="11: 1k;"><3O 2E="\'+o.21+\'" />\');c.J.21=A(\'.dz\',c);c.J.21.E(\'T\',\'1J\');F d=W 8M();d.1d=o.2q;d.2E=o.21;if(d.1T){d.5J=P;A.2p.go({21:d})}L{d.5J=C(){A.2p.go({21:B})}}}L{A.2p.go({2q:c})}if(o.ba){dQ=R(o.ba)*8V}A.2p.56[o.2q]=o.ba?1P.5Y(\'A.2p.2A(\\\'\'+o.2q+\'\\\')\',dQ):P}};A.1d=A.2p.2l;A.1p={73:[],54:{},18:H,6X:P,2b:C(){if(A.X.1g==P){G}F a,3s,c,cs;A.1p.18.I(0).2Z=A.X.1g.D.5z;a=A.1p.18.I(0).Y;a.11=\'2v\';A.1p.18.1w=A.1U(A.12.3a(A.1p.18.I(0)),A.12.2f(A.1p.18.I(0)));a.V=A.X.1g.D.1w.1D+\'Q\';a.S=A.X.1g.D.1w.hb+\'Q\';3s=A.12.b2(A.X.1g);a.4M=3s.t;a.53=3s.r;a.4L=3s.b;a.4K=3s.l;if(A.X.1g.D.3L==14){c=A(A.X.1g).cA(14).I(0);cs=c.Y;cs.4M=\'2G\';cs.53=\'2G\';cs.4L=\'2G\';cs.4K=\'2G\';cs.11=\'2v\';A.1p.18.58().1L(c)}A(A.X.1g).dO(A.1p.18.I(0));A.X.1g.Y.11=\'1k\'},c7:C(e){if(!e.D.3I&&A.1s.4T.bC){if(e.D.3C)e.D.3C.1x(1g);A(e).E(\'T\',e.D.av||e.D.49);A(e).8j();A(A.1s.4T).dN(e)}A.1p.18.3S(e.D.5z).3i(\'&6G;\');A.1p.6X=P;F a=A.1p.18.I(0).Y;a.11=\'1k\';A.1p.18.dO(e);if(e.D.fx>0){A(e).6U(e.D.fx)}A(\'23\').1L(A.1p.18.I(0));F b=[];F c=H;1V(F i=0;i0){c(b)}},8n:C(e,o){if(!A.X.1g)G;F a=H;F i=0;if(e.1f.el.1N()>0){1V(i=e.1f.el.1N();i>0;i--){if(e.1f.el.I(i-1)!=A.X.1g){if(!e.5t.bb){if((e.1f.el.I(i-1).1I.y+e.1f.el.I(i-1).1I.hb/2)>A.X.1g.D.2j){a=e.1f.el.I(i-1)}L{1n}}L{if((e.1f.el.I(i-1).1I.x+e.1f.el.I(i-1).1I.1D/2)>A.X.1g.D.2n&&(e.1f.el.I(i-1).1I.y+e.1f.el.I(i-1).1I.hb/2)>A.X.1g.D.2j){a=e.1f.el.I(i-1)}}}}}if(a&&A.1p.6X!=a){A.1p.6X=a;A(a).iT(A.1p.18.I(0))}L if(!a&&(A.1p.6X!=P||A.1p.18.I(0).2S!=e)){A.1p.6X=P;A(e).1L(A.1p.18.I(0))}A.1p.18.I(0).Y.11=\'2v\'},bM:C(e){if(A.X.1g==P){G}e.1f.el.1y(C(){B.1I=A.1U(A.12.6w(B),A.12.6x(B))})},8g:C(s){F i;F h=\'\';F o={};if(s){if(A.1p.54[s]){o[s]=[];A(\'#\'+s+\' .\'+A.1p.54[s]).1y(C(){if(h.1b>0){h+=\'&\'}h+=s+\'[]=\'+A.1m(B,\'id\');o[s][o[s].1b]=A.1m(B,\'id\')})}L{1V(a in s){if(A.1p.54[s[a]]){o[s[a]]=[];A(\'#\'+s[a]+\' .\'+A.1p.54[s[a]]).1y(C(){if(h.1b>0){h+=\'&\'}h+=s[a]+\'[]=\'+A.1m(B,\'id\');o[s[a]][o[s[a]].1b]=A.1m(B,\'id\')})}}}}L{1V(i in A.1p.54){o[i]=[];A(\'#\'+i+\' .\'+A.1p.54[i]).1y(C(){if(h.1b>0){h+=\'&\'}h+=i+\'[]=\'+A.1m(B,\'id\');o[i][o[i].1b]=A.1m(B,\'id\')})}}G{6A:h,o:o}},dL:C(e){if(!e.ci){G}G B.1y(C(){if(!B.5t||!A(e).is(\'.\'+B.5t.3r))A(e).2H(B.5t.3r);A(e).6r(B.5t.D)})},4v:C(){G B.1y(C(){A(\'.\'+B.5t.3r).8j();A(B).ei();B.5t=P;B.dK=P})},2l:C(o){if(o.3r&&A.12&&A.X&&A.1s){if(!A.1p.18){A(\'23\',1c).1L(\'<1W id="dJ">&6G;\');A.1p.18=A(\'#dJ\');A.1p.18.I(0).Y.11=\'1k\'}B.ee({3r:o.3r,9F:o.9F?o.9F:H,8X:o.8X?o.8X:H,4G:o.4G?o.4G:H,76:o.76||o.ev,6C:o.6C||o.er,bC:14,2I:o.2I||o.iR,fx:o.fx?o.fx:H,3L:o.3L?14:H,5T:o.5T?o.5T:\'9S\'});G B.1y(C(){F a={5B:o.5B?14:H,dI:5P,1E:o.1E?2c(o.1E):H,5z:o.4G?o.4G:H,fx:o.fx?o.fx:H,3I:14,3L:o.3L?14:H,3c:o.3c?o.3c:P,2e:o.2e?o.2e:P,4c:o.4c&&o.4c.1F==2w?o.4c:H,4h:o.4h&&o.4h.1F==2w?o.4h:H,3C:o.3C&&o.3C.1F==2w?o.3C:H,2g:/3K|3Z/.3M(o.2g)?o.2g:H,5D:o.5D?R(o.5D)||0:H,2M:o.2M?o.2M:H};A(\'.\'+o.3r,B).6r(a);B.dK=14;B.5t={3r:o.3r,5B:o.5B?14:H,dI:5P,1E:o.1E?2c(o.1E):H,5z:o.4G?o.4G:H,fx:o.fx?o.fx:H,3I:14,3L:o.3L?14:H,3c:o.3c?o.3c:P,2e:o.2e?o.2e:P,bb:o.bb?14:H,D:a}})}}};A.fn.1U({iP:A.1p.2l,dN:A.1p.dL,iO:A.1p.4v});A.iN=A.1p.8g;A.2k={62:P,9o:H,9p:P,6a:C(e){A.2k.9o=14;A.2k.1S(e,B,14)},bk:C(e){if(A.2k.62!=B)G;A.2k.9o=H;A.2k.2x(e,B)},1S:C(e,a,b){if(A.2k.62!=P)G;if(!a){a=B}A.2k.62=a;1I=A.1U(A.12.3a(a),A.12.2f(a));7U=A(a);3T=7U.1m(\'3T\');2U=7U.1m(\'2U\');if(3T){A.2k.9p=3T;7U.1m(\'3T\',\'\');A(\'#dE\').3i(3T);if(2U)A(\'#bj\').3i(2U.48(\'iI://\',\'\'));L A(\'#bj\').3i(\'\');18=A(\'#7S\');if(a.4m.2Z){18.I(0).2Z=a.4m.2Z}L{18.I(0).2Z=\'\'}bi=A.12.2f(18.I(0));dD=b&&a.4m.T==\'bn\'?\'4e\':a.4m.T;2X(dD){19\'O\':2j=1I.y-bi.hb;2n=1I.x;1n;19\'M\':2j=1I.y;2n=1I.x-bi.1D;1n;19\'2D\':2j=1I.y;2n=1I.x+1I.1D;1n;19\'bn\':A(\'23\').1C(\'3t\',A.2k.3t);1A=A.12.3W(e);2j=1A.y+15;2n=1A.x+15;1n;8T:2j=1I.y+1I.hb;2n=1I.x;1n}18.E({O:2j+\'Q\',M:2n+\'Q\'});if(a.4m.4w==H){18.1S()}L{18.6U(a.4m.4w)}if(a.4m.2K)a.4m.2K.1x(a);7U.1C(\'86\',A.2k.2x).1C(\'4W\',A.2k.bk)}},3t:C(e){if(A.2k.62==P){A(\'23\').3h(\'3t\',A.2k.3t);G}1A=A.12.3W(e);A(\'#7S\').E({O:1A.y+15+\'Q\',M:1A.x+15+\'Q\'})},2x:C(e,a){if(!a){a=B}if(A.2k.9o!=14&&A.2k.62==a){A.2k.62=P;A(\'#7S\').6d(1);A(a).1m(\'3T\',A.2k.9p).3h(\'86\',A.2k.2x).3h(\'4W\',A.2k.bk);if(a.4m.2V)a.4m.2V.1x(a);A.2k.9p=P}},2l:C(b){if(!A.2k.18){A(\'23\').1L(\'<1W id="7S"><1W id="dE"><1W id="bj">\');A(\'#7S\').E({T:\'1J\',3j:5P,11:\'1k\'});A.2k.18=14}G B.1y(C(){if(A.1m(B,\'3T\')){B.4m={T:/O|4e|M|2D|bn/.3M(b.T)?b.T:\'4e\',2Z:b.2Z?b.2Z:H,4w:b.4w?b.4w:H,2K:b.2K&&b.2K.1F==2w?b.2K:H,2V:b.2V&&b.2V.1F==2w?b.2V:H};F a=A(B);a.1C(\'9r\',A.2k.1S);a.1C(\'6a\',A.2k.6a)}})}};A.fn.iH=A.2k.2l;A.7O={bl:C(e){6K=e.6S||e.6R||-1;if(6K==9){if(1P.3N){1P.3N.b6=14;1P.3N.b5=H}L{e.9b();e.99()}if(B.9q){1c.64.dv().3D="\\t";B.dB=C(){B.6a();B.dB=P}}L if(B.9m){2b=B.88;3m=B.dA;B.2m=B.2m.iG(0,2b)+"\\t"+B.2m.iF(3m);B.9m(2b+1,2b+1);B.6a()}G H}},4v:C(){G B.1y(C(){if(B.6V&&B.6V==14){A(B).3h(\'70\',A.7O.bl);B.6V=H}})},2l:C(){G B.1y(C(){if(B.4D==\'bs\'&&(!B.6V||B.6V==H)){A(B).1C(\'70\',A.7O.bl);B.6V=14}})}};A.fn.1U({iD:A.7O.2l,iC:A.7O.4v});A.12={3a:C(e){F x=0;F y=0;F a=e.Y;F b=H;if(A(e).E(\'11\')==\'1k\'){F c=a.2W;F d=a.T;b=14;a.2W=\'2B\';a.11=\'2v\';a.T=\'1J\'}F f=e;6k(f){x+=f.7Y+(f.4u&&!A.2R.6l?R(f.4u.4y)||0:0);y+=f.7t+(f.4u&&!A.2R.6l?R(f.4u.4x)||0:0);f=f.dY}f=e;6k(f&&f.4D&&f.4D.5u()!=\'23\'){x-=f.2P||0;y-=f.2T||0;f=f.2S}if(b==14){a.11=\'1k\';a.T=d;a.2W=c}G{x:x,y:y}},6x:C(a){F x=0,y=0;6k(a){x+=a.7Y||0;y+=a.7t||0;a=a.dY}G{x:x,y:y}},2f:C(e){F w=A.E(e,\'V\');F h=A.E(e,\'S\');F a=0;F b=0;F c=e.Y;if(A(e).E(\'11\')!=\'1k\'){a=e.3P;b=e.5r}L{F d=c.2W;F f=c.T;c.2W=\'2B\';c.11=\'2v\';c.T=\'1J\';a=e.3P;b=e.5r;c.11=\'1k\';c.T=f;c.2W=d}G{w:w,h:h,1D:a,hb:b}},6w:C(a){G{1D:a.3P||0,hb:a.5r||0}},a5:C(e){F h,w,de;if(e){w=e.83;h=e.7P}L{de=1c.4A;w=1P.bg||9z.bg||(de&&de.83)||1c.23.83;h=1P.bf||9z.bf||(de&&de.7P)||1c.23.7P}G{w:w,h:h}},5O:C(e){F t=0,l=0,w=0,h=0,iw=0,ih=0;if(e&&e.98.5u()!=\'23\'){t=e.2T;l=e.2P;w=e.be;h=e.bd;iw=0;ih=0}L{if(1c.4A){t=1c.4A.2T;l=1c.4A.2P;w=1c.4A.be;h=1c.4A.bd}L if(1c.23){t=1c.23.2T;l=1c.23.2P;w=1c.23.be;h=1c.23.bd}iw=9z.bg||1c.4A.83||1c.23.83||0;ih=9z.bf||1c.4A.7P||1c.23.7P||0}G{t:t,l:l,w:w,h:h,iw:iw,ih:ih}},b2:C(e,a){F c=A(e);F t=c.E(\'4M\')||\'\';F r=c.E(\'53\')||\'\';F b=c.E(\'4L\')||\'\';F l=c.E(\'4K\')||\'\';if(a)G{t:R(t)||0,r:R(r)||0,b:R(b)||0,l:R(l)};L G{t:t,r:r,b:b,l:l}},9y:C(e,a){F c=A(e);F t=c.E(\'5b\')||\'\';F r=c.E(\'5g\')||\'\';F b=c.E(\'4Q\')||\'\';F l=c.E(\'4F\')||\'\';if(a)G{t:R(t)||0,r:R(r)||0,b:R(b)||0,l:R(l)};L G{t:t,r:r,b:b,l:l}},6b:C(e,a){F c=A(e);F t=c.E(\'4x\')||\'\';F r=c.E(\'5i\')||\'\';F b=c.E(\'5d\')||\'\';F l=c.E(\'4y\')||\'\';if(a)G{t:R(t)||0,r:R(r)||0,b:R(b)||0,l:R(l)||0};L G{t:t,r:r,b:b,l:l}},3W:C(a){F x=a.iB||(a.iz+(1c.4A.2P||1c.23.2P))||0;F y=a.iy||(a.ix+(1c.4A.2T||1c.23.2T))||0;G{x:x,y:y}},bH:C(a,b){b(a);a=a.6M;6k(a){A.12.bH(a,b);a=a.iv}},ji:C(c){A.12.bH(c,C(a){1V(F b in a){if(28 a[b]===\'C\'){a[b]=P}}})},ir:C(a,b){F c=A.12.5O();F d=A.12.2f(a);if(!b||b==\'3K\')A(a).E({O:c.t+((Z.3g(c.h,c.ih)-c.t-d.hb)/2)+\'Q\'});if(!b||b==\'3Z\')A(a).E({M:c.l+((Z.3g(c.w,c.iw)-c.l-d.1D)/2)+\'Q\'})},iq:C(a,b){F c=A(\'3O[@2E*="7q"]\',a||1c),7q;c.1y(C(){7q=B.2E;B.2E=b;B.Y.4X="9x:9C.9E.ip(2E=\'"+7q+"\')"})}};[].3o||(6h.jn.3o=C(v,n){n=(n==P)?0:n;F m=B.1b;1V(F i=n;i= 0 ? '&' : '?') + q; + options.data = null; // data is null for 'get' + } + else + options.data = q; // data is the query string for 'post' + + var $form = this, callbacks = []; + if (options.resetForm) callbacks.push(function() { $form.resetForm(); }); + if (options.clearForm) callbacks.push(function() { $form.clearForm(); }); + + // perform a load on the target only if dataType is not provided + if (!options.dataType && options.target) { + var oldSuccess = options.success || function(){}; + callbacks.push(function(data) { + if (this.evalScripts) + $(options.target).attr("innerHTML", data).evalScripts().each(oldSuccess, arguments); + else // jQuery v1.1.4 + $(options.target).html(data).each(oldSuccess, arguments); + }); + } + else if (options.success) + callbacks.push(options.success); + + options.success = function(data, status) { + for (var i=0, max=callbacks.length; i < max; i++) + callbacks[i](data, status, $form); + }; + + // are there files to upload? + var files = $('input:file', this).fieldValue(); + var found = false; + for (var j=0; j < files.length; j++) + if (files[j]) + found = true; + + // options.iframe allows user to force iframe mode + if (options.iframe || found) { + // hack to fix Safari hang (thanks to Tim Molendijk for this) + // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d + if ($.browser.safari && options.closeKeepAlive) + $.get(options.closeKeepAlive, fileUpload); + else + fileUpload(); + } + else + $.ajax(options); + + // fire 'notify' event + $.event.trigger('form.submit.notify', [this, options]); + return this; + + + // private function for handling file uploads (hat tip to YAHOO!) + function fileUpload() { + var form = $form[0]; + var opts = $.extend({}, $.ajaxSettings, options); + + var id = 'jqFormIO' + $.fn.ajaxSubmit.counter++; + var $io = $(''); + this.iefix = $(this.update.id+'_iefix'); + } + if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); + }, + + fixIEOverlapping: function() { + Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); + this.iefix.style.zIndex = 1; + this.update.style.zIndex = 2; + Element.show(this.iefix); + }, + + hide: function() { + this.stopIndicator(); + if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); + if(this.iefix) Element.hide(this.iefix); + }, + + startIndicator: function() { + if(this.options.indicator) Element.show(this.options.indicator); + }, + + stopIndicator: function() { + if(this.options.indicator) Element.hide(this.options.indicator); + }, + + onKeyPress: function(event) { + if(this.active) + switch(event.keyCode) { + case Event.KEY_TAB: + case Event.KEY_RETURN: + this.selectEntry(); + Event.stop(event); + case Event.KEY_ESC: + this.hide(); + this.active = false; + Event.stop(event); + return; + case Event.KEY_LEFT: + case Event.KEY_RIGHT: + return; + case Event.KEY_UP: + this.markPrevious(); + this.render(); + if(Prototype.Browser.WebKit) Event.stop(event); + return; + case Event.KEY_DOWN: + this.markNext(); + this.render(); + if(Prototype.Browser.WebKit) Event.stop(event); + return; + } + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; + + this.changed = true; + this.hasFocus = true; + + if(this.observer) clearTimeout(this.observer); + this.observer = + setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); + }, + + activate: function() { + this.changed = false; + this.hasFocus = true; + this.getUpdatedChoices(); + }, + + onHover: function(event) { + var element = Event.findElement(event, 'LI'); + if(this.index != element.autocompleteIndex) + { + this.index = element.autocompleteIndex; + this.render(); + } + Event.stop(event); + }, + + onClick: function(event) { + var element = Event.findElement(event, 'LI'); + this.index = element.autocompleteIndex; + this.selectEntry(); + this.hide(); + }, + + onBlur: function(event) { + // needed to make click events working + setTimeout(this.hide.bind(this), 250); + this.hasFocus = false; + this.active = false; + }, + + render: function() { + if(this.entryCount > 0) { + for (var i = 0; i < this.entryCount; i++) + this.index==i ? + Element.addClassName(this.getEntry(i),"selected") : + Element.removeClassName(this.getEntry(i),"selected"); + if(this.hasFocus) { + this.show(); + this.active = true; + } + } else { + this.active = false; + this.hide(); + } + }, + + markPrevious: function() { + if(this.index > 0) this.index-- + else this.index = this.entryCount-1; + this.getEntry(this.index).scrollIntoView(true); + }, + + markNext: function() { + if(this.index < this.entryCount-1) this.index++ + else this.index = 0; + this.getEntry(this.index).scrollIntoView(false); + }, + + getEntry: function(index) { + return this.update.firstChild.childNodes[index]; + }, + + getCurrentEntry: function() { + return this.getEntry(this.index); + }, + + selectEntry: function() { + this.active = false; + this.updateElement(this.getCurrentEntry()); + }, + + updateElement: function(selectedElement) { + if (this.options.updateElement) { + this.options.updateElement(selectedElement); + return; + } + var value = ''; + if (this.options.select) { + var nodes = $(selectedElement).select('.' + this.options.select) || []; + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); + } else + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); + + var bounds = this.getTokenBounds(); + if (bounds[0] != -1) { + var newValue = this.element.value.substr(0, bounds[0]); + var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/); + if (whitespace) + newValue += whitespace[0]; + this.element.value = newValue + value + this.element.value.substr(bounds[1]); + } else { + this.element.value = value; + } + this.oldElementValue = this.element.value; + this.element.focus(); + + if (this.options.afterUpdateElement) + this.options.afterUpdateElement(this.element, selectedElement); + }, + + updateChoices: function(choices) { + if(!this.changed && this.hasFocus) { + this.update.innerHTML = choices; + Element.cleanWhitespace(this.update); + Element.cleanWhitespace(this.update.down()); + + if(this.update.firstChild && this.update.down().childNodes) { + this.entryCount = + this.update.down().childNodes.length; + for (var i = 0; i < this.entryCount; i++) { + var entry = this.getEntry(i); + entry.autocompleteIndex = i; + this.addObservers(entry); + } + } else { + this.entryCount = 0; + } + + this.stopIndicator(); + this.index = 0; + + if(this.entryCount==1 && this.options.autoSelect) { + this.selectEntry(); + this.hide(); + } else { + this.render(); + } + } + }, + + addObservers: function(element) { + Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); + Event.observe(element, "click", this.onClick.bindAsEventListener(this)); + }, + + onObserverEvent: function() { + this.changed = false; + this.tokenBounds = null; + if(this.getToken().length>=this.options.minChars) { + this.getUpdatedChoices(); + } else { + this.active = false; + this.hide(); + } + this.oldElementValue = this.element.value; + }, + + getToken: function() { + var bounds = this.getTokenBounds(); + return this.element.value.substring(bounds[0], bounds[1]).strip(); + }, + + getTokenBounds: function() { + if (null != this.tokenBounds) return this.tokenBounds; + var value = this.element.value; + if (value.strip().empty()) return [-1, 0]; + var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue); + var offset = (diff == this.oldElementValue.length ? 1 : 0); + var prevTokenPos = -1, nextTokenPos = value.length; + var tp; + for (var index = 0, l = this.options.tokens.length; index < l; ++index) { + tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1); + if (tp > prevTokenPos) prevTokenPos = tp; + tp = value.indexOf(this.options.tokens[index], diff + offset); + if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp; + } + return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]); + } +}); + +Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) { + var boundary = Math.min(newS.length, oldS.length); + for (var index = 0; index < boundary; ++index) + if (newS[index] != oldS[index]) + return index; + return boundary; +}; + +Ajax.Autocompleter = Class.create(Autocompleter.Base, { + initialize: function(element, update, url, options) { + this.baseInitialize(element, update, options); + this.options.asynchronous = true; + this.options.onComplete = this.onComplete.bind(this); + this.options.defaultParams = this.options.parameters || null; + this.url = url; + }, + + getUpdatedChoices: function() { + this.startIndicator(); + + var entry = encodeURIComponent(this.options.paramName) + '=' + + encodeURIComponent(this.getToken()); + + this.options.parameters = this.options.callback ? + this.options.callback(this.element, entry) : entry; + + if(this.options.defaultParams) + this.options.parameters += '&' + this.options.defaultParams; + + new Ajax.Request(this.url, this.options); + }, + + onComplete: function(request) { + this.updateChoices(request.responseText); + } +}); + +// The local array autocompleter. Used when you'd prefer to +// inject an array of autocompletion options into the page, rather +// than sending out Ajax queries, which can be quite slow sometimes. +// +// The constructor takes four parameters. The first two are, as usual, +// the id of the monitored textbox, and id of the autocompletion menu. +// The third is the array you want to autocomplete from, and the fourth +// is the options block. +// +// Extra local autocompletion options: +// - choices - How many autocompletion choices to offer +// +// - partialSearch - If false, the autocompleter will match entered +// text only at the beginning of strings in the +// autocomplete array. Defaults to true, which will +// match text at the beginning of any *word* in the +// strings in the autocomplete array. If you want to +// search anywhere in the string, additionally set +// the option fullSearch to true (default: off). +// +// - fullSsearch - Search anywhere in autocomplete array strings. +// +// - partialChars - How many characters to enter before triggering +// a partial match (unlike minChars, which defines +// how many characters are required to do any match +// at all). Defaults to 2. +// +// - ignoreCase - Whether to ignore case when autocompleting. +// Defaults to true. +// +// It's possible to pass in a custom function as the 'selector' +// option, if you prefer to write your own autocompletion logic. +// In that case, the other options above will not apply unless +// you support them. + +Autocompleter.Local = Class.create(Autocompleter.Base, { + initialize: function(element, update, array, options) { + this.baseInitialize(element, update, options); + this.options.array = array; + }, + + getUpdatedChoices: function() { + this.updateChoices(this.options.selector(this)); + }, + + setOptions: function(options) { + this.options = Object.extend({ + choices: 10, + partialSearch: true, + partialChars: 2, + ignoreCase: true, + fullSearch: false, + selector: function(instance) { + var ret = []; // Beginning matches + var partial = []; // Inside matches + var entry = instance.getToken(); + var count = 0; + + for (var i = 0; i < instance.options.array.length && + ret.length < instance.options.choices ; i++) { + + var elem = instance.options.array[i]; + var foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase()) : + elem.indexOf(entry); + + while (foundPos != -1) { + if (foundPos == 0 && elem.length != entry.length) { + ret.push("
  • " + elem.substr(0, entry.length) + "" + + elem.substr(entry.length) + "
  • "); + break; + } else if (entry.length >= instance.options.partialChars && + instance.options.partialSearch && foundPos != -1) { + if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { + partial.push("
  • " + elem.substr(0, foundPos) + "" + + elem.substr(foundPos, entry.length) + "" + elem.substr( + foundPos + entry.length) + "
  • "); + break; + } + } + + foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : + elem.indexOf(entry, foundPos + 1); + + } + } + if (partial.length) + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)) + return "
      " + ret.join('') + "
    "; + } + }, options || { }); + } +}); + +// AJAX in-place editor and collection editor +// Full rewrite by Christophe Porteneuve (April 2007). + +// Use this if you notice weird scrolling problems on some browsers, +// the DOM might be a bit confused when this gets called so do this +// waits 1 ms (with setTimeout) until it does the activation +Field.scrollFreeActivate = function(field) { + setTimeout(function() { + Field.activate(field); + }, 1); +} + +Ajax.InPlaceEditor = Class.create({ + initialize: function(element, url, options) { + this.url = url; + this.element = element = $(element); + this.prepareOptions(); + this._controls = { }; + arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!! + Object.extend(this.options, options || { }); + if (!this.options.formId && this.element.id) { + this.options.formId = this.element.id + '-inplaceeditor'; + if ($(this.options.formId)) + this.options.formId = ''; + } + if (this.options.externalControl) + this.options.externalControl = $(this.options.externalControl); + if (!this.options.externalControl) + this.options.externalControlOnly = false; + this._originalBackground = this.element.getStyle('background-color') || 'transparent'; + this.element.title = this.options.clickToEditText; + this._boundCancelHandler = this.handleFormCancellation.bind(this); + this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this); + this._boundFailureHandler = this.handleAJAXFailure.bind(this); + this._boundSubmitHandler = this.handleFormSubmission.bind(this); + this._boundWrapperHandler = this.wrapUp.bind(this); + this.registerListeners(); + }, + checkForEscapeOrReturn: function(e) { + if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return; + if (Event.KEY_ESC == e.keyCode) + this.handleFormCancellation(e); + else if (Event.KEY_RETURN == e.keyCode) + this.handleFormSubmission(e); + }, + createControl: function(mode, handler, extraClasses) { + var control = this.options[mode + 'Control']; + var text = this.options[mode + 'Text']; + if ('button' == control) { + var btn = document.createElement('input'); + btn.type = 'submit'; + btn.value = text; + btn.className = 'editor_' + mode + '_button'; + if ('cancel' == mode) + btn.onclick = this._boundCancelHandler; + this._form.appendChild(btn); + this._controls[mode] = btn; + } else if ('link' == control) { + var link = document.createElement('a'); + link.href = '#'; + link.appendChild(document.createTextNode(text)); + link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler; + link.className = 'editor_' + mode + '_link'; + if (extraClasses) + link.className += ' ' + extraClasses; + this._form.appendChild(link); + this._controls[mode] = link; + } + }, + createEditField: function() { + var text = (this.options.loadTextURL ? this.options.loadingText : this.getText()); + var fld; + if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) { + fld = document.createElement('input'); + fld.type = 'text'; + var size = this.options.size || this.options.cols || 0; + if (0 < size) fld.size = size; + } else { + fld = document.createElement('textarea'); + fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows); + fld.cols = this.options.cols || 40; + } + fld.name = this.options.paramName; + fld.value = text; // No HTML breaks conversion anymore + fld.className = 'editor_field'; + if (this.options.submitOnBlur) + fld.onblur = this._boundSubmitHandler; + this._controls.editor = fld; + if (this.options.loadTextURL) + this.loadExternalText(); + this._form.appendChild(this._controls.editor); + }, + createForm: function() { + var ipe = this; + function addText(mode, condition) { + var text = ipe.options['text' + mode + 'Controls']; + if (!text || condition === false) return; + ipe._form.appendChild(document.createTextNode(text)); + }; + this._form = $(document.createElement('form')); + this._form.id = this.options.formId; + this._form.addClassName(this.options.formClassName); + this._form.onsubmit = this._boundSubmitHandler; + this.createEditField(); + if ('textarea' == this._controls.editor.tagName.toLowerCase()) + this._form.appendChild(document.createElement('br')); + if (this.options.onFormCustomization) + this.options.onFormCustomization(this, this._form); + addText('Before', this.options.okControl || this.options.cancelControl); + this.createControl('ok', this._boundSubmitHandler); + addText('Between', this.options.okControl && this.options.cancelControl); + this.createControl('cancel', this._boundCancelHandler, 'editor_cancel'); + addText('After', this.options.okControl || this.options.cancelControl); + }, + destroy: function() { + if (this._oldInnerHTML) + this.element.innerHTML = this._oldInnerHTML; + this.leaveEditMode(); + this.unregisterListeners(); + }, + enterEditMode: function(e) { + if (this._saving || this._editing) return; + this._editing = true; + this.triggerCallback('onEnterEditMode'); + if (this.options.externalControl) + this.options.externalControl.hide(); + this.element.hide(); + this.createForm(); + this.element.parentNode.insertBefore(this._form, this.element); + if (!this.options.loadTextURL) + this.postProcessEditField(); + if (e) Event.stop(e); + }, + enterHover: function(e) { + if (this.options.hoverClassName) + this.element.addClassName(this.options.hoverClassName); + if (this._saving) return; + this.triggerCallback('onEnterHover'); + }, + getText: function() { + return this.element.innerHTML; + }, + handleAJAXFailure: function(transport) { + this.triggerCallback('onFailure', transport); + if (this._oldInnerHTML) { + this.element.innerHTML = this._oldInnerHTML; + this._oldInnerHTML = null; + } + }, + handleFormCancellation: function(e) { + this.wrapUp(); + if (e) Event.stop(e); + }, + handleFormSubmission: function(e) { + var form = this._form; + var value = $F(this._controls.editor); + this.prepareSubmission(); + var params = this.options.callback(form, value) || ''; + if (Object.isString(params)) + params = params.toQueryParams(); + params.editorId = this.element.id; + if (this.options.htmlResponse) { + var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions); + Object.extend(options, { + parameters: params, + onComplete: this._boundWrapperHandler, + onFailure: this._boundFailureHandler + }); + new Ajax.Updater({ success: this.element }, this.url, options); + } else { + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: params, + onComplete: this._boundWrapperHandler, + onFailure: this._boundFailureHandler + }); + new Ajax.Request(this.url, options); + } + if (e) Event.stop(e); + }, + leaveEditMode: function() { + this.element.removeClassName(this.options.savingClassName); + this.removeForm(); + this.leaveHover(); + this.element.style.backgroundColor = this._originalBackground; + this.element.show(); + if (this.options.externalControl) + this.options.externalControl.show(); + this._saving = false; + this._editing = false; + this._oldInnerHTML = null; + this.triggerCallback('onLeaveEditMode'); + }, + leaveHover: function(e) { + if (this.options.hoverClassName) + this.element.removeClassName(this.options.hoverClassName); + if (this._saving) return; + this.triggerCallback('onLeaveHover'); + }, + loadExternalText: function() { + this._form.addClassName(this.options.loadingClassName); + this._controls.editor.disabled = true; + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + this._form.removeClassName(this.options.loadingClassName); + var text = transport.responseText; + if (this.options.stripLoadedTextTags) + text = text.stripTags(); + this._controls.editor.value = text; + this._controls.editor.disabled = false; + this.postProcessEditField(); + }.bind(this), + onFailure: this._boundFailureHandler + }); + new Ajax.Request(this.options.loadTextURL, options); + }, + postProcessEditField: function() { + var fpc = this.options.fieldPostCreation; + if (fpc) + $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate'](); + }, + prepareOptions: function() { + this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions); + Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks); + [this._extraDefaultOptions].flatten().compact().each(function(defs) { + Object.extend(this.options, defs); + }.bind(this)); + }, + prepareSubmission: function() { + this._saving = true; + this.removeForm(); + this.leaveHover(); + this.showSaving(); + }, + registerListeners: function() { + this._listeners = { }; + var listener; + $H(Ajax.InPlaceEditor.Listeners).each(function(pair) { + listener = this[pair.value].bind(this); + this._listeners[pair.key] = listener; + if (!this.options.externalControlOnly) + this.element.observe(pair.key, listener); + if (this.options.externalControl) + this.options.externalControl.observe(pair.key, listener); + }.bind(this)); + }, + removeForm: function() { + if (!this._form) return; + this._form.remove(); + this._form = null; + this._controls = { }; + }, + showSaving: function() { + this._oldInnerHTML = this.element.innerHTML; + this.element.innerHTML = this.options.savingText; + this.element.addClassName(this.options.savingClassName); + this.element.style.backgroundColor = this._originalBackground; + this.element.show(); + }, + triggerCallback: function(cbName, arg) { + if ('function' == typeof this.options[cbName]) { + this.options[cbName](this, arg); + } + }, + unregisterListeners: function() { + $H(this._listeners).each(function(pair) { + if (!this.options.externalControlOnly) + this.element.stopObserving(pair.key, pair.value); + if (this.options.externalControl) + this.options.externalControl.stopObserving(pair.key, pair.value); + }.bind(this)); + }, + wrapUp: function(transport) { + this.leaveEditMode(); + // Can't use triggerCallback due to backward compatibility: requires + // binding + direct element + this._boundComplete(transport, this.element); + } +}); + +Object.extend(Ajax.InPlaceEditor.prototype, { + dispose: Ajax.InPlaceEditor.prototype.destroy +}); + +Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { + initialize: function($super, element, url, options) { + this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions; + $super(element, url, options); + }, + + createEditField: function() { + var list = document.createElement('select'); + list.name = this.options.paramName; + list.size = 1; + this._controls.editor = list; + this._collection = this.options.collection || []; + if (this.options.loadCollectionURL) + this.loadCollection(); + else + this.checkForExternalText(); + this._form.appendChild(this._controls.editor); + }, + + loadCollection: function() { + this._form.addClassName(this.options.loadingClassName); + this.showLoadingText(this.options.loadingCollectionText); + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + var js = transport.responseText.strip(); + if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check + throw 'Server returned an invalid collection representation.'; + this._collection = eval(js); + this.checkForExternalText(); + }.bind(this), + onFailure: this.onFailure + }); + new Ajax.Request(this.options.loadCollectionURL, options); + }, + + showLoadingText: function(text) { + this._controls.editor.disabled = true; + var tempOption = this._controls.editor.firstChild; + if (!tempOption) { + tempOption = document.createElement('option'); + tempOption.value = ''; + this._controls.editor.appendChild(tempOption); + tempOption.selected = true; + } + tempOption.update((text || '').stripScripts().stripTags()); + }, + + checkForExternalText: function() { + this._text = this.getText(); + if (this.options.loadTextURL) + this.loadExternalText(); + else + this.buildOptionList(); + }, + + loadExternalText: function() { + this.showLoadingText(this.options.loadingText); + var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); + Object.extend(options, { + parameters: 'editorId=' + encodeURIComponent(this.element.id), + onComplete: Prototype.emptyFunction, + onSuccess: function(transport) { + this._text = transport.responseText.strip(); + this.buildOptionList(); + }.bind(this), + onFailure: this.onFailure + }); + new Ajax.Request(this.options.loadTextURL, options); + }, + + buildOptionList: function() { + this._form.removeClassName(this.options.loadingClassName); + this._collection = this._collection.map(function(entry) { + return 2 === entry.length ? entry : [entry, entry].flatten(); + }); + var marker = ('value' in this.options) ? this.options.value : this._text; + var textFound = this._collection.any(function(entry) { + return entry[0] == marker; + }.bind(this)); + this._controls.editor.update(''); + var option; + this._collection.each(function(entry, index) { + option = document.createElement('option'); + option.value = entry[0]; + option.selected = textFound ? entry[0] == marker : 0 == index; + option.appendChild(document.createTextNode(entry[1])); + this._controls.editor.appendChild(option); + }.bind(this)); + this._controls.editor.disabled = false; + Field.scrollFreeActivate(this._controls.editor); + } +}); + +//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! **** +//**** This only exists for a while, in order to let **** +//**** users adapt to the new API. Read up on the new **** +//**** API and convert your code to it ASAP! **** + +Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) { + if (!options) return; + function fallback(name, expr) { + if (name in options || expr === undefined) return; + options[name] = expr; + }; + fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' : + options.cancelLink == options.cancelButton == false ? false : undefined))); + fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' : + options.okLink == options.okButton == false ? false : undefined))); + fallback('highlightColor', options.highlightcolor); + fallback('highlightEndColor', options.highlightendcolor); +}; + +Object.extend(Ajax.InPlaceEditor, { + DefaultOptions: { + ajaxOptions: { }, + autoRows: 3, // Use when multi-line w/ rows == 1 + cancelControl: 'link', // 'link'|'button'|false + cancelText: 'cancel', + clickToEditText: 'Click to edit', + externalControl: null, // id|elt + externalControlOnly: false, + fieldPostCreation: 'activate', // 'activate'|'focus'|false + formClassName: 'inplaceeditor-form', + formId: null, // id|elt + highlightColor: '#ffff99', + highlightEndColor: '#ffffff', + hoverClassName: '', + htmlResponse: true, + loadingClassName: 'inplaceeditor-loading', + loadingText: 'Loading...', + okControl: 'button', // 'link'|'button'|false + okText: 'ok', + paramName: 'value', + rows: 1, // If 1 and multi-line, uses autoRows + savingClassName: 'inplaceeditor-saving', + savingText: 'Saving...', + size: 0, + stripLoadedTextTags: false, + submitOnBlur: false, + textAfterControls: '', + textBeforeControls: '', + textBetweenControls: '' + }, + DefaultCallbacks: { + callback: function(form) { + return Form.serialize(form); + }, + onComplete: function(transport, element) { + // For backward compatibility, this one is bound to the IPE, and passes + // the element directly. It was too often customized, so we don't break it. + new Effect.Highlight(element, { + startcolor: this.options.highlightColor, keepBackgroundImage: true }); + }, + onEnterEditMode: null, + onEnterHover: function(ipe) { + ipe.element.style.backgroundColor = ipe.options.highlightColor; + if (ipe._effect) + ipe._effect.cancel(); + }, + onFailure: function(transport, ipe) { + alert('Error communication with the server: ' + transport.responseText.stripTags()); + }, + onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls. + onLeaveEditMode: null, + onLeaveHover: function(ipe) { + ipe._effect = new Effect.Highlight(ipe.element, { + startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor, + restorecolor: ipe._originalBackground, keepBackgroundImage: true + }); + } + }, + Listeners: { + click: 'enterEditMode', + keydown: 'checkForEscapeOrReturn', + mouseover: 'enterHover', + mouseout: 'leaveHover' + } +}); + +Ajax.InPlaceCollectionEditor.DefaultOptions = { + loadingCollectionText: 'Loading options...' +}; + +// Delayed observer, like Form.Element.Observer, +// but waits for delay after last key input +// Ideal for live-search fields + +Form.Element.DelayedObserver = Class.create({ + initialize: function(element, delay, callback) { + this.delay = delay || 0.5; + this.element = $(element); + this.callback = callback; + this.timer = null; + this.lastValue = $F(this.element); + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); + }, + delayedListener: function(event) { + if(this.lastValue == $F(this.element)) return; + if(this.timer) clearTimeout(this.timer); + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); + this.lastValue = $F(this.element); + }, + onTimerEvent: function() { + this.timer = null; + this.callback(this.element, $F(this.element)); + } +}); diff --git a/wp-includes/js/scriptaculous/dragdrop.js b/wp-includes/js/scriptaculous/dragdrop.js new file mode 100644 index 0000000..14ebc6f --- /dev/null +++ b/wp-includes/js/scriptaculous/dragdrop.js @@ -0,0 +1,974 @@ +// script.aculo.us dragdrop.js v1.8.0, Tue Nov 06 15:01:40 +0300 2007 + +// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +if(Object.isUndefined(Effect)) + throw("dragdrop.js requires including script.aculo.us' effects.js library"); + +var Droppables = { + drops: [], + + remove: function(element) { + this.drops = this.drops.reject(function(d) { return d.element==$(element) }); + }, + + add: function(element) { + element = $(element); + var options = Object.extend({ + greedy: true, + hoverclass: null, + tree: false + }, arguments[1] || { }); + + // cache containers + if(options.containment) { + options._containers = []; + var containment = options.containment; + if(Object.isArray(containment)) { + containment.each( function(c) { options._containers.push($(c)) }); + } else { + options._containers.push($(containment)); + } + } + + if(options.accept) options.accept = [options.accept].flatten(); + + Element.makePositioned(element); // fix IE + options.element = element; + + this.drops.push(options); + }, + + findDeepestChild: function(drops) { + deepest = drops[0]; + + for (i = 1; i < drops.length; ++i) + if (Element.isParent(drops[i].element, deepest.element)) + deepest = drops[i]; + + return deepest; + }, + + isContained: function(element, drop) { + var containmentNode; + if(drop.tree) { + containmentNode = element.treeNode; + } else { + containmentNode = element.parentNode; + } + return drop._containers.detect(function(c) { return containmentNode == c }); + }, + + isAffected: function(point, element, drop) { + return ( + (drop.element!=element) && + ((!drop._containers) || + this.isContained(element, drop)) && + ((!drop.accept) || + (Element.classNames(element).detect( + function(v) { return drop.accept.include(v) } ) )) && + Position.within(drop.element, point[0], point[1]) ); + }, + + deactivate: function(drop) { + if(drop.hoverclass) + Element.removeClassName(drop.element, drop.hoverclass); + this.last_active = null; + }, + + activate: function(drop) { + if(drop.hoverclass) + Element.addClassName(drop.element, drop.hoverclass); + this.last_active = drop; + }, + + show: function(point, element) { + if(!this.drops.length) return; + var drop, affected = []; + + this.drops.each( function(drop) { + if(Droppables.isAffected(point, element, drop)) + affected.push(drop); + }); + + if(affected.length>0) + drop = Droppables.findDeepestChild(affected); + + if(this.last_active && this.last_active != drop) this.deactivate(this.last_active); + if (drop) { + Position.within(drop.element, point[0], point[1]); + if(drop.onHover) + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); + + if (drop != this.last_active) Droppables.activate(drop); + } + }, + + fire: function(event, element) { + if(!this.last_active) return; + Position.prepare(); + + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) + if (this.last_active.onDrop) { + this.last_active.onDrop(element, this.last_active.element, event); + return true; + } + }, + + reset: function() { + if(this.last_active) + this.deactivate(this.last_active); + } +} + +var Draggables = { + drags: [], + observers: [], + + register: function(draggable) { + if(this.drags.length == 0) { + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.updateDrag.bindAsEventListener(this); + this.eventKeypress = this.keyPress.bindAsEventListener(this); + + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + Event.observe(document, "keypress", this.eventKeypress); + } + this.drags.push(draggable); + }, + + unregister: function(draggable) { + this.drags = this.drags.reject(function(d) { return d==draggable }); + if(this.drags.length == 0) { + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + Event.stopObserving(document, "keypress", this.eventKeypress); + } + }, + + activate: function(draggable) { + if(draggable.options.delay) { + this._timeout = setTimeout(function() { + Draggables._timeout = null; + window.focus(); + Draggables.activeDraggable = draggable; + }.bind(this), draggable.options.delay); + } else { + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari + this.activeDraggable = draggable; + } + }, + + deactivate: function() { + this.activeDraggable = null; + }, + + updateDrag: function(event) { + if(!this.activeDraggable) return; + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + // Mozilla-based browsers fire successive mousemove events with + // the same coordinates, prevent needless redrawing (moz bug?) + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; + this._lastPointer = pointer; + + this.activeDraggable.updateDrag(event, pointer); + }, + + endDrag: function(event) { + if(this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; + } + if(!this.activeDraggable) return; + this._lastPointer = null; + this.activeDraggable.endDrag(event); + this.activeDraggable = null; + }, + + keyPress: function(event) { + if(this.activeDraggable) + this.activeDraggable.keyPress(event); + }, + + addObserver: function(observer) { + this.observers.push(observer); + this._cacheObserverCallbacks(); + }, + + removeObserver: function(element) { // element instead of observer fixes mem leaks + this.observers = this.observers.reject( function(o) { return o.element==element }); + this._cacheObserverCallbacks(); + }, + + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' + if(this[eventName+'Count'] > 0) + this.observers.each( function(o) { + if(o[eventName]) o[eventName](eventName, draggable, event); + }); + if(draggable.options[eventName]) draggable.options[eventName](draggable, event); + }, + + _cacheObserverCallbacks: function() { + ['onStart','onEnd','onDrag'].each( function(eventName) { + Draggables[eventName+'Count'] = Draggables.observers.select( + function(o) { return o[eventName]; } + ).length; + }); + } +} + +/*--------------------------------------------------------------------------*/ + +var Draggable = Class.create({ + initialize: function(element) { + var defaults = { + handle: false, + reverteffect: function(element, top_offset, left_offset) { + var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; + new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, + queue: {scope:'_draggable', position:'end'} + }); + }, + endeffect: function(element) { + var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, + queue: {scope:'_draggable', position:'end'}, + afterFinish: function(){ + Draggable._dragging[element] = false + } + }); + }, + zindex: 1000, + revert: false, + quiet: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } + delay: 0 + }; + + if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) + Object.extend(defaults, { + starteffect: function(element) { + element._opacity = Element.getOpacity(element); + Draggable._dragging[element] = true; + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + } + }); + + var options = Object.extend(defaults, arguments[1] || { }); + + this.element = $(element); + + if(options.handle && Object.isString(options.handle)) + this.handle = this.element.down('.'+options.handle, 0); + + if(!this.handle) this.handle = $(options.handle); + if(!this.handle) this.handle = this.element; + + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { + options.scroll = $(options.scroll); + this._isScrollChild = Element.childOf(this.element, options.scroll); + } + + Element.makePositioned(this.element); // fix IE + + this.options = options; + this.dragging = false; + + this.eventMouseDown = this.initDrag.bindAsEventListener(this); + Event.observe(this.handle, "mousedown", this.eventMouseDown); + + Draggables.register(this); + }, + + destroy: function() { + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); + Draggables.unregister(this); + }, + + currentDelta: function() { + return([ + parseInt(Element.getStyle(this.element,'left') || '0'), + parseInt(Element.getStyle(this.element,'top') || '0')]); + }, + + initDrag: function(event) { + if(!Object.isUndefined(Draggable._dragging[this.element]) && + Draggable._dragging[this.element]) return; + if(Event.isLeftClick(event)) { + // abort on form elements, fixes a Firefox issue + var src = Event.element(event); + if((tag_name = src.tagName.toUpperCase()) && ( + tag_name=='INPUT' || + tag_name=='SELECT' || + tag_name=='OPTION' || + tag_name=='BUTTON' || + tag_name=='TEXTAREA')) return; + + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var pos = Position.cumulativeOffset(this.element); + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); + + Draggables.activate(this); + Event.stop(event); + } + }, + + startDrag: function(event) { + this.dragging = true; + if(!this.delta) + this.delta = this.currentDelta(); + + if(this.options.zindex) { + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); + this.element.style.zIndex = this.options.zindex; + } + + if(this.options.ghosting) { + this._clone = this.element.cloneNode(true); + this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); + if (!this.element._originallyAbsolute) + Position.absolutize(this.element); + this.element.parentNode.insertBefore(this._clone, this.element); + } + + if(this.options.scroll) { + if (this.options.scroll == window) { + var where = this._getWindowScroll(this.options.scroll); + this.originalScrollLeft = where.left; + this.originalScrollTop = where.top; + } else { + this.originalScrollLeft = this.options.scroll.scrollLeft; + this.originalScrollTop = this.options.scroll.scrollTop; + } + } + + Draggables.notify('onStart', this, event); + + if(this.options.starteffect) this.options.starteffect(this.element); + }, + + updateDrag: function(event, pointer) { + if(!this.dragging) this.startDrag(event); + + if(!this.options.quiet){ + Position.prepare(); + Droppables.show(pointer, this.element); + } + + Draggables.notify('onDrag', this, event); + + this.draw(pointer); + if(this.options.change) this.options.change(this); + + if(this.options.scroll) { + this.stopScrolling(); + + var p; + if (this.options.scroll == window) { + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } + } else { + p = Position.page(this.options.scroll); + p[0] += this.options.scroll.scrollLeft + Position.deltaX; + p[1] += this.options.scroll.scrollTop + Position.deltaY; + p.push(p[0]+this.options.scroll.offsetWidth); + p.push(p[1]+this.options.scroll.offsetHeight); + } + var speed = [0,0]; + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); + this.startScrolling(speed); + } + + // fix AppleWebKit rendering + if(Prototype.Browser.WebKit) window.scrollBy(0,0); + + Event.stop(event); + }, + + finishDrag: function(event, success) { + this.dragging = false; + + if(this.options.quiet){ + Position.prepare(); + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + Droppables.show(pointer, this.element); + } + + if(this.options.ghosting) { + if (!this.element._originallyAbsolute) + Position.relativize(this.element); + delete this.element._originallyAbsolute; + Element.remove(this._clone); + this._clone = null; + } + + var dropped = false; + if(success) { + dropped = Droppables.fire(event, this.element); + if (!dropped) dropped = false; + } + if(dropped && this.options.onDropped) this.options.onDropped(this.element); + Draggables.notify('onEnd', this, event); + + var revert = this.options.revert; + if(revert && Object.isFunction(revert)) revert = revert(this.element); + + var d = this.currentDelta(); + if(revert && this.options.reverteffect) { + if (dropped == 0 || revert != 'failure') + this.options.reverteffect(this.element, + d[1]-this.delta[1], d[0]-this.delta[0]); + } else { + this.delta = d; + } + + if(this.options.zindex) + this.element.style.zIndex = this.originalZ; + + if(this.options.endeffect) + this.options.endeffect(this.element); + + Draggables.deactivate(this); + Droppables.reset(); + }, + + keyPress: function(event) { + if(event.keyCode!=Event.KEY_ESC) return; + this.finishDrag(event, false); + Event.stop(event); + }, + + endDrag: function(event) { + if(!this.dragging) return; + this.stopScrolling(); + this.finishDrag(event, true); + Event.stop(event); + }, + + draw: function(point) { + var pos = Position.cumulativeOffset(this.element); + if(this.options.ghosting) { + var r = Position.realOffset(this.element); + pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; + } + + var d = this.currentDelta(); + pos[0] -= d[0]; pos[1] -= d[1]; + + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; + } + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]) + }.bind(this)); + + if(this.options.snap) { + if(Object.isFunction(this.options.snap)) { + p = this.options.snap(p[0],p[1],this); + } else { + if(Object.isArray(this.options.snap)) { + p = p.map( function(v, i) { + return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)) + } else { + p = p.map( function(v) { + return (v/this.options.snap).round()*this.options.snap }.bind(this)) + } + }} + + var style = this.element.style; + if((!this.options.constraint) || (this.options.constraint=='horizontal')) + style.left = p[0] + "px"; + if((!this.options.constraint) || (this.options.constraint=='vertical')) + style.top = p[1] + "px"; + + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering + }, + + stopScrolling: function() { + if(this.scrollInterval) { + clearInterval(this.scrollInterval); + this.scrollInterval = null; + Draggables._lastScrollPointer = null; + } + }, + + startScrolling: function(speed) { + if(!(speed[0] || speed[1])) return; + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; + this.lastScrolled = new Date(); + this.scrollInterval = setInterval(this.scroll.bind(this), 10); + }, + + scroll: function() { + var current = new Date(); + var delta = current - this.lastScrolled; + this.lastScrolled = current; + if(this.options.scroll == window) { + with (this._getWindowScroll(this.options.scroll)) { + if (this.scrollSpeed[0] || this.scrollSpeed[1]) { + var d = delta / 1000; + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); + } + } + } else { + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; + } + + Position.prepare(); + Droppables.show(Draggables._lastPointer, this.element); + Draggables.notify('onDrag', this); + if (this._isScrollChild) { + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; + if (Draggables._lastScrollPointer[0] < 0) + Draggables._lastScrollPointer[0] = 0; + if (Draggables._lastScrollPointer[1] < 0) + Draggables._lastScrollPointer[1] = 0; + this.draw(Draggables._lastScrollPointer); + } + + if(this.options.change) this.options.change(this); + }, + + _getWindowScroll: function(w) { + var T, L, W, H; + with (w.document) { + if (w.document.documentElement && documentElement.scrollTop) { + T = documentElement.scrollTop; + L = documentElement.scrollLeft; + } else if (w.document.body) { + T = body.scrollTop; + L = body.scrollLeft; + } + if (w.innerWidth) { + W = w.innerWidth; + H = w.innerHeight; + } else if (w.document.documentElement && documentElement.clientWidth) { + W = documentElement.clientWidth; + H = documentElement.clientHeight; + } else { + W = body.offsetWidth; + H = body.offsetHeight + } + } + return { top: T, left: L, width: W, height: H }; + } +}); + +Draggable._dragging = { }; + +/*--------------------------------------------------------------------------*/ + +var SortableObserver = Class.create({ + initialize: function(element, observer) { + this.element = $(element); + this.observer = observer; + this.lastValue = Sortable.serialize(this.element); + }, + + onStart: function() { + this.lastValue = Sortable.serialize(this.element); + }, + + onEnd: function() { + Sortable.unmark(); + if(this.lastValue != Sortable.serialize(this.element)) + this.observer(this.element) + } +}); + +var Sortable = { + SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, + + sortables: { }, + + _findRootElement: function(element) { + while (element.tagName.toUpperCase() != "BODY") { + if(element.id && Sortable.sortables[element.id]) return element; + element = element.parentNode; + } + }, + + options: function(element) { + element = Sortable._findRootElement($(element)); + if(!element) return; + return Sortable.sortables[element.id]; + }, + + destroy: function(element){ + var s = Sortable.options(element); + + if(s) { + Draggables.removeObserver(s.element); + s.droppables.each(function(d){ Droppables.remove(d) }); + s.draggables.invoke('destroy'); + + delete Sortable.sortables[s.element.id]; + } + }, + + create: function(element) { + element = $(element); + var options = Object.extend({ + element: element, + tag: 'li', // assumes li children, override with tag: 'tagname' + dropOnEmpty: false, + tree: false, + treeTag: 'ul', + overlap: 'vertical', // one of 'vertical', 'horizontal' + constraint: 'vertical', // one of 'vertical', 'horizontal', false + containment: element, // also takes array of elements (or id's); or false + handle: false, // or a CSS class + only: false, + delay: 0, + hoverclass: null, + ghosting: false, + quiet: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + format: this.SERIALIZE_RULE, + + // these take arrays of elements or ids and can be + // used for better initialization performance + elements: false, + handles: false, + + onChange: Prototype.emptyFunction, + onUpdate: Prototype.emptyFunction + }, arguments[1] || { }); + + // clear any old sortable with same element + this.destroy(element); + + // build options for the draggables + var options_for_draggable = { + revert: true, + quiet: options.quiet, + scroll: options.scroll, + scrollSpeed: options.scrollSpeed, + scrollSensitivity: options.scrollSensitivity, + delay: options.delay, + ghosting: options.ghosting, + constraint: options.constraint, + handle: options.handle }; + + if(options.starteffect) + options_for_draggable.starteffect = options.starteffect; + + if(options.reverteffect) + options_for_draggable.reverteffect = options.reverteffect; + else + if(options.ghosting) options_for_draggable.reverteffect = function(element) { + element.style.top = 0; + element.style.left = 0; + }; + + if(options.endeffect) + options_for_draggable.endeffect = options.endeffect; + + if(options.zindex) + options_for_draggable.zindex = options.zindex; + + // build options for the droppables + var options_for_droppable = { + overlap: options.overlap, + containment: options.containment, + tree: options.tree, + hoverclass: options.hoverclass, + onHover: Sortable.onHover + } + + var options_for_tree = { + onHover: Sortable.onEmptyHover, + overlap: options.overlap, + containment: options.containment, + hoverclass: options.hoverclass + } + + // fix for gecko engine + Element.cleanWhitespace(element); + + options.draggables = []; + options.droppables = []; + + // drop on empty handling + if(options.dropOnEmpty || options.tree) { + Droppables.add(element, options_for_tree); + options.droppables.push(element); + } + + (options.elements || this.findElements(element, options) || []).each( function(e,i) { + var handle = options.handles ? $(options.handles[i]) : + (options.handle ? $(e).select('.' + options.handle)[0] : e); + options.draggables.push( + new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); + Droppables.add(e, options_for_droppable); + if(options.tree) e.treeNode = element; + options.droppables.push(e); + }); + + if(options.tree) { + (Sortable.findTreeElements(element, options) || []).each( function(e) { + Droppables.add(e, options_for_tree); + e.treeNode = element; + options.droppables.push(e); + }); + } + + // keep reference + this.sortables[element.id] = options; + + // for onupdate + Draggables.addObserver(new SortableObserver(element, options.onUpdate)); + + }, + + // return all suitable-for-sortable elements in a guaranteed order + findElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.tag); + }, + + findTreeElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.treeTag); + }, + + onHover: function(element, dropon, overlap) { + if(Element.isParent(dropon, element)) return; + + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { + return; + } else if(overlap>0.5) { + Sortable.mark(dropon, 'before'); + if(dropon.previousSibling != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, dropon); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } else { + Sortable.mark(dropon, 'after'); + var nextElement = dropon.nextSibling || null; + if(nextElement != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, nextElement); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } + }, + + onEmptyHover: function(element, dropon, overlap) { + var oldParentNode = element.parentNode; + var droponOptions = Sortable.options(dropon); + + if(!Element.isParent(dropon, element)) { + var index; + + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); + var child = null; + + if(children) { + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); + + for (index = 0; index < children.length; index += 1) { + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { + offset -= Element.offsetSize (children[index], droponOptions.overlap); + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { + child = index + 1 < children.length ? children[index + 1] : null; + break; + } else { + child = children[index]; + break; + } + } + } + + dropon.insertBefore(element, child); + + Sortable.options(oldParentNode).onChange(element); + droponOptions.onChange(element); + } + }, + + unmark: function() { + if(Sortable._marker) Sortable._marker.hide(); + }, + + mark: function(dropon, position) { + // mark on ghosting only + var sortable = Sortable.options(dropon.parentNode); + if(sortable && !sortable.ghosting) return; + + if(!Sortable._marker) { + Sortable._marker = + ($('dropmarker') || Element.extend(document.createElement('DIV'))). + hide().addClassName('dropmarker').setStyle({position:'absolute'}); + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); + } + var offsets = Position.cumulativeOffset(dropon); + Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); + + if(position=='after') + if(sortable.overlap == 'horizontal') + Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); + else + Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); + + Sortable._marker.show(); + }, + + _tree: function(element, options, parent) { + var children = Sortable.findElements(element, options) || []; + + for (var i = 0; i < children.length; ++i) { + var match = children[i].id.match(options.format); + + if (!match) continue; + + var child = { + id: encodeURIComponent(match ? match[1] : null), + element: element, + parent: parent, + children: [], + position: parent.children.length, + container: $(children[i]).down(options.treeTag) + } + + /* Get the element containing the children and recurse over it */ + if (child.container) + this._tree(child.container, options, child) + + parent.children.push (child); + } + + return parent; + }, + + tree: function(element) { + element = $(element); + var sortableOptions = this.options(element); + var options = Object.extend({ + tag: sortableOptions.tag, + treeTag: sortableOptions.treeTag, + only: sortableOptions.only, + name: element.id, + format: sortableOptions.format + }, arguments[1] || { }); + + var root = { + id: null, + parent: null, + children: [], + container: element, + position: 0 + } + + return Sortable._tree(element, options, root); + }, + + /* Construct a [i] index for a particular node */ + _constructIndex: function(node) { + var index = ''; + do { + if (node.id) index = '[' + node.position + ']' + index; + } while ((node = node.parent) != null); + return index; + }, + + sequence: function(element) { + element = $(element); + var options = Object.extend(this.options(element), arguments[1] || { }); + + return $(this.findElements(element, options) || []).map( function(item) { + return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; + }); + }, + + setSequence: function(element, new_sequence) { + element = $(element); + var options = Object.extend(this.options(element), arguments[2] || { }); + + var nodeMap = { }; + this.findElements(element, options).each( function(n) { + if (n.id.match(options.format)) + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; + n.parentNode.removeChild(n); + }); + + new_sequence.each(function(ident) { + var n = nodeMap[ident]; + if (n) { + n[1].appendChild(n[0]); + delete nodeMap[ident]; + } + }); + }, + + serialize: function(element) { + element = $(element); + var options = Object.extend(Sortable.options(element), arguments[1] || { }); + var name = encodeURIComponent( + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); + + if (options.tree) { + return Sortable.tree(element, arguments[1]).children.map( function (item) { + return [name + Sortable._constructIndex(item) + "[id]=" + + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); + }).flatten().join('&'); + } else { + return Sortable.sequence(element, arguments[1]).map( function(item) { + return name + "[]=" + encodeURIComponent(item); + }).join('&'); + } + } +} + +// Returns true if child is contained within element +Element.isParent = function(child, element) { + if (!child.parentNode || child == element) return false; + if (child.parentNode == element) return true; + return Element.isParent(child.parentNode, element); +} + +Element.findChildren = function(element, only, recursive, tagName) { + if(!element.hasChildNodes()) return null; + tagName = tagName.toUpperCase(); + if(only) only = [only].flatten(); + var elements = []; + $A(element.childNodes).each( function(e) { + if(e.tagName && e.tagName.toUpperCase()==tagName && + (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) + elements.push(e); + if(recursive) { + var grandchildren = Element.findChildren(e, only, recursive, tagName); + if(grandchildren) elements.push(grandchildren); + } + }); + + return (elements.length>0 ? elements.flatten() : []); +} + +Element.offsetSize = function (element, type) { + return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; +} diff --git a/wp-includes/js/scriptaculous/effects.js b/wp-includes/js/scriptaculous/effects.js new file mode 100644 index 0000000..27c2901 --- /dev/null +++ b/wp-includes/js/scriptaculous/effects.js @@ -0,0 +1,1122 @@ +// script.aculo.us effects.js v1.8.0, Tue Nov 06 15:01:40 +0300 2007 + +// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// Contributors: +// Justin Palmer (http://encytemedia.com/) +// Mark Pilgrim (http://diveintomark.org/) +// Martin Bialasinki +// +// script.aculo.us is freely distributable under the terms of an MIT-style license. +// For details, see the script.aculo.us web site: http://script.aculo.us/ + +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { + var color = '#'; + if (this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); + } else { + if (this.slice(0,1) == '#') { + if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if (this.length==7) color = this.toLowerCase(); + } + } + return (color.length==7 ? color : (arguments[0] || this)); +}; + +/*--------------------------------------------------------------------------*/ + +Element.collectTextNodes = function(element) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); + }).flatten().join(''); +}; + +Element.collectTextNodesIgnoreClass = function(element, className) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + Element.collectTextNodesIgnoreClass(node, className) : '')); + }).flatten().join(''); +}; + +Element.setContentZoom = function(element, percent) { + element = $(element); + element.setStyle({fontSize: (percent/100) + 'em'}); + if (Prototype.Browser.WebKit) window.scrollBy(0,0); + return element; +}; + +Element.getInlineOpacity = function(element){ + return $(element).style.opacity || ''; +}; + +Element.forceRerendering = function(element) { + try { + element = $(element); + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch(e) { } +}; + +/*--------------------------------------------------------------------------*/ + +var Effect = { + _elementDoesNotExistError: { + name: 'ElementDoesNotExistError', + message: 'The specified DOM element does not exist, but is required for this effect to operate' + }, + Transitions: { + linear: Prototype.K, + sinoidal: function(pos) { + return (-Math.cos(pos*Math.PI)/2) + 0.5; + }, + reverse: function(pos) { + return 1-pos; + }, + flicker: function(pos) { + var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; + return pos > 1 ? 1 : pos; + }, + wobble: function(pos) { + return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; + }, + pulse: function(pos, pulses) { + pulses = pulses || 5; + return ( + ((pos % (1/pulses)) * pulses).round() == 0 ? + ((pos * pulses * 2) - (pos * pulses * 2).floor()) : + 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor()) + ); + }, + spring: function(pos) { + return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); + }, + none: function(pos) { + return 0; + }, + full: function(pos) { + return 1; + } + }, + DefaultOptions: { + duration: 1.0, // seconds + fps: 100, // 100= assume 66fps max. + sync: false, // true for combining + from: 0.0, + to: 1.0, + delay: 0.0, + queue: 'parallel' + }, + tagifyText: function(element) { + var tagifyStyle = 'position:relative'; + if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; + + element = $(element); + $A(element.childNodes).each( function(child) { + if (child.nodeType==3) { + child.nodeValue.toArray().each( function(character) { + element.insertBefore( + new Element('span', {style: tagifyStyle}).update( + character == ' ' ? String.fromCharCode(160) : character), + child); + }); + Element.remove(child); + } + }); + }, + multiple: function(element, effect) { + var elements; + if (((typeof element == 'object') || + Object.isFunction(element)) && + (element.length)) + elements = element; + else + elements = $(element).childNodes; + + var options = Object.extend({ + speed: 0.1, + delay: 0.0 + }, arguments[2] || { }); + var masterDelay = options.delay; + + $A(elements).each( function(element, index) { + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); + }); + }, + PAIRS: { + 'slide': ['SlideDown','SlideUp'], + 'blind': ['BlindDown','BlindUp'], + 'appear': ['Appear','Fade'] + }, + toggle: function(element, effect) { + element = $(element); + effect = (effect || 'appear').toLowerCase(); + var options = Object.extend({ + queue: { position:'end', scope:(element.id || 'global'), limit: 1 } + }, arguments[2] || { }); + Effect[element.visible() ? + Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); + } +}; + +Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; + +/* ------------- core effects ------------- */ + +Effect.ScopedQueue = Class.create(Enumerable, { + initialize: function() { + this.effects = []; + this.interval = null; + }, + _each: function(iterator) { + this.effects._each(iterator); + }, + add: function(effect) { + var timestamp = new Date().getTime(); + + var position = Object.isString(effect.options.queue) ? + effect.options.queue : effect.options.queue.position; + + switch(position) { + case 'front': + // move unstarted effects after this effect + this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { + e.startOn += effect.finishOn; + e.finishOn += effect.finishOn; + }); + break; + case 'with-last': + timestamp = this.effects.pluck('startOn').max() || timestamp; + break; + case 'end': + // start effect after last queued effect has finished + timestamp = this.effects.pluck('finishOn').max() || timestamp; + break; + } + + effect.startOn += timestamp; + effect.finishOn += timestamp; + + if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + this.effects.push(effect); + + if (!this.interval) + this.interval = setInterval(this.loop.bind(this), 15); + }, + remove: function(effect) { + this.effects = this.effects.reject(function(e) { return e==effect }); + if (this.effects.length == 0) { + clearInterval(this.interval); + this.interval = null; + } + }, + loop: function() { + var timePos = new Date().getTime(); + for(var i=0, len=this.effects.length;i= this.startOn) { + if (timePos >= this.finishOn) { + this.render(1.0); + this.cancel(); + this.event('beforeFinish'); + if (this.finish) this.finish(); + this.event('afterFinish'); + return; + } + var pos = (timePos - this.startOn) / this.totalTime, + frame = (pos * this.totalFrames).round(); + if (frame > this.currentFrame) { + this.render(pos); + this.currentFrame = frame; + } + } + }, + cancel: function() { + if (!this.options.sync) + Effect.Queues.get(Object.isString(this.options.queue) ? + 'global' : this.options.queue.scope).remove(this); + this.state = 'finished'; + }, + event: function(eventName) { + if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); + if (this.options[eventName]) this.options[eventName](this); + }, + inspect: function() { + var data = $H(); + for(property in this) + if (!Object.isFunction(this[property])) data.set(property, this[property]); + return '#'; + } +}); + +Effect.Parallel = Class.create(Effect.Base, { + initialize: function(effects) { + this.effects = effects || []; + this.start(arguments[1]); + }, + update: function(position) { + this.effects.invoke('render', position); + }, + finish: function(position) { + this.effects.each( function(effect) { + effect.render(1.0); + effect.cancel(); + effect.event('beforeFinish'); + if (effect.finish) effect.finish(position); + effect.event('afterFinish'); + }); + } +}); + +Effect.Tween = Class.create(Effect.Base, { + initialize: function(object, from, to) { + object = Object.isString(object) ? $(object) : object; + var args = $A(arguments), method = args.last(), + options = args.length == 5 ? args[3] : null; + this.method = Object.isFunction(method) ? method.bind(object) : + Object.isFunction(object[method]) ? object[method].bind(object) : + function(value) { object[method] = value }; + this.start(Object.extend({ from: from, to: to }, options || { })); + }, + update: function(position) { + this.method(position); + } +}); + +Effect.Event = Class.create(Effect.Base, { + initialize: function() { + this.start(Object.extend({ duration: 0 }, arguments[0] || { })); + }, + update: Prototype.emptyFunction +}); + +Effect.Opacity = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + // make this work on IE on elements without 'layout' + if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + var options = Object.extend({ + from: this.element.getOpacity() || 0.0, + to: 1.0 + }, arguments[1] || { }); + this.start(options); + }, + update: function(position) { + this.element.setOpacity(position); + } +}); + +Effect.Move = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + x: 0, + y: 0, + mode: 'relative' + }, arguments[1] || { }); + this.start(options); + }, + setup: function() { + this.element.makePositioned(); + this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); + this.originalTop = parseFloat(this.element.getStyle('top') || '0'); + if (this.options.mode == 'absolute') { + this.options.x = this.options.x - this.originalLeft; + this.options.y = this.options.y - this.originalTop; + } + }, + update: function(position) { + this.element.setStyle({ + left: (this.options.x * position + this.originalLeft).round() + 'px', + top: (this.options.y * position + this.originalTop).round() + 'px' + }); + } +}); + +// for backwards compatibility +Effect.MoveBy = function(element, toTop, toLeft) { + return new Effect.Move(element, + Object.extend({ x: toLeft, y: toTop }, arguments[3] || { })); +}; + +Effect.Scale = Class.create(Effect.Base, { + initialize: function(element, percent) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + scaleX: true, + scaleY: true, + scaleContent: true, + scaleFromCenter: false, + scaleMode: 'box', // 'box' or 'contents' or { } with provided values + scaleFrom: 100.0, + scaleTo: percent + }, arguments[2] || { }); + this.start(options); + }, + setup: function() { + this.restoreAfterFinish = this.options.restoreAfterFinish || false; + this.elementPositioning = this.element.getStyle('position'); + + this.originalStyle = { }; + ['top','left','width','height','fontSize'].each( function(k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this)); + + this.originalTop = this.element.offsetTop; + this.originalLeft = this.element.offsetLeft; + + var fontSize = this.element.getStyle('font-size') || '100%'; + ['em','px','%','pt'].each( function(fontSizeType) { + if (fontSize.indexOf(fontSizeType)>0) { + this.fontSize = parseFloat(fontSize); + this.fontSizeType = fontSizeType; + } + }.bind(this)); + + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; + + this.dims = null; + if (this.options.scaleMode=='box') + this.dims = [this.element.offsetHeight, this.element.offsetWidth]; + if (/^content/.test(this.options.scaleMode)) + this.dims = [this.element.scrollHeight, this.element.scrollWidth]; + if (!this.dims) + this.dims = [this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth]; + }, + update: function(position) { + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + if (this.options.scaleContent && this.fontSize) + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); + }, + finish: function(position) { + if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); + }, + setDimensions: function(height, width) { + var d = { }; + if (this.options.scaleX) d.width = width.round() + 'px'; + if (this.options.scaleY) d.height = height.round() + 'px'; + if (this.options.scaleFromCenter) { + var topd = (height - this.dims[0])/2; + var leftd = (width - this.dims[1])/2; + if (this.elementPositioning == 'absolute') { + if (this.options.scaleY) d.top = this.originalTop-topd + 'px'; + if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; + } else { + if (this.options.scaleY) d.top = -topd + 'px'; + if (this.options.scaleX) d.left = -leftd + 'px'; + } + } + this.element.setStyle(d); + } +}); + +Effect.Highlight = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { }); + this.start(options); + }, + setup: function() { + // Prevent executing on elements not in the layout flow + if (this.element.getStyle('display')=='none') { this.cancel(); return; } + // Disable background image during the effect + this.oldStyle = { }; + if (!this.options.keepBackgroundImage) { + this.oldStyle.backgroundImage = this.element.getStyle('background-image'); + this.element.setStyle({backgroundImage: 'none'}); + } + if (!this.options.endcolor) + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); + if (!this.options.restorecolor) + this.options.restorecolor = this.element.getStyle('background-color'); + // init color calculations + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); + this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); + }, + update: function(position) { + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ + return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) }); + }, + finish: function() { + this.element.setStyle(Object.extend(this.oldStyle, { + backgroundColor: this.options.restorecolor + })); + } +}); + +Effect.ScrollTo = function(element) { + var options = arguments[1] || { }, + scrollOffsets = document.viewport.getScrollOffsets(), + elementOffsets = $(element).cumulativeOffset(), + max = (window.height || document.body.scrollHeight) - document.viewport.getHeight(); + + if (options.offset) elementOffsets[1] += options.offset; + + return new Effect.Tween(null, + scrollOffsets.top, + elementOffsets[1] > max ? max : elementOffsets[1], + options, + function(p){ scrollTo(scrollOffsets.left, p.round()) } + ); +}; + +/* ------------- combination effects ------------- */ + +Effect.Fade = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + var options = Object.extend({ + from: element.getOpacity() || 1.0, + to: 0.0, + afterFinishInternal: function(effect) { + if (effect.options.to!=0) return; + effect.element.hide().setStyle({opacity: oldOpacity}); + } + }, arguments[1] || { }); + return new Effect.Opacity(element,options); +}; + +Effect.Appear = function(element) { + element = $(element); + var options = Object.extend({ + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), + to: 1.0, + // force Safari to render floated elements properly + afterFinishInternal: function(effect) { + effect.element.forceRerendering(); + }, + beforeSetup: function(effect) { + effect.element.setOpacity(effect.options.from).show(); + }}, arguments[1] || { }); + return new Effect.Opacity(element,options); +}; + +Effect.Puff = function(element) { + element = $(element); + var oldStyle = { + opacity: element.getInlineOpacity(), + position: element.getStyle('position'), + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height + }; + return new Effect.Parallel( + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, + beforeSetupInternal: function(effect) { + Position.absolutize(effect.effects[0].element) + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().setStyle(oldStyle); } + }, arguments[1] || { }) + ); +}; + +Effect.BlindUp = function(element) { + element = $(element); + element.makeClipping(); + return new Effect.Scale(element, 0, + Object.extend({ scaleContent: false, + scaleX: false, + restoreAfterFinish: true, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }, arguments[1] || { }) + ); +}; + +Effect.BlindDown = function(element) { + element = $(element); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: 0, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + } + }, arguments[1] || { })); +}; + +Effect.SwitchOff = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + return new Effect.Appear(element, Object.extend({ + duration: 0.4, + from: 0, + transition: Effect.Transitions.flicker, + afterFinishInternal: function(effect) { + new Effect.Scale(effect.element, 1, { + duration: 0.3, scaleFromCenter: true, + scaleX: false, scaleContent: false, restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); + } + }) + } + }, arguments[1] || { })); +}; + +Effect.DropOut = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left'), + opacity: element.getInlineOpacity() }; + return new Effect.Parallel( + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 }) ], + Object.extend( + { duration: 0.5, + beforeSetup: function(effect) { + effect.effects[0].element.makePositioned(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); + } + }, arguments[1] || { })); +}; + +Effect.Shake = function(element) { + element = $(element); + var options = Object.extend({ + distance: 20, + duration: 0.5 + }, arguments[1] || {}); + var distance = parseFloat(options.distance); + var split = parseFloat(options.duration) / 10.0; + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left') }; + return new Effect.Move(element, + { x: distance, y: 0, duration: split, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: distance*2, y: 0, duration: split*2, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { + effect.element.undoPositioned().setStyle(oldStyle); + }}) }}) }}) }}) }}) }}); +}; + +Effect.SlideDown = function(element) { + element = $(element).cleanWhitespace(); + // SlideDown need to have the content of the element wrapped in a container element with fixed height! + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: window.opera ? 0 : 1, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if (window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || { }) + ); +}; + +Effect.SlideUp = function(element) { + element = $(element).cleanWhitespace(); + var oldInnerBottom = element.down().getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, window.opera ? 0 : 1, + Object.extend({ scaleContent: false, + scaleX: false, + scaleMode: 'box', + scaleFrom: 100, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.down().makePositioned(); + if (window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping().show(); + }, + afterUpdateInternal: function(effect) { + effect.element.down().setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().undoPositioned(); + effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); + } + }, arguments[1] || { }) + ); +}; + +// Bug in opera makes the TD containing this element expand for a instance after finish +Effect.Squish = function(element) { + return new Effect.Scale(element, window.opera ? 1 : 0, { + restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping(); + } + }); +}; + +Effect.Grow = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.full + }, arguments[1] || { }); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var initialMoveX, initialMoveY; + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + initialMoveX = initialMoveY = moveX = moveY = 0; + break; + case 'top-right': + initialMoveX = dims.width; + initialMoveY = moveY = 0; + moveX = -dims.width; + break; + case 'bottom-left': + initialMoveX = moveX = 0; + initialMoveY = dims.height; + moveY = -dims.height; + break; + case 'bottom-right': + initialMoveX = dims.width; + initialMoveY = dims.height; + moveX = -dims.width; + moveY = -dims.height; + break; + case 'center': + initialMoveX = dims.width / 2; + initialMoveY = dims.height / 2; + moveX = -dims.width / 2; + moveY = -dims.height / 2; + break; + } + + return new Effect.Move(element, { + x: initialMoveX, + y: initialMoveY, + duration: 0.01, + beforeSetup: function(effect) { + effect.element.hide().makeClipping().makePositioned(); + }, + afterFinishInternal: function(effect) { + new Effect.Parallel( + [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), + new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), + new Effect.Scale(effect.element, 100, { + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) + ], Object.extend({ + beforeSetup: function(effect) { + effect.effects[0].element.setStyle({height: '0px'}).show(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); + } + }, options) + ) + } + }); +}; + +Effect.Shrink = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.none + }, arguments[1] || { }); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + moveX = moveY = 0; + break; + case 'top-right': + moveX = dims.width; + moveY = 0; + break; + case 'bottom-left': + moveX = 0; + moveY = dims.height; + break; + case 'bottom-right': + moveX = dims.width; + moveY = dims.height; + break; + case 'center': + moveX = dims.width / 2; + moveY = dims.height / 2; + break; + } + + return new Effect.Parallel( + [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), + new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), + new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) + ], Object.extend({ + beforeStartInternal: function(effect) { + effect.effects[0].element.makePositioned().makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } + }, options) + ); +}; + +Effect.Pulsate = function(element) { + element = $(element); + var options = arguments[1] || { }; + var oldOpacity = element.getInlineOpacity(); + var transition = options.transition || Effect.Transitions.sinoidal; + var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) }; + reverser.bind(transition); + return new Effect.Opacity(element, + Object.extend(Object.extend({ duration: 2.0, from: 0, + afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } + }, options), {transition: reverser})); +}; + +Effect.Fold = function(element) { + element = $(element); + var oldStyle = { + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height }; + element.makeClipping(); + return new Effect.Scale(element, 5, Object.extend({ + scaleContent: false, + scaleX: false, + afterFinishInternal: function(effect) { + new Effect.Scale(element, 1, { + scaleContent: false, + scaleY: false, + afterFinishInternal: function(effect) { + effect.element.hide().undoClipping().setStyle(oldStyle); + } }); + }}, arguments[1] || { })); +}; + +Effect.Morph = Class.create(Effect.Base, { + initialize: function(element) { + this.element = $(element); + if (!this.element) throw(Effect._elementDoesNotExistError); + var options = Object.extend({ + style: { } + }, arguments[1] || { }); + + if (!Object.isString(options.style)) this.style = $H(options.style); + else { + if (options.style.include(':')) + this.style = options.style.parseStyle(); + else { + this.element.addClassName(options.style); + this.style = $H(this.element.getStyles()); + this.element.removeClassName(options.style); + var css = this.element.getStyles(); + this.style = this.style.reject(function(style) { + return style.value == css[style.key]; + }); + options.afterFinishInternal = function(effect) { + effect.element.addClassName(effect.options.style); + effect.transforms.each(function(transform) { + effect.element.style[transform.style] = ''; + }); + } + } + } + this.start(options); + }, + + setup: function(){ + function parseColor(color){ + if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; + color = color.parseColor(); + return $R(0,2).map(function(i){ + return parseInt( color.slice(i*2+1,i*2+3), 16 ) + }); + } + this.transforms = this.style.map(function(pair){ + var property = pair[0], value = pair[1], unit = null; + + if (value.parseColor('#zzzzzz') != '#zzzzzz') { + value = value.parseColor(); + unit = 'color'; + } else if (property == 'opacity') { + value = parseFloat(value); + if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout)) + this.element.setStyle({zoom: 1}); + } else if (Element.CSS_LENGTH.test(value)) { + var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/); + value = parseFloat(components[1]); + unit = (components.length == 3) ? components[2] : null; + } + + var originalValue = this.element.getStyle(property); + return { + style: property.camelize(), + originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), + targetValue: unit=='color' ? parseColor(value) : value, + unit: unit + }; + }.bind(this)).reject(function(transform){ + return ( + (transform.originalValue == transform.targetValue) || + ( + transform.unit != 'color' && + (isNaN(transform.originalValue) || isNaN(transform.targetValue)) + ) + ) + }); + }, + update: function(position) { + var style = { }, transform, i = this.transforms.length; + while(i--) + style[(transform = this.transforms[i]).style] = + transform.unit=='color' ? '#'+ + (Math.round(transform.originalValue[0]+ + (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + + (Math.round(transform.originalValue[1]+ + (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() + + (Math.round(transform.originalValue[2]+ + (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : + (transform.originalValue + + (transform.targetValue - transform.originalValue) * position).toFixed(3) + + (transform.unit === null ? '' : transform.unit); + this.element.setStyle(style, true); + } +}); + +Effect.Transform = Class.create({ + initialize: function(tracks){ + this.tracks = []; + this.options = arguments[1] || { }; + this.addTracks(tracks); + }, + addTracks: function(tracks){ + tracks.each(function(track){ + track = $H(track); + var data = track.values().first(); + this.tracks.push($H({ + ids: track.keys().first(), + effect: Effect.Morph, + options: { style: data } + })); + }.bind(this)); + return this; + }, + play: function(){ + return new Effect.Parallel( + this.tracks.map(function(track){ + var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options'); + var elements = [$(ids) || $$(ids)].flatten(); + return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) }); + }).flatten(), + this.options + ); + } +}); + +Element.CSS_PROPERTIES = $w( + 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + + 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + + 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + + 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + + 'fontSize fontWeight height left letterSpacing lineHeight ' + + 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+ + 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + + 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + + 'right textIndent top width wordSpacing zIndex'); + +Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; + +String.__parseStyleElement = document.createElement('div'); +String.prototype.parseStyle = function(){ + var style, styleRules = $H(); + if (Prototype.Browser.WebKit) + style = new Element('div',{style:this}).style; + else { + String.__parseStyleElement.innerHTML = '
    '; + style = String.__parseStyleElement.childNodes[0].style; + } + + Element.CSS_PROPERTIES.each(function(property){ + if (style[property]) styleRules.set(property, style[property]); + }); + + if (Prototype.Browser.IE && this.include('opacity')) + styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); + + return styleRules; +}; + +if (document.defaultView && document.defaultView.getComputedStyle) { + Element.getStyles = function(element) { + var css = document.defaultView.getComputedStyle($(element), null); + return Element.CSS_PROPERTIES.inject({ }, function(styles, property) { + styles[property] = css[property]; + return styles; + }); + }; +} else { + Element.getStyles = function(element) { + element = $(element); + var css = element.currentStyle, styles; + styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) { + hash.set(property, css[property]); + return hash; + }); + if (!styles.opacity) styles.set('opacity', element.getOpacity()); + return styles; + }; +}; + +Effect.Methods = { + morph: function(element, style) { + element = $(element); + new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { })); + return element; + }, + visualEffect: function(element, effect, options) { + element = $(element) + var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); + new Effect[klass](element, options); + return element; + }, + highlight: function(element, options) { + element = $(element); + new Effect.Highlight(element, options); + return element; + } +}; + +$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ + 'pulsate shake puff squish switchOff dropOut').each( + function(effect) { + Effect.Methods[effect] = function(element, options){ + element = $(element); + Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); + return element; + } + } +); + +$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( + function(f) { Effect.Methods[f] = Element[f]; } +); + +Element.addMethods(Effect.Methods); diff --git a/wp-includes/js/scriptaculous/prototype.js b/wp-includes/js/scriptaculous/prototype.js new file mode 100644 index 0000000..5c73462 --- /dev/null +++ b/wp-includes/js/scriptaculous/prototype.js @@ -0,0 +1,4184 @@ +/* Prototype JavaScript framework, version 1.6.0 + * (c) 2005-2007 Sam Stephenson + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://www.prototypejs.org/ + * + *--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.6.0', + + Browser: { + IE: !!(window.attachEvent && !window.opera), + Opera: !!window.opera, + WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, + Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1, + MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/) + }, + + BrowserFeatures: { + XPath: !!document.evaluate, + ElementExtensions: !!window.HTMLElement, + SpecificElementExtensions: + document.createElement('div').__proto__ && + document.createElement('div').__proto__ !== + document.createElement('form').__proto__ + }, + + ScriptFragment: ']*>([\\S\\s]*?)<\/script>', + JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, + + emptyFunction: function() { }, + K: function(x) { return x } +}; + +if (Prototype.Browser.MobileSafari) + Prototype.BrowserFeatures.SpecificElementExtensions = false; + +if (Prototype.Browser.WebKit) + Prototype.BrowserFeatures.XPath = false; + +/* Based on Alex Arnell's inheritance implementation. */ +var Class = { + create: function() { + var parent = null, properties = $A(arguments); + if (Object.isFunction(properties[0])) + parent = properties.shift(); + + function klass() { + this.initialize.apply(this, arguments); + } + + Object.extend(klass, Class.Methods); + klass.superclass = parent; + klass.subclasses = []; + + if (parent) { + var subclass = function() { }; + subclass.prototype = parent.prototype; + klass.prototype = new subclass; + parent.subclasses.push(klass); + } + + for (var i = 0; i < properties.length; i++) + klass.addMethods(properties[i]); + + if (!klass.prototype.initialize) + klass.prototype.initialize = Prototype.emptyFunction; + + klass.prototype.constructor = klass; + + return klass; + } +}; + +Class.Methods = { + addMethods: function(source) { + var ancestor = this.superclass && this.superclass.prototype; + var properties = Object.keys(source); + + if (!Object.keys({ toString: true }).length) + properties.push("toString", "valueOf"); + + for (var i = 0, length = properties.length; i < length; i++) { + var property = properties[i], value = source[property]; + if (ancestor && Object.isFunction(value) && + value.argumentNames().first() == "$super") { + var method = value, value = Object.extend((function(m) { + return function() { return ancestor[m].apply(this, arguments) }; + })(property).wrap(method), { + valueOf: function() { return method }, + toString: function() { return method.toString() } + }); + } + this.prototype[property] = value; + } + + return this; + } +}; + +var Abstract = { }; + +Object.extend = function(destination, source) { + for (var property in source) + destination[property] = source[property]; + return destination; +}; + +Object.extend(Object, { + inspect: function(object) { + try { + if (object === undefined) return 'undefined'; + if (object === null) return 'null'; + return object.inspect ? object.inspect() : object.toString(); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } + }, + + toJSON: function(object) { + var type = typeof object; + switch (type) { + case 'undefined': + case 'function': + case 'unknown': return; + case 'boolean': return object.toString(); + } + + if (object === null) return 'null'; + if (object.toJSON) return object.toJSON(); + if (Object.isElement(object)) return; + + var results = []; + for (var property in object) { + var value = Object.toJSON(object[property]); + if (value !== undefined) + results.push(property.toJSON() + ': ' + value); + } + + return '{' + results.join(', ') + '}'; + }, + + toQueryString: function(object) { + return $H(object).toQueryString(); + }, + + toHTML: function(object) { + return object && object.toHTML ? object.toHTML() : String.interpret(object); + }, + + keys: function(object) { + var keys = []; + for (var property in object) + keys.push(property); + return keys; + }, + + values: function(object) { + var values = []; + for (var property in object) + values.push(object[property]); + return values; + }, + + clone: function(object) { + return Object.extend({ }, object); + }, + + isElement: function(object) { + return object && object.nodeType == 1; + }, + + isArray: function(object) { + return object && object.constructor === Array; + }, + + isHash: function(object) { + return object instanceof Hash; + }, + + isFunction: function(object) { + return typeof object == "function"; + }, + + isString: function(object) { + return typeof object == "string"; + }, + + isNumber: function(object) { + return typeof object == "number"; + }, + + isUndefined: function(object) { + return typeof object == "undefined"; + } +}); + +Object.extend(Function.prototype, { + argumentNames: function() { + var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip"); + return names.length == 1 && !names[0] ? [] : names; + }, + + bind: function() { + if (arguments.length < 2 && arguments[0] === undefined) return this; + var __method = this, args = $A(arguments), object = args.shift(); + return function() { + return __method.apply(object, args.concat($A(arguments))); + } + }, + + bindAsEventListener: function() { + var __method = this, args = $A(arguments), object = args.shift(); + return function(event) { + return __method.apply(object, [event || window.event].concat(args)); + } + }, + + curry: function() { + if (!arguments.length) return this; + var __method = this, args = $A(arguments); + return function() { + return __method.apply(this, args.concat($A(arguments))); + } + }, + + delay: function() { + var __method = this, args = $A(arguments), timeout = args.shift() * 1000; + return window.setTimeout(function() { + return __method.apply(__method, args); + }, timeout); + }, + + wrap: function(wrapper) { + var __method = this; + return function() { + return wrapper.apply(this, [__method.bind(this)].concat($A(arguments))); + } + }, + + methodize: function() { + if (this._methodized) return this._methodized; + var __method = this; + return this._methodized = function() { + return __method.apply(null, [this].concat($A(arguments))); + }; + } +}); + +Function.prototype.defer = Function.prototype.delay.curry(0.01); + +Date.prototype.toJSON = function() { + return '"' + this.getUTCFullYear() + '-' + + (this.getUTCMonth() + 1).toPaddedString(2) + '-' + + this.getUTCDate().toPaddedString(2) + 'T' + + this.getUTCHours().toPaddedString(2) + ':' + + this.getUTCMinutes().toPaddedString(2) + ':' + + this.getUTCSeconds().toPaddedString(2) + 'Z"'; +}; + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) { } + } + + return returnValue; + } +}; + +RegExp.prototype.match = RegExp.prototype.test; + +RegExp.escape = function(str) { + return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); +}; + +/*--------------------------------------------------------------------------*/ + +var PeriodicalExecuter = Class.create({ + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + execute: function() { + this.callback(this); + }, + + stop: function() { + if (!this.timer) return; + clearInterval(this.timer); + this.timer = null; + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.execute(); + } finally { + this.currentlyExecuting = false; + } + } + } +}); +Object.extend(String, { + interpret: function(value) { + return value == null ? '' : String(value); + }, + specialChar: { + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '\\': '\\\\' + } +}); + +Object.extend(String.prototype, { + gsub: function(pattern, replacement) { + var result = '', source = this, match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += String.interpret(replacement(match)); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + + sub: function(pattern, replacement, count) { + replacement = this.gsub.prepareReplacement(replacement); + count = count === undefined ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + }, + + scan: function(pattern, iterator) { + this.gsub(pattern, iterator); + return String(this); + }, + + truncate: function(length, truncation) { + length = length || 30; + truncation = truncation === undefined ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : String(this); + }, + + strip: function() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + }, + + stripTags: function() { + return this.replace(/<\/?[^>]+>/gi, ''); + }, + + stripScripts: function() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + }, + + extractScripts: function() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + }, + + evalScripts: function() { + return this.extractScripts().map(function(script) { return eval(script) }); + }, + + escapeHTML: function() { + var self = arguments.callee; + self.text.data = this; + return self.div.innerHTML; + }, + + unescapeHTML: function() { + var div = new Element('div'); + div.innerHTML = this.stripTags(); + return div.childNodes[0] ? (div.childNodes.length > 1 ? + $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) : + div.childNodes[0].nodeValue) : ''; + }, + + toQueryParams: function(separator) { + var match = this.strip().match(/([^?#]*)(#.*)?$/); + if (!match) return { }; + + return match[1].split(separator || '&').inject({ }, function(hash, pair) { + if ((pair = pair.split('='))[0]) { + var key = decodeURIComponent(pair.shift()); + var value = pair.length > 1 ? pair.join('=') : pair[0]; + if (value != undefined) value = decodeURIComponent(value); + + if (key in hash) { + if (!Object.isArray(hash[key])) hash[key] = [hash[key]]; + hash[key].push(value); + } + else hash[key] = value; + } + return hash; + }); + }, + + toArray: function() { + return this.split(''); + }, + + succ: function() { + return this.slice(0, this.length - 1) + + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); + }, + + times: function(count) { + return count < 1 ? '' : new Array(count + 1).join(this); + }, + + camelize: function() { + var parts = this.split('-'), len = parts.length; + if (len == 1) return parts[0]; + + var camelized = this.charAt(0) == '-' + ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) + : parts[0]; + + for (var i = 1; i < len; i++) + camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + + return camelized; + }, + + capitalize: function() { + return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); + }, + + underscore: function() { + return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); + }, + + dasherize: function() { + return this.gsub(/_/,'-'); + }, + + inspect: function(useDoubleQuotes) { + var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) { + var character = String.specialChar[match[0]]; + return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16); + }); + if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; + return "'" + escapedString.replace(/'/g, '\\\'') + "'"; + }, + + toJSON: function() { + return this.inspect(true); + }, + + unfilterJSON: function(filter) { + return this.sub(filter || Prototype.JSONFilter, '#{1}'); + }, + + isJSON: function() { + var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); + return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); + }, + + evalJSON: function(sanitize) { + var json = this.unfilterJSON(); + try { + if (!sanitize || json.isJSON()) return eval('(' + json + ')'); + } catch (e) { } + throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); + }, + + include: function(pattern) { + return this.indexOf(pattern) > -1; + }, + + startsWith: function(pattern) { + return this.indexOf(pattern) === 0; + }, + + endsWith: function(pattern) { + var d = this.length - pattern.length; + return d >= 0 && this.lastIndexOf(pattern) === d; + }, + + empty: function() { + return this == ''; + }, + + blank: function() { + return /^\s*$/.test(this); + }, + + interpolate: function(object, pattern) { + return new Template(this, pattern).evaluate(object); + } +}); + +if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, { + escapeHTML: function() { + return this.replace(/&/g,'&').replace(//g,'>'); + }, + unescapeHTML: function() { + return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); + } +}); + +String.prototype.gsub.prepareReplacement = function(replacement) { + if (Object.isFunction(replacement)) return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +}; + +String.prototype.parseQuery = String.prototype.toQueryParams; + +Object.extend(String.prototype.escapeHTML, { + div: document.createElement('div'), + text: document.createTextNode('') +}); + +with (String.prototype.escapeHTML) div.appendChild(text); + +var Template = Class.create({ + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + if (Object.isFunction(object.toTemplateReplacements)) + object = object.toTemplateReplacements(); + + return this.template.gsub(this.pattern, function(match) { + if (object == null) return ''; + + var before = match[1] || ''; + if (before == '\\') return match[2]; + + var ctx = object, expr = match[3]; + var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/, match = pattern.exec(expr); + if (match == null) return before; + + while (match != null) { + var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1]; + ctx = ctx[comp]; + if (null == ctx || '' == match[3]) break; + expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); + match = pattern.exec(expr); + } + + return before + String.interpret(ctx); + }.bind(this)); + } +}); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; + +var $break = { }; + +var Enumerable = { + each: function(iterator, context) { + var index = 0; + iterator = iterator.bind(context); + try { + this._each(function(value) { + iterator(value, index++); + }); + } catch (e) { + if (e != $break) throw e; + } + return this; + }, + + eachSlice: function(number, iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var index = -number, slices = [], array = this.toArray(); + while ((index += number) < array.length) + slices.push(array.slice(index, index+number)); + return slices.collect(iterator, context); + }, + + all: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result = true; + this.each(function(value, index) { + result = result && !!iterator(value, index); + if (!result) throw $break; + }); + return result; + }, + + any: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result = false; + this.each(function(value, index) { + if (result = !!iterator(value, index)) + throw $break; + }); + return result; + }, + + collect: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var results = []; + this.each(function(value, index) { + results.push(iterator(value, index)); + }); + return results; + }, + + detect: function(iterator, context) { + iterator = iterator.bind(context); + var result; + this.each(function(value, index) { + if (iterator(value, index)) { + result = value; + throw $break; + } + }); + return result; + }, + + findAll: function(iterator, context) { + iterator = iterator.bind(context); + var results = []; + this.each(function(value, index) { + if (iterator(value, index)) + results.push(value); + }); + return results; + }, + + grep: function(filter, iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var results = []; + + if (Object.isString(filter)) + filter = new RegExp(filter); + + this.each(function(value, index) { + if (filter.match(value)) + results.push(iterator(value, index)); + }); + return results; + }, + + include: function(object) { + if (Object.isFunction(this.indexOf)) + if (this.indexOf(object) != -1) return true; + + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + }, + + inGroupsOf: function(number, fillWith) { + fillWith = fillWith === undefined ? null : fillWith; + return this.eachSlice(number, function(slice) { + while(slice.length < number) slice.push(fillWith); + return slice; + }); + }, + + inject: function(memo, iterator, context) { + iterator = iterator.bind(context); + this.each(function(value, index) { + memo = iterator(memo, value, index); + }); + return memo; + }, + + invoke: function(method) { + var args = $A(arguments).slice(1); + return this.map(function(value) { + return value[method].apply(value, args); + }); + }, + + max: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result; + this.each(function(value, index) { + value = iterator(value, index); + if (result == undefined || value >= result) + result = value; + }); + return result; + }, + + min: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var result; + this.each(function(value, index) { + value = iterator(value, index); + if (result == undefined || value < result) + result = value; + }); + return result; + }, + + partition: function(iterator, context) { + iterator = iterator ? iterator.bind(context) : Prototype.K; + var trues = [], falses = []; + this.each(function(value, index) { + (iterator(value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + }, + + pluck: function(property) { + var results = []; + this.each(function(value) { + results.push(value[property]); + }); + return results; + }, + + reject: function(iterator, context) { + iterator = iterator.bind(context); + var results = []; + this.each(function(value, index) { + if (!iterator(value, index)) + results.push(value); + }); + return results; + }, + + sortBy: function(iterator, context) { + iterator = iterator.bind(context); + return this.map(function(value, index) { + return {value: value, criteria: iterator(value, index)}; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + }, + + toArray: function() { + return this.map(); + }, + + zip: function() { + var iterator = Prototype.K, args = $A(arguments); + if (Object.isFunction(args.last())) + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + }, + + size: function() { + return this.toArray().length; + }, + + inspect: function() { + return '#'; + } +}; + +Object.extend(Enumerable, { + map: Enumerable.collect, + find: Enumerable.detect, + select: Enumerable.findAll, + filter: Enumerable.findAll, + member: Enumerable.include, + entries: Enumerable.toArray, + every: Enumerable.all, + some: Enumerable.any +}); +function $A(iterable) { + if (!iterable) return []; + if (iterable.toArray) return iterable.toArray(); + var length = iterable.length, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; +} + +if (Prototype.Browser.WebKit) { + function $A(iterable) { + if (!iterable) return []; + if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') && + iterable.toArray) return iterable.toArray(); + var length = iterable.length, results = new Array(length); + while (length--) results[length] = iterable[length]; + return results; + } +} + +Array.from = $A; + +Object.extend(Array.prototype, Enumerable); + +if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; + +Object.extend(Array.prototype, { + _each: function(iterator) { + for (var i = 0, length = this.length; i < length; i++) + iterator(this[i]); + }, + + clear: function() { + this.length = 0; + return this; + }, + + first: function() { + return this[0]; + }, + + last: function() { + return this[this.length - 1]; + }, + + compact: function() { + return this.select(function(value) { + return value != null; + }); + }, + + flatten: function() { + return this.inject([], function(array, value) { + return array.concat(Object.isArray(value) ? + value.flatten() : [value]); + }); + }, + + without: function() { + var values = $A(arguments); + return this.select(function(value) { + return !values.include(value); + }); + }, + + reverse: function(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + }, + + reduce: function() { + return this.length > 1 ? this : this[0]; + }, + + uniq: function(sorted) { + return this.inject([], function(array, value, index) { + if (0 == index || (sorted ? array.last() != value : !array.include(value))) + array.push(value); + return array; + }); + }, + + intersect: function(array) { + return this.uniq().findAll(function(item) { + return array.detect(function(value) { return item === value }); + }); + }, + + clone: function() { + return [].concat(this); + }, + + size: function() { + return this.length; + }, + + inspect: function() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + }, + + toJSON: function() { + var results = []; + this.each(function(object) { + var value = Object.toJSON(object); + if (value !== undefined) results.push(value); + }); + return '[' + results.join(', ') + ']'; + } +}); + +// use native browser JS 1.6 implementation if available +if (Object.isFunction(Array.prototype.forEach)) + Array.prototype._each = Array.prototype.forEach; + +if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) { + i || (i = 0); + var length = this.length; + if (i < 0) i = length + i; + for (; i < length; i++) + if (this[i] === item) return i; + return -1; +}; + +if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) { + i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; + var n = this.slice(0, i).reverse().indexOf(item); + return (n < 0) ? n : i - n - 1; +}; + +Array.prototype.toArray = Array.prototype.clone; + +function $w(string) { + if (!Object.isString(string)) return []; + string = string.strip(); + return string ? string.split(/\s+/) : []; +} + +if (Prototype.Browser.Opera){ + Array.prototype.concat = function() { + var array = []; + for (var i = 0, length = this.length; i < length; i++) array.push(this[i]); + for (var i = 0, length = arguments.length; i < length; i++) { + if (Object.isArray(arguments[i])) { + for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) + array.push(arguments[i][j]); + } else { + array.push(arguments[i]); + } + } + return array; + }; +} +Object.extend(Number.prototype, { + toColorPart: function() { + return this.toPaddedString(2, 16); + }, + + succ: function() { + return this + 1; + }, + + times: function(iterator) { + $R(0, this, true).each(iterator); + return this; + }, + + toPaddedString: function(length, radix) { + var string = this.toString(radix || 10); + return '0'.times(length - string.length) + string; + }, + + toJSON: function() { + return isFinite(this) ? this.toString() : 'null'; + } +}); + +$w('abs round ceil floor').each(function(method){ + Number.prototype[method] = Math[method].methodize(); +}); +function $H(object) { + return new Hash(object); +}; + +var Hash = Class.create(Enumerable, (function() { + if (function() { + var i = 0, Test = function(value) { this.key = value }; + Test.prototype.key = 'foo'; + for (var property in new Test('bar')) i++; + return i > 1; + }()) { + function each(iterator) { + var cache = []; + for (var key in this._object) { + var value = this._object[key]; + if (cache.include(key)) continue; + cache.push(key); + var pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + } + } else { + function each(iterator) { + for (var key in this._object) { + var value = this._object[key], pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + } + } + + function toQueryPair(key, value) { + if (Object.isUndefined(value)) return key; + return key + '=' + encodeURIComponent(String.interpret(value)); + } + + return { + initialize: function(object) { + this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); + }, + + _each: each, + + set: function(key, value) { + return this._object[key] = value; + }, + + get: function(key) { + return this._object[key]; + }, + + unset: function(key) { + var value = this._object[key]; + delete this._object[key]; + return value; + }, + + toObject: function() { + return Object.clone(this._object); + }, + + keys: function() { + return this.pluck('key'); + }, + + values: function() { + return this.pluck('value'); + }, + + index: function(value) { + var match = this.detect(function(pair) { + return pair.value === value; + }); + return match && match.key; + }, + + merge: function(object) { + return this.clone().update(object); + }, + + update: function(object) { + return new Hash(object).inject(this, function(result, pair) { + result.set(pair.key, pair.value); + return result; + }); + }, + + toQueryString: function() { + return this.map(function(pair) { + var key = encodeURIComponent(pair.key), values = pair.value; + + if (values && typeof values == 'object') { + if (Object.isArray(values)) + return values.map(toQueryPair.curry(key)).join('&'); + } + return toQueryPair(key, values); + }).join('&'); + }, + + inspect: function() { + return '#'; + }, + + toJSON: function() { + return Object.toJSON(this.toObject()); + }, + + clone: function() { + return new Hash(this); + } + } +})()); + +Hash.prototype.toTemplateReplacements = Hash.prototype.toObject; +Hash.from = $H; +var ObjectRange = Class.create(Enumerable, { + initialize: function(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + }, + + _each: function(iterator) { + var value = this.start; + while (this.include(value)) { + iterator(value); + value = value.succ(); + } + }, + + include: function(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } +}); + +var $R = function(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +}; + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +}; + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responder) { + if (!this.include(responder)) + this.responders.push(responder); + }, + + unregister: function(responder) { + this.responders = this.responders.without(responder); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (Object.isFunction(responder[callback])) { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) { } + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { Ajax.activeRequestCount++ }, + onComplete: function() { Ajax.activeRequestCount-- } +}); + +Ajax.Base = Class.create({ + initialize: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + encoding: 'UTF-8', + parameters: '', + evalJSON: true, + evalJS: true + }; + Object.extend(this.options, options || { }); + + this.options.method = this.options.method.toLowerCase(); + if (Object.isString(this.options.parameters)) + this.options.parameters = this.options.parameters.toQueryParams(); + } +}); + +Ajax.Request = Class.create(Ajax.Base, { + _complete: false, + + initialize: function($super, url, options) { + $super(options); + this.transport = Ajax.getTransport(); + this.request(url); + }, + + request: function(url) { + this.url = url; + this.method = this.options.method; + var params = Object.clone(this.options.parameters); + + if (!['get', 'post'].include(this.method)) { + // simulate other verbs over post + params['_method'] = this.method; + this.method = 'post'; + } + + this.parameters = params; + + if (params = Object.toQueryString(params)) { + // when GET, append parameters to URL + if (this.method == 'get') + this.url += (this.url.include('?') ? '&' : '?') + params; + else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) + params += '&_='; + } + + try { + var response = new Ajax.Response(this); + if (this.options.onCreate) this.options.onCreate(response); + Ajax.Responders.dispatch('onCreate', this, response); + + this.transport.open(this.method.toUpperCase(), this.url, + this.options.asynchronous); + + if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1); + + this.transport.onreadystatechange = this.onStateChange.bind(this); + this.setRequestHeaders(); + + this.body = this.method == 'post' ? (this.options.postBody || params) : null; + this.transport.send(this.body); + + /* Force Firefox to handle ready state 4 for synchronous requests */ + if (!this.options.asynchronous && this.transport.overrideMimeType) + this.onStateChange(); + + } + catch (e) { + this.dispatchException(e); + } + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState > 1 && !((readyState == 4) && this._complete)) + this.respondToReadyState(this.transport.readyState); + }, + + setRequestHeaders: function() { + var headers = { + 'X-Requested-With': 'XMLHttpRequest', + 'X-Prototype-Version': Prototype.Version, + 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' + }; + + if (this.method == 'post') { + headers['Content-type'] = this.options.contentType + + (this.options.encoding ? '; charset=' + this.options.encoding : ''); + + /* Force "Connection: close" for older Mozilla browsers to work + * around a bug where XMLHttpRequest sends an incorrect + * Content-length header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType && + (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) + headers['Connection'] = 'close'; + } + + // user-defined headers + if (typeof this.options.requestHeaders == 'object') { + var extras = this.options.requestHeaders; + + if (Object.isFunction(extras.push)) + for (var i = 0, length = extras.length; i < length; i += 2) + headers[extras[i]] = extras[i+1]; + else + $H(extras).each(function(pair) { headers[pair.key] = pair.value }); + } + + for (var name in headers) + this.transport.setRequestHeader(name, headers[name]); + }, + + success: function() { + var status = this.getStatus(); + return !status || (status >= 200 && status < 300); + }, + + getStatus: function() { + try { + return this.transport.status || 0; + } catch (e) { return 0 } + }, + + respondToReadyState: function(readyState) { + var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this); + + if (state == 'Complete') { + try { + this._complete = true; + (this.options['on' + response.status] + || this.options['on' + (this.success() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + var contentType = response.getHeader('Content-type'); + if (this.options.evalJS == 'force' + || (this.options.evalJS && contentType + && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))) + this.evalResponse(); + } + + try { + (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON); + Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON); + } catch (e) { + this.dispatchException(e); + } + + if (state == 'Complete') { + // avoid memory leak in MSIE: clean up + this.transport.onreadystatechange = Prototype.emptyFunction; + } + }, + + getHeader: function(name) { + try { + return this.transport.getResponseHeader(name); + } catch (e) { return null } + }, + + evalResponse: function() { + try { + return eval((this.transport.responseText || '').unfilterJSON()); + } catch (e) { + this.dispatchException(e); + } + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + +Ajax.Response = Class.create({ + initialize: function(request){ + this.request = request; + var transport = this.transport = request.transport, + readyState = this.readyState = transport.readyState; + + if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { + this.status = this.getStatus(); + this.statusText = this.getStatusText(); + this.responseText = String.interpret(transport.responseText); + this.headerJSON = this._getHeaderJSON(); + } + + if(readyState == 4) { + var xml = transport.responseXML; + this.responseXML = xml === undefined ? null : xml; + this.responseJSON = this._getResponseJSON(); + } + }, + + status: 0, + statusText: '', + + getStatus: Ajax.Request.prototype.getStatus, + + getStatusText: function() { + try { + return this.transport.statusText || ''; + } catch (e) { return '' } + }, + + getHeader: Ajax.Request.prototype.getHeader, + + getAllHeaders: function() { + try { + return this.getAllResponseHeaders(); + } catch (e) { return null } + }, + + getResponseHeader: function(name) { + return this.transport.getResponseHeader(name); + }, + + getAllResponseHeaders: function() { + return this.transport.getAllResponseHeaders(); + }, + + _getHeaderJSON: function() { + var json = this.getHeader('X-JSON'); + if (!json) return null; + json = decodeURIComponent(escape(json)); + try { + return json.evalJSON(this.request.options.sanitizeJSON); + } catch (e) { + this.request.dispatchException(e); + } + }, + + _getResponseJSON: function() { + var options = this.request.options; + if (!options.evalJSON || (options.evalJSON != 'force' && + !(this.getHeader('Content-type') || '').include('application/json'))) + return null; + try { + return this.transport.responseText.evalJSON(options.sanitizeJSON); + } catch (e) { + this.request.dispatchException(e); + } + } +}); + +Ajax.Updater = Class.create(Ajax.Request, { + initialize: function($super, container, url, options) { + this.container = { + success: (container.success || container), + failure: (container.failure || (container.success ? null : container)) + }; + + options = options || { }; + var onComplete = options.onComplete; + options.onComplete = (function(response, param) { + this.updateContent(response.responseText); + if (Object.isFunction(onComplete)) onComplete(response, param); + }).bind(this); + + $super(url, options); + }, + + updateContent: function(responseText) { + var receiver = this.container[this.success() ? 'success' : 'failure'], + options = this.options; + + if (!options.evalScripts) responseText = responseText.stripScripts(); + + if (receiver = $(receiver)) { + if (options.insertion) { + if (Object.isString(options.insertion)) { + var insertion = { }; insertion[options.insertion] = responseText; + receiver.insert(insertion); + } + else options.insertion(receiver, responseText); + } + else receiver.update(responseText); + } + + if (this.success()) { + if (this.onComplete) this.onComplete.bind(this).defer(); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { + initialize: function($super, container, url, options) { + $super(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = { }; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.options.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(response) { + if (this.options.decay) { + this.decay = (response.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = response.responseText; + } + this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); +function $(element) { + if (arguments.length > 1) { + for (var i = 0, elements = [], length = arguments.length; i < length; i++) + elements.push($(arguments[i])); + return elements; + } + if (Object.isString(element)) + element = document.getElementById(element); + return Element.extend(element); +} + +if (Prototype.BrowserFeatures.XPath) { + document._getElementsByXPath = function(expression, parentElement) { + var results = []; + var query = document.evaluate(expression, $(parentElement) || document, + null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (var i = 0, length = query.snapshotLength; i < length; i++) + results.push(Element.extend(query.snapshotItem(i))); + return results; + }; +} + +/*--------------------------------------------------------------------------*/ + +if (!window.Node) var Node = { }; + +if (!Node.ELEMENT_NODE) { + // DOM level 2 ECMAScript Language Binding + Object.extend(Node, { + ELEMENT_NODE: 1, + ATTRIBUTE_NODE: 2, + TEXT_NODE: 3, + CDATA_SECTION_NODE: 4, + ENTITY_REFERENCE_NODE: 5, + ENTITY_NODE: 6, + PROCESSING_INSTRUCTION_NODE: 7, + COMMENT_NODE: 8, + DOCUMENT_NODE: 9, + DOCUMENT_TYPE_NODE: 10, + DOCUMENT_FRAGMENT_NODE: 11, + NOTATION_NODE: 12 + }); +} + +(function() { + var element = this.Element; + this.Element = function(tagName, attributes) { + attributes = attributes || { }; + tagName = tagName.toLowerCase(); + var cache = Element.cache; + if (Prototype.Browser.IE && attributes.name) { + tagName = '<' + tagName + ' name="' + attributes.name + '">'; + delete attributes.name; + return Element.writeAttribute(document.createElement(tagName), attributes); + } + if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); + return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); + }; + Object.extend(this.Element, element || { }); +}).call(window); + +Element.cache = { }; + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function(element) { + element = $(element); + Element[Element.visible(element) ? 'hide' : 'show'](element); + return element; + }, + + hide: function(element) { + $(element).style.display = 'none'; + return element; + }, + + show: function(element) { + $(element).style.display = ''; + return element; + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + return element; + }, + + update: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) return element.update().insert(content); + content = Object.toHTML(content); + element.innerHTML = content.stripScripts(); + content.evalScripts.bind(content).defer(); + return element; + }, + + replace: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + else if (!Object.isElement(content)) { + content = Object.toHTML(content); + var range = element.ownerDocument.createRange(); + range.selectNode(element); + content.evalScripts.bind(content).defer(); + content = range.createContextualFragment(content.stripScripts()); + } + element.parentNode.replaceChild(content, element); + return element; + }, + + insert: function(element, insertions) { + element = $(element); + + if (Object.isString(insertions) || Object.isNumber(insertions) || + Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) + insertions = {bottom:insertions}; + + var content, t, range; + + for (position in insertions) { + content = insertions[position]; + position = position.toLowerCase(); + t = Element._insertionTranslations[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + t.insert(element, content); + continue; + } + + content = Object.toHTML(content); + + range = element.ownerDocument.createRange(); + t.initializeRange(element, range); + t.insert(element, range.createContextualFragment(content.stripScripts())); + + content.evalScripts.bind(content).defer(); + } + + return element; + }, + + wrap: function(element, wrapper, attributes) { + element = $(element); + if (Object.isElement(wrapper)) + $(wrapper).writeAttribute(attributes || { }); + else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes); + else wrapper = new Element('div', wrapper); + if (element.parentNode) + element.parentNode.replaceChild(wrapper, element); + wrapper.appendChild(element); + return wrapper; + }, + + inspect: function(element) { + element = $(element); + var result = '<' + element.tagName.toLowerCase(); + $H({'id': 'id', 'className': 'class'}).each(function(pair) { + var property = pair.first(), attribute = pair.last(); + var value = (element[property] || '').toString(); + if (value) result += ' ' + attribute + '=' + value.inspect(true); + }); + return result + '>'; + }, + + recursivelyCollect: function(element, property) { + element = $(element); + var elements = []; + while (element = element[property]) + if (element.nodeType == 1) + elements.push(Element.extend(element)); + return elements; + }, + + ancestors: function(element) { + return $(element).recursivelyCollect('parentNode'); + }, + + descendants: function(element) { + return $A($(element).getElementsByTagName('*')).each(Element.extend); + }, + + firstDescendant: function(element) { + element = $(element).firstChild; + while (element && element.nodeType != 1) element = element.nextSibling; + return $(element); + }, + + immediateDescendants: function(element) { + if (!(element = $(element).firstChild)) return []; + while (element && element.nodeType != 1) element = element.nextSibling; + if (element) return [element].concat($(element).nextSiblings()); + return []; + }, + + previousSiblings: function(element) { + return $(element).recursivelyCollect('previousSibling'); + }, + + nextSiblings: function(element) { + return $(element).recursivelyCollect('nextSibling'); + }, + + siblings: function(element) { + element = $(element); + return element.previousSiblings().reverse().concat(element.nextSiblings()); + }, + + match: function(element, selector) { + if (Object.isString(selector)) + selector = new Selector(selector); + return selector.match($(element)); + }, + + up: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(element.parentNode); + var ancestors = element.ancestors(); + return expression ? Selector.findElement(ancestors, expression, index) : + ancestors[index || 0]; + }, + + down: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return element.firstDescendant(); + var descendants = element.descendants(); + return expression ? Selector.findElement(descendants, expression, index) : + descendants[index || 0]; + }, + + previous: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); + var previousSiblings = element.previousSiblings(); + return expression ? Selector.findElement(previousSiblings, expression, index) : + previousSiblings[index || 0]; + }, + + next: function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); + var nextSiblings = element.nextSiblings(); + return expression ? Selector.findElement(nextSiblings, expression, index) : + nextSiblings[index || 0]; + }, + + select: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element, args); + }, + + adjacent: function() { + var args = $A(arguments), element = $(args.shift()); + return Selector.findChildElements(element.parentNode, args).without(element); + }, + + identify: function(element) { + element = $(element); + var id = element.readAttribute('id'), self = arguments.callee; + if (id) return id; + do { id = 'anonymous_element_' + self.counter++ } while ($(id)); + element.writeAttribute('id', id); + return id; + }, + + readAttribute: function(element, name) { + element = $(element); + if (Prototype.Browser.IE) { + var t = Element._attributeTranslations.read; + if (t.values[name]) return t.values[name](element, name); + if (t.names[name]) name = t.names[name]; + if (name.include(':')) { + return (!element.attributes || !element.attributes[name]) ? null : + element.attributes[name].value; + } + } + return element.getAttribute(name); + }, + + writeAttribute: function(element, name, value) { + element = $(element); + var attributes = { }, t = Element._attributeTranslations.write; + + if (typeof name == 'object') attributes = name; + else attributes[name] = value === undefined ? true : value; + + for (var attr in attributes) { + var name = t.names[attr] || attr, value = attributes[attr]; + if (t.values[attr]) name = t.values[attr](element, value); + if (value === false || value === null) + element.removeAttribute(name); + else if (value === true) + element.setAttribute(name, name); + else element.setAttribute(name, value); + } + return element; + }, + + getHeight: function(element) { + return $(element).getDimensions().height; + }, + + getWidth: function(element) { + return $(element).getDimensions().width; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + var elementClassName = element.className; + return (elementClassName.length > 0 && (elementClassName == className || + new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + if (!element.hasClassName(className)) + element.className += (element.className ? ' ' : '') + className; + return element; + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + element.className = element.className.replace( + new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip(); + return element; + }, + + toggleClassName: function(element, className) { + if (!(element = $(element))) return; + return element[element.hasClassName(className) ? + 'removeClassName' : 'addClassName'](className); + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + var node = element.firstChild; + while (node) { + var nextNode = node.nextSibling; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + element.removeChild(node); + node = nextNode; + } + return element; + }, + + empty: function(element) { + return $(element).innerHTML.blank(); + }, + + descendantOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + + if (element.compareDocumentPosition) + return (element.compareDocumentPosition(ancestor) & 8) === 8; + + if (element.sourceIndex && !Prototype.Browser.Opera) { + var e = element.sourceIndex, a = ancestor.sourceIndex, + nextAncestor = ancestor.nextSibling; + if (!nextAncestor) { + do { ancestor = ancestor.parentNode; } + while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode); + } + if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex); + } + + while (element = element.parentNode) + if (element == ancestor) return true; + return false; + }, + + scrollTo: function(element) { + element = $(element); + var pos = element.cumulativeOffset(); + window.scrollTo(pos[0], pos[1]); + return element; + }, + + getStyle: function(element, style) { + element = $(element); + style = style == 'float' ? 'cssFloat' : style.camelize(); + var value = element.style[style]; + if (!value) { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css[style] : null; + } + if (style == 'opacity') return value ? parseFloat(value) : 1.0; + return value == 'auto' ? null : value; + }, + + getOpacity: function(element) { + return $(element).getStyle('opacity'); + }, + + setStyle: function(element, styles) { + element = $(element); + var elementStyle = element.style, match; + if (Object.isString(styles)) { + element.style.cssText += ';' + styles; + return styles.include('opacity') ? + element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element; + } + for (var property in styles) + if (property == 'opacity') element.setOpacity(styles[property]); + else + elementStyle[(property == 'float' || property == 'cssFloat') ? + (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') : + property] = styles[property]; + + return element; + }, + + setOpacity: function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + return element; + }, + + getDimensions: function(element) { + element = $(element); + var display = $(element).getStyle('display'); + if (display != 'none' && display != null) // Safari bug + return {width: element.offsetWidth, height: element.offsetHeight}; + + // All *Width and *Height properties give 0 on elements with display none, + // so enable the element temporarily + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + var originalDisplay = els.display; + els.visibility = 'hidden'; + els.position = 'absolute'; + els.display = 'block'; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = originalDisplay; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + // Opera returns the offset relative to the positioning context, when an + // element is position relative but top and left have not been defined + if (window.opera) { + element.style.top = 0; + element.style.left = 0; + } + } + return element; + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + return element; + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return element; + element._overflow = Element.getStyle(element, 'overflow') || 'auto'; + if (element._overflow !== 'hidden') + element.style.overflow = 'hidden'; + return element; + }, + + undoClipping: function(element) { + element = $(element); + if (!element._overflow) return element; + element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; + element._overflow = null; + return element; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if (element.tagName == 'BODY') break; + var p = Element.getStyle(element, 'position'); + if (p == 'relative' || p == 'absolute') break; + } + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + absolutize: function(element) { + element = $(element); + if (element.getStyle('position') == 'absolute') return; + // Position.prepare(); // To be done manually by Scripty when it needs it. + + var offsets = element.positionedOffset(); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.width = width + 'px'; + element.style.height = height + 'px'; + return element; + }, + + relativize: function(element) { + element = $(element); + if (element.getStyle('position') == 'relative') return; + // Position.prepare(); // To be done manually by Scripty when it needs it. + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + return element; + }, + + cumulativeScrollOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return Element._returnOffset(valueL, valueT); + }, + + getOffsetParent: function(element) { + if (element.offsetParent) return $(element.offsetParent); + if (element == document.body) return $(element); + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return $(element); + + return $(document.body); + }, + + viewportOffset: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + // Safari fix + if (element.offsetParent == document.body && + Element.getStyle(element, 'position') == 'absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + if (!Prototype.Browser.Opera || element.tagName == 'BODY') { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + + return Element._returnOffset(valueL, valueT); + }, + + clonePosition: function(element, source) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || { }); + + // find page position of source + source = $(source); + var p = source.viewportOffset(); + + // find coordinate system to use + element = $(element); + var delta = [0, 0]; + var parent = null; + // delta [0,0] will do fine with position: fixed elements, + // position:absolute needs offsetParent deltas + if (Element.getStyle(element, 'position') == 'absolute') { + parent = element.getOffsetParent(); + delta = parent.viewportOffset(); + } + + // correct by body offsets (fixes Safari) + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + // set position + if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if (options.setWidth) element.style.width = source.offsetWidth + 'px'; + if (options.setHeight) element.style.height = source.offsetHeight + 'px'; + return element; + } +}; + +Element.Methods.identify.counter = 1; + +Object.extend(Element.Methods, { + getElementsBySelector: Element.Methods.select, + childElements: Element.Methods.immediateDescendants +}); + +Element._attributeTranslations = { + write: { + names: { + className: 'class', + htmlFor: 'for' + }, + values: { } + } +}; + + +if (!document.createRange || Prototype.Browser.Opera) { + Element.Methods.insert = function(element, insertions) { + element = $(element); + + if (Object.isString(insertions) || Object.isNumber(insertions) || + Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML))) + insertions = { bottom: insertions }; + + var t = Element._insertionTranslations, content, position, pos, tagName; + + for (position in insertions) { + content = insertions[position]; + position = position.toLowerCase(); + pos = t[position]; + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + pos.insert(element, content); + continue; + } + + content = Object.toHTML(content); + tagName = ((position == 'before' || position == 'after') + ? element.parentNode : element).tagName.toUpperCase(); + + if (t.tags[tagName]) { + var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + if (position == 'top' || position == 'after') fragments.reverse(); + fragments.each(pos.insert.curry(element)); + } + else element.insertAdjacentHTML(pos.adjacency, content.stripScripts()); + + content.evalScripts.bind(content).defer(); + } + + return element; + }; +} + +if (Prototype.Browser.Opera) { + Element.Methods._getStyle = Element.Methods.getStyle; + Element.Methods.getStyle = function(element, style) { + switch(style) { + case 'left': + case 'top': + case 'right': + case 'bottom': + if (Element._getStyle(element, 'position') == 'static') return null; + default: return Element._getStyle(element, style); + } + }; + Element.Methods._readAttribute = Element.Methods.readAttribute; + Element.Methods.readAttribute = function(element, attribute) { + if (attribute == 'title') return element.title; + return Element._readAttribute(element, attribute); + }; +} + +else if (Prototype.Browser.IE) { + $w('positionedOffset getOffsetParent viewportOffset').each(function(method) { + Element.Methods[method] = Element.Methods[method].wrap( + function(proceed, element) { + element = $(element); + var position = element.getStyle('position'); + if (position != 'static') return proceed(element); + element.setStyle({ position: 'relative' }); + var value = proceed(element); + element.setStyle({ position: position }); + return value; + } + ); + }); + + Element.Methods.getStyle = function(element, style) { + element = $(element); + style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); + var value = element.style[style]; + if (!value && element.currentStyle) value = element.currentStyle[style]; + + if (style == 'opacity') { + if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) + if (value[1]) return parseFloat(value[1]) / 100; + return 1.0; + } + + if (value == 'auto') { + if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none')) + return element['offset' + style.capitalize()] + 'px'; + return null; + } + return value; + }; + + Element.Methods.setOpacity = function(element, value) { + function stripAlpha(filter){ + return filter.replace(/alpha\([^\)]*\)/gi,''); + } + element = $(element); + var currentStyle = element.currentStyle; + if ((currentStyle && !currentStyle.hasLayout) || + (!currentStyle && element.style.zoom == 'normal')) + element.style.zoom = 1; + + var filter = element.getStyle('filter'), style = element.style; + if (value == 1 || value === '') { + (filter = stripAlpha(filter)) ? + style.filter = filter : style.removeAttribute('filter'); + return element; + } else if (value < 0.00001) value = 0; + style.filter = stripAlpha(filter) + + 'alpha(opacity=' + (value * 100) + ')'; + return element; + }; + + Element._attributeTranslations = { + read: { + names: { + 'class': 'className', + 'for': 'htmlFor' + }, + values: { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + _getAttrNode: function(element, attribute) { + var node = element.getAttributeNode(attribute); + return node ? node.value : ""; + }, + _getEv: function(element, attribute) { + var attribute = element.getAttribute(attribute); + return attribute ? attribute.toString().slice(23, -2) : null; + }, + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + title: function(element) { + return element.title; + } + } + } + }; + + Element._attributeTranslations.write = { + names: Object.clone(Element._attributeTranslations.read.names), + values: { + checked: function(element, value) { + element.checked = !!value; + }, + + style: function(element, value) { + element.style.cssText = value ? value : ''; + } + } + }; + + Element._attributeTranslations.has = {}; + + $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' + + 'encType maxLength readOnly longDesc').each(function(attr) { + Element._attributeTranslations.write.names[attr.toLowerCase()] = attr; + Element._attributeTranslations.has[attr.toLowerCase()] = attr; + }); + + (function(v) { + Object.extend(v, { + href: v._getAttr, + src: v._getAttr, + type: v._getAttr, + action: v._getAttrNode, + disabled: v._flag, + checked: v._flag, + readonly: v._flag, + multiple: v._flag, + onload: v._getEv, + onunload: v._getEv, + onclick: v._getEv, + ondblclick: v._getEv, + onmousedown: v._getEv, + onmouseup: v._getEv, + onmouseover: v._getEv, + onmousemove: v._getEv, + onmouseout: v._getEv, + onfocus: v._getEv, + onblur: v._getEv, + onkeypress: v._getEv, + onkeydown: v._getEv, + onkeyup: v._getEv, + onsubmit: v._getEv, + onreset: v._getEv, + onselect: v._getEv, + onchange: v._getEv + }); + })(Element._attributeTranslations.read.values); +} + +else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1) ? 0.999999 : + (value === '') ? '' : (value < 0.00001) ? 0 : value; + return element; + }; +} + +else if (Prototype.Browser.WebKit) { + Element.Methods.setOpacity = function(element, value) { + element = $(element); + element.style.opacity = (value == 1 || value === '') ? '' : + (value < 0.00001) ? 0 : value; + + if (value == 1) + if(element.tagName == 'IMG' && element.width) { + element.width++; element.width--; + } else try { + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch (e) { } + + return element; + }; + + // Safari returns margins on body which is incorrect if the child is absolutely + // positioned. For performance reasons, redefine Position.cumulativeOffset for + // KHTML/WebKit only. + Element.Methods.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return Element._returnOffset(valueL, valueT); + }; +} + +if (Prototype.Browser.IE || Prototype.Browser.Opera) { + // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements + Element.Methods.update = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) return element.update().insert(content); + + content = Object.toHTML(content); + var tagName = element.tagName.toUpperCase(); + + if (tagName in Element._insertionTranslations.tags) { + $A(element.childNodes).each(function(node) { element.removeChild(node) }); + Element._getContentFromAnonymousElement(tagName, content.stripScripts()) + .each(function(node) { element.appendChild(node) }); + } + else element.innerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +if (document.createElement('div').outerHTML) { + Element.Methods.replace = function(element, content) { + element = $(element); + + if (content && content.toElement) content = content.toElement(); + if (Object.isElement(content)) { + element.parentNode.replaceChild(content, element); + return element; + } + + content = Object.toHTML(content); + var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); + + if (Element._insertionTranslations.tags[tagName]) { + var nextSibling = element.next(); + var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + parent.removeChild(element); + if (nextSibling) + fragments.each(function(node) { parent.insertBefore(node, nextSibling) }); + else + fragments.each(function(node) { parent.appendChild(node) }); + } + else element.outerHTML = content.stripScripts(); + + content.evalScripts.bind(content).defer(); + return element; + }; +} + +Element._returnOffset = function(l, t) { + var result = [l, t]; + result.left = l; + result.top = t; + return result; +}; + +Element._getContentFromAnonymousElement = function(tagName, html) { + var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; + div.innerHTML = t[0] + html + t[1]; + t[2].times(function() { div = div.firstChild }); + return $A(div.childNodes); +}; + +Element._insertionTranslations = { + before: { + adjacency: 'beforeBegin', + insert: function(element, node) { + element.parentNode.insertBefore(node, element); + }, + initializeRange: function(element, range) { + range.setStartBefore(element); + } + }, + top: { + adjacency: 'afterBegin', + insert: function(element, node) { + element.insertBefore(node, element.firstChild); + }, + initializeRange: function(element, range) { + range.selectNodeContents(element); + range.collapse(true); + } + }, + bottom: { + adjacency: 'beforeEnd', + insert: function(element, node) { + element.appendChild(node); + } + }, + after: { + adjacency: 'afterEnd', + insert: function(element, node) { + element.parentNode.insertBefore(node, element.nextSibling); + }, + initializeRange: function(element, range) { + range.setStartAfter(element); + } + }, + tags: { + TABLE: ['', '
    ', 1], + TBODY: ['', '
    ', 2], + TR: ['', '
    ', 3], + TD: ['
    ', '
    ', 4], + SELECT: ['', 1] + } +}; + +(function() { + this.bottom.initializeRange = this.top.initializeRange; + Object.extend(this.tags, { + THEAD: this.tags.TBODY, + TFOOT: this.tags.TBODY, + TH: this.tags.TD + }); +}).call(Element._insertionTranslations); + +Element.Methods.Simulated = { + hasAttribute: function(element, attribute) { + attribute = Element._attributeTranslations.has[attribute] || attribute; + var node = $(element).getAttributeNode(attribute); + return node && node.specified; + } +}; + +Element.Methods.ByTag = { }; + +Object.extend(Element, Element.Methods); + +if (!Prototype.BrowserFeatures.ElementExtensions && + document.createElement('div').__proto__) { + window.HTMLElement = { }; + window.HTMLElement.prototype = document.createElement('div').__proto__; + Prototype.BrowserFeatures.ElementExtensions = true; +} + +Element.extend = (function() { + if (Prototype.BrowserFeatures.SpecificElementExtensions) + return Prototype.K; + + var Methods = { }, ByTag = Element.Methods.ByTag; + + var extend = Object.extend(function(element) { + if (!element || element._extendedByPrototype || + element.nodeType != 1 || element == window) return element; + + var methods = Object.clone(Methods), + tagName = element.tagName, property, value; + + // extend methods for specific tags + if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); + + for (property in methods) { + value = methods[property]; + if (Object.isFunction(value) && !(property in element)) + element[property] = value.methodize(); + } + + element._extendedByPrototype = Prototype.emptyFunction; + return element; + + }, { + refresh: function() { + // extend methods for all tags (Safari doesn't need this) + if (!Prototype.BrowserFeatures.ElementExtensions) { + Object.extend(Methods, Element.Methods); + Object.extend(Methods, Element.Methods.Simulated); + } + } + }); + + extend.refresh(); + return extend; +})(); + +Element.hasAttribute = function(element, attribute) { + if (element.hasAttribute) return element.hasAttribute(attribute); + return Element.Methods.Simulated.hasAttribute(element, attribute); +}; + +Element.addMethods = function(methods) { + var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; + + if (!methods) { + Object.extend(Form, Form.Methods); + Object.extend(Form.Element, Form.Element.Methods); + Object.extend(Element.Methods.ByTag, { + "FORM": Object.clone(Form.Methods), + "INPUT": Object.clone(Form.Element.Methods), + "SELECT": Object.clone(Form.Element.Methods), + "TEXTAREA": Object.clone(Form.Element.Methods) + }); + } + + if (arguments.length == 2) { + var tagName = methods; + methods = arguments[1]; + } + + if (!tagName) Object.extend(Element.Methods, methods || { }); + else { + if (Object.isArray(tagName)) tagName.each(extend); + else extend(tagName); + } + + function extend(tagName) { + tagName = tagName.toUpperCase(); + if (!Element.Methods.ByTag[tagName]) + Element.Methods.ByTag[tagName] = { }; + Object.extend(Element.Methods.ByTag[tagName], methods); + } + + function copy(methods, destination, onlyIfAbsent) { + onlyIfAbsent = onlyIfAbsent || false; + for (var property in methods) { + var value = methods[property]; + if (!Object.isFunction(value)) continue; + if (!onlyIfAbsent || !(property in destination)) + destination[property] = value.methodize(); + } + } + + function findDOMClass(tagName) { + var klass; + var trans = { + "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph", + "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList", + "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading", + "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote", + "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION": + "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD": + "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR": + "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET": + "FrameSet", "IFRAME": "IFrame" + }; + if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName + 'Element'; + if (window[klass]) return window[klass]; + klass = 'HTML' + tagName.capitalize() + 'Element'; + if (window[klass]) return window[klass]; + + window[klass] = { }; + window[klass].prototype = document.createElement(tagName).__proto__; + return window[klass]; + } + + if (F.ElementExtensions) { + copy(Element.Methods, HTMLElement.prototype); + copy(Element.Methods.Simulated, HTMLElement.prototype, true); + } + + if (F.SpecificElementExtensions) { + for (var tag in Element.Methods.ByTag) { + var klass = findDOMClass(tag); + if (Object.isUndefined(klass)) continue; + copy(T[tag], klass.prototype); + } + } + + Object.extend(Element, Element.Methods); + delete Element.ByTag; + + if (Element.extend.refresh) Element.extend.refresh(); + Element.cache = { }; +}; + +document.viewport = { + getDimensions: function() { + var dimensions = { }; + $w('width height').each(function(d) { + var D = d.capitalize(); + dimensions[d] = self['inner' + D] || + (document.documentElement['client' + D] || document.body['client' + D]); + }); + return dimensions; + }, + + getWidth: function() { + return this.getDimensions().width; + }, + + getHeight: function() { + return this.getDimensions().height; + }, + + getScrollOffsets: function() { + return Element._returnOffset( + window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, + window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); + } +}; +/* Portions of the Selector class are derived from Jack Slocum’s DomQuery, + * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style + * license. Please see http://www.yui-ext.com/ for more information. */ + +var Selector = Class.create({ + initialize: function(expression) { + this.expression = expression.strip(); + this.compileMatcher(); + }, + + compileMatcher: function() { + // Selectors with namespaced attributes can't use the XPath version + if (Prototype.BrowserFeatures.XPath && !(/(\[[\w-]*?:|:checked)/).test(this.expression)) + return this.compileXPathMatcher(); + + var e = this.expression, ps = Selector.patterns, h = Selector.handlers, + c = Selector.criteria, le, p, m; + + if (Selector._cache[e]) { + this.matcher = Selector._cache[e]; + return; + } + + this.matcher = ["this.matcher = function(root) {", + "var r = root, h = Selector.handlers, c = false, n;"]; + + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + p = ps[i]; + if (m = e.match(p)) { + this.matcher.push(Object.isFunction(c[i]) ? c[i](m) : + new Template(c[i]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.matcher.push("return h.unique(n);\n}"); + eval(this.matcher.join('\n')); + Selector._cache[this.expression] = this.matcher; + }, + + compileXPathMatcher: function() { + var e = this.expression, ps = Selector.patterns, + x = Selector.xpath, le, m; + + if (Selector._cache[e]) { + this.xpath = Selector._cache[e]; return; + } + + this.matcher = ['.//*']; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + if (m = e.match(ps[i])) { + this.matcher.push(Object.isFunction(x[i]) ? x[i](m) : + new Template(x[i]).evaluate(m)); + e = e.replace(m[0], ''); + break; + } + } + } + + this.xpath = this.matcher.join(''); + Selector._cache[this.expression] = this.xpath; + }, + + findElements: function(root) { + root = root || document; + if (this.xpath) return document._getElementsByXPath(this.xpath, root); + return this.matcher(root); + }, + + match: function(element) { + this.tokens = []; + + var e = this.expression, ps = Selector.patterns, as = Selector.assertions; + var le, p, m; + + while (e && le !== e && (/\S/).test(e)) { + le = e; + for (var i in ps) { + p = ps[i]; + if (m = e.match(p)) { + // use the Selector.assertions methods unless the selector + // is too complex. + if (as[i]) { + this.tokens.push([i, Object.clone(m)]); + e = e.replace(m[0], ''); + } else { + // reluctantly do a document-wide search + // and look for a match in the array + return this.findElements(document).include(element); + } + } + } + } + + var match = true, name, matches; + for (var i = 0, token; token = this.tokens[i]; i++) { + name = token[0], matches = token[1]; + if (!Selector.assertions[name](element, matches)) { + match = false; break; + } + } + + return match; + }, + + toString: function() { + return this.expression; + }, + + inspect: function() { + return "#"; + } +}); + +Object.extend(Selector, { + _cache: { }, + + xpath: { + descendant: "//*", + child: "/*", + adjacent: "/following-sibling::*[1]", + laterSibling: '/following-sibling::*', + tagName: function(m) { + if (m[1] == '*') return ''; + return "[local-name()='" + m[1].toLowerCase() + + "' or local-name()='" + m[1].toUpperCase() + "']"; + }, + className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", + id: "[@id='#{1}']", + attrPresence: "[@#{1}]", + attr: function(m) { + m[3] = m[5] || m[6]; + return new Template(Selector.xpath.operators[m[2]]).evaluate(m); + }, + pseudo: function(m) { + var h = Selector.xpath.pseudos[m[1]]; + if (!h) return ''; + if (Object.isFunction(h)) return h(m); + return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); + }, + operators: { + '=': "[@#{1}='#{3}']", + '!=': "[@#{1}!='#{3}']", + '^=': "[starts-with(@#{1}, '#{3}')]", + '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", + '*=': "[contains(@#{1}, '#{3}')]", + '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", + '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" + }, + pseudos: { + 'first-child': '[not(preceding-sibling::*)]', + 'last-child': '[not(following-sibling::*)]', + 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', + 'empty': "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]", + 'checked': "[@checked]", + 'disabled': "[@disabled]", + 'enabled': "[not(@disabled)]", + 'not': function(m) { + var e = m[6], p = Selector.patterns, + x = Selector.xpath, le, m, v; + + var exclusion = []; + while (e && le != e && (/\S/).test(e)) { + le = e; + for (var i in p) { + if (m = e.match(p[i])) { + v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m); + exclusion.push("(" + v.substring(1, v.length - 1) + ")"); + e = e.replace(m[0], ''); + break; + } + } + } + return "[not(" + exclusion.join(" and ") + ")]"; + }, + 'nth-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); + }, + 'nth-last-child': function(m) { + return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); + }, + 'nth-of-type': function(m) { + return Selector.xpath.pseudos.nth("position() ", m); + }, + 'nth-last-of-type': function(m) { + return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); + }, + 'first-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); + }, + 'last-of-type': function(m) { + m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); + }, + 'only-of-type': function(m) { + var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); + }, + nth: function(fragment, m) { + var mm, formula = m[6], predicate; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + if (mm = formula.match(/^(\d+)$/)) // digit only + return '[' + fragment + "= " + mm[1] + ']'; + if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (mm[1] == "-") mm[1] = -1; + var a = mm[1] ? Number(mm[1]) : 1; + var b = mm[2] ? Number(mm[2]) : 0; + predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + + "((#{fragment} - #{b}) div #{a} >= 0)]"; + return new Template(predicate).evaluate({ + fragment: fragment, a: a, b: b }); + } + } + } + }, + + criteria: { + tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', + className: 'n = h.className(n, r, "#{1}", c); c = false;', + id: 'n = h.id(n, r, "#{1}", c); c = false;', + attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;', + attr: function(m) { + m[3] = (m[5] || m[6]); + return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m); + }, + pseudo: function(m) { + if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); + return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); + }, + descendant: 'c = "descendant";', + child: 'c = "child";', + adjacent: 'c = "adjacent";', + laterSibling: 'c = "laterSibling";' + }, + + patterns: { + // combinators must be listed first + // (and descendant needs to be last combinator) + laterSibling: /^\s*~\s*/, + child: /^\s*>\s*/, + adjacent: /^\s*\+\s*/, + descendant: /^\s/, + + // selectors follow + tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, + id: /^#([\w\-\*]+)(\b|$)/, + className: /^\.([\w\-\*]+)(\b|$)/, + pseudo: /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s)|(?=:))/, + attrPresence: /^\[([\w]+)\]/, + attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ + }, + + // for Selector.match and Element#match + assertions: { + tagName: function(element, matches) { + return matches[1].toUpperCase() == element.tagName.toUpperCase(); + }, + + className: function(element, matches) { + return Element.hasClassName(element, matches[1]); + }, + + id: function(element, matches) { + return element.id === matches[1]; + }, + + attrPresence: function(element, matches) { + return Element.hasAttribute(element, matches[1]); + }, + + attr: function(element, matches) { + var nodeValue = Element.readAttribute(element, matches[1]); + return Selector.operators[matches[2]](nodeValue, matches[3]); + } + }, + + handlers: { + // UTILITY FUNCTIONS + // joins two collections + concat: function(a, b) { + for (var i = 0, node; node = b[i]; i++) + a.push(node); + return a; + }, + + // marks an array of nodes for counting + mark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node._counted = true; + return nodes; + }, + + unmark: function(nodes) { + for (var i = 0, node; node = nodes[i]; i++) + node._counted = undefined; + return nodes; + }, + + // mark each child node with its position (for nth calls) + // "ofType" flag indicates whether we're indexing for nth-of-type + // rather than nth-child + index: function(parentNode, reverse, ofType) { + parentNode._counted = true; + if (reverse) { + for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { + var node = nodes[i]; + if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; + } + } else { + for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) + if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++; + } + }, + + // filters out duplicates and extends all nodes + unique: function(nodes) { + if (nodes.length == 0) return nodes; + var results = [], n; + for (var i = 0, l = nodes.length; i < l; i++) + if (!(n = nodes[i])._counted) { + n._counted = true; + results.push(Element.extend(n)); + } + return Selector.handlers.unmark(results); + }, + + // COMBINATOR FUNCTIONS + descendant: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName('*')); + return results; + }, + + child: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) { + for (var j = 0, children = [], child; child = node.childNodes[j]; j++) + if (child.nodeType == 1 && child.tagName != '!') results.push(child); + } + return results; + }, + + adjacent: function(nodes) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + var next = this.nextElementSibling(node); + if (next) results.push(next); + } + return results; + }, + + laterSibling: function(nodes) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + h.concat(results, Element.nextSiblings(node)); + return results; + }, + + nextElementSibling: function(node) { + while (node = node.nextSibling) + if (node.nodeType == 1) return node; + return null; + }, + + previousElementSibling: function(node) { + while (node = node.previousSibling) + if (node.nodeType == 1) return node; + return null; + }, + + // TOKEN FUNCTIONS + tagName: function(nodes, root, tagName, combinator) { + tagName = tagName.toUpperCase(); + var results = [], h = Selector.handlers; + if (nodes) { + if (combinator) { + // fastlane for ordinary descendant combinators + if (combinator == "descendant") { + for (var i = 0, node; node = nodes[i]; i++) + h.concat(results, node.getElementsByTagName(tagName)); + return results; + } else nodes = this[combinator](nodes); + if (tagName == "*") return nodes; + } + for (var i = 0, node; node = nodes[i]; i++) + if (node.tagName.toUpperCase() == tagName) results.push(node); + return results; + } else return root.getElementsByTagName(tagName); + }, + + id: function(nodes, root, id, combinator) { + var targetNode = $(id), h = Selector.handlers; + if (!targetNode) return []; + if (!nodes && root == document) return [targetNode]; + if (nodes) { + if (combinator) { + if (combinator == 'child') { + for (var i = 0, node; node = nodes[i]; i++) + if (targetNode.parentNode == node) return [targetNode]; + } else if (combinator == 'descendant') { + for (var i = 0, node; node = nodes[i]; i++) + if (Element.descendantOf(targetNode, node)) return [targetNode]; + } else if (combinator == 'adjacent') { + for (var i = 0, node; node = nodes[i]; i++) + if (Selector.handlers.previousElementSibling(targetNode) == node) + return [targetNode]; + } else nodes = h[combinator](nodes); + } + for (var i = 0, node; node = nodes[i]; i++) + if (node == targetNode) return [targetNode]; + return []; + } + return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; + }, + + className: function(nodes, root, className, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + return Selector.handlers.byClassName(nodes, root, className); + }, + + byClassName: function(nodes, root, className) { + if (!nodes) nodes = Selector.handlers.descendant([root]); + var needle = ' ' + className + ' '; + for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { + nodeClassName = node.className; + if (nodeClassName.length == 0) continue; + if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) + results.push(node); + } + return results; + }, + + attrPresence: function(nodes, root, attr) { + if (!nodes) nodes = root.getElementsByTagName("*"); + var results = []; + for (var i = 0, node; node = nodes[i]; i++) + if (Element.hasAttribute(node, attr)) results.push(node); + return results; + }, + + attr: function(nodes, root, attr, value, operator) { + if (!nodes) nodes = root.getElementsByTagName("*"); + var handler = Selector.operators[operator], results = []; + for (var i = 0, node; node = nodes[i]; i++) { + var nodeValue = Element.readAttribute(node, attr); + if (nodeValue === null) continue; + if (handler(nodeValue, value)) results.push(node); + } + return results; + }, + + pseudo: function(nodes, name, value, root, combinator) { + if (nodes && combinator) nodes = this[combinator](nodes); + if (!nodes) nodes = root.getElementsByTagName("*"); + return Selector.pseudos[name](nodes, value, root); + } + }, + + pseudos: { + 'first-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.previousElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'last-child': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + if (Selector.handlers.nextElementSibling(node)) continue; + results.push(node); + } + return results; + }, + 'only-child': function(nodes, value, root) { + var h = Selector.handlers; + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) + results.push(node); + return results; + }, + 'nth-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root); + }, + 'nth-last-child': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true); + }, + 'nth-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, false, true); + }, + 'nth-last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, formula, root, true, true); + }, + 'first-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, false, true); + }, + 'last-of-type': function(nodes, formula, root) { + return Selector.pseudos.nth(nodes, "1", root, true, true); + }, + 'only-of-type': function(nodes, formula, root) { + var p = Selector.pseudos; + return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); + }, + + // handles the an+b logic + getIndices: function(a, b, total) { + if (a == 0) return b > 0 ? [b] : []; + return $R(1, total).inject([], function(memo, i) { + if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); + return memo; + }); + }, + + // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type + nth: function(nodes, formula, root, reverse, ofType) { + if (nodes.length == 0) return []; + if (formula == 'even') formula = '2n+0'; + if (formula == 'odd') formula = '2n+1'; + var h = Selector.handlers, results = [], indexed = [], m; + h.mark(nodes); + for (var i = 0, node; node = nodes[i]; i++) { + if (!node.parentNode._counted) { + h.index(node.parentNode, reverse, ofType); + indexed.push(node.parentNode); + } + } + if (formula.match(/^\d+$/)) { // just a number + formula = Number(formula); + for (var i = 0, node; node = nodes[i]; i++) + if (node.nodeIndex == formula) results.push(node); + } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b + if (m[1] == "-") m[1] = -1; + var a = m[1] ? Number(m[1]) : 1; + var b = m[2] ? Number(m[2]) : 0; + var indices = Selector.pseudos.getIndices(a, b, nodes.length); + for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { + for (var j = 0; j < l; j++) + if (node.nodeIndex == indices[j]) results.push(node); + } + } + h.unmark(nodes); + h.unmark(indexed); + return results; + }, + + 'empty': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) { + // IE treats comments as element nodes + if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue; + results.push(node); + } + return results; + }, + + 'not': function(nodes, selector, root) { + var h = Selector.handlers, selectorType, m; + var exclusions = new Selector(selector).findElements(root); + h.mark(exclusions); + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node._counted) results.push(node); + h.unmark(exclusions); + return results; + }, + + 'enabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (!node.disabled) results.push(node); + return results; + }, + + 'disabled': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.disabled) results.push(node); + return results; + }, + + 'checked': function(nodes, value, root) { + for (var i = 0, results = [], node; node = nodes[i]; i++) + if (node.checked) results.push(node); + return results; + } + }, + + operators: { + '=': function(nv, v) { return nv == v; }, + '!=': function(nv, v) { return nv != v; }, + '^=': function(nv, v) { return nv.startsWith(v); }, + '$=': function(nv, v) { return nv.endsWith(v); }, + '*=': function(nv, v) { return nv.include(v); }, + '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, + '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); } + }, + + matchElements: function(elements, expression) { + var matches = new Selector(expression).findElements(), h = Selector.handlers; + h.mark(matches); + for (var i = 0, results = [], element; element = elements[i]; i++) + if (element._counted) results.push(element); + h.unmark(matches); + return results; + }, + + findElement: function(elements, expression, index) { + if (Object.isNumber(expression)) { + index = expression; expression = false; + } + return Selector.matchElements(elements, expression || '*')[index || 0]; + }, + + findChildElements: function(element, expressions) { + var exprs = expressions.join(','), expressions = []; + exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { + expressions.push(m[1].strip()); + }); + var results = [], h = Selector.handlers; + for (var i = 0, l = expressions.length, selector; i < l; i++) { + selector = new Selector(expressions[i].strip()); + h.concat(results, selector.findElements(element)); + } + return (l > 1) ? h.unique(results) : results; + } +}); + +function $$() { + return Selector.findChildElements(document, $A(arguments)); +} +var Form = { + reset: function(form) { + $(form).reset(); + return form; + }, + + serializeElements: function(elements, options) { + if (typeof options != 'object') options = { hash: !!options }; + else if (options.hash === undefined) options.hash = true; + var key, value, submitted = false, submit = options.submit; + + var data = elements.inject({ }, function(result, element) { + if (!element.disabled && element.name) { + key = element.name; value = $(element).getValue(); + if (value != null && (element.type != 'submit' || (!submitted && + submit !== false && (!submit || key == submit) && (submitted = true)))) { + if (key in result) { + // a key is already present; construct an array of values + if (!Object.isArray(result[key])) result[key] = [result[key]]; + result[key].push(value); + } + else result[key] = value; + } + } + return result; + }); + + return options.hash ? data : Object.toQueryString(data); + } +}; + +Form.Methods = { + serialize: function(form, options) { + return Form.serializeElements(Form.getElements(form), options); + }, + + getElements: function(form) { + return $A($(form).getElementsByTagName('*')).inject([], + function(elements, child) { + if (Form.Element.Serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + } + ); + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) return $A(inputs).map(Element.extend); + + for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || (name && input.name != name)) + continue; + matchingInputs.push(Element.extend(input)); + } + + return matchingInputs; + }, + + disable: function(form) { + form = $(form); + Form.getElements(form).invoke('disable'); + return form; + }, + + enable: function(form) { + form = $(form); + Form.getElements(form).invoke('enable'); + return form; + }, + + findFirstElement: function(form) { + var elements = $(form).getElements().findAll(function(element) { + return 'hidden' != element.type && !element.disabled; + }); + var firstByIndex = elements.findAll(function(element) { + return element.hasAttribute('tabIndex') && element.tabIndex >= 0; + }).sortBy(function(element) { return element.tabIndex }).first(); + + return firstByIndex ? firstByIndex : elements.find(function(element) { + return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + }); + }, + + focusFirstElement: function(form) { + form = $(form); + form.findFirstElement().activate(); + return form; + }, + + request: function(form, options) { + form = $(form), options = Object.clone(options || { }); + + var params = options.parameters, action = form.readAttribute('action') || ''; + if (action.blank()) action = window.location.href; + options.parameters = form.serialize(true); + + if (params) { + if (Object.isString(params)) params = params.toQueryParams(); + Object.extend(options.parameters, params); + } + + if (form.hasAttribute('method') && !options.method) + options.method = form.method; + + return new Ajax.Request(action, options); + } +}; + +/*--------------------------------------------------------------------------*/ + +Form.Element = { + focus: function(element) { + $(element).focus(); + return element; + }, + + select: function(element) { + $(element).select(); + return element; + } +}; + +Form.Element.Methods = { + serialize: function(element) { + element = $(element); + if (!element.disabled && element.name) { + var value = element.getValue(); + if (value != undefined) { + var pair = { }; + pair[element.name] = value; + return Object.toQueryString(pair); + } + } + return ''; + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + return Form.Element.Serializers[method](element); + }, + + setValue: function(element, value) { + element = $(element); + var method = element.tagName.toLowerCase(); + Form.Element.Serializers[method](element, value); + return element; + }, + + clear: function(element) { + $(element).value = ''; + return element; + }, + + present: function(element) { + return $(element).value != ''; + }, + + activate: function(element) { + element = $(element); + try { + element.focus(); + if (element.select && (element.tagName.toLowerCase() != 'input' || + !['button', 'reset', 'submit'].include(element.type))) + element.select(); + } catch (e) { } + return element; + }, + + disable: function(element) { + element = $(element); + element.blur(); + element.disabled = true; + return element; + }, + + enable: function(element) { + element = $(element); + element.disabled = false; + return element; + } +}; + +/*--------------------------------------------------------------------------*/ + +var Field = Form.Element; +var $F = Form.Element.Methods.getValue; + +/*--------------------------------------------------------------------------*/ + +Form.Element.Serializers = { + input: function(element, value) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element, value); + default: + return Form.Element.Serializers.textarea(element, value); + } + }, + + inputSelector: function(element, value) { + if (value === undefined) return element.checked ? element.value : null; + else element.checked = !!value; + }, + + textarea: function(element, value) { + if (value === undefined) return element.value; + else element.value = value; + }, + + select: function(element, index) { + if (index === undefined) + return this[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + else { + var opt, value, single = !Object.isArray(index); + for (var i = 0, length = element.length; i < length; i++) { + opt = element.options[i]; + value = this.optionValue(opt); + if (single) { + if (value == index) { + opt.selected = true; + return; + } + } + else opt.selected = index.include(value); + } + } + }, + + selectOne: function(element) { + var index = element.selectedIndex; + return index >= 0 ? this.optionValue(element.options[index]) : null; + }, + + selectMany: function(element) { + var values, length = element.length; + if (!length) return null; + + for (var i = 0, values = []; i < length; i++) { + var opt = element.options[i]; + if (opt.selected) values.push(this.optionValue(opt)); + } + return values; + }, + + optionValue: function(opt) { + // extend element because hasAttribute may not be native + return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; + } +}; + +/*--------------------------------------------------------------------------*/ + +Abstract.TimedObserver = Class.create(PeriodicalExecuter, { + initialize: function($super, element, frequency, callback) { + $super(callback, frequency); + this.element = $(element); + this.lastValue = this.getValue(); + }, + + execute: function() { + var value = this.getValue(); + if (Object.isString(this.lastValue) && Object.isString(value) ? + this.lastValue != value : String(this.lastValue) != String(value)) { + this.callback(this.element, value); + this.lastValue = value; + } + } +}); + +Form.Element.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(Abstract.TimedObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = Class.create({ + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + Form.getElements(this.element).each(this.registerCallback, this); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + default: + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +}); + +Form.Element.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(Abstract.EventObserver, { + getValue: function() { + return Form.serialize(this.element); + } +}); +if (!window.Event) var Event = { }; + +Object.extend(Event, { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + KEY_INSERT: 45, + + cache: { }, + + relatedTarget: function(event) { + var element; + switch(event.type) { + case 'mouseover': element = event.fromElement; break; + case 'mouseout': element = event.toElement; break; + default: return null; + } + return Element.extend(element); + } +}); + +Event.Methods = (function() { + var isButton; + + if (Prototype.Browser.IE) { + var buttonMap = { 0: 1, 1: 4, 2: 2 }; + isButton = function(event, code) { + return event.button == buttonMap[code]; + }; + + } else if (Prototype.Browser.WebKit) { + isButton = function(event, code) { + switch (code) { + case 0: return event.which == 1 && !event.metaKey; + case 1: return event.which == 1 && event.metaKey; + default: return false; + } + }; + + } else { + isButton = function(event, code) { + return event.which ? (event.which === code + 1) : (event.button === code); + }; + } + + return { + isLeftClick: function(event) { return isButton(event, 0) }, + isMiddleClick: function(event) { return isButton(event, 1) }, + isRightClick: function(event) { return isButton(event, 2) }, + + element: function(event) { + var node = Event.extend(event).target; + return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node); + }, + + findElement: function(event, expression) { + var element = Event.element(event); + return element.match(expression) ? element : element.up(expression); + }, + + pointer: function(event) { + return { + x: event.pageX || (event.clientX + + (document.documentElement.scrollLeft || document.body.scrollLeft)), + y: event.pageY || (event.clientY + + (document.documentElement.scrollTop || document.body.scrollTop)) + }; + }, + + pointerX: function(event) { return Event.pointer(event).x }, + pointerY: function(event) { return Event.pointer(event).y }, + + stop: function(event) { + Event.extend(event); + event.preventDefault(); + event.stopPropagation(); + event.stopped = true; + } + }; +})(); + +Event.extend = (function() { + var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { + m[name] = Event.Methods[name].methodize(); + return m; + }); + + if (Prototype.Browser.IE) { + Object.extend(methods, { + stopPropagation: function() { this.cancelBubble = true }, + preventDefault: function() { this.returnValue = false }, + inspect: function() { return "[object Event]" } + }); + + return function(event) { + if (!event) return false; + if (event._extendedByPrototype) return event; + + event._extendedByPrototype = Prototype.emptyFunction; + var pointer = Event.pointer(event); + Object.extend(event, { + target: event.srcElement, + relatedTarget: Event.relatedTarget(event), + pageX: pointer.x, + pageY: pointer.y + }); + return Object.extend(event, methods); + }; + + } else { + Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__; + Object.extend(Event.prototype, methods); + return Prototype.K; + } +})(); + +Object.extend(Event, (function() { + var cache = Event.cache; + + function getEventID(element) { + if (element._eventID) return element._eventID; + arguments.callee.id = arguments.callee.id || 1; + return element._eventID = ++arguments.callee.id; + } + + function getDOMEventName(eventName) { + if (eventName && eventName.include(':')) return "dataavailable"; + return eventName; + } + + function getCacheForID(id) { + return cache[id] = cache[id] || { }; + } + + function getWrappersForEventName(id, eventName) { + var c = getCacheForID(id); + return c[eventName] = c[eventName] || []; + } + + function createWrapper(element, eventName, handler) { + var id = getEventID(element); + var c = getWrappersForEventName(id, eventName); + if (c.pluck("handler").include(handler)) return false; + + var wrapper = function(event) { + if (!Event || !Event.extend || + (event.eventName && event.eventName != eventName)) + return false; + + Event.extend(event); + handler.call(element, event) + }; + + wrapper.handler = handler; + c.push(wrapper); + return wrapper; + } + + function findWrapper(id, eventName, handler) { + var c = getWrappersForEventName(id, eventName); + return c.find(function(wrapper) { return wrapper.handler == handler }); + } + + function destroyWrapper(id, eventName, handler) { + var c = getCacheForID(id); + if (!c[eventName]) return false; + c[eventName] = c[eventName].without(findWrapper(id, eventName, handler)); + } + + function destroyCache() { + for (var id in cache) + for (var eventName in cache[id]) + cache[id][eventName] = null; + } + + if (window.attachEvent) { + window.attachEvent("onunload", destroyCache); + } + + return { + observe: function(element, eventName, handler) { + element = $(element); + var name = getDOMEventName(eventName); + + var wrapper = createWrapper(element, eventName, handler); + if (!wrapper) return element; + + if (element.addEventListener) { + element.addEventListener(name, wrapper, false); + } else { + element.attachEvent("on" + name, wrapper); + } + + return element; + }, + + stopObserving: function(element, eventName, handler) { + element = $(element); + var id = getEventID(element), name = getDOMEventName(eventName); + + if (!handler && eventName) { + getWrappersForEventName(id, eventName).each(function(wrapper) { + element.stopObserving(eventName, wrapper.handler); + }); + return element; + + } else if (!eventName) { + Object.keys(getCacheForID(id)).each(function(eventName) { + element.stopObserving(eventName); + }); + return element; + } + + var wrapper = findWrapper(id, eventName, handler); + if (!wrapper) return element; + + if (element.removeEventListener) { + element.removeEventListener(name, wrapper, false); + } else { + element.detachEvent("on" + name, wrapper); + } + + destroyWrapper(id, eventName, handler); + + return element; + }, + + fire: function(element, eventName, memo) { + element = $(element); + if (element == document && document.createEvent && !element.dispatchEvent) + element = document.documentElement; + + if (document.createEvent) { + var event = document.createEvent("HTMLEvents"); + event.initEvent("dataavailable", true, true); + } else { + var event = document.createEventObject(); + event.eventType = "ondataavailable"; + } + + event.eventName = eventName; + event.memo = memo || { }; + + if (document.createEvent) { + element.dispatchEvent(event); + } else { + element.fireEvent(event.eventType, event); + } + + return event; + } + }; +})()); + +Object.extend(Event, Event.Methods); + +Element.addMethods({ + fire: Event.fire, + observe: Event.observe, + stopObserving: Event.stopObserving +}); + +Object.extend(document, { + fire: Element.Methods.fire.methodize(), + observe: Element.Methods.observe.methodize(), + stopObserving: Element.Methods.stopObserving.methodize() +}); + +(function() { + /* Support for the DOMContentLoaded event is based on work by Dan Webb, + Matthias Miller, Dean Edwards and John Resig. */ + + var timer, fired = false; + + function fireContentLoadedEvent() { + if (fired) return; + if (timer) window.clearInterval(timer); + document.fire("dom:loaded"); + fired = true; + } + + if (document.addEventListener) { + if (Prototype.Browser.WebKit) { + timer = window.setInterval(function() { + if (/loaded|complete/.test(document.readyState)) + fireContentLoadedEvent(); + }, 0); + + Event.observe(window, "load", fireContentLoadedEvent); + + } else { + document.addEventListener("DOMContentLoaded", + fireContentLoadedEvent, false); + } + + } else { + document.write("'); + }, + REQUIRED_PROTOTYPE: '1.6', + load: function() { + function convertVersionString(versionString){ + var r = versionString.split('.'); + return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]); + } + + if((typeof Prototype=='undefined') || + (typeof Element == 'undefined') || + (typeof Element.Methods=='undefined') || + (convertVersionString(Prototype.Version) < + convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) + throw("script.aculo.us requires the Prototype JavaScript framework >= " + + Scriptaculous.REQUIRED_PROTOTYPE); + + $A(document.getElementsByTagName("script")).findAll( function(s) { + return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/)) + }).each( function(s) { + var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,''); + var includes = s.src.match(/\?.*load=([a-z,]*)/); + if ( includes ) + includes[1].split(',').each( + function(include) { Scriptaculous.require(path+include+'.js') }); + }); + } +} + +Scriptaculous.load(); diff --git a/wp-includes/js/swfobject.js b/wp-includes/js/swfobject.js new file mode 100644 index 0000000..08fb270 --- /dev/null +++ b/wp-includes/js/swfobject.js @@ -0,0 +1,5 @@ +/* SWFObject v2.1 + Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis + This software is released under the MIT License +*/ +var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write(" + + Notes: + You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8. + The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs + or corrupt Flash Player installations will not trigger this event. + The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can + be used to prepare the SWFUploadUI and hide alternate content. + swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser. + Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made. +*/ + + +// SWFObject v2.1 must be loaded + +var SWFUpload; +if (typeof(SWFUpload) === "function") { + SWFUpload.onload = function () {}; + + swfobject.addDomLoadEvent(function () { + if (typeof(SWFUpload.onload) === "function") { + SWFUpload.onload.call(window); + } + }); + + SWFUpload.prototype.initSettings = (function (oldInitSettings) { + return function () { + if (typeof(oldInitSettings) === "function") { + oldInitSettings.call(this); + } + + this.ensureDefault = function (settingName, defaultValue) { + this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; + }; + + this.ensureDefault("minimum_flash_version", "9.0.28"); + this.ensureDefault("swfupload_pre_load_handler", null); + this.ensureDefault("swfupload_load_failed_handler", null); + + delete this.ensureDefault; + + }; + })(SWFUpload.prototype.initSettings); + + + SWFUpload.prototype.loadFlash = function (oldLoadFlash) { + return function () { + var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version); + + if (hasFlash) { + this.queueEvent("swfupload_pre_load_handler"); + if (typeof(oldLoadFlash) === "function") { + oldLoadFlash.call(this); + } + } else { + this.queueEvent("swfupload_load_failed_handler"); + } + }; + + }(SWFUpload.prototype.loadFlash); + + SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) { + return function () { + if (typeof(oldDisplayDebugInfo) === "function") { + oldDisplayDebugInfo.call(this); + } + + this.debug( + [ + "SWFUpload.SWFObject Plugin settings:", "\n", + "\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n", + "\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n", + "\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n", + ].join("") + ); + }; + }(SWFUpload.prototype.displayDebugInfo); +} diff --git a/wp-includes/js/swfupload/swfupload-all.js b/wp-includes/js/swfupload/swfupload-all.js new file mode 100644 index 0000000..afb7921 --- /dev/null +++ b/wp-includes/js/swfupload/swfupload-all.js @@ -0,0 +1,8 @@ +// swfupload +var SWFUpload;if(SWFUpload==undefined){SWFUpload=function(a){this.initSWFUpload(a)}}SWFUpload.prototype.initSWFUpload=function(b){try{this.customSettings={};this.settings=b;this.eventQueue=[];this.movieName="SWFUpload_"+SWFUpload.movieCount++;this.movieElement=null;SWFUpload.instances[this.movieName]=this;this.initSettings();this.loadFlash()}catch(a){delete SWFUpload.instances[this.movieName];throw a}};SWFUpload.instances={};SWFUpload.movieCount=0;SWFUpload.version="2.2.0 2009-03-25";SWFUpload.QUEUE_ERROR={QUEUE_LIMIT_EXCEEDED:-100,FILE_EXCEEDS_SIZE_LIMIT:-110,ZERO_BYTE_FILE:-120,INVALID_FILETYPE:-130};SWFUpload.UPLOAD_ERROR={HTTP_ERROR:-200,MISSING_UPLOAD_URL:-210,IO_ERROR:-220,SECURITY_ERROR:-230,UPLOAD_LIMIT_EXCEEDED:-240,UPLOAD_FAILED:-250,SPECIFIED_FILE_ID_NOT_FOUND:-260,FILE_VALIDATION_FAILED:-270,FILE_CANCELLED:-280,UPLOAD_STOPPED:-290};SWFUpload.FILE_STATUS={QUEUED:-1,IN_PROGRESS:-2,ERROR:-3,COMPLETE:-4,CANCELLED:-5};SWFUpload.BUTTON_ACTION={SELECT_FILE:-100,SELECT_FILES:-110,START_UPLOAD:-120};SWFUpload.CURSOR={ARROW:-1,HAND:-2};SWFUpload.WINDOW_MODE={WINDOW:"window",TRANSPARENT:"transparent",OPAQUE:"opaque"};SWFUpload.completeURL=function(a){if(typeof(a)!=="string"||a.match(/^https?:\/\//i)||a.match(/^\//)){return a}var c,b;c=window.location.protocol+"//"+window.location.hostname+(window.location.port?":"+window.location.port:"");b=window.location.pathname.lastIndexOf("/");if(b<=0){path="/"}else{path=window.location.pathname.substr(0,b)+"/"}return path+a};SWFUpload.prototype.initSettings=function(){this.ensureDefault=function(b,a){this.settings[b]=(this.settings[b]==undefined)?a:this.settings[b]};this.ensureDefault("upload_url","");this.ensureDefault("preserve_relative_urls",false);this.ensureDefault("file_post_name","Filedata");this.ensureDefault("post_params",{});this.ensureDefault("use_query_string",false);this.ensureDefault("requeue_on_error",false);this.ensureDefault("http_success",[]);this.ensureDefault("assume_success_timeout",0);this.ensureDefault("file_types","*.*");this.ensureDefault("file_types_description","All Files");this.ensureDefault("file_size_limit",0);this.ensureDefault("file_upload_limit",0);this.ensureDefault("file_queue_limit",0);this.ensureDefault("flash_url","swfupload.swf");this.ensureDefault("prevent_swf_caching",true);this.ensureDefault("button_image_url","");this.ensureDefault("button_width",1);this.ensureDefault("button_height",1);this.ensureDefault("button_text","");this.ensureDefault("button_text_style","color: #000000; font-size: 16pt;");this.ensureDefault("button_text_top_padding",0);this.ensureDefault("button_text_left_padding",0);this.ensureDefault("button_action",SWFUpload.BUTTON_ACTION.SELECT_FILES);this.ensureDefault("button_disabled",false);this.ensureDefault("button_placeholder_id","");this.ensureDefault("button_placeholder",null);this.ensureDefault("button_cursor",SWFUpload.CURSOR.ARROW);this.ensureDefault("button_window_mode",SWFUpload.WINDOW_MODE.WINDOW);this.ensureDefault("debug",false);this.settings.debug_enabled=this.settings.debug;this.settings.return_upload_start_handler=this.returnUploadStart;this.ensureDefault("swfupload_loaded_handler",null);this.ensureDefault("file_dialog_start_handler",null);this.ensureDefault("file_queued_handler",null);this.ensureDefault("file_queue_error_handler",null);this.ensureDefault("file_dialog_complete_handler",null);this.ensureDefault("upload_start_handler",null);this.ensureDefault("upload_progress_handler",null);this.ensureDefault("upload_error_handler",null);this.ensureDefault("upload_success_handler",null);this.ensureDefault("upload_complete_handler",null);this.ensureDefault("debug_handler",this.debugMessage);this.ensureDefault("custom_settings",{});this.customSettings=this.settings.custom_settings;if(!!this.settings.prevent_swf_caching){this.settings.flash_url=this.settings.flash_url+(this.settings.flash_url.indexOf("?")<0?"?":"&")+"preventswfcaching="+new Date().getTime()}if(!this.settings.preserve_relative_urls){this.settings.upload_url=SWFUpload.completeURL(this.settings.upload_url);this.settings.button_image_url=SWFUpload.completeURL(this.settings.button_image_url)}delete this.ensureDefault};SWFUpload.prototype.loadFlash=function(){var a,b;if(document.getElementById(this.movieName)!==null){throw"ID "+this.movieName+" is already in use. The Flash Object could not be added"}a=document.getElementById(this.settings.button_placeholder_id)||this.settings.button_placeholder;if(a==undefined){throw"Could not find the placeholder element: "+this.settings.button_placeholder_id}b=document.createElement("div");b.innerHTML=this.getFlashHTML();a.parentNode.replaceChild(b.firstChild,a);if(window[this.movieName]==undefined){window[this.movieName]=this.getMovieElement()}};SWFUpload.prototype.getFlashHTML=function(){return['','','','','','','',""].join("")};SWFUpload.prototype.getFlashVars=function(){var b=this.buildParamString(),a=this.settings.http_success.join(",");return["movieName=",encodeURIComponent(this.movieName),"&uploadURL=",encodeURIComponent(this.settings.upload_url),"&useQueryString=",encodeURIComponent(this.settings.use_query_string),"&requeueOnError=",encodeURIComponent(this.settings.requeue_on_error),"&httpSuccess=",encodeURIComponent(a),"&assumeSuccessTimeout=",encodeURIComponent(this.settings.assume_success_timeout),"&params=",encodeURIComponent(b),"&filePostName=",encodeURIComponent(this.settings.file_post_name),"&fileTypes=",encodeURIComponent(this.settings.file_types),"&fileTypesDescription=",encodeURIComponent(this.settings.file_types_description),"&fileSizeLimit=",encodeURIComponent(this.settings.file_size_limit),"&fileUploadLimit=",encodeURIComponent(this.settings.file_upload_limit),"&fileQueueLimit=",encodeURIComponent(this.settings.file_queue_limit),"&debugEnabled=",encodeURIComponent(this.settings.debug_enabled),"&buttonImageURL=",encodeURIComponent(this.settings.button_image_url),"&buttonWidth=",encodeURIComponent(this.settings.button_width),"&buttonHeight=",encodeURIComponent(this.settings.button_height),"&buttonText=",encodeURIComponent(this.settings.button_text),"&buttonTextTopPadding=",encodeURIComponent(this.settings.button_text_top_padding),"&buttonTextLeftPadding=",encodeURIComponent(this.settings.button_text_left_padding),"&buttonTextStyle=",encodeURIComponent(this.settings.button_text_style),"&buttonAction=",encodeURIComponent(this.settings.button_action),"&buttonDisabled=",encodeURIComponent(this.settings.button_disabled),"&buttonCursor=",encodeURIComponent(this.settings.button_cursor)].join("")};SWFUpload.prototype.getMovieElement=function(){if(this.movieElement==undefined){this.movieElement=document.getElementById(this.movieName)}if(this.movieElement===null){throw"Could not find Flash element"}return this.movieElement};SWFUpload.prototype.buildParamString=function(){var c=this.settings.post_params,b=[],a;if(typeof(c)==="object"){for(a in c){if(c.hasOwnProperty(a)){b.push(encodeURIComponent(a.toString())+"="+encodeURIComponent(c[a].toString()))}}}return b.join("&")};SWFUpload.prototype.destroy=function(){try{this.cancelUpload(null,false);var a=null,c;a=this.getMovieElement();if(a&&typeof(a.CallFunction)==="unknown"){for(c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(e){}}try{a.parentNode.removeChild(a)}catch(b){}}window[this.movieName]=null;SWFUpload.instances[this.movieName]=null;delete SWFUpload.instances[this.movieName];this.movieElement=null;this.settings=null;this.customSettings=null;this.eventQueue=null;this.movieName=null;return true}catch(d){return false}};SWFUpload.prototype.addSetting=function(b,c,a){if(c==undefined){return(this.settings[b]=a)}else{return(this.settings[b]=c)}};SWFUpload.prototype.getSetting=function(a){if(this.settings[a]!=undefined){return this.settings[a]}return""};SWFUpload.prototype.callFlash=function(functionName,argumentArray){argumentArray=argumentArray||[];var movieElement=this.getMovieElement(),returnValue,returnString;try{returnString=movieElement.CallFunction(''+__flash__argumentsToXML(argumentArray,0)+"");returnValue=eval(returnString)}catch(ex){throw"Call to "+functionName+" failed"}if(returnValue!=undefined&&typeof returnValue.post==="object"){returnValue=this.unescapeFilePostParams(returnValue)}return returnValue};SWFUpload.prototype.selectFile=function(){this.callFlash("SelectFile")};SWFUpload.prototype.selectFiles=function(){this.callFlash("SelectFiles")};SWFUpload.prototype.startUpload=function(a){this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelUpload=function(a,b){if(b!==false){b=true}this.callFlash("CancelUpload",[a,b])};SWFUpload.prototype.stopUpload=function(){this.callFlash("StopUpload")};SWFUpload.prototype.getStats=function(){return this.callFlash("GetStats")};SWFUpload.prototype.setStats=function(a){this.callFlash("SetStats",[a])};SWFUpload.prototype.getFile=function(a){if(typeof(a)==="number"){return this.callFlash("GetFileByIndex",[a])}else{return this.callFlash("GetFile",[a])}};SWFUpload.prototype.addFileParam=function(a,b,c){return this.callFlash("AddFileParam",[a,b,c])};SWFUpload.prototype.removeFileParam=function(a,b){this.callFlash("RemoveFileParam",[a,b])};SWFUpload.prototype.setUploadURL=function(a){this.settings.upload_url=a.toString();this.callFlash("SetUploadURL",[a])};SWFUpload.prototype.setPostParams=function(a){this.settings.post_params=a;this.callFlash("SetPostParams",[a])};SWFUpload.prototype.addPostParam=function(a,b){this.settings.post_params[a]=b;this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.removePostParam=function(a){delete this.settings.post_params[a];this.callFlash("SetPostParams",[this.settings.post_params])};SWFUpload.prototype.setFileTypes=function(a,b){this.settings.file_types=a;this.settings.file_types_description=b;this.callFlash("SetFileTypes",[a,b])};SWFUpload.prototype.setFileSizeLimit=function(a){this.settings.file_size_limit=a;this.callFlash("SetFileSizeLimit",[a])};SWFUpload.prototype.setFileUploadLimit=function(a){this.settings.file_upload_limit=a;this.callFlash("SetFileUploadLimit",[a])};SWFUpload.prototype.setFileQueueLimit=function(a){this.settings.file_queue_limit=a;this.callFlash("SetFileQueueLimit",[a])};SWFUpload.prototype.setFilePostName=function(a){this.settings.file_post_name=a;this.callFlash("SetFilePostName",[a])};SWFUpload.prototype.setUseQueryString=function(a){this.settings.use_query_string=a;this.callFlash("SetUseQueryString",[a])};SWFUpload.prototype.setRequeueOnError=function(a){this.settings.requeue_on_error=a;this.callFlash("SetRequeueOnError",[a])};SWFUpload.prototype.setHTTPSuccess=function(a){if(typeof a==="string"){a=a.replace(" ","").split(",")}this.settings.http_success=a;this.callFlash("SetHTTPSuccess",[a])};SWFUpload.prototype.setAssumeSuccessTimeout=function(a){this.settings.assume_success_timeout=a;this.callFlash("SetAssumeSuccessTimeout",[a])};SWFUpload.prototype.setDebugEnabled=function(a){this.settings.debug_enabled=a;this.callFlash("SetDebugEnabled",[a])};SWFUpload.prototype.setButtonImageURL=function(a){if(a==undefined){a=""}this.settings.button_image_url=a;this.callFlash("SetButtonImageURL",[a])};SWFUpload.prototype.setButtonDimensions=function(c,a){this.settings.button_width=c;this.settings.button_height=a;var b=this.getMovieElement();if(b!=undefined){b.style.width=c+"px";b.style.height=a+"px"}this.callFlash("SetButtonDimensions",[c,a])};SWFUpload.prototype.setButtonText=function(a){this.settings.button_text=a;this.callFlash("SetButtonText",[a])};SWFUpload.prototype.setButtonTextPadding=function(b,a){this.settings.button_text_top_padding=a;this.settings.button_text_left_padding=b;this.callFlash("SetButtonTextPadding",[b,a])};SWFUpload.prototype.setButtonTextStyle=function(a){this.settings.button_text_style=a;this.callFlash("SetButtonTextStyle",[a])};SWFUpload.prototype.setButtonDisabled=function(a){this.settings.button_disabled=a;this.callFlash("SetButtonDisabled",[a])};SWFUpload.prototype.setButtonAction=function(a){this.settings.button_action=a;this.callFlash("SetButtonAction",[a])};SWFUpload.prototype.setButtonCursor=function(a){this.settings.button_cursor=a;this.callFlash("SetButtonCursor",[a])};SWFUpload.prototype.queueEvent=function(b,c){if(c==undefined){c=[]}else{if(!(c instanceof Array)){c=[c]}}var a=this;if(typeof this.settings[b]==="function"){this.eventQueue.push(function(){this.settings[b].apply(this,c)});setTimeout(function(){a.executeNextEvent()},0)}else{if(this.settings[b]!==null){throw"Event handler "+b+" is unknown or is not a function"}}};SWFUpload.prototype.executeNextEvent=function(){var a=this.eventQueue?this.eventQueue.shift():null;if(typeof(a)==="function"){a.apply(this)}};SWFUpload.prototype.unescapeFilePostParams=function(c){var e=/[$]([0-9a-f]{4})/i,f={},d,a,b;if(c!=undefined){for(a in c.post){if(c.post.hasOwnProperty(a)){d=a;while((b=e.exec(d))!==null){d=d.replace(b[0],String.fromCharCode(parseInt("0x"+b[1],16)))}f[d]=c.post[a]}}c.post=f}return c};SWFUpload.prototype.testExternalInterface=function(){try{return this.callFlash("TestExternalInterface")}catch(a){return false}};SWFUpload.prototype.flashReady=function(){var a=this.getMovieElement();if(!a){this.debug("Flash called back ready but the flash movie can't be found.");return}this.cleanUp(a);this.queueEvent("swfupload_loaded_handler")};SWFUpload.prototype.cleanUp=function(a){var c;try{if(this.movieElement&&typeof(a.CallFunction)==="unknown"){this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");for(c in a){try{if(typeof(a[c])==="function"){a[c]=null}}catch(b){}}}}catch(d){}window.__flash__removeCallback=function(e,f){try{if(e){e[f]=null}}catch(g){}}};SWFUpload.prototype.fileDialogStart=function(){this.queueEvent("file_dialog_start_handler")};SWFUpload.prototype.fileQueued=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("file_queued_handler",a)};SWFUpload.prototype.fileQueueError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("file_queue_error_handler",[a,c,b])};SWFUpload.prototype.fileDialogComplete=function(b,c,a){this.queueEvent("file_dialog_complete_handler",[b,c,a])};SWFUpload.prototype.uploadStart=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("return_upload_start_handler",a)};SWFUpload.prototype.returnUploadStart=function(a){var b;if(typeof this.settings.upload_start_handler==="function"){a=this.unescapeFilePostParams(a);b=this.settings.upload_start_handler.call(this,a)}else{if(this.settings.upload_start_handler!=undefined){throw"upload_start_handler must be a function"}}if(b===undefined){b=true}b=!!b;this.callFlash("ReturnUploadStart",[b])};SWFUpload.prototype.uploadProgress=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_progress_handler",[a,c,b])};SWFUpload.prototype.uploadError=function(a,c,b){a=this.unescapeFilePostParams(a);this.queueEvent("upload_error_handler",[a,c,b])};SWFUpload.prototype.uploadSuccess=function(b,a,c){b=this.unescapeFilePostParams(b);this.queueEvent("upload_success_handler",[b,a,c])};SWFUpload.prototype.uploadComplete=function(a){a=this.unescapeFilePostParams(a);this.queueEvent("upload_complete_handler",a)};SWFUpload.prototype.debug=function(a){this.queueEvent("debug_handler",a)}; +// swfupload.queue +var SWFUpload;if(typeof(SWFUpload)==="function"){SWFUpload.queue={};SWFUpload.prototype.initSettings=(function(a){return function(){if(typeof(a)==="function"){a.call(this)}this.queueSettings={};this.queueSettings.queue_cancelled_flag=false;this.queueSettings.queue_upload_count=0;this.queueSettings.user_upload_complete_handler=this.settings.upload_complete_handler;this.queueSettings.user_upload_start_handler=this.settings.upload_start_handler;this.settings.upload_complete_handler=SWFUpload.queue.uploadCompleteHandler;this.settings.upload_start_handler=SWFUpload.queue.uploadStartHandler;this.settings.queue_complete_handler=this.settings.queue_complete_handler||null}})(SWFUpload.prototype.initSettings);SWFUpload.prototype.startUpload=function(a){this.queueSettings.queue_cancelled_flag=false;this.callFlash("StartUpload",[a])};SWFUpload.prototype.cancelQueue=function(){this.queueSettings.queue_cancelled_flag=true;this.stopUpload();var a=this.getStats();while(a.files_queued>0){this.cancelUpload();a=this.getStats()}};SWFUpload.queue.uploadStartHandler=function(a){var b;if(typeof(this.queueSettings.user_upload_start_handler)==="function"){b=this.queueSettings.user_upload_start_handler.call(this,a)}b=(b===false)?false:true;this.queueSettings.queue_cancelled_flag=!b;return b};SWFUpload.queue.uploadCompleteHandler=function(b){var c=this.queueSettings.user_upload_complete_handler,d,a;if(b.filestatus===SWFUpload.FILE_STATUS.COMPLETE){this.queueSettings.queue_upload_count++}if(typeof(c)==="function"){d=(c.call(this,b)===false)?false:true}else{if(b.filestatus===SWFUpload.FILE_STATUS.QUEUED){d=false}else{d=true}}if(d){a=this.getStats();if(a.files_queued>0&&this.queueSettings.queue_cancelled_flag===false){this.startUpload()}else{if(this.queueSettings.queue_cancelled_flag===false){this.queueEvent("queue_complete_handler",[this.queueSettings.queue_upload_count]);this.queueSettings.queue_upload_count=0}else{this.queueSettings.queue_cancelled_flag=false;this.queueSettings.queue_upload_count=0}}}}}; +// swfobject +var swfobject=function(){var b="undefined",Q="object",n="Shockwave Flash",p="ShockwaveFlash.ShockwaveFlash",P="application/x-shockwave-flash",m="SWFObjectExprInst",j=window,K=document,T=navigator,o=[],N=[],i=[],d=[],J,Z=null,M=null,l=null,e=false,A=false;var h=function(){var v=typeof K.getElementById!=b&&typeof K.getElementsByTagName!=b&&typeof K.createElement!=b,AC=[0,0,0],x=null;if(typeof T.plugins!=b&&typeof T.plugins[n]==Q){x=T.plugins[n].description;if(x&&!(typeof T.mimeTypes!=b&&T.mimeTypes[P]&&!T.mimeTypes[P].enabledPlugin)){x=x.replace(/^.*\s+(\S+\s+\S+$)/,"$1");AC[0]=parseInt(x.replace(/^(.*)\..*$/,"$1"),10);AC[1]=parseInt(x.replace(/^.*\.(.*)\s.*$/,"$1"),10);AC[2]=/r/.test(x)?parseInt(x.replace(/^.*r(.*)$/,"$1"),10):0}}else{if(typeof j.ActiveXObject!=b){var y=null,AB=false;try{y=new ActiveXObject(p+".7")}catch(t){try{y=new ActiveXObject(p+".6");AC=[6,0,21];y.AllowScriptAccess="always"}catch(t){if(AC[0]==6){AB=true}}if(!AB){try{y=new ActiveXObject(p)}catch(t){}}}if(!AB&&y){try{x=y.GetVariable("$version");if(x){x=x.split(" ")[1].split(",");AC=[parseInt(x[0],10),parseInt(x[1],10),parseInt(x[2],10)]}}catch(t){}}}}var AD=T.userAgent.toLowerCase(),r=T.platform.toLowerCase(),AA=/webkit/.test(AD)?parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,q=false,z=r?/win/.test(r):/win/.test(AD),w=r?/mac/.test(r):/mac/.test(AD);/*@cc_on q=true;@if(@_win32)z=true;@elif(@_mac)w=true;@end@*/return{w3cdom:v,pv:AC,webkit:AA,ie:q,win:z,mac:w}}();var L=function(){if(!h.w3cdom){return }f(H);if(h.ie&&h.win){try{K.write(" + + + +
    + +
    + + + + + diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/editor_plugin.js b/wp-includes/js/tinymce/plugins/inlinepopups/editor_plugin.js new file mode 100644 index 0000000..4affad4 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/inlinepopups/editor_plugin.js @@ -0,0 +1 @@ +(function(){var d=tinymce.DOM,b=tinymce.dom.Element,a=tinymce.dom.Event,e=tinymce.each,c=tinymce.is;tinymce.create("tinymce.plugins.InlinePopups",{init:function(f,g){f.onBeforeRenderUI.add(function(){f.windowManager=new tinymce.InlineWindowManager(f);d.loadCSS(g+"/skins/"+(f.settings.inlinepopups_skin||"clearlooks2")+"/window.css")})},getInfo:function(){return{longname:"InlinePopups",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.create("tinymce.InlineWindowManager:tinymce.WindowManager",{InlineWindowManager:function(f){var g=this;g.parent(f);g.zIndex=300000;g.count=0;g.windows={}},open:function(r,j){var y=this,i,k="",q=y.editor,g=0,s=0,h,m,n,o,l,v,x;r=r||{};j=j||{};if(!r.inline){return y.parent(r,j)}if(!r.type){y.bookmark=q.selection.getBookmark("simple")}i=d.uniqueId();h=d.getViewPort();r.width=parseInt(r.width||320);r.height=parseInt(r.height||240)+(tinymce.isIE?8:0);r.min_width=parseInt(r.min_width||150);r.min_height=parseInt(r.min_height||100);r.max_width=parseInt(r.max_width||2000);r.max_height=parseInt(r.max_height||2000);r.left=r.left||Math.round(Math.max(h.x,h.x+(h.w/2)-(r.width/2)));r.top=r.top||Math.round(Math.max(h.y,h.y+(h.h/2)-(r.height/2)));r.movable=r.resizable=true;j.mce_width=r.width;j.mce_height=r.height;j.mce_inline=true;j.mce_window_id=i;j.mce_auto_focus=r.auto_focus;y.features=r;y.params=j;y.onOpen.dispatch(y,r,j);if(r.type){k+=" mceModal";if(r.type){k+=" mce"+r.type.substring(0,1).toUpperCase()+r.type.substring(1)}r.resizable=false}if(r.statusbar){k+=" mceStatusbar"}if(r.resizable){k+=" mceResizable"}if(r.minimizable){k+=" mceMinimizable"}if(r.maximizable){k+=" mceMaximizable"}if(r.movable){k+=" mceMovable"}y._addAll(d.doc.body,["div",{id:i,"class":q.settings.inlinepopups_skin||"clearlooks2",style:"width:100px;height:100px"},["div",{id:i+"_wrapper","class":"mceWrapper"+k},["div",{id:i+"_top","class":"mceTop"},["div",{"class":"mceLeft"}],["div",{"class":"mceCenter"}],["div",{"class":"mceRight"}],["span",{id:i+"_title"},r.title||""]],["div",{id:i+"_middle","class":"mceMiddle"},["div",{id:i+"_left","class":"mceLeft"}],["span",{id:i+"_content"}],["div",{id:i+"_right","class":"mceRight"}]],["div",{id:i+"_bottom","class":"mceBottom"},["div",{"class":"mceLeft"}],["div",{"class":"mceCenter"}],["div",{"class":"mceRight"}],["span",{id:i+"_status"},"Content"]],["a",{"class":"mceMove",tabindex:"-1",href:"javascript:;"}],["a",{"class":"mceMin",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{"class":"mceMax",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{"class":"mceMed",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{"class":"mceClose",tabindex:"-1",href:"javascript:;",onmousedown:"return false;"}],["a",{id:i+"_resize_n","class":"mceResize mceResizeN",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_s","class":"mceResize mceResizeS",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_w","class":"mceResize mceResizeW",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_e","class":"mceResize mceResizeE",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_nw","class":"mceResize mceResizeNW",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_ne","class":"mceResize mceResizeNE",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_sw","class":"mceResize mceResizeSW",tabindex:"-1",href:"javascript:;"}],["a",{id:i+"_resize_se","class":"mceResize mceResizeSE",tabindex:"-1",href:"javascript:;"}]]]);d.setStyles(i,{top:-10000,left:-10000});if(tinymce.isGecko){d.setStyle(i,"overflow","auto")}if(!r.type){g+=d.get(i+"_left").clientWidth;g+=d.get(i+"_right").clientWidth;s+=d.get(i+"_top").clientHeight;s+=d.get(i+"_bottom").clientHeight}d.setStyles(i,{top:r.top,left:r.left,width:r.width+g,height:r.height+s});x=r.url||r.file;if(x){if(tinymce.relaxedDomain){x+=(x.indexOf("?")==-1?"?":"&")+"mce_rdomain="+tinymce.relaxedDomain}x=tinymce._addVer(x)}if(!r.type){d.add(i+"_content","iframe",{id:i+"_ifr",src:'javascript:""',frameBorder:0,style:"border:0;width:10px;height:10px"});d.setStyles(i+"_ifr",{width:r.width,height:r.height});d.setAttrib(i+"_ifr","src",x)}else{d.add(i+"_wrapper","a",{id:i+"_ok","class":"mceButton mceOk",href:"javascript:;",onmousedown:"return false;"},"Ok");if(r.type=="confirm"){d.add(i+"_wrapper","a",{"class":"mceButton mceCancel",href:"javascript:;",onmousedown:"return false;"},"Cancel")}d.add(i+"_middle","div",{"class":"mceIcon"});d.setHTML(i+"_content",r.content.replace("\n","
    "))}n=a.add(i,"mousedown",function(t){var u=t.target,f,p;f=y.windows[i];y.focus(i);if(u.nodeName=="A"||u.nodeName=="a"){if(u.className=="mceMax"){f.oldPos=f.element.getXY();f.oldSize=f.element.getSize();p=d.getViewPort();p.w-=2;p.h-=2;f.element.moveTo(p.x,p.y);f.element.resizeTo(p.w,p.h);d.setStyles(i+"_ifr",{width:p.w-f.deltaWidth,height:p.h-f.deltaHeight});d.addClass(i+"_wrapper","mceMaximized")}else{if(u.className=="mceMed"){f.element.moveTo(f.oldPos.x,f.oldPos.y);f.element.resizeTo(f.oldSize.w,f.oldSize.h);f.iframeElement.resizeTo(f.oldSize.w-f.deltaWidth,f.oldSize.h-f.deltaHeight);d.removeClass(i+"_wrapper","mceMaximized")}else{if(u.className=="mceMove"){return y._startDrag(i,t,u.className)}else{if(d.hasClass(u,"mceResize")){return y._startDrag(i,t,u.className.substring(13))}}}}}});o=a.add(i,"click",function(f){var p=f.target;y.focus(i);if(p.nodeName=="A"||p.nodeName=="a"){switch(p.className){case"mceClose":y.close(null,i);return a.cancel(f);case"mceButton mceOk":case"mceButton mceCancel":r.button_func(p.className=="mceButton mceOk");return a.cancel(f)}}});v=y.windows[i]={id:i,mousedown_func:n,click_func:o,element:new b(i,{blocker:1,container:q.getContainer()}),iframeElement:new b(i+"_ifr"),features:r,deltaWidth:g,deltaHeight:s};v.iframeElement.on("focus",function(){y.focus(i)});if(y.count==0&&y.editor.getParam("dialog_type","modal")=="modal"){d.add(d.doc.body,"div",{id:"mceModalBlocker","class":(y.editor.settings.inlinepopups_skin||"clearlooks2")+"_modalBlocker",style:{zIndex:y.zIndex-1}});d.show("mceModalBlocker")}else{d.setStyle("mceModalBlocker","z-index",y.zIndex-1)}if(tinymce.isIE6||/Firefox\/2\./.test(navigator.userAgent)||(tinymce.isIE&&!d.boxModel)){d.setStyles("mceModalBlocker",{position:"absolute",left:h.x,top:h.y,width:h.w-2,height:h.h-2})}y.focus(i);y._fixIELayout(i,1);if(d.get(i+"_ok")){d.get(i+"_ok").focus()}y.count++;return v},focus:function(h){var g=this,f;if(f=g.windows[h]){f.zIndex=this.zIndex++;f.element.setStyle("zIndex",f.zIndex);f.element.update();h=h+"_wrapper";d.removeClass(g.lastId,"mceFocus");d.addClass(h,"mceFocus");g.lastId=h}},_addAll:function(k,h){var g,l,f=this,j=tinymce.DOM;if(c(h,"string")){k.appendChild(j.doc.createTextNode(h))}else{if(h.length){k=k.appendChild(j.create(h[0],h[1]));for(g=2;gf){i=m;f=m.zIndex}});if(i){h.focus(i.id)}}},setTitle:function(f,g){var h;f=this._findId(f);if(h=d.get(f+"_title")){h.innerHTML=d.encode(g)}},alert:function(g,f,j){var i=this,h;h=i.open({title:i,type:"alert",button_func:function(k){if(f){f.call(k||i,k)}i.close(null,h.id)},content:d.encode(i.editor.getLang(g,g)),inline:1,width:400,height:130})},confirm:function(g,f,j){var i=this,h;h=i.open({title:i,type:"confirm",button_func:function(k){if(f){f.call(k||i,k)}i.close(null,h.id)},content:d.encode(i.editor.getLang(g,g)),inline:1,width:400,height:130})},_findId:function(f){var g=this;if(typeof(f)=="string"){return f}e(g.windows,function(h){var i=d.get(h.id+"_ifr");if(i&&f==i.contentWindow){f=h.id;return false}});return f},_fixIELayout:function(i,h){var f,g;if(!tinymce.isIE6){return}e(["n","s","w","e","nw","ne","sw","se"],function(j){var k=d.get(i+"_resize_"+j);d.setStyles(k,{width:h?k.clientWidth:"",height:h?k.clientHeight:"",cursor:d.getStyle(k,"cursor",1)});d.setStyle(i+"_bottom","bottom","-1px");k=0});if(f=this.windows[i]){f.element.hide();f.element.show();e(d.select("div,a",i),function(k,j){if(k.currentStyle.backgroundImage!="none"){g=new Image();g.src=k.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/,"$1")}});d.get(i).style.filter=""}}});tinymce.PluginManager.add("inlinepopups",tinymce.plugins.InlinePopups)})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/alert.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/alert.gif new file mode 100644 index 0000000..94abd08 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/alert.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/button.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/button.gif new file mode 100644 index 0000000..e671094 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/button.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif new file mode 100644 index 0000000..b408ae1 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/confirm.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/confirm.gif new file mode 100644 index 0000000..497307a Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/confirm.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/corners.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/corners.gif new file mode 100644 index 0000000..c894b2e Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/corners.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/drag.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/drag.gif new file mode 100644 index 0000000..bf0a03e Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/drag.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/horizontal.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/horizontal.gif new file mode 100644 index 0000000..c2a2ad4 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/horizontal.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/vertical.gif b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/vertical.gif new file mode 100644 index 0000000..43a735f Binary files /dev/null and b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/vertical.gif differ diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/window.css b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/window.css new file mode 100644 index 0000000..cfee3cf --- /dev/null +++ b/wp-includes/js/tinymce/plugins/inlinepopups/skins/clearlooks2/window.css @@ -0,0 +1,125 @@ +/* Clearlooks 2 */ +/* Reset */ +.clearlooks2, .clearlooks2 div, .clearlooks2 span, .clearlooks2 a {vertical-align:baseline; text-align:left; position:absolute; border:0; padding:0; margin:0; background:transparent; font-family:Arial,Verdana; font-size:11px; color:#000; text-decoration:none; font-weight:normal; width:auto; height:auto; overflow:hidden; display:block;} + +/* General */ +.clearlooks2 {position:absolute; direction:ltr} +.clearlooks2 .mceWrapper {position:static} +.mceEventBlocker {position:fixed; left:0; top:0; background:url(img/horizontal.gif) no-repeat 0 -75px; width:100%; height:100%} +.clearlooks2 .mcePlaceHolder {border:1px solid #000; background:#888; top:0; left:0; opacity:0.5; -ms-filter:'alpha(opacity=50)'; filter:alpha(opacity=50)} +.clearlooks2_modalBlocker {position:fixed; left:0; top:0; width:100%; height:100%; background:#FFF; opacity:0.6; -ms-filter:'alpha(opacity=60)'; filter:alpha(opacity=60); display:none} + +/* Top */ +.clearlooks2 .mceTop, +.clearlooks2 .mceTop div { + top:0; + width:100%; + height:23px +} +.clearlooks2 .mceTop .mceLeft { + width:55%; + background-image: none; + border-style: solid none none solid; + border-width: 1px; +} +.clearlooks2 .mceTop .mceCenter { +} +.clearlooks2 .mceTop .mceRight { + right:0; + width:55%; + height:23px; + background-image: none; + border-style: solid solid none none; + border-width: 1px; +} +.clearlooks2 .mceTop span { + width:100%; + font: 12px/20px bold "Lucida Grande","Lucida Sans Unicode",Tahoma,Verdana,sans-serif; + text-align:center; + vertical-align:middle; + line-height:23px; + font-weight:bold; +} +.clearlooks2 .mceFocus .mceTop .mceLeft { + background-image: none; + border-style: solid none none solid; + border-width: 1px; +} +.clearlooks2 .mceFocus .mceTop .mceCenter { +} +.clearlooks2 .mceFocus .mceTop .mceRight { + background-image: none; + border-style: solid solid none none; + border-width: 1px; +} +.clearlooks2 .mceFocus .mceTop span { +color:#FFF +} + +/* Middle */ +.clearlooks2 .mceMiddle, .clearlooks2 .mceMiddle div {top:0} +.clearlooks2 .mceMiddle {width:100%; height:100%; clip:rect(23px auto auto auto)} +.clearlooks2 .mceMiddle .mceLeft {left:0; width:5px; height:100%; background:#E4F2FD;border-left:1px solid #c6d9e9} +.clearlooks2 .mceMiddle span {top:23px; left:5px; width:100%; height:100%; background:#FFF} +.clearlooks2 .mceMiddle .mceRight {right:0; width:5px; height:100%; background:#E4F2FD;border-right:1px solid #c6d9e9} + +/* Bottom */ +.clearlooks2 .mceBottom, .clearlooks2 .mceBottom div {height:6px} +.clearlooks2 .mceBottom {left:0; bottom:0; width:100%;background:#E4F2FD;border-bottom:1px solid #c6d9e9} +.clearlooks2 .mceBottom div {top:0} +.clearlooks2 .mceBottom .mceLeft {left:0; width:5px; background:#E4F2FD ;border-left:1px solid #c6d9e9} +.clearlooks2 .mceBottom .mceCenter {left:5px; width:100%} +.clearlooks2 .mceBottom .mceRight {right:0; width:6px; background:#E4F2FD url(img/drag.gif) no-repeat;border-right:1px solid #c6d9e9} +.clearlooks2 .mceBottom span {display:none} +.clearlooks2 .mceStatusbar .mceBottom, .clearlooks2 .mceStatusbar .mceBottom div {height:23px} +.clearlooks2 .mceStatusbar .mceBottom .mceLeft {background:url(img/corners.gif) -29px 0} +.clearlooks2 .mceStatusbar .mceBottom .mceCenter {background:url(img/horizontal.gif) 0 -52px} +.clearlooks2 .mceStatusbar .mceBottom .mceRight {background:url(img/corners.gif) -24px 0} +.clearlooks2 .mceStatusbar .mceBottom span {display:block; left:7px; font-family:Arial, Verdana; font-size:11px; line-height:23px} + +/* Actions */ +.clearlooks2 a {width:29px; height:16px; top:3px} +.clearlooks2 .mceClose {right:6px; background:url(img/buttons.gif) -87px 0} +.clearlooks2 .mceMin {display:none; right:68px; background:url(img/buttons.gif) 0 0} +.clearlooks2 .mceMed {display:none; right:37px; background:url(img/buttons.gif) -29px 0} +.clearlooks2 .mceMax {display:none; right:37px; background:url(img/buttons.gif) -58px 0} +.clearlooks2 .mceMove {display:none;width:100%;cursor:move;background:url(img/corners.gif) no-repeat -100px -100px} +.clearlooks2 .mceMovable .mceMove {display:block} +.clearlooks2 .mceFocus .mceClose {right:6px; background:url(img/buttons.gif) -87px -16px} +.clearlooks2 .mceFocus .mceMin {right:68px; background:url(img/buttons.gif) 0 -16px} +.clearlooks2 .mceFocus .mceMed {right:37px; background:url(img/buttons.gif) -29px -16px} +.clearlooks2 .mceFocus .mceMax {right:37px; background:url(img/buttons.gif) -58px -16px} +.clearlooks2 .mceFocus .mceClose:hover {right:6px; background:url(img/buttons.gif) -87px -32px} +.clearlooks2 .mceFocus .mceClose:hover {right:6px; background:url(img/buttons.gif) -87px -32px} +.clearlooks2 .mceFocus .mceMin:hover {right:68px; background:url(img/buttons.gif) 0 -32px} +.clearlooks2 .mceFocus .mceMed:hover {right:37px; background:url(img/buttons.gif) -29px -32px} +.clearlooks2 .mceFocus .mceMax:hover {right:37px; background:url(img/buttons.gif) -58px -32px} + +/* Resize */ +.clearlooks2 .mceResize {top:auto; left:auto; display:none; width:5px; height:5px; background:url(img/horizontal.gif) no-repeat 0 -75px} +.clearlooks2 .mceResizable .mceResize {display:block} +.clearlooks2 .mceResizable .mceMin, .clearlooks2 .mceMax {display:none} +.clearlooks2 .mceMinimizable .mceMin {display:block} +.clearlooks2 .mceMaximizable .mceMax {display:block} +.clearlooks2 .mceMaximized .mceMed {display:block} +.clearlooks2 .mceMaximized .mceMax {display:none} +.clearlooks2 a.mceResizeN {top:0; left:0; width:100%; cursor:n-resize} +.clearlooks2 a.mceResizeNW {top:0; left:0; cursor:nw-resize} +.clearlooks2 a.mceResizeNE {top:0; right:0; cursor:ne-resize} +.clearlooks2 a.mceResizeW {top:0; left:0; height:100%; cursor:w-resize} +.clearlooks2 a.mceResizeE {top:0; right:0; height:100%; cursor:e-resize} +.clearlooks2 a.mceResizeS {bottom:0; left:0; width:100%; cursor:s-resize} +.clearlooks2 a.mceResizeSW {bottom:0; left:0; cursor:sw-resize} +.clearlooks2 a.mceResizeSE {bottom:0; right:0; cursor:se-resize} + +/* Alert/Confirm */ +.clearlooks2 .mceButton {font-weight:bold; bottom:10px; width:80px; height:30px; background:url(img/button.gif); line-height:30px; vertical-align:middle; text-align:center; outline:0} +.clearlooks2 .mceMiddle .mceIcon {left:15px; top:35px; width:32px; height:32px} +.clearlooks2 .mceAlert .mceMiddle span, .clearlooks2 .mceConfirm .mceMiddle span {background:transparent;left:60px; top:35px; width:320px; height:50px; font-weight:bold; overflow:auto; white-space:normal} +.clearlooks2 a:hover {font-weight:bold} +.clearlooks2 .mceAlert .mceMiddle, .clearlooks2 .mceConfirm .mceMiddle {background:#E4F2FD} +.clearlooks2 .mceAlert .mceOk {left:50%; top:auto; margin-left: -40px} +.clearlooks2 .mceAlert .mceIcon {background:url(img/alert.gif)} +.clearlooks2 .mceConfirm .mceOk {left:50%; top:auto; margin-left: -90px} +.clearlooks2 .mceConfirm .mceCancel {left:50%; top:auto} +.clearlooks2 .mceConfirm .mceIcon {background:url(img/confirm.gif)} diff --git a/wp-includes/js/tinymce/plugins/inlinepopups/template.htm b/wp-includes/js/tinymce/plugins/inlinepopups/template.htm new file mode 100644 index 0000000..f7bff5d --- /dev/null +++ b/wp-includes/js/tinymce/plugins/inlinepopups/template.htm @@ -0,0 +1,387 @@ + + + +Template for dialogs + + + + +
    +
    +
    +
    +
    +
    +
    + Blured +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Focused +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Statusbar +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Statusbar, Resizable +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Resizable, Maximizable +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Blurred, Maximizable, Statusbar, Resizable +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Maximized, Maximizable, Minimizable +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Blured +
    + +
    +
    + Content +
    +
    + +
    +
    +
    +
    + Statusbar text. +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    +
    +
    + Alert +
    + +
    +
    + + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + +
    +
    +
    + +
    +
    +
    +
    +
    + + + Ok + +
    +
    + +
    +
    +
    +
    +
    +
    + Confirm +
    + +
    +
    + + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + This is a very long error message. This is a very long error message. + +
    +
    +
    + +
    +
    +
    +
    +
    + + + Ok + Cancel + +
    +
    +
    + + + diff --git a/wp-includes/js/tinymce/plugins/media/css/content.css b/wp-includes/js/tinymce/plugins/media/css/content.css new file mode 100644 index 0000000..7739381 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/media/css/content.css @@ -0,0 +1,6 @@ +.mceItemFlash, .mceItemShockWave, .mceItemQuickTime, .mceItemWindowsMedia, .mceItemRealMedia {border:1px dotted #cc0000; background-position:center; background-repeat:no-repeat; background-color:#ffffcc;} +.mceItemShockWave {background-image: url(../img/shockwave.gif);} +.mceItemFlash {background-image:url(../img/flash.gif);} +.mceItemQuickTime {background-image:url(../img/quicktime.gif);} +.mceItemWindowsMedia {background-image:url(../img/windowsmedia.gif);} +.mceItemRealMedia {background-image:url(../img/realmedia.gif);} diff --git a/wp-includes/js/tinymce/plugins/media/css/media.css b/wp-includes/js/tinymce/plugins/media/css/media.css new file mode 100644 index 0000000..7b2253b --- /dev/null +++ b/wp-includes/js/tinymce/plugins/media/css/media.css @@ -0,0 +1,16 @@ +#id, #name, #hspace, #vspace, #class_name, #align { width: 100px } +#hspace, #vspace { width: 50px } +#flash_quality, #flash_align, #flash_scale, #flash_salign, #flash_wmode { width: 100px } +#flash_base, #flash_flashvars { width: 240px } +#width, #height { width: 40px } +#src, #media_type { width: 250px } +#class { width: 120px } +#prev { margin: 0; border: 1px solid black; width: 380px; height: 230px; overflow: auto } +.panel_wrapper div.current { height: 390px; overflow: auto } +#flash_options, #shockwave_options, #qt_options, #wmp_options, #rmp_options { display: none } +.mceAddSelectValue { background-color: #DDDDDD } +#qt_starttime, #qt_endtime, #qt_fov, #qt_href, #qt_moveid, #qt_moviename, #qt_node, #qt_pan, #qt_qtsrc, #qt_qtsrcchokespeed, #qt_target, #qt_tilt, #qt_urlsubstituten, #qt_volume { width: 70px } +#wmp_balance, #wmp_baseurl, #wmp_captioningid, #wmp_currentmarker, #wmp_currentposition, #wmp_defaultframe, #wmp_playcount, #wmp_rate, #wmp_uimode, #wmp_volume { width: 70px } +#rmp_console, #rmp_numloop, #rmp_controls, #rmp_scriptcallbacks { width: 70px } +#shockwave_swvolume, #shockwave_swframe, #shockwave_swurl, #shockwave_swstretchvalign, #shockwave_swstretchhalign, #shockwave_swstretchstyle { width: 90px } +#qt_qtsrc { width: 200px } diff --git a/wp-includes/js/tinymce/plugins/media/editor_plugin.js b/wp-includes/js/tinymce/plugins/media/editor_plugin.js new file mode 100644 index 0000000..951d1e4 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/media/editor_plugin.js @@ -0,0 +1 @@ +(function(){var a=tinymce.each;tinymce.create("tinymce.plugins.MediaPlugin",{init:function(b,c){var e=this;e.editor=b;e.url=c;function f(g){return/^(mceItemFlash|mceItemShockWave|mceItemWindowsMedia|mceItemQuickTime|mceItemRealMedia)$/.test(g.className)}b.onPreInit.add(function(){b.serializer.addRules("param[name|value|_mce_value]")});b.addCommand("mceMedia",function(){b.windowManager.open({file:c+"/media.htm",width:430+parseInt(b.getLang("media.delta_width",0)),height:470+parseInt(b.getLang("media.delta_height",0)),inline:1},{plugin_url:c})});b.addButton("media",{title:"media.desc",cmd:"mceMedia"});b.onNodeChange.add(function(h,g,i){g.setActive("media",i.nodeName=="IMG"&&f(i))});b.onInit.add(function(){var g={mceItemFlash:"flash",mceItemShockWave:"shockwave",mceItemWindowsMedia:"windowsmedia",mceItemQuickTime:"quicktime",mceItemRealMedia:"realmedia"};b.selection.onSetContent.add(function(){e._spansToImgs(b.getBody())});b.selection.onBeforeSetContent.add(e._objectsToSpans,e);if(b.settings.content_css!==false){b.dom.loadCSS(c+"/css/content.css")}if(b.theme.onResolveName){b.theme.onResolveName.add(function(h,i){if(i.name=="img"){a(g,function(l,j){if(b.dom.hasClass(i.node,j)){i.name=l;i.title=b.dom.getAttrib(i.node,"title");return false}})}})}if(b&&b.plugins.contextmenu){b.plugins.contextmenu.onContextMenu.add(function(i,h,j){if(j.nodeName=="IMG"&&/mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(j.className)){h.add({title:"media.edit",icon:"media",cmd:"mceMedia"})}})}});b.onBeforeSetContent.add(e._objectsToSpans,e);b.onSetContent.add(function(){e._spansToImgs(b.getBody())});b.onPreProcess.add(function(g,i){var h=g.dom;if(i.set){e._spansToImgs(i.node);a(h.select("IMG",i.node),function(k){var j;if(f(k)){j=e._parse(k.title);h.setAttrib(k,"width",h.getAttrib(k,"width",j.width||100));h.setAttrib(k,"height",h.getAttrib(k,"height",j.height||100))}})}if(i.get){a(h.select("IMG",i.node),function(m){var l,j,k;if(g.getParam("media_use_script")){if(f(m)){m.className=m.className.replace(/mceItem/g,"mceTemp")}return}switch(m.className){case"mceItemFlash":l="d27cdb6e-ae6d-11cf-96b8-444553540000";j="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0";k="application/x-shockwave-flash";break;case"mceItemShockWave":l="166b1bca-3f9c-11cf-8075-444553540000";j="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0";k="application/x-director";break;case"mceItemWindowsMedia":l=g.getParam("media_wmp6_compatible")?"05589fa1-c356-11ce-bf01-00aa0055595a":"6bf52a52-394a-11d3-b153-00c04f79faa6";j="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701";k="application/x-mplayer2";break;case"mceItemQuickTime":l="02bf25d5-8c17-4b23-bc80-d3488abddc6b";j="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0";k="video/quicktime";break;case"mceItemRealMedia":l="cfcdaa03-8be4-11cf-b84b-0020afbbccfa";j="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0";k="audio/x-pn-realaudio-plugin";break}if(l){h.replace(e._buildObj({classid:l,codebase:j,type:k},m),m)}})}});b.onPostProcess.add(function(g,h){h.content=h.content.replace(/_mce_value=/g,"value=")});function d(g,h){h=new RegExp(h+'="([^"]+)"',"g").exec(g);return h?b.dom.decode(h[1]):""}b.onPostProcess.add(function(g,h){if(g.getParam("media_use_script")){h.content=h.content.replace(/]+>/g,function(j){var i=d(j,"class");if(/^(mceTempFlash|mceTempShockWave|mceTempWindowsMedia|mceTempQuickTime|mceTempRealMedia)$/.test(i)){at=e._parse(d(j,"title"));at.width=d(j,"width");at.height=d(j,"height");j=''); + +function init() { + var pl = "", f, val; + var type = "flash", fe, i; + + ed = tinyMCEPopup.editor; + + tinyMCEPopup.resizeToInnerSize(); + f = document.forms[0] + + fe = ed.selection.getNode(); + if (/mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(ed.dom.getAttrib(fe, 'class'))) { + pl = fe.title; + + switch (ed.dom.getAttrib(fe, 'class')) { + case 'mceItemFlash': + type = 'flash'; + break; + + case 'mceItemFlashVideo': + type = 'flv'; + break; + + case 'mceItemShockWave': + type = 'shockwave'; + break; + + case 'mceItemWindowsMedia': + type = 'wmp'; + break; + + case 'mceItemQuickTime': + type = 'qt'; + break; + + case 'mceItemRealMedia': + type = 'rmp'; + break; + } + + document.forms[0].insert.value = ed.getLang('update', 'Insert', true); + } + + document.getElementById('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media'); + document.getElementById('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','qt_qtsrc','media','media'); + document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); + + var html = getMediaListHTML('medialist','src','media','media'); + if (html == "") + document.getElementById("linklistrow").style.display = 'none'; + else + document.getElementById("linklistcontainer").innerHTML = html; + + // Resize some elements + if (isVisible('filebrowser')) + document.getElementById('src').style.width = '230px'; + + // Setup form + if (pl != "") { + pl = tinyMCEPopup.editor.plugins.media._parse(pl); + + switch (type) { + case "flash": + setBool(pl, 'flash', 'play'); + setBool(pl, 'flash', 'loop'); + setBool(pl, 'flash', 'menu'); + setBool(pl, 'flash', 'swliveconnect'); + setStr(pl, 'flash', 'quality'); + setStr(pl, 'flash', 'scale'); + setStr(pl, 'flash', 'salign'); + setStr(pl, 'flash', 'wmode'); + setStr(pl, 'flash', 'base'); + setStr(pl, 'flash', 'flashvars'); + break; + + case "qt": + setBool(pl, 'qt', 'loop'); + setBool(pl, 'qt', 'autoplay'); + setBool(pl, 'qt', 'cache'); + setBool(pl, 'qt', 'controller'); + setBool(pl, 'qt', 'correction'); + setBool(pl, 'qt', 'enablejavascript'); + setBool(pl, 'qt', 'kioskmode'); + setBool(pl, 'qt', 'autohref'); + setBool(pl, 'qt', 'playeveryframe'); + setBool(pl, 'qt', 'tarsetcache'); + setStr(pl, 'qt', 'scale'); + setStr(pl, 'qt', 'starttime'); + setStr(pl, 'qt', 'endtime'); + setStr(pl, 'qt', 'tarset'); + setStr(pl, 'qt', 'qtsrcchokespeed'); + setStr(pl, 'qt', 'volume'); + setStr(pl, 'qt', 'qtsrc'); + break; + + case "shockwave": + setBool(pl, 'shockwave', 'sound'); + setBool(pl, 'shockwave', 'progress'); + setBool(pl, 'shockwave', 'autostart'); + setBool(pl, 'shockwave', 'swliveconnect'); + setStr(pl, 'shockwave', 'swvolume'); + setStr(pl, 'shockwave', 'swstretchstyle'); + setStr(pl, 'shockwave', 'swstretchhalign'); + setStr(pl, 'shockwave', 'swstretchvalign'); + break; + + case "wmp": + setBool(pl, 'wmp', 'autostart'); + setBool(pl, 'wmp', 'enabled'); + setBool(pl, 'wmp', 'enablecontextmenu'); + setBool(pl, 'wmp', 'fullscreen'); + setBool(pl, 'wmp', 'invokeurls'); + setBool(pl, 'wmp', 'mute'); + setBool(pl, 'wmp', 'stretchtofit'); + setBool(pl, 'wmp', 'windowlessvideo'); + setStr(pl, 'wmp', 'balance'); + setStr(pl, 'wmp', 'baseurl'); + setStr(pl, 'wmp', 'captioningid'); + setStr(pl, 'wmp', 'currentmarker'); + setStr(pl, 'wmp', 'currentposition'); + setStr(pl, 'wmp', 'defaultframe'); + setStr(pl, 'wmp', 'playcount'); + setStr(pl, 'wmp', 'rate'); + setStr(pl, 'wmp', 'uimode'); + setStr(pl, 'wmp', 'volume'); + break; + + case "rmp": + setBool(pl, 'rmp', 'autostart'); + setBool(pl, 'rmp', 'loop'); + setBool(pl, 'rmp', 'autogotourl'); + setBool(pl, 'rmp', 'center'); + setBool(pl, 'rmp', 'imagestatus'); + setBool(pl, 'rmp', 'maintainaspect'); + setBool(pl, 'rmp', 'nojava'); + setBool(pl, 'rmp', 'prefetch'); + setBool(pl, 'rmp', 'shuffle'); + setStr(pl, 'rmp', 'console'); + setStr(pl, 'rmp', 'controls'); + setStr(pl, 'rmp', 'numloop'); + setStr(pl, 'rmp', 'scriptcallbacks'); + break; + } + + setStr(pl, null, 'src'); + setStr(pl, null, 'id'); + setStr(pl, null, 'name'); + setStr(pl, null, 'vspace'); + setStr(pl, null, 'hspace'); + setStr(pl, null, 'bgcolor'); + setStr(pl, null, 'align'); + setStr(pl, null, 'width'); + setStr(pl, null, 'height'); + + if ((val = ed.dom.getAttrib(fe, "width")) != "") + pl.width = f.width.value = val; + + if ((val = ed.dom.getAttrib(fe, "height")) != "") + pl.height = f.height.value = val; + + oldWidth = pl.width ? parseInt(pl.width) : 0; + oldHeight = pl.height ? parseInt(pl.height) : 0; + } else + oldWidth = oldHeight = 0; + + selectByValue(f, 'media_type', type); + changedType(type); + updateColor('bgcolor_pick', 'bgcolor'); + + TinyMCE_EditableSelects.init(); + generatePreview(); +} + +function insertMedia() { + var fe, f = document.forms[0], h; + + tinyMCEPopup.restoreSelection(); + + if (!AutoValidator.validate(f)) { + tinyMCEPopup.alert(ed.getLang('invalid_data')); + return false; + } + + f.width.value = f.width.value == "" ? 100 : f.width.value; + f.height.value = f.height.value == "" ? 100 : f.height.value; + + fe = ed.selection.getNode(); + if (fe != null && /mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(ed.dom.getAttrib(fe, 'class'))) { + switch (f.media_type.options[f.media_type.selectedIndex].value) { + case "flash": + fe.className = "mceItemFlash"; + break; + + case "flv": + fe.className = "mceItemFlashVideo"; + break; + + case "shockwave": + fe.className = "mceItemShockWave"; + break; + + case "qt": + fe.className = "mceItemQuickTime"; + break; + + case "wmp": + fe.className = "mceItemWindowsMedia"; + break; + + case "rmp": + fe.className = "mceItemRealMedia"; + break; + } + + if (fe.width != f.width.value || fe.height != f.height.value) + ed.execCommand('mceRepaint'); + + fe.title = serializeParameters(); + fe.width = f.width.value; + fe.height = f.height.value; + fe.style.width = f.width.value + (f.width.value.indexOf('%') == -1 ? 'px' : ''); + fe.style.height = f.height.value + (f.height.value.indexOf('%') == -1 ? 'px' : ''); + fe.align = f.align.options[f.align.selectedIndex].value; + } else { + h = ' 0) { + var html = ""; + + html += ''; + + return html; + } + + return ""; +} + +function getType(v) { + var fo, i, c, el, x, f = document.forms[0]; + + fo = ed.getParam("media_types", "flash=swf;flv=flv;shockwave=dcr;qt=mov,qt,mpg,mp3,mp4,mpeg;shockwave=dcr;wmp=avi,wmv,wm,asf,asx,wmx,wvx;rmp=rm,ra,ram").split(';'); + + // YouTube + if (v.match(/watch\?v=(.+)(.*)/)) { + f.width.value = '425'; + f.height.value = '350'; + f.src.value = 'http://www.youtube.com/v/' + v.match(/v=(.*)(.*)/)[0].split('=')[1]; + return 'flash'; + } + + // Google video + if (v.indexOf('http://video.google.com/videoplay?docid=') == 0) { + f.width.value = '425'; + f.height.value = '326'; + f.src.value = 'http://video.google.com/googleplayer.swf?docId=' + v.substring('http://video.google.com/videoplay?docid='.length) + '&hl=en'; + return 'flash'; + } + + for (i=0; i 0 ? s.substring(0, s.length - 1) : s; + + return s; +} + +function setBool(pl, p, n) { + if (typeof(pl[n]) == "undefined") + return; + + document.forms[0].elements[p + "_" + n].checked = pl[n] != 'false'; +} + +function setStr(pl, p, n) { + var f = document.forms[0], e = f.elements[(p != null ? p + "_" : '') + n]; + + if (typeof(pl[n]) == "undefined") + return; + + if (e.type == "text") + e.value = pl[n]; + else + selectByValue(f, (p != null ? p + "_" : '') + n, pl[n]); +} + +function getBool(p, n, d, tv, fv) { + var v = document.forms[0].elements[p + "_" + n].checked; + + tv = typeof(tv) == 'undefined' ? 'true' : "'" + jsEncode(tv) + "'"; + fv = typeof(fv) == 'undefined' ? 'false' : "'" + jsEncode(fv) + "'"; + + return (v == d) ? '' : n + (v ? ':' + tv + ',' : ":\'" + fv + "\',"); +} + +function getStr(p, n, d) { + var e = document.forms[0].elements[(p != null ? p + "_" : "") + n]; + var v = e.type == "text" ? e.value : e.options[e.selectedIndex].value; + + if (n == 'src') + v = tinyMCEPopup.editor.convertURL(v, 'src', null); + + return ((n == d || v == '') ? '' : n + ":'" + jsEncode(v) + "',"); +} + +function getInt(p, n, d) { + var e = document.forms[0].elements[(p != null ? p + "_" : "") + n]; + var v = e.type == "text" ? e.value : e.options[e.selectedIndex].value; + + return ((n == d || v == '') ? '' : n + ":" + v.replace(/[^0-9]+/g, '') + ","); +} + +function jsEncode(s) { + s = s.replace(new RegExp('\\\\', 'g'), '\\\\'); + s = s.replace(new RegExp('"', 'g'), '\\"'); + s = s.replace(new RegExp("'", 'g'), "\\'"); + + return s; +} + +function generatePreview(c) { + var f = document.forms[0], p = document.getElementById('prev'), h = '', cls, pl, n, type, codebase, wp, hp, nw, nh; + + p.innerHTML = ''; + + nw = parseInt(f.width.value); + nh = parseInt(f.height.value); + + if (f.width.value != "" && f.height.value != "") { + if (f.constrain.checked) { + if (c == 'width' && oldWidth != 0) { + wp = nw / oldWidth; + nh = Math.round(wp * nh); + f.height.value = nh; + } else if (c == 'height' && oldHeight != 0) { + hp = nh / oldHeight; + nw = Math.round(hp * nw); + f.width.value = nw; + } + } + } + + if (f.width.value != "") + oldWidth = nw; + + if (f.height.value != "") + oldHeight = nh; + + // After constrain + pl = serializeParameters(); + + switch (f.media_type.options[f.media_type.selectedIndex].value) { + case "flash": + cls = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; + codebase = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; + type = 'application/x-shockwave-flash'; + break; + + case "shockwave": + cls = 'clsid:166B1BCA-3F9C-11CF-8075-444553540000'; + codebase = 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0'; + type = 'application/x-director'; + break; + + case "qt": + cls = 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'; + codebase = 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0'; + type = 'video/quicktime'; + break; + + case "wmp": + cls = ed.getParam('media_wmp6_compatible') ? 'clsid:05589FA1-C356-11CE-BF01-00AA0055595A' : 'clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6'; + codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; + type = 'application/x-mplayer2'; + break; + + case "rmp": + cls = 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'; + codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; + type = 'audio/x-pn-realaudio-plugin'; + break; + } + + if (pl == '') { + p.innerHTML = ''; + return; + } + + pl = tinyMCEPopup.editor.plugins.media._parse(pl); + + if (!pl.src) { + p.innerHTML = ''; + return; + } + + pl.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(pl.src); + pl.width = !pl.width ? 100 : pl.width; + pl.height = !pl.height ? 100 : pl.height; + pl.id = !pl.id ? 'obj' : pl.id; + pl.name = !pl.name ? 'eobj' : pl.name; + pl.align = !pl.align ? '' : pl.align; + + // Avoid annoying warning about insecure items + if (!tinymce.isIE || document.location.protocol != 'https:') { + h += ''; + + for (n in pl) { + h += ''; + + // Add extra url parameter if it's an absolute URL + if (n == 'src' && pl[n].indexOf('://') != -1) + h += ''; + } + } + + h += ' + + + {#media_dlg.title} + + + + + + + + + +
    + + +
    +
    +
    + {#media_dlg.general} + + + + + + + + + + + + + + + + + + +
    + +
    + + + + + +
     
    +
    + + + + + + +
    x   
    +
    +
    + +
    + {#media_dlg.preview} + +
    +
    + +
    +
    + {#media_dlg.advanced} + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + +
     
    +
    +
    + +
    + {#media_dlg.flash_options} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + + + + + + + +
    +
    + +
    + {#media_dlg.flv_options} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    +
    + +
    + {#media_dlg.qt_options} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    +  
    + + + + + +
     
    +
    +
    + +
    + {#media_dlg.wmp_options} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    +
    + +
    + {#media_dlg.rmp_options} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    +   +
    +
    + +
    + {#media_dlg.shockwave_options} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + + +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    + + + + + +
    +
    +
    +
    +
    + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/plugins/paste/blank.htm b/wp-includes/js/tinymce/plugins/paste/blank.htm new file mode 100644 index 0000000..4382a11 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/paste/blank.htm @@ -0,0 +1,21 @@ + + +blank_page + + + + + + + + diff --git a/wp-includes/js/tinymce/plugins/paste/editor_plugin.js b/wp-includes/js/tinymce/plugins/paste/editor_plugin.js new file mode 100644 index 0000000..e0e51b5 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/paste/editor_plugin.js @@ -0,0 +1 @@ +(function(){var a=tinymce.each;tinymce.create("tinymce.plugins.PastePlugin",{init:function(c,d){var e=this,b;e.editor=c;e.url=d;e.onPreProcess=new tinymce.util.Dispatcher(e);e.onPostProcess=new tinymce.util.Dispatcher(e);e.onPreProcess.add(e._preProcess);e.onPostProcess.add(e._postProcess);e.onPreProcess.add(function(h,i){c.execCallback("paste_preprocess",h,i)});e.onPostProcess.add(function(h,i){c.execCallback("paste_postprocess",h,i)});function g(i){var k=c.dom,j={content:i};e.onPreProcess.dispatch(e,j);j.node=k.create("div",0,j.content);e.onPostProcess.dispatch(e,j);j.content=c.serializer.serialize(j.node,{getInner:1});if(/<(p|h[1-6]|ul|ol)/.test(j.content)){e._insertBlockContent(c,k,j.content)}else{e._insert(j.content)}}c.addCommand("mceInsertClipboardContent",function(i,h){g(h)});function f(l){var p,k,i,j=c.selection,o=c.dom,h=c.getBody(),m;if(o.get("_mcePaste")){return}p=o.add(h,"div",{id:"_mcePaste"}," ");if(h!=c.getDoc().body){m=o.getPos(c.selection.getStart(),h).y}else{m=h.scrollTop}o.setStyles(p,{position:"absolute",left:-10000,top:m,width:1,height:1,overflow:"hidden"});if(tinymce.isIE){i=o.doc.body.createTextRange();i.moveToElementText(p);i.execCommand("Paste");o.remove(p);g(p.innerHTML);return tinymce.dom.Event.cancel(l)}else{k=c.selection.getRng();p=p.firstChild;i=c.getDoc().createRange();i.setStart(p,0);i.setEnd(p,1);j.setRng(i);window.setTimeout(function(){var r=o.get("_mcePaste"),q;r.id="_mceRemoved";o.remove(r);r=o.get("_mcePaste")||r;q=(o.select("> span.Apple-style-span div",r)[0]||o.select("> span.Apple-style-span",r)[0]||r).innerHTML;o.remove(r);if(k){j.setRng(k)}g(q)},0)}}if(c.getParam("paste_auto_cleanup_on_paste",true)){if(tinymce.isOpera||/Firefox\/2/.test(navigator.userAgent)){c.onKeyDown.add(function(h,i){if(((tinymce.isMac?i.metaKey:i.ctrlKey)&&i.keyCode==86)||(i.shiftKey&&i.keyCode==45)){f(i)}})}else{c.onPaste.addToTop(function(h,i){return f(i)})}}if(c.getParam("paste_block_drop")){c.onInit.add(function(){c.dom.bind(c.getBody(),["dragend","dragover","draggesture","dragdrop","drop","drag"],function(h){h.preventDefault();h.stopPropagation();return false})})}e._legacySupport()},getInfo:function(){return{longname:"Paste text/word",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_preProcess:function(d,g){var b=this.editor,c=g.content,f,e;function f(h){a(h,function(i){if(i.constructor==RegExp){c=c.replace(i,"")}else{c=c.replace(i[0],i[1])}})}f([/^\s*( )+/g,/( |]*>)+\s*$/g]);if(/(class=\"?Mso|style=\"[^\"]*\bmso\-|w:WordDocument)/.test(c)){g.wordContent=true;if(b.getParam("paste_convert_middot_lists",true)){f([[//gi,"$&__MCE_ITEM__"],[/(]+:\s*symbol[^>]+>)/gi,"$1__MCE_ITEM__"],[/(]+mso-list:[^>]+>)/gi,"$1__MCE_ITEM__"]])}f([//gi,/<\/?(img|font|meta|link|style|div|v:\w+)[^>]*>/gi,/<\\?\?xml[^>]*>/gi,/<\/?o:[^>]*>/gi,/ (id|name|language|type|on\w+|v:\w+)=\"([^\"]*)\"/gi,/ (id|name|language|type|on\w+|v:\w+)=(\w+)/gi,[/<(\/?)s>/gi,"<$1strike>"],/]+>[\s\S]*?<\/script>/gi,[/ /g,"\u00a0"]]);if(!b.getParam("paste_retain_style_properties")){f([/<\/?(span)[^>]*>/gi])}}e=b.getParam("paste_strip_class_attributes","all");if(e!="none"){if(e=="all"){f([/ class=\"([^\"]*)\"/gi,/ class=(\w+)/gi])}else{f([/ class=\"(mso[^\"]*)\"/gi,/ class=(mso\w+)/gi])}}if(b.getParam("paste_remove_spans")){f([/<\/?(span)[^>]*>/gi])}g.content=c},_postProcess:function(e,g){var d=this,c=d.editor,f=c.dom,b;if(g.wordContent){a(f.select("a",g.node),function(h){if(!h.href||h.href.indexOf("#_Toc")!=-1){f.remove(h,1)}});if(d.editor.getParam("paste_convert_middot_lists",true)){d._convertLists(e,g)}b=c.getParam("paste_retain_style_properties");if(tinymce.is(b,"string")){b=tinymce.explode(b)}a(f.select("*",g.node),function(l){var m={},j=0,k,n,h;if(b){for(k=0;k0){f.setStyles(l,m)}else{if(l.nodeName=="SPAN"&&!l.className){f.remove(l,true)}}})}if(c.getParam("paste_remove_styles")||(c.getParam("paste_remove_styles_if_webkit")&&tinymce.isWebKit)){a(f.select("*[style]",g.node),function(h){h.removeAttribute("style");h.removeAttribute("mce_style")})}else{if(tinymce.isWebKit){a(f.select("*",g.node),function(h){h.removeAttribute("mce_style")})}}},_convertLists:function(e,c){var g=e.editor.dom,f,j,b=-1,d,k=[],i,h;a(g.select("p",c.node),function(r){var n,s="",q,o,l,m;for(n=r.firstChild;n&&n.nodeType==3;n=n.nextSibling){s+=n.nodeValue}s=r.innerHTML.replace(/<\/?\w+[^>]*>/gi,"").replace(/ /g,"\u00a0");if(/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o]\s*\u00a0*/.test(s)){q="ul"}if(/^__MCE_ITEM__\s*\w+\.\s*\u00a0{2,}/.test(s)){q="ol"}if(q){d=parseFloat(r.style.marginLeft||0);if(d>b){k.push(d)}if(!f||q!=i){f=g.create(q);g.insertAfter(f,r)}else{if(d>b){f=j.appendChild(g.create(q))}else{if(d]*>/gi,"");if(q=="ul"&&/^[\u2022\u00b7\u00a7\u00d8o]/.test(p)){g.remove(t)}else{if(/^[\s\S]*\w+\.( |\u00a0)*\s*/.test(p)){g.remove(t)}}});o=r.innerHTML;if(q=="ul"){o=r.innerHTML.replace(/__MCE_ITEM__/g,"").replace(/^[\u2022\u00b7\u00a7\u00d8o]\s*( |\u00a0)+\s*/,"")}else{o=r.innerHTML.replace(/__MCE_ITEM__/g,"").replace(/^\s*\w+\.( |\u00a0)+\s*/,"")}j=f.appendChild(g.create("li",0,o));g.remove(r);b=d;i=q}else{f=b=0}});h=c.node.innerHTML;if(h.indexOf("__MCE_ITEM__")!=-1){c.node.innerHTML=h.replace(/__MCE_ITEM__/g,"")}},_insertBlockContent:function(h,e,i){var c,g,d=h.selection,m,j,b,k,f;function l(p){var o;if(tinymce.isIE){o=h.getDoc().body.createTextRange();o.moveToElementText(p);o.collapse(false);o.select()}else{d.select(p,1);d.collapse(false)}}this._insert(' ',1);g=e.get("_marker");c=e.getParent(g,"p,h1,h2,h3,h4,h5,h6,ul,ol");if(c){g=e.split(c,g);a(e.create("div",0,i).childNodes,function(o){m=g.parentNode.insertBefore(o.cloneNode(true),g)});l(m)}else{e.setOuterHTML(g,i);d.select(h.getBody(),1);d.collapse(0)}e.remove("_marker");j=d.getStart();b=e.getViewPort(h.getWin());k=h.dom.getPos(j).y;f=j.clientHeight;if(kb.y+b.h){h.getDoc().body.scrollTop=k 1) { + h = ''; + tinymce.each(lines, function(row) { + h += '

    ' + row + '

    '; + }); + } + } + + tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, h); + tinyMCEPopup.close(); + }, + + resize : function() { + var vp = tinyMCEPopup.dom.getViewPort(window), el; + + el = document.getElementById('content'); + + el.style.width = (vp.w - 20) + 'px'; + el.style.height = (vp.h - 90) + 'px'; + } +}; + +tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog); diff --git a/wp-includes/js/tinymce/plugins/paste/js/pasteword.js b/wp-includes/js/tinymce/plugins/paste/js/pasteword.js new file mode 100644 index 0000000..fb3e54d --- /dev/null +++ b/wp-includes/js/tinymce/plugins/paste/js/pasteword.js @@ -0,0 +1,51 @@ +tinyMCEPopup.requireLangPack(); + +var PasteWordDialog = { + init : function() { + var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = ''; + + // Create iframe + el.innerHTML = ''; + ifr = document.getElementById('iframe'); + doc = ifr.contentWindow.document; + + // Force absolute CSS urls + css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")]; + css = css.concat(tinymce.explode(ed.settings.content_css) || []); + tinymce.each(css, function(u) { + cssHTML += ''; + }); + + // Write content into iframe + doc.open(); + doc.write('' + cssHTML + ''); + doc.close(); + + doc.designMode = 'on'; + this.resize(); + + window.setTimeout(function() { + ifr.contentWindow.focus(); + }, 10); + }, + + insert : function() { + var h = document.getElementById('iframe').contentWindow.document.body.innerHTML; + + tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, h); + tinyMCEPopup.close(); + }, + + resize : function() { + var vp = tinyMCEPopup.dom.getViewPort(window), el; + + el = document.getElementById('iframe'); + + if (el) { + el.style.width = (vp.w - 20) + 'px'; + el.style.height = (vp.h - 90) + 'px'; + } + } +}; + +tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog); diff --git a/wp-includes/js/tinymce/plugins/paste/pastetext.htm b/wp-includes/js/tinymce/plugins/paste/pastetext.htm new file mode 100644 index 0000000..bedde9a --- /dev/null +++ b/wp-includes/js/tinymce/plugins/paste/pastetext.htm @@ -0,0 +1,33 @@ + + + {#paste.paste_text_desc} + + + + + +
    +
    {#paste.paste_text_desc}
    + +
    + +
    + +
    + +
    {#paste_dlg.text_title}
    + + + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/plugins/paste/pasteword.htm b/wp-includes/js/tinymce/plugins/paste/pasteword.htm new file mode 100644 index 0000000..de6b5e4 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/paste/pasteword.htm @@ -0,0 +1,27 @@ + + + + {#paste.paste_word_desc} + + + + +
    +
    {#paste.paste_word_desc}
    + +
    {#paste_dlg.word_title}
    + +
    + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/plugins/safari/blank.htm b/wp-includes/js/tinymce/plugins/safari/blank.htm new file mode 100644 index 0000000..266808c --- /dev/null +++ b/wp-includes/js/tinymce/plugins/safari/blank.htm @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/safari/editor_plugin.js b/wp-includes/js/tinymce/plugins/safari/editor_plugin.js new file mode 100644 index 0000000..794477c --- /dev/null +++ b/wp-includes/js/tinymce/plugins/safari/editor_plugin.js @@ -0,0 +1 @@ +(function(){var a=tinymce.dom.Event,c=tinymce.grep,d=tinymce.each,b=tinymce.inArray;function e(j,i,h){var g,k;g=j.createTreeWalker(i,NodeFilter.SHOW_ALL,null,false);while(k=g.nextNode()){if(h){if(!h(k)){return false}}if(k.nodeType==3&&k.nodeValue&&/[^\s\u00a0]+/.test(k.nodeValue)){return false}if(k.nodeType==1&&/^(HR|IMG|TABLE)$/.test(k.nodeName)){return false}}return true}tinymce.create("tinymce.plugins.Safari",{init:function(f){var g=this,h;if(!tinymce.isWebKit){return}g.editor=f;g.webKitFontSizes=["x-small","small","medium","large","x-large","xx-large","-webkit-xxx-large"];g.namedFontSizes=["xx-small","x-small","small","medium","large","x-large","xx-large"];f.addCommand("CreateLink",function(k,j){var m=f.selection.getNode(),l=f.dom,i;if(m&&(/^(left|right)$/i.test(l.getStyle(m,"float",1))||/^(left|right)$/i.test(l.getAttrib(m,"align")))){i=l.create("a",{href:j},m.cloneNode());m.parentNode.replaceChild(i,m);f.selection.select(i)}else{f.getDoc().execCommand("CreateLink",false,j)}});f.onKeyUp.add(function(j,o){var l,i,m,p,k;if(o.keyCode==46||o.keyCode==8){i=j.getBody();l=i.innerHTML;k=j.selection;if(i.childNodes.length==1&&!/<(img|hr)/.test(l)&&tinymce.trim(l.replace(/<[^>]+>/g,"")).length==0){j.setContent('


    ',{format:"raw"});p=i.firstChild;m=k.getRng();m.setStart(p,0);m.setEnd(p,0);k.setRng(m)}}});f.addCommand("FormatBlock",function(j,i){var l=f.dom,k=l.getParent(f.selection.getNode(),l.isBlock);if(k){l.replace(l.create(i),k,1)}else{f.getDoc().execCommand("FormatBlock",false,i)}});f.addCommand("mceInsertContent",function(j,i){f.getDoc().execCommand("InsertText",false,"mce_marker");f.getBody().innerHTML=f.getBody().innerHTML.replace(/mce_marker/g,f.dom.processHTML(i)+'XX');f.selection.select(f.dom.get("_mce_tmp"));f.getDoc().execCommand("Delete",false," ")});f.onKeyPress.add(function(o,p){var q,v,r,l,j,k,i,u,m,t,s;if(p.keyCode==13){i=o.selection;q=i.getNode();if(p.shiftKey||o.settings.force_br_newlines&&q.nodeName!="LI"){g._insertBR(o);a.cancel(p)}if(v=h.getParent(q,"LI")){r=h.getParent(v,"OL,UL");u=o.getDoc();s=h.create("p");h.add(s,"br",{mce_bogus:"1"});if(e(u,v)){if(k=h.getParent(r.parentNode,"LI,OL,UL")){return}k=h.getParent(r,"p,h1,h2,h3,h4,h5,h6,div")||r;l=u.createRange();l.setStartBefore(k);l.setEndBefore(v);j=u.createRange();j.setStartAfter(v);j.setEndAfter(k);m=l.cloneContents();t=j.cloneContents();if(!e(u,t)){h.insertAfter(t,k)}h.insertAfter(s,k);if(!e(u,m)){h.insertAfter(m,k)}h.remove(k);k=s.firstChild;l=u.createRange();l.setStartBefore(k);l.setEndBefore(k);i.setRng(l);return a.cancel(p)}}}});f.onExecCommand.add(function(i,k){var j,m,n,l;if(k=="InsertUnorderedList"||k=="InsertOrderedList"){j=i.selection;m=i.dom;if(n=m.getParent(j.getNode(),function(o){return/^(H[1-6]|P|ADDRESS|PRE)$/.test(o.nodeName)})){l=j.getBookmark();m.remove(n,1);j.moveToBookmark(l)}}});f.onClick.add(function(i,j){j=j.target;if(j.nodeName=="IMG"){g.selElm=j;i.selection.select(j)}else{g.selElm=null}});f.onInit.add(function(){g._fixWebKitSpans()});f.onSetContent.add(function(){h=f.dom;d(["strong","b","em","u","strike","sub","sup","a"],function(i){d(c(h.select(i)).reverse(),function(l){var k=l.nodeName.toLowerCase(),j;if(k=="a"){if(l.name){h.replace(h.create("img",{mce_name:"a",name:l.name,"class":"mceItemAnchor"}),l)}return}switch(k){case"b":case"strong":if(k=="b"){k="strong"}j="font-weight: bold;";break;case"em":j="font-style: italic;";break;case"u":j="text-decoration: underline;";break;case"sub":j="vertical-align: sub;";break;case"sup":j="vertical-align: super;";break;case"strike":j="text-decoration: line-through;";break}h.replace(h.create("span",{mce_name:k,style:j,"class":"Apple-style-span"}),l,1)})})});f.onPreProcess.add(function(i,j){h=i.dom;d(c(j.node.getElementsByTagName("span")).reverse(),function(m){var k,l;if(j.get){if(h.hasClass(m,"Apple-style-span")){l=m.style.backgroundColor;switch(h.getAttrib(m,"mce_name")){case"font":if(!i.settings.convert_fonts_to_spans){h.setAttrib(m,"style","")}break;case"strong":case"em":case"sub":case"sup":h.setAttrib(m,"style","");break;case"strike":case"u":if(!i.settings.inline_styles){h.setAttrib(m,"style","")}else{h.setAttrib(m,"mce_name","")}break;default:if(!i.settings.inline_styles){h.setAttrib(m,"style","")}}if(l){m.style.backgroundColor=l}}}if(h.hasClass(m,"mceItemRemoved")){h.remove(m,1)}})});f.onPostProcess.add(function(i,j){j.content=j.content.replace(/
    <\/(h[1-6]|div|p|address|pre)>/g,"");j.content=j.content.replace(/ id=\"undefined\"/g,"")})},getInfo:function(){return{longname:"Safari compatibility",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/safari",version:tinymce.majorVersion+"."+tinymce.minorVersion}},_fixWebKitSpans:function(){var g=this,f=g.editor;a.add(f.getDoc(),"DOMNodeInserted",function(h){h=h.target;if(h&&h.nodeType==1){g._fixAppleSpan(h)}})},_fixAppleSpan:function(l){var g=this.editor,m=g.dom,i=this.webKitFontSizes,f=this.namedFontSizes,j=g.settings,h,k;if(m.getAttrib(l,"mce_fixed")){return}if(l.nodeName=="SPAN"&&l.className=="Apple-style-span"){h=l.style;if(!j.convert_fonts_to_spans){if(h.fontSize){m.setAttrib(l,"mce_name","font");m.setAttrib(l,"size",b(i,h.fontSize)+1)}if(h.fontFamily){m.setAttrib(l,"mce_name","font");m.setAttrib(l,"face",h.fontFamily)}if(h.color){m.setAttrib(l,"mce_name","font");m.setAttrib(l,"color",m.toHex(h.color))}if(h.backgroundColor){m.setAttrib(l,"mce_name","font");m.setStyle(l,"background-color",h.backgroundColor)}}else{if(h.fontSize){m.setStyle(l,"fontSize",f[b(i,h.fontSize)])}}if(h.fontWeight=="bold"){m.setAttrib(l,"mce_name","strong")}if(h.fontStyle=="italic"){m.setAttrib(l,"mce_name","em")}if(h.textDecoration=="underline"){m.setAttrib(l,"mce_name","u")}if(h.textDecoration=="line-through"){m.setAttrib(l,"mce_name","strike")}if(h.verticalAlign=="super"){m.setAttrib(l,"mce_name","sup")}if(h.verticalAlign=="sub"){m.setAttrib(l,"mce_name","sub")}m.setAttrib(l,"mce_fixed","1")}},_insertBR:function(f){var j=f.dom,h=f.selection,i=h.getRng(),g;i.insertNode(g=j.create("br"));i.setStartAfter(g);i.setEndAfter(g);h.setRng(i);if(h.getSel().focusNode==g.previousSibling){h.select(j.insertAfter(j.doc.createTextNode("\u00a0"),g));h.collapse(1)}f.getWin().scrollTo(0,j.getPos(h.getRng().startContainer).y)}});tinymce.PluginManager.add("safari",tinymce.plugins.Safari)})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/EnchantSpell.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/EnchantSpell.php new file mode 100644 index 0000000..59133c6 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/EnchantSpell.php @@ -0,0 +1,67 @@ += 1.4.1 + * @param Array $words Array of words to check. + * @return Array of misspelled words. + */ + function &checkWords($lang, $words) { + $r = enchant_broker_init(); + + if (enchant_broker_dict_exists($r,$lang)) { + $d = enchant_broker_request_dict($r, $lang); + + $returnData = array(); + foreach($words as $key => $value) { + $correct = enchant_dict_check($d, $value); + if(!$correct) { + $returnData[] = trim($value); + } + } + + return $returnData; + enchant_broker_free_dict($d); + } else { + + } + enchant_broker_free($r); + } + + /** + * Returns suggestions for a specific word. + * + * @param String $lang Selected language code (like en_US or de_DE). Shortcodes like "en" and "de" work with enchant >= 1.4.1 + * @param String $word Specific word to get suggestions for. + * @return Array of suggestions for the specified word. + */ + function &getSuggestions($lang, $word) { + $r = enchant_broker_init(); + $suggs = array(); + + if (enchant_broker_dict_exists($r,$lang)) { + $d = enchant_broker_request_dict($r, $lang); + $suggs = enchant_dict_suggest($d, $word); + + enchant_broker_free_dict($d); + } else { + + } + enchant_broker_free($r); + + return $suggs; + } +} + +?> \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/GoogleSpell.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/GoogleSpell.php new file mode 100644 index 0000000..446b96a --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/GoogleSpell.php @@ -0,0 +1,159 @@ +_getMatches($lang, $wordstr); + $words = array(); + + for ($i=0; $i_unhtmlentities(mb_substr($wordstr, $matches[$i][1], $matches[$i][2], "UTF-8")); + + return $words; + } + + /** + * Returns suggestions of for a specific word. + * + * @param {String} $lang Language code like sv or en. + * @param {String} $word Specific word to get suggestions for. + * @return {Array} Array of suggestions for the specified word. + */ + function &getSuggestions($lang, $word) { + $sug = array(); + $osug = array(); + $matches = $this->_getMatches($lang, $word); + + if (count($matches) > 0) + $sug = explode("\t", utf8_encode($this->_unhtmlentities($matches[0][4]))); + + // Remove empty + foreach ($sug as $item) { + if ($item) + $osug[] = $item; + } + + return $osug; + } + + function &_getMatches($lang, $str) { + $server = "www.google.com"; + $port = 443; + $path = "/tbproxy/spell?lang=" . $lang . "&hl=en"; + $host = "www.google.com"; + $url = "https://" . $server; + + // Setup XML request + $xml = '' . $str . ''; + + $header = "POST ".$path." HTTP/1.0 \r\n"; + $header .= "MIME-Version: 1.0 \r\n"; + $header .= "Content-type: application/PTI26 \r\n"; + $header .= "Content-length: ".strlen($xml)." \r\n"; + $header .= "Content-transfer-encoding: text \r\n"; + $header .= "Request-number: 1 \r\n"; + $header .= "Document-type: Request \r\n"; + $header .= "Interface-Version: Test 1.4 \r\n"; + $header .= "Connection: close \r\n\r\n"; + $header .= $xml; + + // Use curl if it exists + if (function_exists('curl_init')) { + // Use curl + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL,$url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); + $xml = curl_exec($ch); + curl_close($ch); + } else { + // Use raw sockets + $fp = fsockopen("ssl://" . $server, $port, $errno, $errstr, 30); + if ($fp) { + // Send request + fwrite($fp, $header); + + // Read response + $xml = ""; + while (!feof($fp)) + $xml .= fgets($fp, 128); + + fclose($fp); + } else + echo "Could not open SSL connection to google."; + } + + // Grab and parse content + $matches = array(); + preg_match_all('/([^<]*)<\/c>/', $xml, $matches, PREG_SET_ORDER); + + return $matches; + } + + function _unhtmlentities($string) { + $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string); + $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string); + + $trans_tbl = get_html_translation_table(HTML_ENTITIES); + $trans_tbl = array_flip($trans_tbl); + + return strtr($string, $trans_tbl); + } +} + +// Patch in multibyte support +if (!function_exists('mb_substr')) { + function mb_substr($str, $start, $len = '', $encoding="UTF-8"){ + $limit = strlen($str); + + for ($s = 0; $start > 0;--$start) {// found the real start + if ($s >= $limit) + break; + + if ($str[$s] <= "\x7F") + ++$s; + else { + ++$s; // skip length + + while ($str[$s] >= "\x80" && $str[$s] <= "\xBF") + ++$s; + } + } + + if ($len == '') + return substr($str, $s); + else + for ($e = $s; $len > 0; --$len) {//found the real end + if ($e >= $limit) + break; + + if ($str[$e] <= "\x7F") + ++$e; + else { + ++$e;//skip length + + while ($str[$e] >= "\x80" && $str[$e] <= "\xBF" && $e < $limit) + ++$e; + } + } + + return substr($str, $s, $e - $s); + } +} + +?> \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/PSpell.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/PSpell.php new file mode 100644 index 0000000..3c6424d --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/PSpell.php @@ -0,0 +1,82 @@ +_getPLink($lang); + + $outWords = array(); + foreach ($words as $word) { + if (!pspell_check($plink, trim($word))) + $outWords[] = utf8_encode($word); + } + + return $outWords; + } + + /** + * Returns suggestions of for a specific word. + * + * @param {String} $lang Language code like sv or en. + * @param {String} $word Specific word to get suggestions for. + * @return {Array} Array of suggestions for the specified word. + */ + function &getSuggestions($lang, $word) { + $words = pspell_suggest($this->_getPLink($lang), $word); + + for ($i=0; $ithrowError("PSpell support not found in PHP installation."); + + // Setup PSpell link + $plink = pspell_new( + $lang, + $this->_config['PSpell.spelling'], + $this->_config['PSpell.jargon'], + $this->_config['PSpell.encoding'], + $this->_config['PSpell.mode'] + ); + + // Setup PSpell link +/* if (!$plink) { + $pspellConfig = pspell_config_create( + $lang, + $this->_config['PSpell.spelling'], + $this->_config['PSpell.jargon'], + $this->_config['PSpell.encoding'] + ); + + $plink = pspell_new_config($pspell_config); + }*/ + + if (!$plink) + $this->throwError("No PSpell link found opened."); + + return $plink; + } +} + +?> diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/PSpellShell.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/PSpellShell.php new file mode 100644 index 0000000..7d3102c --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/PSpellShell.php @@ -0,0 +1,113 @@ +_getCMD($lang); + + if ($fh = fopen($this->_tmpfile, "w")) { + fwrite($fh, "!\n"); + + foreach($words as $key => $value) + fwrite($fh, "^" . $value . "\n"); + + fclose($fh); + } else + $this->throwError("PSpell support was not found."); + + $data = shell_exec($cmd); + @unlink($this->_tmpfile); + + $returnData = array(); + $dataArr = preg_split("/[\r\n]/", $data, -1, PREG_SPLIT_NO_EMPTY); + + foreach ($dataArr as $dstr) { + $matches = array(); + + // Skip this line. + if (strpos($dstr, "@") === 0) + continue; + + preg_match("/\& ([^ ]+) .*/i", $dstr, $matches); + + if (!empty($matches[1])) + $returnData[] = utf8_encode(trim($matches[1])); + } + + return $returnData; + } + + /** + * Returns suggestions of for a specific word. + * + * @param {String} $lang Language code like sv or en. + * @param {String} $word Specific word to get suggestions for. + * @return {Array} Array of suggestions for the specified word. + */ + function &getSuggestions($lang, $word) { + $cmd = $this->_getCMD($lang); + + if (function_exists("mb_convert_encoding")) + $word = mb_convert_encoding($word, "ISO-8859-1", mb_detect_encoding($word, "UTF-8")); + else + $word = utf8_encode($word); + + if ($fh = fopen($this->_tmpfile, "w")) { + fwrite($fh, "!\n"); + fwrite($fh, "^$word\n"); + fclose($fh); + } else + $this->throwError("Error opening tmp file."); + + $data = shell_exec($cmd); + @unlink($this->_tmpfile); + + $returnData = array(); + $dataArr = preg_split("/\n/", $data, -1, PREG_SPLIT_NO_EMPTY); + + foreach($dataArr as $dstr) { + $matches = array(); + + // Skip this line. + if (strpos($dstr, "@") === 0) + continue; + + preg_match("/\&[^:]+:(.*)/i", $dstr, $matches); + + if (!empty($matches[1])) { + $words = array_slice(explode(',', $matches[1]), 0, 10); + + for ($i=0; $i_tmpfile = tempnam($this->_config['PSpellShell.tmp'], "tinyspell"); + + if(preg_match("#win#i", php_uname())) + return $this->_config['PSpellShell.aspell'] . " -a --lang=". escapeshellarg($lang) . " --encoding=utf-8 -H < " . $this->_tmpfile . " 2>&1"; + + return "cat ". $this->_tmpfile ." | " . $this->_config['PSpellShell.aspell'] . " -a --encoding=utf-8 -H --lang=". escapeshellarg($lang); + } +} + +?> \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/SpellChecker.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/SpellChecker.php new file mode 100644 index 0000000..5d9205f --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/SpellChecker.php @@ -0,0 +1,62 @@ +_config = $config; + } + + /** + * Simple loopback function everything that gets in will be send back. + * + * @param $args.. Arguments. + * @return {Array} Array of all input arguments. + */ + function &loopback(/* args.. */) { + return func_get_args(); + } + + /** + * Spellchecks an array of words. + * + * @param {String} $lang Language code like sv or en. + * @param {Array} $words Array of words to spellcheck. + * @return {Array} Array of misspelled words. + */ + function &checkWords($lang, $words) { + return $words; + } + + /** + * Returns suggestions of for a specific word. + * + * @param {String} $lang Language code like sv or en. + * @param {String} $word Specific word to get suggestions for. + * @return {Array} Array of suggestions for the specified word. + */ + function &getSuggestions($lang, $word) { + return array(); + } + + /** + * Throws an error message back to the user. This will stop all execution. + * + * @param {String} $str Message to send back to user. + */ + function throwError($str) { + die('{"result":null,"id":null,"error":{"errstr":"' . addslashes($str) . '","errfile":"","errline":null,"errcontext":"","level":"FATAL"}}'); + } +} + +?> diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/utils/JSON.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/utils/JSON.php new file mode 100644 index 0000000..1c46116 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/utils/JSON.php @@ -0,0 +1,595 @@ +_data = $data; + $this->_len = strlen($data); + $this->_pos = -1; + $this->_location = JSON_IN_BETWEEN; + $this->_lastLocations = array(); + $this->_needProp = false; + } + + function getToken() { + return $this->_token; + } + + function getLocation() { + return $this->_location; + } + + function getTokenName() { + switch ($this->_token) { + case JSON_BOOL: + return 'JSON_BOOL'; + + case JSON_INT: + return 'JSON_INT'; + + case JSON_STR: + return 'JSON_STR'; + + case JSON_FLOAT: + return 'JSON_FLOAT'; + + case JSON_NULL: + return 'JSON_NULL'; + + case JSON_START_OBJ: + return 'JSON_START_OBJ'; + + case JSON_END_OBJ: + return 'JSON_END_OBJ'; + + case JSON_START_ARRAY: + return 'JSON_START_ARRAY'; + + case JSON_END_ARRAY: + return 'JSON_END_ARRAY'; + + case JSON_KEY: + return 'JSON_KEY'; + } + + return 'UNKNOWN'; + } + + function getValue() { + return $this->_value; + } + + function readToken() { + $chr = $this->read(); + + if ($chr != null) { + switch ($chr) { + case '[': + $this->_lastLocation[] = $this->_location; + $this->_location = JSON_IN_ARRAY; + $this->_token = JSON_START_ARRAY; + $this->_value = null; + $this->readAway(); + return true; + + case ']': + $this->_location = array_pop($this->_lastLocation); + $this->_token = JSON_END_ARRAY; + $this->_value = null; + $this->readAway(); + + if ($this->_location == JSON_IN_OBJECT) + $this->_needProp = true; + + return true; + + case '{': + $this->_lastLocation[] = $this->_location; + $this->_location = JSON_IN_OBJECT; + $this->_needProp = true; + $this->_token = JSON_START_OBJ; + $this->_value = null; + $this->readAway(); + return true; + + case '}': + $this->_location = array_pop($this->_lastLocation); + $this->_token = JSON_END_OBJ; + $this->_value = null; + $this->readAway(); + + if ($this->_location == JSON_IN_OBJECT) + $this->_needProp = true; + + return true; + + // String + case '"': + case '\'': + return $this->_readString($chr); + + // Null + case 'n': + return $this->_readNull(); + + // Bool + case 't': + case 'f': + return $this->_readBool($chr); + + default: + // Is number + if (is_numeric($chr) || $chr == '-' || $chr == '.') + return $this->_readNumber($chr); + + return true; + } + } + + return false; + } + + function _readBool($chr) { + $this->_token = JSON_BOOL; + $this->_value = $chr == 't'; + + if ($chr == 't') + $this->skip(3); // rue + else + $this->skip(4); // alse + + $this->readAway(); + + if ($this->_location == JSON_IN_OBJECT && !$this->_needProp) + $this->_needProp = true; + + return true; + } + + function _readNull() { + $this->_token = JSON_NULL; + $this->_value = null; + + $this->skip(3); // ull + $this->readAway(); + + if ($this->_location == JSON_IN_OBJECT && !$this->_needProp) + $this->_needProp = true; + + return true; + } + + function _readString($quote) { + $output = ""; + $this->_token = JSON_STR; + $endString = false; + + while (($chr = $this->peek()) != -1) { + switch ($chr) { + case '\\': + // Read away slash + $this->read(); + + // Read escape code + $chr = $this->read(); + switch ($chr) { + case 't': + $output .= "\t"; + break; + + case 'b': + $output .= "\b"; + break; + + case 'f': + $output .= "\f"; + break; + + case 'r': + $output .= "\r"; + break; + + case 'n': + $output .= "\n"; + break; + + case 'u': + $output .= $this->_int2utf8(hexdec($this->read(4))); + break; + + default: + $output .= $chr; + break; + } + + break; + + case '\'': + case '"': + if ($chr == $quote) + $endString = true; + + $chr = $this->read(); + if ($chr != -1 && $chr != $quote) + $output .= $chr; + + break; + + default: + $output .= $this->read(); + } + + // String terminated + if ($endString) + break; + } + + $this->readAway(); + $this->_value = $output; + + // Needed a property + if ($this->_needProp) { + $this->_token = JSON_KEY; + $this->_needProp = false; + return true; + } + + if ($this->_location == JSON_IN_OBJECT && !$this->_needProp) + $this->_needProp = true; + + return true; + } + + function _int2utf8($int) { + $int = intval($int); + + switch ($int) { + case 0: + return chr(0); + + case ($int & 0x7F): + return chr($int); + + case ($int & 0x7FF): + return chr(0xC0 | (($int >> 6) & 0x1F)) . chr(0x80 | ($int & 0x3F)); + + case ($int & 0xFFFF): + return chr(0xE0 | (($int >> 12) & 0x0F)) . chr(0x80 | (($int >> 6) & 0x3F)) . chr (0x80 | ($int & 0x3F)); + + case ($int & 0x1FFFFF): + return chr(0xF0 | ($int >> 18)) . chr(0x80 | (($int >> 12) & 0x3F)) . chr(0x80 | (($int >> 6) & 0x3F)) . chr(0x80 | ($int & 0x3F)); + } + } + + function _readNumber($start) { + $value = ""; + $isFloat = false; + + $this->_token = JSON_INT; + $value .= $start; + + while (($chr = $this->peek()) != -1) { + if (is_numeric($chr) || $chr == '-' || $chr == '.') { + if ($chr == '.') + $isFloat = true; + + $value .= $this->read(); + } else + break; + } + + $this->readAway(); + + if ($isFloat) { + $this->_token = JSON_FLOAT; + $this->_value = floatval($value); + } else + $this->_value = intval($value); + + if ($this->_location == JSON_IN_OBJECT && !$this->_needProp) + $this->_needProp = true; + + return true; + } + + function readAway() { + while (($chr = $this->peek()) != null) { + if ($chr != ':' && $chr != ',' && $chr != ' ') + return; + + $this->read(); + } + } + + function read($len = 1) { + if ($this->_pos < $this->_len) { + if ($len > 1) { + $str = substr($this->_data, $this->_pos + 1, $len); + $this->_pos += $len; + + return $str; + } else + return $this->_data[++$this->_pos]; + } + + return null; + } + + function skip($len) { + $this->_pos += $len; + } + + function peek() { + if ($this->_pos < $this->_len) + return $this->_data[$this->_pos + 1]; + + return null; + } +} + +/** + * This class handles JSON stuff. + * + * @package MCManager.utils + */ +class Moxiecode_JSON { + function Moxiecode_JSON() { + } + + function decode($input) { + $reader = new Moxiecode_JSONReader($input); + + return $this->readValue($reader); + } + + function readValue(&$reader) { + $this->data = array(); + $this->parents = array(); + $this->cur =& $this->data; + $key = null; + $loc = JSON_IN_ARRAY; + + while ($reader->readToken()) { + switch ($reader->getToken()) { + case JSON_STR: + case JSON_INT: + case JSON_BOOL: + case JSON_FLOAT: + case JSON_NULL: + switch ($reader->getLocation()) { + case JSON_IN_OBJECT: + $this->cur[$key] = $reader->getValue(); + break; + + case JSON_IN_ARRAY: + $this->cur[] = $reader->getValue(); + break; + + default: + return $reader->getValue(); + } + break; + + case JSON_KEY: + $key = $reader->getValue(); + break; + + case JSON_START_OBJ: + case JSON_START_ARRAY: + if ($loc == JSON_IN_OBJECT) + $this->addArray($key); + else + $this->addArray(null); + + $cur =& $obj; + + $loc = $reader->getLocation(); + break; + + case JSON_END_OBJ: + case JSON_END_ARRAY: + $loc = $reader->getLocation(); + + if (count($this->parents) > 0) { + $this->cur =& $this->parents[count($this->parents) - 1]; + array_pop($this->parents); + } + break; + } + } + + return $this->data[0]; + } + + // This method was needed since PHP is crapy and doesn't have pointers/references + function addArray($key) { + $this->parents[] =& $this->cur; + $ar = array(); + + if ($key) + $this->cur[$key] =& $ar; + else + $this->cur[] =& $ar; + + $this->cur =& $ar; + } + + function getDelim($index, &$reader) { + switch ($reader->getLocation()) { + case JSON_IN_ARRAY: + case JSON_IN_OBJECT: + if ($index > 0) + return ","; + break; + } + + return ""; + } + + function encode($input) { + switch (gettype($input)) { + case 'boolean': + return $input ? 'true' : 'false'; + + case 'integer': + return (int) $input; + + case 'float': + case 'double': + return (float) $input; + + case 'NULL': + return 'null'; + + case 'string': + return $this->encodeString($input); + + case 'array': + return $this->_encodeArray($input); + + case 'object': + return $this->_encodeArray(get_object_vars($input)); + } + + return ''; + } + + function encodeString($input) { + // Needs to be escaped + if (preg_match('/[^a-zA-Z0-9]/', $input)) { + $output = ''; + + for ($i=0; $i_utf82utf16($char))); + } if (($byte & 0xF0) == 0xE0) { + $char = pack('C*', $byte, ord($input[$i + 1]), ord($input[$i + 2])); + $i += 2; + $output .= sprintf('\u%04s', bin2hex($this->_utf82utf16($char))); + } if (($byte & 0xF8) == 0xF0) { + $char = pack('C*', $byte, ord($input[$i + 1]), ord($input[$i + 2], ord($input[$i + 3]))); + $i += 3; + $output .= sprintf('\u%04s', bin2hex($this->_utf82utf16($char))); + } if (($byte & 0xFC) == 0xF8) { + $char = pack('C*', $byte, ord($input[$i + 1]), ord($input[$i + 2], ord($input[$i + 3]), ord($input[$i + 4]))); + $i += 4; + $output .= sprintf('\u%04s', bin2hex($this->_utf82utf16($char))); + } if (($byte & 0xFE) == 0xFC) { + $char = pack('C*', $byte, ord($input[$i + 1]), ord($input[$i + 2], ord($input[$i + 3]), ord($input[$i + 4]), ord($input[$i + 5]))); + $i += 5; + $output .= sprintf('\u%04s', bin2hex($this->_utf82utf16($char))); + } else if ($byte < 128) + $output .= $input[$i]; + } + } + + return '"' . $output . '"'; + } + + return '"' . $input . '"'; + } + + function _utf82utf16($utf8) { + if (function_exists('mb_convert_encoding')) + return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); + + switch (strlen($utf8)) { + case 1: + return $utf8; + + case 2: + return chr(0x07 & (ord($utf8[0]) >> 2)) . chr((0xC0 & (ord($utf8[0]) << 6)) | (0x3F & ord($utf8[1]))); + + case 3: + return chr((0xF0 & (ord($utf8[0]) << 4)) | (0x0F & (ord($utf8[1]) >> 2))) . chr((0xC0 & (ord($utf8[1]) << 6)) | (0x7F & ord($utf8[2]))); + } + + return ''; + } + + function _encodeArray($input) { + $output = ''; + $isIndexed = true; + + $keys = array_keys($input); + for ($i=0; $iencodeString($keys[$i]) . ':' . $this->encode($input[$keys[$i]]); + $isIndexed = false; + } else + $output .= $this->encode($input[$keys[$i]]); + + if ($i != count($keys) - 1) + $output .= ','; + } + + return $isIndexed ? '[' . $output . ']' : '{' . $output . '}'; + } +} + +?> diff --git a/wp-includes/js/tinymce/plugins/spellchecker/classes/utils/Logger.php b/wp-includes/js/tinymce/plugins/spellchecker/classes/utils/Logger.php new file mode 100644 index 0000000..a1fb4cd --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/classes/utils/Logger.php @@ -0,0 +1,268 @@ +_path = ""; + $this->_filename = "{level}.log"; + $this->setMaxSize("100k"); + $this->_maxFiles = 10; + $this->_level = MC_LOGGER_DEBUG; + $this->_format = "[{time}] [{level}] {message}"; + } + + /** + * Sets the current log level, use the MC_LOGGER constants. + * + * @param int $level Log level instance for example MC_LOGGER_DEBUG. + */ + function setLevel($level) { + if (is_string($level)) { + switch (strtolower($level)) { + case "debug": + $level = MC_LOGGER_DEBUG; + break; + + case "info": + $level = MC_LOGGER_INFO; + break; + + case "warn": + case "warning": + $level = MC_LOGGER_WARN; + break; + + case "error": + $level = MC_LOGGER_ERROR; + break; + + case "fatal": + $level = MC_LOGGER_FATAL; + break; + + default: + $level = MC_LOGGER_FATAL; + } + } + + $this->_level = $level; + } + + /** + * Returns the current log level for example MC_LOGGER_DEBUG. + * + * @return int Current log level for example MC_LOGGER_DEBUG. + */ + function getLevel() { + return $this->_level; + } + + function setPath($path) { + $this->_path = $path; + } + + function getPath() { + return $this->_path; + } + + function setFileName($file_name) { + $this->_filename = $file_name; + } + + function getFileName() { + return $this->_filename; + } + + function setFormat($format) { + $this->_format = $format; + } + + function getFormat() { + return $this->_format; + } + + function setMaxSize($size) { + // Fix log max size + $logMaxSizeBytes = intval(preg_replace("/[^0-9]/", "", $size)); + + // Is KB + if (strpos((strtolower($size)), "k") > 0) + $logMaxSizeBytes *= 1024; + + // Is MB + if (strpos((strtolower($size)), "m") > 0) + $logMaxSizeBytes *= (1024 * 1024); + + $this->_maxSizeBytes = $logMaxSizeBytes; + $this->_maxSize = $size; + } + + function getMaxSize() { + return $this->_maxSize; + } + + function setMaxFiles($max_files) { + $this->_maxFiles = $max_files; + } + + function getMaxFiles() { + return $this->_maxFiles; + } + + function debug($msg) { + $args = func_get_args(); + $this->_logMsg(MC_LOGGER_DEBUG, implode(', ', $args)); + } + + function info($msg) { + $args = func_get_args(); + $this->_logMsg(MC_LOGGER_INFO, implode(', ', $args)); + } + + function warn($msg) { + $args = func_get_args(); + $this->_logMsg(MC_LOGGER_WARN, implode(', ', $args)); + } + + function error($msg) { + $args = func_get_args(); + $this->_logMsg(MC_LOGGER_ERROR, implode(', ', $args)); + } + + function fatal($msg) { + $args = func_get_args(); + $this->_logMsg(MC_LOGGER_FATAL, implode(', ', $args)); + } + + function isDebugEnabled() { + return $this->_level >= MC_LOGGER_DEBUG; + } + + function isInfoEnabled() { + return $this->_level >= MC_LOGGER_INFO; + } + + function isWarnEnabled() { + return $this->_level >= MC_LOGGER_WARN; + } + + function isErrorEnabled() { + return $this->_level >= MC_LOGGER_ERROR; + } + + function isFatalEnabled() { + return $this->_level >= MC_LOGGER_FATAL; + } + + function _logMsg($level, $message) { + $roll = false; + + if ($level < $this->_level) + return; + + $logFile = $this->toOSPath($this->_path . "/" . $this->_filename); + + switch ($level) { + case MC_LOGGER_DEBUG: + $levelName = "DEBUG"; + break; + + case MC_LOGGER_INFO: + $levelName = "INFO"; + break; + + case MC_LOGGER_WARN: + $levelName = "WARN"; + break; + + case MC_LOGGER_ERROR: + $levelName = "ERROR"; + break; + + case MC_LOGGER_FATAL: + $levelName = "FATAL"; + break; + } + + $logFile = str_replace('{level}', strtolower($levelName), $logFile); + + $text = $this->_format; + $text = str_replace('{time}', date("Y-m-d H:i:s"), $text); + $text = str_replace('{level}', strtolower($levelName), $text); + $text = str_replace('{message}', $message, $text); + $message = $text . "\r\n"; + + // Check filesize + if (file_exists($logFile)) { + $size = @filesize($logFile); + + if ($size + strlen($message) > $this->_maxSizeBytes) + $roll = true; + } + + // Roll if the size is right + if ($roll) { + for ($i=$this->_maxFiles-1; $i>=1; $i--) { + $rfile = $this->toOSPath($logFile . "." . $i); + $nfile = $this->toOSPath($logFile . "." . ($i+1)); + + if (@file_exists($rfile)) + @rename($rfile, $nfile); + } + + @rename($logFile, $this->toOSPath($logFile . ".1")); + + // Delete last logfile + $delfile = $this->toOSPath($logFile . "." . ($this->_maxFiles + 1)); + if (@file_exists($delfile)) + @unlink($delfile); + } + + // Append log line + if (($fp = @fopen($logFile, "a")) != null) { + @fputs($fp, $message); + @fflush($fp); + @fclose($fp); + } + } + + /** + * Converts a Unix path to OS specific path. + * + * @param String $path Unix path to convert. + */ + function toOSPath($path) { + return str_replace("/", DIRECTORY_SEPARATOR, $path); + } +} + +?> \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/config.php b/wp-includes/js/tinymce/plugins/spellchecker/config.php new file mode 100644 index 0000000..fb15b80 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/config.php @@ -0,0 +1,28 @@ + diff --git a/wp-includes/js/tinymce/plugins/spellchecker/css/content.css b/wp-includes/js/tinymce/plugins/spellchecker/css/content.css new file mode 100644 index 0000000..656ce1e --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/css/content.css @@ -0,0 +1 @@ +.mceItemHiddenSpellWord {background:url(../img/wline.gif) repeat-x bottom left; cursor:default;} diff --git a/wp-includes/js/tinymce/plugins/spellchecker/editor_plugin.js b/wp-includes/js/tinymce/plugins/spellchecker/editor_plugin.js new file mode 100644 index 0000000..054a2da --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/editor_plugin.js @@ -0,0 +1,338 @@ +/** + * $Id: editor_plugin_src.js 425 2007-11-21 15:17:39Z spocke $ + * + * @author Moxiecode + * @copyright Copyright © 2004-2008, Moxiecode Systems AB, All rights reserved. + */ + +(function() { + var JSONRequest = tinymce.util.JSONRequest, each = tinymce.each, DOM = tinymce.DOM; + + tinymce.create('tinymce.plugins.SpellcheckerPlugin', { + getInfo : function() { + return { + longname : 'Spellchecker', + author : 'Moxiecode Systems AB', + authorurl : 'http://tinymce.moxiecode.com', + infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker', + version : tinymce.majorVersion + "." + tinymce.minorVersion + }; + }, + + init : function(ed, url) { + var t = this, cm; + + t.url = url; + t.editor = ed; + + // Register commands + ed.addCommand('mceSpellCheck', function() { + if (!t.active) { + ed.setProgressState(1); + t._sendRPC('checkWords', [t.selectedLang, t._getWords()], function(r) { + if (r.length > 0) { + t.active = 1; + t._markWords(r); + ed.setProgressState(0); + ed.nodeChanged(); + } else { + ed.setProgressState(0); + ed.windowManager.alert('spellchecker.no_mpell'); + } + }); + } else + t._done(); + }); + + ed.onInit.add(function() { + if (ed.settings.content_css !== false) + ed.dom.loadCSS(url + '/css/content.css'); + }); + + ed.onClick.add(t._showMenu, t); + ed.onContextMenu.add(t._showMenu, t); + ed.onBeforeGetContent.add(function() { + if (t.active) + t._removeWords(); + }); + + ed.onNodeChange.add(function(ed, cm) { + cm.setActive('spellchecker', t.active); + }); + + ed.onSetContent.add(function() { + t._done(); + }); + + ed.onBeforeGetContent.add(function() { + t._done(); + }); + + ed.onBeforeExecCommand.add(function(ed, cmd) { + if (cmd == 'mceFullScreen') + t._done(); + }); + + // Find selected language + t.languages = {}; + each(ed.getParam('spellchecker_languages', '+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv', 'hash'), function(v, k) { + if (k.indexOf('+') === 0) { + k = k.substring(1); + t.selectedLang = v; + } + + t.languages[k] = v; + }); + }, + + createControl : function(n, cm) { + var t = this, c, ed = t.editor; + + if (n == 'spellchecker') { + c = cm.createSplitButton(n, {title : 'spellchecker.desc', cmd : 'mceSpellCheck', scope : t}); + + c.onRenderMenu.add(function(c, m) { + m.add({title : 'spellchecker.langs', 'class' : 'mceMenuItemTitle'}).setDisabled(1); + each(t.languages, function(v, k) { + var o = {icon : 1}, mi; + + o.onclick = function() { + mi.setSelected(1); + t.selectedItem.setSelected(0); + t.selectedItem = mi; + t.selectedLang = v; + }; + + o.title = k; + mi = m.add(o); + mi.setSelected(v == t.selectedLang); + + if (v == t.selectedLang) + t.selectedItem = mi; + }) + }); + + return c; + } + }, + + // Internal functions + + _walk : function(n, f) { + var d = this.editor.getDoc(), w; + + if (d.createTreeWalker) { + w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false); + + while ((n = w.nextNode()) != null) + f.call(this, n); + } else + tinymce.walk(n, f, 'childNodes'); + }, + + _getSeparators : function() { + var re = '', i, str = this.editor.getParam('spellchecker_word_separator_chars', '\\s!"#$%&()*+,-./:;<=>?@[\]^_{|}§©«®±¶·¸»¼½¾¿×÷¤\u201d\u201c'); + + // Build word separator regexp + for (i=0; i$1$2'); + v = v.replace(r3, '$1$2'); + + dom.replace(dom.create('span', {'class' : 'mceItemHidden'}, v), n); + } + } + }); + + se.moveToBookmark(b); + }, + + _showMenu : function(ed, e) { + var t = this, ed = t.editor, m = t._menu, p1, dom = ed.dom, vp = dom.getViewPort(ed.getWin()); + + if (!m) { + p1 = DOM.getPos(ed.getContentAreaContainer()); + //p2 = DOM.getPos(ed.getContainer()); + + m = ed.controlManager.createDropMenu('spellcheckermenu', { + offset_x : p1.x, + offset_y : p1.y, + 'class' : 'mceNoIcons' + }); + + t._menu = m; + } + + if (dom.hasClass(e.target, 'mceItemHiddenSpellWord')) { + m.removeAll(); + m.add({title : 'spellchecker.wait', 'class' : 'mceMenuItemTitle'}).setDisabled(1); + + t._sendRPC('getSuggestions', [t.selectedLang, dom.decode(e.target.innerHTML)], function(r) { + m.removeAll(); + + if (r.length > 0) { + m.add({title : 'spellchecker.sug', 'class' : 'mceMenuItemTitle'}).setDisabled(1); + each(r, function(v) { + m.add({title : v, onclick : function() { + dom.replace(ed.getDoc().createTextNode(v), e.target); + t._checkDone(); + }}); + }); + + m.addSeparator(); + } else + m.add({title : 'spellchecker.no_sug', 'class' : 'mceMenuItemTitle'}).setDisabled(1); + + m.add({ + title : 'spellchecker.ignore_word', + onclick : function() { + dom.remove(e.target, 1); + t._checkDone(); + } + }); + + m.add({ + title : 'spellchecker.ignore_words', + onclick : function() { + t._removeWords(dom.decode(e.target.innerHTML)); + t._checkDone(); + } + }); + + m.update(); + }); + + ed.selection.select(e.target); + p1 = dom.getPos(e.target); + m.showMenu(p1.x, p1.y + e.target.offsetHeight - vp.y); + + return tinymce.dom.Event.cancel(e); + } else + m.hideMenu(); + }, + + _checkDone : function() { + var t = this, ed = t.editor, dom = ed.dom, o; + + each(dom.select('span'), function(n) { + if (n && dom.hasClass(n, 'mceItemHiddenSpellWord')) { + o = true; + return false; + } + }); + + if (!o) + t._done(); + }, + + _done : function() { + var t = this, la = t.active; + + if (t.active) { + t.active = 0; + t._removeWords(); + + if (t._menu) + t._menu.hideMenu(); + + if (la) + t.editor.nodeChanged(); + } + }, + + _sendRPC : function(m, p, cb) { + var t = this, url = t.editor.getParam("spellchecker_rpc_url", this.url+'/rpc.php'); + + if (url == '{backend}') { + t.editor.setProgressState(0); + alert('Please specify: spellchecker_rpc_url'); + return; + } + + JSONRequest.sendRPC({ + url : url, + method : m, + params : p, + success : cb, + error : function(e, x) { + t.editor.setProgressState(0); + t.editor.windowManager.alert(e.errstr || ('Error response: ' + x.responseText)); + } + }); + } + }); + + // Register plugin + tinymce.PluginManager.add('spellchecker', tinymce.plugins.SpellcheckerPlugin); +})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/img/wline.gif b/wp-includes/js/tinymce/plugins/spellchecker/img/wline.gif new file mode 100644 index 0000000..7d0a4db Binary files /dev/null and b/wp-includes/js/tinymce/plugins/spellchecker/img/wline.gif differ diff --git a/wp-includes/js/tinymce/plugins/spellchecker/includes/general.php b/wp-includes/js/tinymce/plugins/spellchecker/includes/general.php new file mode 100644 index 0000000..9a12145 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/includes/general.php @@ -0,0 +1,98 @@ + $value) + $newarray[formatParam($name, $sanitize)] = formatParam($value, $sanitize); + + return $newarray; + } + + return formatParam($_REQUEST[$name], $sanitize); +} + +function &getLogger() { + global $mcLogger, $man; + + if (isset($man)) + $mcLogger = $man->getLogger(); + + if (!$mcLogger) { + $mcLogger = new Moxiecode_Logger(); + + // Set logger options + $mcLogger->setPath(dirname(__FILE__) . "/../logs"); + $mcLogger->setMaxSize("100kb"); + $mcLogger->setMaxFiles("10"); + $mcLogger->setFormat("{time} - {message}"); + } + + return $mcLogger; +} + +function debug($msg) { + $args = func_get_args(); + + $log = getLogger(); + $log->debug(implode(', ', $args)); +} + +function info($msg) { + $args = func_get_args(); + + $log = getLogger(); + $log->info(implode(', ', $args)); +} + +function error($msg) { + $args = func_get_args(); + + $log = getLogger(); + $log->error(implode(', ', $args)); +} + +function warn($msg) { + $args = func_get_args(); + + $log = getLogger(); + $log->warn(implode(', ', $args)); +} + +function fatal($msg) { + $args = func_get_args(); + + $log = getLogger(); + $log->fatal(implode(', ', $args)); +} + +?> \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/spellchecker/rpc.php b/wp-includes/js/tinymce/plugins/spellchecker/rpc.php new file mode 100644 index 0000000..d996c5d --- /dev/null +++ b/wp-includes/js/tinymce/plugins/spellchecker/rpc.php @@ -0,0 +1,112 @@ +decode($raw); + +// Execute RPC +if (isset($config['general.engine'])) { + $spellchecker = new $config['general.engine']($config); + $result = call_user_func_array(array($spellchecker, $input['method']), $input['params']); +} else + die('{"result":null,"id":null,"error":{"errstr":"You must choose an spellchecker engine in the config.php file.","errfile":"","errline":null,"errcontext":"","level":"FATAL"}}'); + +// Request and response id should always be the same +$output = array( + "id" => $input->id, + "result" => $result, + "error" => null +); + +// Return JSON encoded string +echo $json->encode($output); + +?> \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/tabfocus/editor_plugin.js b/wp-includes/js/tinymce/plugins/tabfocus/editor_plugin.js new file mode 100644 index 0000000..7f1fe26 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/tabfocus/editor_plugin.js @@ -0,0 +1 @@ +(function(){var c=tinymce.DOM,a=tinymce.dom.Event,d=tinymce.each,b=tinymce.explode;tinymce.create("tinymce.plugins.TabFocusPlugin",{init:function(f,g){function e(i,j){if(j.keyCode===9){return a.cancel(j)}}function h(l,p){var j,m,o,n,k;function q(i){o=c.getParent(l.id,"form");n=o.elements;if(o){d(n,function(s,r){if(s.id==l.id){j=r;return false}});if(i>0){for(m=j+1;m=0;m--){if(n[m].type!="hidden"){return n[m]}}}}return null}if(p.keyCode===9){k=b(l.getParam("tab_focus",l.getParam("tabfocus_elements",":prev,:next")));if(k.length==1){k[1]=k[0];k[0]=":prev"}if(p.shiftKey){if(k[0]==":prev"){n=q(-1)}else{n=c.get(k[0])}}else{if(k[1]==":next"){n=q(1)}else{n=c.get(k[1])}}if(n){if(l=tinymce.EditorManager.get(n.id||n.name)){l.focus()}else{window.setTimeout(function(){window.focus();n.focus()},10)}return a.cancel(p)}}}f.onKeyUp.add(e);if(tinymce.isGecko){f.onKeyPress.add(h);f.onKeyDown.add(e)}else{f.onKeyDown.add(h)}f.onInit.add(function(){d(c.select("a:first,a:last",f.getContainer()),function(i){a.add(i,"focus",function(){f.focus()})})})},getInfo:function(){return{longname:"Tabfocus",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",infourl:"http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus",version:tinymce.majorVersion+"."+tinymce.minorVersion}}});tinymce.PluginManager.add("tabfocus",tinymce.plugins.TabFocusPlugin)})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/wordpress/css/content.css b/wp-includes/js/tinymce/plugins/wordpress/css/content.css new file mode 100644 index 0000000..a542e6e --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wordpress/css/content.css @@ -0,0 +1,15 @@ + +.mceWPnextpage, .mceWPmore { + border: 0px; + border-top: 1px dotted #cccccc; + display: block; + width: 100%; + height: 12px; + margin-top: 15px; +} +.mceWPmore { + background: #ffffff url(../img/more_bug.gif) no-repeat right top; +} +.mceWPnextpage { + background: #ffffff url(../img/page_bug.gif) no-repeat right top; +} \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.dev.js b/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.dev.js new file mode 100644 index 0000000..0962cff --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.dev.js @@ -0,0 +1,297 @@ +/** + * WordPress plugin. + */ + +(function() { + var DOM = tinymce.DOM; + + tinymce.create('tinymce.plugins.WordPress', { + init : function(ed, url) { + var t = this, tbId = ed.getParam('wordpress_adv_toolbar', 'toolbar2'), last = 0, moreHTML, nextpageHTML; + moreHTML = ''; + nextpageHTML = ''; + + if ( getUserSetting('hidetb', '0') == '1' ) + ed.settings.wordpress_adv_hidden = 0; + + // Hides the specified toolbar and resizes the iframe + ed.onPostRender.add(function() { + if ( ed.getParam('wordpress_adv_hidden', 1) ) { + DOM.hide(ed.controlManager.get(tbId).id); + t._resizeIframe(ed, tbId, 28); + } + }); + + // Register commands + ed.addCommand('WP_More', function() { + ed.execCommand('mceInsertContent', 0, moreHTML); + }); + + ed.addCommand('WP_Page', function() { + ed.execCommand('mceInsertContent', 0, nextpageHTML); + }); + + ed.addCommand('WP_Help', function() { + ed.windowManager.open({ + url : tinymce.baseURL + '/wp-mce-help.php', + width : 450, + height : 420, + inline : 1 + }); + }); + + ed.addCommand('WP_Adv', function() { + var id = ed.controlManager.get(tbId).id, cm = ed.controlManager; + + if (DOM.isHidden(id)) { + cm.setActive('wp_adv', 1); + DOM.show(id); + t._resizeIframe(ed, tbId, -28); + ed.settings.wordpress_adv_hidden = 0; + setUserSetting('hidetb', '1'); + } else { + cm.setActive('wp_adv', 0); + DOM.hide(id); + t._resizeIframe(ed, tbId, 28); + ed.settings.wordpress_adv_hidden = 1; + setUserSetting('hidetb', '0'); + } + }); + + // Register buttons + ed.addButton('wp_more', { + title : 'wordpress.wp_more_desc', + image : url + '/img/more.gif', + cmd : 'WP_More' + }); + + ed.addButton('wp_page', { + title : 'wordpress.wp_page_desc', + image : url + '/img/page.gif', + cmd : 'WP_Page' + }); + + ed.addButton('wp_help', { + title : 'wordpress.wp_help_desc', + image : url + '/img/help.gif', + cmd : 'WP_Help' + }); + + ed.addButton('wp_adv', { + title : 'wordpress.wp_adv_desc', + image : url + '/img/toolbars.gif', + cmd : 'WP_Adv' + }); + + // Add Media buttons + ed.addButton('add_media', { + title : 'wordpress.add_media', + image : url + '/img/media.gif', + onclick : function() { + tb_show('', tinymce.DOM.get('add_media').href); + tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); + } + }); + + ed.addButton('add_image', { + title : 'wordpress.add_image', + image : url + '/img/image.gif', + onclick : function() { + tb_show('', tinymce.DOM.get('add_image').href); + tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); + } + }); + + ed.addButton('add_video', { + title : 'wordpress.add_video', + image : url + '/img/video.gif', + onclick : function() { + tb_show('', tinymce.DOM.get('add_video').href); + tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); + } + }); + + ed.addButton('add_audio', { + title : 'wordpress.add_audio', + image : url + '/img/audio.gif', + onclick : function() { + tb_show('', tinymce.DOM.get('add_audio').href); + tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); + } + }); + + // Add Media buttons to fullscreen + ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { + if ( 'mceFullScreen' != cmd ) return; + if ( 'mce_fullscreen' != ed.id ) + ed.settings.theme_advanced_buttons1 += ',|,add_image,add_video,add_audio,add_media'; + }); + + // Add class "alignleft", "alignright" and "aligncenter" when selecting align for images. + ed.addCommand('JustifyLeft', function() { + var n = ed.selection.getNode(); + + if ( n.nodeName != 'IMG' ) + ed.editorCommands.mceJustify('JustifyLeft', 'left'); + else ed.plugins.wordpress.do_align(n, 'alignleft'); + }); + + ed.addCommand('JustifyRight', function() { + var n = ed.selection.getNode(); + + if ( n.nodeName != 'IMG' ) + ed.editorCommands.mceJustify('JustifyRight', 'right'); + else ed.plugins.wordpress.do_align(n, 'alignright'); + }); + + ed.addCommand('JustifyCenter', function() { + var n = ed.selection.getNode(), P = ed.dom.getParent(n, 'p'), DL = ed.dom.getParent(n, 'dl'); + + if ( n.nodeName == 'IMG' && ( P || DL ) ) + ed.plugins.wordpress.do_align(n, 'aligncenter'); + else ed.editorCommands.mceJustify('JustifyCenter', 'center'); + }); + + // Word count if script is loaded + if ( 'undefined' != typeof wpWordCount ) { + ed.onKeyUp.add(function(ed, e) { + if ( e.keyCode == last ) return; + if ( 13 == e.keyCode || 8 == last || 46 == last ) wpWordCount.wc( ed.getContent({format : 'raw'}) ); + last = e.keyCode; + }); + }; + + // Add listeners to handle more break + t._handleMoreBreak(ed, url); + + // Add custom shortcuts + ed.addShortcut('alt+shift+c', ed.getLang('justifycenter_desc'), 'JustifyCenter'); + ed.addShortcut('alt+shift+r', ed.getLang('justifyright_desc'), 'JustifyRight'); + ed.addShortcut('alt+shift+l', ed.getLang('justifyleft_desc'), 'JustifyLeft'); + ed.addShortcut('alt+shift+j', ed.getLang('justifyfull_desc'), 'JustifyFull'); + ed.addShortcut('alt+shift+q', ed.getLang('blockquote_desc'), 'mceBlockQuote'); + ed.addShortcut('alt+shift+u', ed.getLang('bullist_desc'), 'InsertUnorderedList'); + ed.addShortcut('alt+shift+o', ed.getLang('numlist_desc'), 'InsertOrderedList'); + ed.addShortcut('alt+shift+d', ed.getLang('striketrough_desc'), 'Strikethrough'); + ed.addShortcut('alt+shift+n', ed.getLang('spellchecker.desc'), 'mceSpellCheck'); + ed.addShortcut('alt+shift+a', ed.getLang('link_desc'), 'mceLink'); + ed.addShortcut('alt+shift+s', ed.getLang('unlink_desc'), 'unlink'); + ed.addShortcut('alt+shift+m', ed.getLang('image_desc'), 'mceImage'); + ed.addShortcut('alt+shift+g', ed.getLang('fullscreen.desc'), 'mceFullScreen'); + ed.addShortcut('alt+shift+z', ed.getLang('wp_adv_desc'), 'WP_Adv'); + ed.addShortcut('alt+shift+h', ed.getLang('help_desc'), 'WP_Help'); + ed.addShortcut('alt+shift+t', ed.getLang('wp_more_desc'), 'WP_More'); + ed.addShortcut('alt+shift+p', ed.getLang('wp_page_desc'), 'WP_Page'); + ed.addShortcut('ctrl+s', ed.getLang('save_desc'), function(){if('function'==typeof autosave)autosave();}); + + if ( tinymce.isWebKit ) { + ed.addShortcut('alt+shift+b', ed.getLang('bold_desc'), 'Bold'); + ed.addShortcut('alt+shift+i', ed.getLang('italic_desc'), 'Italic'); + } + }, + + getInfo : function() { + return { + longname : 'WordPress Plugin', + author : 'WordPress', // add Moxiecode? + authorurl : 'http://wordpress.org', + infourl : 'http://wordpress.org', + version : '3.0' + }; + }, + + // Internal functions + do_align : function(n, a) { + var P, DL, DIV, cls, c, ed = tinyMCE.activeEditor; + + if ( /^(mceItemFlash|mceItemShockWave|mceItemWindowsMedia|mceItemQuickTime|mceItemRealMedia)$/.test(n.className) ) + return; + + P = ed.dom.getParent(n, 'p'); + DL = ed.dom.getParent(n, 'dl'); + DIV = ed.dom.getParent(n, 'div'); + + if ( DL && DIV ) { + cls = ed.dom.hasClass(DL, a) ? 'alignnone' : a; + DL.className = DL.className.replace(/align[^ '"]+\s?/g, ''); + ed.dom.addClass(DL, cls); + c = (cls == 'aligncenter') ? ed.dom.addClass(DIV, 'mceIEcenter') : ed.dom.removeClass(DIV, 'mceIEcenter'); + } else if ( P ) { + cls = ed.dom.hasClass(n, a) ? 'alignnone' : a; + n.className = n.className.replace(/align[^ '"]+\s?/g, ''); + ed.dom.addClass(n, cls); + if ( cls == 'aligncenter' ) + ed.dom.setStyle(P, 'textAlign', 'center'); + else if (P.style && P.style.textAlign == 'center') + ed.dom.setStyle(P, 'textAlign', ''); + } + + ed.execCommand('mceRepaint'); + }, + + // Resizes the iframe by a relative height value + _resizeIframe : function(ed, tb_id, dy) { + var ifr = ed.getContentAreaContainer().firstChild; + + DOM.setStyle(ifr, 'height', ifr.clientHeight + dy); // Resize iframe + ed.theme.deltaHeight += dy; // For resize cookie + }, + + _handleMoreBreak : function(ed, url) { + var moreHTML, nextpageHTML; + + moreHTML = '$1'; + nextpageHTML = ''; + + // Load plugin specific CSS into editor + ed.onInit.add(function() { + ed.dom.loadCSS(url + '/css/content.css'); + }); + + // Display morebreak instead if img in element path + ed.onPostRender.add(function() { + if (ed.theme.onResolveName) { + ed.theme.onResolveName.add(function(th, o) { + if (o.node.nodeName == 'IMG') { + if ( ed.dom.hasClass(o.node, 'mceWPmore') ) + o.name = 'wpmore'; + if ( ed.dom.hasClass(o.node, 'mceWPnextpage') ) + o.name = 'wppage'; + } + + }); + } + }); + + // Replace morebreak with images + ed.onBeforeSetContent.add(function(ed, o) { + o.content = o.content.replace(//g, moreHTML); + o.content = o.content.replace(//g, nextpageHTML); + }); + + // Replace images with morebreak + ed.onPostProcess.add(function(ed, o) { + if (o.get) + o.content = o.content.replace(/]+>/g, function(im) { + if (im.indexOf('class="mceWPmore') !== -1) { + var m, moretext = (m = im.match(/alt="(.*?)"/)) ? m[1] : ''; + im = ''; + } + if (im.indexOf('class="mceWPnextpage') !== -1) + im = ''; + + return im; + }); + }); + + // Set active buttons if user selected pagebreak or more break + ed.onNodeChange.add(function(ed, cm, n) { + cm.setActive('wp_page', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPnextpage')); + cm.setActive('wp_more', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPmore')); + }); + } + }); + + // Register plugin + tinymce.PluginManager.add('wordpress', tinymce.plugins.WordPress); +})(); diff --git a/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.js b/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.js new file mode 100644 index 0000000..28f6c62 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.js @@ -0,0 +1 @@ +(function(){var a=tinymce.DOM;tinymce.create("tinymce.plugins.WordPress",{init:function(c,d){var e=this,h=c.getParam("wordpress_adv_toolbar","toolbar2"),g=0,f,b;f='';b='';if(getUserSetting("hidetb","0")=="1"){c.settings.wordpress_adv_hidden=0}c.onPostRender.add(function(){if(c.getParam("wordpress_adv_hidden",1)){a.hide(c.controlManager.get(h).id);e._resizeIframe(c,h,28)}});c.addCommand("WP_More",function(){c.execCommand("mceInsertContent",0,f)});c.addCommand("WP_Page",function(){c.execCommand("mceInsertContent",0,b)});c.addCommand("WP_Help",function(){c.windowManager.open({url:tinymce.baseURL+"/wp-mce-help.php",width:450,height:420,inline:1})});c.addCommand("WP_Adv",function(){var j=c.controlManager.get(h).id,i=c.controlManager;if(a.isHidden(j)){i.setActive("wp_adv",1);a.show(j);e._resizeIframe(c,h,-28);c.settings.wordpress_adv_hidden=0;setUserSetting("hidetb","1")}else{i.setActive("wp_adv",0);a.hide(j);e._resizeIframe(c,h,28);c.settings.wordpress_adv_hidden=1;setUserSetting("hidetb","0")}});c.addButton("wp_more",{title:"wordpress.wp_more_desc",image:d+"/img/more.gif",cmd:"WP_More"});c.addButton("wp_page",{title:"wordpress.wp_page_desc",image:d+"/img/page.gif",cmd:"WP_Page"});c.addButton("wp_help",{title:"wordpress.wp_help_desc",image:d+"/img/help.gif",cmd:"WP_Help"});c.addButton("wp_adv",{title:"wordpress.wp_adv_desc",image:d+"/img/toolbars.gif",cmd:"WP_Adv"});c.addButton("add_media",{title:"wordpress.add_media",image:d+"/img/media.gif",onclick:function(){tb_show("",tinymce.DOM.get("add_media").href);tinymce.DOM.setStyle(["TB_overlay","TB_window","TB_load"],"z-index","999999")}});c.addButton("add_image",{title:"wordpress.add_image",image:d+"/img/image.gif",onclick:function(){tb_show("",tinymce.DOM.get("add_image").href);tinymce.DOM.setStyle(["TB_overlay","TB_window","TB_load"],"z-index","999999")}});c.addButton("add_video",{title:"wordpress.add_video",image:d+"/img/video.gif",onclick:function(){tb_show("",tinymce.DOM.get("add_video").href);tinymce.DOM.setStyle(["TB_overlay","TB_window","TB_load"],"z-index","999999")}});c.addButton("add_audio",{title:"wordpress.add_audio",image:d+"/img/audio.gif",onclick:function(){tb_show("",tinymce.DOM.get("add_audio").href);tinymce.DOM.setStyle(["TB_overlay","TB_window","TB_load"],"z-index","999999")}});c.onBeforeExecCommand.add(function(i,k,j,l){if("mceFullScreen"!=k){return}if("mce_fullscreen"!=i.id){i.settings.theme_advanced_buttons1+=",|,add_image,add_video,add_audio,add_media"}});c.addCommand("JustifyLeft",function(){var i=c.selection.getNode();if(i.nodeName!="IMG"){c.editorCommands.mceJustify("JustifyLeft","left")}else{c.plugins.wordpress.do_align(i,"alignleft")}});c.addCommand("JustifyRight",function(){var i=c.selection.getNode();if(i.nodeName!="IMG"){c.editorCommands.mceJustify("JustifyRight","right")}else{c.plugins.wordpress.do_align(i,"alignright")}});c.addCommand("JustifyCenter",function(){var k=c.selection.getNode(),j=c.dom.getParent(k,"p"),i=c.dom.getParent(k,"dl");if(k.nodeName=="IMG"&&(j||i)){c.plugins.wordpress.do_align(k,"aligncenter")}else{c.editorCommands.mceJustify("JustifyCenter","center")}});if("undefined"!=typeof wpWordCount){c.onKeyUp.add(function(i,j){if(j.keyCode==g){return}if(13==j.keyCode||8==g||46==g){wpWordCount.wc(i.getContent({format:"raw"}))}g=j.keyCode})}e._handleMoreBreak(c,d);c.addShortcut("alt+shift+c",c.getLang("justifycenter_desc"),"JustifyCenter");c.addShortcut("alt+shift+r",c.getLang("justifyright_desc"),"JustifyRight");c.addShortcut("alt+shift+l",c.getLang("justifyleft_desc"),"JustifyLeft");c.addShortcut("alt+shift+j",c.getLang("justifyfull_desc"),"JustifyFull");c.addShortcut("alt+shift+q",c.getLang("blockquote_desc"),"mceBlockQuote");c.addShortcut("alt+shift+u",c.getLang("bullist_desc"),"InsertUnorderedList");c.addShortcut("alt+shift+o",c.getLang("numlist_desc"),"InsertOrderedList");c.addShortcut("alt+shift+d",c.getLang("striketrough_desc"),"Strikethrough");c.addShortcut("alt+shift+n",c.getLang("spellchecker.desc"),"mceSpellCheck");c.addShortcut("alt+shift+a",c.getLang("link_desc"),"mceLink");c.addShortcut("alt+shift+s",c.getLang("unlink_desc"),"unlink");c.addShortcut("alt+shift+m",c.getLang("image_desc"),"mceImage");c.addShortcut("alt+shift+g",c.getLang("fullscreen.desc"),"mceFullScreen");c.addShortcut("alt+shift+z",c.getLang("wp_adv_desc"),"WP_Adv");c.addShortcut("alt+shift+h",c.getLang("help_desc"),"WP_Help");c.addShortcut("alt+shift+t",c.getLang("wp_more_desc"),"WP_More");c.addShortcut("alt+shift+p",c.getLang("wp_page_desc"),"WP_Page");c.addShortcut("ctrl+s",c.getLang("save_desc"),function(){if("function"==typeof autosave){autosave()}});if(tinymce.isWebKit){c.addShortcut("alt+shift+b",c.getLang("bold_desc"),"Bold");c.addShortcut("alt+shift+i",c.getLang("italic_desc"),"Italic")}},getInfo:function(){return{longname:"WordPress Plugin",author:"WordPress",authorurl:"http://wordpress.org",infourl:"http://wordpress.org",version:"3.0"}},do_align:function(j,d){var h,f,g,b,i,e=tinyMCE.activeEditor;if(/^(mceItemFlash|mceItemShockWave|mceItemWindowsMedia|mceItemQuickTime|mceItemRealMedia)$/.test(j.className)){return}h=e.dom.getParent(j,"p");f=e.dom.getParent(j,"dl");g=e.dom.getParent(j,"div");if(f&&g){b=e.dom.hasClass(f,d)?"alignnone":d;f.className=f.className.replace(/align[^ '"]+\s?/g,"");e.dom.addClass(f,b);i=(b=="aligncenter")?e.dom.addClass(g,"mceIEcenter"):e.dom.removeClass(g,"mceIEcenter")}else{if(h){b=e.dom.hasClass(j,d)?"alignnone":d;j.className=j.className.replace(/align[^ '"]+\s?/g,"");e.dom.addClass(j,b);if(b=="aligncenter"){e.dom.setStyle(h,"textAlign","center")}else{if(h.style&&h.style.textAlign=="center"){e.dom.setStyle(h,"textAlign","")}}}}e.execCommand("mceRepaint")},_resizeIframe:function(c,e,b){var d=c.getContentAreaContainer().firstChild;a.setStyle(d,"height",d.clientHeight+b);c.theme.deltaHeight+=b},_handleMoreBreak:function(c,d){var e,b;e='$1';b='';c.onInit.add(function(){c.dom.loadCSS(d+"/css/content.css")});c.onPostRender.add(function(){if(c.theme.onResolveName){c.theme.onResolveName.add(function(f,g){if(g.node.nodeName=="IMG"){if(c.dom.hasClass(g.node,"mceWPmore")){g.name="wpmore"}if(c.dom.hasClass(g.node,"mceWPnextpage")){g.name="wppage"}}})}});c.onBeforeSetContent.add(function(f,g){g.content=g.content.replace(//g,e);g.content=g.content.replace(//g,b)});c.onPostProcess.add(function(f,g){if(g.get){g.content=g.content.replace(/]+>/g,function(i){if(i.indexOf('class="mceWPmore')!==-1){var h,j=(h=i.match(/alt="(.*?)"/))?h[1]:"";i=""}if(i.indexOf('class="mceWPnextpage')!==-1){i=""}return i})}});c.onNodeChange.add(function(g,f,h){f.setActive("wp_page",h.nodeName==="IMG"&&g.dom.hasClass(h,"mceWPnextpage"));f.setActive("wp_more",h.nodeName==="IMG"&&g.dom.hasClass(h,"mceWPmore"))})}});tinymce.PluginManager.add("wordpress",tinymce.plugins.WordPress)})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/audio.gif b/wp-includes/js/tinymce/plugins/wordpress/img/audio.gif new file mode 100644 index 0000000..f8ad223 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/audio.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/help.gif b/wp-includes/js/tinymce/plugins/wordpress/img/help.gif new file mode 100644 index 0000000..51a1ee4 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/help.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/image.gif b/wp-includes/js/tinymce/plugins/wordpress/img/image.gif new file mode 100644 index 0000000..6736e6b Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/image.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/media.gif b/wp-includes/js/tinymce/plugins/wordpress/img/media.gif new file mode 100644 index 0000000..786e4f5 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/media.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/more.gif b/wp-includes/js/tinymce/plugins/wordpress/img/more.gif new file mode 100644 index 0000000..4ff564d Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/more.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/more_bug.gif b/wp-includes/js/tinymce/plugins/wordpress/img/more_bug.gif new file mode 100644 index 0000000..4589cb4 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/more_bug.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/page.gif b/wp-includes/js/tinymce/plugins/wordpress/img/page.gif new file mode 100644 index 0000000..1cea78a Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/page.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/page_bug.gif b/wp-includes/js/tinymce/plugins/wordpress/img/page_bug.gif new file mode 100644 index 0000000..9ea3565 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/page_bug.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/toolbars.gif b/wp-includes/js/tinymce/plugins/wordpress/img/toolbars.gif new file mode 100644 index 0000000..dcb7066 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/toolbars.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif b/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif new file mode 100644 index 0000000..3884865 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif differ diff --git a/wp-includes/js/tinymce/plugins/wordpress/img/video.gif b/wp-includes/js/tinymce/plugins/wordpress/img/video.gif new file mode 100644 index 0000000..b8e0975 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wordpress/img/video.gif differ diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/css/editimage-rtl.css b/wp-includes/js/tinymce/plugins/wpeditimage/css/editimage-rtl.css new file mode 100644 index 0000000..e78820f --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpeditimage/css/editimage-rtl.css @@ -0,0 +1,68 @@ + +body#media-upload ul#sidemenu { + left: auto; + right: 0; +} + +#basic .align .field label { + display: block; + float: right; + padding: 0 24px 0 0; + margin: 5px 3px 5px 5px; +} + +.align .field input { + display: block; + float: right; + margin: 5px 15px 5px 0; +} + +tr.image-size label { + margin: 0; +} + +tr.image-size input { + margin: 3px 15px 0 5px; +} + +.image-align-none-label, +.image-align-left-label, +.image-align-center-label, +.image-align-right-label { + background-position: center right; +} + +#media-upload .describe th.label { + text-align: right; +} + +.show-align, +.alignright, +#img_size { + float: left; +} + +tr.image-size label, +tr.image-size input, +#img_dim label, +#img_dim input, +#img_prop label, +#img_prop input, +#img_size_div, +.alignleft { + float: right; +} + +#img_dim label, +#img_prop label { + margin: 5px 0pt; +} + +#img_dim input, +#img_prop input { + margin: 0 5px 0 10px; +} + +#img_size_title { + text-align: left; +} diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/css/editimage.css b/wp-includes/js/tinymce/plugins/wpeditimage/css/editimage.css new file mode 100644 index 0000000..26974d3 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpeditimage/css/editimage.css @@ -0,0 +1,343 @@ + +html, body { + background-color: #fff; + margin: 0; + padding: 0; +} + +.submit input, +.button, +.button-primary, +.button-secondary, +.button-highlighted { + font-family: "Lucida Grande", "Lucida Sans Unicode", Tahoma, Verdana, sans-serif; + text-decoration: none; + font-size: 11px !important; + line-height: 16px; + padding: 2px 8px; + cursor: pointer; + border-width: 1px; + border-style: solid; + -moz-border-radius: 11px; + -khtml-border-radius: 11px; + -webkit-border-radius: 11px; + border-radius: 11px; + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + -khtml-box-sizing: content-box; + box-sizing: content-box; +} + +a.button { + padding: 4px 8px; +} + +textarea, +input, +select { + font: 13px Verdana, Arial, Helvetica, sans-serif; + margin: 1px; + padding: 3px; +} + +body, td { + font: 13px "Lucida Grande", "Lucida Sans Unicode", Tahoma, Verdana, sans-serif; +} + +abbr.required { + color: #FF0000; + text-align: left; +} + +img.alignright, +.alignright { + float: right; +} + +img.alignleft, +.alignleft { + float: left; +} + +img.aligncenter { + display: block; + margin-left: auto; + margin-right: auto; +} + +label { + cursor: pointer; +} + +th.label { + width: 107px; +} + +#media-upload #basic th.label { + padding: 5px 5px 5px 0; +} + +.show-align { + height: 200px; + width: 480px; + float: right; + background-color: #f1f1f1; + cursor: default; + -moz-user-select: none; + user-select: none; + overflow: hidden; +} + +#img-edit { + border: 1px solid #dfdfdf; + width: 623px; + margin: 15px auto; +} + +#media-upload .media-upload-form table.describe { + border-top-style: none; + border-top-width: 0; +} + +#img_demo_txt { + font-size: 9px; + line-height: 13px; + font-family: Monaco,"Courier New",Courier,monospace; + color: #888; +} + +#img_demo { + padding: 0; +} + +#saveeditimg { + padding: 10px 0 0 5px; + border-top: 1px solid #ccc; +} + +#sidemenu, +#sidemenu li { + list-style: none; +} + +#sidemenu li { + display: inline; +} + +#sidemenu a { + border-bottom-style: solid; + border-bottom-width: 1px; + border-top-style: solid; + border-top-width: 1px; + display: block; + float: left; + height: 28px; + line-height: 28px; + text-decoration: none; + text-align: center; + white-space: nowrap; + margin: 0; + padding: 0pt 7px; +} + +#sidemenu a.current { + -moz-border-radius-topleft: 4px; + -khtml-border-top-left-radius: 4px; + -webkit-border-top-left-radius: 4px; + border-top-left-radius: 4px; + -moz-border-radius-topright: 4px; + -khtml-border-top-right-radius: 4px; + -webkit-border-top-right-radius: 4px; + border-top-right-radius: 4px; + border-style:solid; + border-width:1px; + font-weight:normal; +} + +#adv_settings .field label { + padding: 0 5px 5px; +} + +#media-upload h3 { + clear: both; + padding: 0pt 0pt 3px; + border-bottom-style: solid; + border-bottom-width: 1px; + font-family: Georgia,"Times New Roman",Times,serif; + font-size: 20px; + font-weight: normal; + line-height: normal; + margin: 0 0 10px -4px; + padding: 15px 0 3px; + border-bottom-color: #DADADA; + color: #5A5A5A; +} + +#img_dim #width, +#img_dim #height, +#img_prop #border, +#img_prop #vspace, +#img_prop #hspace { + width: 36px; +} + +#img_dim abbr { + padding: 0 4px; +} + +#show_align_sp { + width: 115px; +} + +#img_dim input, +#img_prop input { + margin-right: 10px; +} + +#basic .align .field label { + padding: 0 0 0 24px; +} + +#basic { + padding-top: 2px; +} + +td { + padding: 2px 0; +} + +#img_size { + float: right; + text-align: center; + cursor: pointer; + background-color: #f1f1f1; + padding: 5px 0; + width: 45px; +} + +#img_size div { + font-size: 10px; + padding: 2px; + border: 1px solid #f1f1f1; + line-height: 15px; + height: 15px; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; + color: #07273E; +} + +#img_size div#s100 { + border-color: #A3A3A3; + background-color: #E5E5E5; +} + +#img_size_div { + width: 100px; + float: left; + cursor: default; +} + +#img_size_title { + margin: 0 7px 5px; + text-align: right; + font-weight: bold; +} + +#img_align_td { + padding: 2px 0 8px; +} + +#media-upload tr.align td.field { + text-align: center; +} + +.describe td { + vertical-align: middle; +} + +#media-upload .describe th.label { + padding-top: .5em; + text-align: left; +} + +#media-upload .describe { + border-top-width: 1px; + border-top-style: solid; + padding: 5px; + width: 100%; + clear: both; + cursor: default; +} + +form { + margin: 1em; +} + +.describe input[type="text"], +.describe textarea { + width: 460px; + border: 1px solid #dfdfdf; +} + + +.media-upload-form label, +.media-upload-form legend { + font-weight: bold; + font-size: 13px; + color: #464646; +} + +.align .field label { + display: inline; + padding: 0 0 0 28px; + margin: 0 1em 0 0; +} +.image-align-none-label { + background: url(../../../../../../wp-admin/images/align-none.png) no-repeat center left; +} + +.image-align-left-label { + background: url(../../../../../../wp-admin/images/align-left.png) no-repeat center left; +} + +.image-align-center-label { + background: url(../../../../../../wp-admin/images/align-center.png) no-repeat center left; +} + +.image-align-right-label { + background: url(../../../../../../wp-admin/images/align-right.png) no-repeat center left; +} + +div#media-upload-header { + margin: 0; + padding: 0 5px; + font-weight: bold; + position: relative; + border-bottom-width: 1px; + border-bottom-style: solid; + height: 2.5em; +} + +body#media-upload ul#sidemenu { + font-weight: normal; + margin: 0 5px; + position: relative; + left: 0px; + bottom: -4px; +} + +div#media-upload-error { + margin: 1em; + font-weight: bold; +} + +* html #sidemenu li { + zoom: 100%; +} + +* html #sidemenu a { + height: 27px; + line-height: 26px; +} diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/editimage.html b/wp-includes/js/tinymce/plugins/wpeditimage/editimage.html new file mode 100644 index 0000000..efba4a2 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpeditimage/editimage.html @@ -0,0 +1,275 @@ + + + + + + + + + + + + + + + + + + +
    +
    +
    +
    {#wpeditimage.size}
    +
    +
    {#wpeditimage.s130}
    +
    {#wpeditimage.s120}
    +
    {#wpeditimage.s110}
    +
    {#wpeditimage.s100}
    +
    {#wpeditimage.s90}
    +
    {#wpeditimage.s80}
    +
    {#wpeditimage.s70}
    +
    {#wpeditimage.s60}
    +
    +
    +
    + + + Lorem ipsum dolor sit amet consectetuer velit pretium euismod ipsum enim. Mi cursus at a mollis senectus id arcu gravida quis urna. Sed et felis id tempus Morbi mauris tincidunt enim In mauris. Pede eu risus velit libero natoque enim lorem adipiscing ipsum consequat. In malesuada et sociis tincidunt tempus pellentesque cursus convallis ipsum Suspendisse. Risus In ac quis ut Nunc convallis laoreet ante Suspendisse Nam. Amet amet urna condimentum Vestibulum sem at Curabitur lorem et cursus. Sodales tortor fermentum leo dui habitant Nunc Sed Vestibulum. + Ut lorem In penatibus libero id ipsum sagittis nec elit Sed. Condimentum eget Vivamus vel consectetuer lorem molestie turpis amet tellus id. Condimentum vel ridiculus Fusce sed pede Nam nunc sodales eros tempor. Sit lacus magna dictumst Curabitur fringilla auctor id vitae wisi facilisi. Fermentum eget turpis felis velit leo Nunc Proin orci molestie Praesent. Curabitur tellus scelerisque suscipit ut sem amet cursus mi Morbi eu. Donec libero Vestibulum augue et mollis accumsan ornare condimentum In enim. Leo eget ac consectetuer quis condimentum malesuada. + Condimentum commodo et Lorem fringilla malesuada libero volutpat sem tellus enim. Tincidunt sed at Aenean nec nonummy porttitor Nam Sed Nulla ut. Auctor leo In aliquet Curabitur eros et velit Quisque justo morbi. Et vel mauris sit nulla semper vitae et quis at dui. Id at elit laoreet justo eu mauris Quisque et interdum pharetra. Nullam accumsan interdum Maecenas condimentum quis quis Fusce a sollicitudin Sed. Non Quisque Vivamus congue porttitor non semper ipsum porttitor quis vel. Donec eros lacus volutpat et tincidunt sem convallis id venenatis sit. Consectetuer odio. + Semper faucibus Morbi nulla convallis orci Aliquam Sed porttitor et Pellentesque. Venenatis laoreet lorem id a a Morbi augue turpis id semper. Arcu volutpat ac mauris Vestibulum fringilla Aenean condimentum nibh sed id. Sagittis eu lacus orci urna tellus tellus pretium Curabitur dui nunc. Et nibh eu eu nibh adipiscing at lorem Vestibulum adipiscing augue. Magna convallis Phasellus dolor malesuada Curabitur ornare adipiscing tellus Aliquam tempus. Id Aliquam Integer augue Nulla consectetuer ac Donec Curabitur tincidunt et. Id vel Nunc amet lacus dui magna ridiculus penatibus laoreet Duis. Enim sagittis nibh quis Nulla nec laoreet vel Maecenas mattis vel. + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + +
    + + + +

    {#wpeditimage.link_help}

    +
    + + + +
    + + + + +
    +
    +
    + + + diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.dev.js b/wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.dev.js new file mode 100644 index 0000000..2e256a0 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.dev.js @@ -0,0 +1,243 @@ + +(function() { + tinymce.create('tinymce.plugins.wpEditImage', { + + init : function(ed, url) { + var t = this; + + t.url = url; + t._createButtons(); + + // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); + ed.addCommand('WP_EditImage', function() { + var el = ed.selection.getNode(), vp = tinymce.DOM.getViewPort(), H = vp.h, W = ( 720 < vp.w ) ? 720 : vp.w, cls = ed.dom.getAttrib(el, 'class'); + + if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' ) + return; + + tb_show('', url + '/editimage.html?ver=321&TB_iframe=true'); + tinymce.DOM.setStyles('TB_window', { + 'width':( W - 50 )+'px', + 'height':( H - 45 )+'px', + 'margin-left':'-'+parseInt((( W - 50 ) / 2),10) + 'px' + }); + + if ( ! tinymce.isIE6 ) { + tinymce.DOM.setStyles('TB_window', { + 'top':'20px', + 'marginTop':'0' + }); + } + + tinymce.DOM.setStyles('TB_iframeContent', { + 'width':( W - 50 )+'px', + 'height':( H - 75 )+'px' + }); + tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); + }); + + ed.onInit.add(function(ed) { + tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) { + ed.plugins.wpeditimage.hideButtons(); + }); + }); + + ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { + ed.plugins.wpeditimage.hideButtons(); + }); + + ed.onSaveContent.add(function(ed, o) { + ed.plugins.wpeditimage.hideButtons(); + }); + + ed.onMouseUp.add(function(ed, e) { + var n, DL; + + if ( tinymce.isOpera ) { + if ( e.target.nodeName == 'IMG' ) + ed.plugins.wpeditimage.showButtons(e.target); + } else if ( ! tinymce.isWebKit ) { + n = ed.selection.getNode(); + + if ( n.nodeName == 'IMG' && (DL = ed.dom.getParent(n, 'DL')) ) { + window.setTimeout(function(){ + var ed = tinyMCE.activeEditor, n = ed.selection.getNode(), DL = ed.dom.getParent(n, 'DL'); + + if ( n.width != (parseInt(ed.dom.getStyle(DL, 'width')) - 10) ) { + ed.dom.setStyle(DL, 'width', parseInt(n.width)+10); + ed.execCommand('mceRepaint'); + } + }, 100); + } + } + }); + + ed.onMouseDown.add(function(ed, e) { + if ( tinymce.isOpera || e.target.nodeName != 'IMG' ) { + t.hideButtons(); + return; + } + ed.plugins.wpeditimage.showButtons(e.target); + }); + + ed.onKeyPress.add(function(ed, e) { + var DL, DIV, P; + + if ( e.keyCode == 13 && (DL = ed.dom.getParent(ed.selection.getNode(), 'DL')) ) { + P = ed.dom.create('p', {}, ' '); + if ( (DIV = DL.parentNode) && DIV.nodeName == 'DIV' ) + ed.dom.insertAfter( P, DIV ); + else ed.dom.insertAfter( P, DL ); + + tinymce.dom.Event.cancel(e); + ed.selection.select(P); + return false; + } + }); + + ed.onBeforeSetContent.add(function(ed, o) { + o.content = t._do_shcode(o.content); + }); + + ed.onPostProcess.add(function(ed, o) { + if (o.get) + o.content = t._get_shcode(o.content); + }); + }, + + _do_shcode : function(co) { + return co.replace(/\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\][\s\u00a0]*/g, function(a,b,c){ + var id, cls, w, cap, div_cls; + + b = b.replace(/\\'|\\'|\\'/g, ''').replace(/\\"|\\"/g, '"'); + c = c.replace(/\\'|\\'/g, ''').replace(/\\"/g, '"'); + id = b.match(/id=['"]([^'"]+)/i); + cls = b.match(/align=['"]([^'"]+)/i); + w = b.match(/width=['"]([0-9]+)/); + cap = b.match(/caption=['"]([^'"]+)/i); + + id = ( id && id[1] ) ? id[1] : ''; + cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; + w = ( w && w[1] ) ? w[1] : ''; + cap = ( cap && cap[1] ) ? cap[1] : ''; + if ( ! w || ! cap ) return c; + + div_cls = (cls == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp'; + + return '
    '+c+'
    '+cap+'
    '; + }); + }, + + _get_shcode : function(co) { + return co.replace(/
    \s*]+)>\s*]+>([\s\S]+?)<\/dt>\s*]+>(.+?)<\/dd>\s*<\/dl>\s*<\/div>\s*/gi, function(a,b,c,cap){ + var id, cls, w; + + id = b.match(/id=['"]([^'"]+)/i); + cls = b.match(/class=['"]([^'"]+)/i); + w = c.match(/width=['"]([0-9]+)/); + + id = ( id && id[1] ) ? id[1] : ''; + cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; + w = ( w && w[1] ) ? w[1] : ''; + + if ( ! w || ! cap ) return c; + cls = cls.match(/align[^ '"]+/) || 'alignnone'; + cap = cap.replace(/<\S[^<>]*>/gi, '').replace(/'/g, ''').replace(/"/g, '"'); + + return '[caption id="'+id+'" align="'+cls+'" width="'+w+'" caption="'+cap+'"]'+c+'[/caption]'; + }); + }, + + showButtons : function(n) { + var t = this, ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y, cls = ed.dom.getAttrib(n, 'class'); + + if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 ) + return; + + vp = ed.dom.getViewPort(ed.getWin()); + p1 = DOM.getPos(ed.getContentAreaContainer()); + p2 = ed.dom.getPos(n); + + X = Math.max(p2.x - vp.x, 0) + p1.x; + Y = Math.max(p2.y - vp.y, 0) + p1.y; + + DOM.setStyles('wp_editbtns', { + 'top' : Y+5+'px', + 'left' : X+5+'px', + 'display' : 'block' + }); + + t.btnsTout = window.setTimeout( function(){ed.plugins.wpeditimage.hideButtons();}, 5000 ); + }, + + hideButtons : function() { + if ( tinymce.DOM.isHidden('wp_editbtns') ) return; + + tinymce.DOM.hide('wp_editbtns'); + window.clearTimeout(this.btnsTout); + }, + + _createButtons : function() { + var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, wp_editbtns, wp_editimgbtn, wp_delimgbtn; + + DOM.remove('wp_editbtns'); + + wp_editbtns = DOM.add(document.body, 'div', { + id : 'wp_editbtns', + style : 'display:none;' + }); + + wp_editimgbtn = DOM.add('wp_editbtns', 'img', { + src : t.url+'/img/image.png', + id : 'wp_editimgbtn', + width : '24', + height : '24', + title : ed.getLang('wpeditimage.edit_img') + }); + + wp_editimgbtn.onmousedown = function(e) { + var ed = tinyMCE.activeEditor; + ed.windowManager.bookmark = ed.selection.getBookmark('simple'); + ed.execCommand("WP_EditImage"); + this.parentNode.style.display = 'none'; + }; + + wp_delimgbtn = DOM.add('wp_editbtns', 'img', { + src : t.url+'/img/delete.png', + id : 'wp_delimgbtn', + width : '24', + height : '24', + title : ed.getLang('wpeditimage.del_img') + }); + + wp_delimgbtn.onmousedown = function(e) { + var ed = tinyMCE.activeEditor, el = ed.selection.getNode(), p; + + if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('mceItem') == -1 ) { + if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') ) + ed.dom.remove(p); + else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 ) + ed.dom.remove(p); + else ed.dom.remove(el); + + this.parentNode.style.display = 'none'; + ed.execCommand('mceRepaint'); + return false; + } + }; + }, + + getInfo : function() { + return { + longname : 'Edit Image', + author : 'WordPress', + authorurl : 'http://wordpress.org', + infourl : '', + version : "1.0" + }; + } + }); + + tinymce.PluginManager.add('wpeditimage', tinymce.plugins.wpEditImage); +})(); diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.js b/wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.js new file mode 100644 index 0000000..9c17ed3 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpeditimage/editor_plugin.js @@ -0,0 +1 @@ +(function(){tinymce.create("tinymce.plugins.wpEditImage",{init:function(a,b){var c=this;c.url=b;c._createButtons();a.addCommand("WP_EditImage",function(){var h=a.selection.getNode(),f=tinymce.DOM.getViewPort(),g=f.h,d=(720
    '+k+'
    '+h+"
    "})},_get_shcode:function(a){return a.replace(/
    \s*]+)>\s*]+>([\s\S]+?)<\/dt>\s*]+>(.+?)<\/dd>\s*<\/dl>\s*<\/div>\s*/gi,function(g,d,j,h){var i,f,e;i=d.match(/id=['"]([^'"]+)/i);f=d.match(/class=['"]([^'"]+)/i);e=j.match(/width=['"]([0-9]+)/);i=(i&&i[1])?i[1]:"";f=(f&&f[1])?f[1]:"alignnone";e=(e&&e[1])?e[1]:"";if(!e||!h){return j}f=f.match(/align[^ '"]+/)||"alignnone";h=h.replace(/<\S[^<>]*>/gi,"").replace(/'/g,"'").replace(/"/g,""");return'[caption id="'+i+'" align="'+f+'" width="'+e+'" caption="'+h+'"]'+j+"[/caption]"})},showButtons:function(d){var j=this,e=tinyMCE.activeEditor,g,f,a,i=tinymce.DOM,c,b,h=e.dom.getAttrib(d,"class");if(h.indexOf("mceItem")!=-1||h.indexOf("wpGallery")!=-1){return}a=e.dom.getViewPort(e.getWin());g=i.getPos(e.getContentAreaContainer());f=e.dom.getPos(d);c=Math.max(f.x-a.x,0)+g.x;b=Math.max(f.y-a.y,0)+g.y;i.setStyles("wp_editbtns",{top:b+5+"px",left:c+5+"px",display:"block"});j.btnsTout=window.setTimeout(function(){e.plugins.wpeditimage.hideButtons()},5000)},hideButtons:function(){if(tinymce.DOM.isHidden("wp_editbtns")){return}tinymce.DOM.hide("wp_editbtns");window.clearTimeout(this.btnsTout)},_createButtons:function(){var d=this,b=tinyMCE.activeEditor,e=tinymce.DOM,a,c,f;e.remove("wp_editbtns");a=e.add(document.body,"div",{id:"wp_editbtns",style:"display:none;"});c=e.add("wp_editbtns","img",{src:d.url+"/img/image.png",id:"wp_editimgbtn",width:"24",height:"24",title:b.getLang("wpeditimage.edit_img")});c.onmousedown=function(h){var g=tinyMCE.activeEditor;g.windowManager.bookmark=g.selection.getBookmark("simple");g.execCommand("WP_EditImage");this.parentNode.style.display="none"};f=e.add("wp_editbtns","img",{src:d.url+"/img/delete.png",id:"wp_delimgbtn",width:"24",height:"24",title:b.getLang("wpeditimage.del_img")});f.onmousedown=function(j){var g=tinyMCE.activeEditor,h=g.selection.getNode(),i;if(h.nodeName=="IMG"&&g.dom.getAttrib(h,"class").indexOf("mceItem")==-1){if((i=g.dom.getParent(h,"div"))&&g.dom.hasClass(i,"mceTemp")){g.dom.remove(i)}else{if((i=g.dom.getParent(h,"A"))&&i.childNodes.length==1){g.dom.remove(i)}else{g.dom.remove(h)}}this.parentNode.style.display="none";g.execCommand("mceRepaint");return false}}},getInfo:function(){return{longname:"Edit Image",author:"WordPress",authorurl:"http://wordpress.org",infourl:"",version:"1.0"}}});tinymce.PluginManager.add("wpeditimage",tinymce.plugins.wpEditImage)})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/img/delete.png b/wp-includes/js/tinymce/plugins/wpeditimage/img/delete.png new file mode 100644 index 0000000..d64d8a6 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wpeditimage/img/delete.png differ diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/img/image.png b/wp-includes/js/tinymce/plugins/wpeditimage/img/image.png new file mode 100644 index 0000000..f3d4b44 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wpeditimage/img/image.png differ diff --git a/wp-includes/js/tinymce/plugins/wpeditimage/js/editimage.js b/wp-includes/js/tinymce/plugins/wpeditimage/js/editimage.js new file mode 100644 index 0000000..9534c64 --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpeditimage/js/editimage.js @@ -0,0 +1,607 @@ + +var tinymce = null, tinyMCEPopup, tinyMCE; + +tinyMCEPopup = { + init: function() { + var t = this, w, ti, li, q, i, it; + + li = ('' + document.location.search).replace(/^\?/, '').split('&'); + q = {}; + for (i=0; i' ); + } + }, + + I : function(e) { + return document.getElementById(e); + }, + + current : '', + link : '', + link_rel : '', + target_value : '', + current_size_sel : 's100', + width : '', + height : '', + align : '', + img_alt : '', + + setTabs : function(tab) { + var t = this; + + if ( 'current' == tab.className ) return false; + t.I('div_advanced').style.display = ( 'tab_advanced' == tab.id ) ? 'block' : 'none'; + t.I('div_basic').style.display = ( 'tab_basic' == tab.id ) ? 'block' : 'none'; + t.I('tab_basic').className = t.I('tab_advanced').className = ''; + tab.className = 'current'; + return false; + }, + + img_seturl : function(u) { + var t = this, rel = t.I('link_rel').value; + + if ( 'current' == u ) { + t.I('link_href').value = t.current; + t.I('link_rel').value = t.link_rel; + } else { + t.I('link_href').value = t.link; + if ( rel ) { + rel = rel.replace( /attachment|wp-att-[0-9]+/gi, '' ); + t.I('link_rel').value = tinymce.trim(rel); + } + } + }, + + imgAlignCls : function(v) { + var t = this, cls = t.I('img_classes').value; + + t.I('img_demo').className = t.align = v; + + cls = cls.replace( /align[^ "']+/gi, '' ); + cls += (' ' + v); + cls = cls.replace( /\s+/g, ' ' ).replace( /^\s/, '' ); + + if ( 'aligncenter' == v ) { + t.I('hspace').value = ''; + t.updateStyle('hspace'); + } + + t.I('img_classes').value = cls; + }, + + showSize : function(el) { + var t = this, demo = t.I('img_demo'), w = t.width, h = t.height, id = el.id || 's100', size; + + size = parseInt(id.substring(1)) / 200; + demo.width = Math.round(w * size); + demo.height = Math.round(h * size); + + t.showSizeClear(); + el.style.borderColor = '#A3A3A3'; + el.style.backgroundColor = '#E5E5E5'; + }, + + showSizeSet : function() { + var t = this; + + if ( (t.width * 1.3) > parseInt(t.preloadImg.width) ) { + var s130 = t.I('s130'), s120 = t.I('s120'), s110 = t.I('s110'); + + s130.onclick = s120.onclick = s110.onclick = null; + s130.onmouseover = s120.onmouseover = s110.onmouseover = null; + s130.style.color = s120.style.color = s110.style.color = '#aaa'; + } + }, + + showSizeRem : function() { + var t = this, demo = t.I('img_demo'), f = document.forms[0]; + + demo.width = Math.round(f.width.value * 0.5); + demo.height = Math.round(f.height.value * 0.5); + t.showSizeClear(); + t.I(t.current_size_sel).style.borderColor = '#A3A3A3'; + t.I(t.current_size_sel).style.backgroundColor = '#E5E5E5'; + + return false; + }, + + showSizeClear : function() { + var divs = this.I('img_size').getElementsByTagName('div'); + + for ( i = 0; i < divs.length; i++ ) { + divs[i].style.borderColor = '#f1f1f1'; + divs[i].style.backgroundColor = '#f1f1f1'; + } + }, + + imgEditSize : function(el) { + var t = this, f = document.forms[0]; + + if ( ! t.preloadImg || ! t.preloadImg.width || ! t.preloadImg.height ) return; + var W = parseInt(t.preloadImg.width), H = parseInt(t.preloadImg.height), w = t.width || W, h = t.height || H, id = el.id || 's100'; + + size = parseInt(id.substring(1)) / 100; + + w = Math.round(w * size); + h = Math.round(h * size); + + f.width.value = Math.min(W, w); + f.height.value = Math.min(H, h); + + t.current_size_sel = id; + t.demoSetSize(); + }, + + demoSetSize : function(img) { + var demo = this.I('img_demo'), f = document.forms[0]; + + demo.width = f.width.value ? Math.round(f.width.value * 0.5) : ''; + demo.height = f.height.value ? Math.round(f.height.value * 0.5) : ''; + }, + + demoSetStyle : function() { + var f = document.forms[0], demo = this.I('img_demo'), dom = tinyMCEPopup.editor.dom; + + if (demo) { + dom.setAttrib(demo, 'style', f.img_style.value); + dom.setStyle(demo, 'width', ''); + dom.setStyle(demo, 'height', ''); + } + }, + + origSize : function() { + var t = this, f = document.forms[0], el = t.I('s100'); + + f.width.value = t.width = t.preloadImg.width; + f.height.value = t.height = t.preloadImg.height; + t.showSizeSet(); + t.demoSetSize(); + t.showSize(el); + }, + + init : function() { + var ed = tinyMCEPopup.editor, h; + + h = document.body.innerHTML; + + // Replace a=x with a="x" in IE + if (tinymce.isIE) + h = h.replace(/ (value|title|alt)=([^"][^\s>]+)/gi, ' $1="$2"') + + document.body.innerHTML = ed.translate(h); + window.setTimeout( function(){wpImage.setup();}, 100 ); + }, + + setup : function() { + var t = this, h, c, el, id, link, fname, f = document.forms[0], ed = tinyMCEPopup.editor, d = t.I('img_demo'), dom = tinyMCEPopup.dom, DL, caption = ''; + document.dir = tinyMCEPopup.editor.getParam('directionality',''); + + if ( tinyMCEPopup.editor.getParam('wpeditimage_disable_captions', false) ) + t.I('cap_field').style.display = 'none'; + + tinyMCEPopup.restoreSelection(); + el = ed.selection.getNode(); + if (el.nodeName != 'IMG') return; + + f.img_src.value = d.src = link = ed.dom.getAttrib(el, 'src'); + ed.dom.setStyle(el, 'float', ''); + t.getImageData(); + c = ed.dom.getAttrib(el, 'class'); + + if ( DL = dom.getParent(el, 'dl') ) { + var dlc = ed.dom.getAttrib(DL, 'class'); + dlc = dlc.match(/align[^ "']+/i); + if ( dlc && ! dom.hasClass(el, dlc) ) { + c += ' '+dlc; + tinymce.trim(c); + } + + tinymce.each(DL.childNodes, function(e) { + if ( e.nodeName == 'DD' && dom.hasClass(e, 'wp-caption-dd') ) { + caption = e.innerHTML; + return; + } + }); + } + + f.img_cap.value = caption; + f.img_title.value = ed.dom.getAttrib(el, 'title'); + f.img_alt.value = ed.dom.getAttrib(el, 'alt'); + f.border.value = ed.dom.getAttrib(el, 'border'); + f.vspace.value = ed.dom.getAttrib(el, 'vspace'); + f.hspace.value = ed.dom.getAttrib(el, 'hspace'); + f.align.value = ed.dom.getAttrib(el, 'align'); + f.width.value = t.width = ed.dom.getAttrib(el, 'width'); + f.height.value = t.height = ed.dom.getAttrib(el, 'height'); + f.img_classes.value = c; + f.img_style.value = ed.dom.getAttrib(el, 'style'); + + // Move attribs to styles + if (dom.getAttrib(el, 'hspace')) + t.updateStyle('hspace'); + + if (dom.getAttrib(el, 'border')) + t.updateStyle('border'); + + if (dom.getAttrib(el, 'vspace')) + t.updateStyle('vspace'); + + if (pa = ed.dom.getParent(el, 'A')) { + f.link_href.value = t.current = ed.dom.getAttrib(pa, 'href'); + f.link_title.value = ed.dom.getAttrib(pa, 'title'); + f.link_rel.value = t.link_rel = ed.dom.getAttrib(pa, 'rel'); + f.link_style.value = ed.dom.getAttrib(pa, 'style'); + t.target_value = ed.dom.getAttrib(pa, 'target'); + f.link_classes.value = ed.dom.getAttrib(pa, 'class'); + } + + f.link_target.checked = ( t.target_value && t.target_value == '_blank' ) ? 'checked' : ''; + + fname = link.substring( link.lastIndexOf('/') ); + fname = fname.replace(/-[0-9]{2,4}x[0-9]{2,4}/, '' ); + t.link = link.substring( 0, link.lastIndexOf('/') ) + fname; + + if ( c.indexOf('alignleft') != -1 ) { + t.I('alignleft').checked = "checked"; + d.className = t.align = "alignleft"; + } else if ( c.indexOf('aligncenter') != -1 ) { + t.I('aligncenter').checked = "checked"; + d.className = t.align = "aligncenter"; + } else if ( c.indexOf('alignright') != -1 ) { + t.I('alignright').checked = "checked"; + d.className = t.align = "alignright"; + } else if ( c.indexOf('alignnone') != -1 ) { + t.I('alignnone').checked = "checked"; + d.className = t.align = "alignnone"; + } + + if ( t.width && t.preloadImg.width ) t.showSizeSet(); + document.body.style.display = ''; + }, + + remove : function() { + var ed = tinyMCEPopup.editor, p, el; + + tinyMCEPopup.restoreSelection(); + el = ed.selection.getNode(); + if (el.nodeName != 'IMG') return; + + if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') ) + ed.dom.remove(p); + else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 ) + ed.dom.remove(p); + else ed.dom.remove(el); + + ed.execCommand('mceRepaint'); + tinyMCEPopup.close(); + return; + }, + + update : function() { + var t = this, f = document.forms[0], ed = tinyMCEPopup.editor, el, b, fixSafari = null, DL, P, A, DIV, do_caption = null, img_class = f.img_classes.value, html; + + tinyMCEPopup.restoreSelection(); + el = ed.selection.getNode(); + + if (el.nodeName != 'IMG') return; + if (f.img_src.value === '') { + t.remove(); + return; + } + + if ( f.img_cap.value != '' && f.width.value != '' ) { + do_caption = 1; + img_class = img_class.replace( /align[^ "']+\s?/gi, '' ); + } + + A = ed.dom.getParent(el, 'a'); + P = ed.dom.getParent(el, 'p'); + DL = ed.dom.getParent(el, 'dl'); + DIV = ed.dom.getParent(el, 'div'); + + tinyMCEPopup.execCommand("mceBeginUndoLevel"); + + ed.dom.setAttribs(el, { + src : f.img_src.value, + title : f.img_title.value, + alt : f.img_alt.value, + width : f.width.value, + height : f.height.value, + style : f.img_style.value, + 'class' : img_class + }); + + if ( f.link_href.value ) { + // Create new anchor elements + if ( A == null ) { + if ( ! f.link_href.value.match(/https?:\/\//i) ) + f.link_href.value = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.link_href.value); + + if ( tinymce.isWebKit && ed.dom.hasClass(el, 'aligncenter') ) { + ed.dom.removeClass(el, 'aligncenter'); + fixSafari = 1; + } + + tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1}); + if ( fixSafari ) ed.dom.addClass(el, 'aligncenter'); + + tinymce.each(ed.dom.select("a"), function(n) { + if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { + + ed.dom.setAttribs(n, { + href : f.link_href.value, + title : f.link_title.value, + rel : f.link_rel.value, + target : (f.link_target.checked == true) ? '_blank' : '', + 'class' : f.link_classes.value, + style : f.link_style.value + }); + } + }); + } else { + ed.dom.setAttribs(A, { + href : f.link_href.value, + title : f.link_title.value, + rel : f.link_rel.value, + target : (f.link_target.checked == true) ? '_blank' : '', + 'class' : f.link_classes.value, + style : f.link_style.value + }); + } + } + + if ( do_caption ) { + var id, cap_id = '', cap, DT, DD, cap_width = 10 + parseInt(f.width.value), align = t.align.substring(5), div_cls = (t.align == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp'; + + if ( DL ) { + ed.dom.setAttribs(DL, { + 'class' : 'wp-caption '+t.align, + style : 'width: '+cap_width+'px;' + }); + + if ( DIV ) + ed.dom.setAttrib(DIV, 'class', div_cls); + + if ( (DT = ed.dom.getParent(el, 'dt')) && (DD = DT.nextSibling) && ed.dom.hasClass(DD, 'wp-caption-dd') ) + ed.dom.setHTML(DD, f.img_cap.value); + + } else { + var lnk = '', pa; + if ( (id = f.img_classes.value.match( /wp-image-([0-9]{1,6})/ )) && id[1] ) + cap_id = 'attachment_'+id[1]; + + if ( f.link_href.value && (lnk = ed.dom.getParent(el, 'a')) ) { + if ( lnk.childNodes.length == 1 ) + html = ed.dom.getOuterHTML(lnk); + else { + html = ed.dom.getOuterHTML(lnk); + html = html.match(/]+>/i); + html = html+ed.dom.getOuterHTML(el)+''; + } + } else html = ed.dom.getOuterHTML(el); + + html = '
    '+html+'
    '+f.img_cap.value+'
    '; + + cap = ed.dom.create('div', {'class': div_cls}, html); + + if ( P ) { + P.parentNode.insertBefore(cap, P); + if ( P.childNodes.length == 1 ) + ed.dom.remove(P); + else if ( lnk && lnk.childNodes.length == 1 ) + ed.dom.remove(lnk); + else ed.dom.remove(el); + } else if ( pa = ed.dom.getParent(el, 'TD,TH,LI') ) { + pa.appendChild(cap); + if ( lnk && lnk.childNodes.length == 1 ) + ed.dom.remove(lnk); + else ed.dom.remove(el); + } + } + + } else { + if ( DL && DIV ) { + var aa; + if ( f.link_href.value && (aa = ed.dom.getParent(el, 'a')) ) html = ed.dom.getOuterHTML(aa); + else html = ed.dom.getOuterHTML(el); + + P = ed.dom.create('p', {}, html); + DIV.parentNode.insertBefore(P, DIV); + ed.dom.remove(DIV); + } + } + + if ( f.img_classes.value.indexOf('aligncenter') != -1 ) { + if ( P && ( ! P.style || P.style.textAlign != 'center' ) ) + ed.dom.setStyle(P, 'textAlign', 'center'); + } else { + if ( P && P.style && P.style.textAlign == 'center' ) + ed.dom.setStyle(P, 'textAlign', ''); + } + + if ( ! f.link_href.value && A ) { + b = ed.selection.getBookmark(); + ed.dom.remove(A, 1); + ed.selection.moveToBookmark(b); + } + + tinyMCEPopup.execCommand("mceEndUndoLevel"); + ed.execCommand('mceRepaint'); + tinyMCEPopup.close(); + }, + + updateStyle : function(ty) { + var dom = tinyMCEPopup.dom, st, v, f = document.forms[0], img = dom.create('img', {style : f.img_style.value}); + + if (tinyMCEPopup.editor.settings.inline_styles) { + // Handle align + if (ty == 'align') { + dom.setStyle(img, 'float', ''); + dom.setStyle(img, 'vertical-align', ''); + + v = f.align.value; + if (v) { + if (v == 'left' || v == 'right') + dom.setStyle(img, 'float', v); + else + img.style.verticalAlign = v; + } + } + + // Handle border + if (ty == 'border') { + dom.setStyle(img, 'border', ''); + + v = f.border.value; + if (v || v == '0') { + if (v == '0') + img.style.border = '0'; + else + img.style.border = v + 'px solid black'; + } + } + + // Handle hspace + if (ty == 'hspace') { + dom.setStyle(img, 'marginLeft', ''); + dom.setStyle(img, 'marginRight', ''); + + v = f.hspace.value; + if (v) { + img.style.marginLeft = v + 'px'; + img.style.marginRight = v + 'px'; + } + } + + // Handle vspace + if (ty == 'vspace') { + dom.setStyle(img, 'marginTop', ''); + dom.setStyle(img, 'marginBottom', ''); + + v = f.vspace.value; + if (v) { + img.style.marginTop = v + 'px'; + img.style.marginBottom = v + 'px'; + } + } + + // Merge + f.img_style.value = dom.serializeStyle(dom.parseStyle(img.style.cssText)); + this.demoSetStyle(); + } + }, + + checkVal : function(f) { + + if ( f.value == '' ) { + // if ( f.id == 'width' ) f.value = this.width || this.preloadImg.width; + // if ( f.id == 'height' ) f.value = this.height || this.preloadImg.height; + if ( f.id == 'img_src' ) f.value = this.I('img_demo').src || this.preloadImg.src; + } + }, + + resetImageData : function() { + var f = document.forms[0]; + + f.width.value = f.height.value = ''; + }, + + updateImageData : function() { + var f = document.forms[0], t = wpImage; + + if ( f.width.value == '' || f.height.value == '' ) { + f.width.value = t.width = t.preloadImg.width; + f.height.value = t.height = t.preloadImg.height; + } + + t.showSizeSet(); + t.demoSetSize(); + if ( f.img_style.value ) + t.demoSetStyle(); + }, + + getImageData : function() { + var t = wpImage, f = document.forms[0]; + + t.preloadImg = new Image(); + t.preloadImg.onload = t.updateImageData; + t.preloadImg.onerror = t.resetImageData; + t.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.img_src.value); + } +}; + +window.onload = function(){wpImage.init();} +wpImage.preInit(); diff --git a/wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.dev.js b/wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.dev.js new file mode 100644 index 0000000..3c9701d --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.dev.js @@ -0,0 +1,174 @@ + +(function() { + tinymce.create('tinymce.plugins.wpGallery', { + + init : function(ed, url) { + var t = this; + + t.url = url; + t._createButtons(); + + // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); + ed.addCommand('WP_Gallery', function() { + var el = ed.selection.getNode(), post_id, vp = tinymce.DOM.getViewPort(), H = vp.h - 80, W = ( 640 < vp.w ) ? 640 : vp.w; + + if ( el.nodeName != 'IMG' ) return; + if ( ed.dom.getAttrib(el, 'class').indexOf('wpGallery') == -1 ) return; + + post_id = tinymce.DOM.get('post_ID').value; + tb_show('', tinymce.documentBaseURL + '/media-upload.php?post_id='+post_id+'&tab=gallery&TB_iframe=true&width='+W+'&height='+H); + + tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); + }); + + ed.onInit.add(function(ed) { + tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) { + ed.plugins.wpgallery.hideButtons(); + }); + }); + + ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { + ed.plugins.wpgallery.hideButtons(); + }); + + ed.onSaveContent.add(function(ed, o) { + ed.plugins.wpgallery.hideButtons(); + }); + + ed.onMouseUp.add(function(ed, e) { + if ( tinymce.isOpera ) { + if ( e.target.nodeName == 'IMG' ) + ed.plugins.wpgallery.showButtons(e.target); + } + + }); + + ed.onMouseDown.add(function(ed, e) { + if ( tinymce.isOpera || e.target.nodeName != 'IMG' ) { + t.hideButtons(); + return; + } + ed.plugins.wpgallery.showButtons(e.target); + }); + + ed.onBeforeSetContent.add(function(ed, o) { + o.content = t._do_gallery(o.content); + }); + + ed.onPostProcess.add(function(ed, o) { + if (o.get) + o.content = t._get_gallery(o.content); + }); + }, + + _do_gallery : function(co) { + return co.replace(/\[gallery([^\]]*)\]/g, function(a,b){ + return ''; + }); + }, + + _get_gallery : function(co) { + + function getAttr(s, n) { + n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s); + return n ? tinymce.DOM.decode(n[1]) : ''; + }; + + return co.replace(/(?:]*>)*(]+>)(?:<\/p>)*/g, function(a,im) { + var cls = getAttr(im, 'class'); + + if ( cls.indexOf('wpGallery') != -1 ) + return '

    ['+tinymce.trim(getAttr(im, 'title'))+']

    '; + + return a; + }); + }, + + showButtons : function(n) { + var t = this, ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y; + + if (ed.dom.getAttrib(n, 'class').indexOf('wpGallery') == -1) + return; + + vp = ed.dom.getViewPort(ed.getWin()); + p1 = DOM.getPos(ed.getContentAreaContainer()); + p2 = ed.dom.getPos(n); + + X = Math.max(p2.x - vp.x, 0) + p1.x; + Y = Math.max(p2.y - vp.y, 0) + p1.y; + + DOM.setStyles('wp_gallerybtns', { + 'top' : Y+5+'px', + 'left' : X+5+'px', + 'display' : 'block' + }); + + t.btnsTout = window.setTimeout( function(){ed.plugins.wpgallery.hideButtons();}, 5000 ); + }, + + hideButtons : function() { + if ( tinymce.DOM.isHidden('wp_gallerybtns') ) return; + + tinymce.DOM.hide('wp_gallerybtns'); + window.clearTimeout(this.btnsTout); + }, + + _createButtons : function() { + var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, wp_gallerybtns, wp_editgallery, wp_delgallery; + + DOM.remove('wp_gallerybtns'); + + wp_gallerybtns = DOM.add(document.body, 'div', { + id : 'wp_gallerybtns', + style : 'display:none;' + }); + + wp_editgallery = DOM.add('wp_gallerybtns', 'img', { + src : t.url+'/img/edit.png', + id : 'wp_editgallery', + width : '24', + height : '24', + title : ed.getLang('wordpress.editgallery') + }); + + wp_editgallery.onmousedown = function(e) { + var ed = tinyMCE.activeEditor; + ed.windowManager.bookmark = ed.selection.getBookmark('simple'); + ed.execCommand("WP_Gallery"); + this.parentNode.style.display = 'none'; + }; + + wp_delgallery = DOM.add('wp_gallerybtns', 'img', { + src : t.url+'/img/delete.png', + id : 'wp_delgallery', + width : '24', + height : '24', + title : ed.getLang('wordpress.delgallery') + }); + + wp_delgallery.onmousedown = function(e) { + var ed = tinyMCE.activeEditor, el = ed.selection.getNode(); + + if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('wpGallery') != -1 ) { + ed.dom.remove(el); + + this.parentNode.style.display = 'none'; + ed.execCommand('mceRepaint'); + return false; + } + }; + }, + + getInfo : function() { + return { + longname : 'Gallery Settings', + author : 'WordPress', + authorurl : 'http://wordpress.org', + infourl : '', + version : "1.0" + }; + } + }); + + tinymce.PluginManager.add('wpgallery', tinymce.plugins.wpGallery); +})(); diff --git a/wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.js b/wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.js new file mode 100644 index 0000000..e924e3d --- /dev/null +++ b/wp-includes/js/tinymce/plugins/wpgallery/editor_plugin.js @@ -0,0 +1 @@ +(function(){tinymce.create("tinymce.plugins.wpGallery",{init:function(a,b){var c=this;c.url=b;c._createButtons();a.addCommand("WP_Gallery",function(){var h=a.selection.getNode(),f,e=tinymce.DOM.getViewPort(),g=e.h-80,d=(640'})},_get_gallery:function(b){function a(c,d){d=new RegExp(d+'="([^"]+)"',"g").exec(c);return d?tinymce.DOM.decode(d[1]):""}return b.replace(/(?:]*>)*(]+>)(?:<\/p>)*/g,function(e,d){var c=a(d,"class");if(c.indexOf("wpGallery")!=-1){return"

    ["+tinymce.trim(a(d,"title"))+"]

    "}return e})},showButtons:function(d){var i=this,e=tinyMCE.activeEditor,g,f,a,h=tinymce.DOM,c,b;if(e.dom.getAttrib(d,"class").indexOf("wpGallery")==-1){return}a=e.dom.getViewPort(e.getWin());g=h.getPos(e.getContentAreaContainer());f=e.dom.getPos(d);c=Math.max(f.x-a.x,0)+g.x;b=Math.max(f.y-a.y,0)+g.y;h.setStyles("wp_gallerybtns",{top:b+5+"px",left:c+5+"px",display:"block"});i.btnsTout=window.setTimeout(function(){e.plugins.wpgallery.hideButtons()},5000)},hideButtons:function(){if(tinymce.DOM.isHidden("wp_gallerybtns")){return}tinymce.DOM.hide("wp_gallerybtns");window.clearTimeout(this.btnsTout)},_createButtons:function(){var d=this,b=tinyMCE.activeEditor,e=tinymce.DOM,c,f,a;e.remove("wp_gallerybtns");c=e.add(document.body,"div",{id:"wp_gallerybtns",style:"display:none;"});f=e.add("wp_gallerybtns","img",{src:d.url+"/img/edit.png",id:"wp_editgallery",width:"24",height:"24",title:b.getLang("wordpress.editgallery")});f.onmousedown=function(h){var g=tinyMCE.activeEditor;g.windowManager.bookmark=g.selection.getBookmark("simple");g.execCommand("WP_Gallery");this.parentNode.style.display="none"};a=e.add("wp_gallerybtns","img",{src:d.url+"/img/delete.png",id:"wp_delgallery",width:"24",height:"24",title:b.getLang("wordpress.delgallery")});a.onmousedown=function(i){var g=tinyMCE.activeEditor,h=g.selection.getNode();if(h.nodeName=="IMG"&&g.dom.getAttrib(h,"class").indexOf("wpGallery")!=-1){g.dom.remove(h);this.parentNode.style.display="none";g.execCommand("mceRepaint");return false}}},getInfo:function(){return{longname:"Gallery Settings",author:"WordPress",authorurl:"http://wordpress.org",infourl:"",version:"1.0"}}});tinymce.PluginManager.add("wpgallery",tinymce.plugins.wpGallery)})(); \ No newline at end of file diff --git a/wp-includes/js/tinymce/plugins/wpgallery/img/delete.png b/wp-includes/js/tinymce/plugins/wpgallery/img/delete.png new file mode 100644 index 0000000..d64d8a6 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wpgallery/img/delete.png differ diff --git a/wp-includes/js/tinymce/plugins/wpgallery/img/edit.png b/wp-includes/js/tinymce/plugins/wpgallery/img/edit.png new file mode 100644 index 0000000..41def51 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wpgallery/img/edit.png differ diff --git a/wp-includes/js/tinymce/plugins/wpgallery/img/gallery.png b/wp-includes/js/tinymce/plugins/wpgallery/img/gallery.png new file mode 100644 index 0000000..803ad63 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wpgallery/img/gallery.png differ diff --git a/wp-includes/js/tinymce/plugins/wpgallery/img/t.gif b/wp-includes/js/tinymce/plugins/wpgallery/img/t.gif new file mode 100644 index 0000000..3884865 Binary files /dev/null and b/wp-includes/js/tinymce/plugins/wpgallery/img/t.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/about.htm b/wp-includes/js/tinymce/themes/advanced/about.htm new file mode 100644 index 0000000..f521bd5 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/about.htm @@ -0,0 +1,56 @@ + + + + {#advanced_dlg.about_title} + + + + + + + +
    +
    +

    {#advanced_dlg.about_title}

    +

    Version: ()

    +

    TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under LGPL + by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.

    +

    Copyright © 2003-2008, Moxiecode Systems AB, All rights reserved.

    +

    For more information about this software visit the TinyMCE website.

    + +
    + Got Moxie? + Hosted By Sourceforge + Also on freshmeat +
    +
    + +
    +
    +

    {#advanced_dlg.about_loaded}

    + +
    +
    + +

     

    +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    +
    + + diff --git a/wp-includes/js/tinymce/themes/advanced/anchor.htm b/wp-includes/js/tinymce/themes/advanced/anchor.htm new file mode 100644 index 0000000..2928b04 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/anchor.htm @@ -0,0 +1,31 @@ + + + + {#advanced_dlg.anchor_title} + + + + +
    + + + + + + + + +
    {#advanced_dlg.anchor_title}
    {#advanced_dlg.anchor_name}:
    + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/themes/advanced/charmap.htm b/wp-includes/js/tinymce/themes/advanced/charmap.htm new file mode 100644 index 0000000..42ceaa3 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/charmap.htm @@ -0,0 +1,53 @@ + + + + {#advanced_dlg.charmap_title} + + + + + + + + + + + + + + + + +
    {#advanced_dlg.charmap_title}
    + + + + + + + + + +
     
     
    +
    + + + + + + + + + + + + + + + + +
    HTML-Code
     
     
    NUM-Code
     
    +
    + + + diff --git a/wp-includes/js/tinymce/themes/advanced/color_picker.htm b/wp-includes/js/tinymce/themes/advanced/color_picker.htm new file mode 100644 index 0000000..5cdca6e --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/color_picker.htm @@ -0,0 +1,75 @@ + + + + {#advanced_dlg.colorpicker_title} + + + + + +
    + + +
    +
    +
    + {#advanced_dlg.colorpicker_picker_title} +
    +  + +
    + +
    + +
    +
    +
    +
    + +
    +
    + {#advanced_dlg.colorpicker_palette_title} +
    + +
    + +
    +
    +
    + +
    +
    + {#advanced_dlg.colorpicker_named_title} +
    + +
    + +
    + +
    + {#advanced_dlg.colorpicker_name} +
    +
    +
    +
    + +
    +
    + +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/themes/advanced/editor_template.js b/wp-includes/js/tinymce/themes/advanced/editor_template.js new file mode 100644 index 0000000..628c793 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/editor_template.js @@ -0,0 +1 @@ +(function(e){var d=e.DOM,b=e.dom.Event,h=e.extend,f=e.each,a=e.util.Cookie,g,c=e.explode;e.ThemeManager.requireLangPack("advanced");e.create("tinymce.themes.AdvancedTheme",{sizes:[8,10,12,14,18,24,36],controls:{bold:["bold_desc","Bold"],italic:["italic_desc","Italic"],underline:["underline_desc","Underline"],strikethrough:["striketrough_desc","Strikethrough"],justifyleft:["justifyleft_desc","JustifyLeft"],justifycenter:["justifycenter_desc","JustifyCenter"],justifyright:["justifyright_desc","JustifyRight"],justifyfull:["justifyfull_desc","JustifyFull"],bullist:["bullist_desc","InsertUnorderedList"],numlist:["numlist_desc","InsertOrderedList"],outdent:["outdent_desc","Outdent"],indent:["indent_desc","Indent"],cut:["cut_desc","Cut"],copy:["copy_desc","Copy"],paste:["paste_desc","Paste"],undo:["undo_desc","Undo"],redo:["redo_desc","Redo"],link:["link_desc","mceLink"],unlink:["unlink_desc","unlink"],image:["image_desc","mceImage"],cleanup:["cleanup_desc","mceCleanup"],help:["help_desc","mceHelp"],code:["code_desc","mceCodeEditor"],hr:["hr_desc","InsertHorizontalRule"],removeformat:["removeformat_desc","RemoveFormat"],sub:["sub_desc","subscript"],sup:["sup_desc","superscript"],forecolor:["forecolor_desc","ForeColor"],forecolorpicker:["forecolor_desc","mceForeColor"],backcolor:["backcolor_desc","HiliteColor"],backcolorpicker:["backcolor_desc","mceBackColor"],charmap:["charmap_desc","mceCharMap"],visualaid:["visualaid_desc","mceToggleVisualAid"],anchor:["anchor_desc","mceInsertAnchor"],newdocument:["newdocument_desc","mceNewDocument"],blockquote:["blockquote_desc","mceBlockQuote"]},stateControls:["bold","italic","underline","strikethrough","bullist","numlist","justifyleft","justifycenter","justifyright","justifyfull","sub","sup","blockquote"],init:function(j,k){var l=this,m,i,n;l.editor=j;l.url=k;l.onResolveName=new e.util.Dispatcher(this);l.settings=m=h({theme_advanced_path:true,theme_advanced_toolbar_location:"bottom",theme_advanced_buttons1:"bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect",theme_advanced_buttons2:"bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code",theme_advanced_buttons3:"hr,removeformat,visualaid,|,sub,sup,|,charmap",theme_advanced_blockformats:"p,address,pre,h1,h2,h3,h4,h5,h6",theme_advanced_toolbar_align:"center",theme_advanced_fonts:"Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats",theme_advanced_more_colors:1,theme_advanced_row_height:23,theme_advanced_resize_horizontal:1,theme_advanced_resizing_use_cookie:1,theme_advanced_font_sizes:"1,2,3,4,5,6,7",readonly:j.settings.readonly},j.settings);if(!m.font_size_style_values){m.font_size_style_values="8pt,10pt,12pt,14pt,18pt,24pt,36pt"}if(e.is(m.theme_advanced_font_sizes,"string")){m.font_size_style_values=e.explode(m.font_size_style_values);m.font_size_classes=e.explode(m.font_size_classes||"");n={};j.settings.theme_advanced_font_sizes=m.theme_advanced_font_sizes;f(j.getParam("theme_advanced_font_sizes","","hash"),function(q,p){var o;if(p==q&&q>=1&&q<=7){p=q+" ("+l.sizes[q-1]+"pt)";if(j.settings.convert_fonts_to_spans){o=m.font_size_classes[q-1];q=m.font_size_style_values[q-1]||(l.sizes[q-1]+"pt")}}if(/^\s*\./.test(q)){o=q.replace(/\./g,"")}n[p]=o?{"class":o}:{fontSize:q}});m.theme_advanced_font_sizes=n}if((i=m.theme_advanced_path_location)&&i!="none"){m.theme_advanced_statusbar_location=m.theme_advanced_path_location}if(m.theme_advanced_statusbar_location=="none"){m.theme_advanced_statusbar_location=0}j.onInit.add(function(){j.onNodeChange.add(l._nodeChanged,l);if(j.settings.content_css!==false){j.dom.loadCSS(j.baseURI.toAbsolute("themes/advanced/skins/"+j.settings.skin+"/content.css"))}});j.onSetProgressState.add(function(q,o,r){var s,t=q.id,p;if(o){l.progressTimer=setTimeout(function(){s=q.getContainer();s=s.insertBefore(d.create("DIV",{style:"position:relative"}),s.firstChild);p=d.get(q.id+"_tbl");d.add(s,"div",{id:t+"_blocker","class":"mceBlocker",style:{width:p.clientWidth+2,height:p.clientHeight+2}});d.add(s,"div",{id:t+"_progress","class":"mceProgress",style:{left:p.clientWidth/2,top:p.clientHeight/2}})},r||0)}else{d.remove(t+"_blocker");d.remove(t+"_progress");clearTimeout(l.progressTimer)}});d.loadCSS(m.editor_css?j.documentBaseURI.toAbsolute(m.editor_css):k+"/skins/"+j.settings.skin+"/ui.css");if(m.skin_variant){d.loadCSS(k+"/skins/"+j.settings.skin+"/ui_"+m.skin_variant+".css")}},createControl:function(l,i){var j,k;if(k=i.createControl(l)){return k}switch(l){case"styleselect":return this._createStyleSelect();case"formatselect":return this._createBlockFormats();case"fontselect":return this._createFontSelect();case"fontsizeselect":return this._createFontSizeSelect();case"forecolor":return this._createForeColorMenu();case"backcolor":return this._createBackColorMenu()}if((j=this.controls[l])){return i.createButton(l,{title:"advanced."+j[0],cmd:j[1],ui:j[2],value:j[3]})}},execCommand:function(k,j,l){var i=this["_"+k];if(i){i.call(this,j,l);return true}return false},_importClasses:function(j){var i=this.editor,k=i.controlManager.get("styleselect");if(k.getLength()==0){f(i.dom.getClasses(),function(l){k.add(l["class"],l["class"])})}},_createStyleSelect:function(m){var j=this,i=j.editor,k=i.controlManager,l=k.createListBox("styleselect",{title:"advanced.style_select",onselect:function(n){if(l.selectedValue===n){i.execCommand("mceSetStyleInfo",0,{command:"removeformat"});l.select();return false}else{i.execCommand("mceSetCSSClass",0,n)}}});if(l){f(i.getParam("theme_advanced_styles","","hash"),function(o,n){if(o){l.add(j.editor.translate(n),o)}});l.onPostRender.add(function(o,p){if(!l.NativeListBox){b.add(p.id+"_text","focus",j._importClasses,j);b.add(p.id+"_text","mousedown",j._importClasses,j);b.add(p.id+"_open","focus",j._importClasses,j);b.add(p.id+"_open","mousedown",j._importClasses,j)}else{b.add(p.id,"focus",j._importClasses,j)}})}return l},_createFontSelect:function(){var k,j=this,i=j.editor;k=i.controlManager.createListBox("fontselect",{title:"advanced.fontdefault",cmd:"FontName"});if(k){f(i.getParam("theme_advanced_fonts",j.settings.theme_advanced_fonts,"hash"),function(m,l){k.add(i.translate(l),m,{style:m.indexOf("dings")==-1?"font-family:"+m:""})})}return k},_createFontSizeSelect:function(){var m=this,k=m.editor,n,l=0,j=[];n=k.controlManager.createListBox("fontsizeselect",{title:"advanced.font_size",onselect:function(i){if(i.fontSize){k.execCommand("FontSize",false,i.fontSize)}else{f(m.settings.theme_advanced_font_sizes,function(p,o){if(p["class"]){j.push(p["class"])}});k.editorCommands._applyInlineStyle("span",{"class":i["class"]},{check_classes:j})}}});if(n){f(m.settings.theme_advanced_font_sizes,function(o,i){var p=o.fontSize;if(p>=1&&p<=7){p=m.sizes[parseInt(p)-1]+"pt"}n.add(i,o,{style:"font-size:"+p,"class":"mceFontSize"+(l++)+(" "+(o["class"]||""))})})}return n},_createBlockFormats:function(){var k,i={p:"advanced.paragraph",address:"advanced.address",pre:"advanced.pre",h1:"advanced.h1",h2:"advanced.h2",h3:"advanced.h3",h4:"advanced.h4",h5:"advanced.h5",h6:"advanced.h6",div:"advanced.div",blockquote:"advanced.blockquote",code:"advanced.code",dt:"advanced.dt",dd:"advanced.dd",samp:"advanced.samp"},j=this;k=j.editor.controlManager.createListBox("formatselect",{title:"advanced.block",cmd:"FormatBlock"});if(k){f(j.editor.getParam("theme_advanced_blockformats",j.settings.theme_advanced_blockformats,"hash"),function(m,l){k.add(j.editor.translate(l!=m?l:i[m]),m,{"class":"mce_formatPreview mce_"+m})})}return k},_createForeColorMenu:function(){var m,j=this,k=j.settings,l={},i;if(k.theme_advanced_more_colors){l.more_colors_func=function(){j._mceColorPicker(0,{color:m.value,func:function(n){m.setColor(n)}})}}if(i=k.theme_advanced_text_colors){l.colors=i}if(k.theme_advanced_default_foreground_color){l.default_color=k.theme_advanced_default_foreground_color}l.title="advanced.forecolor_desc";l.cmd="ForeColor";l.scope=this;m=j.editor.controlManager.createColorSplitButton("forecolor",l);return m},_createBackColorMenu:function(){var m,j=this,k=j.settings,l={},i;if(k.theme_advanced_more_colors){l.more_colors_func=function(){j._mceColorPicker(0,{color:m.value,func:function(n){m.setColor(n)}})}}if(i=k.theme_advanced_background_colors){l.colors=i}if(k.theme_advanced_default_background_color){l.default_color=k.theme_advanced_default_background_color}l.title="advanced.backcolor_desc";l.cmd="HiliteColor";l.scope=this;m=j.editor.controlManager.createColorSplitButton("backcolor",l);return m},renderUI:function(k){var m,l,q,v=this,r=v.editor,w=v.settings,u,j,i;m=j=d.create("span",{id:r.id+"_parent","class":"mceEditor "+r.settings.skin+"Skin"+(w.skin_variant?" "+r.settings.skin+"Skin"+v._ufirst(w.skin_variant):"")});if(!d.boxModel){m=d.add(m,"div",{"class":"mceOldBoxModel"})}m=u=d.add(m,"table",{id:r.id+"_tbl","class":"mceLayout",cellSpacing:0,cellPadding:0});m=q=d.add(m,"tbody");switch((w.theme_advanced_layout_manager||"").toLowerCase()){case"rowlayout":l=v._rowLayout(w,q,k);break;case"customlayout":l=r.execCallback("theme_advanced_custom_layout",w,q,k,j);break;default:l=v._simpleLayout(w,q,k,j)}m=k.targetNode;i=d.stdMode?u.getElementsByTagName("tr"):u.rows;d.addClass(i[0],"mceFirst");d.addClass(i[i.length-1],"mceLast");f(d.select("tr",q),function(o){d.addClass(o.firstChild,"mceFirst");d.addClass(o.childNodes[o.childNodes.length-1],"mceLast")});if(d.get(w.theme_advanced_toolbar_container)){d.get(w.theme_advanced_toolbar_container).appendChild(j)}else{d.insertAfter(j,m)}b.add(r.id+"_path_row","click",function(n){n=n.target;if(n.nodeName=="A"){v._sel(n.className.replace(/^.*mcePath_([0-9]+).*$/,"$1"));return b.cancel(n)}});if(!r.getParam("accessibility_focus")){b.add(d.add(j,"a",{href:"#"},""),"focus",function(){tinyMCE.get(r.id).focus()})}if(w.theme_advanced_toolbar_location=="external"){k.deltaHeight=0}v.deltaHeight=k.deltaHeight;k.targetNode=null;return{iframeContainer:l,editorContainer:r.id+"_parent",sizeContainer:u,deltaHeight:k.deltaHeight}},getInfo:function(){return{longname:"Advanced theme",author:"Moxiecode Systems AB",authorurl:"http://tinymce.moxiecode.com",version:e.majorVersion+"."+e.minorVersion}},resizeBy:function(i,j){var k=d.get(this.editor.id+"_tbl");this.resizeTo(k.clientWidth+i,k.clientHeight+j)},resizeTo:function(i,l){var j=this.editor,k=j.settings,n=d.get(j.id+"_tbl"),o=d.get(j.id+"_ifr"),m;i=Math.max(k.theme_advanced_resizing_min_width||100,i);l=Math.max(k.theme_advanced_resizing_min_height||100,l);i=Math.min(k.theme_advanced_resizing_max_width||65535,i);l=Math.min(k.theme_advanced_resizing_max_height||65535,l);m=n.clientHeight-o.clientHeight;d.setStyle(o,"height",l-m);d.setStyles(n,{width:i,height:l})},destroy:function(){var i=this.editor.id;b.clear(i+"_resize");b.clear(i+"_path_row");b.clear(i+"_external_close")},_simpleLayout:function(y,r,k,i){var x=this,u=x.editor,v=y.theme_advanced_toolbar_location,m=y.theme_advanced_statusbar_location,l,j,q,w;if(y.readonly){l=d.add(r,"tr");l=j=d.add(l,"td",{"class":"mceIframeContainer"});return j}if(v=="top"){x._addToolbars(r,k)}if(v=="external"){l=w=d.create("div",{style:"position:relative"});l=d.add(l,"div",{id:u.id+"_external","class":"mceExternalToolbar"});d.add(l,"a",{id:u.id+"_external_close",href:"javascript:;","class":"mceExternalClose"});l=d.add(l,"table",{id:u.id+"_tblext",cellSpacing:0,cellPadding:0});q=d.add(l,"tbody");if(i.firstChild.className=="mceOldBoxModel"){i.firstChild.appendChild(w)}else{i.insertBefore(w,i.firstChild)}x._addToolbars(q,k);u.onMouseUp.add(function(){var o=d.get(u.id+"_external");d.show(o);d.hide(g);var n=b.add(u.id+"_external_close","click",function(){d.hide(u.id+"_external");b.remove(u.id+"_external_close","click",n)});d.show(o);d.setStyle(o,"top",0-d.getRect(u.id+"_tblext").h-1);d.hide(o);d.show(o);o.style.filter="";g=u.id+"_external";o=null})}if(m=="top"){x._addStatusBar(r,k)}if(!y.theme_advanced_toolbar_container){l=d.add(r,"tr");l=j=d.add(l,"td",{"class":"mceIframeContainer"})}if(v=="bottom"){x._addToolbars(r,k)}if(m=="bottom"){x._addStatusBar(r,k)}return j},_rowLayout:function(w,m,k){var v=this,p=v.editor,u,x,i=p.controlManager,l,j,r,q;u=w.theme_advanced_containers_default_class||"";x=w.theme_advanced_containers_default_align||"center";f(c(w.theme_advanced_containers||""),function(s,o){var n=w["theme_advanced_container_"+s]||"";switch(n.toLowerCase()){case"mceeditor":l=d.add(m,"tr");l=j=d.add(l,"td",{"class":"mceIframeContainer"});break;case"mceelementpath":v._addStatusBar(m,k);break;default:q=(w["theme_advanced_container_"+s+"_align"]||x).toLowerCase();q="mce"+v._ufirst(q);l=d.add(d.add(m,"tr"),"td",{"class":"mceToolbar "+(w["theme_advanced_container_"+s+"_class"]||u)+" "+q||x});r=i.createToolbar("toolbar"+o);v._addControls(n,r);d.setHTML(l,r.renderHTML());k.deltaHeight-=w.theme_advanced_row_height}});return j},_addControls:function(j,i){var k=this,l=k.settings,m,n=k.editor.controlManager;if(l.theme_advanced_disable&&!k._disabled){m={};f(c(l.theme_advanced_disable),function(o){m[o]=1});k._disabled=m}else{m=k._disabled}f(c(j),function(p){var o;if(m&&m[p]){return}if(p=="tablecontrols"){f(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"],function(q){q=k.createControl(q,n);if(q){i.add(q)}});return}o=k.createControl(p,n);if(o){i.add(o)}})},_addToolbars:function(w,k){var z=this,p,m,r=z.editor,A=z.settings,y,j=r.controlManager,u,l,q=[],x;x=A.theme_advanced_toolbar_align.toLowerCase();x="mce"+z._ufirst(x);l=d.add(d.add(w,"tr"),"td",{"class":"mceToolbar "+x});if(!r.getParam("accessibility_focus")){q.push(d.createHTML("a",{href:"#",onfocus:"tinyMCE.get('"+r.id+"').focus();"},""))}q.push(d.createHTML("a",{href:"#",accesskey:"q",title:r.getLang("advanced.toolbar_focus")},""));for(p=1;(y=A["theme_advanced_buttons"+p]);p++){m=j.createToolbar("toolbar"+p,{"class":"mceToolbarRow"+p});if(A["theme_advanced_buttons"+p+"_add"]){y+=","+A["theme_advanced_buttons"+p+"_add"]}if(A["theme_advanced_buttons"+p+"_add_before"]){y=A["theme_advanced_buttons"+p+"_add_before"]+","+y}z._addControls(y,m);q.push(m.renderHTML());k.deltaHeight-=A.theme_advanced_row_height}q.push(d.createHTML("a",{href:"#",accesskey:"z",title:r.getLang("advanced.toolbar_focus"),onfocus:"tinyMCE.getInstanceById('"+r.id+"').focus();"},""));d.setHTML(l,q.join(""))},_addStatusBar:function(m,j){var k,v=this,p=v.editor,w=v.settings,i,q,u,l;k=d.add(m,"tr");k=l=d.add(k,"td",{"class":"mceStatusbar"});k=d.add(k,"div",{id:p.id+"_path_row"},w.theme_advanced_path?p.translate("advanced.path")+": ":" ");d.add(k,"a",{href:"#",accesskey:"x"});if(w.theme_advanced_resizing){d.add(l,"a",{id:p.id+"_resize",href:"javascript:;",onclick:"return false;","class":"mceResize"});if(w.theme_advanced_resizing_use_cookie){p.onPostRender.add(function(){var n=a.getHash("TinyMCE_"+p.id+"_size"),r=d.get(p.id+"_tbl");if(!n){return}if(w.theme_advanced_resize_horizontal){r.style.width=Math.max(10,n.cw)+"px"}r.style.height=Math.max(10,n.ch)+"px";d.get(p.id+"_ifr").style.height=Math.max(10,parseInt(n.ch)+v.deltaHeight)+"px"})}p.onPostRender.add(function(){b.add(p.id+"_resize","mousedown",function(x){var z,t,o,s,y,r;z=d.get(p.id+"_tbl");o=z.clientWidth;s=z.clientHeight;miw=w.theme_advanced_resizing_min_width||100;mih=w.theme_advanced_resizing_min_height||100;maw=w.theme_advanced_resizing_max_width||65535;mah=w.theme_advanced_resizing_max_height||65535;t=d.add(d.get(p.id+"_parent"),"div",{"class":"mcePlaceHolder"});d.setStyles(t,{width:o,height:s});d.hide(z);d.show(t);i={x:x.screenX,y:x.screenY,w:o,h:s,dx:null,dy:null};q=b.add(d.doc,"mousemove",function(B){var n,A;i.dx=B.screenX-i.x;i.dy=B.screenY-i.y;n=Math.max(miw,i.w+i.dx);A=Math.max(mih,i.h+i.dy);n=Math.min(maw,n);A=Math.min(mah,A);if(w.theme_advanced_resize_horizontal){t.style.width=n+"px"}t.style.height=A+"px";return b.cancel(B)});u=b.add(d.doc,"mouseup",function(n){var A;b.remove(d.doc,"mousemove",q);b.remove(d.doc,"mouseup",u);z.style.display="";d.remove(t);if(i.dx===null){return}A=d.get(p.id+"_ifr");if(w.theme_advanced_resize_horizontal){z.style.width=Math.max(10,i.w+i.dx)+"px"}z.style.height=Math.max(10,i.h+i.dy)+"px";A.style.height=Math.max(10,A.clientHeight+i.dy)+"px";if(w.theme_advanced_resizing_use_cookie){a.setHash("TinyMCE_"+p.id+"_size",{cw:i.w+i.dx,ch:i.h+i.dy})}});return b.cancel(x)})})}j.deltaHeight-=21;k=m=null},_nodeChanged:function(l,u,k,q){var y=this,i,r=0,x,m,z=y.settings,w,j,o;if(z.readonly){return}e.each(y.stateControls,function(n){u.setActive(n,l.queryCommandState(y.controls[n][1]))});u.setActive("visualaid",l.hasVisual);u.setDisabled("undo",!l.undoManager.hasUndo()&&!l.typing);u.setDisabled("redo",!l.undoManager.hasRedo());u.setDisabled("outdent",!l.queryCommandState("Outdent"));i=d.getParent(k,"A");if(m=u.get("link")){if(!i||!i.name){m.setDisabled(!i&&q);m.setActive(!!i)}}if(m=u.get("unlink")){m.setDisabled(!i&&q);m.setActive(!!i&&!i.name)}if(m=u.get("anchor")){m.setActive(!!i&&i.name);if(e.isWebKit){i=d.getParent(k,"IMG");m.setActive(!!i&&d.getAttrib(i,"mce_name")=="a")}}i=d.getParent(k,"IMG");if(m=u.get("image")){m.setActive(!!i&&k.className.indexOf("mceItem")==-1)}if(m=u.get("styleselect")){if(k.className){y._importClasses();m.select(k.className)}else{m.select()}}if(m=u.get("formatselect")){i=d.getParent(k,d.isBlock);if(i){m.select(i.nodeName.toLowerCase())}}if(l.settings.convert_fonts_to_spans){l.dom.getParent(k,function(p){if(p.nodeName==="SPAN"){if(!w&&p.className){w=p.className}if(!j&&p.style.fontSize){j=p.style.fontSize}if(!o&&p.style.fontFamily){o=p.style.fontFamily.replace(/[\"\']+/g,"").replace(/^([^,]+).*/,"$1").toLowerCase()}}return false});if(m=u.get("fontselect")){m.select(function(n){return n.replace(/^([^,]+).*/,"$1").toLowerCase()==o})}if(m=u.get("fontsizeselect")){m.select(function(n){if(n.fontSize&&n.fontSize===j){return true}if(n["class"]&&n["class"]===w){return true}})}}else{if(m=u.get("fontselect")){m.select(l.queryCommandValue("FontName"))}if(m=u.get("fontsizeselect")){x=l.queryCommandValue("FontSize");m.select(function(n){return n.fontSize==x})}}if(z.theme_advanced_path&&z.theme_advanced_statusbar_location){i=d.get(l.id+"_path")||d.add(l.id+"_path_row","span",{id:l.id+"_path"});d.setHTML(i,"");l.dom.getParent(k,function(A){var p=A.nodeName.toLowerCase(),s,v,t="";if(A.nodeType!=1||A.nodeName==="BR"||(d.hasClass(A,"mceItemHidden")||d.hasClass(A,"mceItemRemoved"))){return}if(x=d.getAttrib(A,"mce_name")){p=x}if(e.isIE&&A.scopeName!=="HTML"){p=A.scopeName+":"+p}p=p.replace(/mce\:/g,"");switch(p){case"b":p="strong";break;case"i":p="em";break;case"img":if(x=d.getAttrib(A,"src")){t+="src: "+x+" "}break;case"a":if(x=d.getAttrib(A,"name")){t+="name: "+x+" ";p+="#"+x}if(x=d.getAttrib(A,"href")){t+="href: "+x+" "}break;case"font":if(z.convert_fonts_to_spans){p="span"}if(x=d.getAttrib(A,"face")){t+="font: "+x+" "}if(x=d.getAttrib(A,"size")){t+="size: "+x+" "}if(x=d.getAttrib(A,"color")){t+="color: "+x+" "}break;case"span":if(x=d.getAttrib(A,"style")){t+="style: "+x+" "}break}if(x=d.getAttrib(A,"id")){t+="id: "+x+" "}if(x=A.className){x=x.replace(/(webkit-[\w\-]+|Apple-[\w\-]+|mceItem\w+|mceVisualAid)/g,"");if(x&&x.indexOf("mceItem")==-1){t+="class: "+x+" ";if(d.isBlock(A)||p=="img"||p=="span"){p+="."+x}}}p=p.replace(/(html:)/g,"");p={name:p,node:A,title:t};y.onResolveName.dispatch(y,p);t=p.title;p=p.name;v=d.create("a",{href:"javascript:;",onmousedown:"return false;",title:t,"class":"mcePath_"+(r++)},p);if(i.hasChildNodes()){i.insertBefore(d.doc.createTextNode(" \u00bb "),i.firstChild);i.insertBefore(v,i.firstChild)}else{i.appendChild(v)}},l.getBody())}},_sel:function(i){this.editor.execCommand("mceSelectNodeDepth",false,i)},_mceInsertAnchor:function(k,j){var i=this.editor;i.windowManager.open({url:e.baseURL+"/themes/advanced/anchor.htm",width:320+parseInt(i.getLang("advanced.anchor_delta_width",0)),height:90+parseInt(i.getLang("advanced.anchor_delta_height",0)),inline:true},{theme_url:this.url})},_mceCharMap:function(){var i=this.editor;i.windowManager.open({url:e.baseURL+"/themes/advanced/charmap.htm",width:550+parseInt(i.getLang("advanced.charmap_delta_width",0)),height:250+parseInt(i.getLang("advanced.charmap_delta_height",0)),inline:true},{theme_url:this.url})},_mceHelp:function(){var i=this.editor;i.windowManager.open({url:e.baseURL+"/themes/advanced/about.htm",width:480,height:380,inline:true},{theme_url:this.url})},_mceColorPicker:function(k,j){var i=this.editor;j=j||{};i.windowManager.open({url:e.baseURL+"/themes/advanced/color_picker.htm",width:375+parseInt(i.getLang("advanced.colorpicker_delta_width",0)),height:250+parseInt(i.getLang("advanced.colorpicker_delta_height",0)),close_previous:false,inline:true},{input_color:j.color,func:j.func,theme_url:this.url})},_mceCodeEditor:function(j,k){var i=this.editor;i.windowManager.open({url:e.baseURL+"/themes/advanced/source_editor.htm",width:parseInt(i.getParam("theme_advanced_source_editor_width",720)),height:parseInt(i.getParam("theme_advanced_source_editor_height",580)),inline:true,resizable:true,maximizable:true},{theme_url:this.url})},_mceImage:function(j,k){var i=this.editor;if(i.dom.getAttrib(i.selection.getNode(),"class").indexOf("mceItem")!=-1){return}i.windowManager.open({url:e.baseURL+"/themes/advanced/image.htm",width:355+parseInt(i.getLang("advanced.image_delta_width",0)),height:275+parseInt(i.getLang("advanced.image_delta_height",0)),inline:true},{theme_url:this.url})},_mceLink:function(j,k){var i=this.editor;i.windowManager.open({url:e.baseURL+"/themes/advanced/link.htm",width:310+parseInt(i.getLang("advanced.link_delta_width",0)),height:200+parseInt(i.getLang("advanced.link_delta_height",0)),inline:true},{theme_url:this.url})},_mceNewDocument:function(){var i=this.editor;i.windowManager.confirm("advanced.newdocument",function(j){if(j){i.execCommand("mceSetContent",false,"")}})},_mceForeColor:function(){var i=this;this._mceColorPicker(0,{color:i.fgColor,func:function(j){i.fgColor=j;i.editor.execCommand("ForeColor",false,j)}})},_mceBackColor:function(){var i=this;this._mceColorPicker(0,{color:i.bgColor,func:function(j){i.bgColor=j;i.editor.execCommand("HiliteColor",false,j)}})},_ufirst:function(i){return i.substring(0,1).toUpperCase()+i.substring(1)}});e.ThemeManager.add("advanced",e.themes.AdvancedTheme)}(tinymce)); \ No newline at end of file diff --git a/wp-includes/js/tinymce/themes/advanced/image.htm b/wp-includes/js/tinymce/themes/advanced/image.htm new file mode 100644 index 0000000..487227b --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/image.htm @@ -0,0 +1,89 @@ + + + + {#advanced_dlg.image_title} + + + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +
     
    + x +
    +
    +
    + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/themes/advanced/img/colorpicker.jpg b/wp-includes/js/tinymce/themes/advanced/img/colorpicker.jpg new file mode 100644 index 0000000..b4c542d Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/img/colorpicker.jpg differ diff --git a/wp-includes/js/tinymce/themes/advanced/img/fm.gif b/wp-includes/js/tinymce/themes/advanced/img/fm.gif new file mode 100644 index 0000000..b5f022b Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/img/fm.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/img/gotmoxie.png b/wp-includes/js/tinymce/themes/advanced/img/gotmoxie.png new file mode 100644 index 0000000..8a396e0 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/img/gotmoxie.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/img/icons.gif b/wp-includes/js/tinymce/themes/advanced/img/icons.gif new file mode 100644 index 0000000..ccac36f Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/img/icons.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/img/sflogo.png b/wp-includes/js/tinymce/themes/advanced/img/sflogo.png new file mode 100644 index 0000000..142a6f9 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/img/sflogo.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/js/about.js b/wp-includes/js/tinymce/themes/advanced/js/about.js new file mode 100644 index 0000000..7fc8ba2 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/js/about.js @@ -0,0 +1,72 @@ +tinyMCEPopup.requireLangPack(); + +function init() { + var ed, tcont; + + tinyMCEPopup.resizeToInnerSize(); + ed = tinyMCEPopup.editor; + + // Give FF some time + window.setTimeout(insertHelpIFrame, 10); + + tcont = document.getElementById('plugintablecontainer'); + document.getElementById('plugins_tab').style.display = 'none'; + + var html = ""; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + + tinymce.each(ed.plugins, function(p, n) { + var info; + + if (!p.getInfo) + return; + + html += ''; + + info = p.getInfo(); + + if (info.infourl != null && info.infourl != '') + html += ''; + else + html += ''; + + if (info.authorurl != null && info.authorurl != '') + html += ''; + else + html += ''; + + html += ''; + html += ''; + + document.getElementById('plugins_tab').style.display = ''; + + }); + + html += ''; + html += '
    ' + ed.getLang('advanced_dlg.about_plugin') + '' + ed.getLang('advanced_dlg.about_author') + '' + ed.getLang('advanced_dlg.about_version') + '
    ' + info.longname + '' + info.longname + '' + info.author + '' + info.author + '' + info.version + '
    '; + + tcont.innerHTML = html; + + tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion; + tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate; +} + +function insertHelpIFrame() { + var html; + + if (tinyMCEPopup.getParam('docs_url')) { + html = ''; + document.getElementById('iframecontainer').innerHTML = html; + document.getElementById('help_tab').style.display = 'block'; + } +} + +tinyMCEPopup.onInit.add(init); diff --git a/wp-includes/js/tinymce/themes/advanced/js/anchor.js b/wp-includes/js/tinymce/themes/advanced/js/anchor.js new file mode 100644 index 0000000..76f4f7d --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/js/anchor.js @@ -0,0 +1,37 @@ +tinyMCEPopup.requireLangPack(); + +var AnchorDialog = { + init : function(ed) { + var action, elm, f = document.forms[0]; + + this.editor = ed; + elm = ed.dom.getParent(ed.selection.getNode(), 'A,IMG'); + v = ed.dom.getAttrib(elm, 'name'); + + if (v) { + this.action = 'update'; + f.anchorName.value = v; + } + + f.insert.value = ed.getLang(elm ? 'update' : 'insert'); + }, + + update : function() { + var ed = this.editor; + + tinyMCEPopup.restoreSelection(); + + if (this.action != 'update') + ed.selection.collapse(1); + + // Webkit acts weird if empty inline element is inserted so we need to use a image instead + if (tinymce.isWebKit) + ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('img', {mce_name : 'a', name : document.forms[0].anchorName.value, 'class' : 'mceItemAnchor'})); + else + ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', {name : document.forms[0].anchorName.value, 'class' : 'mceItemAnchor'}, '')); + + tinyMCEPopup.close(); + } +}; + +tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog); diff --git a/wp-includes/js/tinymce/themes/advanced/js/charmap.js b/wp-includes/js/tinymce/themes/advanced/js/charmap.js new file mode 100644 index 0000000..d9fd8d3 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/js/charmap.js @@ -0,0 +1,325 @@ +tinyMCEPopup.requireLangPack(); + +var charmap = [ + [' ', ' ', true, 'no-break space'], + ['&', '&', true, 'ampersand'], + ['"', '"', true, 'quotation mark'], +// finance + ['¢', '¢', true, 'cent sign'], + ['€', '€', true, 'euro sign'], + ['£', '£', true, 'pound sign'], + ['¥', '¥', true, 'yen sign'], +// signs + ['©', '©', true, 'copyright sign'], + ['®', '®', true, 'registered sign'], + ['™', '™', true, 'trade mark sign'], + ['‰', '‰', true, 'per mille sign'], + ['µ', 'µ', true, 'micro sign'], + ['·', '·', true, 'middle dot'], + ['•', '•', true, 'bullet'], + ['…', '…', true, 'three dot leader'], + ['′', '′', true, 'minutes / feet'], + ['″', '″', true, 'seconds / inches'], + ['§', '§', true, 'section sign'], + ['¶', '¶', true, 'paragraph sign'], + ['ß', 'ß', true, 'sharp s / ess-zed'], +// quotations + ['‹', '‹', true, 'single left-pointing angle quotation mark'], + ['›', '›', true, 'single right-pointing angle quotation mark'], + ['«', '«', true, 'left pointing guillemet'], + ['»', '»', true, 'right pointing guillemet'], + ['‘', '‘', true, 'left single quotation mark'], + ['’', '’', true, 'right single quotation mark'], + ['“', '“', true, 'left double quotation mark'], + ['”', '”', true, 'right double quotation mark'], + ['‚', '‚', true, 'single low-9 quotation mark'], + ['„', '„', true, 'double low-9 quotation mark'], + ['<', '<', true, 'less-than sign'], + ['>', '>', true, 'greater-than sign'], + ['≤', '≤', true, 'less-than or equal to'], + ['≥', '≥', true, 'greater-than or equal to'], + ['–', '–', true, 'en dash'], + ['—', '—', true, 'em dash'], + ['¯', '¯', true, 'macron'], + ['‾', '‾', true, 'overline'], + ['¤', '¤', true, 'currency sign'], + ['¦', '¦', true, 'broken bar'], + ['¨', '¨', true, 'diaeresis'], + ['¡', '¡', true, 'inverted exclamation mark'], + ['¿', '¿', true, 'turned question mark'], + ['ˆ', 'ˆ', true, 'circumflex accent'], + ['˜', '˜', true, 'small tilde'], + ['°', '°', true, 'degree sign'], + ['−', '−', true, 'minus sign'], + ['±', '±', true, 'plus-minus sign'], + ['÷', '÷', true, 'division sign'], + ['⁄', '⁄', true, 'fraction slash'], + ['×', '×', true, 'multiplication sign'], + ['¹', '¹', true, 'superscript one'], + ['²', '²', true, 'superscript two'], + ['³', '³', true, 'superscript three'], + ['¼', '¼', true, 'fraction one quarter'], + ['½', '½', true, 'fraction one half'], + ['¾', '¾', true, 'fraction three quarters'], +// math / logical + ['ƒ', 'ƒ', true, 'function / florin'], + ['∫', '∫', true, 'integral'], + ['∑', '∑', true, 'n-ary sumation'], + ['∞', '∞', true, 'infinity'], + ['√', '√', true, 'square root'], + ['∼', '∼', false,'similar to'], + ['≅', '≅', false,'approximately equal to'], + ['≈', '≈', true, 'almost equal to'], + ['≠', '≠', true, 'not equal to'], + ['≡', '≡', true, 'identical to'], + ['∈', '∈', false,'element of'], + ['∉', '∉', false,'not an element of'], + ['∋', '∋', false,'contains as member'], + ['∏', '∏', true, 'n-ary product'], + ['∧', '∧', false,'logical and'], + ['∨', '∨', false,'logical or'], + ['¬', '¬', true, 'not sign'], + ['∩', '∩', true, 'intersection'], + ['∪', '∪', false,'union'], + ['∂', '∂', true, 'partial differential'], + ['∀', '∀', false,'for all'], + ['∃', '∃', false,'there exists'], + ['∅', '∅', false,'diameter'], + ['∇', '∇', false,'backward difference'], + ['∗', '∗', false,'asterisk operator'], + ['∝', '∝', false,'proportional to'], + ['∠', '∠', false,'angle'], +// undefined + ['´', '´', true, 'acute accent'], + ['¸', '¸', true, 'cedilla'], + ['ª', 'ª', true, 'feminine ordinal indicator'], + ['º', 'º', true, 'masculine ordinal indicator'], + ['†', '†', true, 'dagger'], + ['‡', '‡', true, 'double dagger'], +// alphabetical special chars + ['À', 'À', true, 'A - grave'], + ['Á', 'Á', true, 'A - acute'], + ['Â', 'Â', true, 'A - circumflex'], + ['Ã', 'Ã', true, 'A - tilde'], + ['Ä', 'Ä', true, 'A - diaeresis'], + ['Å', 'Å', true, 'A - ring above'], + ['Æ', 'Æ', true, 'ligature AE'], + ['Ç', 'Ç', true, 'C - cedilla'], + ['È', 'È', true, 'E - grave'], + ['É', 'É', true, 'E - acute'], + ['Ê', 'Ê', true, 'E - circumflex'], + ['Ë', 'Ë', true, 'E - diaeresis'], + ['Ì', 'Ì', true, 'I - grave'], + ['Í', 'Í', true, 'I - acute'], + ['Î', 'Î', true, 'I - circumflex'], + ['Ï', 'Ï', true, 'I - diaeresis'], + ['Ð', 'Ð', true, 'ETH'], + ['Ñ', 'Ñ', true, 'N - tilde'], + ['Ò', 'Ò', true, 'O - grave'], + ['Ó', 'Ó', true, 'O - acute'], + ['Ô', 'Ô', true, 'O - circumflex'], + ['Õ', 'Õ', true, 'O - tilde'], + ['Ö', 'Ö', true, 'O - diaeresis'], + ['Ø', 'Ø', true, 'O - slash'], + ['Œ', 'Œ', true, 'ligature OE'], + ['Š', 'Š', true, 'S - caron'], + ['Ù', 'Ù', true, 'U - grave'], + ['Ú', 'Ú', true, 'U - acute'], + ['Û', 'Û', true, 'U - circumflex'], + ['Ü', 'Ü', true, 'U - diaeresis'], + ['Ý', 'Ý', true, 'Y - acute'], + ['Ÿ', 'Ÿ', true, 'Y - diaeresis'], + ['Þ', 'Þ', true, 'THORN'], + ['à', 'à', true, 'a - grave'], + ['á', 'á', true, 'a - acute'], + ['â', 'â', true, 'a - circumflex'], + ['ã', 'ã', true, 'a - tilde'], + ['ä', 'ä', true, 'a - diaeresis'], + ['å', 'å', true, 'a - ring above'], + ['æ', 'æ', true, 'ligature ae'], + ['ç', 'ç', true, 'c - cedilla'], + ['è', 'è', true, 'e - grave'], + ['é', 'é', true, 'e - acute'], + ['ê', 'ê', true, 'e - circumflex'], + ['ë', 'ë', true, 'e - diaeresis'], + ['ì', 'ì', true, 'i - grave'], + ['í', 'í', true, 'i - acute'], + ['î', 'î', true, 'i - circumflex'], + ['ï', 'ï', true, 'i - diaeresis'], + ['ð', 'ð', true, 'eth'], + ['ñ', 'ñ', true, 'n - tilde'], + ['ò', 'ò', true, 'o - grave'], + ['ó', 'ó', true, 'o - acute'], + ['ô', 'ô', true, 'o - circumflex'], + ['õ', 'õ', true, 'o - tilde'], + ['ö', 'ö', true, 'o - diaeresis'], + ['ø', 'ø', true, 'o slash'], + ['œ', 'œ', true, 'ligature oe'], + ['š', 'š', true, 's - caron'], + ['ù', 'ù', true, 'u - grave'], + ['ú', 'ú', true, 'u - acute'], + ['û', 'û', true, 'u - circumflex'], + ['ü', 'ü', true, 'u - diaeresis'], + ['ý', 'ý', true, 'y - acute'], + ['þ', 'þ', true, 'thorn'], + ['ÿ', 'ÿ', true, 'y - diaeresis'], + ['Α', 'Α', true, 'Alpha'], + ['Β', 'Β', true, 'Beta'], + ['Γ', 'Γ', true, 'Gamma'], + ['Δ', 'Δ', true, 'Delta'], + ['Ε', 'Ε', true, 'Epsilon'], + ['Ζ', 'Ζ', true, 'Zeta'], + ['Η', 'Η', true, 'Eta'], + ['Θ', 'Θ', true, 'Theta'], + ['Ι', 'Ι', true, 'Iota'], + ['Κ', 'Κ', true, 'Kappa'], + ['Λ', 'Λ', true, 'Lambda'], + ['Μ', 'Μ', true, 'Mu'], + ['Ν', 'Ν', true, 'Nu'], + ['Ξ', 'Ξ', true, 'Xi'], + ['Ο', 'Ο', true, 'Omicron'], + ['Π', 'Π', true, 'Pi'], + ['Ρ', 'Ρ', true, 'Rho'], + ['Σ', 'Σ', true, 'Sigma'], + ['Τ', 'Τ', true, 'Tau'], + ['Υ', 'Υ', true, 'Upsilon'], + ['Φ', 'Φ', true, 'Phi'], + ['Χ', 'Χ', true, 'Chi'], + ['Ψ', 'Ψ', true, 'Psi'], + ['Ω', 'Ω', true, 'Omega'], + ['α', 'α', true, 'alpha'], + ['β', 'β', true, 'beta'], + ['γ', 'γ', true, 'gamma'], + ['δ', 'δ', true, 'delta'], + ['ε', 'ε', true, 'epsilon'], + ['ζ', 'ζ', true, 'zeta'], + ['η', 'η', true, 'eta'], + ['θ', 'θ', true, 'theta'], + ['ι', 'ι', true, 'iota'], + ['κ', 'κ', true, 'kappa'], + ['λ', 'λ', true, 'lambda'], + ['μ', 'μ', true, 'mu'], + ['ν', 'ν', true, 'nu'], + ['ξ', 'ξ', true, 'xi'], + ['ο', 'ο', true, 'omicron'], + ['π', 'π', true, 'pi'], + ['ρ', 'ρ', true, 'rho'], + ['ς', 'ς', true, 'final sigma'], + ['σ', 'σ', true, 'sigma'], + ['τ', 'τ', true, 'tau'], + ['υ', 'υ', true, 'upsilon'], + ['φ', 'φ', true, 'phi'], + ['χ', 'χ', true, 'chi'], + ['ψ', 'ψ', true, 'psi'], + ['ω', 'ω', true, 'omega'], +// symbols + ['ℵ', 'ℵ', false,'alef symbol'], + ['ϖ', 'ϖ', false,'pi symbol'], + ['ℜ', 'ℜ', false,'real part symbol'], + ['ϑ','ϑ', false,'theta symbol'], + ['ϒ', 'ϒ', false,'upsilon - hook symbol'], + ['℘', '℘', false,'Weierstrass p'], + ['ℑ', 'ℑ', false,'imaginary part'], +// arrows + ['←', '←', true, 'leftwards arrow'], + ['↑', '↑', true, 'upwards arrow'], + ['→', '→', true, 'rightwards arrow'], + ['↓', '↓', true, 'downwards arrow'], + ['↔', '↔', true, 'left right arrow'], + ['↵', '↵', false,'carriage return'], + ['⇐', '⇐', false,'leftwards double arrow'], + ['⇑', '⇑', false,'upwards double arrow'], + ['⇒', '⇒', false,'rightwards double arrow'], + ['⇓', '⇓', false,'downwards double arrow'], + ['⇔', '⇔', false,'left right double arrow'], + ['∴', '∴', false,'therefore'], + ['⊂', '⊂', false,'subset of'], + ['⊃', '⊃', false,'superset of'], + ['⊄', '⊄', false,'not a subset of'], + ['⊆', '⊆', false,'subset of or equal to'], + ['⊇', '⊇', false,'superset of or equal to'], + ['⊕', '⊕', false,'circled plus'], + ['⊗', '⊗', false,'circled times'], + ['⊥', '⊥', false,'perpendicular'], + ['⋅', '⋅', false,'dot operator'], + ['⌈', '⌈', false,'left ceiling'], + ['⌉', '⌉', false,'right ceiling'], + ['⌊', '⌊', false,'left floor'], + ['⌋', '⌋', false,'right floor'], + ['⟨', '〈', false,'left-pointing angle bracket'], + ['⟩', '〉', false,'right-pointing angle bracket'], + ['◊', '◊', true,'lozenge'], + ['♠', '♠', false,'black spade suit'], + ['♣', '♣', true, 'black club suit'], + ['♥', '♥', true, 'black heart suit'], + ['♦', '♦', true, 'black diamond suit'], + [' ', ' ', false,'en space'], + [' ', ' ', false,'em space'], + [' ', ' ', false,'thin space'], + ['‌', '‌', false,'zero width non-joiner'], + ['‍', '‍', false,'zero width joiner'], + ['‎', '‎', false,'left-to-right mark'], + ['‏', '‏', false,'right-to-left mark'], + ['­', '­', false,'soft hyphen'] +]; + +tinyMCEPopup.onInit.add(function() { + tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML()); +}); + +function renderCharMapHTML() { + var charsPerRow = 20, tdWidth=20, tdHeight=20, i; + var html = ''; + var cols=-1; + + for (i=0; i' + + '' + + charmap[i][1] + + ''; + if ((cols+1) % charsPerRow == 0) + html += ''; + } + } + + if (cols % charsPerRow > 0) { + var padd = charsPerRow - (cols % charsPerRow); + for (var i=0; i '; + } + + html += '
    '; + + return html; +} + +function insertChar(chr) { + tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';'); + + // Refocus in window + if (tinyMCEPopup.isWindow) + window.focus(); + + tinyMCEPopup.editor.focus(); + tinyMCEPopup.close(); +} + +function previewChar(codeA, codeB, codeN) { + var elmA = document.getElementById('codeA'); + var elmB = document.getElementById('codeB'); + var elmV = document.getElementById('codeV'); + var elmN = document.getElementById('codeN'); + + if (codeA=='#160;') { + elmV.innerHTML = '__'; + } else { + elmV.innerHTML = '&' + codeA; + } + + elmB.innerHTML = '&' + codeA; + elmA.innerHTML = '&' + codeB; + elmN.innerHTML = codeN; +} diff --git a/wp-includes/js/tinymce/themes/advanced/js/color_picker.js b/wp-includes/js/tinymce/themes/advanced/js/color_picker.js new file mode 100644 index 0000000..c1a65db --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/js/color_picker.js @@ -0,0 +1,253 @@ +tinyMCEPopup.requireLangPack(); + +var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false; + +var colors = [ + "#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033", + "#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099", + "#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff", + "#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033", + "#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399", + "#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff", + "#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333", + "#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399", + "#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff", + "#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633", + "#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699", + "#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff", + "#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633", + "#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999", + "#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff", + "#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933", + "#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999", + "#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff", + "#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33", + "#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99", + "#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff", + "#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33", + "#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99", + "#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff", + "#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33", + "#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99", + "#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff" +]; + +var named = { + '#F0F8FF':'AliceBlue','#FAEBD7':'AntiqueWhite','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige', + '#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'BlanchedAlmond','#0000FF':'Blue','#8A2BE2':'BlueViolet','#A52A2A':'Brown', + '#DEB887':'BurlyWood','#5F9EA0':'CadetBlue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'CornflowerBlue', + '#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'DarkBlue','#008B8B':'DarkCyan','#B8860B':'DarkGoldenRod', + '#A9A9A9':'DarkGray','#A9A9A9':'DarkGrey','#006400':'DarkGreen','#BDB76B':'DarkKhaki','#8B008B':'DarkMagenta','#556B2F':'DarkOliveGreen', + '#FF8C00':'Darkorange','#9932CC':'DarkOrchid','#8B0000':'DarkRed','#E9967A':'DarkSalmon','#8FBC8F':'DarkSeaGreen','#483D8B':'DarkSlateBlue', + '#2F4F4F':'DarkSlateGray','#2F4F4F':'DarkSlateGrey','#00CED1':'DarkTurquoise','#9400D3':'DarkViolet','#FF1493':'DeepPink','#00BFFF':'DeepSkyBlue', + '#696969':'DimGray','#696969':'DimGrey','#1E90FF':'DodgerBlue','#B22222':'FireBrick','#FFFAF0':'FloralWhite','#228B22':'ForestGreen', + '#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'GhostWhite','#FFD700':'Gold','#DAA520':'GoldenRod','#808080':'Gray','#808080':'Grey', + '#008000':'Green','#ADFF2F':'GreenYellow','#F0FFF0':'HoneyDew','#FF69B4':'HotPink','#CD5C5C':'IndianRed','#4B0082':'Indigo','#FFFFF0':'Ivory', + '#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'LavenderBlush','#7CFC00':'LawnGreen','#FFFACD':'LemonChiffon','#ADD8E6':'LightBlue', + '#F08080':'LightCoral','#E0FFFF':'LightCyan','#FAFAD2':'LightGoldenRodYellow','#D3D3D3':'LightGray','#D3D3D3':'LightGrey','#90EE90':'LightGreen', + '#FFB6C1':'LightPink','#FFA07A':'LightSalmon','#20B2AA':'LightSeaGreen','#87CEFA':'LightSkyBlue','#778899':'LightSlateGray','#778899':'LightSlateGrey', + '#B0C4DE':'LightSteelBlue','#FFFFE0':'LightYellow','#00FF00':'Lime','#32CD32':'LimeGreen','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon', + '#66CDAA':'MediumAquaMarine','#0000CD':'MediumBlue','#BA55D3':'MediumOrchid','#9370D8':'MediumPurple','#3CB371':'MediumSeaGreen','#7B68EE':'MediumSlateBlue', + '#00FA9A':'MediumSpringGreen','#48D1CC':'MediumTurquoise','#C71585':'MediumVioletRed','#191970':'MidnightBlue','#F5FFFA':'MintCream','#FFE4E1':'MistyRose','#FFE4B5':'Moccasin', + '#FFDEAD':'NavajoWhite','#000080':'Navy','#FDF5E6':'OldLace','#808000':'Olive','#6B8E23':'OliveDrab','#FFA500':'Orange','#FF4500':'OrangeRed','#DA70D6':'Orchid', + '#EEE8AA':'PaleGoldenRod','#98FB98':'PaleGreen','#AFEEEE':'PaleTurquoise','#D87093':'PaleVioletRed','#FFEFD5':'PapayaWhip','#FFDAB9':'PeachPuff', + '#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'PowderBlue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'RosyBrown','#4169E1':'RoyalBlue', + '#8B4513':'SaddleBrown','#FA8072':'Salmon','#F4A460':'SandyBrown','#2E8B57':'SeaGreen','#FFF5EE':'SeaShell','#A0522D':'Sienna','#C0C0C0':'Silver', + '#87CEEB':'SkyBlue','#6A5ACD':'SlateBlue','#708090':'SlateGray','#708090':'SlateGrey','#FFFAFA':'Snow','#00FF7F':'SpringGreen', + '#4682B4':'SteelBlue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet', + '#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'WhiteSmoke','#FFFF00':'Yellow','#9ACD32':'YellowGreen' +}; + +function init() { + var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')); + + tinyMCEPopup.resizeToInnerSize(); + + generatePicker(); + + if (inputColor) { + changeFinalColor(inputColor); + + col = convertHexToRGB(inputColor); + + if (col) + updateLight(col.r, col.g, col.b); + } +} + +function insertAction() { + var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func'); + + tinyMCEPopup.restoreSelection(); + + if (f) + f(color); + + tinyMCEPopup.close(); +} + +function showColor(color, name) { + if (name) + document.getElementById("colorname").innerHTML = name; + + document.getElementById("preview").style.backgroundColor = color; + document.getElementById("color").value = color.toLowerCase(); +} + +function convertRGBToHex(col) { + var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); + + if (!col) + return col; + + var rgb = col.replace(re, "$1,$2,$3").split(','); + if (rgb.length == 3) { + r = parseInt(rgb[0]).toString(16); + g = parseInt(rgb[1]).toString(16); + b = parseInt(rgb[2]).toString(16); + + r = r.length == 1 ? '0' + r : r; + g = g.length == 1 ? '0' + g : g; + b = b.length == 1 ? '0' + b : b; + + return "#" + r + g + b; + } + + return col; +} + +function convertHexToRGB(col) { + if (col.indexOf('#') != -1) { + col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); + + r = parseInt(col.substring(0, 2), 16); + g = parseInt(col.substring(2, 4), 16); + b = parseInt(col.substring(4, 6), 16); + + return {r : r, g : g, b : b}; + } + + return null; +} + +function generatePicker() { + var el = document.getElementById('light'), h = '', i; + + for (i = 0; i < detail; i++){ + h += '
    '; + } + + el.innerHTML = h; +} + +function generateWebColors() { + var el = document.getElementById('webcolors'), h = '', i; + + if (el.className == 'generated') + return; + + h += '' + + ''; + + for (i=0; i' + + '' + + ''; + if ((i+1) % 18 == 0) + h += ''; + } + + h += '
    '; + + el.innerHTML = h; + el.className = 'generated'; +} + +function generateNamedColors() { + var el = document.getElementById('namedcolors'), h = '', n, v, i = 0; + + if (el.className == 'generated') + return; + + for (n in named) { + v = named[n]; + h += '' + } + + el.innerHTML = h; + el.className = 'generated'; +} + +function dechex(n) { + return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16); +} + +function computeColor(e) { + var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB; + + x = e.offsetX ? e.offsetX : (e.target ? e.clientX - e.target.x : 0); + y = e.offsetY ? e.offsetY : (e.target ? e.clientY - e.target.y : 0); + + partWidth = document.getElementById('colors').width / 6; + partDetail = detail / 2; + imHeight = document.getElementById('colors').height; + + r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255; + g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth); + b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth); + + coef = (imHeight - y) / imHeight; + r = 128 + (r - 128) * coef; + g = 128 + (g - 128) * coef; + b = 128 + (b - 128) * coef; + + changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b)); + updateLight(r, g, b); +} + +function updateLight(r, g, b) { + var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color; + + for (i=0; i=0) && (i'); + }, + + init : function() { + var f = document.forms[0], ed = tinyMCEPopup.editor; + + // Setup browse button + document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); + if (isVisible('srcbrowser')) + document.getElementById('src').style.width = '180px'; + + e = ed.selection.getNode(); + + this.fillFileList('image_list', 'tinyMCEImageList'); + + if (e.nodeName == 'IMG') { + f.src.value = ed.dom.getAttrib(e, 'src'); + f.alt.value = ed.dom.getAttrib(e, 'alt'); + f.border.value = this.getAttrib(e, 'border'); + f.vspace.value = this.getAttrib(e, 'vspace'); + f.hspace.value = this.getAttrib(e, 'hspace'); + f.width.value = ed.dom.getAttrib(e, 'width'); + f.height.value = ed.dom.getAttrib(e, 'height'); + f.insert.value = ed.getLang('update'); + f.class_name.value = ed.dom.getAttrib(e, 'class'); + this.styleVal = ed.dom.getAttrib(e, 'style'); + selectByValue(f, 'image_list', f.src.value); + selectByValue(f, 'align', this.getAttrib(e, 'align')); + this.updateStyle(); + } + }, + + fillFileList : function(id, l) { + var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; + + l = window[l]; + + if (l && l.length > 0) { + lst.options[lst.options.length] = new Option('', ''); + + tinymce.each(l, function(o) { + lst.options[lst.options.length] = new Option(o[0], o[1]); + }); + } else + dom.remove(dom.getParent(id, 'tr')); + }, + + update : function() { + var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el; + + tinyMCEPopup.restoreSelection(); + + if (f.src.value === '') { + if (ed.selection.getNode().nodeName == 'IMG') { + ed.dom.remove(ed.selection.getNode()); + ed.execCommand('mceRepaint'); + } + + tinyMCEPopup.close(); + return; + } + + if (!ed.settings.inline_styles) { + args = tinymce.extend(args, { + vspace : nl.vspace.value, + hspace : nl.hspace.value, + border : nl.border.value, + align : getSelectValue(f, 'align') + }); + } else + args.style = this.styleVal; + + tinymce.extend(args, { + src : f.src.value, + alt : f.alt.value, + width : f.width.value, + height : f.height.value, + 'class' : f.class_name.value + }); + + el = ed.selection.getNode(); + + if (el && el.nodeName == 'IMG') { + ed.dom.setAttribs(el, args); + } else { + ed.execCommand('mceInsertContent', false, '', {skip_undo : 1}); + ed.dom.setAttribs('__mce_tmp', args); + ed.dom.setAttrib('__mce_tmp', 'id', ''); + ed.undoManager.add(); + } + + tinyMCEPopup.close(); + }, + + updateStyle : function() { + var dom = tinyMCEPopup.dom, st, v, cls, oldcls, rep, f = document.forms[0]; + + if (tinyMCEPopup.editor.settings.inline_styles) { + st = tinyMCEPopup.dom.parseStyle(this.styleVal); + + // Handle align + v = getSelectValue(f, 'align'); + cls = f.class_name.value || ''; + cls = cls ? cls.replace(/alignright\s*|alignleft\s*|aligncenter\s*/g, '') : ''; + cls = cls ? cls.replace(/^\s*(.+?)\s*$/, '$1') : ''; + if (v) { + if (v == 'left' || v == 'right') { + st['float'] = v; + delete st['vertical-align']; + oldcls = cls ? ' '+cls : ''; + f.class_name.value = 'align' + v + oldcls; + } else { + st['vertical-align'] = v; + delete st['float']; + f.class_name.value = cls; + } + } else { + delete st['float']; + delete st['vertical-align']; + f.class_name.value = cls; + } + + // Handle border + v = f.border.value; + if (v || v == '0') { + if (v == '0') + st['border'] = '0'; + else + st['border'] = v + 'px solid black'; + } else + delete st['border']; + + // Handle hspace + v = f.hspace.value; + if (v) { + delete st['margin']; + st['margin-left'] = v + 'px'; + st['margin-right'] = v + 'px'; + } else { + delete st['margin-left']; + delete st['margin-right']; + } + + // Handle vspace + v = f.vspace.value; + if (v) { + delete st['margin']; + st['margin-top'] = v + 'px'; + st['margin-bottom'] = v + 'px'; + } else { + delete st['margin-top']; + delete st['margin-bottom']; + } + + // Merge + st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st)); + this.styleVal = dom.serializeStyle(st); + } + }, + + getAttrib : function(e, at) { + var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; + + if (ed.settings.inline_styles) { + switch (at) { + case 'align': + if (v = dom.getStyle(e, 'float')) + return v; + + if (v = dom.getStyle(e, 'vertical-align')) + return v; + + break; + + case 'hspace': + v = dom.getStyle(e, 'margin-left') + v2 = dom.getStyle(e, 'margin-right'); + if (v && v == v2) + return parseInt(v.replace(/[^0-9]/g, '')); + + break; + + case 'vspace': + v = dom.getStyle(e, 'margin-top') + v2 = dom.getStyle(e, 'margin-bottom'); + if (v && v == v2) + return parseInt(v.replace(/[^0-9]/g, '')); + + break; + + case 'border': + v = 0; + + tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { + sv = dom.getStyle(e, 'border-' + sv + '-width'); + + // False or not the same as prev + if (!sv || (sv != v && v !== 0)) { + v = 0; + return false; + } + + if (sv) + v = sv; + }); + + if (v) + return parseInt(v.replace(/[^0-9]/g, '')); + + break; + } + } + + if (v = dom.getAttrib(e, at)) + return v; + + return ''; + }, + + resetImageData : function() { + var f = document.forms[0]; + + f.width.value = f.height.value = ""; + }, + + updateImageData : function() { + var f = document.forms[0], t = ImageDialog; + + if (f.width.value == "") + f.width.value = t.preloadImg.width; + + if (f.height.value == "") + f.height.value = t.preloadImg.height; + }, + + getImageData : function() { + var f = document.forms[0]; + + this.preloadImg = new Image(); + this.preloadImg.onload = this.updateImageData; + this.preloadImg.onerror = this.resetImageData; + this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value); + } +}; + +ImageDialog.preInit(); +tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog); diff --git a/wp-includes/js/tinymce/themes/advanced/js/link.js b/wp-includes/js/tinymce/themes/advanced/js/link.js new file mode 100644 index 0000000..f46137c --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/js/link.js @@ -0,0 +1,156 @@ +tinyMCEPopup.requireLangPack(); + +var LinkDialog = { + preInit : function() { + var url; + + if (url = tinyMCEPopup.getParam("external_link_list_url")) + document.write(''); + }, + + init : function() { + var f = document.forms[0], ed = tinyMCEPopup.editor; + + // Setup browse button + document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link'); + if (isVisible('hrefbrowser')) + document.getElementById('href').style.width = '180px'; + + this.fillClassList('class_list'); + this.fillFileList('link_list', 'tinyMCELinkList'); + this.fillTargetList('target_list'); + + if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) { + f.href.value = ed.dom.getAttrib(e, 'href'); + f.linktitle.value = ed.dom.getAttrib(e, 'title'); + f.insert.value = ed.getLang('update'); + selectByValue(f, 'link_list', f.href.value); + selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target')); + selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class')); + } + }, + + update : function() { + var f = document.forms[0], ed = tinyMCEPopup.editor, e, b; + + tinyMCEPopup.restoreSelection(); + e = ed.dom.getParent(ed.selection.getNode(), 'A'); + + // Remove element if there is no href + if (!f.href.value) { + if (e) { + tinyMCEPopup.execCommand("mceBeginUndoLevel"); + b = ed.selection.getBookmark(); + ed.dom.remove(e, 1); + ed.selection.moveToBookmark(b); + tinyMCEPopup.execCommand("mceEndUndoLevel"); + tinyMCEPopup.close(); + return; + } + } + + tinyMCEPopup.execCommand("mceBeginUndoLevel"); + + // Create new anchor elements + if (e == null) { + ed.getDoc().execCommand("unlink", false, null); + tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1}); + + tinymce.each(ed.dom.select("a"), function(n) { + if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { + e = n; + + ed.dom.setAttribs(e, { + href : f.href.value, + title : f.linktitle.value, + target : f.target_list ? f.target_list.options[f.target_list.selectedIndex].value : null, + 'class' : f.class_list ? f.class_list.options[f.class_list.selectedIndex].value : null + }); + } + }); + } else { + ed.dom.setAttribs(e, { + href : f.href.value, + title : f.linktitle.value, + target : f.target_list ? f.target_list.options[f.target_list.selectedIndex].value : null, + 'class' : f.class_list ? f.class_list.options[f.class_list.selectedIndex].value : null + }); + } + + // Don't move caret if selection was image + if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') { + ed.focus(); + ed.selection.select(e); + ed.selection.collapse(0); + tinyMCEPopup.storeSelection(); + } + + tinyMCEPopup.execCommand("mceEndUndoLevel"); + tinyMCEPopup.close(); + }, + + checkPrefix : function(n) { + if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email'))) + n.value = 'mailto:' + n.value; + + if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external'))) + n.value = 'http://' + n.value; + }, + + fillFileList : function(id, l) { + var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; + + l = window[l]; + + if (l && l.length > 0) { + lst.options[lst.options.length] = new Option('', ''); + + tinymce.each(l, function(o) { + lst.options[lst.options.length] = new Option(o[0], o[1]); + }); + } else + dom.remove(dom.getParent(id, 'tr')); + }, + + fillClassList : function(id) { + var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; + + if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { + cl = []; + + tinymce.each(v.split(';'), function(v) { + var p = v.split('='); + + cl.push({'title' : p[0], 'class' : p[1]}); + }); + } else + cl = tinyMCEPopup.editor.dom.getClasses(); + + if (cl.length > 0) { + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); + + tinymce.each(cl, function(o) { + lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); + }); + } else + dom.remove(dom.getParent(id, 'tr')); + }, + + fillTargetList : function(id) { + var dom = tinyMCEPopup.dom, lst = dom.get(id), v; + + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self'); + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank'); + + if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) { + tinymce.each(v.split(','), function(v) { + v = v.split('='); + lst.options[lst.options.length] = new Option(v[0], v[1]); + }); + } + } +}; + +LinkDialog.preInit(); +tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog); diff --git a/wp-includes/js/tinymce/themes/advanced/js/source_editor.js b/wp-includes/js/tinymce/themes/advanced/js/source_editor.js new file mode 100644 index 0000000..81063ec --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/js/source_editor.js @@ -0,0 +1,62 @@ +tinyMCEPopup.requireLangPack(); +tinyMCEPopup.onInit.add(onLoadInit); + +function saveContent() { + tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true}); + tinyMCEPopup.close(); +} + +function onLoadInit() { + tinyMCEPopup.resizeToInnerSize(); + + // Remove Gecko spellchecking + if (tinymce.isGecko) + document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck"); + + document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true}); + + if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) { + setWrap('soft'); + document.getElementById('wraped').checked = true; + } + + resizeInputs(); +} + +function setWrap(val) { + var v, n, s = document.getElementById('htmlSource'); + + s.wrap = val; + + if (!tinymce.isIE) { + v = s.value; + n = s.cloneNode(false); + n.setAttribute("wrap", val); + s.parentNode.replaceChild(n, s); + n.value = v; + } +} + +function toggleWordWrap(elm) { + if (elm.checked) + setWrap('soft'); + else + setWrap('off'); +} + +var wHeight=0, wWidth=0, owHeight=0, owWidth=0; + +function resizeInputs() { + var el = document.getElementById('htmlSource'); + + if (!tinymce.isIE) { + wHeight = self.innerHeight - 65; + wWidth = self.innerWidth - 16; + } else { + wHeight = document.body.clientHeight - 70; + wWidth = document.body.clientWidth - 16; + } + + el.style.height = Math.abs(wHeight) + 'px'; + el.style.width = Math.abs(wWidth) + 'px'; +} diff --git a/wp-includes/js/tinymce/themes/advanced/link.htm b/wp-includes/js/tinymce/themes/advanced/link.htm new file mode 100644 index 0000000..09ba2a6 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/link.htm @@ -0,0 +1,63 @@ + + + + {#advanced_dlg.link_title} + + + + + + + +
    + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +
     
    +
    +
    + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/content.css b/wp-includes/js/tinymce/themes/advanced/skins/default/content.css new file mode 100644 index 0000000..cb7604e --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/default/content.css @@ -0,0 +1,32 @@ +body, td, pre {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; margin:8px;} +body {background:#FFF;} +body.mceForceColors {background:#FFF; color:#000;} +h1 {font-size: 2em} +h2 {font-size: 1.5em} +h3 {font-size: 1.17em} +h4 {font-size: 1em} +h5 {font-size: .83em} +h6 {font-size: .75em} +.mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} +a.mceItemAnchor {width:12px; line-height:6px; overflow:hidden; padding-left:12px; background:url(img/items.gif) no-repeat bottom left;} +img.mceItemAnchor {width:12px; height:12px; background:url(img/items.gif) no-repeat;} +img {border:0;} +table {cursor:default} +table td, table th {cursor:text} +ins {border-bottom:1px solid green; text-decoration: none; color:green} +del {color:red; text-decoration:line-through} +cite {border-bottom:1px dashed blue} +acronym {border-bottom:1px dotted #CCC; cursor:help} +abbr, html\:abbr {border-bottom:1px dashed #CCC; cursor:help} + +/* IE */ +* html body { +scrollbar-3dlight-color:#F0F0EE; +scrollbar-arrow-color:#676662; +scrollbar-base-color:#F0F0EE; +scrollbar-darkshadow-color:#DDD; +scrollbar-face-color:#E0E0DD; +scrollbar-highlight-color:#F0F0EE; +scrollbar-shadow-color:#F0F0EE; +scrollbar-track-color:#F5F5F5; +} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/dialog.css b/wp-includes/js/tinymce/themes/advanced/skins/default/dialog.css new file mode 100644 index 0000000..fa2df25 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/default/dialog.css @@ -0,0 +1,116 @@ +/* Generic */ +body { +font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; +scrollbar-3dlight-color:#F0F0EE; +scrollbar-arrow-color:#676662; +scrollbar-base-color:#F0F0EE; +scrollbar-darkshadow-color:#DDDDDD; +scrollbar-face-color:#E0E0DD; +scrollbar-highlight-color:#F0F0EE; +scrollbar-shadow-color:#F0F0EE; +scrollbar-track-color:#F5F5F5; +background:#F0F0EE; +padding:0; +margin:8px 8px 0 8px; +} + +html {background:#F0F0EE;} +td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} +textarea {resize:none;outline:none;} +a:link, a:visited {color:black;} +a:hover {color:#2B6FB6;} +.nowrap {white-space: nowrap} + +/* Forms */ +fieldset {margin:0; padding:4px; border:1px solid #919B9C; font-family:Verdana, Arial; font-size:10px;} +legend {color:#2B6FB6; font-weight:bold;} +label.msg {display:none;} +label.invalid {color:#EE0000; display:inline;} +input.invalid {border:1px solid #EE0000;} +input {background:#FFF; border:1px solid #CCC;} +input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} +input, select, textarea {border:1px solid #808080;} +input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} +input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} +.input_noborder {border:0;} + +/* Buttons */ +#insert, #cancel, input.button, .updateButton { +border:0; margin:0; padding:0; +font-weight:bold; +width:94px; height:26px; +background:url(img/buttons.png) 0 -26px; +cursor:pointer; +padding-bottom:2px; +} + +#insert {background:url(img/buttons.png) 0 -52px;} +#cancel {background:url(img/buttons.png) 0 0;} + +/* Browse */ +a.pickcolor, a.browse {text-decoration:none} +a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} +.mceOldBoxModel a.browse span {width:22px; height:20px;} +a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} +a.browse span.disabled {border:1px solid white; opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} +a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} +a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} +.mceOldBoxModel a.pickcolor span {width:21px; height:17px;} +a.pickcolor:hover span {background-color:#B2BBD0;} +a.pickcolor:hover span.disabled {} + +/* Charmap */ +table.charmap {border:1px solid #AAA; text-align:center} +td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} +#charmap a {display:block; color:#000; text-decoration:none; border:0} +#charmap a:hover {background:#CCC;color:#2B6FB6} +#charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} +#charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} + +/* Source */ +.wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} +.mceActionPanel {margin-top:5px;} + +/* Tabs classes */ +.tabs {width:100%; height:18px; line-height:normal; background:url(img/tabs.gif) repeat-x 0 -72px;} +.tabs ul {margin:0; padding:0; list-style:none;} +.tabs li {float:left; background:url(img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;} +.tabs li.current {background:url(img/tabs.gif) no-repeat 0 -18px; margin-right:2px;} +.tabs span {float:left; display:block; background:url(img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;} +.tabs .current span {background:url(img/tabs.gif) no-repeat right -54px;} +.tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} +.tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} + +/* Panels */ +.panel_wrapper div.panel {display:none;} +.panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} +.panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;} + +/* Columns */ +.column {float:left;} +.properties {width:100%;} +.properties .column1 {} +.properties .column2 {text-align:left;} + +/* Titles */ +h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} +h3 {font-size:14px;} +.title {font-size:12px; font-weight:bold; color:#2B6FB6;} + +/* Dialog specific */ +#link .panel_wrapper, #link div.current {height:125px;} +#image .panel_wrapper, #image div.current {height:200px;} +#plugintable thead {font-weight:bold; background:#DDD;} +#plugintable, #about #plugintable td {border:1px solid #919B9C;} +#plugintable {width:96%; margin-top:10px;} +#pluginscontainer {height:290px; overflow:auto;} +#colorpicker #preview {float:right; width:50px; height:14px;line-height:1px; border:1px solid black; margin-left:5px;} +#colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} +#colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} +#colorpicker #light div {overflow:hidden;} +#colorpicker #previewblock {float:right; padding-left:10px; height:20px;} +#colorpicker .panel_wrapper div.current {height:175px;} +#colorpicker #namedcolors {width:150px;} +#colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} +#colorpicker #colornamecontainer {margin-top:5px;} +#colorpicker #picker_panel fieldset {margin:auto;width:325px;} \ No newline at end of file diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/img/buttons.png b/wp-includes/js/tinymce/themes/advanced/skins/default/img/buttons.png new file mode 100644 index 0000000..7dd5841 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/default/img/buttons.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/img/items.gif b/wp-includes/js/tinymce/themes/advanced/skins/default/img/items.gif new file mode 100644 index 0000000..2eafd79 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/default/img/items.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/img/menu_arrow.gif b/wp-includes/js/tinymce/themes/advanced/skins/default/img/menu_arrow.gif new file mode 100644 index 0000000..85e31df Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/default/img/menu_arrow.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/img/menu_check.gif b/wp-includes/js/tinymce/themes/advanced/skins/default/img/menu_check.gif new file mode 100644 index 0000000..adfdddc Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/default/img/menu_check.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/img/progress.gif b/wp-includes/js/tinymce/themes/advanced/skins/default/img/progress.gif new file mode 100644 index 0000000..5bb90fd Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/default/img/progress.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/img/tabs.gif b/wp-includes/js/tinymce/themes/advanced/skins/default/img/tabs.gif new file mode 100644 index 0000000..ce4be63 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/default/img/tabs.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/default/ui.css b/wp-includes/js/tinymce/themes/advanced/skins/default/ui.css new file mode 100644 index 0000000..2c90d49 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/default/ui.css @@ -0,0 +1,214 @@ +/* Reset */ +.defaultSkin table, .defaultSkin tbody, .defaultSkin a, .defaultSkin img, .defaultSkin tr, .defaultSkin div, .defaultSkin td, .defaultSkin iframe, .defaultSkin span, .defaultSkin *, .defaultSkin .mceText {border:0; margin:0; padding:0; background:transparent; white-space:nowrap; text-decoration:none; font-weight:normal; cursor:default; color:#000; vertical-align:baseline; width:auto; border-collapse:separate; text-align:left} +.defaultSkin a:hover, .defaultSkin a:link, .defaultSkin a:visited, .defaultSkin a:active {text-decoration:none; font-weight:normal; cursor:default; color:#000} +.defaultSkin table td {vertical-align:middle} + +/* Containers */ +.defaultSkin table {background:#F0F0EE} +.defaultSkin iframe {display:block; background:#FFF} +.defaultSkin .mceToolbar {height:26px} +.defaultSkin .mceLeft {text-align:left} +.defaultSkin .mceRight {text-align:right} + +/* External */ +.defaultSkin .mceExternalToolbar {position:absolute; border:1px solid #CCC; border-bottom:0; display:none;} +.defaultSkin .mceExternalToolbar td.mceToolbar {padding-right:13px;} +.defaultSkin .mceExternalClose {position:absolute; top:3px; right:3px; width:7px; height:7px; background:url(../../img/icons.gif) -820px 0} + +/* Layout */ +.defaultSkin table.mceLayout {border:0; border-left:1px solid #CCC; border-right:1px solid #CCC} +.defaultSkin table.mceLayout tr.mceFirst td {border-top:1px solid #CCC} +.defaultSkin table.mceLayout tr.mceLast td {border-bottom:1px solid #CCC} +.defaultSkin table.mceToolbar, .defaultSkin tr.mceFirst .mceToolbar tr td, .defaultSkin tr.mceLast .mceToolbar tr td {border:0; margin:0; padding:0;} +.defaultSkin td.mceToolbar {padding-top:1px; vertical-align:top} +.defaultSkin .mceIframeContainer {border-top:1px solid #CCC; border-bottom:1px solid #CCC} +.defaultSkin .mceStatusbar {font-family:'MS Sans Serif',sans-serif,Verdana,Arial; font-size:9pt; line-height:16px; overflow:visible; color:#000; display:block; height:20px} +.defaultSkin .mceStatusbar div {float:left; margin:2px} +.defaultSkin .mceStatusbar a.mceResize {display:block; float:right; background:url(../../img/icons.gif) -800px 0; width:20px; height:20px; cursor:se-resize} +.defaultSkin .mceStatusbar a:hover {text-decoration:underline} +.defaultSkin table.mceToolbar {margin-left:3px} +.defaultSkin span.mceIcon, .defaultSkin img.mceIcon {display:block; width:20px; height:20px} +.defaultSkin .mceIcon {background:url(../../img/icons.gif) no-repeat 20px 20px} +.defaultSkin td.mceCenter {text-align:center;} +.defaultSkin td.mceCenter table {margin:0 auto; text-align:left;} +.defaultSkin td.mceRight table {margin:0 0 0 auto;} + +/* Button */ +.defaultSkin .mceButton {display:block; border:1px solid #F0F0EE; width:20px; height:20px; margin-right:1px} +.defaultSkin a.mceButtonEnabled:hover {border:1px solid #0A246A; background-color:#B2BBD0} +.defaultSkin a.mceButtonActive, .defaultSkin a.mceButtonSelected {border:1px solid #0A246A; background-color:#C2CBE0} +.defaultSkin .mceButtonDisabled .mceIcon {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} +.defaultSkin .mceButtonLabeled {width:auto} +.defaultSkin .mceButtonLabeled span.mceIcon {float:left} +.defaultSkin span.mceButtonLabel {display:block; font-size:10px; padding:4px 6px 0 22px; font-family:Tahoma,Verdana,Arial,Helvetica} +.defaultSkin .mceButtonDisabled .mceButtonLabel {color:#888} + +/* Separator */ +.defaultSkin .mceSeparator {display:block; background:url(../../img/icons.gif) -180px 0; width:2px; height:20px; margin:2px 2px 0 4px} + +/* ListBox */ +.defaultSkin .mceListBox {direction:ltr} +.defaultSkin .mceListBox, .defaultSkin .mceListBox a {display:block} +.defaultSkin .mceListBox .mceText {padding-left:4px; width:70px; text-align:left; border:1px solid #CCC; border-right:0; background:#FFF; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; height:20px; line-height:20px; overflow:hidden} +.defaultSkin .mceListBox .mceOpen {width:9px; height:20px; background:url(../../img/icons.gif) -741px 0; margin-right:2px; border:1px solid #CCC;} +.defaultSkin table.mceListBoxEnabled:hover .mceText, .defaultSkin .mceListBoxHover .mceText, .defaultSkin .mceListBoxSelected .mceText {border:1px solid #A2ABC0; border-right:0; background:#FFF} +.defaultSkin table.mceListBoxEnabled:hover .mceOpen, .defaultSkin .mceListBoxHover .mceOpen, .defaultSkin .mceListBoxSelected .mceOpen {background-color:#FFF; border:1px solid #A2ABC0} +.defaultSkin .mceListBoxDisabled a.mceText {color:gray; background-color:transparent;} +.defaultSkin .mceListBoxMenu {overflow:auto; overflow-x:hidden} +.defaultSkin .mceOldBoxModel .mceListBox .mceText {height:22px} +.defaultSkin .mceOldBoxModel .mceListBox .mceOpen {width:11px; height:22px;} +.defaultSkin select.mceNativeListBox {font-family:'MS Sans Serif',sans-serif,Verdana,Arial; font-size:7pt; background:#F0F0EE; border:1px solid gray; margin-right:2px;} + +/* SplitButton */ +.defaultSkin .mceSplitButton {width:32px; height:20px; direction:ltr} +.defaultSkin .mceSplitButton a, .defaultSkin .mceSplitButton span {height:20px; display:block} +.defaultSkin .mceSplitButton a.mceAction {width:20px; border:1px solid #F0F0EE; border-right:0;} +.defaultSkin .mceSplitButton span.mceAction {width:20px; background:url(../../img/icons.gif) 20px 20px;} +.defaultSkin .mceSplitButton a.mceOpen {width:9px; background:url(../../img/icons.gif) -741px 0; border:1px solid #F0F0EE;} +.defaultSkin .mceSplitButton span.mceOpen {display:none} +.defaultSkin table.mceSplitButtonEnabled:hover a.mceAction, .defaultSkin .mceSplitButtonHover a.mceAction, .defaultSkin .mceSplitButtonSelected a.mceAction {border:1px solid #0A246A; border-right:0; background-color:#B2BBD0} +.defaultSkin table.mceSplitButtonEnabled:hover a.mceOpen, .defaultSkin .mceSplitButtonHover a.mceOpen, .defaultSkin .mceSplitButtonSelected a.mceOpen {background-color:#B2BBD0; border:1px solid #0A246A;} +.defaultSkin .mceSplitButtonDisabled .mceAction, .defaultSkin .mceSplitButtonDisabled a.mceOpen {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} +.defaultSkin .mceSplitButtonActive a.mceAction {border:1px solid #0A246A; background-color:#C2CBE0} +.defaultSkin .mceSplitButtonActive a.mceOpen {border-left:0;} + +/* ColorSplitButton */ +.defaultSkin div.mceColorSplitMenu table {background:#FFF; border:1px solid gray} +.defaultSkin .mceColorSplitMenu td {padding:2px} +.defaultSkin .mceColorSplitMenu a {display:block; width:9px; height:9px; overflow:hidden; border:1px solid #808080} +.defaultSkin .mceColorSplitMenu td.mceMoreColors {padding:1px 3px 1px 1px} +.defaultSkin .mceColorSplitMenu a.mceMoreColors {width:100%; height:auto; text-align:center; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; line-height:20px; border:1px solid #FFF} +.defaultSkin .mceColorSplitMenu a.mceMoreColors:hover {border:1px solid #0A246A; background-color:#B6BDD2} +.defaultSkin a.mceMoreColors:hover {border:1px solid #0A246A} +.defaultSkin .mceColorPreview {margin-left:2px; width:16px; height:4px; overflow:hidden; background:#9a9b9a} +.defaultSkin .mce_forecolor span.mceAction, .defaultSkin .mce_backcolor span.mceAction {overflow:hidden; height:16px} + +/* Menu */ +.defaultSkin .mceMenu {position:absolute; left:0; top:0; z-index:1000; border:1px solid #D4D0C8} +.defaultSkin .mceNoIcons span.mceIcon {width:0;} +.defaultSkin .mceNoIcons a .mceText {padding-left:10px} +.defaultSkin .mceMenu table {background:#FFF} +.defaultSkin .mceMenu a, .defaultSkin .mceMenu span, .defaultSkin .mceMenu {display:block} +.defaultSkin .mceMenu td {height:20px} +.defaultSkin .mceMenu a {position:relative;padding:3px 0 4px 0} +.defaultSkin .mceMenu .mceText {position:relative; display:block; font-family:Tahoma,Verdana,Arial,Helvetica; color:#000; cursor:default; margin:0; padding:0 25px 0 25px; display:block} +.defaultSkin .mceMenu span.mceText, .defaultSkin .mceMenu .mcePreview {font-size:11px} +.defaultSkin .mceMenu pre.mceText {font-family:Monospace} +.defaultSkin .mceMenu .mceIcon {position:absolute; top:0; left:0; width:22px;} +.defaultSkin .mceMenu .mceMenuItemEnabled a:hover, .defaultSkin .mceMenu .mceMenuItemActive {background-color:#dbecf3} +.defaultSkin td.mceMenuItemSeparator {background:#DDD; height:1px} +.defaultSkin .mceMenuItemTitle a {border:0; background:#EEE; border-bottom:1px solid #DDD} +.defaultSkin .mceMenuItemTitle span.mceText {color:#000; font-weight:bold; padding-left:4px} +.defaultSkin .mceMenuItemDisabled .mceText {color:#888} +.defaultSkin .mceMenuItemSelected .mceIcon {background:url(img/menu_check.gif)} +.defaultSkin .mceNoIcons .mceMenuItemSelected a {background:url(img/menu_arrow.gif) no-repeat -6px center} +.defaultSkin .mceMenu span.mceMenuLine {display:none} +.defaultSkin .mceMenuItemSub a {background:url(img/menu_arrow.gif) no-repeat top right;} + +/* Progress,Resize */ +.defaultSkin .mceBlocker {position:absolute; left:0; top:0; z-index:1000; opacity:0.5; -ms-filter:'alpha(opacity=50)'; filter:alpha(opacity=50); background:#FFF} +.defaultSkin .mceProgress {position:absolute; left:0; top:0; z-index:1001; background:url(img/progress.gif) no-repeat; width:32px; height:32px; margin:-16px 0 0 -16px} +.defaultSkin .mcePlaceHolder {border:1px dotted gray} + +/* Formats */ +.defaultSkin .mce_formatPreview a {font-size:10px} +.defaultSkin .mce_p span.mceText {} +.defaultSkin .mce_address span.mceText {font-style:italic} +.defaultSkin .mce_pre span.mceText {font-family:monospace} +.defaultSkin .mce_h1 span.mceText {font-weight:bolder; font-size: 2em} +.defaultSkin .mce_h2 span.mceText {font-weight:bolder; font-size: 1.5em} +.defaultSkin .mce_h3 span.mceText {font-weight:bolder; font-size: 1.17em} +.defaultSkin .mce_h4 span.mceText {font-weight:bolder; font-size: 1em} +.defaultSkin .mce_h5 span.mceText {font-weight:bolder; font-size: .83em} +.defaultSkin .mce_h6 span.mceText {font-weight:bolder; font-size: .75em} + +/* Theme */ +.defaultSkin span.mce_bold {background-position:0 0} +.defaultSkin span.mce_italic {background-position:-60px 0} +.defaultSkin span.mce_underline {background-position:-140px 0} +.defaultSkin span.mce_strikethrough {background-position:-120px 0} +.defaultSkin span.mce_undo {background-position:-160px 0} +.defaultSkin span.mce_redo {background-position:-100px 0} +.defaultSkin span.mce_cleanup {background-position:-40px 0} +.defaultSkin span.mce_bullist {background-position:-20px 0} +.defaultSkin span.mce_numlist {background-position:-80px 0} +.defaultSkin span.mce_justifyleft {background-position:-460px 0} +.defaultSkin span.mce_justifyright {background-position:-480px 0} +.defaultSkin span.mce_justifycenter {background-position:-420px 0} +.defaultSkin span.mce_justifyfull {background-position:-440px 0} +.defaultSkin span.mce_anchor {background-position:-200px 0} +.defaultSkin span.mce_indent {background-position:-400px 0} +.defaultSkin span.mce_outdent {background-position:-540px 0} +.defaultSkin span.mce_link {background-position:-500px 0} +.defaultSkin span.mce_unlink {background-position:-640px 0} +.defaultSkin span.mce_sub {background-position:-600px 0} +.defaultSkin span.mce_sup {background-position:-620px 0} +.defaultSkin span.mce_removeformat {background-position:-580px 0} +.defaultSkin span.mce_newdocument {background-position:-520px 0} +.defaultSkin span.mce_image {background-position:-380px 0} +.defaultSkin span.mce_help {background-position:-340px 0} +.defaultSkin span.mce_code {background-position:-260px 0} +.defaultSkin span.mce_hr {background-position:-360px 0} +.defaultSkin span.mce_visualaid {background-position:-660px 0} +.defaultSkin span.mce_charmap {background-position:-240px 0} +.defaultSkin span.mce_paste {background-position:-560px 0} +.defaultSkin span.mce_copy {background-position:-700px 0} +.defaultSkin span.mce_cut {background-position:-680px 0} +.defaultSkin span.mce_blockquote {background-position:-220px 0} +.defaultSkin .mce_forecolor span.mceAction {background-position:-720px 0} +.defaultSkin .mce_backcolor span.mceAction {background-position:-760px 0} +.defaultSkin span.mce_forecolorpicker {background-position:-720px 0} +.defaultSkin span.mce_backcolorpicker {background-position:-760px 0} + +/* Plugins */ +.defaultSkin span.mce_advhr {background-position:-0px -20px} +.defaultSkin span.mce_ltr {background-position:-20px -20px} +.defaultSkin span.mce_rtl {background-position:-40px -20px} +.defaultSkin span.mce_emotions {background-position:-60px -20px} +.defaultSkin span.mce_fullpage {background-position:-80px -20px} +.defaultSkin span.mce_fullscreen {background-position:-100px -20px} +.defaultSkin span.mce_iespell {background-position:-120px -20px} +.defaultSkin span.mce_insertdate {background-position:-140px -20px} +.defaultSkin span.mce_inserttime {background-position:-160px -20px} +.defaultSkin span.mce_absolute {background-position:-180px -20px} +.defaultSkin span.mce_backward {background-position:-200px -20px} +.defaultSkin span.mce_forward {background-position:-220px -20px} +.defaultSkin span.mce_insert_layer {background-position:-240px -20px} +.defaultSkin span.mce_insertlayer {background-position:-260px -20px} +.defaultSkin span.mce_movebackward {background-position:-280px -20px} +.defaultSkin span.mce_moveforward {background-position:-300px -20px} +.defaultSkin span.mce_media {background-position:-320px -20px} +.defaultSkin span.mce_nonbreaking {background-position:-340px -20px} +.defaultSkin span.mce_pastetext {background-position:-360px -20px} +.defaultSkin span.mce_pasteword {background-position:-380px -20px} +.defaultSkin span.mce_selectall {background-position:-400px -20px} +.defaultSkin span.mce_preview {background-position:-420px -20px} +.defaultSkin span.mce_print {background-position:-440px -20px} +.defaultSkin span.mce_cancel {background-position:-460px -20px} +.defaultSkin span.mce_save {background-position:-480px -20px} +.defaultSkin span.mce_replace {background-position:-500px -20px} +.defaultSkin span.mce_search {background-position:-520px -20px} +.defaultSkin span.mce_styleprops {background-position:-560px -20px} +.defaultSkin span.mce_table {background-position:-580px -20px} +.defaultSkin span.mce_cell_props {background-position:-600px -20px} +.defaultSkin span.mce_delete_table {background-position:-620px -20px} +.defaultSkin span.mce_delete_col {background-position:-640px -20px} +.defaultSkin span.mce_delete_row {background-position:-660px -20px} +.defaultSkin span.mce_col_after {background-position:-680px -20px} +.defaultSkin span.mce_col_before {background-position:-700px -20px} +.defaultSkin span.mce_row_after {background-position:-720px -20px} +.defaultSkin span.mce_row_before {background-position:-740px -20px} +.defaultSkin span.mce_merge_cells {background-position:-760px -20px} +.defaultSkin span.mce_table_props {background-position:-980px -20px} +.defaultSkin span.mce_row_props {background-position:-780px -20px} +.defaultSkin span.mce_split_cells {background-position:-800px -20px} +.defaultSkin span.mce_template {background-position:-820px -20px} +.defaultSkin span.mce_visualchars {background-position:-840px -20px} +.defaultSkin span.mce_abbr {background-position:-860px -20px} +.defaultSkin span.mce_acronym {background-position:-880px -20px} +.defaultSkin span.mce_attribs {background-position:-900px -20px} +.defaultSkin span.mce_cite {background-position:-920px -20px} +.defaultSkin span.mce_del {background-position:-940px -20px} +.defaultSkin span.mce_ins {background-position:-960px -20px} +.defaultSkin span.mce_pagebreak {background-position:0 -40px} +.defaultSkin .mce_spellchecker span.mceAction {background-position:-540px -20px} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/content.css b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/content.css new file mode 100644 index 0000000..a404931 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/content.css @@ -0,0 +1,32 @@ +body, td, pre {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; margin:8px;} +body {background:#FFF;} +body.mceForceColors {background:#FFF; color:#000;} +h1 {font-size: 2em} +h2 {font-size: 1.5em} +h3 {font-size: 1.17em} +h4 {font-size: 1em} +h5 {font-size: .83em} +h6 {font-size: .75em} +.mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} +a.mceItemAnchor {width:12px; line-height:6px; overflow:hidden; padding-left:12px; background:url(../default/img/items.gif) no-repeat bottom left;} +img.mceItemAnchor {width:12px; height:12px; background:url(../default/img/items.gif) no-repeat;} +img {border:0;} +table {cursor:default} +table td, table th {cursor:text} +ins {border-bottom:1px solid green; text-decoration: none; color:green} +del {color:red; text-decoration:line-through} +cite {border-bottom:1px dashed blue} +acronym {border-bottom:1px dotted #CCC; cursor:help} +abbr, html\:abbr {border-bottom:1px dashed #CCC; cursor:help} + +/* IE */ +* html body { +scrollbar-3dlight-color:#F0F0EE; +scrollbar-arrow-color:#676662; +scrollbar-base-color:#F0F0EE; +scrollbar-darkshadow-color:#DDD; +scrollbar-face-color:#E0E0DD; +scrollbar-highlight-color:#F0F0EE; +scrollbar-shadow-color:#F0F0EE; +scrollbar-track-color:#F5F5F5; +} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/dialog.css b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/dialog.css new file mode 100644 index 0000000..6b278b6 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/dialog.css @@ -0,0 +1,115 @@ +/* Generic */ +body { +font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; +scrollbar-3dlight-color:#F0F0EE; +scrollbar-arrow-color:#676662; +scrollbar-base-color:#F0F0EE; +scrollbar-darkshadow-color:#DDDDDD; +scrollbar-face-color:#E0E0DD; +scrollbar-highlight-color:#F0F0EE; +scrollbar-shadow-color:#F0F0EE; +scrollbar-track-color:#F5F5F5; +background:#F0F0EE; +padding:0; +margin:8px 8px 0 8px; +} + +html {background:#F0F0EE;} +td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} +textarea {resize:none;outline:none;} +a:link, a:visited {color:black;} +a:hover {color:#2B6FB6;} +.nowrap {white-space: nowrap} + +/* Forms */ +fieldset {margin:0; padding:4px; border:1px solid #919B9C; font-family:Verdana, Arial; font-size:10px;} +legend {color:#2B6FB6; font-weight:bold;} +label.msg {display:none;} +label.invalid {color:#EE0000; display:inline;} +input.invalid {border:1px solid #EE0000;} +input {background:#FFF; border:1px solid #CCC;} +input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} +input, select, textarea {border:1px solid #808080;} +input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} +input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} +.input_noborder {border:0;} + +/* Buttons */ +#insert, #cancel, input.button, .updateButton { +border:0; margin:0; padding:0; +font-weight:bold; +width:94px; height:26px; +background:url(../default/img/buttons.png) 0 -26px; +cursor:pointer; +padding-bottom:2px; +} + +#insert {background:url(../default/img/buttons.png) 0 -52px;} +#cancel {background:url(../default/img/buttons.png) 0 0;} + +/* Browse */ +a.pickcolor, a.browse {text-decoration:none} +a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} +.mceOldBoxModel a.browse span {width:22px; height:20px;} +a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} +a.browse span.disabled {border:1px solid white; opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} +a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} +a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} +.mceOldBoxModel a.pickcolor span {width:21px; height:17px;} +a.pickcolor:hover span {background-color:#B2BBD0;} +a.pickcolor:hover span.disabled {} + +/* Charmap */ +table.charmap {border:1px solid #AAA; text-align:center} +td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} +#charmap a {display:block; color:#000; text-decoration:none; border:0} +#charmap a:hover {background:#CCC;color:#2B6FB6} +#charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} +#charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} + +/* Source */ +.wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} +.mceActionPanel {margin-top:5px;} + +/* Tabs classes */ +.tabs {width:100%; height:18px; line-height:normal; background:url(../default/img/tabs.gif) repeat-x 0 -72px;} +.tabs ul {margin:0; padding:0; list-style:none;} +.tabs li {float:left; background:url(../default/img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;} +.tabs li.current {background:url(../default/img/tabs.gif) no-repeat 0 -18px; margin-right:2px;} +.tabs span {float:left; display:block; background:url(../default/img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;} +.tabs .current span {background:url(../default/img/tabs.gif) no-repeat right -54px;} +.tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} +.tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} + +/* Panels */ +.panel_wrapper div.panel {display:none;} +.panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} +.panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;} + +/* Columns */ +.column {float:left;} +.properties {width:100%;} +.properties .column1 {} +.properties .column2 {text-align:left;} + +/* Titles */ +h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} +h3 {font-size:14px;} +.title {font-size:12px; font-weight:bold; color:#2B6FB6;} + +/* Dialog specific */ +#link .panel_wrapper, #link div.current {height:125px;} +#image .panel_wrapper, #image div.current {height:200px;} +#plugintable thead {font-weight:bold; background:#DDD;} +#plugintable, #about #plugintable td {border:1px solid #919B9C;} +#plugintable {width:96%; margin-top:10px;} +#pluginscontainer {height:290px; overflow:auto;} +#colorpicker #preview {float:right; width:50px; height:14px;line-height:1px; border:1px solid black; margin-left:5px;} +#colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} +#colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} +#colorpicker #light div {overflow:hidden;} +#colorpicker #previewblock {float:right; padding-left:10px; height:20px;} +#colorpicker .panel_wrapper div.current {height:175px;} +#colorpicker #namedcolors {width:150px;} +#colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} +#colorpicker #colornamecontainer {margin-top:5px;} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg.png b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg.png new file mode 100644 index 0000000..12cfb41 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg_black.png b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg_black.png new file mode 100644 index 0000000..8996c74 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg_black.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg_silver.png b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg_silver.png new file mode 100644 index 0000000..bd5d255 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/img/button_bg_silver.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui.css b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui.css new file mode 100644 index 0000000..0f8d5c2 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui.css @@ -0,0 +1,215 @@ +/* Reset */ +.o2k7Skin table, .o2k7Skin tbody, .o2k7Skin a, .o2k7Skin img, .o2k7Skin tr, .o2k7Skin div, .o2k7Skin td, .o2k7Skin iframe, .o2k7Skin span, .o2k7Skin *, .o2k7Skin .mceText {border:0; margin:0; padding:0; background:transparent; white-space:nowrap; text-decoration:none; font-weight:normal; cursor:default; color:#000; vertical-align:baseline; width:auto; border-collapse:separate; text-align:left} +.o2k7Skin a:hover, .o2k7Skin a:link, .o2k7Skin a:visited, .o2k7Skin a:active {text-decoration:none; font-weight:normal; cursor:default; color:#000} +.o2k7Skin table td {vertical-align:middle} + +/* Containers */ +.o2k7Skin table {background:#E5EFFD} +.o2k7Skin iframe {display:block; background:#FFF} +.o2k7Skin .mceToolbar {height:26px} + +/* External */ +.o2k7Skin .mceExternalToolbar {position:absolute; border:1px solid #ABC6DD; border-bottom:0; display:none} +.o2k7Skin .mceExternalToolbar td.mceToolbar {padding-right:13px;} +.o2k7Skin .mceExternalClose {position:absolute; top:3px; right:3px; width:7px; height:7px; background:url(../../img/icons.gif) -820px 0} + +/* Layout */ +.o2k7Skin table.mceLayout {border:0; border-left:1px solid #ABC6DD; border-right:1px solid #ABC6DD} +.o2k7Skin table.mceLayout tr.mceFirst td {border-top:1px solid #ABC6DD} +.o2k7Skin table.mceLayout tr.mceLast td {border-bottom:1px solid #ABC6DD} +.o2k7Skin table.mceToolbar, .o2k7Skin tr.mceFirst .mceToolbar tr td, .o2k7Skin tr.mceLast .mceToolbar tr td {border:0; margin:0; padding:0} +.o2k7Skin .mceIframeContainer {border-top:1px solid #ABC6DD; border-bottom:1px solid #ABC6DD} +.o2k7Skin .mceStatusbar {display:block; font-family:'MS Sans Serif',sans-serif,Verdana,Arial; font-size:9pt; line-height:16px; overflow:visible; color:#000; height:20px} +.o2k7Skin .mceStatusbar div {float:left; padding:2px} +.o2k7Skin .mceStatusbar a.mceResize {display:block; float:right; background:url(../../img/icons.gif) -800px 0; width:20px; height:20px; cursor:se-resize} +.o2k7Skin .mceStatusbar a:hover {text-decoration:underline} +.o2k7Skin table.mceToolbar {margin-left:3px} +.o2k7Skin .mceToolbar .mceToolbarStart span {display:block; background:url(img/button_bg.png) -22px 0; width:1px; height:22px; margin-left:3px;} +.o2k7Skin .mceToolbar td.mceFirst span {margin:0} +.o2k7Skin .mceToolbar .mceToolbarEnd span {display:block; background:url(img/button_bg.png) -22px 0; width:1px; height:22px} +.o2k7Skin .mceToolbar .mceToolbarEndListBox span, .o2k7Skin .mceToolbar .mceToolbarStartListBox span {display:none} +.o2k7Skin span.mceIcon, .o2k7Skin img.mceIcon {display:block; width:20px; height:20px} +.o2k7Skin .mceIcon {background:url(../../img/icons.gif) no-repeat 20px 20px} +.o2k7Skin td.mceCenter {text-align:center;} +.o2k7Skin td.mceCenter table {margin:0 auto; text-align:left;} +.o2k7Skin td.mceRight table {margin:0 0 0 auto;} + +/* Button */ +.o2k7Skin .mceButton {display:block; background:url(img/button_bg.png); width:22px; height:22px} +.o2k7Skin a.mceButton span, .o2k7Skin a.mceButton img {margin-left:1px} +.o2k7Skin .mceOldBoxModel a.mceButton span, .o2k7Skin .mceOldBoxModel a.mceButton img {margin:0 0 0 1px} +.o2k7Skin a.mceButtonEnabled:hover {background-color:#B2BBD0; background-position:0 -22px} +.o2k7Skin a.mceButtonActive, .o2k7Skin a.mceButtonSelected {background-position:0 -44px} +.o2k7Skin .mceButtonDisabled .mceIcon {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} +.o2k7Skin .mceButtonLabeled {width:auto} +.o2k7Skin .mceButtonLabeled span.mceIcon {float:left} +.o2k7Skin span.mceButtonLabel {display:block; font-size:10px; padding:4px 6px 0 22px; font-family:Tahoma,Verdana,Arial,Helvetica} +.o2k7Skin .mceButtonDisabled .mceButtonLabel {color:#888} + +/* Separator */ +.o2k7Skin .mceSeparator {display:block; background:url(img/button_bg.png) -22px 0; width:5px; height:22px} + +/* ListBox */ +.o2k7Skin .mceListBox {margin-left:3px} +.o2k7Skin .mceListBox, .o2k7Skin .mceListBox a {display:block} +.o2k7Skin .mceListBox .mceText {padding-left:4px; text-align:left; width:70px; border:1px solid #b3c7e1; border-right:0; background:#eaf2fb; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; height:20px; line-height:20px; overflow:hidden} +.o2k7Skin .mceListBox .mceOpen {width:14px; height:22px; background:url(img/button_bg.png) -66px 0} +.o2k7Skin table.mceListBoxEnabled:hover .mceText, .o2k7Skin .mceListBoxHover .mceText, .o2k7Skin .mceListBoxSelected .mceText {background:#FFF} +.o2k7Skin table.mceListBoxEnabled:hover .mceOpen, .o2k7Skin .mceListBoxHover .mceOpen, .o2k7Skin .mceListBoxSelected .mceOpen {background-position:-66px -22px} +.o2k7Skin .mceListBoxDisabled .mceText {color:gray} +.o2k7Skin .mceListBoxMenu {overflow:auto; overflow-x:hidden} +.o2k7Skin .mceOldBoxModel .mceListBox .mceText {height:22px} +.o2k7Skin select.mceListBox {font-family:Tahoma,Verdana,Arial,Helvetica; font-size:12px; border:1px solid #b3c7e1; background:#FFF;} + +/* SplitButton */ +.o2k7Skin .mceSplitButton, .o2k7Skin .mceSplitButton a, .o2k7Skin .mceSplitButton span {display:block; height:22px} +.o2k7Skin .mceSplitButton {background:url(img/button_bg.png)} +.o2k7Skin .mceSplitButton a.mceAction {width:22px} +.o2k7Skin .mceSplitButton span.mceAction {width:22px; background:url(../../img/icons.gif) 20px 20px} +.o2k7Skin .mceSplitButton a.mceOpen {width:10px; background:url(img/button_bg.png) -44px 0} +.o2k7Skin .mceSplitButton span.mceOpen {display:none} +.o2k7Skin table.mceSplitButtonEnabled:hover a.mceAction, .o2k7Skin .mceSplitButtonHover a.mceAction, .o2k7Skin .mceSplitButtonSelected {background:url(img/button_bg.png) 0 -22px} +.o2k7Skin table.mceSplitButtonEnabled:hover a.mceOpen, .o2k7Skin .mceSplitButtonHover a.mceOpen, .o2k7Skin .mceSplitButtonSelected a.mceOpen {background-position:-44px -44px} +.o2k7Skin .mceSplitButtonDisabled .mceAction {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} +.o2k7Skin .mceSplitButtonActive {background-position:0 -44px} + +/* ColorSplitButton */ +.o2k7Skin div.mceColorSplitMenu table {background:#FFF; border:1px solid gray} +.o2k7Skin .mceColorSplitMenu td {padding:2px} +.o2k7Skin .mceColorSplitMenu a {display:block; width:9px; height:9px; overflow:hidden; border:1px solid #808080} +.o2k7Skin .mceColorSplitMenu td.mceMoreColors {padding:1px 3px 1px 1px} +.o2k7Skin .mceColorSplitMenu a.mceMoreColors {width:100%; height:auto; text-align:center; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; line-height:20px; border:1px solid #FFF} +.o2k7Skin .mceColorSplitMenu a.mceMoreColors:hover {border:1px solid #0A246A; background-color:#B6BDD2} +.o2k7Skin a.mceMoreColors:hover {border:1px solid #0A246A} +.o2k7Skin .mceColorPreview {margin-left:2px; width:16px; height:4px; overflow:hidden; background:#9a9b9a;overflow:hidden} +.o2k7Skin .mce_forecolor span.mceAction, .o2k7Skin .mce_backcolor span.mceAction {height:15px;overflow:hidden} + +/* Menu */ +.o2k7Skin .mceMenu {position:absolute; left:0; top:0; z-index:1000; border:1px solid #ABC6DD} +.o2k7Skin .mceNoIcons span.mceIcon {width:0;} +.o2k7Skin .mceNoIcons a .mceText {padding-left:10px} +.o2k7Skin .mceMenu table {background:#FFF} +.o2k7Skin .mceMenu a, .o2k7Skin .mceMenu span, .o2k7Skin .mceMenu {display:block} +.o2k7Skin .mceMenu td {height:20px} +.o2k7Skin .mceMenu a {position:relative;padding:3px 0 4px 0} +.o2k7Skin .mceMenu .mceText {position:relative; display:block; font-family:Tahoma,Verdana,Arial,Helvetica; color:#000; cursor:default; margin:0; padding:0 25px 0 25px; display:block} +.o2k7Skin .mceMenu span.mceText, .o2k7Skin .mceMenu .mcePreview {font-size:11px} +.o2k7Skin .mceMenu pre.mceText {font-family:Monospace} +.o2k7Skin .mceMenu .mceIcon {position:absolute; top:0; left:0; width:22px;} +.o2k7Skin .mceMenu .mceMenuItemEnabled a:hover, .o2k7Skin .mceMenu .mceMenuItemActive {background-color:#dbecf3} +.o2k7Skin td.mceMenuItemSeparator {background:#DDD; height:1px} +.o2k7Skin .mceMenuItemTitle a {border:0; background:#E5EFFD; border-bottom:1px solid #ABC6DD} +.o2k7Skin .mceMenuItemTitle span.mceText {color:#000; font-weight:bold; padding-left:4px} +.o2k7Skin .mceMenuItemDisabled .mceText {color:#888} +.o2k7Skin .mceMenuItemSelected .mceIcon {background:url(../default/img/menu_check.gif)} +.o2k7Skin .mceNoIcons .mceMenuItemSelected a {background:url(../default/img/menu_arrow.gif) no-repeat -6px center} +.o2k7Skin .mceMenu span.mceMenuLine {display:none} +.o2k7Skin .mceMenuItemSub a {background:url(../default/img/menu_arrow.gif) no-repeat top right;} + +/* Progress,Resize */ +.o2k7Skin .mceBlocker {position:absolute; left:0; top:0; z-index:1000; opacity:0.5; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=50); background:#FFF} +.o2k7Skin .mceProgress {position:absolute; left:0; top:0; z-index:1001; background:url(../default/img/progress.gif) no-repeat; width:32px; height:32px; margin:-16px 0 0 -16px} +.o2k7Skin .mcePlaceHolder {border:1px dotted gray} + +/* Formats */ +.o2k7Skin .mce_formatPreview a {font-size:10px} +.o2k7Skin .mce_p span.mceText {} +.o2k7Skin .mce_address span.mceText {font-style:italic} +.o2k7Skin .mce_pre span.mceText {font-family:monospace} +.o2k7Skin .mce_h1 span.mceText {font-weight:bolder; font-size: 2em} +.o2k7Skin .mce_h2 span.mceText {font-weight:bolder; font-size: 1.5em} +.o2k7Skin .mce_h3 span.mceText {font-weight:bolder; font-size: 1.17em} +.o2k7Skin .mce_h4 span.mceText {font-weight:bolder; font-size: 1em} +.o2k7Skin .mce_h5 span.mceText {font-weight:bolder; font-size: .83em} +.o2k7Skin .mce_h6 span.mceText {font-weight:bolder; font-size: .75em} + +/* Theme */ +.o2k7Skin span.mce_bold {background-position:0 0} +.o2k7Skin span.mce_italic {background-position:-60px 0} +.o2k7Skin span.mce_underline {background-position:-140px 0} +.o2k7Skin span.mce_strikethrough {background-position:-120px 0} +.o2k7Skin span.mce_undo {background-position:-160px 0} +.o2k7Skin span.mce_redo {background-position:-100px 0} +.o2k7Skin span.mce_cleanup {background-position:-40px 0} +.o2k7Skin span.mce_bullist {background-position:-20px 0} +.o2k7Skin span.mce_numlist {background-position:-80px 0} +.o2k7Skin span.mce_justifyleft {background-position:-460px 0} +.o2k7Skin span.mce_justifyright {background-position:-480px 0} +.o2k7Skin span.mce_justifycenter {background-position:-420px 0} +.o2k7Skin span.mce_justifyfull {background-position:-440px 0} +.o2k7Skin span.mce_anchor {background-position:-200px 0} +.o2k7Skin span.mce_indent {background-position:-400px 0} +.o2k7Skin span.mce_outdent {background-position:-540px 0} +.o2k7Skin span.mce_link {background-position:-500px 0} +.o2k7Skin span.mce_unlink {background-position:-640px 0} +.o2k7Skin span.mce_sub {background-position:-600px 0} +.o2k7Skin span.mce_sup {background-position:-620px 0} +.o2k7Skin span.mce_removeformat {background-position:-580px 0} +.o2k7Skin span.mce_newdocument {background-position:-520px 0} +.o2k7Skin span.mce_image {background-position:-380px 0} +.o2k7Skin span.mce_help {background-position:-340px 0} +.o2k7Skin span.mce_code {background-position:-260px 0} +.o2k7Skin span.mce_hr {background-position:-360px 0} +.o2k7Skin span.mce_visualaid {background-position:-660px 0} +.o2k7Skin span.mce_charmap {background-position:-240px 0} +.o2k7Skin span.mce_paste {background-position:-560px 0} +.o2k7Skin span.mce_copy {background-position:-700px 0} +.o2k7Skin span.mce_cut {background-position:-680px 0} +.o2k7Skin span.mce_blockquote {background-position:-220px 0} +.o2k7Skin .mce_forecolor span.mceAction {background-position:-720px 0} +.o2k7Skin .mce_backcolor span.mceAction {background-position:-760px 0} +.o2k7Skin span.mce_forecolorpicker {background-position:-720px 0} +.o2k7Skin span.mce_backcolorpicker {background-position:-760px 0} + +/* Plugins */ +.o2k7Skin span.mce_advhr {background-position:-0px -20px} +.o2k7Skin span.mce_ltr {background-position:-20px -20px} +.o2k7Skin span.mce_rtl {background-position:-40px -20px} +.o2k7Skin span.mce_emotions {background-position:-60px -20px} +.o2k7Skin span.mce_fullpage {background-position:-80px -20px} +.o2k7Skin span.mce_fullscreen {background-position:-100px -20px} +.o2k7Skin span.mce_iespell {background-position:-120px -20px} +.o2k7Skin span.mce_insertdate {background-position:-140px -20px} +.o2k7Skin span.mce_inserttime {background-position:-160px -20px} +.o2k7Skin span.mce_absolute {background-position:-180px -20px} +.o2k7Skin span.mce_backward {background-position:-200px -20px} +.o2k7Skin span.mce_forward {background-position:-220px -20px} +.o2k7Skin span.mce_insert_layer {background-position:-240px -20px} +.o2k7Skin span.mce_insertlayer {background-position:-260px -20px} +.o2k7Skin span.mce_movebackward {background-position:-280px -20px} +.o2k7Skin span.mce_moveforward {background-position:-300px -20px} +.o2k7Skin span.mce_media {background-position:-320px -20px} +.o2k7Skin span.mce_nonbreaking {background-position:-340px -20px} +.o2k7Skin span.mce_pastetext {background-position:-360px -20px} +.o2k7Skin span.mce_pasteword {background-position:-380px -20px} +.o2k7Skin span.mce_selectall {background-position:-400px -20px} +.o2k7Skin span.mce_preview {background-position:-420px -20px} +.o2k7Skin span.mce_print {background-position:-440px -20px} +.o2k7Skin span.mce_cancel {background-position:-460px -20px} +.o2k7Skin span.mce_save {background-position:-480px -20px} +.o2k7Skin span.mce_replace {background-position:-500px -20px} +.o2k7Skin span.mce_search {background-position:-520px -20px} +.o2k7Skin span.mce_styleprops {background-position:-560px -20px} +.o2k7Skin span.mce_table {background-position:-580px -20px} +.o2k7Skin span.mce_cell_props {background-position:-600px -20px} +.o2k7Skin span.mce_delete_table {background-position:-620px -20px} +.o2k7Skin span.mce_delete_col {background-position:-640px -20px} +.o2k7Skin span.mce_delete_row {background-position:-660px -20px} +.o2k7Skin span.mce_col_after {background-position:-680px -20px} +.o2k7Skin span.mce_col_before {background-position:-700px -20px} +.o2k7Skin span.mce_row_after {background-position:-720px -20px} +.o2k7Skin span.mce_row_before {background-position:-740px -20px} +.o2k7Skin span.mce_merge_cells {background-position:-760px -20px} +.o2k7Skin span.mce_table_props {background-position:-980px -20px} +.o2k7Skin span.mce_row_props {background-position:-780px -20px} +.o2k7Skin span.mce_split_cells {background-position:-800px -20px} +.o2k7Skin span.mce_template {background-position:-820px -20px} +.o2k7Skin span.mce_visualchars {background-position:-840px -20px} +.o2k7Skin span.mce_abbr {background-position:-860px -20px} +.o2k7Skin span.mce_acronym {background-position:-880px -20px} +.o2k7Skin span.mce_attribs {background-position:-900px -20px} +.o2k7Skin span.mce_cite {background-position:-920px -20px} +.o2k7Skin span.mce_del {background-position:-940px -20px} +.o2k7Skin span.mce_ins {background-position:-960px -20px} +.o2k7Skin span.mce_pagebreak {background-position:0 -40px} +.o2k7Skin .mce_spellchecker span.mceAction {background-position:-540px -20px} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui_black.css b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui_black.css new file mode 100644 index 0000000..81dbfe4 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui_black.css @@ -0,0 +1,8 @@ +/* Black */ +.o2k7SkinBlack .mceToolbar .mceToolbarStart span, .o2k7SkinBlack .mceToolbar .mceToolbarEnd span, .o2k7SkinBlack .mceButton, .o2k7SkinBlack .mceSplitButton, .o2k7SkinBlack .mceSeparator, .o2k7SkinBlack .mceSplitButton a.mceOpen, .o2k7SkinBlack .mceListBox a.mceOpen {background-image:url(img/button_bg_black.png)} +.o2k7SkinBlack table, .o2k7SkinBlack .mceMenuItemTitle a, .o2k7SkinBlack .mceMenuItemTitle span.mceText, .o2k7SkinBlack .mceStatusbar div, .o2k7SkinBlack .mceStatusbar span, .o2k7SkinBlack .mceStatusbar a {background:#535353; color:#FFF} +.o2k7SkinBlack table.mceListBoxEnabled .mceText, o2k7SkinBlack .mceListBox .mceText {background:#FFF; border:1px solid #CBCFD4; border-bottom-color:#989FA9; border-right:0} +.o2k7SkinBlack table.mceListBoxEnabled:hover .mceText, .o2k7SkinBlack .mceListBoxHover .mceText, .o2k7SkinBlack .mceListBoxSelected .mceText {background:#FFF; border:1px solid #FFBD69; border-right:0} +.o2k7SkinBlack .mceExternalToolbar, .o2k7SkinBlack .mceListBox .mceText, .o2k7SkinBlack div.mceMenu, .o2k7SkinBlack table.mceLayout, .o2k7SkinBlack .mceMenuItemTitle a, .o2k7SkinBlack table.mceLayout tr.mceFirst td, .o2k7SkinBlack table.mceLayout, .o2k7SkinBlack .mceMenuItemTitle a, .o2k7SkinBlack table.mceLayout tr.mceLast td, .o2k7SkinBlack .mceIframeContainer {border-color: #535353;} +.o2k7SkinBlack table.mceSplitButtonEnabled:hover a.mceAction, .o2k7SkinBlack .mceSplitButtonHover a.mceAction, .o2k7SkinBlack .mceSplitButtonSelected {background-image:url(img/button_bg_black.png)} +.o2k7SkinBlack .mceMenu .mceMenuItemEnabled a:hover, .o2k7SkinBlack .mceMenu .mceMenuItemActive {background-color:#FFE7A1} \ No newline at end of file diff --git a/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui_silver.css b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui_silver.css new file mode 100644 index 0000000..e8ae844 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui_silver.css @@ -0,0 +1,5 @@ +/* Silver */ +.o2k7SkinSilver .mceToolbar .mceToolbarStart span, .o2k7SkinSilver .mceButton, .o2k7SkinSilver .mceSplitButton, .o2k7SkinSilver .mceSeparator, .o2k7SkinSilver .mceSplitButton a.mceOpen, .o2k7SkinSilver .mceListBox a.mceOpen {background-image:url(img/button_bg_silver.png)} +.o2k7SkinSilver table, .o2k7SkinSilver .mceMenuItemTitle a {background:#eee} +.o2k7SkinSilver .mceListBox .mceText {background:#FFF} +.o2k7SkinSilver .mceExternalToolbar, .o2k7SkinSilver .mceListBox .mceText, .o2k7SkinSilver div.mceMenu, .o2k7SkinSilver table.mceLayout, .o2k7SkinSilver .mceMenuItemTitle a, .o2k7SkinSilver table.mceLayout tr.mceFirst td, .o2k7SkinSilver table.mceLayout, .o2k7SkinSilver .mceMenuItemTitle a, .o2k7SkinSilver table.mceLayout tr.mceLast td, .o2k7SkinSilver .mceIframeContainer {border-color: #bbb} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/content.css b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/content.css new file mode 100644 index 0000000..aee70e7 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/content.css @@ -0,0 +1,92 @@ +/* default styles */ +body {background:#FFF;} +body.mceForceColors {background:#FFF; color:#000;} +h1 {font-size: 2em} +h2 {font-size: 1.5em} +h3 {font-size: 1.17em} +h4 {font-size: 1em} +h5 {font-size: .83em} +h6 {font-size: .75em} +.mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} +a.mceItemAnchor {width:12px; line-height:6px; overflow:hidden; padding-left:12px; background:url(../default/img/items.gif) no-repeat bottom left;} +img.mceItemAnchor {width:12px; height:12px; background:url(../default/img/items.gif) no-repeat;} +img {border:0;} +table {cursor:default} +table td, table th {cursor:text} +ins {border-bottom:1px solid green; text-decoration: none; color:green} +del {color:red; text-decoration:line-through} +cite {border-bottom:1px dashed blue} +acronym {border-bottom:1px dotted #CCC; cursor:help} +abbr, html\:abbr {border-bottom:1px dashed #CCC; cursor:help} + +/* WordPress styles */ +html { + background-color: #fff; +} + +.aligncenter, +dl.aligncenter { + display: block; + margin-left: auto; + margin-right: auto; +} + +.alignleft { + float: left; +} + +.alignright { + float: right; +} + +.wp-caption { + border: 1px solid #ddd; + text-align: center; + background-color: #f3f3f3; + padding-top: 4px; + margin: 10px; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} + +.wp-caption img { + margin: 0; + padding: 0; + border: 0 none; +} + +.wp-caption-dd { + font-size: 11px; + line-height: 17px; + padding: 0 4px 5px; + margin: 0; +} + +img.wpGallery { + border: 1px dotted #cc0000; + background: #ffffcc url("../../../../plugins/wpgallery/img/gallery.png") no-repeat scroll center center; + width: 99%; + height: 250px; +} + +body.mceContentBody { + font: 13px/19px Georgia, "Times New Roman", "Bitstream Charter", Times, serif; + padding: 0.6em; + margin: 0; +} + +pre { + font: 12px/18px Consolas, Monaco, "Courier New", Courier, monospace; +} + +td { + color: #000; + font-size: 11px; + margin: 8px; +} + +.mceIEcenter { + text-align: center; +} diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/dialog.css b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/dialog.css new file mode 100644 index 0000000..7fe6b8d --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/dialog.css @@ -0,0 +1,117 @@ +/* Generic */ +body { +font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; +background:#f1f1f1; +padding:0; +margin:8px 8px 0 8px; +} + +html {background:#f1f1f1;} +td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} +textarea {resize:none;outline:none;} +a:link, a:visited {color:black;} +a:hover {color:#2B6FB6;} +.nowrap {white-space: nowrap} + +/* Forms */ +fieldset {margin:0; padding:4px; border:1px solid #dfdfdf; font-family:Verdana, Arial; font-size:10px;} +legend {color:#2B6FB6; font-weight:bold;} +label.msg {display:none;} +label.invalid {color:#EE0000; display:inline;} +input.invalid {border:1px solid #EE0000;} +input {background:#FFF; border:1px solid #dfdfdf;} +input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} +input, select, textarea {border:1px solid #dfdfdf;} +input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} +input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} +.input_noborder {border:0;} + +/* Buttons */ +#insert, #cancel, #apply, .mceActionPanel .button, input.mceButton, .updateButton { + border: 1px solid #bbb; + margin:0; + padding:0 0 1px; + font-weight:bold; + font-size: 11px; + width:94px; + height:24px; + background:url(img/fade-butt.png) 0 0; + color:#000; + cursor:pointer; + -moz-border-radius: 3px; + -khtml-border-radius: 3px; + -webkit-border-radius: 3px; + border-radius: 3px; +} +#insert:hover, #cancel:hover, input.mceButton:hover, .updateButton:hover, +#insert:focus, #cancel:focus, input.mceButton:focus, .updateButton:focus { + border: 1px solid #555; +} + +/* Browse */ +a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} +.mceOldBoxModel a.browse span {width:22px; height:20px;} +a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} +a.browse span.disabled {border:1px solid white; -moz-opacity:0.3; opacity:0.3; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);} +a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} +a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} +.mceOldBoxModel a.pickcolor span {width:21px; height:17px;} +a.pickcolor:hover span {background-color:#B2BBD0;} +a.pickcolor, a.browse {text-decoration:none} + +/* Charmap */ +table.charmap {border:1px solid #AAA; text-align:center} +td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} +#charmap a {display:block; color:#000; text-decoration:none; border:0} +#charmap a:hover {background:#CCC;color:#2B6FB6} +#charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} +#charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} +#charmap #charmapView {background-color:#fff;} + +/* Source */ +.wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} +.mceActionPanel {margin-top:5px;} + +/* Tabs classes */ +.tabs {width:100%; height:18px; line-height:normal; background:url(img/tabs.gif) repeat-x 0 -72px;} +.tabs ul {margin:0; padding:0; list-style:none;} +.tabs li {float:left; background:url(img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;} +.tabs li.current {background:url(img/tabs.gif) no-repeat 0 -18px; margin-right:2px;} +.tabs span {float:left; display:block; background:url(img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;} +.tabs .current span {background:url(img/tabs.gif) no-repeat right -54px;} +.tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} +.tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} + +/* Panels */ +.panel_wrapper div.panel {display:none;} +.panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} +.panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;} + +/* Columns */ +.column {float:left;} +.properties {width:100%;} +.properties .column1 {} +.properties .column2 {text-align:left;} + +/* Titles */ +h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} +h3 {font-size:14px;} +.title {font-size:12px; font-weight:bold; color:#2B6FB6;} + +/* Dialog specific */ +#link .panel_wrapper, #link div.current {height:125px;} +#image .panel_wrapper, #image div.current {height:200px;} +#plugintable thead {font-weight:bold; background:#DDD;} +#plugintable, #about #plugintable td {border:1px solid #919B9C;} +#plugintable {width:96%; margin-top:10px;} +#pluginscontainer {height:290px; overflow:auto;} +#colorpicker #preview {float:right; width:50px; height:14px;line-height:1px; border:1px solid black; margin-left:5px;} +#colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} +#colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} +#colorpicker #light div {overflow:hidden;} +#colorpicker #previewblock {float:right; padding-left:10px; height:20px;} +#colorpicker .panel_wrapper div.current {height:175px;} +#colorpicker #namedcolors {width:150px;} +#colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} +#colorpicker #colornamecontainer {margin-top:5px;} +#colorpicker #picker_panel fieldset {margin:auto;width:325px;} \ No newline at end of file diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/butt2.png b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/butt2.png new file mode 100644 index 0000000..adb83cd Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/butt2.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/button_bg.png b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/button_bg.png new file mode 100644 index 0000000..12cfb41 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/button_bg.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/down_arrow.gif b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/down_arrow.gif new file mode 100644 index 0000000..687b241 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/down_arrow.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/fade-butt.png b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/fade-butt.png new file mode 100644 index 0000000..42f08b7 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/fade-butt.png differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/separator.gif b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/separator.gif new file mode 100644 index 0000000..4f39b80 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/separator.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/tabs.gif b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/tabs.gif new file mode 100644 index 0000000..ce4be63 Binary files /dev/null and b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/img/tabs.gif differ diff --git a/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/ui.css b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/ui.css new file mode 100644 index 0000000..1cd2771 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/ui.css @@ -0,0 +1,380 @@ +/* Reset */ +.wp_themeSkin table, .wp_themeSkin tbody, .wp_themeSkin a, .wp_themeSkin img, .wp_themeSkin tr, .wp_themeSkin div, .wp_themeSkin td, .wp_themeSkin iframe, .wp_themeSkin span, .wp_themeSkin *, .wp_themeSkin .mceText { +border:0; margin:0; padding:0; white-space:nowrap; text-decoration:none; font-weight:normal; cursor:default; vertical-align:baseline; width:auto; border-collapse:separate; +} +.wp_themeSkin a:hover, .wp_themeSkin a:link, .wp_themeSkin a:visited, .wp_themeSkin a:active {text-decoration:none; font-weight:normal; cursor:default;} +.wp_themeSkin table td {vertical-align:middle} + +/* Containers */ +.wp_themeSkin table {} +.wp_themeSkin iframe {display:block;} +.wp_themeSkin .mceToolbar {padding: 2px;} + +/* External */ +.wp_themeSkin .mceExternalToolbar {position:absolute; border-bottom:0; display:none} +.wp_themeSkin .mceExternalToolbar td.mceToolbar {padding-right:13px;} +.wp_themeSkin .mceExternalClose {position:absolute; top:3px; right:3px; width:7px; height:7px; background:url(../../img/icons.gif) -820px 0} + +/* Layout */ +.wp_themeSkin table.mceToolbar, .wp_themeSkin tr.mceFirst .mceToolbar tr td, .wp_themeSkin tr.mceLast .mceToolbar tr td {border:0; margin:0; padding:0} +.wp_themeSkin table.mceLayout {border:0;} +.wp_themeSkin .mceIframeContainer {} +.wp_themeSkin .mceStatusbar { + display: block; + font-family: 'MS Sans Serif',sans-serif,Verdana,Arial; + font-size: 9pt; + line-height: 16px; + overflow: visible; + height: 20px; + border-top-width: 1px; + border-top-style: solid; +} +.wp_themeSkin .mceStatusbar div {float:left; padding:2px;} +.wp_themeSkin .mceStatusbar a.mceResize { + display: block; + float: right; + background: url(../../img/icons.gif) -800px 0; + width: 20px; + height: 20px; + cursor: se-resize +} +.wp_themeSkin .mceStatusbar a:hover {text-decoration:underline} +.wp_themeSkin table.mceToolbar {margin: 0 2px 2px;} +.wp_themeSkin #content_toolbar1 {margin-top: 2px;} +.wp_themeSkin .mceToolbar .mceToolbarEndListBox span {display:none} +.wp_themeSkin span.mceIcon, .wp_themeSkin img.mceIcon {display:block; width:20px; height:20px} +.wp_themeSkin .mceIcon {background:url(../../img/icons.gif) no-repeat 20px 20px} + +/* Button */ +.wp_themeSkin .mceButton { + display:block; + width: 20px; + height: 20px; + cursor: default; + padding: 1px 2px; + margin: 1px; + background-image: url(img/butt2.png); + background-position: left top; + background-repeat: repeat-x; + -moz-border-radius: 3px; + -webkit-border-radius: 3px; + -khtml-border-radius: 3px; + border-radius: 3px; +} +.wp_themeSkin a.mceButton span, .wp_themeSkin a.mceButton img {} +.wp_themeSkin .mceOldBoxModel a.mceButton span, .wp_themeSkin .mceOldBoxModel a.mceButton img {margin:0 0 0 1px} +.wp_themeSkin a.mceButtonEnabled:hover { + background-position:0 -10px; +} +.wp_themeSkin a.mceButtonActive, .wp_themeSkin a.mceButtonSelected { + background-image: inherit; +} +.wp_themeSkin .mceButtonDisabled .mceIcon {opacity:0.3; filter:alpha(opacity=30);} +.wp_themeSkin .mceButtonDisabled {} + +/* Separator */ +.wp_themeSkin .mceSeparator { + height: 24px; + width: 1px; + display: block; + background: transparent; + overflow: hidden; + margin: 0 2px; +} + +/* ListBox */ +.wp_themeSkin .mceListBox, .wp_themeSkin .mceListBox a {display:block} +.wp_themeSkin .mceListBox .mceText { + padding: 1px 2px 1px 5px; + text-align:left; + text-decoration: none !important; + width:70px; + background-image: url(img/butt2.png); + background-position: left top; + background-repeat: repeat-x; + font-family: Tahoma,Verdana,Arial,Helvetica; + font-size: 11px; + height: 20px; + line-height: 20px; + overflow: hidden; +} +.wp_themeSkin .mceListBox { + margin: 1px; + direction: ltr; +} +.wp_themeSkin .mceListBox .mceOpen { + width: 14px; + height: 20px; + border-collapse: separate; + background-image: url(img/butt2.png); + background-position: left top; + background-repeat: repeat-x; + padding: 1px; + border-left: 0 none !important; +} +.wp_themeSkin .mceListBox .mceOpen span { + display: block; + width:14px; + height:20px; + background-image: url(img/down_arrow.gif); + background-position: 2px 1px; + background-repeat: no-repeat; +} +.wp_themeSkin table.mceListBoxEnabled:hover .mceText, +.wp_themeSkin .mceListBoxHover .mceText, +.wp_themeSkin .mceListBoxSelected .mceText, +.wp_themeSkin table.mceListBoxEnabled:hover .mceOpen, +.wp_themeSkin .mceListBoxHover .mceOpen, +.wp_themeSkin .mceListBoxSelected .mceOpen { + background-image: none; +} +.wp_themeSkin .mceListBoxDisabled .mceText {color:gray} +.wp_themeSkin .mceListBoxMenu {overflow:auto; overflow-x:hidden} +.wp_themeSkin .mceOldBoxModel .mceListBox .mceText {height:22px} +.wp_themeSkin select.mceListBox {font-family:Tahoma,Verdana,Arial,Helvetica; font-size:12px;} + +/* SplitButton */ +.wp_themeSkin .mceSplitButton a, .wp_themeSkin .mceSplitButton span {display:block; height:20px} +.wp_themeSkin .mceSplitButton { + display:block; + margin: 1px; + direction: ltr; +} +.wp_themeSkin table.mceSplitButton td { + padding: 2px; + background-image: url(img/butt2.png); + background-position: left top; + background-repeat: repeat-x; +} +.wp_themeSkin .mceSplitButton a.mceAction { + height:20px; + width:20px; + padding: 1px 2px; +} +.wp_themeSkin .mceSplitButton span.mceAction { + background: url(../../img/icons.gif) 20px 20px; + width:20px; +} +.wp_themeSkin .mceSplitButton a.mceOpen { + width:10px; + height:20px; + background-image: url(img/down_arrow.gif); + background-position: 1px 2px; + background-repeat: no-repeat; + padding: 1px; + border-left: 0 none !important; +} +.wp_themeSkin .mceSplitButton span.mceOpen {display:none} +.wp_themeSkin .mceSplitButtonDisabled .mceAction { + opacity:0.3; filter:alpha(opacity=30); +} +.wp_themeSkin .mceListBox a.mceText, .wp_themeSkin .mceSplitButton a.mceAction { + -moz-border-radius-bottomleft: 3px; + -webkit-border-bottom-left-radius: 3px; + -khtml-border-bottom-left-radius: 3px; + border-bottom-left-radius: 3px; + -moz-border-radius-topleft: 3px; + -webkit-border-top-left-radius: 3px; + -khtml-border-top-left-radius: 3px; + border-top-left-radius: 3px; +} +.wp_themeSkin .mceSplitButton a.mceOpen, .wp_themeSkin .mceListBox a.mceOpen { + -moz-border-radius-bottomright: 3px; + -webkit-border-bottom-right-radius: 3px; + -khtml-border-bottom-right-radius: 3px; + border-bottom-right-radius: 3px; + -moz-border-radius-topright: 3px; + -webkit-border-top-right-radius: 3px; + -khtml-border-top-right-radius: 3px; + border-top-right-radius: 3px; +} + +/* ColorSplitButton */ +.wp_themeSkin div.mceColorSplitMenu table {} +.wp_themeSkin .mceColorSplitMenu td {padding:2px} +.wp_themeSkin .mceColorSplitMenu a {display:block; width:9px; height:9px; overflow:hidden;} +.wp_themeSkin .mceColorSplitMenu td.mceMoreColors {padding:1px 3px 1px 1px} +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors {width:100%; height:auto; text-align:center; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; line-height:20px;} +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover {} +.wp_themeSkin a.mceMoreColors:hover {} +.wp_themeSkin .mceColorPreview {margin: -4px 0 0 2px; width:16px; height:4px; overflow:hidden} + +/* Menu */ +.wp_themeSkin .mceMenu {position:absolute; left:0; top:0; z-index:1000;} +.wp_themeSkin .mceNoIcons span.mceIcon {width:0;} +.wp_themeSkin .mceNoIcons a .mceText {padding-left:10px} +.wp_themeSkin .mceMenu table {} +.wp_themeSkin .mceMenu a, .wp_themeSkin .mceMenu span, .wp_themeSkin .mceMenu {display:block} +.wp_themeSkin .mceMenu td {height:20px;overflow:hidden;} +.wp_themeSkin .mceMenu a { + position:relative; + padding:3px 0 4px 0; + text-decoration: none !important; +} +.wp_themeSkin .mceMenu .mceText { + position:relative; + display:block; + font-family:Tahoma,Verdana,Arial,Helvetica; + cursor:default; + margin:0; + padding:0 25px; +} +.wp_themeSkin .mceMenu span.mceText, .wp_themeSkin .mceMenu .mcePreview {font-size:11px} +.wp_themeSkin .mceMenu pre.mceText {font-family:Monospace} +.wp_themeSkin .mceMenu .mceIcon {position:absolute; top:0; left:0; width:22px;} +.wp_themeSkin .mceMenu .mceMenuItemEnabled a:hover, +.wp_themeSkin .mceMenu .mceMenuItemActive {} +.wp_themeSkin td.mceMenuItemSeparator {height:1px} +.wp_themeSkin .mceMenuItemTitle a { + border-top: 0; + border-right: 0; + border-left: 0; + border-bottom-style: solid; + border-bottom-width: 1px; + text-decoration: none !important; +} +.wp_themeSkin .mceMenuItemTitle span.mceText {font-weight:bold; padding-left:4px} +.wp_themeSkin .mceMenuItemDisabled .mceText {} +.wp_themeSkin .mceMenuItemSelected .mceIcon {background:url(../default/img/menu_check.gif)} +.wp_themeSkin .mceNoIcons .mceMenuItemSelected a {background:url(../default/img/menu_arrow.gif) no-repeat -6px center} +.wp_themeSkin .mceMenu span.mceMenuLine {display:none} +.wp_themeSkin .mceMenuItemSub a {background:url(../default/img/menu_arrow.gif) no-repeat top right;} + +/* Progress,Resize */ +.wp_themeSkin .mceBlocker {position:absolute; left:0; top:0; z-index:1000; opacity:0.5; filter:alpha(opacity=50); background:#FFF} +.wp_themeSkin .mceProgress {position:absolute; left:0; top:0; z-index:1001; background:url(../default/img/progress.gif) no-repeat; width:32px; height:32px; margin:-16px 0 0 -16px} +.wp_themeSkin .mcePlaceHolder {border:1px dotted gray} + +/* Formats */ +.wp_themeSkin .mce_formatPreview a {font-size:10px} +.wp_themeSkin .mce_p span.mceText {} +.wp_themeSkin .mce_address span.mceText {font-style:italic} +.wp_themeSkin .mce_pre span.mceText {font-family:monospace} +.wp_themeSkin .mce_h1 span.mceText {font-weight:bolder; font-size: 2em} +.wp_themeSkin .mce_h2 span.mceText {font-weight:bolder; font-size: 1.5em} +.wp_themeSkin .mce_h3 span.mceText {font-weight:bolder; font-size: 1.17em} +.wp_themeSkin .mce_h4 span.mceText {font-weight:bolder; font-size: 1em} +.wp_themeSkin .mce_h5 span.mceText {font-weight:bolder; font-size: .83em} +.wp_themeSkin .mce_h6 span.mceText {font-weight:bolder; font-size: .75em} + +/* Theme */ +.wp_themeSkin span.mce_bold {background-position:0 0} +.wp_themeSkin span.mce_italic {background-position:-60px 0} +.wp_themeSkin span.mce_underline {background-position:-140px 0} +.wp_themeSkin span.mce_strikethrough {background-position:-120px 0} +.wp_themeSkin span.mce_undo {background-position:-160px 0} +.wp_themeSkin span.mce_redo {background-position:-100px 0} +.wp_themeSkin span.mce_cleanup {background-position:-40px 0} +.wp_themeSkin span.mce_bullist {background-position:-20px 0} +.wp_themeSkin span.mce_numlist {background-position:-80px 0} +.wp_themeSkin span.mce_justifyleft {background-position:-460px 0} +.wp_themeSkin span.mce_justifyright {background-position:-480px 0} +.wp_themeSkin span.mce_justifycenter {background-position:-420px 0} +.wp_themeSkin span.mce_justifyfull {background-position:-440px 0} +.wp_themeSkin span.mce_anchor {background-position:-200px 0} +.wp_themeSkin span.mce_indent {background-position:-400px 0} +.wp_themeSkin span.mce_outdent {background-position:-540px 0} +.wp_themeSkin span.mce_link {background-position:-500px 0} +.wp_themeSkin span.mce_unlink {background-position:-640px 0} +.wp_themeSkin span.mce_sub {background-position:-600px 0} +.wp_themeSkin span.mce_sup {background-position:-620px 0} +.wp_themeSkin span.mce_removeformat {background-position:-580px 0} +.wp_themeSkin span.mce_newdocument {background-position:-520px 0} +.wp_themeSkin span.mce_image {background-position:-380px 0} +.wp_themeSkin span.mce_help {background-position:-340px 0} +.wp_themeSkin span.mce_code {background-position:-260px 0} +.wp_themeSkin span.mce_hr {background-position:-360px 0} +.wp_themeSkin span.mce_visualaid {background-position:-660px 0} +.wp_themeSkin span.mce_charmap {background-position:-240px 0} +.wp_themeSkin span.mce_paste {background-position:-560px 0} +.wp_themeSkin span.mce_copy {background-position:-700px 0} +.wp_themeSkin span.mce_cut {background-position:-680px 0} +.wp_themeSkin span.mce_blockquote {background-position:-220px 0} +.wp_themeSkin .mce_forecolor span.mceAction {background-position:-720px 0} +.wp_themeSkin .mce_backcolor span.mceAction {background-position:-760px 0} +.wp_themeSkin .mce_forecolorpicker {background-position:-720px 0} +.wp_themeSkin .mce_backcolorpicker {background-position:-760px 0} + +/* Plugins */ +.wp_themeSkin span.mce_advhr {background-position:-0px -20px} +.wp_themeSkin span.mce_ltr {background-position:-20px -20px} +.wp_themeSkin span.mce_rtl {background-position:-40px -20px} +.wp_themeSkin span.mce_emotions {background-position:-60px -20px} +.wp_themeSkin span.mce_fullpage {background-position:-80px -20px} +.wp_themeSkin span.mce_fullscreen {background-position:-100px -20px} +.wp_themeSkin span.mce_iespell {background-position:-120px -20px} +.wp_themeSkin span.mce_insertdate {background-position:-140px -20px} +.wp_themeSkin span.mce_inserttime {background-position:-160px -20px} +.wp_themeSkin span.mce_absolute {background-position:-180px -20px} +.wp_themeSkin span.mce_backward {background-position:-200px -20px} +.wp_themeSkin span.mce_forward {background-position:-220px -20px} +.wp_themeSkin span.mce_insert_layer {background-position:-240px -20px} +.wp_themeSkin span.mce_insertlayer {background-position:-260px -20px} +.wp_themeSkin span.mce_movebackward {background-position:-280px -20px} +.wp_themeSkin span.mce_moveforward {background-position:-300px -20px} +.wp_themeSkin span.mce_media {background-position:-320px -20px} +.wp_themeSkin span.mce_nonbreaking {background-position:-340px -20px} +.wp_themeSkin span.mce_pastetext {background-position:-360px -20px} +.wp_themeSkin span.mce_pasteword {background-position:-380px -20px} +.wp_themeSkin span.mce_selectall {background-position:-400px -20px} +.wp_themeSkin span.mce_preview {background-position:-420px -20px} +.wp_themeSkin span.mce_print {background-position:-440px -20px} +.wp_themeSkin span.mce_cancel {background-position:-460px -20px} +.wp_themeSkin span.mce_save {background-position:-480px -20px} +.wp_themeSkin span.mce_replace {background-position:-500px -20px} +.wp_themeSkin span.mce_search {background-position:-520px -20px} +.wp_themeSkin span.mce_styleprops {background-position:-560px -20px} +.wp_themeSkin span.mce_table {background-position:-580px -20px} +.wp_themeSkin span.mce_cell_props {background-position:-600px -20px} +.wp_themeSkin span.mce_delete_table {background-position:-620px -20px} +.wp_themeSkin span.mce_delete_col {background-position:-640px -20px} +.wp_themeSkin span.mce_delete_row {background-position:-660px -20px} +.wp_themeSkin span.mce_col_after {background-position:-680px -20px} +.wp_themeSkin span.mce_col_before {background-position:-700px -20px} +.wp_themeSkin span.mce_row_after {background-position:-720px -20px} +.wp_themeSkin span.mce_row_before {background-position:-740px -20px} +.wp_themeSkin span.mce_merge_cells {background-position:-760px -20px} +.wp_themeSkin span.mce_table_props {background-position:-980px -20px} +.wp_themeSkin span.mce_row_props {background-position:-780px -20px} +.wp_themeSkin span.mce_split_cells {background-position:-800px -20px} +.wp_themeSkin span.mce_template {background-position:-820px -20px} +.wp_themeSkin span.mce_visualchars {background-position:-840px -20px} +.wp_themeSkin span.mce_abbr {background-position:-860px -20px} +.wp_themeSkin span.mce_acronym {background-position:-880px -20px} +.wp_themeSkin span.mce_attribs {background-position:-900px -20px} +.wp_themeSkin span.mce_cite {background-position:-920px -20px} +.wp_themeSkin span.mce_del {background-position:-940px -20px} +.wp_themeSkin span.mce_ins {background-position:-960px -20px} +.wp_themeSkin span.mce_pagebreak {background-position:0 -40px} +.wp_themeSkin .mce_spellchecker span.mceAction {background-position:-540px -20px} + +/* border */ +.wp_themeSkin .mceExternalToolbar, +.wp_themeSkin .mceButton, +.wp_themeSkin a.mceButtonEnabled:hover, +.wp_themeSkin a.mceButtonActive, +.wp_themeSkin a.mceButtonSelected, +.wp_themeSkin .mceListBox .mceText, +.wp_themeSkin .mceListBox .mceOpen, +.wp_themeSkin table.mceListBoxEnabled:hover .mceText, +.wp_themeSkin .mceListBoxHover .mceText, +.wp_themeSkin .mceListBoxSelected .mceText, +.wp_themeSkin table.mceListBoxEnabled:hover .mceOpen, +.wp_themeSkin .mceListBoxHover .mceOpen, +.wp_themeSkin .mceListBoxSelected .mceOpen, +.wp_themeSkin select.mceListBox, +.wp_themeSkin .mceSplitButton a.mceAction, +.wp_themeSkin .mceSplitButton a.mceOpen, +.wp_themeSkin .mceSplitButton a.mceOpen:hover, +.wp_themeSkin .mceSplitButtonSelected a.mceOpen, +.wp_themeSkin table.mceSplitButtonEnabled:hover a.mceAction, +.wp_themeSkin .mceSplitButton a.mceAction:hover, +.wp_themeSkin div.mceColorSplitMenu table, +.wp_themeSkin .mceColorSplitMenu a, +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors, +.wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover, +.wp_themeSkin a.mceMoreColors:hover, +.wp_themeSkin .mceMenu { + border-style: solid; + border-width: 1px; +} diff --git a/wp-includes/js/tinymce/themes/advanced/source_editor.htm b/wp-includes/js/tinymce/themes/advanced/source_editor.htm new file mode 100644 index 0000000..41d7ed4 --- /dev/null +++ b/wp-includes/js/tinymce/themes/advanced/source_editor.htm @@ -0,0 +1,31 @@ + + + + {#advanced_dlg.code_title} + + + + +
    +
    {#advanced_dlg.code_title}
    + +
    + +
    + +
    + + + +
    +
    + +
    + +
    + +
    +
    +
    + + diff --git a/wp-includes/js/tinymce/tiny_mce.js b/wp-includes/js/tinymce/tiny_mce.js new file mode 100644 index 0000000..5e2fe09 --- /dev/null +++ b/wp-includes/js/tinymce/tiny_mce.js @@ -0,0 +1 @@ +var tinymce={majorVersion:"3",minorVersion:"2.4.1",releaseDate:"2009-05-25",_init:function(){var o=this,k=document,l=window,j=navigator,b=j.userAgent,h,a,g,f,e,m;o.isOpera=l.opera&&opera.buildNumber;o.isWebKit=/WebKit/.test(b);o.isIE=!o.isWebKit&&!o.isOpera&&(/MSIE/gi).test(b)&&(/Explorer/gi).test(j.appName);o.isIE6=o.isIE&&/MSIE [56]/.test(b);o.isGecko=!o.isWebKit&&/Gecko/.test(b);o.isMac=b.indexOf("Mac")!=-1;o.isAir=/adobeair/i.test(b);if(l.tinyMCEPreInit){o.suffix=tinyMCEPreInit.suffix;o.baseURL=tinyMCEPreInit.base;o.query=tinyMCEPreInit.query;return}o.suffix="";a=k.getElementsByTagName("base");for(h=0;h=c.length){for(e=0,b=g.length;e=c.length||g[e]!=c[e]){f=e+1;break}}}if(g.length=g.length||g[e]!=c[e]){f=e+1;break}}}if(f==1){return h}for(e=0,b=g.length-(f-1);e=0;c--){if(f[c].length==0||f[c]=="."){continue}if(f[c]==".."){b++;continue}if(b>0){b--;continue}g.push(f[c])}c=e.length-b;if(c<=0){return"/"+g.reverse().join("/")+d}return"/"+e.slice(0,c).join("/")+"/"+g.reverse().join("/")+d},getURI:function(d){var c,b=this;if(!b.source||d){c="";if(!d){if(b.protocol){c+=b.protocol+"://"}if(b.userInfo){c+=b.userInfo+"@"}if(b.host){c+=b.host}if(b.port){c+=":"+b.port}}if(b.path){c+=b.path}if(b.query){c+="?"+b.query}if(b.anchor){c+="#"+b.anchor}b.source=c}return b.source}})})();(function(){var a=tinymce.each;tinymce.create("static tinymce.util.Cookie",{getHash:function(d){var b=this.get(d),c;if(b){a(b.split("&"),function(e){e=e.split("=");c=c||{};c[unescape(e[0])]=unescape(e[1])})}return c},setHash:function(j,b,g,f,i,c){var h="";a(b,function(e,d){h+=(!h?"":"&")+escape(d)+"="+escape(e)});this.set(j,h,g,f,i,c)},get:function(i){var h=document.cookie,g,f=i+"=",d;if(!h){return}d=h.indexOf("; "+f);if(d==-1){d=h.indexOf(f);if(d!=0){return null}}else{d+=2}g=h.indexOf(";",d);if(g==-1){g=h.length}return unescape(h.substring(d+f.length,g))},set:function(i,b,g,f,h,c){document.cookie=i+"="+escape(b)+((g)?"; expires="+g.toGMTString():"")+((f)?"; path="+escape(f):"")+((h)?"; domain="+h:"")+((c)?"; secure":"")},remove:function(e,b){var c=new Date();c.setTime(c.getTime()-1000);this.set(e,"",c,b,c)}})})();tinymce.create("static tinymce.util.JSON",{serialize:function(e){var c,a,d=tinymce.util.JSON.serialize,b;if(e==null){return"null"}b=typeof e;if(b=="string"){a="\bb\tt\nn\ff\rr\"\"''\\\\";return'"'+e.replace(/([\u0080-\uFFFF\x00-\x1f\"])/g,function(g,f){c=a.indexOf(f);if(c+1){return"\\"+a.charAt(c+1)}g=f.charCodeAt().toString(16);return"\\u"+"0000".substring(g.length)+g})+'"'}if(b=="object"){if(e.hasOwnProperty&&e instanceof Array){for(c=0,a="[";c0?",":"")+d(e[c])}return a+"]"}a="{";for(c in e){a+=typeof e[c]!="function"?(a.length>1?',"':'"')+c+'":'+d(e[c]):""}return a+"}"}return""+e},parse:function(s){try{return eval("("+s+")")}catch(ex){}}});tinymce.create("static tinymce.util.XHR",{send:function(g){var a,e,b=window,h=0;g.scope=g.scope||this;g.success_scope=g.success_scope||g.scope;g.error_scope=g.error_scope||g.scope;g.async=g.async===false?false:true;g.data=g.data||"";function d(i){a=0;try{a=new ActiveXObject(i)}catch(c){}return a}a=b.XMLHttpRequest?new XMLHttpRequest():d("Microsoft.XMLHTTP")||d("Msxml2.XMLHTTP");if(a){if(a.overrideMimeType){a.overrideMimeType(g.content_type)}a.open(g.type||(g.data?"POST":"GET"),g.url,g.async);if(g.content_type){a.setRequestHeader("Content-Type",g.content_type)}a.send(g.data);function f(){if(!g.async||a.readyState==4||h++>10000){if(g.success&&h<10000&&a.status==200){g.success.call(g.success_scope,""+a.responseText,a,g)}else{if(g.error){g.error.call(g.error_scope,h>10000?"TIMED_OUT":"GENERAL",a,g)}}a=null}else{b.setTimeout(f,10)}}if(!g.async){return f()}e=b.setTimeout(f,10)}}});(function(){var c=tinymce.extend,b=tinymce.util.JSON,a=tinymce.util.XHR;tinymce.create("tinymce.util.JSONRequest",{JSONRequest:function(d){this.settings=c({},d);this.count=0},send:function(f){var e=f.error,d=f.success;f=c(this.settings,f);f.success=function(h,g){h=b.parse(h);if(typeof(h)=="undefined"){h={error:"JSON Parse error."}}if(h.error){e.call(f.error_scope||f.scope,h.error,g)}else{d.call(f.success_scope||f.scope,h.result)}};f.error=function(h,g){e.call(f.error_scope||f.scope,h,g)};f.data=b.serialize({id:f.id||"c"+(this.count++),method:f.method,params:f.params});f.content_type="application/json";a.send(f)},"static":{sendRPC:function(d){return new tinymce.util.JSONRequest().send(d)}}})}());(function(c){var e=c.each,b=c.is;var d=c.isWebKit,a=c.isIE;c.create("tinymce.dom.DOMUtils",{doc:null,root:null,files:null,pixelStyles:/^(top|left|bottom|right|width|height|borderWidth)$/,props:{"for":"htmlFor","class":"className",className:"className",checked:"checked",disabled:"disabled",maxlength:"maxLength",readonly:"readOnly",selected:"selected",value:"value",id:"id",name:"name",type:"type"},DOMUtils:function(i,g){var f=this;f.doc=i;f.win=window;f.files={};f.cssFlicker=false;f.counter=0;f.boxModel=!c.isIE||i.compatMode=="CSS1Compat";f.stdMode=i.documentMode===8;f.settings=g=c.extend({keep_values:false,hex_colors:1,process_html:1},g);if(c.isIE6){try{i.execCommand("BackgroundImageCache",false,true)}catch(h){f.cssFlicker=true}}c.addUnload(f.destroy,f)},getRoot:function(){var f=this,g=f.settings;return(g&&f.get(g.root_element))||f.doc.body},getViewPort:function(g){var h,f;g=!g?this.win:g;h=g.document;f=this.boxModel?h.documentElement:h.body;return{x:g.pageXOffset||f.scrollLeft,y:g.pageYOffset||f.scrollTop,w:g.innerWidth||f.clientWidth,h:g.innerHeight||f.clientHeight}},getRect:function(i){var h,f=this,g;i=f.get(i);h=f.getPos(i);g=f.getSize(i);return{x:h.x,y:h.y,w:g.w,h:g.h}},getSize:function(j){var g=this,f,i;j=g.get(j);f=g.getStyle(j,"width");i=g.getStyle(j,"height");if(f.indexOf("px")===-1){f=0}if(i.indexOf("px")===-1){i=0}return{w:parseInt(f)||j.offsetWidth||j.clientWidth,h:parseInt(i)||j.offsetHeight||j.clientHeight}},is:function(g,f){return c.dom.Sizzle.matches(f,g.nodeType?[g]:g).length>0},getParent:function(i,h,g){return this.getParents(i,h,g,false)},getParents:function(p,k,i,m){var h=this,g,j=h.settings,l=[];p=h.get(p);m=m===undefined;if(j.strict_root){i=i||h.getRoot()}if(b(k,"string")){g=k;if(k==="*"){k=function(f){return f.nodeType==1}}else{k=function(f){return h.is(f,g)}}}while(p){if(p==i||!p.nodeType||p.nodeType===9){break}if(!k||k(p)){if(m){l.push(p)}else{return p}}p=p.parentNode}return m?l:null},get:function(f){var g;if(f&&this.doc&&typeof(f)=="string"){g=f;f=this.doc.getElementById(f);if(f&&f.id!==g){return this.doc.getElementsByName(g)[1]}}return f},select:function(h,g){var f=this;return c.dom.Sizzle(h,f.get(g)||f.get(f.settings.root_element)||f.doc,[])},add:function(j,l,f,i,k){var g=this;return this.run(j,function(n){var m,h;m=b(l,"string")?g.doc.createElement(l):l;g.setAttribs(m,f);if(i){if(i.nodeType){m.appendChild(i)}else{g.setHTML(m,i)}}return !k?n.appendChild(m):m})},create:function(i,f,g){return this.add(this.doc.createElement(i),i,f,g,1)},createHTML:function(m,f,j){var l="",i=this,g;l+="<"+m;for(g in f){if(f.hasOwnProperty(g)){l+=" "+g+'="'+i.encode(f[g])+'"'}}if(c.is(j)){return l+">"+j+""}return l+" />"},remove:function(h,f){var g=this;return this.run(h,function(m){var l,k,j;l=m.parentNode;if(!l){return null}if(f){for(j=m.childNodes.length-1;j>=0;j--){g.insertAfter(m.childNodes[j],m)}}if(g.fixPsuedoLeaks){l=m.cloneNode(true);f="IELeakGarbageBin";k=g.get(f)||g.add(g.doc.body,"div",{id:f,style:"display:none"});k.appendChild(m);k.innerHTML="";return l}return l.removeChild(m)})},setStyle:function(i,f,g){var h=this;return h.run(i,function(l){var k,j;k=l.style;f=f.replace(/-(\D)/g,function(n,m){return m.toUpperCase()});if(h.pixelStyles.test(f)&&(c.is(g,"number")||/^[\-0-9\.]+$/.test(g))){g+="px"}switch(f){case"opacity":if(a){k.filter=g===""?"":"alpha(opacity="+(g*100)+")";if(!i.currentStyle||!i.currentStyle.hasLayout){k.display="inline-block"}}k[f]=k["-moz-opacity"]=k["-khtml-opacity"]=g||"";break;case"float":a?k.styleFloat=g:k.cssFloat=g;break;default:k[f]=g||""}if(h.settings.update_styles){h.setAttrib(l,"mce_style")}})},getStyle:function(i,f,h){i=this.get(i);if(!i){return false}if(this.doc.defaultView&&h){f=f.replace(/[A-Z]/g,function(j){return"-"+j});try{return this.doc.defaultView.getComputedStyle(i,null).getPropertyValue(f)}catch(g){return null}}f=f.replace(/-(\D)/g,function(k,j){return j.toUpperCase()});if(f=="float"){f=a?"styleFloat":"cssFloat"}if(i.currentStyle&&h){return i.currentStyle[f]}return i.style[f]},setStyles:function(i,j){var g=this,h=g.settings,f;f=h.update_styles;h.update_styles=0;e(j,function(k,l){g.setStyle(i,l,k)});h.update_styles=f;if(h.update_styles){g.setAttrib(i,h.cssText)}},setAttrib:function(h,i,f){var g=this;if(!h||!i){return}if(g.settings.strict){i=i.toLowerCase()}return this.run(h,function(k){var j=g.settings;switch(i){case"style":if(!b(f,"string")){e(f,function(l,m){g.setStyle(k,m,l)});return}if(j.keep_values){if(f&&!g._isRes(f)){k.setAttribute("mce_style",f,2)}else{k.removeAttribute("mce_style",2)}}k.style.cssText=f;break;case"class":k.className=f||"";break;case"src":case"href":if(j.keep_values){if(j.url_converter){f=j.url_converter.call(j.url_converter_scope||g,f,i,k)}g.setAttrib(k,"mce_"+i,f,2)}break;case"shape":k.setAttribute("mce_style",f);break}if(b(f)&&f!==null&&f.length!==0){k.setAttribute(i,""+f,2)}else{k.removeAttribute(i,2)}})},setAttribs:function(g,h){var f=this;return this.run(g,function(i){e(h,function(j,k){f.setAttrib(i,k,j)})})},getAttrib:function(i,j,h){var f,g=this;i=g.get(i);if(!i||i.nodeType!==1){return false}if(!b(h)){h=""}if(/^(src|href|style|coords|shape)$/.test(j)){f=i.getAttribute("mce_"+j);if(f){return f}}if(a&&g.props[j]){f=i[g.props[j]];f=f&&f.nodeValue?f.nodeValue:f}if(!f){f=i.getAttribute(j,2)}if(j==="style"){f=f||i.style.cssText;if(f){f=g.serializeStyle(g.parseStyle(f));if(g.settings.keep_values&&!g._isRes(f)){i.setAttribute("mce_style",f)}}}if(d&&j==="class"&&f){f=f.replace(/(apple|webkit)\-[a-z\-]+/gi,"")}if(a){switch(j){case"rowspan":case"colspan":if(f===1){f=""}break;case"size":if(f==="+0"||f===20||f===0){f=""}break;case"width":case"height":case"vspace":case"checked":case"disabled":case"readonly":if(f===0){f=""}break;case"hspace":if(f===-1){f=""}break;case"maxlength":case"tabindex":if(f===32768||f===2147483647||f==="32768"){f=""}break;case"multiple":case"compact":case"noshade":case"nowrap":if(f===65535){return j}return h;case"shape":f=f.toLowerCase();break;default:if(j.indexOf("on")===0&&f){f=(""+f).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/,"$1")}}}return(f!==undefined&&f!==null&&f!=="")?""+f:h},getPos:function(m,i){var g=this,f=0,l=0,j,k=g.doc,h;m=g.get(m);i=i||k.body;if(m){if(a&&!g.stdMode){m=m.getBoundingClientRect();j=g.boxModel?k.documentElement:k.body;f=g.getStyle(g.select("html")[0],"borderWidth");f=(f=="medium"||g.boxModel&&!g.isIE6)&&2||f;m.top+=g.win.self!=g.win.top?2:0;return{x:m.left+j.scrollLeft-f,y:m.top+j.scrollTop-f}}h=m;while(h&&h!=i&&h.nodeType){f+=h.offsetLeft||0;l+=h.offsetTop||0;h=h.offsetParent}h=m.parentNode;while(h&&h!=i&&h.nodeType){f-=h.scrollLeft||0;l-=h.scrollTop||0;h=h.parentNode}}return{x:f,y:l}},parseStyle:function(h){var i=this,j=i.settings,k={};if(!h){return k}function f(w,q,v){var o,u,m,n;o=k[w+"-top"+q];if(!o){return}u=k[w+"-right"+q];if(o!=u){return}m=k[w+"-bottom"+q];if(u!=m){return}n=k[w+"-left"+q];if(m!=n){return}k[v]=n;delete k[w+"-top"+q];delete k[w+"-right"+q];delete k[w+"-bottom"+q];delete k[w+"-left"+q]}function g(n,m,l,p){var o;o=k[m];if(!o){return}o=k[l];if(!o){return}o=k[p];if(!o){return}k[n]=k[m]+" "+k[l]+" "+k[p];delete k[m];delete k[l];delete k[p]}h=h.replace(/&(#?[a-z0-9]+);/g,"&$1_MCE_SEMI_");e(h.split(";"),function(m){var l,n=[];if(m){m=m.replace(/_MCE_SEMI_/g,";");m=m.replace(/url\([^\)]+\)/g,function(o){n.push(o);return"url("+n.length+")"});m=m.split(":");l=c.trim(m[1]);l=l.replace(/url\(([^\)]+)\)/g,function(p,o){return n[parseInt(o)-1]});l=l.replace(/rgb\([^\)]+\)/g,function(o){return i.toHex(o)});if(j.url_converter){l=l.replace(/url\([\'\"]?([^\)\'\"]+)[\'\"]?\)/g,function(o,p){return"url("+j.url_converter.call(j.url_converter_scope||i,i.decode(p),"style",null)+")"})}k[c.trim(m[0]).toLowerCase()]=l}});f("border","","border");f("border","-width","border-width");f("border","-color","border-color");f("border","-style","border-style");f("padding","","padding");f("margin","","margin");g("border","border-width","border-style","border-color");if(a){if(k.border=="medium none"){k.border=""}}return k},serializeStyle:function(g){var f="";e(g,function(i,h){if(h&&i){if(c.isGecko&&h.indexOf("-moz-")===0){return}switch(h){case"color":case"background-color":i=i.toLowerCase();break}f+=(f?" ":"")+h+": "+i+";"}});return f},loadCSS:function(f){var h=this,i=h.doc,g;if(!f){f=""}g=h.select("head")[0];e(f.split(","),function(j){var k;if(h.files[j]){return}h.files[j]=true;k=h.create("link",{rel:"stylesheet",href:c._addVer(j)});if(a&&i.documentMode){k.onload=function(){i.recalc();k.onload=null}}g.appendChild(k)})},addClass:function(f,g){return this.run(f,function(h){var i;if(!g){return 0}if(this.hasClass(h,g)){return h.className}i=this.removeClass(h,g);return h.className=(i!=""?(i+" "):"")+g})},removeClass:function(h,i){var f=this,g;return f.run(h,function(k){var j;if(f.hasClass(k,i)){if(!g){g=new RegExp("(^|\\s+)"+i+"(\\s+|$)","g")}j=k.className.replace(g," ");return k.className=c.trim(j!=" "?j:"")}return k.className})},hasClass:function(g,f){g=this.get(g);if(!g||!f){return false}return(" "+g.className+" ").indexOf(" "+f+" ")!==-1},show:function(f){return this.setStyle(f,"display","block")},hide:function(f){return this.setStyle(f,"display","none")},isHidden:function(f){f=this.get(f);return !f||f.style.display=="none"||this.getStyle(f,"display")=="none"},uniqueId:function(f){return(!f?"mce_":f)+(this.counter++)},setHTML:function(i,g){var f=this;return this.run(i,function(m){var h,k,j,q,l,h;g=f.processHTML(g);if(a){function o(){try{m.innerHTML="
    "+g;m.removeChild(m.firstChild)}catch(n){while(m.firstChild){m.firstChild.removeNode()}h=f.create("div");h.innerHTML="
    "+g;e(h.childNodes,function(r,p){if(p){m.appendChild(r)}})}}if(f.settings.fix_ie_paragraphs){g=g.replace(/

    <\/p>|]+)><\/p>|/gi,' 

    ')}o();if(f.settings.fix_ie_paragraphs){j=m.getElementsByTagName("p");for(k=j.length-1,h=0;k>=0;k--){q=j[k];if(!q.hasChildNodes()){if(!q.mce_keep){h=1;break}q.removeAttribute("mce_keep")}}}if(h){g=g.replace(/

    ]+)>|

    /g,'

    ');g=g.replace(/<\/p>/g,"
    ");o();if(f.settings.fix_ie_paragraphs){j=m.getElementsByTagName("DIV");for(k=j.length-1;k>=0;k--){q=j[k];if(q.mce_tmp){l=f.doc.createElement("p");q.cloneNode(false).outerHTML.replace(/([a-z0-9\-_]+)=/gi,function(p,n){var r;if(n!=="mce_tmp"){r=q.getAttribute(n);if(!r&&n==="class"){r=q.className}l.setAttribute(n,r)}});for(h=0;h|]+)>/gi,"<$1b$2>");j=j.replace(/<(\/?)em>|]+)>/gi,"<$1i$2>")}else{if(a){j=j.replace(/'/g,"'");j=j.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/gi,"")}}j=j.replace(/]+)\/>|/gi,"");if(i.keep_values){if(/)/g,"\n");h=h.replace(/^[\r\n]*|[\r\n]*$/g,"");h=h.replace(/^\s*(\/\/\s*|\]\]>|-->|\]\]-->)\s*$/g,"");return h}j=j.replace(/]+|)>([\s\S]*?)<\/script>/g,function(h,l,k){if(!l){l=' type="text/javascript"'}l=l.replace(/(type|language)=\"?/,"$&mce-");l=l.replace(/src=\"([^\"]+)\"?/,function(m,n){if(i.url_converter){n=g.encode(i.url_converter.call(i.url_converter_scope||g,g.decode(n),"src","script"))}return'mce_src="'+n+'"'});if(c.trim(k)){k=""}return""+k+""});j=j.replace(/]+|)>([\s\S]*?)<\/style>/g,function(h,l,k){if(k){k=""}return""+k+""})}j=j.replace(//g,"");j=j.replace(/<([\w:]+) [^>]*(src|href|style|shape|coords)[^>]*>/gi,function(h,l){function k(o,n,q){var p=q;if(h.indexOf("mce_"+n)!=-1){return o}if(n=="style"){if(g._isRes(q)){return o}if(i.hex_colors){p=p.replace(/rgb\([^\)]+\)/g,function(m){return g.toHex(m)})}if(i.url_converter){p=p.replace(/url\([\'\"]?([^\)\'\"]+)\)/g,function(m,r){return"url("+g.encode(i.url_converter.call(i.url_converter_scope||g,g.decode(r),n,l))+")"})}}else{if(n!="coords"&&n!="shape"){if(i.url_converter){p=g.encode(i.url_converter.call(i.url_converter_scope||g,g.decode(q),n,l))}}}return" "+n+'="'+q+'" mce_'+n+'="'+p+'"'}h=h.replace(/ (src|href|style|coords|shape)=[\"]([^\"]+)[\"]/gi,k);h=h.replace(/ (src|href|style|coords|shape)=[\']([^\']+)[\']/gi,k);return h.replace(/ (src|href|style|coords|shape)=([^\s\"\'>]+)/gi,k)})}return j},getOuterHTML:function(f){var g;f=this.get(f);if(!f){return null}if(f.outerHTML!==undefined){return f.outerHTML}g=(f.ownerDocument||this.doc).createElement("body");g.appendChild(f.cloneNode(true));return g.innerHTML},setOuterHTML:function(i,g,j){var f=this;return this.run(i,function(h){var l,k;h=f.get(h);j=j||h.ownerDocument||f.doc;if(a&&h.nodeType==1){h.outerHTML=g}else{k=j.createElement("body");k.innerHTML=g;l=k.lastChild;while(l){f.insertAfter(l.cloneNode(true),h);l=l.previousSibling}f.remove(h)}})},decode:function(g){var h,i,f;if(/&[^;]+;/.test(g)){h=this.doc.createElement("div");h.innerHTML=g;i=h.firstChild;f="";if(i){do{f+=i.nodeValue}while(i.nextSibling)}return f||g}return g},encode:function(f){return f?(""+f).replace(/[<>&\"]/g,function(h,g){switch(h){case"&":return"&";case'"':return""";case"<":return"<";case">":return">"}return h}):f},insertAfter:function(h,g){var f=this;g=f.get(g);return this.run(h,function(k){var j,i;j=g.parentNode;i=g.nextSibling;if(i){j.insertBefore(k,i)}else{j.appendChild(k)}return k})},isBlock:function(f){if(f.nodeType&&f.nodeType!==1){return false}f=f.nodeName||f;return/^(H[1-6]|HR|P|DIV|ADDRESS|PRE|FORM|TABLE|LI|OL|UL|TR|TD|CAPTION|BLOCKQUOTE|CENTER|DL|DT|DD|DIR|FIELDSET|NOSCRIPT|NOFRAMES|MENU|ISINDEX|SAMP)$/.test(f)},replace:function(i,h,f){var g=this;if(b(h,"array")){i=i.cloneNode(true)}return g.run(h,function(j){if(f){e(j.childNodes,function(k){i.appendChild(k.cloneNode(true))})}if(g.fixPsuedoLeaks&&j.nodeType===1){j.parentNode.insertBefore(i,j);g.remove(j);return i}return j.parentNode.replaceChild(i,j)})},findCommonAncestor:function(h,f){var i=h,g;while(i){g=f;while(g&&i!=g){g=g.parentNode}if(i==g){break}i=i.parentNode}if(!i&&h.ownerDocument){return h.ownerDocument.documentElement}return i},toHex:function(f){var h=/^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(f);function g(i){i=parseInt(i).toString(16);return i.length>1?i:"0"+i}if(h){f="#"+g(h[1])+g(h[2])+g(h[3]);return f}return f},getClasses:function(){var l=this,g=[],k,m={},n=l.settings.class_filter,j;if(l.classes){return l.classes}function o(f){e(f.imports,function(i){o(i)});e(f.cssRules||f.rules,function(i){switch(i.type||1){case 1:if(i.selectorText){e(i.selectorText.split(","),function(p){p=p.replace(/^\s*|\s*$|^\s\./g,"");if(/\.mce/.test(p)||!/\.[\w\-]+$/.test(p)){return}j=p;p=p.replace(/.*\.([a-z0-9_\-]+).*/i,"$1");if(n&&!(p=n(p,j))){return}if(!m[p]){g.push({"class":p});m[p]=1}})}break;case 3:o(i.styleSheet);break}})}try{e(l.doc.styleSheets,o)}catch(h){}if(g.length>0){l.classes=g}return g},run:function(j,i,h){var g=this,k;if(g.doc&&typeof(j)==="string"){j=g.get(j)}if(!j){return false}h=h||this;if(!j.nodeType&&(j.length||j.length===0)){k=[];e(j,function(l,f){if(l){if(typeof(l)=="string"){l=g.doc.getElementById(l)}k.push(i.call(h,l,f))}});return k}return i.call(h,j)},getAttribs:function(g){var f;g=this.get(g);if(!g){return[]}if(a){f=[];if(g.nodeName=="OBJECT"){return g.attributes}g.cloneNode(false).outerHTML.replace(/([a-z0-9\:\-_]+)=/gi,function(i,h){f.push({specified:1,nodeName:h})});return f}return g.attributes},destroy:function(g){var f=this;if(f.events){f.events.destroy()}f.win=f.doc=f.root=f.events=null;if(!g){c.removeUnload(f.destroy)}},createRng:function(){var f=this.doc;return f.createRange?f.createRange():new c.dom.Range(this)},split:function(l,k,o){var p=this,f=p.createRng(),m,j,n;function g(r,q){r=r[q];if(r&&r[q]&&r[q].nodeType==1&&i(r[q])){p.remove(r[q])}}function i(q){q=p.getOuterHTML(q);q=q.replace(/<(img|hr|table)/gi,"-");q=q.replace(/<[^>]+>/g,"");return q.replace(/[ \t\r\n]+| | /g,"")==""}function h(r){var q=0;while(r.previousSibling){q++;r=r.previousSibling}return q}if(l&&k){f.setStart(l.parentNode,h(l));f.setEnd(k.parentNode,h(k));m=f.extractContents();f=p.createRng();f.setStart(k.parentNode,h(k)+1);f.setEnd(l.parentNode,h(l)+1);j=f.extractContents();n=l.parentNode;g(m,"lastChild");if(!i(m)){n.insertBefore(m,l)}if(o){n.replaceChild(o,k)}else{n.insertBefore(k,l)}g(j,"firstChild");if(!i(j)){n.insertBefore(j,l)}p.remove(l);return o||k}},bind:function(j,f,i,h){var g=this;if(!g.events){g.events=new c.dom.EventUtils()}return g.events.add(j,f,i,h||this)},unbind:function(i,f,h){var g=this;if(!g.events){g.events=new c.dom.EventUtils()}return g.events.remove(i,f,h)},_isRes:function(f){return/^(top|left|bottom|right|width|height)/i.test(f)||/;\s*(top|left|bottom|right|width|height)/i.test(f)}});c.DOM=new c.dom.DOMUtils(document,{process_html:0})})(tinymce);(function(f){var h=0,c=1,e=2,d=tinymce.extend;function g(m,k){var j,l;if(m.parentNode!=k){return -1}for(l=k.firstChild,j=0;l!=m;l=l.nextSibling){j++}return j}function b(k){var j=0;while(k.previousSibling){j++;k=k.previousSibling}return j}function i(j,k){var l;if(j.nodeType==3){return j}if(k<0){return j}l=j.firstChild;while(l!=null&&k>0){--k;l=l.nextSibling}if(l!=null){return l}return j}function a(k){var j=k.doc;d(this,{dom:k,startContainer:j,startOffset:0,endContainer:j,endOffset:0,collapsed:true,commonAncestorContainer:j,START_TO_START:0,START_TO_END:1,END_TO_END:2,END_TO_START:3})}d(a.prototype,{setStart:function(k,j){this._setEndPoint(true,k,j)},setEnd:function(k,j){this._setEndPoint(false,k,j)},setStartBefore:function(j){this.setStart(j.parentNode,b(j))},setStartAfter:function(j){this.setStart(j.parentNode,b(j)+1)},setEndBefore:function(j){this.setEnd(j.parentNode,b(j))},setEndAfter:function(j){this.setEnd(j.parentNode,b(j)+1)},collapse:function(k){var j=this;if(k){j.endContainer=j.startContainer;j.endOffset=j.startOffset}else{j.startContainer=j.endContainer;j.startOffset=j.endOffset}j.collapsed=true},selectNode:function(j){this.setStartBefore(j);this.setEndAfter(j)},selectNodeContents:function(j){this.setStart(j,0);this.setEnd(j,j.nodeType===1?j.childNodes.length:j.nodeValue.length)},compareBoundaryPoints:function(m,n){var l=this,p=l.startContainer,o=l.startOffset,k=l.endContainer,j=l.endOffset;if(m===0){return l._compareBoundaryPoints(p,o,p,o)}if(m===1){return l._compareBoundaryPoints(p,o,k,j)}if(m===2){return l._compareBoundaryPoints(k,j,k,j)}if(m===3){return l._compareBoundaryPoints(k,j,p,o)}},deleteContents:function(){this._traverse(e)},extractContents:function(){return this._traverse(h)},cloneContents:function(){return this._traverse(c)},insertNode:function(m){var j=this,l,k;if(m.nodeType===3||m.nodeType===4){l=j.startContainer.splitText(j.startOffset);j.startContainer.parentNode.insertBefore(m,l)}else{if(j.startContainer.childNodes.length>0){k=j.startContainer.childNodes[j.startOffset]}j.startContainer.insertBefore(m,k)}},surroundContents:function(l){var j=this,k=j.extractContents();j.insertNode(l);l.appendChild(k);j.selectNode(l)},cloneRange:function(){var j=this;return d(new a(j.dom),{startContainer:j.startContainer,startOffset:j.startOffset,endContainer:j.endContainer,endOffset:j.endOffset,collapsed:j.collapsed,commonAncestorContainer:j.commonAncestorContainer})},_isCollapsed:function(){return(this.startContainer==this.endContainer&&this.startOffset==this.endOffset)},_compareBoundaryPoints:function(m,p,k,o){var q,l,j,r,t,s;if(m==k){if(p==o){return 0}else{if(p0){l.collapse(k)}}l.collapsed=l._isCollapsed();l.commonAncestorContainer=l.dom.findCommonAncestor(l.startContainer,l.endContainer)},_traverse:function(r){var s=this,q,m=0,v=0,k,o,l,n,j,u;if(s.startContainer==s.endContainer){return s._traverseSameContainer(r)}for(q=s.endContainer,k=q.parentNode;k!=null;q=k,k=k.parentNode){if(k==s.startContainer){return s._traverseCommonStartContainer(q,r)}++m}for(q=s.startContainer,k=q.parentNode;k!=null;q=k,k=k.parentNode){if(k==s.endContainer){return s._traverseCommonEndContainer(q,r)}++v}o=v-m;l=s.startContainer;while(o>0){l=l.parentNode;o--}n=s.endContainer;while(o<0){n=n.parentNode;o++}for(j=l.parentNode,u=n.parentNode;j!=u;j=j.parentNode,u=u.parentNode){l=j;n=u}return s._traverseCommonAncestors(l,n,r)},_traverseSameContainer:function(o){var r=this,q,u,j,k,l,p,m;if(o!=e){q=r.dom.doc.createDocumentFragment()}if(r.startOffset==r.endOffset){return q}if(r.startContainer.nodeType==3){u=r.startContainer.nodeValue;j=u.substring(r.startOffset,r.endOffset);if(o!=c){r.startContainer.deleteData(r.startOffset,r.endOffset-r.startOffset);r.collapse(true)}if(o==e){return null}q.appendChild(r.dom.doc.createTextNode(j));return q}k=i(r.startContainer,r.startOffset);l=r.endOffset-r.startOffset;while(l>0){p=k.nextSibling;m=r._traverseFullySelected(k,o);if(q){q.appendChild(m)}--l;k=p}if(o!=c){r.collapse(true)}return q},_traverseCommonStartContainer:function(j,p){var s=this,r,k,l,m,q,o;if(p!=e){r=s.dom.doc.createDocumentFragment()}k=s._traverseRightBoundary(j,p);if(r){r.appendChild(k)}l=g(j,s.startContainer);m=l-s.startOffset;if(m<=0){if(p!=c){s.setEndBefore(j);s.collapse(false)}return r}k=j.previousSibling;while(m>0){q=k.previousSibling;o=s._traverseFullySelected(k,p);if(r){r.insertBefore(o,r.firstChild)}--m;k=q}if(p!=c){s.setEndBefore(j);s.collapse(false)}return r},_traverseCommonEndContainer:function(m,p){var s=this,r,o,j,k,q,l;if(p!=e){r=s.dom.doc.createDocumentFragment()}j=s._traverseLeftBoundary(m,p);if(r){r.appendChild(j)}o=g(m,s.endContainer);++o;k=s.endOffset-o;j=m.nextSibling;while(k>0){q=j.nextSibling;l=s._traverseFullySelected(j,p);if(r){r.appendChild(l)}--k;j=q}if(p!=c){s.setStartAfter(m);s.collapse(true)}return r},_traverseCommonAncestors:function(p,j,s){var w=this,l,v,o,q,r,k,u,m;if(s!=e){v=w.dom.doc.createDocumentFragment()}l=w._traverseLeftBoundary(p,s);if(v){v.appendChild(l)}o=p.parentNode;q=g(p,o);r=g(j,o);++q;k=r-q;u=p.nextSibling;while(k>0){m=u.nextSibling;l=w._traverseFullySelected(u,s);if(v){v.appendChild(l)}u=m;--k}l=w._traverseRightBoundary(j,s);if(v){v.appendChild(l)}if(s!=c){w.setStartAfter(p);w.collapse(true)}return v},_traverseRightBoundary:function(p,q){var s=this,l=i(s.endContainer,s.endOffset-1),r,o,n,j,k;var m=l!=s.endContainer;if(l==p){return s._traverseNode(l,m,false,q)}r=l.parentNode;o=s._traverseNode(r,false,false,q);while(r!=null){while(l!=null){n=l.previousSibling;j=s._traverseNode(l,m,false,q);if(q!=e){o.insertBefore(j,o.firstChild)}m=true;l=n}if(r==p){return o}l=r.previousSibling;r=r.parentNode;k=s._traverseNode(r,false,false,q);if(q!=e){k.appendChild(o)}o=k}return null},_traverseLeftBoundary:function(p,q){var s=this,m=i(s.startContainer,s.startOffset);var n=m!=s.startContainer,r,o,l,j,k;if(m==p){return s._traverseNode(m,n,true,q)}r=m.parentNode;o=s._traverseNode(r,false,true,q);while(r!=null){while(m!=null){l=m.nextSibling;j=s._traverseNode(m,n,true,q);if(q!=e){o.appendChild(j)}n=true;m=l}if(r==p){return o}m=r.nextSibling;r=r.parentNode;k=s._traverseNode(r,false,true,q);if(q!=e){k.appendChild(o)}o=k}return null},_traverseNode:function(j,o,r,s){var u=this,m,l,p,k,q;if(o){return u._traverseFullySelected(j,s)}if(j.nodeType==3){m=j.nodeValue;if(r){k=u.startOffset;l=m.substring(k);p=m.substring(0,k)}else{k=u.endOffset;l=m.substring(0,k);p=m.substring(k)}if(s!=c){j.nodeValue=p}if(s==e){return null}q=j.cloneNode(false);q.nodeValue=l;return q}if(s==e){return null}return j.cloneNode(false)},_traverseFullySelected:function(l,k){var j=this;if(k!=e){return k==c?l.cloneNode(true):l}l.parentNode.removeChild(l);return null}});f.Range=a})(tinymce.dom);(function(){function a(e){var d=this,h="\uFEFF",b,g;function c(j,i){if(j&&i){if(j.item&&i.item&&j.item(0)===i.item(0)){return 1}if(j.isEqual&&i.isEqual&&i.isEqual(j)){return 1}}return 0}function f(){var m=e.dom,j=e.getRng(),s=m.createRng(),p,k,n,q,o,l;function i(v){var t=v.parentNode.childNodes,u;for(u=t.length-1;u>=0;u--){if(t[u]==v){return u}}return -1}function r(v){var t=j.duplicate(),B,y,u,w,x=0,z=0,A,C;t.collapse(v);B=t.parentElement();t.pasteHTML(h);u=B.childNodes;for(y=0;y0&&(w.nodeType!==3||u[y-1].nodeType!==3)){z++}if(w.nodeType===3){A=w.nodeValue.indexOf(h);if(A!==-1){x+=A;break}x+=w.nodeValue.length}else{x=0}}t.moveStart("character",-1);t.text="";return{index:z,offset:x,parent:B}}n=j.item?j.item(0):j.parentElement();if(n.ownerDocument!=m.doc){return s}if(j.item||!n.hasChildNodes()){s.setStart(n.parentNode,i(n));s.setEnd(s.startContainer,s.startOffset+1);return s}l=e.isCollapsed();p=r(true);k=r(false);p.parent.normalize();k.parent.normalize();q=p.parent.childNodes[Math.min(p.index,p.parent.childNodes.length-1)];if(q.nodeType!=3){s.setStart(p.parent,p.index)}else{s.setStart(p.parent.childNodes[p.index],p.offset)}o=k.parent.childNodes[Math.min(k.index,k.parent.childNodes.length-1)];if(o.nodeType!=3){if(!l){k.index++}s.setEnd(k.parent,k.index)}else{s.setEnd(k.parent.childNodes[k.index],k.offset)}if(!l){q=s.startContainer;if(q.nodeType==1){s.setStart(q,Math.min(s.startOffset,q.childNodes.length))}o=s.endContainer;if(o.nodeType==1){s.setEnd(o,Math.min(s.endOffset,o.childNodes.length))}}d.addRange(s);return s}this.addRange=function(j){var o,m=e.dom.doc.body,p,k,q,l,n,i;q=j.startContainer;l=j.startOffset;n=j.endContainer;i=j.endOffset;o=m.createTextRange();q=q.nodeType==1?q.childNodes[Math.min(l,q.childNodes.length-1)]:q;n=n.nodeType==1?n.childNodes[Math.min(l==i?i:i-1,n.childNodes.length-1)]:n;if(q==n&&q.nodeType==1){if(/^(IMG|TABLE)$/.test(q.nodeName)&&l!=i){o=m.createControlRange();o.addElement(q)}else{o=m.createTextRange();if(!q.hasChildNodes()&&q.canHaveHTML){q.innerHTML=h}o.moveToElementText(q);if(q.innerHTML==h){o.collapse(true);q.removeChild(q.firstChild)}}if(l==i){o.collapse(i<=j.endContainer.childNodes.length-1)}o.select();return}function r(t,v){var u,s,w;if(t.nodeType!=3){return -1}u=t.nodeValue;s=m.createTextRange();t.nodeValue=u.substring(0,v)+h+u.substring(v);s.moveToElementText(t.parentNode);s.findText(h);w=Math.abs(s.moveStart("character",-1048575));t.nodeValue=u;return w}if(j.collapsed){pos=r(q,l);o=m.createTextRange();o.move("character",pos);o.select();return}else{if(q==n&&q.nodeType==3){p=r(q,l);o.move("character",p);o.moveEnd("character",i-l);o.select();return}p=r(q,l);k=r(n,i);o=m.createTextRange();if(p==-1){o.moveToElementText(q);p=0}else{o.move("character",p)}tmpRng=m.createTextRange();if(k==-1){tmpRng.moveToElementText(n)}else{tmpRng.move("character",k)}o.setEndPoint("EndToEnd",tmpRng);o.select();return}};this.getRangeAt=function(){if(!b||!c(g,e.getRng())){b=f();g=e.getRng()}return b};this.destroy=function(){g=b=null}}tinymce.dom.TridentSelection=a})();(function(){var p=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,i=0,d=Object.prototype.toString,n=false;var b=function(D,t,A,v){A=A||[];var e=t=t||document;if(t.nodeType!==1&&t.nodeType!==9){return[]}if(!D||typeof D!=="string"){return A}var B=[],C,y,G,F,z,s,r=true,w=o(t);p.lastIndex=0;while((C=p.exec(D))!==null){B.push(C[1]);if(C[2]){s=RegExp.rightContext;break}}if(B.length>1&&j.exec(D)){if(B.length===2&&f.relative[B[0]]){y=g(B[0]+B[1],t)}else{y=f.relative[B[0]]?[t]:b(B.shift(),t);while(B.length){D=B.shift();if(f.relative[D]){D+=B.shift()}y=g(D,y)}}}else{if(!v&&B.length>1&&t.nodeType===9&&!w&&f.match.ID.test(B[0])&&!f.match.ID.test(B[B.length-1])){var H=b.find(B.shift(),t,w);t=H.expr?b.filter(H.expr,H.set)[0]:H.set[0]}if(t){var H=v?{expr:B.pop(),set:a(v)}:b.find(B.pop(),B.length===1&&(B[0]==="~"||B[0]==="+")&&t.parentNode?t.parentNode:t,w);y=H.expr?b.filter(H.expr,H.set):H.set;if(B.length>0){G=a(y)}else{r=false}while(B.length){var u=B.pop(),x=u;if(!f.relative[u]){u=""}else{x=B.pop()}if(x==null){x=t}f.relative[u](G,x,w)}}else{G=B=[]}}if(!G){G=y}if(!G){throw"Syntax error, unrecognized expression: "+(u||D)}if(d.call(G)==="[object Array]"){if(!r){A.push.apply(A,G)}else{if(t&&t.nodeType===1){for(var E=0;G[E]!=null;E++){if(G[E]&&(G[E]===true||G[E].nodeType===1&&h(t,G[E]))){A.push(y[E])}}}else{for(var E=0;G[E]!=null;E++){if(G[E]&&G[E].nodeType===1){A.push(y[E])}}}}}else{a(G,A)}if(s){b(s,e,A,v);b.uniqueSort(A)}return A};b.uniqueSort=function(r){if(c){n=false;r.sort(c);if(n){for(var e=1;e":function(w,r,x){var u=typeof r==="string";if(u&&!/\W/.test(r)){r=x?r:r.toUpperCase();for(var s=0,e=w.length;s=0)){if(!s){e.push(v)}}else{if(s){r[u]=false}}}}return false},ID:function(e){return e[1].replace(/\\/g,"")},TAG:function(r,e){for(var s=0;e[s]===false;s++){}return e[s]&&o(e[s])?r[1]:r[1].toUpperCase()},CHILD:function(e){if(e[1]=="nth"){var r=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(e[2]=="even"&&"2n"||e[2]=="odd"&&"2n+1"||!/\D/.test(e[2])&&"0n+"+e[2]||e[2]);e[2]=(r[1]+(r[2]||1))-0;e[3]=r[3]-0}e[0]=i++;return e},ATTR:function(u,r,s,e,v,w){var t=u[1].replace(/\\/g,"");if(!w&&f.attrMap[t]){u[1]=f.attrMap[t]}if(u[2]==="~="){u[4]=" "+u[4]+" "}return u},PSEUDO:function(u,r,s,e,v){if(u[1]==="not"){if(u[3].match(p).length>1||/^\w/.test(u[3])){u[3]=b(u[3],null,null,r)}else{var t=b.filter(u[3],r,s,true^v);if(!s){e.push.apply(e,t)}return false}}else{if(f.match.POS.test(u[0])||f.match.CHILD.test(u[0])){return true}}return u},POS:function(e){e.unshift(true);return e}},filters:{enabled:function(e){return e.disabled===false&&e.type!=="hidden"},disabled:function(e){return e.disabled===true},checked:function(e){return e.checked===true},selected:function(e){e.parentNode.selectedIndex;return e.selected===true},parent:function(e){return !!e.firstChild},empty:function(e){return !e.firstChild},has:function(s,r,e){return !!b(e[3],s).length},header:function(e){return/h\d/i.test(e.nodeName)},text:function(e){return"text"===e.type},radio:function(e){return"radio"===e.type},checkbox:function(e){return"checkbox"===e.type},file:function(e){return"file"===e.type},password:function(e){return"password"===e.type},submit:function(e){return"submit"===e.type},image:function(e){return"image"===e.type},reset:function(e){return"reset"===e.type},button:function(e){return"button"===e.type||e.nodeName.toUpperCase()==="BUTTON"},input:function(e){return/input|select|textarea|button/i.test(e.nodeName)}},setFilters:{first:function(r,e){return e===0},last:function(s,r,e,t){return r===t.length-1},even:function(r,e){return e%2===0},odd:function(r,e){return e%2===1},lt:function(s,r,e){return re[3]-0},nth:function(s,r,e){return e[3]-0==r},eq:function(s,r,e){return e[3]-0==r}},filter:{PSEUDO:function(w,s,t,x){var r=s[1],u=f.filters[r];if(u){return u(w,t,s,x)}else{if(r==="contains"){return(w.textContent||w.innerText||"").indexOf(s[3])>=0}else{if(r==="not"){var v=s[3];for(var t=0,e=v.length;t=0)}}},ID:function(r,e){return r.nodeType===1&&r.getAttribute("id")===e},TAG:function(r,e){return(e==="*"&&r.nodeType===1)||r.nodeName===e},CLASS:function(r,e){return(" "+(r.className||r.getAttribute("class"))+" ").indexOf(e)>-1},ATTR:function(v,t){var s=t[1],e=f.attrHandle[s]?f.attrHandle[s](v):v[s]!=null?v[s]:v.getAttribute(s),w=e+"",u=t[2],r=t[4];return e==null?u==="!=":u==="="?w===r:u==="*="?w.indexOf(r)>=0:u==="~="?(" "+w+" ").indexOf(r)>=0:!r?w&&e!==false:u==="!="?w!=r:u==="^="?w.indexOf(r)===0:u==="$="?w.substr(w.length-r.length)===r:u==="|="?w===r||w.substr(0,r.length+1)===r+"-":false},POS:function(u,r,s,v){var e=r[2],t=f.setFilters[e];if(t){return t(u,s,r,v)}}}};var j=f.match.POS;for(var l in f.match){f.match[l]=new RegExp(f.match[l].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var a=function(r,e){r=Array.prototype.slice.call(r);if(e){e.push.apply(e,r);return e}return r};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(k){a=function(u,t){var r=t||[];if(d.call(u)==="[object Array]"){Array.prototype.push.apply(r,u)}else{if(typeof u.length==="number"){for(var s=0,e=u.length;s";var e=document.documentElement;e.insertBefore(r,e.firstChild);if(!!document.getElementById(s)){f.find.ID=function(u,v,w){if(typeof v.getElementById!=="undefined"&&!w){var t=v.getElementById(u[1]);return t?t.id===u[1]||typeof t.getAttributeNode!=="undefined"&&t.getAttributeNode("id").nodeValue===u[1]?[t]:undefined:[]}};f.filter.ID=function(v,t){var u=typeof v.getAttributeNode!=="undefined"&&v.getAttributeNode("id");return v.nodeType===1&&u&&u.nodeValue===t}}e.removeChild(r)})();(function(){var e=document.createElement("div");e.appendChild(document.createComment(""));if(e.getElementsByTagName("*").length>0){f.find.TAG=function(r,v){var u=v.getElementsByTagName(r[1]);if(r[1]==="*"){var t=[];for(var s=0;u[s];s++){if(u[s].nodeType===1){t.push(u[s])}}u=t}return u}}e.innerHTML="";if(e.firstChild&&typeof e.firstChild.getAttribute!=="undefined"&&e.firstChild.getAttribute("href")!=="#"){f.attrHandle.href=function(r){return r.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var e=b,s=document.createElement("div");s.innerHTML="

    ";if(s.querySelectorAll&&s.querySelectorAll(".TEST").length===0){return}b=function(w,v,t,u){v=v||document;if(!u&&v.nodeType===9&&!o(v)){try{return a(v.querySelectorAll(w),t)}catch(x){}}return e(w,v,t,u)};for(var r in e){b[r]=e[r]}})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var e=document.createElement("div");e.innerHTML="
    ";if(e.getElementsByClassName("e").length===0){return}e.lastChild.className="e";if(e.getElementsByClassName("e").length===1){return}f.order.splice(1,0,"CLASS");f.find.CLASS=function(r,s,t){if(typeof s.getElementsByClassName!=="undefined"&&!t){return s.getElementsByClassName(r[1])}}})()}function m(r,w,v,A,x,z){var y=r=="previousSibling"&&!z;for(var t=0,s=A.length;t0){u=e;break}}}e=e[r]}A[t]=u}}}var h=document.compareDocumentPosition?function(r,e){return r.compareDocumentPosition(e)&16}:function(r,e){return r!==e&&(r.contains?r.contains(e):true)};var o=function(e){return e.nodeType===9&&e.documentElement.nodeName!=="HTML"||!!e.ownerDocument&&e.ownerDocument.documentElement.nodeName!=="HTML"};var g=function(e,x){var t=[],u="",v,s=x.nodeType?[x]:x;while((v=f.match.PSEUDO.exec(e))){u+=v[0];e=e.replace(f.match.PSEUDO,"")}e=f.relative[e]?e+"*":e;for(var w=0,r=s.length;w=0;h--){k=g[h];if(k.obj===l){j._remove(k.obj,k.name,k.cfunc);k.obj=k.cfunc=null;g.splice(h,1)}}}},cancel:function(g){if(!g){return false}this.stop(g);return this.prevent(g)},stop:function(g){if(g.stopPropagation){g.stopPropagation()}else{g.cancelBubble=true}return false},prevent:function(g){if(g.preventDefault){g.preventDefault()}else{g.returnValue=false}return false},destroy:function(){var g=this;f(g.events,function(j,h){g._remove(j.obj,j.name,j.cfunc);j.obj=j.cfunc=null});g.events=[];g=null},_add:function(h,i,g){if(h.attachEvent){h.attachEvent("on"+i,g)}else{if(h.addEventListener){h.addEventListener(i,g,false)}else{h["on"+i]=g}}},_remove:function(i,j,h){if(i){try{if(i.detachEvent){i.detachEvent("on"+j,h)}else{if(i.removeEventListener){i.removeEventListener(j,h,false)}else{i["on"+j]=null}}}catch(g){}}},_pageInit:function(h){var g=this;if(g.domLoaded){return}g.domLoaded=true;f(g.inits,function(i){i()});g.inits=[]},_wait:function(i){var g=this,h=i.document;if(i.tinyMCE_GZ&&tinyMCE_GZ.loaded){g.domLoaded=1;return}if(h.attachEvent){h.attachEvent("onreadystatechange",function(){if(h.readyState==="complete"){h.detachEvent("onreadystatechange",arguments.callee);g._pageInit(i)}});if(h.documentElement.doScroll&&i==i.top){(function(){if(g.domLoaded){return}try{h.documentElement.doScroll("left")}catch(j){setTimeout(arguments.callee,0);return}g._pageInit(i)})()}}else{if(h.addEventListener){g._add(i,"DOMContentLoaded",function(){g._pageInit(i)})}}g._add(i,"load",function(){g._pageInit(i)})}});a=d.dom.Event=new d.dom.EventUtils();a._wait(window);d.addUnload(function(){a.destroy()})})(tinymce);(function(a){var b=a.each;a.create("tinymce.dom.Element",{Element:function(g,e){var c=this,f,d;e=e||{};c.id=g;c.dom=f=e.dom||a.DOM;c.settings=e;if(!a.isIE){d=c.dom.get(c.id)}b(["getPos","getRect","getParent","add","setStyle","getStyle","setStyles","setAttrib","setAttribs","getAttrib","addClass","removeClass","hasClass","getOuterHTML","setOuterHTML","remove","show","hide","isHidden","setHTML","get"],function(h){c[h]=function(){var j=[g],k;for(k=0;k_';j.deleteContents();j.insertNode(f.getRng().createContextualFragment(i));l=f.dom.get("__caret");j=k.createRange();j.setStartBefore(l);j.setEndAfter(l);f.setRng(j);f.dom.remove("__caret")}else{if(j.item){k.execCommand("Delete",false,null);j=f.getRng()}j.pasteHTML(i)}f.onSetContent.dispatch(f,g)},getStart:function(){var f=this,g=f.getRng(),h;if(a){if(g.item){return g.item(0)}g=g.duplicate();g.collapse(1);h=g.parentElement();if(h&&h.nodeName=="BODY"){return h.firstChild}return h}else{h=g.startContainer;if(h.nodeName=="BODY"){return h.firstChild}return f.dom.getParent(h,"*")}},getEnd:function(){var f=this,g=f.getRng(),h;if(a){if(g.item){return g.item(0)}g=g.duplicate();g.collapse(0);h=g.parentElement();if(h&&h.nodeName=="BODY"){return h.lastChild}return h}else{h=g.endContainer;if(h.nodeName=="BODY"){return h.lastChild}return f.dom.getParent(h,"*")}},getBookmark:function(x){var j=this,m=j.getRng(),f,n,l,u=j.dom.getViewPort(j.win),v,p,z,o,w=-16777215,k,h=j.dom.getRoot(),g=0,i=0,y;n=u.x;l=u.y;if(x=="simple"){return{rng:m,scrollX:n,scrollY:l}}if(a){if(m.item){v=m.item(0);d(j.dom.select(v.nodeName),function(s,r){if(v==s){p=r;return false}});return{tag:v.nodeName,index:p,scrollX:n,scrollY:l}}f=j.dom.doc.body.createTextRange();f.moveToElementText(h);f.collapse(true);z=Math.abs(f.move("character",w));f=m.duplicate();f.collapse(true);p=Math.abs(f.move("character",w));f=m.duplicate();f.collapse(false);o=Math.abs(f.move("character",w))-p;return{start:p-z,length:o,scrollX:n,scrollY:l}}v=j.getNode();k=j.getSel();if(!k){return null}if(v&&v.nodeName=="IMG"){return{scrollX:n,scrollY:l}}function q(A,D,t){var s=j.dom.doc.createTreeWalker(A,NodeFilter.SHOW_TEXT,null,false),E,B=0,C={};while((E=s.nextNode())!=null){if(E==D){C.start=B}if(E==t){C.end=B;return C}B+=e(E.nodeValue||"").length}return null}if(k.anchorNode==k.focusNode&&k.anchorOffset==k.focusOffset){v=q(h,k.anchorNode,k.focusNode);if(!v){return{scrollX:n,scrollY:l}}e(k.anchorNode.nodeValue||"").replace(/^\s+/,function(r){g=r.length});return{start:Math.max(v.start+k.anchorOffset-g,0),end:Math.max(v.end+k.focusOffset-g,0),scrollX:n,scrollY:l,beg:k.anchorOffset-g==0}}else{v=q(h,m.startContainer,m.endContainer);if(!v){return{scrollX:n,scrollY:l}}return{start:Math.max(v.start+m.startOffset-g,0),end:Math.max(v.end+m.endOffset-i,0),scrollX:n,scrollY:l,beg:m.startOffset-g==0}}},moveToBookmark:function(n){var o=this,g=o.getRng(),p=o.getSel(),j=o.dom.getRoot(),m,h,k;function i(q,t,D){var B=o.dom.doc.createTreeWalker(q,NodeFilter.SHOW_TEXT,null,false),x,s=0,A={},u,C,z,y;while((x=B.nextNode())!=null){z=y=0;k=x.nodeValue||"";h=e(k).length;s+=h;if(s>=t&&!A.startNode){u=t-(s-h);if(n.beg&&u>=h){continue}A.startNode=x;A.startOffset=u+y}if(s>=D){A.endNode=x;A.endOffset=D-(s-h)+y;return A}}return null}if(!n){return false}o.win.scrollTo(n.scrollX,n.scrollY);if(a){if(g=n.rng){try{g.select()}catch(l){}return true}o.win.focus();if(n.tag){g=j.createControlRange();d(o.dom.select(n.tag),function(r,q){if(q==n.index){g.addElement(r)}})}else{try{if(n.start<0){return true}g=p.createRange();g.moveToElementText(j);g.collapse(true);g.moveStart("character",n.start);g.moveEnd("character",n.length)}catch(f){return true}}try{g.select()}catch(l){}return true}if(!p){return false}if(n.rng){p.removeAllRanges();p.addRange(n.rng)}else{if(b(n.start)&&b(n.end)){try{m=i(j,n.start,n.end);if(m){g=o.dom.doc.createRange();g.setStart(m.startNode,m.startOffset);g.setEnd(m.endNode,m.endOffset);p.removeAllRanges();p.addRange(g)}if(!c.isOpera){o.win.focus()}}catch(l){}}}},select:function(g,l){var p=this,f=p.getRng(),q=p.getSel(),o,m,k,j=p.win.document;function h(u,t){var s,r;if(u){s=j.createTreeWalker(u,NodeFilter.SHOW_TEXT,null,false);while(u=s.nextNode()){r=u;if(c.trim(u.nodeValue).length!=0){if(t){return u}else{r=u}}}}return r}if(a){try{o=j.body;if(/^(IMG|TABLE)$/.test(g.nodeName)){f=o.createControlRange();f.addElement(g)}else{f=o.createTextRange();f.moveToElementText(g)}f.select()}catch(i){}}else{if(l){m=h(g,1)||p.dom.select("br:first",g)[0];k=h(g,0)||p.dom.select("br:last",g)[0];if(m&&k){f=j.createRange();if(m.nodeName=="BR"){f.setStartBefore(m)}else{f.setStart(m,0)}if(k.nodeName=="BR"){f.setEndBefore(k)}else{f.setEnd(k,k.nodeValue.length)}}else{f.selectNode(g)}}else{f.selectNode(g)}p.setRng(f)}return g},isCollapsed:function(){var f=this,h=f.getRng(),g=f.getSel();if(!h||h.item){return false}return !g||h.boundingWidth==0||h.collapsed},collapse:function(f){var g=this,h=g.getRng(),i;if(h.item){i=h.item(0);h=this.win.document.body.createTextRange();h.moveToElementText(i)}h.collapse(!!f);g.setRng(h)},getSel:function(){var g=this,f=this.win;return f.getSelection?f.getSelection():f.document.selection},getRng:function(j){var g=this,h,i;if(j&&g.tridentSel){return g.tridentSel.getRangeAt(0)}try{if(h=g.getSel()){i=h.rangeCount>0?h.getRangeAt(0):(h.createRange?h.createRange():g.win.document.createRange())}}catch(f){}if(!i){i=a?g.win.document.body.createTextRange():g.win.document.createRange()}return i},setRng:function(i){var h,g=this;if(!g.tridentSel){h=g.getSel();if(h){h.removeAllRanges();h.addRange(i)}}else{if(i.cloneRange){g.tridentSel.addRange(i);return}try{i.select()}catch(f){}}},setNode:function(g){var f=this;f.setContent(f.dom.getOuterHTML(g));return g},getNode:function(){var f=this,h=f.getRng(),g=f.getSel(),i;if(!a){if(!h){return f.dom.getRoot()}i=h.commonAncestorContainer;if(!h.collapsed){if(c.isWebKit&&g.anchorNode&&g.anchorNode.nodeType==1){return g.anchorNode.childNodes[g.anchorOffset]}if(h.startContainer==h.endContainer){if(h.startOffset-h.endOffset<2){if(h.startContainer.hasChildNodes()){i=h.startContainer.childNodes[h.startOffset]}}}}return f.dom.getParent(i,"*")}return h.item?h.item(0):h.parentElement()},getSelectedBlocks:function(g,f){var i=this,j=i.dom,m,h,l,k=[];m=j.getParent(g||i.getStart(),j.isBlock);h=j.getParent(f||i.getEnd(),j.isBlock);if(m){k.push(m)}if(m&&h&&m!=h){l=m;while((l=l.nextSibling)&&l!=h){if(j.isBlock(l)){k.push(l)}}}if(h&&m!=h){k.push(h)}return k},destroy:function(g){var f=this;f.win=null;if(f.tridentSel){f.tridentSel.destroy()}if(!g){c.removeUnload(f.destroy)}}})})(tinymce);(function(a){a.create("tinymce.dom.XMLWriter",{node:null,XMLWriter:function(c){function b(){var e=document.implementation;if(!e||!e.createDocument){try{return new ActiveXObject("MSXML2.DOMDocument")}catch(d){}try{return new ActiveXObject("Microsoft.XmlDom")}catch(d){}}else{return e.createDocument("","",null)}}this.doc=b();this.valid=a.isOpera||a.isWebKit;this.reset()},reset:function(){var b=this,c=b.doc;if(c.firstChild){c.removeChild(c.firstChild)}b.node=c.appendChild(c.createElement("html"))},writeStartElement:function(c){var b=this;b.node=b.node.appendChild(b.doc.createElement(c))},writeAttribute:function(c,b){if(this.valid){b=b.replace(/>/g,"%MCGT%")}this.node.setAttribute(c,b)},writeEndElement:function(){this.node=this.node.parentNode},writeFullEndElement:function(){var b=this,c=b.node;c.appendChild(b.doc.createTextNode(""));b.node=c.parentNode},writeText:function(b){if(this.valid){b=b.replace(/>/g,"%MCGT%")}this.node.appendChild(this.doc.createTextNode(b))},writeCDATA:function(b){this.node.appendChild(this.doc.createCDATASection(b))},writeComment:function(b){if(a.isIE){b=b.replace(/^\-|\-$/g," ")}this.node.appendChild(this.doc.createComment(b.replace(/\-\-/g," ")))},getContent:function(){var b;b=this.doc.xml||new XMLSerializer().serializeToString(this.doc);b=b.replace(/<\?[^?]+\?>||<\/html>||]+>/g,"");b=b.replace(/ ?\/>/g," />");if(this.valid){b=b.replace(/\%MCGT%/g,">")}return b}})})(tinymce);(function(a){a.create("tinymce.dom.StringWriter",{str:null,tags:null,count:0,settings:null,indent:null,StringWriter:function(b){this.settings=a.extend({indent_char:" ",indentation:0},b);this.reset()},reset:function(){this.indent="";this.str="";this.tags=[];this.count=0},writeStartElement:function(b){this._writeAttributesEnd();this.writeRaw("<"+b);this.tags.push(b);this.inAttr=true;this.count++;this.elementCount=this.count},writeAttribute:function(d,b){var c=this;c.writeRaw(" "+c.encode(d)+'="'+c.encode(b)+'"')},writeEndElement:function(){var b;if(this.tags.length>0){b=this.tags.pop();if(this._writeAttributesEnd(1)){this.writeRaw("")}if(this.settings.indentation>0){this.writeRaw("\n")}}},writeFullEndElement:function(){if(this.tags.length>0){this._writeAttributesEnd();this.writeRaw("");if(this.settings.indentation>0){this.writeRaw("\n")}}},writeText:function(b){this._writeAttributesEnd();this.writeRaw(this.encode(b));this.count++},writeCDATA:function(b){this._writeAttributesEnd();this.writeRaw("");this.count++},writeComment:function(b){this._writeAttributesEnd();this.writeRaw("");this.count++},writeRaw:function(b){this.str+=b},encode:function(b){return b.replace(/[<>&"]/g,function(c){switch(c){case"<":return"<";case">":return">";case"&":return"&";case'"':return"""}return c})},getContent:function(){return this.str},_writeAttributesEnd:function(b){if(!this.inAttr){return}this.inAttr=false;if(b&&this.elementCount==this.count){this.writeRaw(" />");return false}this.writeRaw(">");return true}})})(tinymce);(function(e){var g=e.extend,f=e.each,b=e.util.Dispatcher,d=e.isIE,a=e.isGecko;function c(h){return h.replace(/([?+*])/g,".$1")}e.create("tinymce.dom.Serializer",{Serializer:function(j){var i=this;i.key=0;i.onPreProcess=new b(i);i.onPostProcess=new b(i);try{i.writer=new e.dom.XMLWriter()}catch(h){i.writer=new e.dom.StringWriter()}i.settings=j=g({dom:e.DOM,valid_nodes:0,node_filter:0,attr_filter:0,invalid_attrs:/^(mce_|_moz_)/,closed:/^(br|hr|input|meta|img|link|param|area)$/,entity_encoding:"named",entities:"160,nbsp,161,iexcl,162,cent,163,pound,164,curren,165,yen,166,brvbar,167,sect,168,uml,169,copy,170,ordf,171,laquo,172,not,173,shy,174,reg,175,macr,176,deg,177,plusmn,178,sup2,179,sup3,180,acute,181,micro,182,para,183,middot,184,cedil,185,sup1,186,ordm,187,raquo,188,frac14,189,frac12,190,frac34,191,iquest,192,Agrave,193,Aacute,194,Acirc,195,Atilde,196,Auml,197,Aring,198,AElig,199,Ccedil,200,Egrave,201,Eacute,202,Ecirc,203,Euml,204,Igrave,205,Iacute,206,Icirc,207,Iuml,208,ETH,209,Ntilde,210,Ograve,211,Oacute,212,Ocirc,213,Otilde,214,Ouml,215,times,216,Oslash,217,Ugrave,218,Uacute,219,Ucirc,220,Uuml,221,Yacute,222,THORN,223,szlig,224,agrave,225,aacute,226,acirc,227,atilde,228,auml,229,aring,230,aelig,231,ccedil,232,egrave,233,eacute,234,ecirc,235,euml,236,igrave,237,iacute,238,icirc,239,iuml,240,eth,241,ntilde,242,ograve,243,oacute,244,ocirc,245,otilde,246,ouml,247,divide,248,oslash,249,ugrave,250,uacute,251,ucirc,252,uuml,253,yacute,254,thorn,255,yuml,402,fnof,913,Alpha,914,Beta,915,Gamma,916,Delta,917,Epsilon,918,Zeta,919,Eta,920,Theta,921,Iota,922,Kappa,923,Lambda,924,Mu,925,Nu,926,Xi,927,Omicron,928,Pi,929,Rho,931,Sigma,932,Tau,933,Upsilon,934,Phi,935,Chi,936,Psi,937,Omega,945,alpha,946,beta,947,gamma,948,delta,949,epsilon,950,zeta,951,eta,952,theta,953,iota,954,kappa,955,lambda,956,mu,957,nu,958,xi,959,omicron,960,pi,961,rho,962,sigmaf,963,sigma,964,tau,965,upsilon,966,phi,967,chi,968,psi,969,omega,977,thetasym,978,upsih,982,piv,8226,bull,8230,hellip,8242,prime,8243,Prime,8254,oline,8260,frasl,8472,weierp,8465,image,8476,real,8482,trade,8501,alefsym,8592,larr,8593,uarr,8594,rarr,8595,darr,8596,harr,8629,crarr,8656,lArr,8657,uArr,8658,rArr,8659,dArr,8660,hArr,8704,forall,8706,part,8707,exist,8709,empty,8711,nabla,8712,isin,8713,notin,8715,ni,8719,prod,8721,sum,8722,minus,8727,lowast,8730,radic,8733,prop,8734,infin,8736,ang,8743,and,8744,or,8745,cap,8746,cup,8747,int,8756,there4,8764,sim,8773,cong,8776,asymp,8800,ne,8801,equiv,8804,le,8805,ge,8834,sub,8835,sup,8836,nsub,8838,sube,8839,supe,8853,oplus,8855,otimes,8869,perp,8901,sdot,8968,lceil,8969,rceil,8970,lfloor,8971,rfloor,9001,lang,9002,rang,9674,loz,9824,spades,9827,clubs,9829,hearts,9830,diams,338,OElig,339,oelig,352,Scaron,353,scaron,376,Yuml,710,circ,732,tilde,8194,ensp,8195,emsp,8201,thinsp,8204,zwnj,8205,zwj,8206,lrm,8207,rlm,8211,ndash,8212,mdash,8216,lsquo,8217,rsquo,8218,sbquo,8220,ldquo,8221,rdquo,8222,bdquo,8224,dagger,8225,Dagger,8240,permil,8249,lsaquo,8250,rsaquo,8364,euro",bool_attrs:/(checked|disabled|readonly|selected|nowrap)/,valid_elements:"*[*]",extended_valid_elements:0,valid_child_elements:0,invalid_elements:0,fix_table_elements:1,fix_list_elements:true,fix_content_duplication:true,convert_fonts_to_spans:false,font_size_classes:0,font_size_style_values:0,apply_source_formatting:0,indent_mode:"simple",indent_char:"\t",indent_levels:1,remove_linebreaks:1,remove_redundant_brs:1,element_format:"xhtml"},j);i.dom=j.dom;if(j.remove_redundant_brs){i.onPostProcess.add(function(k,l){l.content=l.content.replace(/(
    \s*)+<\/(p|h[1-6]|div|li)>/gi,function(n,m,o){if(/^
    \s*<\//.test(n)){return""}return n})})}if(j.element_format=="html"){i.onPostProcess.add(function(k,l){l.content=l.content.replace(/<([^>]+) \/>/g,"<$1>")})}if(j.fix_list_elements){i.onPreProcess.add(function(v,s){var l,y,w=["ol","ul"],u,t,q,k=/^(OL|UL)$/,z;function m(r,x){var o=x.split(","),p;while((r=r.previousSibling)!=null){for(p=0;p1){f(q[1].split("|"),function(u){var p={},t;k=k||[];u=u.replace(/::/g,"~");u=/^([!\-])?([\w*.?~_\-]+|)([=:<])?(.+)?$/.exec(u);u[2]=u[2].replace(/~/g,":");if(u[1]=="!"){r=r||[];r.push(u[2])}if(u[1]=="-"){for(t=0;t]*>)(.*?)(<\/script>)/g},{pattern:/(]*>)(.*?)(<\/style>)/g},{pattern:/(]*>)(.*?)(<\/pre>)/g,encode:1},{pattern:/()/g}]});j=l.content;if(k.entity_encoding!=="raw"){j=i._encode(j)}if(!n.set){j=j.replace(/

    \s+<\/p>|]+)>\s+<\/p>/g,k.entity_encoding=="numeric"?" 

    ":" 

    ");if(k.remove_linebreaks){j=j.replace(/\r?\n|\r/g," ");j=j.replace(/(<[^>]+>)\s+/g,"$1 ");j=j.replace(/\s+(<\/[^>]+>)/g," $1");j=j.replace(/<(p|h[1-6]|blockquote|hr|div|table|tbody|tr|td|body|head|html|title|meta|style|pre|script|link|object) ([^>]+)>\s+/g,"<$1 $2>");j=j.replace(/<(p|h[1-6]|blockquote|hr|div|table|tbody|tr|td|body|head|html|title|meta|style|pre|script|link|object)>\s+/g,"<$1>");j=j.replace(/\s+<\/(p|h[1-6]|blockquote|hr|div|table|tbody|tr|td|body|head|html|title|meta|style|pre|script|link|object)>/g,"")}if(k.apply_source_formatting&&k.indent_mode=="simple"){j=j.replace(/<(\/?)(ul|hr|table|meta|link|tbody|tr|object|body|head|html|map)(|[^>]+)>\s*/g,"\n<$1$2$3>\n");j=j.replace(/\s*<(p|h[1-6]|blockquote|div|title|style|pre|script|td|li|area)(|[^>]+)>/g,"\n<$1$2>");j=j.replace(/<\/(p|h[1-6]|blockquote|div|title|style|pre|script|td|li)>\s*/g,"\n");j=j.replace(/\n\n/g,"\n")}}j=i._unprotect(j,l);j=j.replace(//g,"");j=j.replace(/(type|language)=\"mce-/g,'$1="');if(k.entity_encoding=="raw"){j=j.replace(/

     <\/p>|]+)> <\/p>/g,"\u00a0

    ")}}n.content=j},_serializeNode:function(D,o){var z=this,A=z.settings,x=z.writer,q,j,u,F,E,G,B,h,y,k,r,C,p,m;if(!A.node_filter||A.node_filter(D)){switch(D.nodeType){case 1:if(D.hasAttribute?D.hasAttribute("mce_bogus"):D.getAttribute("mce_bogus")){return}p=false;q=D.hasChildNodes();k=D.getAttribute("mce_name")||D.nodeName.toLowerCase();if(d){if(D.scopeName!=="HTML"&&D.scopeName!=="html"){k=D.scopeName+":"+k}}if(k.indexOf("mce:")===0){k=k.substring(4)}if(!z.validElementsRE||!z.validElementsRE.test(k)||(z.invalidElementsRE&&z.invalidElementsRE.test(k))||o){p=true;break}if(d){if(A.fix_content_duplication){if(D.mce_serialized==z.key){return}D.mce_serialized=z.key}if(k.charAt(0)=="/"){k=k.substring(1)}}else{if(a){if(D.nodeName==="BR"&&D.getAttribute("type")=="_moz"){return}}}if(z.childRules){if(z.parentElementsRE.test(z.elementName)){if(!z.childRules[z.elementName].test(k)){p=true;break}}z.elementName=k}r=z.findRule(k);k=r.name||k;m=A.closed.test(k);if((!q&&r.noEmpty)||(d&&!k)){p=true;break}if(r.requiredAttribs){G=r.requiredAttribs;for(F=G.length-1;F>=0;F--){if(this.dom.getAttrib(D,G[F])!==""){break}}if(F==-1){p=true;break}}x.writeStartElement(k);if(r.attribs){for(F=0,B=r.attribs,E=B.length;F-1;F--){h=B[F];if(h.specified){G=h.nodeName.toLowerCase();if(A.invalid_attrs.test(G)||!r.validAttribsRE.test(G)){continue}C=z.findAttribRule(r,G);y=z._getAttrib(D,C,G);if(y!==null){x.writeAttribute(G,y)}}}}if(k==="script"&&e.trim(D.innerHTML)){x.writeText("// ");x.writeCDATA(D.innerHTML.replace(/|<\[CDATA\[|\]\]>/g,""));q=false;break}if(r.padd){if(q&&(u=D.firstChild)&&u.nodeType===1&&D.childNodes.length===1){if(u.hasAttribute?u.hasAttribute("mce_bogus"):u.getAttribute("mce_bogus")){x.writeText("\u00a0")}}else{if(!q){x.writeText("\u00a0")}}}break;case 3:if(z.childRules&&z.parentElementsRE.test(z.elementName)){if(!z.childRules[z.elementName].test(D.nodeName)){return}}return x.writeText(D.nodeValue);case 4:return x.writeCDATA(D.nodeValue);case 8:return x.writeComment(D.nodeValue)}}else{if(D.nodeType==1){q=D.hasChildNodes()}}if(q&&!m){u=D.firstChild;while(u){z._serializeNode(u);z.elementName=k;u=u.nextSibling}}if(!p){if(!m){x.writeFullEndElement()}else{x.writeEndElement()}}},_protect:function(j){var i=this;j.items=j.items||[];function h(l){return l.replace(/[\r\n\\]/g,function(m){if(m==="\n"){return"\\n"}else{if(m==="\\"){return"\\\\"}}return"\\r"})}function k(l){return l.replace(/\\[\\rn]/g,function(m){if(m==="\\n"){return"\n"}else{if(m==="\\\\"){return"\\"}}return"\r"})}f(j.patterns,function(l){j.content=k(h(j.content).replace(l.pattern,function(n,o,m,p){m=k(m);if(l.encode){m=i._encode(m)}j.items.push(m);return o+""+p}))});return j},_unprotect:function(i,j){i=i.replace(/\"))}if(a&&j.ListBox){if(a.Button||a.SplitButton){e+=b.createHTML("td",{"class":"mceToolbarEnd"},b.createHTML("span",null,""))}}if(b.stdMode){e+=''+j.renderHTML()+""}else{e+=""+j.renderHTML()+""}if(f&&j.ListBox){if(f.Button||f.SplitButton){e+=b.createHTML("td",{"class":"mceToolbarStart"},b.createHTML("span",null,""))}}}g="mceToolbarEnd";if(j.Button){g+=" mceToolbarEndButton"}else{if(j.SplitButton){g+=" mceToolbarEndSplitButton"}else{if(j.ListBox){g+=" mceToolbarEndListBox"}}}e+=b.createHTML("td",{"class":g},b.createHTML("span",null,""));return b.createHTML("table",{id:l.id,"class":"mceToolbar"+(m["class"]?" "+m["class"]:""),cellpadding:"0",cellspacing:"0",align:l.settings.align||""},""+e+"")}});(function(b){var a=b.util.Dispatcher,c=b.each;b.create("tinymce.AddOnManager",{items:[],urls:{},lookup:{},onAdd:new a(this),get:function(d){return this.lookup[d]},requireLangPack:function(f){var d,e=b.EditorManager.settings;if(e&&e.language){d=this.urls[f]+"/langs/"+e.language+".js";if(!b.dom.Event.domLoaded&&!e.strict_mode){b.ScriptLoader.load(d)}else{b.ScriptLoader.add(d)}}},add:function(e,d){this.items.push(d);this.lookup[e]=d;this.onAdd.dispatch(this,e,d);return d},load:function(h,e,d,g){var f=this;if(f.urls[h]){return}if(e.indexOf("/")!=0&&e.indexOf("://")==-1){e=b.baseURL+"/"+e}f.urls[h]=e.substring(0,e.lastIndexOf("/"));b.ScriptLoader.add(e,d,g)}});b.PluginManager=new b.AddOnManager();b.ThemeManager=new b.AddOnManager()}(tinymce));(function(f){var g=f.each,h=f.extend,e=f.DOM,a=f.dom.Event,c=f.ThemeManager,b=f.PluginManager,d=f.explode;f.create("static tinymce.EditorManager",{editors:{},i18n:{},activeEditor:null,preInit:function(){var i=this,j=window.location;f.documentBaseURL=j.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,"");if(!/[\/\\]$/.test(f.documentBaseURL)){f.documentBaseURL+="/"}f.baseURL=new f.util.URI(f.documentBaseURL).toAbsolute(f.baseURL);f.EditorManager.baseURI=new f.util.URI(f.baseURL);if(document.domain&&j.hostname!=document.domain){f.relaxedDomain=document.domain}i.onBeforeUnload=new f.util.Dispatcher(i);a.add(window,"beforeunload",function(k){i.onBeforeUnload.dispatch(i,k)})},init:function(q){var p=this,l,k=f.ScriptLoader,o,n,i=[],m;function j(u,v,r){var t=u[v];if(!t){return}if(f.is(t,"string")){r=t.replace(/\.\w+$/,"");r=r?f.resolve(r):0;t=f.resolve(t)}return t.apply(r||this,Array.prototype.slice.call(arguments,2))}q=h({theme:"simple",language:"en",strict_loading_mode:document.contentType=="application/xhtml+xml"},q);p.settings=q;if(!a.domLoaded&&!q.strict_loading_mode){if(q.language){k.add(f.baseURL+"/langs/"+q.language+".js")}if(q.theme&&q.theme.charAt(0)!="-"&&!c.urls[q.theme]){c.load(q.theme,"themes/"+q.theme+"/editor_template"+f.suffix+".js")}if(q.plugins){l=d(q.plugins);if(f.inArray(l,"compat2x")!=-1){b.load("compat2x","plugins/compat2x/editor_plugin"+f.suffix+".js")}g(l,function(r){if(r&&r.charAt(0)!="-"&&!b.urls[r]){if(!f.isWebKit&&r=="safari"){return}b.load(r,"plugins/"+r+"/editor_plugin"+f.suffix+".js")}})}k.loadQueue()}a.add(document,"init",function(){var r,t;j(q,"onpageload");if(q.browsers){r=false;g(d(q.browsers),function(u){switch(u){case"ie":case"msie":if(f.isIE){r=true}break;case"gecko":if(f.isGecko){r=true}break;case"safari":case"webkit":if(f.isWebKit){r=true}break;case"opera":if(f.isOpera){r=true}break}});if(!r){return}}switch(q.mode){case"exact":r=q.elements||"";if(r.length>0){g(d(r),function(u){if(e.get(u)){m=new f.Editor(u,q);i.push(m);m.render(1)}else{o=0;g(document.forms,function(v){g(v.elements,function(w){if(w.name===u){u="mce_editor_"+o;e.setAttrib(w,"id",u);m=new f.Editor(u,q);i.push(m);m.render(1)}})})}})}break;case"textareas":case"specific_textareas":function s(v,u){return u.constructor===RegExp?u.test(v.className):e.hasClass(v,u)}g(e.select("textarea"),function(u){if(q.editor_deselector&&s(u,q.editor_deselector)){return}if(!q.editor_selector||s(u,q.editor_selector)){n=e.get(u.name);if(!u.id&&!n){u.id=u.name}if(!u.id||p.get(u.id)){u.id=e.uniqueId()}m=new f.Editor(u.id,q);i.push(m);m.render(1)}});break}if(q.oninit){r=t=0;g(i,function(u){t++;if(!u.initialized){u.onInit.add(function(){r++;if(r==t){j(q,"oninit")}})}else{r++}if(r==t){j(q,"oninit")}})}})},get:function(i){return this.editors[i]},getInstanceById:function(i){return this.get(i)},add:function(i){this.editors[i.id]=i;this._setActive(i);return i},remove:function(j){var i=this;if(!i.editors[j.id]){return null}delete i.editors[j.id];if(i.activeEditor==j){g(i.editors,function(k){i._setActive(k);return false})}j.destroy();return j},execCommand:function(o,m,l){var n=this,k=n.get(l),i;switch(o){case"mceFocus":k.focus();return true;case"mceAddEditor":case"mceAddControl":if(!n.get(l)){new f.Editor(l,n.settings).render()}return true;case"mceAddFrameControl":i=l.window;i.tinyMCE=tinyMCE;i.tinymce=f;f.DOM.doc=i.document;f.DOM.win=i;k=new f.Editor(l.element_id,l);k.render();if(f.isIE){function j(){k.destroy();i.detachEvent("onunload",j);i=i.tinyMCE=i.tinymce=null}i.attachEvent("onunload",j)}l.page_window=null;return true;case"mceRemoveEditor":case"mceRemoveControl":if(k){k.remove()}return true;case"mceToggleEditor":if(!k){n.execCommand("mceAddControl",0,l);return true}if(k.isHidden()){k.show()}else{k.hide()}return true}if(n.activeEditor){return n.activeEditor.execCommand(o,m,l)}return false},execInstanceCommand:function(m,l,k,j){var i=this.get(m);if(i){return i.execCommand(l,k,j)}return false},triggerSave:function(){g(this.editors,function(i){i.save()})},addI18n:function(k,l){var i,j=this.i18n;if(!f.is(k,"string")){g(k,function(n,m){g(n,function(q,p){g(q,function(s,r){if(p==="common"){j[m+"."+r]=s}else{j[m+"."+p+"."+r]=s}})})})}else{g(l,function(n,m){j[k+"."+m]=n})}},_setActive:function(i){this.selectedInstance=this.activeEditor=i}});f.EditorManager.preInit()})(tinymce);var tinyMCE=window.tinyMCE=tinymce.EditorManager;(function(n){var o=n.DOM,k=n.dom.Event,f=n.extend,l=n.util.Dispatcher;var j=n.each,a=n.isGecko,b=n.isIE,e=n.isWebKit;var d=n.is,h=n.ThemeManager,c=n.PluginManager,i=n.EditorManager;var p=n.inArray,m=n.grep,g=n.explode;n.create("tinymce.Editor",{Editor:function(u,r){var q=this;q.id=q.editorId=u;q.execCommands={};q.queryStateCommands={};q.queryValueCommands={};q.plugins={};j(["onPreInit","onBeforeRenderUI","onPostRender","onInit","onRemove","onActivate","onDeactivate","onClick","onEvent","onMouseUp","onMouseDown","onDblClick","onKeyDown","onKeyUp","onKeyPress","onContextMenu","onSubmit","onReset","onPaste","onPreProcess","onPostProcess","onBeforeSetContent","onBeforeGetContent","onSetContent","onGetContent","onLoadContent","onSaveContent","onNodeChange","onChange","onBeforeExecCommand","onExecCommand","onUndo","onRedo","onVisualAid","onSetProgressState"],function(s){q[s]=new l(q)});q.settings=r=f({id:u,language:"en",docs_language:"en",theme:"simple",skin:"default",delta_width:0,delta_height:0,popup_css:"",plugins:"",document_base_url:n.documentBaseURL,add_form_submit_trigger:1,submit_patch:1,add_unload_trigger:1,convert_urls:1,relative_urls:1,remove_script_host:1,table_inline_editing:0,object_resizing:1,cleanup:1,accessibility_focus:1,custom_shortcuts:1,custom_undo_redo_keyboard_shortcuts:1,custom_undo_redo_restore_selection:1,custom_undo_redo:1,doctype:'',visual_table_class:"mceItemTable",visual:1,inline_styles:true,convert_fonts_to_spans:true,font_size_style_values:"xx-small,x-small,small,medium,large,x-large,xx-large",apply_source_formatting:1,directionality:"ltr",forced_root_block:"p",valid_elements:"@[id|class|style|title|dir';F.iframeHTML+='';if(n.relaxedDomain){F.iframeHTML+=' + + +text_direction) ) : ?> + + + + + + + + +
      +
    • +
    • +
    • +
    • +
    + +
    + +
    +

    +

    Rich editing, also called WYSIWYG for What You See Is What You Get, means your text is formatted as you type. The rich editor creates HTML code behind the scenes while you concentrate on writing. Font styles, links and images all appear approximately as they will on the internet.') ?>

    +

    +

    +

    +
    + + + + + + +
    + +
    +
    + +
    +
    + + + diff --git a/wp-includes/js/tinymce/wp-tinymce.js b/wp-includes/js/tinymce/wp-tinymce.js new file mode 100644 index 0000000..cc13fc8 --- /dev/null +++ b/wp-includes/js/tinymce/wp-tinymce.js @@ -0,0 +1,28 @@ +//core +var tinymce={majorVersion:"3",minorVersion:"2.4.1",releaseDate:"2009-05-25",_init:function(){var o=this,k=document,l=window,j=navigator,b=j.userAgent,h,a,g,f,e,m;o.isOpera=l.opera&&opera.buildNumber;o.isWebKit=/WebKit/.test(b);o.isIE=!o.isWebKit&&!o.isOpera&&(/MSIE/gi).test(b)&&(/Explorer/gi).test(j.appName);o.isIE6=o.isIE&&/MSIE [56]/.test(b);o.isGecko=!o.isWebKit&&/Gecko/.test(b);o.isMac=b.indexOf("Mac")!=-1;o.isAir=/adobeair/i.test(b);if(l.tinyMCEPreInit){o.suffix=tinyMCEPreInit.suffix;o.baseURL=tinyMCEPreInit.base;o.query=tinyMCEPreInit.query;return}o.suffix="";a=k.getElementsByTagName("base");for(h=0;h=c.length){for(e=0,b=g.length;e=c.length||g[e]!=c[e]){f=e+1;break}}}if(g.length=g.length||g[e]!=c[e]){f=e+1;break}}}if(f==1){return h}for(e=0,b=g.length-(f-1);e=0;c--){if(f[c].length==0||f[c]=="."){continue}if(f[c]==".."){b++;continue}if(b>0){b--;continue}g.push(f[c])}c=e.length-b;if(c<=0){return"/"+g.reverse().join("/")+d}return"/"+e.slice(0,c).join("/")+"/"+g.reverse().join("/")+d},getURI:function(d){var c,b=this;if(!b.source||d){c="";if(!d){if(b.protocol){c+=b.protocol+"://"}if(b.userInfo){c+=b.userInfo+"@"}if(b.host){c+=b.host}if(b.port){c+=":"+b.port}}if(b.path){c+=b.path}if(b.query){c+="?"+b.query}if(b.anchor){c+="#"+b.anchor}b.source=c}return b.source}})})();(function(){var a=tinymce.each;tinymce.create("static tinymce.util.Cookie",{getHash:function(d){var b=this.get(d),c;if(b){a(b.split("&"),function(e){e=e.split("=");c=c||{};c[unescape(e[0])]=unescape(e[1])})}return c},setHash:function(j,b,g,f,i,c){var h="";a(b,function(e,d){h+=(!h?"":"&")+escape(d)+"="+escape(e)});this.set(j,h,g,f,i,c)},get:function(i){var h=document.cookie,g,f=i+"=",d;if(!h){return}d=h.indexOf("; "+f);if(d==-1){d=h.indexOf(f);if(d!=0){return null}}else{d+=2}g=h.indexOf(";",d);if(g==-1){g=h.length}return unescape(h.substring(d+f.length,g))},set:function(i,b,g,f,h,c){document.cookie=i+"="+escape(b)+((g)?"; expires="+g.toGMTString():"")+((f)?"; path="+escape(f):"")+((h)?"; domain="+h:"")+((c)?"; secure":"")},remove:function(e,b){var c=new Date();c.setTime(c.getTime()-1000);this.set(e,"",c,b,c)}})})();tinymce.create("static tinymce.util.JSON",{serialize:function(e){var c,a,d=tinymce.util.JSON.serialize,b;if(e==null){return"null"}b=typeof e;if(b=="string"){a="\bb\tt\nn\ff\rr\"\"''\\\\";return'"'+e.replace(/([\u0080-\uFFFF\x00-\x1f\"])/g,function(g,f){c=a.indexOf(f);if(c+1){return"\\"+a.charAt(c+1)}g=f.charCodeAt().toString(16);return"\\u"+"0000".substring(g.length)+g})+'"'}if(b=="object"){if(e.hasOwnProperty&&e instanceof Array){for(c=0,a="[";c0?",":"")+d(e[c])}return a+"]"}a="{";for(c in e){a+=typeof e[c]!="function"?(a.length>1?',"':'"')+c+'":'+d(e[c]):""}return a+"}"}return""+e},parse:function(s){try{return eval("("+s+")")}catch(ex){}}});tinymce.create("static tinymce.util.XHR",{send:function(g){var a,e,b=window,h=0;g.scope=g.scope||this;g.success_scope=g.success_scope||g.scope;g.error_scope=g.error_scope||g.scope;g.async=g.async===false?false:true;g.data=g.data||"";function d(i){a=0;try{a=new ActiveXObject(i)}catch(c){}return a}a=b.XMLHttpRequest?new XMLHttpRequest():d("Microsoft.XMLHTTP")||d("Msxml2.XMLHTTP");if(a){if(a.overrideMimeType){a.overrideMimeType(g.content_type)}a.open(g.type||(g.data?"POST":"GET"),g.url,g.async);if(g.content_type){a.setRequestHeader("Content-Type",g.content_type)}a.send(g.data);function f(){if(!g.async||a.readyState==4||h++>10000){if(g.success&&h<10000&&a.status==200){g.success.call(g.success_scope,""+a.responseText,a,g)}else{if(g.error){g.error.call(g.error_scope,h>10000?"TIMED_OUT":"GENERAL",a,g)}}a=null}else{b.setTimeout(f,10)}}if(!g.async){return f()}e=b.setTimeout(f,10)}}});(function(){var c=tinymce.extend,b=tinymce.util.JSON,a=tinymce.util.XHR;tinymce.create("tinymce.util.JSONRequest",{JSONRequest:function(d){this.settings=c({},d);this.count=0},send:function(f){var e=f.error,d=f.success;f=c(this.settings,f);f.success=function(h,g){h=b.parse(h);if(typeof(h)=="undefined"){h={error:"JSON Parse error."}}if(h.error){e.call(f.error_scope||f.scope,h.error,g)}else{d.call(f.success_scope||f.scope,h.result)}};f.error=function(h,g){e.call(f.error_scope||f.scope,h,g)};f.data=b.serialize({id:f.id||"c"+(this.count++),method:f.method,params:f.params});f.content_type="application/json";a.send(f)},"static":{sendRPC:function(d){return new tinymce.util.JSONRequest().send(d)}}})}());(function(c){var e=c.each,b=c.is;var d=c.isWebKit,a=c.isIE;c.create("tinymce.dom.DOMUtils",{doc:null,root:null,files:null,pixelStyles:/^(top|left|bottom|right|width|height|borderWidth)$/,props:{"for":"htmlFor","class":"className",className:"className",checked:"checked",disabled:"disabled",maxlength:"maxLength",readonly:"readOnly",selected:"selected",value:"value",id:"id",name:"name",type:"type"},DOMUtils:function(i,g){var f=this;f.doc=i;f.win=window;f.files={};f.cssFlicker=false;f.counter=0;f.boxModel=!c.isIE||i.compatMode=="CSS1Compat";f.stdMode=i.documentMode===8;f.settings=g=c.extend({keep_values:false,hex_colors:1,process_html:1},g);if(c.isIE6){try{i.execCommand("BackgroundImageCache",false,true)}catch(h){f.cssFlicker=true}}c.addUnload(f.destroy,f)},getRoot:function(){var f=this,g=f.settings;return(g&&f.get(g.root_element))||f.doc.body},getViewPort:function(g){var h,f;g=!g?this.win:g;h=g.document;f=this.boxModel?h.documentElement:h.body;return{x:g.pageXOffset||f.scrollLeft,y:g.pageYOffset||f.scrollTop,w:g.innerWidth||f.clientWidth,h:g.innerHeight||f.clientHeight}},getRect:function(i){var h,f=this,g;i=f.get(i);h=f.getPos(i);g=f.getSize(i);return{x:h.x,y:h.y,w:g.w,h:g.h}},getSize:function(j){var g=this,f,i;j=g.get(j);f=g.getStyle(j,"width");i=g.getStyle(j,"height");if(f.indexOf("px")===-1){f=0}if(i.indexOf("px")===-1){i=0}return{w:parseInt(f)||j.offsetWidth||j.clientWidth,h:parseInt(i)||j.offsetHeight||j.clientHeight}},is:function(g,f){return c.dom.Sizzle.matches(f,g.nodeType?[g]:g).length>0},getParent:function(i,h,g){return this.getParents(i,h,g,false)},getParents:function(p,k,i,m){var h=this,g,j=h.settings,l=[];p=h.get(p);m=m===undefined;if(j.strict_root){i=i||h.getRoot()}if(b(k,"string")){g=k;if(k==="*"){k=function(f){return f.nodeType==1}}else{k=function(f){return h.is(f,g)}}}while(p){if(p==i||!p.nodeType||p.nodeType===9){break}if(!k||k(p)){if(m){l.push(p)}else{return p}}p=p.parentNode}return m?l:null},get:function(f){var g;if(f&&this.doc&&typeof(f)=="string"){g=f;f=this.doc.getElementById(f);if(f&&f.id!==g){return this.doc.getElementsByName(g)[1]}}return f},select:function(h,g){var f=this;return c.dom.Sizzle(h,f.get(g)||f.get(f.settings.root_element)||f.doc,[])},add:function(j,l,f,i,k){var g=this;return this.run(j,function(n){var m,h;m=b(l,"string")?g.doc.createElement(l):l;g.setAttribs(m,f);if(i){if(i.nodeType){m.appendChild(i)}else{g.setHTML(m,i)}}return !k?n.appendChild(m):m})},create:function(i,f,g){return this.add(this.doc.createElement(i),i,f,g,1)},createHTML:function(m,f,j){var l="",i=this,g;l+="<"+m;for(g in f){if(f.hasOwnProperty(g)){l+=" "+g+'="'+i.encode(f[g])+'"'}}if(c.is(j)){return l+">"+j+""}return l+" />"},remove:function(h,f){var g=this;return this.run(h,function(m){var l,k,j;l=m.parentNode;if(!l){return null}if(f){for(j=m.childNodes.length-1;j>=0;j--){g.insertAfter(m.childNodes[j],m)}}if(g.fixPsuedoLeaks){l=m.cloneNode(true);f="IELeakGarbageBin";k=g.get(f)||g.add(g.doc.body,"div",{id:f,style:"display:none"});k.appendChild(m);k.innerHTML="";return l}return l.removeChild(m)})},setStyle:function(i,f,g){var h=this;return h.run(i,function(l){var k,j;k=l.style;f=f.replace(/-(\D)/g,function(n,m){return m.toUpperCase()});if(h.pixelStyles.test(f)&&(c.is(g,"number")||/^[\-0-9\.]+$/.test(g))){g+="px"}switch(f){case"opacity":if(a){k.filter=g===""?"":"alpha(opacity="+(g*100)+")";if(!i.currentStyle||!i.currentStyle.hasLayout){k.display="inline-block"}}k[f]=k["-moz-opacity"]=k["-khtml-opacity"]=g||"";break;case"float":a?k.styleFloat=g:k.cssFloat=g;break;default:k[f]=g||""}if(h.settings.update_styles){h.setAttrib(l,"mce_style")}})},getStyle:function(i,f,h){i=this.get(i);if(!i){return false}if(this.doc.defaultView&&h){f=f.replace(/[A-Z]/g,function(j){return"-"+j});try{return this.doc.defaultView.getComputedStyle(i,null).getPropertyValue(f)}catch(g){return null}}f=f.replace(/-(\D)/g,function(k,j){return j.toUpperCase()});if(f=="float"){f=a?"styleFloat":"cssFloat"}if(i.currentStyle&&h){return i.currentStyle[f]}return i.style[f]},setStyles:function(i,j){var g=this,h=g.settings,f;f=h.update_styles;h.update_styles=0;e(j,function(k,l){g.setStyle(i,l,k)});h.update_styles=f;if(h.update_styles){g.setAttrib(i,h.cssText)}},setAttrib:function(h,i,f){var g=this;if(!h||!i){return}if(g.settings.strict){i=i.toLowerCase()}return this.run(h,function(k){var j=g.settings;switch(i){case"style":if(!b(f,"string")){e(f,function(l,m){g.setStyle(k,m,l)});return}if(j.keep_values){if(f&&!g._isRes(f)){k.setAttribute("mce_style",f,2)}else{k.removeAttribute("mce_style",2)}}k.style.cssText=f;break;case"class":k.className=f||"";break;case"src":case"href":if(j.keep_values){if(j.url_converter){f=j.url_converter.call(j.url_converter_scope||g,f,i,k)}g.setAttrib(k,"mce_"+i,f,2)}break;case"shape":k.setAttribute("mce_style",f);break}if(b(f)&&f!==null&&f.length!==0){k.setAttribute(i,""+f,2)}else{k.removeAttribute(i,2)}})},setAttribs:function(g,h){var f=this;return this.run(g,function(i){e(h,function(j,k){f.setAttrib(i,k,j)})})},getAttrib:function(i,j,h){var f,g=this;i=g.get(i);if(!i||i.nodeType!==1){return false}if(!b(h)){h=""}if(/^(src|href|style|coords|shape)$/.test(j)){f=i.getAttribute("mce_"+j);if(f){return f}}if(a&&g.props[j]){f=i[g.props[j]];f=f&&f.nodeValue?f.nodeValue:f}if(!f){f=i.getAttribute(j,2)}if(j==="style"){f=f||i.style.cssText;if(f){f=g.serializeStyle(g.parseStyle(f));if(g.settings.keep_values&&!g._isRes(f)){i.setAttribute("mce_style",f)}}}if(d&&j==="class"&&f){f=f.replace(/(apple|webkit)\-[a-z\-]+/gi,"")}if(a){switch(j){case"rowspan":case"colspan":if(f===1){f=""}break;case"size":if(f==="+0"||f===20||f===0){f=""}break;case"width":case"height":case"vspace":case"checked":case"disabled":case"readonly":if(f===0){f=""}break;case"hspace":if(f===-1){f=""}break;case"maxlength":case"tabindex":if(f===32768||f===2147483647||f==="32768"){f=""}break;case"multiple":case"compact":case"noshade":case"nowrap":if(f===65535){return j}return h;case"shape":f=f.toLowerCase();break;default:if(j.indexOf("on")===0&&f){f=(""+f).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/,"$1")}}}return(f!==undefined&&f!==null&&f!=="")?""+f:h},getPos:function(m,i){var g=this,f=0,l=0,j,k=g.doc,h;m=g.get(m);i=i||k.body;if(m){if(a&&!g.stdMode){m=m.getBoundingClientRect();j=g.boxModel?k.documentElement:k.body;f=g.getStyle(g.select("html")[0],"borderWidth");f=(f=="medium"||g.boxModel&&!g.isIE6)&&2||f;m.top+=g.win.self!=g.win.top?2:0;return{x:m.left+j.scrollLeft-f,y:m.top+j.scrollTop-f}}h=m;while(h&&h!=i&&h.nodeType){f+=h.offsetLeft||0;l+=h.offsetTop||0;h=h.offsetParent}h=m.parentNode;while(h&&h!=i&&h.nodeType){f-=h.scrollLeft||0;l-=h.scrollTop||0;h=h.parentNode}}return{x:f,y:l}},parseStyle:function(h){var i=this,j=i.settings,k={};if(!h){return k}function f(w,q,v){var o,u,m,n;o=k[w+"-top"+q];if(!o){return}u=k[w+"-right"+q];if(o!=u){return}m=k[w+"-bottom"+q];if(u!=m){return}n=k[w+"-left"+q];if(m!=n){return}k[v]=n;delete k[w+"-top"+q];delete k[w+"-right"+q];delete k[w+"-bottom"+q];delete k[w+"-left"+q]}function g(n,m,l,p){var o;o=k[m];if(!o){return}o=k[l];if(!o){return}o=k[p];if(!o){return}k[n]=k[m]+" "+k[l]+" "+k[p];delete k[m];delete k[l];delete k[p]}h=h.replace(/&(#?[a-z0-9]+);/g,"&$1_MCE_SEMI_");e(h.split(";"),function(m){var l,n=[];if(m){m=m.replace(/_MCE_SEMI_/g,";");m=m.replace(/url\([^\)]+\)/g,function(o){n.push(o);return"url("+n.length+")"});m=m.split(":");l=c.trim(m[1]);l=l.replace(/url\(([^\)]+)\)/g,function(p,o){return n[parseInt(o)-1]});l=l.replace(/rgb\([^\)]+\)/g,function(o){return i.toHex(o)});if(j.url_converter){l=l.replace(/url\([\'\"]?([^\)\'\"]+)[\'\"]?\)/g,function(o,p){return"url("+j.url_converter.call(j.url_converter_scope||i,i.decode(p),"style",null)+")"})}k[c.trim(m[0]).toLowerCase()]=l}});f("border","","border");f("border","-width","border-width");f("border","-color","border-color");f("border","-style","border-style");f("padding","","padding");f("margin","","margin");g("border","border-width","border-style","border-color");if(a){if(k.border=="medium none"){k.border=""}}return k},serializeStyle:function(g){var f="";e(g,function(i,h){if(h&&i){if(c.isGecko&&h.indexOf("-moz-")===0){return}switch(h){case"color":case"background-color":i=i.toLowerCase();break}f+=(f?" ":"")+h+": "+i+";"}});return f},loadCSS:function(f){var h=this,i=h.doc,g;if(!f){f=""}g=h.select("head")[0];e(f.split(","),function(j){var k;if(h.files[j]){return}h.files[j]=true;k=h.create("link",{rel:"stylesheet",href:c._addVer(j)});if(a&&i.documentMode){k.onload=function(){i.recalc();k.onload=null}}g.appendChild(k)})},addClass:function(f,g){return this.run(f,function(h){var i;if(!g){return 0}if(this.hasClass(h,g)){return h.className}i=this.removeClass(h,g);return h.className=(i!=""?(i+" "):"")+g})},removeClass:function(h,i){var f=this,g;return f.run(h,function(k){var j;if(f.hasClass(k,i)){if(!g){g=new RegExp("(^|\\s+)"+i+"(\\s+|$)","g")}j=k.className.replace(g," ");return k.className=c.trim(j!=" "?j:"")}return k.className})},hasClass:function(g,f){g=this.get(g);if(!g||!f){return false}return(" "+g.className+" ").indexOf(" "+f+" ")!==-1},show:function(f){return this.setStyle(f,"display","block")},hide:function(f){return this.setStyle(f,"display","none")},isHidden:function(f){f=this.get(f);return !f||f.style.display=="none"||this.getStyle(f,"display")=="none"},uniqueId:function(f){return(!f?"mce_":f)+(this.counter++)},setHTML:function(i,g){var f=this;return this.run(i,function(m){var h,k,j,q,l,h;g=f.processHTML(g);if(a){function o(){try{m.innerHTML="
    "+g;m.removeChild(m.firstChild)}catch(n){while(m.firstChild){m.firstChild.removeNode()}h=f.create("div");h.innerHTML="
    "+g;e(h.childNodes,function(r,p){if(p){m.appendChild(r)}})}}if(f.settings.fix_ie_paragraphs){g=g.replace(/

    <\/p>|]+)><\/p>|/gi,' 

    ')}o();if(f.settings.fix_ie_paragraphs){j=m.getElementsByTagName("p");for(k=j.length-1,h=0;k>=0;k--){q=j[k];if(!q.hasChildNodes()){if(!q.mce_keep){h=1;break}q.removeAttribute("mce_keep")}}}if(h){g=g.replace(/

    ]+)>|

    /g,'

    ');g=g.replace(/<\/p>/g,"
    ");o();if(f.settings.fix_ie_paragraphs){j=m.getElementsByTagName("DIV");for(k=j.length-1;k>=0;k--){q=j[k];if(q.mce_tmp){l=f.doc.createElement("p");q.cloneNode(false).outerHTML.replace(/([a-z0-9\-_]+)=/gi,function(p,n){var r;if(n!=="mce_tmp"){r=q.getAttribute(n);if(!r&&n==="class"){r=q.className}l.setAttribute(n,r)}});for(h=0;h|]+)>/gi,"<$1b$2>");j=j.replace(/<(\/?)em>|]+)>/gi,"<$1i$2>")}else{if(a){j=j.replace(/'/g,"'");j=j.replace(/\s+(disabled|checked|readonly|selected)\s*=\s*[\"\']?(false|0)[\"\']?/gi,"")}}j=j.replace(/]+)\/>|/gi,"");if(i.keep_values){if(/)/g,"\n");h=h.replace(/^[\r\n]*|[\r\n]*$/g,"");h=h.replace(/^\s*(\/\/\s*|\]\]>|-->|\]\]-->)\s*$/g,"");return h}j=j.replace(/]+|)>([\s\S]*?)<\/script>/g,function(h,l,k){if(!l){l=' type="text/javascript"'}l=l.replace(/(type|language)=\"?/,"$&mce-");l=l.replace(/src=\"([^\"]+)\"?/,function(m,n){if(i.url_converter){n=g.encode(i.url_converter.call(i.url_converter_scope||g,g.decode(n),"src","script"))}return'mce_src="'+n+'"'});if(c.trim(k)){k=""}return""+k+""});j=j.replace(/]+|)>([\s\S]*?)<\/style>/g,function(h,l,k){if(k){k=""}return""+k+""})}j=j.replace(//g,"");j=j.replace(/<([\w:]+) [^>]*(src|href|style|shape|coords)[^>]*>/gi,function(h,l){function k(o,n,q){var p=q;if(h.indexOf("mce_"+n)!=-1){return o}if(n=="style"){if(g._isRes(q)){return o}if(i.hex_colors){p=p.replace(/rgb\([^\)]+\)/g,function(m){return g.toHex(m)})}if(i.url_converter){p=p.replace(/url\([\'\"]?([^\)\'\"]+)\)/g,function(m,r){return"url("+g.encode(i.url_converter.call(i.url_converter_scope||g,g.decode(r),n,l))+")"})}}else{if(n!="coords"&&n!="shape"){if(i.url_converter){p=g.encode(i.url_converter.call(i.url_converter_scope||g,g.decode(q),n,l))}}}return" "+n+'="'+q+'" mce_'+n+'="'+p+'"'}h=h.replace(/ (src|href|style|coords|shape)=[\"]([^\"]+)[\"]/gi,k);h=h.replace(/ (src|href|style|coords|shape)=[\']([^\']+)[\']/gi,k);return h.replace(/ (src|href|style|coords|shape)=([^\s\"\'>]+)/gi,k)})}return j},getOuterHTML:function(f){var g;f=this.get(f);if(!f){return null}if(f.outerHTML!==undefined){return f.outerHTML}g=(f.ownerDocument||this.doc).createElement("body");g.appendChild(f.cloneNode(true));return g.innerHTML},setOuterHTML:function(i,g,j){var f=this;return this.run(i,function(h){var l,k;h=f.get(h);j=j||h.ownerDocument||f.doc;if(a&&h.nodeType==1){h.outerHTML=g}else{k=j.createElement("body");k.innerHTML=g;l=k.lastChild;while(l){f.insertAfter(l.cloneNode(true),h);l=l.previousSibling}f.remove(h)}})},decode:function(g){var h,i,f;if(/&[^;]+;/.test(g)){h=this.doc.createElement("div");h.innerHTML=g;i=h.firstChild;f="";if(i){do{f+=i.nodeValue}while(i.nextSibling)}return f||g}return g},encode:function(f){return f?(""+f).replace(/[<>&\"]/g,function(h,g){switch(h){case"&":return"&";case'"':return""";case"<":return"<";case">":return">"}return h}):f},insertAfter:function(h,g){var f=this;g=f.get(g);return this.run(h,function(k){var j,i;j=g.parentNode;i=g.nextSibling;if(i){j.insertBefore(k,i)}else{j.appendChild(k)}return k})},isBlock:function(f){if(f.nodeType&&f.nodeType!==1){return false}f=f.nodeName||f;return/^(H[1-6]|HR|P|DIV|ADDRESS|PRE|FORM|TABLE|LI|OL|UL|TR|TD|CAPTION|BLOCKQUOTE|CENTER|DL|DT|DD|DIR|FIELDSET|NOSCRIPT|NOFRAMES|MENU|ISINDEX|SAMP)$/.test(f)},replace:function(i,h,f){var g=this;if(b(h,"array")){i=i.cloneNode(true)}return g.run(h,function(j){if(f){e(j.childNodes,function(k){i.appendChild(k.cloneNode(true))})}if(g.fixPsuedoLeaks&&j.nodeType===1){j.parentNode.insertBefore(i,j);g.remove(j);return i}return j.parentNode.replaceChild(i,j)})},findCommonAncestor:function(h,f){var i=h,g;while(i){g=f;while(g&&i!=g){g=g.parentNode}if(i==g){break}i=i.parentNode}if(!i&&h.ownerDocument){return h.ownerDocument.documentElement}return i},toHex:function(f){var h=/^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(f);function g(i){i=parseInt(i).toString(16);return i.length>1?i:"0"+i}if(h){f="#"+g(h[1])+g(h[2])+g(h[3]);return f}return f},getClasses:function(){var l=this,g=[],k,m={},n=l.settings.class_filter,j;if(l.classes){return l.classes}function o(f){e(f.imports,function(i){o(i)});e(f.cssRules||f.rules,function(i){switch(i.type||1){case 1:if(i.selectorText){e(i.selectorText.split(","),function(p){p=p.replace(/^\s*|\s*$|^\s\./g,"");if(/\.mce/.test(p)||!/\.[\w\-]+$/.test(p)){return}j=p;p=p.replace(/.*\.([a-z0-9_\-]+).*/i,"$1");if(n&&!(p=n(p,j))){return}if(!m[p]){g.push({"class":p});m[p]=1}})}break;case 3:o(i.styleSheet);break}})}try{e(l.doc.styleSheets,o)}catch(h){}if(g.length>0){l.classes=g}return g},run:function(j,i,h){var g=this,k;if(g.doc&&typeof(j)==="string"){j=g.get(j)}if(!j){return false}h=h||this;if(!j.nodeType&&(j.length||j.length===0)){k=[];e(j,function(l,f){if(l){if(typeof(l)=="string"){l=g.doc.getElementById(l)}k.push(i.call(h,l,f))}});return k}return i.call(h,j)},getAttribs:function(g){var f;g=this.get(g);if(!g){return[]}if(a){f=[];if(g.nodeName=="OBJECT"){return g.attributes}g.cloneNode(false).outerHTML.replace(/([a-z0-9\:\-_]+)=/gi,function(i,h){f.push({specified:1,nodeName:h})});return f}return g.attributes},destroy:function(g){var f=this;if(f.events){f.events.destroy()}f.win=f.doc=f.root=f.events=null;if(!g){c.removeUnload(f.destroy)}},createRng:function(){var f=this.doc;return f.createRange?f.createRange():new c.dom.Range(this)},split:function(l,k,o){var p=this,f=p.createRng(),m,j,n;function g(r,q){r=r[q];if(r&&r[q]&&r[q].nodeType==1&&i(r[q])){p.remove(r[q])}}function i(q){q=p.getOuterHTML(q);q=q.replace(/<(img|hr|table)/gi,"-");q=q.replace(/<[^>]+>/g,"");return q.replace(/[ \t\r\n]+| | /g,"")==""}function h(r){var q=0;while(r.previousSibling){q++;r=r.previousSibling}return q}if(l&&k){f.setStart(l.parentNode,h(l));f.setEnd(k.parentNode,h(k));m=f.extractContents();f=p.createRng();f.setStart(k.parentNode,h(k)+1);f.setEnd(l.parentNode,h(l)+1);j=f.extractContents();n=l.parentNode;g(m,"lastChild");if(!i(m)){n.insertBefore(m,l)}if(o){n.replaceChild(o,k)}else{n.insertBefore(k,l)}g(j,"firstChild");if(!i(j)){n.insertBefore(j,l)}p.remove(l);return o||k}},bind:function(j,f,i,h){var g=this;if(!g.events){g.events=new c.dom.EventUtils()}return g.events.add(j,f,i,h||this)},unbind:function(i,f,h){var g=this;if(!g.events){g.events=new c.dom.EventUtils()}return g.events.remove(i,f,h)},_isRes:function(f){return/^(top|left|bottom|right|width|height)/i.test(f)||/;\s*(top|left|bottom|right|width|height)/i.test(f)}});c.DOM=new c.dom.DOMUtils(document,{process_html:0})})(tinymce);(function(f){var h=0,c=1,e=2,d=tinymce.extend;function g(m,k){var j,l;if(m.parentNode!=k){return -1}for(l=k.firstChild,j=0;l!=m;l=l.nextSibling){j++}return j}function b(k){var j=0;while(k.previousSibling){j++;k=k.previousSibling}return j}function i(j,k){var l;if(j.nodeType==3){return j}if(k<0){return j}l=j.firstChild;while(l!=null&&k>0){--k;l=l.nextSibling}if(l!=null){return l}return j}function a(k){var j=k.doc;d(this,{dom:k,startContainer:j,startOffset:0,endContainer:j,endOffset:0,collapsed:true,commonAncestorContainer:j,START_TO_START:0,START_TO_END:1,END_TO_END:2,END_TO_START:3})}d(a.prototype,{setStart:function(k,j){this._setEndPoint(true,k,j)},setEnd:function(k,j){this._setEndPoint(false,k,j)},setStartBefore:function(j){this.setStart(j.parentNode,b(j))},setStartAfter:function(j){this.setStart(j.parentNode,b(j)+1)},setEndBefore:function(j){this.setEnd(j.parentNode,b(j))},setEndAfter:function(j){this.setEnd(j.parentNode,b(j)+1)},collapse:function(k){var j=this;if(k){j.endContainer=j.startContainer;j.endOffset=j.startOffset}else{j.startContainer=j.endContainer;j.startOffset=j.endOffset}j.collapsed=true},selectNode:function(j){this.setStartBefore(j);this.setEndAfter(j)},selectNodeContents:function(j){this.setStart(j,0);this.setEnd(j,j.nodeType===1?j.childNodes.length:j.nodeValue.length)},compareBoundaryPoints:function(m,n){var l=this,p=l.startContainer,o=l.startOffset,k=l.endContainer,j=l.endOffset;if(m===0){return l._compareBoundaryPoints(p,o,p,o)}if(m===1){return l._compareBoundaryPoints(p,o,k,j)}if(m===2){return l._compareBoundaryPoints(k,j,k,j)}if(m===3){return l._compareBoundaryPoints(k,j,p,o)}},deleteContents:function(){this._traverse(e)},extractContents:function(){return this._traverse(h)},cloneContents:function(){return this._traverse(c)},insertNode:function(m){var j=this,l,k;if(m.nodeType===3||m.nodeType===4){l=j.startContainer.splitText(j.startOffset);j.startContainer.parentNode.insertBefore(m,l)}else{if(j.startContainer.childNodes.length>0){k=j.startContainer.childNodes[j.startOffset]}j.startContainer.insertBefore(m,k)}},surroundContents:function(l){var j=this,k=j.extractContents();j.insertNode(l);l.appendChild(k);j.selectNode(l)},cloneRange:function(){var j=this;return d(new a(j.dom),{startContainer:j.startContainer,startOffset:j.startOffset,endContainer:j.endContainer,endOffset:j.endOffset,collapsed:j.collapsed,commonAncestorContainer:j.commonAncestorContainer})},_isCollapsed:function(){return(this.startContainer==this.endContainer&&this.startOffset==this.endOffset)},_compareBoundaryPoints:function(m,p,k,o){var q,l,j,r,t,s;if(m==k){if(p==o){return 0}else{if(p0){l.collapse(k)}}l.collapsed=l._isCollapsed();l.commonAncestorContainer=l.dom.findCommonAncestor(l.startContainer,l.endContainer)},_traverse:function(r){var s=this,q,m=0,v=0,k,o,l,n,j,u;if(s.startContainer==s.endContainer){return s._traverseSameContainer(r)}for(q=s.endContainer,k=q.parentNode;k!=null;q=k,k=k.parentNode){if(k==s.startContainer){return s._traverseCommonStartContainer(q,r)}++m}for(q=s.startContainer,k=q.parentNode;k!=null;q=k,k=k.parentNode){if(k==s.endContainer){return s._traverseCommonEndContainer(q,r)}++v}o=v-m;l=s.startContainer;while(o>0){l=l.parentNode;o--}n=s.endContainer;while(o<0){n=n.parentNode;o++}for(j=l.parentNode,u=n.parentNode;j!=u;j=j.parentNode,u=u.parentNode){l=j;n=u}return s._traverseCommonAncestors(l,n,r)},_traverseSameContainer:function(o){var r=this,q,u,j,k,l,p,m;if(o!=e){q=r.dom.doc.createDocumentFragment()}if(r.startOffset==r.endOffset){return q}if(r.startContainer.nodeType==3){u=r.startContainer.nodeValue;j=u.substring(r.startOffset,r.endOffset);if(o!=c){r.startContainer.deleteData(r.startOffset,r.endOffset-r.startOffset);r.collapse(true)}if(o==e){return null}q.appendChild(r.dom.doc.createTextNode(j));return q}k=i(r.startContainer,r.startOffset);l=r.endOffset-r.startOffset;while(l>0){p=k.nextSibling;m=r._traverseFullySelected(k,o);if(q){q.appendChild(m)}--l;k=p}if(o!=c){r.collapse(true)}return q},_traverseCommonStartContainer:function(j,p){var s=this,r,k,l,m,q,o;if(p!=e){r=s.dom.doc.createDocumentFragment()}k=s._traverseRightBoundary(j,p);if(r){r.appendChild(k)}l=g(j,s.startContainer);m=l-s.startOffset;if(m<=0){if(p!=c){s.setEndBefore(j);s.collapse(false)}return r}k=j.previousSibling;while(m>0){q=k.previousSibling;o=s._traverseFullySelected(k,p);if(r){r.insertBefore(o,r.firstChild)}--m;k=q}if(p!=c){s.setEndBefore(j);s.collapse(false)}return r},_traverseCommonEndContainer:function(m,p){var s=this,r,o,j,k,q,l;if(p!=e){r=s.dom.doc.createDocumentFragment()}j=s._traverseLeftBoundary(m,p);if(r){r.appendChild(j)}o=g(m,s.endContainer);++o;k=s.endOffset-o;j=m.nextSibling;while(k>0){q=j.nextSibling;l=s._traverseFullySelected(j,p);if(r){r.appendChild(l)}--k;j=q}if(p!=c){s.setStartAfter(m);s.collapse(true)}return r},_traverseCommonAncestors:function(p,j,s){var w=this,l,v,o,q,r,k,u,m;if(s!=e){v=w.dom.doc.createDocumentFragment()}l=w._traverseLeftBoundary(p,s);if(v){v.appendChild(l)}o=p.parentNode;q=g(p,o);r=g(j,o);++q;k=r-q;u=p.nextSibling;while(k>0){m=u.nextSibling;l=w._traverseFullySelected(u,s);if(v){v.appendChild(l)}u=m;--k}l=w._traverseRightBoundary(j,s);if(v){v.appendChild(l)}if(s!=c){w.setStartAfter(p);w.collapse(true)}return v},_traverseRightBoundary:function(p,q){var s=this,l=i(s.endContainer,s.endOffset-1),r,o,n,j,k;var m=l!=s.endContainer;if(l==p){return s._traverseNode(l,m,false,q)}r=l.parentNode;o=s._traverseNode(r,false,false,q);while(r!=null){while(l!=null){n=l.previousSibling;j=s._traverseNode(l,m,false,q);if(q!=e){o.insertBefore(j,o.firstChild)}m=true;l=n}if(r==p){return o}l=r.previousSibling;r=r.parentNode;k=s._traverseNode(r,false,false,q);if(q!=e){k.appendChild(o)}o=k}return null},_traverseLeftBoundary:function(p,q){var s=this,m=i(s.startContainer,s.startOffset);var n=m!=s.startContainer,r,o,l,j,k;if(m==p){return s._traverseNode(m,n,true,q)}r=m.parentNode;o=s._traverseNode(r,false,true,q);while(r!=null){while(m!=null){l=m.nextSibling;j=s._traverseNode(m,n,true,q);if(q!=e){o.appendChild(j)}n=true;m=l}if(r==p){return o}m=r.nextSibling;r=r.parentNode;k=s._traverseNode(r,false,true,q);if(q!=e){k.appendChild(o)}o=k}return null},_traverseNode:function(j,o,r,s){var u=this,m,l,p,k,q;if(o){return u._traverseFullySelected(j,s)}if(j.nodeType==3){m=j.nodeValue;if(r){k=u.startOffset;l=m.substring(k);p=m.substring(0,k)}else{k=u.endOffset;l=m.substring(0,k);p=m.substring(k)}if(s!=c){j.nodeValue=p}if(s==e){return null}q=j.cloneNode(false);q.nodeValue=l;return q}if(s==e){return null}return j.cloneNode(false)},_traverseFullySelected:function(l,k){var j=this;if(k!=e){return k==c?l.cloneNode(true):l}l.parentNode.removeChild(l);return null}});f.Range=a})(tinymce.dom);(function(){function a(e){var d=this,h="\uFEFF",b,g;function c(j,i){if(j&&i){if(j.item&&i.item&&j.item(0)===i.item(0)){return 1}if(j.isEqual&&i.isEqual&&i.isEqual(j)){return 1}}return 0}function f(){var m=e.dom,j=e.getRng(),s=m.createRng(),p,k,n,q,o,l;function i(v){var t=v.parentNode.childNodes,u;for(u=t.length-1;u>=0;u--){if(t[u]==v){return u}}return -1}function r(v){var t=j.duplicate(),B,y,u,w,x=0,z=0,A,C;t.collapse(v);B=t.parentElement();t.pasteHTML(h);u=B.childNodes;for(y=0;y0&&(w.nodeType!==3||u[y-1].nodeType!==3)){z++}if(w.nodeType===3){A=w.nodeValue.indexOf(h);if(A!==-1){x+=A;break}x+=w.nodeValue.length}else{x=0}}t.moveStart("character",-1);t.text="";return{index:z,offset:x,parent:B}}n=j.item?j.item(0):j.parentElement();if(n.ownerDocument!=m.doc){return s}if(j.item||!n.hasChildNodes()){s.setStart(n.parentNode,i(n));s.setEnd(s.startContainer,s.startOffset+1);return s}l=e.isCollapsed();p=r(true);k=r(false);p.parent.normalize();k.parent.normalize();q=p.parent.childNodes[Math.min(p.index,p.parent.childNodes.length-1)];if(q.nodeType!=3){s.setStart(p.parent,p.index)}else{s.setStart(p.parent.childNodes[p.index],p.offset)}o=k.parent.childNodes[Math.min(k.index,k.parent.childNodes.length-1)];if(o.nodeType!=3){if(!l){k.index++}s.setEnd(k.parent,k.index)}else{s.setEnd(k.parent.childNodes[k.index],k.offset)}if(!l){q=s.startContainer;if(q.nodeType==1){s.setStart(q,Math.min(s.startOffset,q.childNodes.length))}o=s.endContainer;if(o.nodeType==1){s.setEnd(o,Math.min(s.endOffset,o.childNodes.length))}}d.addRange(s);return s}this.addRange=function(j){var o,m=e.dom.doc.body,p,k,q,l,n,i;q=j.startContainer;l=j.startOffset;n=j.endContainer;i=j.endOffset;o=m.createTextRange();q=q.nodeType==1?q.childNodes[Math.min(l,q.childNodes.length-1)]:q;n=n.nodeType==1?n.childNodes[Math.min(l==i?i:i-1,n.childNodes.length-1)]:n;if(q==n&&q.nodeType==1){if(/^(IMG|TABLE)$/.test(q.nodeName)&&l!=i){o=m.createControlRange();o.addElement(q)}else{o=m.createTextRange();if(!q.hasChildNodes()&&q.canHaveHTML){q.innerHTML=h}o.moveToElementText(q);if(q.innerHTML==h){o.collapse(true);q.removeChild(q.firstChild)}}if(l==i){o.collapse(i<=j.endContainer.childNodes.length-1)}o.select();return}function r(t,v){var u,s,w;if(t.nodeType!=3){return -1}u=t.nodeValue;s=m.createTextRange();t.nodeValue=u.substring(0,v)+h+u.substring(v);s.moveToElementText(t.parentNode);s.findText(h);w=Math.abs(s.moveStart("character",-1048575));t.nodeValue=u;return w}if(j.collapsed){pos=r(q,l);o=m.createTextRange();o.move("character",pos);o.select();return}else{if(q==n&&q.nodeType==3){p=r(q,l);o.move("character",p);o.moveEnd("character",i-l);o.select();return}p=r(q,l);k=r(n,i);o=m.createTextRange();if(p==-1){o.moveToElementText(q);p=0}else{o.move("character",p)}tmpRng=m.createTextRange();if(k==-1){tmpRng.moveToElementText(n)}else{tmpRng.move("character",k)}o.setEndPoint("EndToEnd",tmpRng);o.select();return}};this.getRangeAt=function(){if(!b||!c(g,e.getRng())){b=f();g=e.getRng()}return b};this.destroy=function(){g=b=null}}tinymce.dom.TridentSelection=a})();(function(){var p=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,i=0,d=Object.prototype.toString,n=false;var b=function(D,t,A,v){A=A||[];var e=t=t||document;if(t.nodeType!==1&&t.nodeType!==9){return[]}if(!D||typeof D!=="string"){return A}var B=[],C,y,G,F,z,s,r=true,w=o(t);p.lastIndex=0;while((C=p.exec(D))!==null){B.push(C[1]);if(C[2]){s=RegExp.rightContext;break}}if(B.length>1&&j.exec(D)){if(B.length===2&&f.relative[B[0]]){y=g(B[0]+B[1],t)}else{y=f.relative[B[0]]?[t]:b(B.shift(),t);while(B.length){D=B.shift();if(f.relative[D]){D+=B.shift()}y=g(D,y)}}}else{if(!v&&B.length>1&&t.nodeType===9&&!w&&f.match.ID.test(B[0])&&!f.match.ID.test(B[B.length-1])){var H=b.find(B.shift(),t,w);t=H.expr?b.filter(H.expr,H.set)[0]:H.set[0]}if(t){var H=v?{expr:B.pop(),set:a(v)}:b.find(B.pop(),B.length===1&&(B[0]==="~"||B[0]==="+")&&t.parentNode?t.parentNode:t,w);y=H.expr?b.filter(H.expr,H.set):H.set;if(B.length>0){G=a(y)}else{r=false}while(B.length){var u=B.pop(),x=u;if(!f.relative[u]){u=""}else{x=B.pop()}if(x==null){x=t}f.relative[u](G,x,w)}}else{G=B=[]}}if(!G){G=y}if(!G){throw"Syntax error, unrecognized expression: "+(u||D)}if(d.call(G)==="[object Array]"){if(!r){A.push.apply(A,G)}else{if(t&&t.nodeType===1){for(var E=0;G[E]!=null;E++){if(G[E]&&(G[E]===true||G[E].nodeType===1&&h(t,G[E]))){A.push(y[E])}}}else{for(var E=0;G[E]!=null;E++){if(G[E]&&G[E].nodeType===1){A.push(y[E])}}}}}else{a(G,A)}if(s){b(s,e,A,v);b.uniqueSort(A)}return A};b.uniqueSort=function(r){if(c){n=false;r.sort(c);if(n){for(var e=1;e":function(w,r,x){var u=typeof r==="string";if(u&&!/\W/.test(r)){r=x?r:r.toUpperCase();for(var s=0,e=w.length;s=0)){if(!s){e.push(v)}}else{if(s){r[u]=false}}}}return false},ID:function(e){return e[1].replace(/\\/g,"")},TAG:function(r,e){for(var s=0;e[s]===false;s++){}return e[s]&&o(e[s])?r[1]:r[1].toUpperCase()},CHILD:function(e){if(e[1]=="nth"){var r=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(e[2]=="even"&&"2n"||e[2]=="odd"&&"2n+1"||!/\D/.test(e[2])&&"0n+"+e[2]||e[2]);e[2]=(r[1]+(r[2]||1))-0;e[3]=r[3]-0}e[0]=i++;return e},ATTR:function(u,r,s,e,v,w){var t=u[1].replace(/\\/g,"");if(!w&&f.attrMap[t]){u[1]=f.attrMap[t]}if(u[2]==="~="){u[4]=" "+u[4]+" "}return u},PSEUDO:function(u,r,s,e,v){if(u[1]==="not"){if(u[3].match(p).length>1||/^\w/.test(u[3])){u[3]=b(u[3],null,null,r)}else{var t=b.filter(u[3],r,s,true^v);if(!s){e.push.apply(e,t)}return false}}else{if(f.match.POS.test(u[0])||f.match.CHILD.test(u[0])){return true}}return u},POS:function(e){e.unshift(true);return e}},filters:{enabled:function(e){return e.disabled===false&&e.type!=="hidden"},disabled:function(e){return e.disabled===true},checked:function(e){return e.checked===true},selected:function(e){e.parentNode.selectedIndex;return e.selected===true},parent:function(e){return !!e.firstChild},empty:function(e){return !e.firstChild},has:function(s,r,e){return !!b(e[3],s).length},header:function(e){return/h\d/i.test(e.nodeName)},text:function(e){return"text"===e.type},radio:function(e){return"radio"===e.type},checkbox:function(e){return"checkbox"===e.type},file:function(e){return"file"===e.type},password:function(e){return"password"===e.type},submit:function(e){return"submit"===e.type},image:function(e){return"image"===e.type},reset:function(e){return"reset"===e.type},button:function(e){return"button"===e.type||e.nodeName.toUpperCase()==="BUTTON"},input:function(e){return/input|select|textarea|button/i.test(e.nodeName)}},setFilters:{first:function(r,e){return e===0},last:function(s,r,e,t){return r===t.length-1},even:function(r,e){return e%2===0},odd:function(r,e){return e%2===1},lt:function(s,r,e){return re[3]-0},nth:function(s,r,e){return e[3]-0==r},eq:function(s,r,e){return e[3]-0==r}},filter:{PSEUDO:function(w,s,t,x){var r=s[1],u=f.filters[r];if(u){return u(w,t,s,x)}else{if(r==="contains"){return(w.textContent||w.innerText||"").indexOf(s[3])>=0}else{if(r==="not"){var v=s[3];for(var t=0,e=v.length;t=0)}}},ID:function(r,e){return r.nodeType===1&&r.getAttribute("id")===e},TAG:function(r,e){return(e==="*"&&r.nodeType===1)||r.nodeName===e},CLASS:function(r,e){return(" "+(r.className||r.getAttribute("class"))+" ").indexOf(e)>-1},ATTR:function(v,t){var s=t[1],e=f.attrHandle[s]?f.attrHandle[s](v):v[s]!=null?v[s]:v.getAttribute(s),w=e+"",u=t[2],r=t[4];return e==null?u==="!=":u==="="?w===r:u==="*="?w.indexOf(r)>=0:u==="~="?(" "+w+" ").indexOf(r)>=0:!r?w&&e!==false:u==="!="?w!=r:u==="^="?w.indexOf(r)===0:u==="$="?w.substr(w.length-r.length)===r:u==="|="?w===r||w.substr(0,r.length+1)===r+"-":false},POS:function(u,r,s,v){var e=r[2],t=f.setFilters[e];if(t){return t(u,s,r,v)}}}};var j=f.match.POS;for(var l in f.match){f.match[l]=new RegExp(f.match[l].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var a=function(r,e){r=Array.prototype.slice.call(r);if(e){e.push.apply(e,r);return e}return r};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(k){a=function(u,t){var r=t||[];if(d.call(u)==="[object Array]"){Array.prototype.push.apply(r,u)}else{if(typeof u.length==="number"){for(var s=0,e=u.length;s";var e=document.documentElement;e.insertBefore(r,e.firstChild);if(!!document.getElementById(s)){f.find.ID=function(u,v,w){if(typeof v.getElementById!=="undefined"&&!w){var t=v.getElementById(u[1]);return t?t.id===u[1]||typeof t.getAttributeNode!=="undefined"&&t.getAttributeNode("id").nodeValue===u[1]?[t]:undefined:[]}};f.filter.ID=function(v,t){var u=typeof v.getAttributeNode!=="undefined"&&v.getAttributeNode("id");return v.nodeType===1&&u&&u.nodeValue===t}}e.removeChild(r)})();(function(){var e=document.createElement("div");e.appendChild(document.createComment(""));if(e.getElementsByTagName("*").length>0){f.find.TAG=function(r,v){var u=v.getElementsByTagName(r[1]);if(r[1]==="*"){var t=[];for(var s=0;u[s];s++){if(u[s].nodeType===1){t.push(u[s])}}u=t}return u}}e.innerHTML="";if(e.firstChild&&typeof e.firstChild.getAttribute!=="undefined"&&e.firstChild.getAttribute("href")!=="#"){f.attrHandle.href=function(r){return r.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var e=b,s=document.createElement("div");s.innerHTML="

    ";if(s.querySelectorAll&&s.querySelectorAll(".TEST").length===0){return}b=function(w,v,t,u){v=v||document;if(!u&&v.nodeType===9&&!o(v)){try{return a(v.querySelectorAll(w),t)}catch(x){}}return e(w,v,t,u)};for(var r in e){b[r]=e[r]}})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var e=document.createElement("div");e.innerHTML="
    ";if(e.getElementsByClassName("e").length===0){return}e.lastChild.className="e";if(e.getElementsByClassName("e").length===1){return}f.order.splice(1,0,"CLASS");f.find.CLASS=function(r,s,t){if(typeof s.getElementsByClassName!=="undefined"&&!t){return s.getElementsByClassName(r[1])}}})()}function m(r,w,v,A,x,z){var y=r=="previousSibling"&&!z;for(var t=0,s=A.length;t0){u=e;break}}}e=e[r]}A[t]=u}}}var h=document.compareDocumentPosition?function(r,e){return r.compareDocumentPosition(e)&16}:function(r,e){return r!==e&&(r.contains?r.contains(e):true)};var o=function(e){return e.nodeType===9&&e.documentElement.nodeName!=="HTML"||!!e.ownerDocument&&e.ownerDocument.documentElement.nodeName!=="HTML"};var g=function(e,x){var t=[],u="",v,s=x.nodeType?[x]:x;while((v=f.match.PSEUDO.exec(e))){u+=v[0];e=e.replace(f.match.PSEUDO,"")}e=f.relative[e]?e+"*":e;for(var w=0,r=s.length;w=0;h--){k=g[h];if(k.obj===l){j._remove(k.obj,k.name,k.cfunc);k.obj=k.cfunc=null;g.splice(h,1)}}}},cancel:function(g){if(!g){return false}this.stop(g);return this.prevent(g)},stop:function(g){if(g.stopPropagation){g.stopPropagation()}else{g.cancelBubble=true}return false},prevent:function(g){if(g.preventDefault){g.preventDefault()}else{g.returnValue=false}return false},destroy:function(){var g=this;f(g.events,function(j,h){g._remove(j.obj,j.name,j.cfunc);j.obj=j.cfunc=null});g.events=[];g=null},_add:function(h,i,g){if(h.attachEvent){h.attachEvent("on"+i,g)}else{if(h.addEventListener){h.addEventListener(i,g,false)}else{h["on"+i]=g}}},_remove:function(i,j,h){if(i){try{if(i.detachEvent){i.detachEvent("on"+j,h)}else{if(i.removeEventListener){i.removeEventListener(j,h,false)}else{i["on"+j]=null}}}catch(g){}}},_pageInit:function(h){var g=this;if(g.domLoaded){return}g.domLoaded=true;f(g.inits,function(i){i()});g.inits=[]},_wait:function(i){var g=this,h=i.document;if(i.tinyMCE_GZ&&tinyMCE_GZ.loaded){g.domLoaded=1;return}if(h.attachEvent){h.attachEvent("onreadystatechange",function(){if(h.readyState==="complete"){h.detachEvent("onreadystatechange",arguments.callee);g._pageInit(i)}});if(h.documentElement.doScroll&&i==i.top){(function(){if(g.domLoaded){return}try{h.documentElement.doScroll("left")}catch(j){setTimeout(arguments.callee,0);return}g._pageInit(i)})()}}else{if(h.addEventListener){g._add(i,"DOMContentLoaded",function(){g._pageInit(i)})}}g._add(i,"load",function(){g._pageInit(i)})}});a=d.dom.Event=new d.dom.EventUtils();a._wait(window);d.addUnload(function(){a.destroy()})})(tinymce);(function(a){var b=a.each;a.create("tinymce.dom.Element",{Element:function(g,e){var c=this,f,d;e=e||{};c.id=g;c.dom=f=e.dom||a.DOM;c.settings=e;if(!a.isIE){d=c.dom.get(c.id)}b(["getPos","getRect","getParent","add","setStyle","getStyle","setStyles","setAttrib","setAttribs","getAttrib","addClass","removeClass","hasClass","getOuterHTML","setOuterHTML","remove","show","hide","isHidden","setHTML","get"],function(h){c[h]=function(){var j=[g],k;for(k=0;k_';j.deleteContents();j.insertNode(f.getRng().createContextualFragment(i));l=f.dom.get("__caret");j=k.createRange();j.setStartBefore(l);j.setEndAfter(l);f.setRng(j);f.dom.remove("__caret")}else{if(j.item){k.execCommand("Delete",false,null);j=f.getRng()}j.pasteHTML(i)}f.onSetContent.dispatch(f,g)},getStart:function(){var f=this,g=f.getRng(),h;if(a){if(g.item){return g.item(0)}g=g.duplicate();g.collapse(1);h=g.parentElement();if(h&&h.nodeName=="BODY"){return h.firstChild}return h}else{h=g.startContainer;if(h.nodeName=="BODY"){return h.firstChild}return f.dom.getParent(h,"*")}},getEnd:function(){var f=this,g=f.getRng(),h;if(a){if(g.item){return g.item(0)}g=g.duplicate();g.collapse(0);h=g.parentElement();if(h&&h.nodeName=="BODY"){return h.lastChild}return h}else{h=g.endContainer;if(h.nodeName=="BODY"){return h.lastChild}return f.dom.getParent(h,"*")}},getBookmark:function(x){var j=this,m=j.getRng(),f,n,l,u=j.dom.getViewPort(j.win),v,p,z,o,w=-16777215,k,h=j.dom.getRoot(),g=0,i=0,y;n=u.x;l=u.y;if(x=="simple"){return{rng:m,scrollX:n,scrollY:l}}if(a){if(m.item){v=m.item(0);d(j.dom.select(v.nodeName),function(s,r){if(v==s){p=r;return false}});return{tag:v.nodeName,index:p,scrollX:n,scrollY:l}}f=j.dom.doc.body.createTextRange();f.moveToElementText(h);f.collapse(true);z=Math.abs(f.move("character",w));f=m.duplicate();f.collapse(true);p=Math.abs(f.move("character",w));f=m.duplicate();f.collapse(false);o=Math.abs(f.move("character",w))-p;return{start:p-z,length:o,scrollX:n,scrollY:l}}v=j.getNode();k=j.getSel();if(!k){return null}if(v&&v.nodeName=="IMG"){return{scrollX:n,scrollY:l}}function q(A,D,t){var s=j.dom.doc.createTreeWalker(A,NodeFilter.SHOW_TEXT,null,false),E,B=0,C={};while((E=s.nextNode())!=null){if(E==D){C.start=B}if(E==t){C.end=B;return C}B+=e(E.nodeValue||"").length}return null}if(k.anchorNode==k.focusNode&&k.anchorOffset==k.focusOffset){v=q(h,k.anchorNode,k.focusNode);if(!v){return{scrollX:n,scrollY:l}}e(k.anchorNode.nodeValue||"").replace(/^\s+/,function(r){g=r.length});return{start:Math.max(v.start+k.anchorOffset-g,0),end:Math.max(v.end+k.focusOffset-g,0),scrollX:n,scrollY:l,beg:k.anchorOffset-g==0}}else{v=q(h,m.startContainer,m.endContainer);if(!v){return{scrollX:n,scrollY:l}}return{start:Math.max(v.start+m.startOffset-g,0),end:Math.max(v.end+m.endOffset-i,0),scrollX:n,scrollY:l,beg:m.startOffset-g==0}}},moveToBookmark:function(n){var o=this,g=o.getRng(),p=o.getSel(),j=o.dom.getRoot(),m,h,k;function i(q,t,D){var B=o.dom.doc.createTreeWalker(q,NodeFilter.SHOW_TEXT,null,false),x,s=0,A={},u,C,z,y;while((x=B.nextNode())!=null){z=y=0;k=x.nodeValue||"";h=e(k).length;s+=h;if(s>=t&&!A.startNode){u=t-(s-h);if(n.beg&&u>=h){continue}A.startNode=x;A.startOffset=u+y}if(s>=D){A.endNode=x;A.endOffset=D-(s-h)+y;return A}}return null}if(!n){return false}o.win.scrollTo(n.scrollX,n.scrollY);if(a){if(g=n.rng){try{g.select()}catch(l){}return true}o.win.focus();if(n.tag){g=j.createControlRange();d(o.dom.select(n.tag),function(r,q){if(q==n.index){g.addElement(r)}})}else{try{if(n.start<0){return true}g=p.createRange();g.moveToElementText(j);g.collapse(true);g.moveStart("character",n.start);g.moveEnd("character",n.length)}catch(f){return true}}try{g.select()}catch(l){}return true}if(!p){return false}if(n.rng){p.removeAllRanges();p.addRange(n.rng)}else{if(b(n.start)&&b(n.end)){try{m=i(j,n.start,n.end);if(m){g=o.dom.doc.createRange();g.setStart(m.startNode,m.startOffset);g.setEnd(m.endNode,m.endOffset);p.removeAllRanges();p.addRange(g)}if(!c.isOpera){o.win.focus()}}catch(l){}}}},select:function(g,l){var p=this,f=p.getRng(),q=p.getSel(),o,m,k,j=p.win.document;function h(u,t){var s,r;if(u){s=j.createTreeWalker(u,NodeFilter.SHOW_TEXT,null,false);while(u=s.nextNode()){r=u;if(c.trim(u.nodeValue).length!=0){if(t){return u}else{r=u}}}}return r}if(a){try{o=j.body;if(/^(IMG|TABLE)$/.test(g.nodeName)){f=o.createControlRange();f.addElement(g)}else{f=o.createTextRange();f.moveToElementText(g)}f.select()}catch(i){}}else{if(l){m=h(g,1)||p.dom.select("br:first",g)[0];k=h(g,0)||p.dom.select("br:last",g)[0];if(m&&k){f=j.createRange();if(m.nodeName=="BR"){f.setStartBefore(m)}else{f.setStart(m,0)}if(k.nodeName=="BR"){f.setEndBefore(k)}else{f.setEnd(k,k.nodeValue.length)}}else{f.selectNode(g)}}else{f.selectNode(g)}p.setRng(f)}return g},isCollapsed:function(){var f=this,h=f.getRng(),g=f.getSel();if(!h||h.item){return false}return !g||h.boundingWidth==0||h.collapsed},collapse:function(f){var g=this,h=g.getRng(),i;if(h.item){i=h.item(0);h=this.win.document.body.createTextRange();h.moveToElementText(i)}h.collapse(!!f);g.setRng(h)},getSel:function(){var g=this,f=this.win;return f.getSelection?f.getSelection():f.document.selection},getRng:function(j){var g=this,h,i;if(j&&g.tridentSel){return g.tridentSel.getRangeAt(0)}try{if(h=g.getSel()){i=h.rangeCount>0?h.getRangeAt(0):(h.createRange?h.createRange():g.win.document.createRange())}}catch(f){}if(!i){i=a?g.win.document.body.createTextRange():g.win.document.createRange()}return i},setRng:function(i){var h,g=this;if(!g.tridentSel){h=g.getSel();if(h){h.removeAllRanges();h.addRange(i)}}else{if(i.cloneRange){g.tridentSel.addRange(i);return}try{i.select()}catch(f){}}},setNode:function(g){var f=this;f.setContent(f.dom.getOuterHTML(g));return g},getNode:function(){var f=this,h=f.getRng(),g=f.getSel(),i;if(!a){if(!h){return f.dom.getRoot()}i=h.commonAncestorContainer;if(!h.collapsed){if(c.isWebKit&&g.anchorNode&&g.anchorNode.nodeType==1){return g.anchorNode.childNodes[g.anchorOffset]}if(h.startContainer==h.endContainer){if(h.startOffset-h.endOffset<2){if(h.startContainer.hasChildNodes()){i=h.startContainer.childNodes[h.startOffset]}}}}return f.dom.getParent(i,"*")}return h.item?h.item(0):h.parentElement()},getSelectedBlocks:function(g,f){var i=this,j=i.dom,m,h,l,k=[];m=j.getParent(g||i.getStart(),j.isBlock);h=j.getParent(f||i.getEnd(),j.isBlock);if(m){k.push(m)}if(m&&h&&m!=h){l=m;while((l=l.nextSibling)&&l!=h){if(j.isBlock(l)){k.push(l)}}}if(h&&m!=h){k.push(h)}return k},destroy:function(g){var f=this;f.win=null;if(f.tridentSel){f.tridentSel.destroy()}if(!g){c.removeUnload(f.destroy)}}})})(tinymce);(function(a){a.create("tinymce.dom.XMLWriter",{node:null,XMLWriter:function(c){function b(){var e=document.implementation;if(!e||!e.createDocument){try{return new ActiveXObject("MSXML2.DOMDocument")}catch(d){}try{return new ActiveXObject("Microsoft.XmlDom")}catch(d){}}else{return e.createDocument("","",null)}}this.doc=b();this.valid=a.isOpera||a.isWebKit;this.reset()},reset:function(){var b=this,c=b.doc;if(c.firstChild){c.removeChild(c.firstChild)}b.node=c.appendChild(c.createElement("html"))},writeStartElement:function(c){var b=this;b.node=b.node.appendChild(b.doc.createElement(c))},writeAttribute:function(c,b){if(this.valid){b=b.replace(/>/g,"%MCGT%")}this.node.setAttribute(c,b)},writeEndElement:function(){this.node=this.node.parentNode},writeFullEndElement:function(){var b=this,c=b.node;c.appendChild(b.doc.createTextNode(""));b.node=c.parentNode},writeText:function(b){if(this.valid){b=b.replace(/>/g,"%MCGT%")}this.node.appendChild(this.doc.createTextNode(b))},writeCDATA:function(b){this.node.appendChild(this.doc.createCDATASection(b))},writeComment:function(b){if(a.isIE){b=b.replace(/^\-|\-$/g," ")}this.node.appendChild(this.doc.createComment(b.replace(/\-\-/g," ")))},getContent:function(){var b;b=this.doc.xml||new XMLSerializer().serializeToString(this.doc);b=b.replace(/<\?[^?]+\?>||<\/html>||]+>/g,"");b=b.replace(/ ?\/>/g," />");if(this.valid){b=b.replace(/\%MCGT%/g,">")}return b}})})(tinymce);(function(a){a.create("tinymce.dom.StringWriter",{str:null,tags:null,count:0,settings:null,indent:null,StringWriter:function(b){this.settings=a.extend({indent_char:" ",indentation:0},b);this.reset()},reset:function(){this.indent="";this.str="";this.tags=[];this.count=0},writeStartElement:function(b){this._writeAttributesEnd();this.writeRaw("<"+b);this.tags.push(b);this.inAttr=true;this.count++;this.elementCount=this.count},writeAttribute:function(d,b){var c=this;c.writeRaw(" "+c.encode(d)+'="'+c.encode(b)+'"')},writeEndElement:function(){var b;if(this.tags.length>0){b=this.tags.pop();if(this._writeAttributesEnd(1)){this.writeRaw("")}if(this.settings.indentation>0){this.writeRaw("\n")}}},writeFullEndElement:function(){if(this.tags.length>0){this._writeAttributesEnd();this.writeRaw("");if(this.settings.indentation>0){this.writeRaw("\n")}}},writeText:function(b){this._writeAttributesEnd();this.writeRaw(this.encode(b));this.count++},writeCDATA:function(b){this._writeAttributesEnd();this.writeRaw("");this.count++},writeComment:function(b){this._writeAttributesEnd();this.writeRaw("");this.count++},writeRaw:function(b){this.str+=b},encode:function(b){return b.replace(/[<>&"]/g,function(c){switch(c){case"<":return"<";case">":return">";case"&":return"&";case'"':return"""}return c})},getContent:function(){return this.str},_writeAttributesEnd:function(b){if(!this.inAttr){return}this.inAttr=false;if(b&&this.elementCount==this.count){this.writeRaw(" />");return false}this.writeRaw(">");return true}})})(tinymce);(function(e){var g=e.extend,f=e.each,b=e.util.Dispatcher,d=e.isIE,a=e.isGecko;function c(h){return h.replace(/([?+*])/g,".$1")}e.create("tinymce.dom.Serializer",{Serializer:function(j){var i=this;i.key=0;i.onPreProcess=new b(i);i.onPostProcess=new b(i);try{i.writer=new e.dom.XMLWriter()}catch(h){i.writer=new e.dom.StringWriter()}i.settings=j=g({dom:e.DOM,valid_nodes:0,node_filter:0,attr_filter:0,invalid_attrs:/^(mce_|_moz_)/,closed:/^(br|hr|input|meta|img|link|param|area)$/,entity_encoding:"named",entities:"160,nbsp,161,iexcl,162,cent,163,pound,164,curren,165,yen,166,brvbar,167,sect,168,uml,169,copy,170,ordf,171,laquo,172,not,173,shy,174,reg,175,macr,176,deg,177,plusmn,178,sup2,179,sup3,180,acute,181,micro,182,para,183,middot,184,cedil,185,sup1,186,ordm,187,raquo,188,frac14,189,frac12,190,frac34,191,iquest,192,Agrave,193,Aacute,194,Acirc,195,Atilde,196,Auml,197,Aring,198,AElig,199,Ccedil,200,Egrave,201,Eacute,202,Ecirc,203,Euml,204,Igrave,205,Iacute,206,Icirc,207,Iuml,208,ETH,209,Ntilde,210,Ograve,211,Oacute,212,Ocirc,213,Otilde,214,Ouml,215,times,216,Oslash,217,Ugrave,218,Uacute,219,Ucirc,220,Uuml,221,Yacute,222,THORN,223,szlig,224,agrave,225,aacute,226,acirc,227,atilde,228,auml,229,aring,230,aelig,231,ccedil,232,egrave,233,eacute,234,ecirc,235,euml,236,igrave,237,iacute,238,icirc,239,iuml,240,eth,241,ntilde,242,ograve,243,oacute,244,ocirc,245,otilde,246,ouml,247,divide,248,oslash,249,ugrave,250,uacute,251,ucirc,252,uuml,253,yacute,254,thorn,255,yuml,402,fnof,913,Alpha,914,Beta,915,Gamma,916,Delta,917,Epsilon,918,Zeta,919,Eta,920,Theta,921,Iota,922,Kappa,923,Lambda,924,Mu,925,Nu,926,Xi,927,Omicron,928,Pi,929,Rho,931,Sigma,932,Tau,933,Upsilon,934,Phi,935,Chi,936,Psi,937,Omega,945,alpha,946,beta,947,gamma,948,delta,949,epsilon,950,zeta,951,eta,952,theta,953,iota,954,kappa,955,lambda,956,mu,957,nu,958,xi,959,omicron,960,pi,961,rho,962,sigmaf,963,sigma,964,tau,965,upsilon,966,phi,967,chi,968,psi,969,omega,977,thetasym,978,upsih,982,piv,8226,bull,8230,hellip,8242,prime,8243,Prime,8254,oline,8260,frasl,8472,weierp,8465,image,8476,real,8482,trade,8501,alefsym,8592,larr,8593,uarr,8594,rarr,8595,darr,8596,harr,8629,crarr,8656,lArr,8657,uArr,8658,rArr,8659,dArr,8660,hArr,8704,forall,8706,part,8707,exist,8709,empty,8711,nabla,8712,isin,8713,notin,8715,ni,8719,prod,8721,sum,8722,minus,8727,lowast,8730,radic,8733,prop,8734,infin,8736,ang,8743,and,8744,or,8745,cap,8746,cup,8747,int,8756,there4,8764,sim,8773,cong,8776,asymp,8800,ne,8801,equiv,8804,le,8805,ge,8834,sub,8835,sup,8836,nsub,8838,sube,8839,supe,8853,oplus,8855,otimes,8869,perp,8901,sdot,8968,lceil,8969,rceil,8970,lfloor,8971,rfloor,9001,lang,9002,rang,9674,loz,9824,spades,9827,clubs,9829,hearts,9830,diams,338,OElig,339,oelig,352,Scaron,353,scaron,376,Yuml,710,circ,732,tilde,8194,ensp,8195,emsp,8201,thinsp,8204,zwnj,8205,zwj,8206,lrm,8207,rlm,8211,ndash,8212,mdash,8216,lsquo,8217,rsquo,8218,sbquo,8220,ldquo,8221,rdquo,8222,bdquo,8224,dagger,8225,Dagger,8240,permil,8249,lsaquo,8250,rsaquo,8364,euro",bool_attrs:/(checked|disabled|readonly|selected|nowrap)/,valid_elements:"*[*]",extended_valid_elements:0,valid_child_elements:0,invalid_elements:0,fix_table_elements:1,fix_list_elements:true,fix_content_duplication:true,convert_fonts_to_spans:false,font_size_classes:0,font_size_style_values:0,apply_source_formatting:0,indent_mode:"simple",indent_char:"\t",indent_levels:1,remove_linebreaks:1,remove_redundant_brs:1,element_format:"xhtml"},j);i.dom=j.dom;if(j.remove_redundant_brs){i.onPostProcess.add(function(k,l){l.content=l.content.replace(/(
    \s*)+<\/(p|h[1-6]|div|li)>/gi,function(n,m,o){if(/^
    \s*<\//.test(n)){return""}return n})})}if(j.element_format=="html"){i.onPostProcess.add(function(k,l){l.content=l.content.replace(/<([^>]+) \/>/g,"<$1>")})}if(j.fix_list_elements){i.onPreProcess.add(function(v,s){var l,y,w=["ol","ul"],u,t,q,k=/^(OL|UL)$/,z;function m(r,x){var o=x.split(","),p;while((r=r.previousSibling)!=null){for(p=0;p1){f(q[1].split("|"),function(u){var p={},t;k=k||[];u=u.replace(/::/g,"~");u=/^([!\-])?([\w*.?~_\-]+|)([=:<])?(.+)?$/.exec(u);u[2]=u[2].replace(/~/g,":");if(u[1]=="!"){r=r||[];r.push(u[2])}if(u[1]=="-"){for(t=0;t]*>)(.*?)(<\/script>)/g},{pattern:/(]*>)(.*?)(<\/style>)/g},{pattern:/(]*>)(.*?)(<\/pre>)/g,encode:1},{pattern:/()/g}]});j=l.content;if(k.entity_encoding!=="raw"){j=i._encode(j)}if(!n.set){j=j.replace(/

    \s+<\/p>|]+)>\s+<\/p>/g,k.entity_encoding=="numeric"?" 

    ":" 

    ");if(k.remove_linebreaks){j=j.replace(/\r?\n|\r/g," ");j=j.replace(/(<[^>]+>)\s+/g,"$1 ");j=j.replace(/\s+(<\/[^>]+>)/g," $1");j=j.replace(/<(p|h[1-6]|blockquote|hr|div|table|tbody|tr|td|body|head|html|title|meta|style|pre|script|link|object) ([^>]+)>\s+/g,"<$1 $2>");j=j.replace(/<(p|h[1-6]|blockquote|hr|div|table|tbody|tr|td|body|head|html|title|meta|style|pre|script|link|object)>\s+/g,"<$1>");j=j.replace(/\s+<\/(p|h[1-6]|blockquote|hr|div|table|tbody|tr|td|body|head|html|title|meta|style|pre|script|link|object)>/g,"")}if(k.apply_source_formatting&&k.indent_mode=="simple"){j=j.replace(/<(\/?)(ul|hr|table|meta|link|tbody|tr|object|body|head|html|map)(|[^>]+)>\s*/g,"\n<$1$2$3>\n");j=j.replace(/\s*<(p|h[1-6]|blockquote|div|title|style|pre|script|td|li|area)(|[^>]+)>/g,"\n<$1$2>");j=j.replace(/<\/(p|h[1-6]|blockquote|div|title|style|pre|script|td|li)>\s*/g,"\n");j=j.replace(/\n\n/g,"\n")}}j=i._unprotect(j,l);j=j.replace(//g,"");j=j.replace(/(type|language)=\"mce-/g,'$1="');if(k.entity_encoding=="raw"){j=j.replace(/

     <\/p>|]+)> <\/p>/g,"\u00a0

    ")}}n.content=j},_serializeNode:function(D,o){var z=this,A=z.settings,x=z.writer,q,j,u,F,E,G,B,h,y,k,r,C,p,m;if(!A.node_filter||A.node_filter(D)){switch(D.nodeType){case 1:if(D.hasAttribute?D.hasAttribute("mce_bogus"):D.getAttribute("mce_bogus")){return}p=false;q=D.hasChildNodes();k=D.getAttribute("mce_name")||D.nodeName.toLowerCase();if(d){if(D.scopeName!=="HTML"&&D.scopeName!=="html"){k=D.scopeName+":"+k}}if(k.indexOf("mce:")===0){k=k.substring(4)}if(!z.validElementsRE||!z.validElementsRE.test(k)||(z.invalidElementsRE&&z.invalidElementsRE.test(k))||o){p=true;break}if(d){if(A.fix_content_duplication){if(D.mce_serialized==z.key){return}D.mce_serialized=z.key}if(k.charAt(0)=="/"){k=k.substring(1)}}else{if(a){if(D.nodeName==="BR"&&D.getAttribute("type")=="_moz"){return}}}if(z.childRules){if(z.parentElementsRE.test(z.elementName)){if(!z.childRules[z.elementName].test(k)){p=true;break}}z.elementName=k}r=z.findRule(k);k=r.name||k;m=A.closed.test(k);if((!q&&r.noEmpty)||(d&&!k)){p=true;break}if(r.requiredAttribs){G=r.requiredAttribs;for(F=G.length-1;F>=0;F--){if(this.dom.getAttrib(D,G[F])!==""){break}}if(F==-1){p=true;break}}x.writeStartElement(k);if(r.attribs){for(F=0,B=r.attribs,E=B.length;F-1;F--){h=B[F];if(h.specified){G=h.nodeName.toLowerCase();if(A.invalid_attrs.test(G)||!r.validAttribsRE.test(G)){continue}C=z.findAttribRule(r,G);y=z._getAttrib(D,C,G);if(y!==null){x.writeAttribute(G,y)}}}}if(k==="script"&&e.trim(D.innerHTML)){x.writeText("// ");x.writeCDATA(D.innerHTML.replace(/|<\[CDATA\[|\]\]>/g,""));q=false;break}if(r.padd){if(q&&(u=D.firstChild)&&u.nodeType===1&&D.childNodes.length===1){if(u.hasAttribute?u.hasAttribute("mce_bogus"):u.getAttribute("mce_bogus")){x.writeText("\u00a0")}}else{if(!q){x.writeText("\u00a0")}}}break;case 3:if(z.childRules&&z.parentElementsRE.test(z.elementName)){if(!z.childRules[z.elementName].test(D.nodeName)){return}}return x.writeText(D.nodeValue);case 4:return x.writeCDATA(D.nodeValue);case 8:return x.writeComment(D.nodeValue)}}else{if(D.nodeType==1){q=D.hasChildNodes()}}if(q&&!m){u=D.firstChild;while(u){z._serializeNode(u);z.elementName=k;u=u.nextSibling}}if(!p){if(!m){x.writeFullEndElement()}else{x.writeEndElement()}}},_protect:function(j){var i=this;j.items=j.items||[];function h(l){return l.replace(/[\r\n\\]/g,function(m){if(m==="\n"){return"\\n"}else{if(m==="\\"){return"\\\\"}}return"\\r"})}function k(l){return l.replace(/\\[\\rn]/g,function(m){if(m==="\\n"){return"\n"}else{if(m==="\\\\"){return"\\"}}return"\r"})}f(j.patterns,function(l){j.content=k(h(j.content).replace(l.pattern,function(n,o,m,p){m=k(m);if(l.encode){m=i._encode(m)}j.items.push(m);return o+""+p}))});return j},_unprotect:function(i,j){i=i.replace(/\"))}if(a&&j.ListBox){if(a.Button||a.SplitButton){e+=b.createHTML("td",{"class":"mceToolbarEnd"},b.createHTML("span",null,""))}}if(b.stdMode){e+=''+j.renderHTML()+""}else{e+=""+j.renderHTML()+""}if(f&&j.ListBox){if(f.Button||f.SplitButton){e+=b.createHTML("td",{"class":"mceToolbarStart"},b.createHTML("span",null,""))}}}g="mceToolbarEnd";if(j.Button){g+=" mceToolbarEndButton"}else{if(j.SplitButton){g+=" mceToolbarEndSplitButton"}else{if(j.ListBox){g+=" mceToolbarEndListBox"}}}e+=b.createHTML("td",{"class":g},b.createHTML("span",null,""));return b.createHTML("table",{id:l.id,"class":"mceToolbar"+(m["class"]?" "+m["class"]:""),cellpadding:"0",cellspacing:"0",align:l.settings.align||""},""+e+"")}});(function(b){var a=b.util.Dispatcher,c=b.each;b.create("tinymce.AddOnManager",{items:[],urls:{},lookup:{},onAdd:new a(this),get:function(d){return this.lookup[d]},requireLangPack:function(f){var d,e=b.EditorManager.settings;if(e&&e.language){d=this.urls[f]+"/langs/"+e.language+".js";if(!b.dom.Event.domLoaded&&!e.strict_mode){b.ScriptLoader.load(d)}else{b.ScriptLoader.add(d)}}},add:function(e,d){this.items.push(d);this.lookup[e]=d;this.onAdd.dispatch(this,e,d);return d},load:function(h,e,d,g){var f=this;if(f.urls[h]){return}if(e.indexOf("/")!=0&&e.indexOf("://")==-1){e=b.baseURL+"/"+e}f.urls[h]=e.substring(0,e.lastIndexOf("/"));b.ScriptLoader.add(e,d,g)}});b.PluginManager=new b.AddOnManager();b.ThemeManager=new b.AddOnManager()}(tinymce));(function(f){var g=f.each,h=f.extend,e=f.DOM,a=f.dom.Event,c=f.ThemeManager,b=f.PluginManager,d=f.explode;f.create("static tinymce.EditorManager",{editors:{},i18n:{},activeEditor:null,preInit:function(){var i=this,j=window.location;f.documentBaseURL=j.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,"");if(!/[\/\\]$/.test(f.documentBaseURL)){f.documentBaseURL+="/"}f.baseURL=new f.util.URI(f.documentBaseURL).toAbsolute(f.baseURL);f.EditorManager.baseURI=new f.util.URI(f.baseURL);if(document.domain&&j.hostname!=document.domain){f.relaxedDomain=document.domain}i.onBeforeUnload=new f.util.Dispatcher(i);a.add(window,"beforeunload",function(k){i.onBeforeUnload.dispatch(i,k)})},init:function(q){var p=this,l,k=f.ScriptLoader,o,n,i=[],m;function j(u,v,r){var t=u[v];if(!t){return}if(f.is(t,"string")){r=t.replace(/\.\w+$/,"");r=r?f.resolve(r):0;t=f.resolve(t)}return t.apply(r||this,Array.prototype.slice.call(arguments,2))}q=h({theme:"simple",language:"en",strict_loading_mode:document.contentType=="application/xhtml+xml"},q);p.settings=q;if(!a.domLoaded&&!q.strict_loading_mode){if(q.language){k.add(f.baseURL+"/langs/"+q.language+".js")}if(q.theme&&q.theme.charAt(0)!="-"&&!c.urls[q.theme]){c.load(q.theme,"themes/"+q.theme+"/editor_template"+f.suffix+".js")}if(q.plugins){l=d(q.plugins);if(f.inArray(l,"compat2x")!=-1){b.load("compat2x","plugins/compat2x/editor_plugin"+f.suffix+".js")}g(l,function(r){if(r&&r.charAt(0)!="-"&&!b.urls[r]){if(!f.isWebKit&&r=="safari"){return}b.load(r,"plugins/"+r+"/editor_plugin"+f.suffix+".js")}})}k.loadQueue()}a.add(document,"init",function(){var r,t;j(q,"onpageload");if(q.browsers){r=false;g(d(q.browsers),function(u){switch(u){case"ie":case"msie":if(f.isIE){r=true}break;case"gecko":if(f.isGecko){r=true}break;case"safari":case"webkit":if(f.isWebKit){r=true}break;case"opera":if(f.isOpera){r=true}break}});if(!r){return}}switch(q.mode){case"exact":r=q.elements||"";if(r.length>0){g(d(r),function(u){if(e.get(u)){m=new f.Editor(u,q);i.push(m);m.render(1)}else{o=0;g(document.forms,function(v){g(v.elements,function(w){if(w.name===u){u="mce_editor_"+o;e.setAttrib(w,"id",u);m=new f.Editor(u,q);i.push(m);m.render(1)}})})}})}break;case"textareas":case"specific_textareas":function s(v,u){return u.constructor===RegExp?u.test(v.className):e.hasClass(v,u)}g(e.select("textarea"),function(u){if(q.editor_deselector&&s(u,q.editor_deselector)){return}if(!q.editor_selector||s(u,q.editor_selector)){n=e.get(u.name);if(!u.id&&!n){u.id=u.name}if(!u.id||p.get(u.id)){u.id=e.uniqueId()}m=new f.Editor(u.id,q);i.push(m);m.render(1)}});break}if(q.oninit){r=t=0;g(i,function(u){t++;if(!u.initialized){u.onInit.add(function(){r++;if(r==t){j(q,"oninit")}})}else{r++}if(r==t){j(q,"oninit")}})}})},get:function(i){return this.editors[i]},getInstanceById:function(i){return this.get(i)},add:function(i){this.editors[i.id]=i;this._setActive(i);return i},remove:function(j){var i=this;if(!i.editors[j.id]){return null}delete i.editors[j.id];if(i.activeEditor==j){g(i.editors,function(k){i._setActive(k);return false})}j.destroy();return j},execCommand:function(o,m,l){var n=this,k=n.get(l),i;switch(o){case"mceFocus":k.focus();return true;case"mceAddEditor":case"mceAddControl":if(!n.get(l)){new f.Editor(l,n.settings).render()}return true;case"mceAddFrameControl":i=l.window;i.tinyMCE=tinyMCE;i.tinymce=f;f.DOM.doc=i.document;f.DOM.win=i;k=new f.Editor(l.element_id,l);k.render();if(f.isIE){function j(){k.destroy();i.detachEvent("onunload",j);i=i.tinyMCE=i.tinymce=null}i.attachEvent("onunload",j)}l.page_window=null;return true;case"mceRemoveEditor":case"mceRemoveControl":if(k){k.remove()}return true;case"mceToggleEditor":if(!k){n.execCommand("mceAddControl",0,l);return true}if(k.isHidden()){k.show()}else{k.hide()}return true}if(n.activeEditor){return n.activeEditor.execCommand(o,m,l)}return false},execInstanceCommand:function(m,l,k,j){var i=this.get(m);if(i){return i.execCommand(l,k,j)}return false},triggerSave:function(){g(this.editors,function(i){i.save()})},addI18n:function(k,l){var i,j=this.i18n;if(!f.is(k,"string")){g(k,function(n,m){g(n,function(q,p){g(q,function(s,r){if(p==="common"){j[m+"."+r]=s}else{j[m+"."+p+"."+r]=s}})})})}else{g(l,function(n,m){j[k+"."+m]=n})}},_setActive:function(i){this.selectedInstance=this.activeEditor=i}});f.EditorManager.preInit()})(tinymce);var tinyMCE=window.tinyMCE=tinymce.EditorManager;(function(n){var o=n.DOM,k=n.dom.Event,f=n.extend,l=n.util.Dispatcher;var j=n.each,a=n.isGecko,b=n.isIE,e=n.isWebKit;var d=n.is,h=n.ThemeManager,c=n.PluginManager,i=n.EditorManager;var p=n.inArray,m=n.grep,g=n.explode;n.create("tinymce.Editor",{Editor:function(u,r){var q=this;q.id=q.editorId=u;q.execCommands={};q.queryStateCommands={};q.queryValueCommands={};q.plugins={};j(["onPreInit","onBeforeRenderUI","onPostRender","onInit","onRemove","onActivate","onDeactivate","onClick","onEvent","onMouseUp","onMouseDown","onDblClick","onKeyDown","onKeyUp","onKeyPress","onContextMenu","onSubmit","onReset","onPaste","onPreProcess","onPostProcess","onBeforeSetContent","onBeforeGetContent","onSetContent","onGetContent","onLoadContent","onSaveContent","onNodeChange","onChange","onBeforeExecCommand","onExecCommand","onUndo","onRedo","onVisualAid","onSetProgressState"],function(s){q[s]=new l(q)});q.settings=r=f({id:u,language:"en",docs_language:"en",theme:"simple",skin:"default",delta_width:0,delta_height:0,popup_css:"",plugins:"",document_base_url:n.documentBaseURL,add_form_submit_trigger:1,submit_patch:1,add_unload_trigger:1,convert_urls:1,relative_urls:1,remove_script_host:1,table_inline_editing:0,object_resizing:1,cleanup:1,accessibility_focus:1,custom_shortcuts:1,custom_undo_redo_keyboard_shortcuts:1,custom_undo_redo_restore_selection:1,custom_undo_redo:1,doctype:'',visual_table_class:"mceItemTable",visual:1,inline_styles:true,convert_fonts_to_spans:true,font_size_style_values:"xx-small,x-small,small,medium,large,x-large,xx-large",apply_source_formatting:1,directionality:"ltr",forced_root_block:"p",valid_elements:"@[id|class|style|title|dir';F.iframeHTML+='';if(n.relaxedDomain){F.iframeHTML+='\n"; + } + + $ver = md5("$wp_scripts->concat_version"); + $src = $wp_scripts->base_url . "/wp-admin/load-scripts.php?c={$zip}&load=" . trim($wp_scripts->concat, ', ') . "&ver=$ver"; + echo "\n"; + } + + if ( !empty($wp_scripts->print_html) ) + echo $wp_scripts->print_html; +} + +/** + * Prints the script queue in the HTML head on the front end. + * + * Postpones the scripts that were queued for the footer. + * wp_print_footer_scripts() is called in the footer to print these scripts. + * + * @since 2.8 + */ +function wp_print_head_scripts() { + if ( ! did_action('wp_print_scripts') ) + do_action('wp_print_scripts'); + + global $wp_scripts; + + if ( !is_a($wp_scripts, 'WP_Scripts') ) + return array(); // no need to run if nothing is queued + + return print_head_scripts(); +} + +/** + * Prints the scripts that were queued for the footer on the front end. + * + * @since 2.8 + */ +function wp_print_footer_scripts() { + return print_footer_scripts(); +} + +/** + * Wrapper for do_action('wp_enqueue_scripts') + * + * Allows plugins to queue scripts for the front end using wp_enqueue_script(). + * Runs first in wp_head() where all is_home(), is_page(), etc. functions are available. + * + * @since 2.8 + */ +function wp_enqueue_scripts() { + do_action('wp_enqueue_scripts'); +} + +function print_admin_styles() { + global $wp_styles, $concatenate_scripts, $compress_css; + + if ( !is_a($wp_styles, 'WP_Styles') ) + $wp_styles = new WP_Styles(); + + script_concat_settings(); + $wp_styles->do_concat = $concatenate_scripts; + $zip = $compress_css ? 1 : 0; + if ( $zip && defined('ENFORCE_GZIP') && ENFORCE_GZIP ) + $zip = 'gzip'; + + $wp_styles->do_items(false); + + if ( apply_filters('print_admin_styles', true) ) { + if ( !empty($wp_styles->concat) ) { + $dir = $wp_styles->text_direction; + $ver = md5("$wp_styles->concat_version{$dir}"); + $href = $wp_styles->base_url . "/wp-admin/load-styles.php?c={$zip}&dir={$dir}&load=" . trim($wp_styles->concat, ', ') . "&ver=$ver"; + echo "\n"; + } + + if ( !empty($wp_styles->print_html) ) + echo $wp_styles->print_html; + } + + $wp_styles->do_concat = false; + $wp_styles->concat = $wp_styles->concat_version = $wp_styles->print_html = ''; + return $wp_styles->done; +} + +function script_concat_settings() { + global $concatenate_scripts, $compress_scripts, $compress_css; + + $compressed_output = ( ini_get('zlib.output_compression') || 'ob_gzhandler' == ini_get('output_handler') ); + + if ( ! isset($concatenate_scripts) ) { + $concatenate_scripts = defined('CONCATENATE_SCRIPTS') ? CONCATENATE_SCRIPTS : true; + if ( ! is_admin() || ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) ) + $concatenate_scripts = false; + } + + if ( ! isset($compress_scripts) ) { + $compress_scripts = defined('COMPRESS_SCRIPTS') ? COMPRESS_SCRIPTS : true; + if ( $compress_scripts && ( ! get_site_option('can_compress_scripts') || $compressed_output ) ) + $compress_scripts = false; + } + + if ( ! isset($compress_css) ) { + $compress_css = defined('COMPRESS_CSS') ? COMPRESS_CSS : true; + if ( $compress_css && ( ! get_site_option('can_compress_scripts') || $compressed_output ) ) + $compress_css = false; + } +} + +add_action( 'wp_default_scripts', 'wp_default_scripts' ); +add_filter( 'wp_print_scripts', 'wp_just_in_time_script_localization' ); +add_filter( 'print_scripts_array', 'wp_prototype_before_jquery' ); + +add_action( 'wp_default_styles', 'wp_default_styles' ); +add_filter( 'style_loader_src', 'wp_style_loader_src', 10, 2 ); diff --git a/wp-includes/shortcodes.php b/wp-includes/shortcodes.php new file mode 100644 index 0000000..6ced181 --- /dev/null +++ b/wp-includes/shortcodes.php @@ -0,0 +1,297 @@ + + * $out = do_shortcode($content); + * + * + * @link http://codex.wordpress.org/Shortcode_API + * + * @package WordPress + * @subpackage Shortcodes + * @since 2.5 + */ + +/** + * Container for storing shortcode tags and their hook to call for the shortcode + * + * @since 2.5 + * @name $shortcode_tags + * @var array + * @global array $shortcode_tags + */ +$shortcode_tags = array(); + +/** + * Add hook for shortcode tag. + * + * There can only be one hook for each shortcode. Which means that if another + * plugin has a similar shortcode, it will override yours or yours will override + * theirs depending on which order the plugins are included and/or ran. + * + * Simplest example of a shortcode tag using the API: + * + * + * // [footag foo="bar"] + * function footag_func($atts) { + * return "foo = {$atts[foo]}"; + * } + * add_shortcode('footag', 'footag_func'); + * + * + * Example with nice attribute defaults: + * + * + * // [bartag foo="bar"] + * function bartag_func($atts) { + * extract(shortcode_atts(array( + * 'foo' => 'no foo', + * 'baz' => 'default baz', + * ), $atts)); + * + * return "foo = {$foo}"; + * } + * add_shortcode('bartag', 'bartag_func'); + * + * + * Example with enclosed content: + * + * + * // [baztag]content[/baztag] + * function baztag_func($atts, $content='') { + * return "content = $content"; + * } + * add_shortcode('baztag', 'baztag_func'); + * + * + * @since 2.5 + * @uses $shortcode_tags + * + * @param string $tag Shortcode tag to be searched in post content. + * @param callable $func Hook to run when shortcode is found. + */ +function add_shortcode($tag, $func) { + global $shortcode_tags; + + if ( is_callable($func) ) + $shortcode_tags[$tag] = $func; +} + +/** + * Removes hook for shortcode. + * + * @since 2.5 + * @uses $shortcode_tags + * + * @param string $tag shortcode tag to remove hook for. + */ +function remove_shortcode($tag) { + global $shortcode_tags; + + unset($shortcode_tags[$tag]); +} + +/** + * Clear all shortcodes. + * + * This function is simple, it clears all of the shortcode tags by replacing the + * shortcodes global by a empty array. This is actually a very efficient method + * for removing all shortcodes. + * + * @since 2.5 + * @uses $shortcode_tags + */ +function remove_all_shortcodes() { + global $shortcode_tags; + + $shortcode_tags = array(); +} + +/** + * Search content for shortcodes and filter shortcodes through their hooks. + * + * If there are no shortcode tags defined, then the content will be returned + * without any filtering. This might cause issues when plugins are disabled but + * the shortcode will still show up in the post or content. + * + * @since 2.5 + * @uses $shortcode_tags + * @uses get_shortcode_regex() Gets the search pattern for searching shortcodes. + * + * @param string $content Content to search for shortcodes + * @return string Content with shortcodes filtered out. + */ +function do_shortcode($content) { + global $shortcode_tags; + + if (empty($shortcode_tags) || !is_array($shortcode_tags)) + return $content; + + $pattern = get_shortcode_regex(); + return preg_replace_callback('/'.$pattern.'/s', 'do_shortcode_tag', $content); +} + +/** + * Retrieve the shortcode regular expression for searching. + * + * The regular expression combines the shortcode tags in the regular expression + * in a regex class. + * + * The regular expresion contains 6 different sub matches to help with parsing. + * + * 1/6 - An extra [ or ] to allow for escaping shortcodes with double [[]] + * 2 - The shortcode name + * 3 - The shortcode argument list + * 4 - The self closing / + * 5 - The content of a shortcode when it wraps some content. + * + * @since 2.5 + * @uses $shortcode_tags + * + * @return string The shortcode search regular expression + */ +function get_shortcode_regex() { + global $shortcode_tags; + $tagnames = array_keys($shortcode_tags); + $tagregexp = join( '|', array_map('preg_quote', $tagnames) ); + + return '(.?)\[('.$tagregexp.')\b(.*?)(?:(\/))?\](?:(.+?)\[\/\2\])?(.?)'; +} + +/** + * Regular Expression callable for do_shortcode() for calling shortcode hook. + * @see get_shortcode_regex for details of the match array contents. + * + * @since 2.5 + * @access private + * @uses $shortcode_tags + * + * @param array $m Regular expression match array + * @return mixed False on failure. + */ +function do_shortcode_tag($m) { + global $shortcode_tags; + + // allow [[foo]] syntax for escaping a tag + if ($m[1] == '[' && $m[6] == ']') { + return substr($m[0], 1, -1); + } + + $tag = $m[2]; + $attr = shortcode_parse_atts($m[3]); + + if ( isset($m[5]) ) { + // enclosing tag - extra parameter + return $m[1] . call_user_func($shortcode_tags[$tag], $attr, $m[5], $m[2]) . $m[6]; + } else { + // self-closing tag + return $m[1] . call_user_func($shortcode_tags[$tag], $attr, NULL, $m[2]) . $m[6]; + } +} + +/** + * Retrieve all attributes from the shortcodes tag. + * + * The attributes list has the attribute name as the key and the value of the + * attribute as the value in the key/value pair. This allows for easier + * retrieval of the attributes, since all attributes have to be known. + * + * @since 2.5 + * + * @param string $text + * @return array List of attributes and their value. + */ +function shortcode_parse_atts($text) { + $atts = array(); + $pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/'; + $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text); + if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) { + foreach ($match as $m) { + if (!empty($m[1])) + $atts[strtolower($m[1])] = stripcslashes($m[2]); + elseif (!empty($m[3])) + $atts[strtolower($m[3])] = stripcslashes($m[4]); + elseif (!empty($m[5])) + $atts[strtolower($m[5])] = stripcslashes($m[6]); + elseif (isset($m[7]) and strlen($m[7])) + $atts[] = stripcslashes($m[7]); + elseif (isset($m[8])) + $atts[] = stripcslashes($m[8]); + } + } else { + $atts = ltrim($text); + } + return $atts; +} + +/** + * Combine user attributes with known attributes and fill in defaults when needed. + * + * The pairs should be considered to be all of the attributes which are + * supported by the caller and given as a list. The returned attributes will + * only contain the attributes in the $pairs list. + * + * If the $atts list has unsupported attributes, then they will be ignored and + * removed from the final returned list. + * + * @since 2.5 + * + * @param array $pairs Entire list of supported attributes and their defaults. + * @param array $atts User defined attributes in shortcode tag. + * @return array Combined and filtered attribute list. + */ +function shortcode_atts($pairs, $atts) { + $atts = (array)$atts; + $out = array(); + foreach($pairs as $name => $default) { + if ( array_key_exists($name, $atts) ) + $out[$name] = $atts[$name]; + else + $out[$name] = $default; + } + return $out; +} + +/** + * Remove all shortcode tags from the given content. + * + * @since 2.5 + * @uses $shortcode_tags + * + * @param string $content Content to remove shortcode tags. + * @return string Content without shortcode tags. + */ +function strip_shortcodes( $content ) { + global $shortcode_tags; + + if (empty($shortcode_tags) || !is_array($shortcode_tags)) + return $content; + + $pattern = get_shortcode_regex(); + + return preg_replace('/'.$pattern.'/s', '', $content); +} + +add_filter('the_content', 'do_shortcode', 11); // AFTER wpautop() + +?> \ No newline at end of file diff --git a/wp-includes/streams.php b/wp-includes/streams.php new file mode 100644 index 0000000..60b617d --- /dev/null +++ b/wp-includes/streams.php @@ -0,0 +1,191 @@ +. + + This file is part of PHP-gettext. + + PHP-gettext 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. + + PHP-gettext 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 PHP-gettext; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + */ + + +// Simple class to wrap file streams, string streams, etc. +// seek is essential, and it should be byte stream +class StreamReader { + // should return a string [FIXME: perhaps return array of bytes?] + function read($bytes) { + return false; + } + + // should return new position + function seekto($position) { + return false; + } + + // returns current position + function currentpos() { + return false; + } + + // returns length of entire stream (limit for seekto()s) + function length() { + return false; + } +} + +class StringReader { + var $_pos; + var $_str; + + function StringReader($str='') { + $this->_str = $str; + $this->_pos = 0; + // If string functions are overloaded, we need to use the mb versions + $this->is_overloaded = ((ini_get("mbstring.func_overload") & 2) != 0) && function_exists('mb_substr'); + } + + function _substr($string, $start, $length) { + if ($this->is_overloaded) { + return mb_substr($string,$start,$length,'ascii'); + } else { + return substr($string,$start,$length); + } + } + + function _strlen($string) { + if ($this->is_overloaded) { + return mb_strlen($string,'ascii'); + } else { + return strlen($string); + } + } + + function read($bytes) { + $data = $this->_substr($this->_str, $this->_pos, $bytes); + $this->_pos += $bytes; + if ($this->_strlen($this->_str)<$this->_pos) + $this->_pos = $this->_strlen($this->_str); + + return $data; + } + + function seekto($pos) { + $this->_pos = $pos; + if ($this->_strlen($this->_str)<$this->_pos) + $this->_pos = $this->_strlen($this->_str); + return $this->_pos; + } + + function currentpos() { + return $this->_pos; + } + + function length() { + return $this->_strlen($this->_str); + } +} + + +class FileReader { + var $_pos; + var $_fd; + var $_length; + + function FileReader($filename) { + if (file_exists($filename)) { + + $this->_length=filesize($filename); + $this->_pos = 0; + $this->_fd = fopen($filename,'rb'); + if (!$this->_fd) { + $this->error = 3; // Cannot read file, probably permissions + return false; + } + } else { + $this->error = 2; // File doesn't exist + return false; + } + } + + function read($bytes) { + if ($bytes) { + fseek($this->_fd, $this->_pos); + + // PHP 5.1.1 does not read more than 8192 bytes in one fread() + // the discussions at PHP Bugs suggest it's the intended behaviour + while ($bytes > 0) { + $chunk = fread($this->_fd, $bytes); + $data .= $chunk; + $bytes -= strlen($chunk); + } + $this->_pos = ftell($this->_fd); + + return $data; + } else return ''; + } + + function seekto($pos) { + fseek($this->_fd, $pos); + $this->_pos = ftell($this->_fd); + return $this->_pos; + } + + function currentpos() { + return $this->_pos; + } + + function length() { + return $this->_length; + } + + function close() { + fclose($this->_fd); + } + +} + +// Preloads entire file in memory first, then creates a StringReader +// over it (it assumes knowledge of StringReader internals) +class CachedFileReader extends StringReader { + function CachedFileReader($filename) { + parent::StringReader(); + + if (file_exists($filename)) { + + $length=filesize($filename); + $fd = fopen($filename,'rb'); + + if (!$fd) { + $this->error = 3; // Cannot read file, probably permissions + return false; + } + $this->_str = fread($fd, $length); + fclose($fd); + + } else { + $this->error = 2; // File doesn't exist + return false; + } + } +} + + +?> diff --git a/wp-includes/taxonomy.php b/wp-includes/taxonomy.php new file mode 100644 index 0000000..12f86a3 --- /dev/null +++ b/wp-includes/taxonomy.php @@ -0,0 +1,2352 @@ + true, 'update_count_callback' => '_update_post_term_count', 'label' => __('Categories'), 'query_var' => false, 'rewrite' => false) ) ; + register_taxonomy( 'post_tag', 'post', array('hierarchical' => false, 'update_count_callback' => '_update_post_term_count', 'label' => __('Post Tags'), 'query_var' => false, 'rewrite' => false) ) ; + register_taxonomy( 'link_category', 'link', array('hierarchical' => false, 'label' => __('Categories'), 'query_var' => false, 'rewrite' => false) ) ; +} +add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority + +/** + * Return all of the taxonomy names that are of $object_type. + * + * It appears that this function can be used to find all of the names inside of + * $wp_taxonomies global variable. + * + * Should + * result in Array('category', 'post_tag') + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wp_taxonomies + * + * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts) + * @return array The names of all taxonomy of $object_type. + */ +function get_object_taxonomies($object) { + global $wp_taxonomies; + + if ( is_object($object) ) { + if ( $object->post_type == 'attachment' ) + return get_attachment_taxonomies($object); + $object = $object->post_type; + } + + $object = (array) $object; + + $taxonomies = array(); + foreach ( (array) $wp_taxonomies as $taxonomy ) { + if ( array_intersect($object, (array) $taxonomy->object_type) ) + $taxonomies[] = $taxonomy->name; + } + + return $taxonomies; +} + +/** + * Retrieves the taxonomy object of $taxonomy. + * + * The get_taxonomy function will first check that the parameter string given + * is a taxonomy object and if it is, it will return it. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wp_taxonomies + * @uses is_taxonomy() Checks whether taxonomy exists + * + * @param string $taxonomy Name of taxonomy object to return + * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist + */ +function get_taxonomy( $taxonomy ) { + global $wp_taxonomies; + + if ( ! is_taxonomy($taxonomy) ) + return false; + + return $wp_taxonomies[$taxonomy]; +} + +/** + * Checks that the taxonomy name exists. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wp_taxonomies + * + * @param string $taxonomy Name of taxonomy object + * @return bool Whether the taxonomy exists or not. + */ +function is_taxonomy( $taxonomy ) { + global $wp_taxonomies; + + return isset($wp_taxonomies[$taxonomy]); +} + +/** + * Whether the taxonomy object is hierarchical. + * + * Checks to make sure that the taxonomy is an object first. Then Gets the + * object, and finally returns the hierarchical value in the object. + * + * A false return value might also mean that the taxonomy does not exist. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses is_taxonomy() Checks whether taxonomy exists + * @uses get_taxonomy() Used to get the taxonomy object + * + * @param string $taxonomy Name of taxonomy object + * @return bool Whether the taxonomy is hierarchical + */ +function is_taxonomy_hierarchical($taxonomy) { + if ( ! is_taxonomy($taxonomy) ) + return false; + + $taxonomy = get_taxonomy($taxonomy); + return $taxonomy->hierarchical; +} + +/** + * Create or modify a taxonomy object. Do not use before init. + * + * A simple function for creating or modifying a taxonomy object based on the + * parameters given. The function will accept an array (third optional + * parameter), along with strings for the taxonomy name and another string for + * the object type. + * + * Nothing is returned, so expect error maybe or use is_taxonomy() to check + * whether taxonomy exists. + * + * Optional $args contents: + * + * hierarachical - has some defined purpose at other parts of the API and is a + * boolean value. + * + * update_count_callback - works much like a hook, in that it will be called + * when the count is updated. + * + * rewrite - false to prevent rewrite, or array('slug'=>$slug) to customize + * permastruct; default will use $taxonomy as slug. + * + * query_var - false to prevent queries, or string to customize query var + * (?$query_var=$term); default will use $taxonomy as query var. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wp_taxonomies Inserts new taxonomy object into the list + * @uses $wp_rewrite Adds rewrite tags and permastructs + * @uses $wp Adds query vars + * + * @param string $taxonomy Name of taxonomy object + * @param array|string $object_type Name of the object type for the taxonomy object. + * @param array|string $args See above description for the two keys values. + */ +function register_taxonomy( $taxonomy, $object_type, $args = array() ) { + global $wp_taxonomies, $wp_rewrite, $wp; + + if (!is_array($wp_taxonomies)) + $wp_taxonomies = array(); + + $defaults = array('hierarchical' => false, 'update_count_callback' => '', 'rewrite' => true, 'query_var' => true); + $args = wp_parse_args($args, $defaults); + + if ( false !== $args['query_var'] && !empty($wp) ) { + if ( true === $args['query_var'] ) + $args['query_var'] = $taxonomy; + $args['query_var'] = sanitize_title_with_dashes($args['query_var']); + $wp->add_query_var($args['query_var']); + } + + if ( false !== $args['rewrite'] && !empty($wp_rewrite) ) { + if ( !is_array($args['rewrite']) ) + $args['rewrite'] = array(); + if ( !isset($args['rewrite']['slug']) ) + $args['rewrite']['slug'] = sanitize_title_with_dashes($taxonomy); + $wp_rewrite->add_rewrite_tag("%$taxonomy%", '([^/]+)', $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=$term"); + $wp_rewrite->add_permastruct($taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%"); + } + + $args['name'] = $taxonomy; + $args['object_type'] = $object_type; + $wp_taxonomies[$taxonomy] = (object) $args; +} + +// +// Term API +// + +/** + * Retrieve object_ids of valid taxonomy and term. + * + * The strings of $taxonomies must exist before this function will continue. On + * failure of finding a valid taxonomy, it will return an WP_Error class, kind + * of like Exceptions in PHP 5, except you can't catch them. Even so, you can + * still test for the WP_Error class and get the error message. + * + * The $terms aren't checked the same as $taxonomies, but still need to exist + * for $object_ids to be returned. + * + * It is possible to change the order that object_ids is returned by either + * using PHP sort family functions or using the database by using $args with + * either ASC or DESC array. The value should be in the key named 'order'. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses wp_parse_args() Creates an array from string $args. + * + * @param string|array $terms String of term or array of string values of terms that will be used + * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names + * @param array|string $args Change the order of the object_ids, either ASC or DESC + * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success + * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found. + */ +function get_objects_in_term( $terms, $taxonomies, $args = array() ) { + global $wpdb; + + if ( !is_array( $terms) ) + $terms = array($terms); + + if ( !is_array($taxonomies) ) + $taxonomies = array($taxonomies); + + foreach ( (array) $taxonomies as $taxonomy ) { + if ( ! is_taxonomy($taxonomy) ) + return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy')); + } + + $defaults = array('order' => 'ASC'); + $args = wp_parse_args( $args, $defaults ); + extract($args, EXTR_SKIP); + + $order = ( 'desc' == strtolower($order) ) ? 'DESC' : 'ASC'; + + $terms = array_map('intval', $terms); + + $taxonomies = "'" . implode("', '", $taxonomies) . "'"; + $terms = "'" . implode("', '", $terms) . "'"; + + $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($terms) ORDER BY tr.object_id $order"); + + if ( ! $object_ids ) + return array(); + + return $object_ids; +} + +/** + * Get all Term data from database by Term ID. + * + * The usage of the get_term function is to apply filters to a term object. It + * is possible to get a term object from the database before applying the + * filters. + * + * $term ID must be part of $taxonomy, to get from the database. Failure, might + * be able to be captured by the hooks. Failure would be the same value as $wpdb + * returns for the get_row method. + * + * There are two hooks, one is specifically for each term, named 'get_term', and + * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the + * term object, and the taxonomy name as parameters. Both hooks are expected to + * return a Term object. + * + * 'get_term' hook - Takes two parameters the term Object and the taxonomy name. + * Must return term object. Used in get_term() as a catch-all filter for every + * $term. + * + * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy + * name. Must return term object. $taxonomy will be the taxonomy name, so for + * example, if 'category', it would be 'get_category' as the filter name. Useful + * for custom taxonomies or plugging into default taxonomies. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses sanitize_term() Cleanses the term based on $filter context before returning. + * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param. + * + * @param int|object $term If integer, will get from database. If object will apply filters and return $term. + * @param string $taxonomy Taxonomy name that $term is part of. + * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N + * @param string $filter Optional, default is raw or no WordPress defined filter will applied. + * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not + * exist then WP_Error will be returned. + */ +function &get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') { + global $wpdb; + + if ( empty($term) ) { + $error = new WP_Error('invalid_term', __('Empty Term')); + return $error; + } + + if ( ! is_taxonomy($taxonomy) ) { + $error = new WP_Error('invalid_taxonomy', __('Invalid Taxonomy')); + return $error; + } + + if ( is_object($term) && empty($term->filter) ) { + wp_cache_add($term->term_id, $term, $taxonomy); + $_term = $term; + } else { + if ( is_object($term) ) + $term = $term->term_id; + $term = (int) $term; + if ( ! $_term = wp_cache_get($term, $taxonomy) ) { + $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %s LIMIT 1", $taxonomy, $term) ); + wp_cache_add($term, $_term, $taxonomy); + } + } + + $_term = apply_filters('get_term', $_term, $taxonomy); + $_term = apply_filters("get_$taxonomy", $_term, $taxonomy); + $_term = sanitize_term($_term, $taxonomy, $filter); + + if ( $output == OBJECT ) { + return $_term; + } elseif ( $output == ARRAY_A ) { + $__term = get_object_vars($_term); + return $__term; + } elseif ( $output == ARRAY_N ) { + $__term = array_values(get_object_vars($_term)); + return $__term; + } else { + return $_term; + } +} + +/** + * Get all Term data from database by Term field and data. + * + * Warning: $value is not escaped for 'name' $field. You must do it yourself, if + * required. + * + * The default $field is 'id', therefore it is possible to also use null for + * field, but not recommended that you do so. + * + * If $value does not exist, the return value will be false. If $taxonomy exists + * and $field and $value combinations exist, the Term will be returned. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses sanitize_term() Cleanses the term based on $filter context before returning. + * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param. + * + * @param string $field Either 'slug', 'name', or 'id' + * @param string|int $value Search for this term value + * @param string $taxonomy Taxonomy Name + * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N + * @param string $filter Optional, default is raw or no WordPress defined filter will applied. + * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found. + */ +function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') { + global $wpdb; + + if ( ! is_taxonomy($taxonomy) ) + return false; + + if ( 'slug' == $field ) { + $field = 't.slug'; + $value = sanitize_title($value); + if ( empty($value) ) + return false; + } else if ( 'name' == $field ) { + // Assume already escaped + $value = stripslashes($value); + $field = 't.name'; + } else { + $field = 't.term_id'; + $value = (int) $value; + } + + $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) ); + if ( !$term ) + return false; + + wp_cache_add($term->term_id, $term, $taxonomy); + + $term = sanitize_term($term, $taxonomy, $filter); + + if ( $output == OBJECT ) { + return $term; + } elseif ( $output == ARRAY_A ) { + return get_object_vars($term); + } elseif ( $output == ARRAY_N ) { + return array_values(get_object_vars($term)); + } else { + return $term; + } +} + +/** + * Merge all term children into a single array of their IDs. + * + * This recursive function will merge all of the children of $term into the same + * array of term IDs. Only useful for taxonomies which are hierarchical. + * + * Will return an empty array if $term does not exist in $taxonomy. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses _get_term_hierarchy() + * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term + * + * @param string $term ID of Term to get children + * @param string $taxonomy Taxonomy Name + * @return array|WP_Error List of Term Objects. WP_Error returned if $taxonomy does not exist + */ +function get_term_children( $term_id, $taxonomy ) { + if ( ! is_taxonomy($taxonomy) ) + return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy')); + + $term_id = intval( $term_id ); + + $terms = _get_term_hierarchy($taxonomy); + + if ( ! isset($terms[$term_id]) ) + return array(); + + $children = $terms[$term_id]; + + foreach ( (array) $terms[$term_id] as $child ) { + if ( isset($terms[$child]) ) + $children = array_merge($children, get_term_children($child, $taxonomy)); + } + + return $children; +} + +/** + * Get sanitized Term field. + * + * Does checks for $term, based on the $taxonomy. The function is for contextual + * reasons and for simplicity of usage. See sanitize_term_field() for more + * information. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success. + * + * @param string $field Term field to fetch + * @param int $term Term ID + * @param string $taxonomy Taxonomy Name + * @param string $context Optional, default is display. Look at sanitize_term_field() for available options. + * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term. + */ +function get_term_field( $field, $term, $taxonomy, $context = 'display' ) { + $term = (int) $term; + $term = get_term( $term, $taxonomy ); + if ( is_wp_error($term) ) + return $term; + + if ( !is_object($term) ) + return ''; + + if ( !isset($term->$field) ) + return ''; + + return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context); +} + +/** + * Sanitizes Term for editing. + * + * Return value is sanitize_term() and usage is for sanitizing the term for + * editing. Function is for contextual and simplicity. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses sanitize_term() Passes the return value on success + * + * @param int|object $id Term ID or Object + * @param string $taxonomy Taxonomy Name + * @return mixed|null|WP_Error Will return empty string if $term is not an object. + */ +function get_term_to_edit( $id, $taxonomy ) { + $term = get_term( $id, $taxonomy ); + + if ( is_wp_error($term) ) + return $term; + + if ( !is_object($term) ) + return ''; + + return sanitize_term($term, $taxonomy, 'edit'); +} + +/** + * Retrieve the terms in a given taxonomy or list of taxonomies. + * + * You can fully inject any customizations to the query before it is sent, as + * well as control the output with a filter. + * + * The 'get_terms' filter will be called when the cache has the term and will + * pass the found term along with the array of $taxonomies and array of $args. + * This filter is also called before the array of terms is passed and will pass + * the array of terms, along with the $taxonomies and $args. + * + * The 'list_terms_exclusions' filter passes the compiled exclusions along with + * the $args. + * + * The 'get_terms_orderby' filter passes the ORDER BY clause for the query + * along with the $args array. + + * The 'get_terms_fields' filter passes the fields for the SELECT query + * along with the $args array. + * + * The list of arguments that $args can contain, which will overwrite the defaults: + * + * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing + * (will use term_id), Passing a custom value other than these will cause it to + * order based on the custom value. + * + * order - Default is ASC. Can use DESC. + * + * hide_empty - Default is true. Will not return empty terms, which means + * terms whose count is 0 according to the given taxonomy. + * + * exclude - Default is an empty string. A comma- or space-delimited string + * of term ids to exclude from the return array. If 'include' is non-empty, + * 'exclude' is ignored. + * + * exclude_tree - A comma- or space-delimited string of term ids to exclude + * from the return array, along with all of their descendant terms according to + * the primary taxonomy. If 'include' is non-empty, 'exclude_tree' is ignored. + * + * include - Default is an empty string. A comma- or space-delimited string + * of term ids to include in the return array. + * + * number - The maximum number of terms to return. Default is empty. + * + * offset - The number by which to offset the terms query. + * + * fields - Default is 'all', which returns an array of term objects. + * If 'fields' is 'ids' or 'names', returns an array of + * integers or strings, respectively. + * + * slug - Returns terms whose "slug" matches this value. Default is empty string. + * + * hierarchical - Whether to include terms that have non-empty descendants + * (even if 'hide_empty' is set to true). + * + * search - Returned terms' names will contain the value of 'search', + * case-insensitive. Default is an empty string. + * + * name__like - Returned terms' names will begin with the value of 'name__like', + * case-insensitive. Default is empty string. + * + * The argument 'pad_counts', if set to true will include the quantity of a term's + * children in the quantity of each term's "count" object variable. + * + * The 'get' argument, if set to 'all' instead of its default empty string, + * returns terms regardless of ancestry or whether the terms are empty. + * + * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default + * is 0. If set to a non-zero value, all returned terms will be descendants + * of that term according to the given taxonomy. Hence 'child_of' is set to 0 + * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies + * make term ancestry ambiguous. + * + * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is + * the empty string '', which has a different meaning from the integer 0. + * If set to an integer value, all returned terms will have as an immediate + * ancestor the term whose ID is specified by that integer according to the given taxonomy. + * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent' + * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings. + * + * @param string|array Taxonomy name or list of Taxonomy names + * @param string|array $args The values of what to search for when returning terms + * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist. + */ +function &get_terms($taxonomies, $args = '') { + global $wpdb; + $empty_array = array(); + + $single_taxonomy = false; + if ( !is_array($taxonomies) ) { + $single_taxonomy = true; + $taxonomies = array($taxonomies); + } + + foreach ( (array) $taxonomies as $taxonomy ) { + if ( ! is_taxonomy($taxonomy) ) { + $error = & new WP_Error('invalid_taxonomy', __('Invalid Taxonomy')); + return $error; + } + } + + $in_taxonomies = "'" . implode("', '", $taxonomies) . "'"; + + $defaults = array('orderby' => 'name', 'order' => 'ASC', + 'hide_empty' => true, 'exclude' => '', 'exclude_tree' => '', 'include' => '', + 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '', + 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', + 'pad_counts' => false, 'offset' => '', 'search' => ''); + $args = wp_parse_args( $args, $defaults ); + $args['number'] = absint( $args['number'] ); + $args['offset'] = absint( $args['offset'] ); + if ( !$single_taxonomy || !is_taxonomy_hierarchical($taxonomies[0]) || + '' !== $args['parent'] ) { + $args['child_of'] = 0; + $args['hierarchical'] = false; + $args['pad_counts'] = false; + } + + if ( 'all' == $args['get'] ) { + $args['child_of'] = 0; + $args['hide_empty'] = 0; + $args['hierarchical'] = false; + $args['pad_counts'] = false; + } + extract($args, EXTR_SKIP); + + if ( $child_of ) { + $hierarchy = _get_term_hierarchy($taxonomies[0]); + if ( !isset($hierarchy[$child_of]) ) + return $empty_array; + } + + if ( $parent ) { + $hierarchy = _get_term_hierarchy($taxonomies[0]); + if ( !isset($hierarchy[$parent]) ) + return $empty_array; + } + + // $args can be whatever, only use the args defined in defaults to compute the key + $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : ''; + $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key ); + $last_changed = wp_cache_get('last_changed', 'terms'); + if ( !$last_changed ) { + $last_changed = time(); + wp_cache_set('last_changed', $last_changed, 'terms'); + } + $cache_key = "get_terms:$key:$last_changed"; + $cache = wp_cache_get( $cache_key, 'terms' ); + if ( false !== $cache ) { + $cache = apply_filters('get_terms', $cache, $taxonomies, $args); + return $cache; + } + + $_orderby = strtolower($orderby); + if ( 'count' == $_orderby ) + $orderby = 'tt.count'; + else if ( 'name' == $_orderby ) + $orderby = 't.name'; + else if ( 'slug' == $_orderby ) + $orderby = 't.slug'; + else if ( 'term_group' == $_orderby ) + $orderby = 't.term_group'; + elseif ( empty($_orderby) || 'id' == $_orderby ) + $orderby = 't.term_id'; + + $orderby = apply_filters( 'get_terms_orderby', $orderby, $args ); + + $where = ''; + $inclusions = ''; + if ( !empty($include) ) { + $exclude = ''; + $exclude_tree = ''; + $interms = preg_split('/[\s,]+/',$include); + if ( count($interms) ) { + foreach ( (array) $interms as $interm ) { + if (empty($inclusions)) + $inclusions = ' AND ( t.term_id = ' . intval($interm) . ' '; + else + $inclusions .= ' OR t.term_id = ' . intval($interm) . ' '; + } + } + } + + if ( !empty($inclusions) ) + $inclusions .= ')'; + $where .= $inclusions; + + $exclusions = ''; + if ( ! empty( $exclude_tree ) ) { + $excluded_trunks = preg_split('/[\s,]+/',$exclude_tree); + foreach( (array) $excluded_trunks as $extrunk ) { + $excluded_children = (array) get_terms($taxonomies[0], array('child_of' => intval($extrunk), 'fields' => 'ids')); + $excluded_children[] = $extrunk; + foreach( (array) $excluded_children as $exterm ) { + if ( empty($exclusions) ) + $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' '; + else + $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' '; + + } + } + } + if ( !empty($exclude) ) { + $exterms = preg_split('/[\s,]+/',$exclude); + if ( count($exterms) ) { + foreach ( (array) $exterms as $exterm ) { + if ( empty($exclusions) ) + $exclusions = ' AND ( t.term_id <> ' . intval($exterm) . ' '; + else + $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' '; + } + } + } + + if ( !empty($exclusions) ) + $exclusions .= ')'; + $exclusions = apply_filters('list_terms_exclusions', $exclusions, $args ); + $where .= $exclusions; + + if ( !empty($slug) ) { + $slug = sanitize_title($slug); + $where .= " AND t.slug = '$slug'"; + } + + if ( !empty($name__like) ) + $where .= " AND t.name LIKE '{$name__like}%'"; + + if ( '' !== $parent ) { + $parent = (int) $parent; + $where .= " AND tt.parent = '$parent'"; + } + + if ( $hide_empty && !$hierarchical ) + $where .= ' AND tt.count > 0'; + + // don't limit the query results when we have to descend the family tree + if ( ! empty($number) && ! $hierarchical && empty( $child_of ) && '' === $parent ) { + if( $offset ) + $limit = 'LIMIT ' . $offset . ',' . $number; + else + $limit = 'LIMIT ' . $number; + + } else + $limit = ''; + + if ( !empty($search) ) { + $search = like_escape($search); + $where .= " AND (t.name LIKE '%$search%')"; + } + + $selects = array(); + if ( 'all' == $fields ) + $selects = array('t.*', 'tt.*'); + else if ( 'ids' == $fields ) + $selects = array('t.term_id', 'tt.parent', 'tt.count'); + else if ( 'names' == $fields ) + $selects = array('t.term_id', 'tt.parent', 'tt.count', 't.name'); + $select_this = implode(', ', apply_filters( 'get_terms_fields', $selects, $args )); + + $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ($in_taxonomies) $where ORDER BY $orderby $order $limit"; + + $terms = $wpdb->get_results($query); + if ( 'all' == $fields ) { + update_term_cache($terms); + } + + if ( empty($terms) ) { + wp_cache_add( $cache_key, array(), 'terms' ); + $terms = apply_filters('get_terms', array(), $taxonomies, $args); + return $terms; + } + + if ( $child_of ) { + $children = _get_term_hierarchy($taxonomies[0]); + if ( ! empty($children) ) + $terms = & _get_term_children($child_of, $terms, $taxonomies[0]); + } + + // Update term counts to include children. + if ( $pad_counts && 'all' == $fields ) + _pad_term_counts($terms, $taxonomies[0]); + + // Make sure we show empty categories that have children. + if ( $hierarchical && $hide_empty && is_array($terms) ) { + foreach ( $terms as $k => $term ) { + if ( ! $term->count ) { + $children = _get_term_children($term->term_id, $terms, $taxonomies[0]); + if( is_array($children) ) + foreach ( $children as $child ) + if ( $child->count ) + continue 2; + + // It really is empty + unset($terms[$k]); + } + } + } + reset ( $terms ); + + $_terms = array(); + if ( 'ids' == $fields ) { + while ( $term = array_shift($terms) ) + $_terms[] = $term->term_id; + $terms = $_terms; + } elseif ( 'names' == $fields ) { + while ( $term = array_shift($terms) ) + $_terms[] = $term->name; + $terms = $_terms; + } + + if ( 0 < $number && intval(@count($terms)) > $number ) { + $terms = array_slice($terms, $offset, $number); + } + + wp_cache_add( $cache_key, $terms, 'terms' ); + + $terms = apply_filters('get_terms', $terms, $taxonomies, $args); + return $terms; +} + +/** + * Check if Term exists. + * + * Returns the index of a defined term, or 0 (false) if the term doesn't exist. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * + * @param int|string $term The term to check + * @param string $taxonomy The taxonomy name to use + * @param int $parent ID of parent term under which to confine the exists search. + * @return mixed Get the term id or Term Object, if exists. + */ +function is_term($term, $taxonomy = '', $parent = 0) { + global $wpdb; + + $select = "SELECT term_id FROM $wpdb->terms as t WHERE "; + $tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE "; + + if ( is_int($term) ) { + if ( 0 == $term ) + return 0; + $where = 't.term_id = %d'; + if ( !empty($taxonomy) ) + return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A ); + else + return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) ); + } + + $term = trim( stripslashes( $term ) ); + + if ( '' === $slug = sanitize_title($term) ) + return 0; + + $where = 't.slug = %s'; + $else_where = 't.name = %s'; + $where_fields = array($slug); + $else_where_fields = array($term); + if ( !empty($taxonomy) ) { + $parent = (int) $parent; + if ( $parent > 0 ) { + $where_fields[] = $parent; + $else_where_fields[] = $parent; + $where .= ' AND tt.parent = %d'; + $else_where .= ' AND tt.parent = %d'; + } + + $where_fields[] = $taxonomy; + $else_where_fields[] = $taxonomy; + + if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) ) + return $result; + + return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A); + } + + if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) ) + return $result; + + return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) ); +} + +/** + * Sanitize Term all fields. + * + * Relys on sanitize_term_field() to sanitize the term. The difference is that + * this function will sanitize all fields. The context is based + * on sanitize_term_field(). + * + * The $term is expected to be either an array or an object. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses sanitize_term_field Used to sanitize all fields in a term + * + * @param array|object $term The term to check + * @param string $taxonomy The taxonomy name to use + * @param string $context Default is 'display'. + * @return array|object Term with all fields sanitized + */ +function sanitize_term($term, $taxonomy, $context = 'display') { + + if ( 'raw' == $context ) + return $term; + + $fields = array('term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group'); + + $do_object = false; + if ( is_object($term) ) + $do_object = true; + + $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0); + + foreach ( (array) $fields as $field ) { + if ( $do_object ) { + if ( isset($term->$field) ) + $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context); + } else { + if ( isset($term[$field]) ) + $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context); + } + } + + if ( $do_object ) + $term->filter = $context; + else + $term['filter'] = $context; + + return $term; +} + +/** + * Cleanse the field value in the term based on the context. + * + * Passing a term field value through the function should be assumed to have + * cleansed the value for whatever context the term field is going to be used. + * + * If no context or an unsupported context is given, then default filters will + * be applied. + * + * There are enough filters for each context to support a custom filtering + * without creating your own filter function. Simply create a function that + * hooks into the filter you need. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * + * @param string $field Term field to sanitize + * @param string $value Search for this term value + * @param int $term_id Term ID + * @param string $taxonomy Taxonomy Name + * @param string $context Either edit, db, display, attribute, or js. + * @return mixed sanitized field + */ +function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) { + if ( 'parent' == $field || 'term_id' == $field || 'count' == $field || 'term_group' == $field ) { + $value = (int) $value; + if ( $value < 0 ) + $value = 0; + } + + if ( 'raw' == $context ) + return $value; + + if ( 'edit' == $context ) { + $value = apply_filters("edit_term_$field", $value, $term_id, $taxonomy); + $value = apply_filters("edit_${taxonomy}_$field", $value, $term_id); + if ( 'description' == $field ) + $value = format_to_edit($value); + else + $value = esc_attr($value); + } else if ( 'db' == $context ) { + $value = apply_filters("pre_term_$field", $value, $taxonomy); + $value = apply_filters("pre_${taxonomy}_$field", $value); + // Back compat filters + if ( 'slug' == $field ) + $value = apply_filters('pre_category_nicename', $value); + + } else if ( 'rss' == $context ) { + $value = apply_filters("term_${field}_rss", $value, $taxonomy); + $value = apply_filters("${taxonomy}_${field}_rss", $value); + } else { + // Use display filters by default. + $value = apply_filters("term_$field", $value, $term_id, $taxonomy, $context); + $value = apply_filters("${taxonomy}_$field", $value, $term_id, $context); + } + + if ( 'attribute' == $context ) + $value = esc_attr($value); + else if ( 'js' == $context ) + $value = esc_js($value); + + return $value; +} + +/** + * Count how many terms are in Taxonomy. + * + * Default $args is 'ignore_empty' which can be 'ignore_empty=true' + * or array('ignore_empty' => true);. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array. + * + * @param string $taxonomy Taxonomy name + * @param array|string $args Overwrite defaults + * @return int How many terms are in $taxonomy + */ +function wp_count_terms( $taxonomy, $args = array() ) { + global $wpdb; + + $defaults = array('ignore_empty' => false); + $args = wp_parse_args($args, $defaults); + extract($args, EXTR_SKIP); + + $where = ''; + if ( $ignore_empty ) + $where = 'AND count > 0'; + + return $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE taxonomy = %s $where", $taxonomy) ); +} + +/** + * Will unlink the term from the taxonomy. + * + * Will remove the term's relationship to the taxonomy, not the term or taxonomy + * itself. The term and taxonomy will still exist. Will require the term's + * object ID to perform the operation. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @param int $object_id The term Object Id that refers to the term + * @param string|array $taxonomy List of Taxonomy Names or single Taxonomy name. + */ +function wp_delete_object_term_relationships( $object_id, $taxonomies ) { + global $wpdb; + + $object_id = (int) $object_id; + + if ( !is_array($taxonomies) ) + $taxonomies = array($taxonomies); + + foreach ( (array) $taxonomies as $taxonomy ) { + $tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids'); + $in_tt_ids = "'" . implode("', '", $tt_ids) . "'"; + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id) ); + wp_update_term_count($tt_ids, $taxonomy); + } +} + +/** + * Removes a term from the database. + * + * If the term is a parent of other terms, then the children will be updated to + * that term's parent. + * + * The $args 'default' will only override the terms found, if there is only one + * term found. Any other and the found terms are used. + * + * The $args 'force_default' will force the term supplied as default to be + * assigned even if the object was not going to be termless + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses do_action() Calls both 'delete_term' and 'delete_$taxonomy' action + * hooks, passing term object, term id. 'delete_term' gets an additional + * parameter with the $taxonomy parameter. + * + * @param int $term Term ID + * @param string $taxonomy Taxonomy Name + * @param array|string $args Optional. Change 'default' term id and override found term ids. + * @return bool|WP_Error Returns false if not term; true if completes delete action. + */ +function wp_delete_term( $term, $taxonomy, $args = array() ) { + global $wpdb; + + $term = (int) $term; + + if ( ! $ids = is_term($term, $taxonomy) ) + return false; + if ( is_wp_error( $ids ) ) + return $ids; + + $tt_id = $ids['term_taxonomy_id']; + + $defaults = array(); + $args = wp_parse_args($args, $defaults); + extract($args, EXTR_SKIP); + + if ( isset($default) ) { + $default = (int) $default; + if ( ! is_term($default, $taxonomy) ) + unset($default); + } + + // Update children to point to new parent + if ( is_taxonomy_hierarchical($taxonomy) ) { + $term_obj = get_term($term, $taxonomy); + if ( is_wp_error( $term_obj ) ) + return $term_obj; + $parent = $term_obj->parent; + + $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) ); + } + + $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) ); + + foreach ( (array) $objects as $object ) { + $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none')); + if ( 1 == count($terms) && isset($default) ) { + $terms = array($default); + } else { + $terms = array_diff($terms, array($term)); + if (isset($default) && isset($force_default) && $force_default) + $terms = array_merge($terms, array($default)); + } + $terms = array_map('intval', $terms); + wp_set_object_terms($object, $terms, $taxonomy); + } + + $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_taxonomy WHERE term_taxonomy_id = %d", $tt_id ) ); + + // Delete the term if no taxonomies use it. + if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) ) + $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->terms WHERE term_id = %d", $term) ); + + clean_term_cache($term, $taxonomy); + + do_action('delete_term', $term, $tt_id, $taxonomy); + do_action("delete_$taxonomy", $term, $tt_id); + + return true; +} + +/** + * Retrieves the terms associated with the given object(s), in the supplied taxonomies. + * + * The following information has to do the $args parameter and for what can be + * contained in the string or array of that parameter, if it exists. + * + * The first argument is called, 'orderby' and has the default value of 'name'. + * The other value that is supported is 'count'. + * + * The second argument is called, 'order' and has the default value of 'ASC'. + * The only other value that will be acceptable is 'DESC'. + * + * The final argument supported is called, 'fields' and has the default value of + * 'all'. There are multiple other options that can be used instead. Supported + * values are as follows: 'all', 'ids', 'names', and finally + * 'all_with_object_id'. + * + * The fields argument also decides what will be returned. If 'all' or + * 'all_with_object_id' is choosen or the default kept intact, then all matching + * terms objects will be returned. If either 'ids' or 'names' is used, then an + * array of all matching term ids or term names will be returned respectively. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @param int|array $object_id The id of the object(s) to retrieve. + * @param string|array $taxonomies The taxonomies to retrieve terms from. + * @param array|string $args Change what is returned + * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if $taxonomy does not exist. + */ +function wp_get_object_terms($object_ids, $taxonomies, $args = array()) { + global $wpdb; + + if ( !is_array($taxonomies) ) + $taxonomies = array($taxonomies); + + foreach ( (array) $taxonomies as $taxonomy ) { + if ( ! is_taxonomy($taxonomy) ) + return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy')); + } + + if ( !is_array($object_ids) ) + $object_ids = array($object_ids); + $object_ids = array_map('intval', $object_ids); + + $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all'); + $args = wp_parse_args( $args, $defaults ); + + $terms = array(); + if ( count($taxonomies) > 1 ) { + foreach ( $taxonomies as $index => $taxonomy ) { + $t = get_taxonomy($taxonomy); + if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) { + unset($taxonomies[$index]); + $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args))); + } + } + } else { + $t = get_taxonomy($taxonomies[0]); + if ( isset($t->args) && is_array($t->args) ) + $args = array_merge($args, $t->args); + } + + extract($args, EXTR_SKIP); + + if ( 'count' == $orderby ) + $orderby = 'tt.count'; + else if ( 'name' == $orderby ) + $orderby = 't.name'; + else if ( 'slug' == $orderby ) + $orderby = 't.slug'; + else if ( 'term_group' == $orderby ) + $orderby = 't.term_group'; + else if ( 'term_order' == $orderby ) + $orderby = 'tr.term_order'; + else if ( 'none' == $orderby ) { + $orderby = ''; + $order = ''; + } else { + $orderby = 't.term_id'; + } + + // tt_ids queries can only be none or tr.term_taxonomy_id + if ( ('tt_ids' == $fields) && !empty($orderby) ) + $orderby = 'tr.term_taxonomy_id'; + + if ( !empty($orderby) ) + $orderby = "ORDER BY $orderby"; + + $taxonomies = "'" . implode("', '", $taxonomies) . "'"; + $object_ids = implode(', ', $object_ids); + + $select_this = ''; + if ( 'all' == $fields ) + $select_this = 't.*, tt.*'; + else if ( 'ids' == $fields ) + $select_this = 't.term_id'; + else if ( 'names' == $fields ) + $select_this = 't.name'; + else if ( 'all_with_object_id' == $fields ) + $select_this = 't.*, tt.*, tr.object_id'; + + $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order"; + + if ( 'all' == $fields || 'all_with_object_id' == $fields ) { + $terms = array_merge($terms, $wpdb->get_results($query)); + update_term_cache($terms); + } else if ( 'ids' == $fields || 'names' == $fields ) { + $terms = array_merge($terms, $wpdb->get_col($query)); + } else if ( 'tt_ids' == $fields ) { + $terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order"); + } + + if ( ! $terms ) + $terms = array(); + + return apply_filters('wp_get_object_terms', $terms, $object_ids, $taxonomies, $args); +} + +/** + * Adds a new term to the database. Optionally marks it as an alias of an existing term. + * + * Error handling is assigned for the nonexistance of the $taxonomy and $term + * parameters before inserting. If both the term id and taxonomy exist + * previously, then an array will be returned that contains the term id and the + * contents of what is returned. The keys of the array are 'term_id' and + * 'term_taxonomy_id' containing numeric values. + * + * It is assumed that the term does not yet exist or the above will apply. The + * term will be first added to the term table and then related to the taxonomy + * if everything is well. If everything is correct, then several actions will be + * run prior to a filter and then several actions will be run after the filter + * is run. + * + * The arguments decide how the term is handled based on the $args parameter. + * The following is a list of the available overrides and the defaults. + * + * 'alias_of'. There is no default, but if added, expected is the slug that the + * term will be an alias of. Expected to be a string. + * + * 'description'. There is no default. If exists, will be added to the database + * along with the term. Expected to be a string. + * + * 'parent'. Expected to be numeric and default is 0 (zero). Will assign value + * of 'parent' to the term. + * + * 'slug'. Expected to be a string. There is no default. + * + * If 'slug' argument exists then the slug will be checked to see if it is not + * a valid term. If that check succeeds (it is not a valid term), then it is + * added and the term id is given. If it fails, then a check is made to whether + * the taxonomy is hierarchical and the parent argument is not empty. If the + * second check succeeds, the term will be inserted and the term id will be + * given. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @uses do_action() Calls 'create_term' hook with the term id and taxonomy id as parameters. + * @uses do_action() Calls 'create_$taxonomy' hook with term id and taxonomy id as parameters. + * @uses apply_filters() Calls 'term_id_filter' hook with term id and taxonomy id as parameters. + * @uses do_action() Calls 'created_term' hook with the term id and taxonomy id as parameters. + * @uses do_action() Calls 'created_$taxonomy' hook with term id and taxonomy id as parameters. + * + * @param int|string $term The term to add or update. + * @param string $taxonomy The taxonomy to which to add the term + * @param array|string $args Change the values of the inserted term + * @return array|WP_Error The Term ID and Term Taxonomy ID + */ +function wp_insert_term( $term, $taxonomy, $args = array() ) { + global $wpdb; + + if ( ! is_taxonomy($taxonomy) ) + return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); + + if ( is_int($term) && 0 == $term ) + return new WP_Error('invalid_term_id', __('Invalid term ID')); + + if ( '' == trim($term) ) + return new WP_Error('empty_term_name', __('A name is required for this term')); + + $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => ''); + $args = wp_parse_args($args, $defaults); + $args['name'] = $term; + $args['taxonomy'] = $taxonomy; + $args = sanitize_term($args, $taxonomy, 'db'); + extract($args, EXTR_SKIP); + + // expected_slashed ($name) + $name = stripslashes($name); + $description = stripslashes($description); + + if ( empty($slug) ) + $slug = sanitize_title($name); + + $term_group = 0; + if ( $alias_of ) { + $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) ); + if ( $alias->term_group ) { + // The alias we want is already in a group, so let's use that one. + $term_group = $alias->term_group; + } else { + // The alias isn't in a group, so let's create a new one and firstly add the alias term to it. + $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1; + $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) ); + } + } + + if ( ! $term_id = is_term($slug) ) { + if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) + return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error); + $term_id = (int) $wpdb->insert_id; + } else if ( is_taxonomy_hierarchical($taxonomy) && !empty($parent) ) { + // If the taxonomy supports hierarchy and the term has a parent, make the slug unique + // by incorporating parent slugs. + $slug = wp_unique_term_slug($slug, (object) $args); + if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) + return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error); + $term_id = (int) $wpdb->insert_id; + } + + if ( empty($slug) ) { + $slug = sanitize_title($slug, $term_id); + $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) ); + } + + $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) ); + + if ( !empty($tt_id) ) + return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id); + + $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) ); + $tt_id = (int) $wpdb->insert_id; + + do_action("create_term", $term_id, $tt_id); + do_action("create_$taxonomy", $term_id, $tt_id); + + $term_id = apply_filters('term_id_filter', $term_id, $tt_id); + + clean_term_cache($term_id, $taxonomy); + + do_action("created_term", $term_id, $tt_id); + do_action("created_$taxonomy", $term_id, $tt_id); + + return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id); +} + +/** + * Create Term and Taxonomy Relationships. + * + * Relates an object (post, link etc) to a term and taxonomy type. Creates the + * term and taxonomy relationship if it doesn't already exist. Creates a term if + * it doesn't exist (using the slug). + * + * A relationship means that the term is grouped in or belongs to the taxonomy. + * A term has no meaning until it is given context by defining which taxonomy it + * exists under. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @param int $object_id The object to relate to. + * @param array|int|string $term The slug or id of the term, will replace all existing + * related terms in this taxonomy. + * @param array|string $taxonomy The context in which to relate the term to the object. + * @param bool $append If false will delete difference of terms. + * @return array|WP_Error Affected Term IDs + */ +function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) { + global $wpdb; + + $object_id = (int) $object_id; + + if ( ! is_taxonomy($taxonomy) ) + return new WP_Error('invalid_taxonomy', __('Invalid Taxonomy')); + + if ( !is_array($terms) ) + $terms = array($terms); + + if ( ! $append ) + $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none')); + + $tt_ids = array(); + $term_ids = array(); + + foreach ( (array) $terms as $term) { + if ( !strlen(trim($term)) ) + continue; + + if ( !$term_info = is_term($term, $taxonomy) ) + $term_info = wp_insert_term($term, $taxonomy); + if ( is_wp_error($term_info) ) + return $term_info; + $term_ids[] = $term_info['term_id']; + $tt_id = $term_info['term_taxonomy_id']; + $tt_ids[] = $tt_id; + + if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) ) + continue; + $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) ); + } + + wp_update_term_count($tt_ids, $taxonomy); + + if ( ! $append ) { + $delete_terms = array_diff($old_tt_ids, $tt_ids); + if ( $delete_terms ) { + $in_delete_terms = "'" . implode("', '", $delete_terms) . "'"; + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_delete_terms)", $object_id) ); + wp_update_term_count($delete_terms, $taxonomy); + } + } + + $t = get_taxonomy($taxonomy); + if ( ! $append && isset($t->sort) && $t->sort ) { + $values = array(); + $term_order = 0; + $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, 'fields=tt_ids'); + foreach ( $tt_ids as $tt_id ) + if ( in_array($tt_id, $final_tt_ids) ) + $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order); + if ( $values ) + $wpdb->query("INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join(',', $values) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)"); + } + + do_action('set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append); + return $tt_ids; +} + +/** + * Will make slug unique, if it isn't already. + * + * The $slug has to be unique global to every taxonomy, meaning that one + * taxonomy term can't have a matching slug with another taxonomy term. Each + * slug has to be globally unique for every taxonomy. + * + * The way this works is that if the taxonomy that the term belongs to is + * heirarchical and has a parent, it will append that parent to the $slug. + * + * If that still doesn't return an unique slug, then it try to append a number + * until it finds a number that is truely unique. + * + * The only purpose for $term is for appending a parent, if one exists. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @param string $slug The string that will be tried for a unique slug + * @param object $term The term object that the $slug will belong too + * @return string Will return a true unique slug. + */ +function wp_unique_term_slug($slug, $term) { + global $wpdb; + + // If the taxonomy supports hierarchy and the term has a parent, make the slug unique + // by incorporating parent slugs. + if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) { + $the_parent = $term->parent; + while ( ! empty($the_parent) ) { + $parent_term = get_term($the_parent, $term->taxonomy); + if ( is_wp_error($parent_term) || empty($parent_term) ) + break; + $slug .= '-' . $parent_term->slug; + if ( empty($parent_term->parent) ) + break; + $the_parent = $parent_term->parent; + } + } + + // If we didn't get a unique slug, try appending a number to make it unique. + if ( !empty($args['term_id']) ) + $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $args['term_id'] ); + else + $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug ); + + if ( $wpdb->get_var( $query ) ) { + $num = 2; + do { + $alt_slug = $slug . "-$num"; + $num++; + $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) ); + } while ( $slug_check ); + $slug = $alt_slug; + } + + return $slug; +} + +/** + * Update term based on arguments provided. + * + * The $args will indiscriminately override all values with the same field name. + * Care must be taken to not override important information need to update or + * update will fail (or perhaps create a new term, neither would be acceptable). + * + * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not + * defined in $args already. + * + * 'alias_of' will create a term group, if it doesn't already exist, and update + * it for the $term. + * + * If the 'slug' argument in $args is missing, then the 'name' in $args will be + * used. It should also be noted that if you set 'slug' and it isn't unique then + * a WP_Error will be passed back. If you don't pass any slug, then a unique one + * will be created for you. + * + * For what can be overrode in $args, check the term scheme can contain and stay + * away from the term keys. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses $wpdb + * @uses do_action() Will call both 'edit_term' and 'edit_$taxonomy' twice. + * @uses apply_filters() Will call the 'term_id_filter' filter and pass the term + * id and taxonomy id. + * + * @param int $term_id The ID of the term + * @param string $taxonomy The context in which to relate the term to the object. + * @param array|string $args Overwrite term field values + * @return array|WP_Error Returns Term ID and Taxonomy Term ID + */ +function wp_update_term( $term_id, $taxonomy, $args = array() ) { + global $wpdb; + + if ( ! is_taxonomy($taxonomy) ) + return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); + + $term_id = (int) $term_id; + + // First, get all of the original args + $term = get_term ($term_id, $taxonomy, ARRAY_A); + + if ( is_wp_error( $term ) ) + return $term; + + // Escape data pulled from DB. + $term = add_magic_quotes($term); + + // Merge old and new args with new args overwriting old ones. + $args = array_merge($term, $args); + + $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => ''); + $args = wp_parse_args($args, $defaults); + $args = sanitize_term($args, $taxonomy, 'db'); + extract($args, EXTR_SKIP); + + // expected_slashed ($name) + $name = stripslashes($name); + $description = stripslashes($description); + + if ( '' == trim($name) ) + return new WP_Error('empty_term_name', __('A name is required for this term')); + + $empty_slug = false; + if ( empty($slug) ) { + $empty_slug = true; + $slug = sanitize_title($name); + } + + if ( $alias_of ) { + $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) ); + if ( $alias->term_group ) { + // The alias we want is already in a group, so let's use that one. + $term_group = $alias->term_group; + } else { + // The alias isn't in a group, so let's create a new one and firstly add the alias term to it. + $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1; + $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) ); + } + } + + // Check for duplicate slug + $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) ); + if ( $id && ($id != $term_id) ) { + // If an empty slug was passed or the parent changed, reset the slug to something unique. + // Otherwise, bail. + if ( $empty_slug || ( $parent != $term->parent) ) + $slug = wp_unique_term_slug($slug, (object) $args); + else + return new WP_Error('duplicate_term_slug', sprintf(__('The slug “%s” is already in use by another term'), $slug)); + } + + $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) ); + + if ( empty($slug) ) { + $slug = sanitize_title($name, $term_id); + $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) ); + } + + $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) ); + + $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) ); + + do_action("edit_term", $term_id, $tt_id); + do_action("edit_$taxonomy", $term_id, $tt_id); + + $term_id = apply_filters('term_id_filter', $term_id, $tt_id); + + clean_term_cache($term_id, $taxonomy); + + do_action("edited_term", $term_id, $tt_id); + do_action("edited_$taxonomy", $term_id, $tt_id); + + return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id); +} + +/** + * Enable or disable term counting. + * + * @since 2.5.0 + * + * @param bool $defer Optional. Enable if true, disable if false. + * @return bool Whether term counting is enabled or disabled. + */ +function wp_defer_term_counting($defer=null) { + static $_defer = false; + + if ( is_bool($defer) ) { + $_defer = $defer; + // flush any deferred counts + if ( !$defer ) + wp_update_term_count( null, null, true ); + } + + return $_defer; +} + +/** + * Updates the amount of terms in taxonomy. + * + * If there is a taxonomy callback applyed, then it will be called for updating + * the count. + * + * The default action is to count what the amount of terms have the relationship + * of term ID. Once that is done, then update the database. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @param int|array $terms The term_taxonomy_id of the terms + * @param string $taxonomy The context of the term. + * @return bool If no terms will return false, and if successful will return true. + */ +function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) { + static $_deferred = array(); + + if ( $do_deferred ) { + foreach ( (array) array_keys($_deferred) as $tax ) { + wp_update_term_count_now( $_deferred[$tax], $tax ); + unset( $_deferred[$tax] ); + } + } + + if ( empty($terms) ) + return false; + + if ( !is_array($terms) ) + $terms = array($terms); + + if ( wp_defer_term_counting() ) { + if ( !isset($_deferred[$taxonomy]) ) + $_deferred[$taxonomy] = array(); + $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) ); + return true; + } + + return wp_update_term_count_now( $terms, $taxonomy ); +} + +/** + * Perform term count update immediately. + * + * @since 2.5.0 + * + * @param array $terms The term_taxonomy_id of terms to update. + * @param string $taxonomy The context of the term. + * @return bool Always true when complete. + */ +function wp_update_term_count_now( $terms, $taxonomy ) { + global $wpdb; + + $terms = array_map('intval', $terms); + + $taxonomy = get_taxonomy($taxonomy); + if ( !empty($taxonomy->update_count_callback) ) { + call_user_func($taxonomy->update_count_callback, $terms); + } else { + // Default count updater + foreach ( (array) $terms as $term) { + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term) ); + $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) ); + } + + } + + clean_term_cache($terms); + + return true; +} + +// +// Cache +// + + +/** + * Removes the taxonomy relationship to terms from the cache. + * + * Will remove the entire taxonomy relationship containing term $object_id. The + * term IDs have to exist within the taxonomy $object_type for the deletion to + * take place. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @see get_object_taxonomies() for more on $object_type + * @uses do_action() Will call action hook named, 'clean_object_term_cache' after completion. + * Passes, function params in same order. + * + * @param int|array $object_ids Single or list of term object ID(s) + * @param array|string $object_type The taxonomy object type + */ +function clean_object_term_cache($object_ids, $object_type) { + if ( !is_array($object_ids) ) + $object_ids = array($object_ids); + + foreach ( $object_ids as $id ) + foreach ( get_object_taxonomies($object_type) as $taxonomy ) + wp_cache_delete($id, "{$taxonomy}_relationships"); + + do_action('clean_object_term_cache', $object_ids, $object_type); +} + + +/** + * Will remove all of the term ids from the cache. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses $wpdb + * + * @param int|array $ids Single or list of Term IDs + * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context. + */ +function clean_term_cache($ids, $taxonomy = '') { + global $wpdb; + static $cleaned = array(); + + if ( !is_array($ids) ) + $ids = array($ids); + + $taxonomies = array(); + // If no taxonomy, assume tt_ids. + if ( empty($taxonomy) ) { + $tt_ids = implode(', ', $ids); + $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)"); + foreach ( (array) $terms as $term ) { + $taxonomies[] = $term->taxonomy; + wp_cache_delete($term->term_id, $term->taxonomy); + } + $taxonomies = array_unique($taxonomies); + } else { + foreach ( $ids as $id ) { + wp_cache_delete($id, $taxonomy); + } + $taxonomies = array($taxonomy); + } + + foreach ( $taxonomies as $taxonomy ) { + if ( isset($cleaned[$taxonomy]) ) + continue; + $cleaned[$taxonomy] = true; + wp_cache_delete('all_ids', $taxonomy); + wp_cache_delete('get', $taxonomy); + delete_option("{$taxonomy}_children"); + } + + wp_cache_set('last_changed', time(), 'terms'); + + do_action('clean_term_cache', $ids, $taxonomy); +} + + +/** + * Retrieves the taxonomy relationship to the term object id. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @uses wp_cache_get() Retrieves taxonomy relationship from cache + * + * @param int|array $id Term object ID + * @param string $taxonomy Taxonomy Name + * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id. + */ +function &get_object_term_cache($id, $taxonomy) { + $cache = wp_cache_get($id, "{$taxonomy}_relationships"); + return $cache; +} + + +/** + * Updates the cache for Term ID(s). + * + * Will only update the cache for terms not already cached. + * + * The $object_ids expects that the ids be separated by commas, if it is a + * string. + * + * It should be noted that update_object_term_cache() is very time extensive. It + * is advised that the function is not called very often or at least not for a + * lot of terms that exist in a lot of taxonomies. The amount of time increases + * for each term and it also increases for each taxonomy the term belongs to. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * @uses wp_get_object_terms() Used to get terms from the database to update + * + * @param string|array $object_ids Single or list of term object ID(s) + * @param array|string $object_type The taxonomy object type + * @return null|bool Null value is given with empty $object_ids. False if + */ +function update_object_term_cache($object_ids, $object_type) { + if ( empty($object_ids) ) + return; + + if ( !is_array($object_ids) ) + $object_ids = explode(',', $object_ids); + + $object_ids = array_map('intval', $object_ids); + + $taxonomies = get_object_taxonomies($object_type); + + $ids = array(); + foreach ( (array) $object_ids as $id ) { + foreach ( $taxonomies as $taxonomy ) { + if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) { + $ids[] = $id; + break; + } + } + } + + if ( empty( $ids ) ) + return false; + + $terms = wp_get_object_terms($ids, $taxonomies, 'fields=all_with_object_id'); + + $object_terms = array(); + foreach ( (array) $terms as $term ) + $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term; + + foreach ( $ids as $id ) { + foreach ( $taxonomies as $taxonomy ) { + if ( ! isset($object_terms[$id][$taxonomy]) ) { + if ( !isset($object_terms[$id]) ) + $object_terms[$id] = array(); + $object_terms[$id][$taxonomy] = array(); + } + } + } + + foreach ( $object_terms as $id => $value ) { + foreach ( $value as $taxonomy => $terms ) { + wp_cache_set($id, $terms, "{$taxonomy}_relationships"); + } + } +} + + +/** + * Updates Terms to Taxonomy in cache. + * + * @package WordPress + * @subpackage Taxonomy + * @since 2.3.0 + * + * @param array $terms List of Term objects to change + * @param string $taxonomy Optional. Update Term to this taxonomy in cache + */ +function update_term_cache($terms, $taxonomy = '') { + foreach ( (array) $terms as $term ) { + $term_taxonomy = $taxonomy; + if ( empty($term_taxonomy) ) + $term_taxonomy = $term->taxonomy; + + wp_cache_add($term->term_id, $term, $term_taxonomy); + } +} + +// +// Private +// + + +/** + * Retrieves children of taxonomy as Term IDs. + * + * @package WordPress + * @subpackage Taxonomy + * @access private + * @since 2.3.0 + * + * @uses update_option() Stores all of the children in "$taxonomy_children" + * option. That is the name of the taxonomy, immediately followed by '_children'. + * + * @param string $taxonomy Taxonomy Name + * @return array Empty if $taxonomy isn't hierarachical or returns children as Term IDs. + */ +function _get_term_hierarchy($taxonomy) { + if ( !is_taxonomy_hierarchical($taxonomy) ) + return array(); + $children = get_option("{$taxonomy}_children"); + if ( is_array($children) ) + return $children; + + $children = array(); + $terms = get_terms($taxonomy, 'get=all'); + foreach ( $terms as $term ) { + if ( $term->parent > 0 ) + $children[$term->parent][] = $term->term_id; + } + update_option("{$taxonomy}_children", $children); + + return $children; +} + + +/** + * Get the subset of $terms that are descendants of $term_id. + * + * If $terms is an array of objects, then _get_term_children returns an array of objects. + * If $terms is an array of IDs, then _get_term_children returns an array of IDs. + * + * @package WordPress + * @subpackage Taxonomy + * @access private + * @since 2.3.0 + * + * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id. + * @param array $terms The set of terms---either an array of term objects or term IDs---from which those that are descendants of $term_id will be chosen. + * @param string $taxonomy The taxonomy which determines the hierarchy of the terms. + * @return array The subset of $terms that are descendants of $term_id. + */ +function &_get_term_children($term_id, $terms, $taxonomy) { + $empty_array = array(); + if ( empty($terms) ) + return $empty_array; + + $term_list = array(); + $has_children = _get_term_hierarchy($taxonomy); + + if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) ) + return $empty_array; + + foreach ( (array) $terms as $term ) { + $use_id = false; + if ( !is_object($term) ) { + $term = get_term($term, $taxonomy); + if ( is_wp_error( $term ) ) + return $term; + $use_id = true; + } + + if ( $term->term_id == $term_id ) + continue; + + if ( $term->parent == $term_id ) { + if ( $use_id ) + $term_list[] = $term->term_id; + else + $term_list[] = $term; + + if ( !isset($has_children[$term->term_id]) ) + continue; + + if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) ) + $term_list = array_merge($term_list, $children); + } + } + + return $term_list; +} + + +/** + * Add count of children to parent count. + * + * Recalculates term counts by including items from child terms. Assumes all + * relevant children are already in the $terms argument. + * + * @package WordPress + * @subpackage Taxonomy + * @access private + * @since 2.3.0 + * @uses $wpdb + * + * @param array $terms List of Term IDs + * @param string $taxonomy Term Context + * @return null Will break from function if conditions are not met. + */ +function _pad_term_counts(&$terms, $taxonomy) { + global $wpdb; + + // This function only works for hierarchical taxonomies like post categories. + if ( !is_taxonomy_hierarchical( $taxonomy ) ) + return; + + $term_hier = _get_term_hierarchy($taxonomy); + + if ( empty($term_hier) ) + return; + + $term_items = array(); + + foreach ( (array) $terms as $key => $term ) { + $terms_by_id[$term->term_id] = & $terms[$key]; + $term_ids[$term->term_taxonomy_id] = $term->term_id; + } + + // Get the object and term ids and stick them in a lookup table + $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (".join(',', array_keys($term_ids)).") AND post_type = 'post' AND post_status = 'publish'"); + foreach ( $results as $row ) { + $id = $term_ids[$row->term_taxonomy_id]; + $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1; + } + + // Touch every ancestor's lookup row for each post in each term + foreach ( $term_ids as $term_id ) { + $child = $term_id; + while ( $parent = $terms_by_id[$child]->parent ) { + if ( !empty($term_items[$term_id]) ) + foreach ( $term_items[$term_id] as $item_id => $touches ) { + $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1; + } + $child = $parent; + } + } + + // Transfer the touched cells + foreach ( (array) $term_items as $id => $items ) + if ( isset($terms_by_id[$id]) ) + $terms_by_id[$id]->count = count($items); +} + +// +// Default callbacks +// + +/** + * Will update term count based on posts. + * + * Private function for the default callback for post_tag and category + * taxonomies. + * + * @package WordPress + * @subpackage Taxonomy + * @access private + * @since 2.3.0 + * @uses $wpdb + * + * @param array $terms List of Term taxonomy IDs + */ +function _update_post_term_count( $terms ) { + global $wpdb; + + foreach ( (array) $terms as $term ) { + $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type = 'post' AND term_taxonomy_id = %d", $term ) ); + $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) ); + } +} + + +/** + * Generates a permalink for a taxonomy term archive. + * + * @since 2.5.0 + * + * @param object|int|string $term + * @param string $taxonomy + * @return string HTML link to taxonomy term archive + */ +function get_term_link( $term, $taxonomy ) { + global $wp_rewrite; + + if ( !is_object($term) ) { + if ( is_int($term) ) { + $term = &get_term($term, $taxonomy); + } else { + $term = &get_term_by('slug', $term, $taxonomy); + } + } + if ( is_wp_error( $term ) ) + return $term; + + // use legacy functions for core taxonomies until they are fully plugged in + if ( $taxonomy == 'category' ) + return get_category_link((int) $term->term_id); + if ( $taxonomy == 'post_tag' ) + return get_tag_link((int) $term->term_id); + + $termlink = $wp_rewrite->get_extra_permastruct($taxonomy); + + $slug = $term->slug; + + if ( empty($termlink) ) { + $file = get_option('home') . '/'; + $t = get_taxonomy($taxonomy); + if ( $t->query_var ) + $termlink = "$file?$t->query_var=$slug"; + else + $termlink = "$file?taxonomy=$taxonomy&term=$slug"; + } else { + $termlink = str_replace("%$taxonomy%", $slug, $termlink); + $termlink = get_option('home') . user_trailingslashit($termlink, 'category'); + } + return apply_filters('term_link', $termlink, $term, $taxonomy); +} + +/** + * Display the taxonomies of a post with available options. + * + * This function can be used within the loop to display the taxonomies for a + * post without specifying the Post ID. You can also use it outside the Loop to + * display the taxonomies for a specific post. + * + * The available defaults are: + * 'post' : default is 0. The post ID to get taxonomies of. + * 'before' : default is empty string. Display before taxonomies list. + * 'sep' : default is empty string. Separate every taxonomy with value in this. + * 'after' : default is empty string. Display this after the taxonomies list. + * + * @since 2.5.0 + * @uses get_the_taxonomies() + * + * @param array $args Override the defaults. + */ +function the_taxonomies($args = array()) { + $defaults = array( + 'post' => 0, + 'before' => '', + 'sep' => ' ', + 'after' => '', + ); + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + echo $before . join($sep, get_the_taxonomies($post)) . $after; +} + +/** + * Retrieve all taxonomies associated with a post. + * + * This function can be used within the loop. It will also return an array of + * the taxonomies with links to the taxonomy and name. + * + * @since 2.5.0 + * + * @param int $post Optional. Post ID or will use Global Post ID (in loop). + * @return array + */ +function get_the_taxonomies($post = 0) { + if ( is_int($post) ) + $post =& get_post($post); + elseif ( !is_object($post) ) + $post =& $GLOBALS['post']; + + $taxonomies = array(); + + if ( !$post ) + return $taxonomies; + + $template = apply_filters('taxonomy_template', '%s: %l.'); + + foreach ( get_object_taxonomies($post) as $taxonomy ) { + $t = (array) get_taxonomy($taxonomy); + if ( empty($t['label']) ) + $t['label'] = $taxonomy; + if ( empty($t['args']) ) + $t['args'] = array(); + if ( empty($t['template']) ) + $t['template'] = $template; + + $terms = get_object_term_cache($post->ID, $taxonomy); + if ( empty($terms) ) + $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']); + + $links = array(); + + foreach ( $terms as $term ) + $links[] = "$term->name"; + + if ( $links ) + $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms); + } + return $taxonomies; +} + +/** + * Retrieve all taxonomies of a post with just the names. + * + * @since 2.5.0 + * @uses get_object_taxonomies() + * + * @param int $post Optional. Post ID + * @return array + */ +function get_post_taxonomies($post = 0) { + $post =& get_post($post); + + return get_object_taxonomies($post); +} + +/** + * Determine if the given object is associated with any of the given terms. + * + * The given terms are checked against the object's terms' term_ids, names and slugs. + * Terms given as integers will only be checked against the object's terms' term_ids. + * If no terms are given, determines if object is associated with any terms in the given taxonomy. + * + * @since 2.7.0 + * @uses get_object_term_cache() + * @uses wp_get_object_terms() + * + * @param int $object_id. ID of the object (post ID, link ID, ...) + * @param string $taxonomy. Single taxonomy name + * @param int|string|array $terms Optional. Term term_id, name, slug or array of said + * @return bool|WP_Error. WP_Error on input error. + */ +function is_object_in_term( $object_id, $taxonomy, $terms = null ) { + if ( !$object_id = (int) $object_id ) + return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) ); + + $object_terms = get_object_term_cache( $object_id, $taxonomy ); + if ( empty( $object_terms ) ) + $object_terms = wp_get_object_terms( $object_id, $taxonomy ); + + if ( is_wp_error( $object_terms ) ) + return $object_terms; + if ( empty( $object_terms ) ) + return false; + if ( empty( $terms ) ) + return ( !empty( $object_terms ) ); + + $terms = (array) $terms; + + if ( $ints = array_filter( $terms, 'is_int' ) ) + $strs = array_diff( $terms, $ints ); + else + $strs =& $terms; + + foreach ( $object_terms as $object_term ) { + if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id + if ( $strs ) { + if ( in_array( $object_term->term_id, $strs ) ) return true; + if ( in_array( $object_term->name, $strs ) ) return true; + if ( in_array( $object_term->slug, $strs ) ) return true; + } + } + + return false; +} + +?> diff --git a/wp-includes/template-loader.php b/wp-includes/template-loader.php new file mode 100644 index 0000000..9fd4ffe --- /dev/null +++ b/wp-includes/template-loader.php @@ -0,0 +1,78 @@ + \ No newline at end of file diff --git a/wp-includes/theme.php b/wp-includes/theme.php new file mode 100644 index 0000000..9d56a64 --- /dev/null +++ b/wp-includes/theme.php @@ -0,0 +1,1137 @@ +text_direction) && file_exists("$dir/{$wp_locale->text_direction}.css") ) + $stylesheet_uri = "$stylesheet_dir_uri/{$wp_locale->text_direction}.css"; + else + $stylesheet_uri = ''; + return apply_filters('locale_stylesheet_uri', $stylesheet_uri, $stylesheet_dir_uri); +} + +/** + * Retrieve name of the current theme. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'template' filter on template option. + * + * @return string Template name. + */ +function get_template() { + return apply_filters('template', get_option('template')); +} + +/** + * Retrieve current theme directory. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'template_directory' filter on template directory path and template name. + * + * @return string Template directory path. + */ +function get_template_directory() { + $template = get_template(); + $template_dir = get_theme_root() . "/$template"; + return apply_filters('template_directory', $template_dir, $template); +} + +/** + * Retrieve theme directory URI. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'template_directory_uri' filter on template directory URI path and template name. + * + * @return string Template directory URI. + */ +function get_template_directory_uri() { + $template = get_template(); + $template_dir_uri = get_theme_root_uri() . "/$template"; + return apply_filters('template_directory_uri', $template_dir_uri, $template); +} + +/** + * Retrieve theme data from parsed theme file. + * + * The description will have the tags filtered with the following HTML elements + * whitelisted. The 'a' element with the href and title + * attributes. The abbr element with the title attribute. The + * acronym element with the title attribute allowed. The + * code, em, and strong elements also allowed. + * + * The style.css file must contain theme name, theme URI, and description. The + * data can also contain author URI, author, template (parent template), + * version, status, and finally tags. Some of these are not used by WordPress + * administration panels, but are used by theme directory web sites which list + * the theme. + * + * @since 1.5.0 + * + * @param string $theme_file Theme file path. + * @return array Theme data. + */ +function get_theme_data( $theme_file ) { + $themes_allowed_tags = array( + 'a' => array( + 'href' => array(),'title' => array() + ), + 'abbr' => array( + 'title' => array() + ), + 'acronym' => array( + 'title' => array() + ), + 'code' => array(), + 'em' => array(), + 'strong' => array() + ); + + $theme_data = implode( '', file( $theme_file ) ); + $theme_data = str_replace ( '\r', '\n', $theme_data ); + if ( preg_match( '|Theme Name:(.*)$|mi', $theme_data, $theme_name ) ) + $name = $theme = wp_kses( _cleanup_header_comment($theme_name[1]), $themes_allowed_tags ); + else + $name = $theme = ''; + + if ( preg_match( '|Theme URI:(.*)$|mi', $theme_data, $theme_uri ) ) + $theme_uri = esc_url( _cleanup_header_comment($theme_uri[1]) ); + else + $theme_uri = ''; + + if ( preg_match( '|Description:(.*)$|mi', $theme_data, $description ) ) + $description = wptexturize( wp_kses( _cleanup_header_comment($description[1]), $themes_allowed_tags ) ); + else + $description = ''; + + if ( preg_match( '|Author URI:(.*)$|mi', $theme_data, $author_uri ) ) + $author_uri = esc_url( _cleanup_header_comment($author_uri[1]) ); + else + $author_uri = ''; + + if ( preg_match( '|Template:(.*)$|mi', $theme_data, $template ) ) + $template = wp_kses( _cleanup_header_comment($template[1]), $themes_allowed_tags ); + else + $template = ''; + + if ( preg_match( '|Version:(.*)|i', $theme_data, $version ) ) + $version = wp_kses( _cleanup_header_comment($version[1]), $themes_allowed_tags ); + else + $version = ''; + + if ( preg_match('|Status:(.*)|i', $theme_data, $status) ) + $status = wp_kses( _cleanup_header_comment($status[1]), $themes_allowed_tags ); + else + $status = 'publish'; + + if ( preg_match('|Tags:(.*)|i', $theme_data, $tags) ) + $tags = array_map( 'trim', explode( ',', wp_kses( _cleanup_header_comment($tags[1]), array() ) ) ); + else + $tags = array(); + + if ( preg_match( '|Author:(.*)$|mi', $theme_data, $author_name ) ) { + if ( empty( $author_uri ) ) { + $author = wp_kses( _cleanup_header_comment($author_name[1]), $themes_allowed_tags ); + } else { + $author = sprintf( '%3$s', $author_uri, __( 'Visit author homepage' ), wp_kses( _cleanup_header_comment($author_name[1]), $themes_allowed_tags ) ); + } + } else { + $author = __('Anonymous'); + } + + return array( 'Name' => $name, 'Title' => $theme, 'URI' => $theme_uri, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template, 'Status' => $status, 'Tags' => $tags ); +} + +/** + * Retrieve list of themes with theme data in theme directory. + * + * The theme is broken, if it doesn't have a parent theme and is missing either + * style.css and, or index.php. If the theme has a parent theme then it is + * broken, if it is missing style.css; index.php is optional. The broken theme + * list is saved in the {@link $wp_broken_themes} global, which is displayed on + * the theme list in the administration panels. + * + * @since 1.5.0 + * @global array $wp_broken_themes Stores the broken themes. + * @global array $wp_themes Stores the working themes. + * + * @return array Theme list with theme data. + */ +function get_themes() { + global $wp_themes, $wp_broken_themes; + + if ( isset($wp_themes) ) + return $wp_themes; + + $themes = array(); + $wp_broken_themes = array(); + $theme_loc = $theme_root = get_theme_root(); + if ( '/' != WP_CONTENT_DIR ) // don't want to replace all forward slashes, see Trac #4541 + $theme_loc = str_replace(WP_CONTENT_DIR, '', $theme_root); + + // Files in wp-content/themes directory and one subdir down + $themes_dir = @ opendir($theme_root); + if ( !$themes_dir ) + return false; + + while ( ($theme_dir = readdir($themes_dir)) !== false ) { + if ( is_dir($theme_root . '/' . $theme_dir) && is_readable($theme_root . '/' . $theme_dir) ) { + if ( $theme_dir{0} == '.' || $theme_dir == '..' || $theme_dir == 'CVS' ) + continue; + $stylish_dir = @ opendir($theme_root . '/' . $theme_dir); + $found_stylesheet = false; + while ( ($theme_file = readdir($stylish_dir)) !== false ) { + if ( $theme_file == 'style.css' ) { + $theme_files[] = $theme_dir . '/' . $theme_file; + $found_stylesheet = true; + break; + } + } + @closedir($stylish_dir); + if ( !$found_stylesheet ) { // look for themes in that dir + $subdir = "$theme_root/$theme_dir"; + $subdir_name = $theme_dir; + $theme_subdir = @ opendir( $subdir ); + while ( ($theme_dir = readdir($theme_subdir)) !== false ) { + if ( is_dir( $subdir . '/' . $theme_dir) && is_readable($subdir . '/' . $theme_dir) ) { + if ( $theme_dir{0} == '.' || $theme_dir == '..' || $theme_dir == 'CVS' ) + continue; + $stylish_dir = @ opendir($subdir . '/' . $theme_dir); + $found_stylesheet = false; + while ( ($theme_file = readdir($stylish_dir)) !== false ) { + if ( $theme_file == 'style.css' ) { + $theme_files[] = $subdir_name . '/' . $theme_dir . '/' . $theme_file; + $found_stylesheet = true; + break; + } + } + @closedir($stylish_dir); + } + } + @closedir($theme_subdir); + $wp_broken_themes[$theme_dir] = array('Name' => $theme_dir, 'Title' => $theme_dir, 'Description' => __('Stylesheet is missing.')); + } + } + } + if ( is_dir( $theme_dir ) ) + @closedir( $theme_dir ); + + if ( !$themes_dir || !$theme_files ) + return $themes; + + sort($theme_files); + + foreach ( (array) $theme_files as $theme_file ) { + if ( !is_readable("$theme_root/$theme_file") ) { + $wp_broken_themes[$theme_file] = array('Name' => $theme_file, 'Title' => $theme_file, 'Description' => __('File not readable.')); + continue; + } + + $theme_data = get_theme_data("$theme_root/$theme_file"); + + $name = $theme_data['Name']; + $title = $theme_data['Title']; + $description = wptexturize($theme_data['Description']); + $version = $theme_data['Version']; + $author = $theme_data['Author']; + $template = $theme_data['Template']; + $stylesheet = dirname($theme_file); + + $screenshot = false; + foreach ( array('png', 'gif', 'jpg', 'jpeg') as $ext ) { + if (file_exists("$theme_root/$stylesheet/screenshot.$ext")) { + $screenshot = "screenshot.$ext"; + break; + } + } + + if ( empty($name) ) { + $name = dirname($theme_file); + $title = $name; + } + + if ( empty($template) ) { + if ( file_exists(dirname("$theme_root/$theme_file/index.php")) ) + $template = dirname($theme_file); + else + continue; + } + + $template = trim($template); + + if ( !file_exists("$theme_root/$template/index.php") ) { + $parent_dir = dirname(dirname($theme_file)); + if ( file_exists("$theme_root/$parent_dir/$template/index.php") ) { + $template = "$parent_dir/$template"; + } else { + $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.')); + continue; + } + } + + $stylesheet_files = array(); + $template_files = array(); + + $stylesheet_dir = @ dir("$theme_root/$stylesheet"); + if ( $stylesheet_dir ) { + while ( ($file = $stylesheet_dir->read()) !== false ) { + if ( !preg_match('|^\.+$|', $file) ) { + if ( preg_match('|\.css$|', $file) ) + $stylesheet_files[] = "$theme_loc/$stylesheet/$file"; + elseif ( preg_match('|\.php$|', $file) ) + $template_files[] = "$theme_loc/$stylesheet/$file"; + } + } + @ $stylesheet_dir->close(); + } + + $template_dir = @ dir("$theme_root/$template"); + if ( $template_dir ) { + while ( ($file = $template_dir->read()) !== false ) { + if ( preg_match('|^\.+$|', $file) ) + continue; + if ( preg_match('|\.php$|', $file) ) { + $template_files[] = "$theme_loc/$template/$file"; + } elseif ( is_dir("$theme_root/$template/$file") ) { + $template_subdir = @ dir("$theme_root/$template/$file"); + while ( ($subfile = $template_subdir->read()) !== false ) { + if ( preg_match('|^\.+$|', $subfile) ) + continue; + if ( preg_match('|\.php$|', $subfile) ) + $template_files[] = "$theme_loc/$template/$file/$subfile"; + } + @ $template_subdir->close(); + } + } + @ $template_dir->close(); + } + + $template_dir = dirname($template_files[0]); + $stylesheet_dir = dirname($stylesheet_files[0]); + + if ( empty($template_dir) ) + $template_dir = '/'; + if ( empty($stylesheet_dir) ) + $stylesheet_dir = '/'; + + // Check for theme name collision. This occurs if a theme is copied to + // a new theme directory and the theme header is not updated. Whichever + // theme is first keeps the name. Subsequent themes get a suffix applied. + // The Default and Classic themes always trump their pretenders. + if ( isset($themes[$name]) ) { + if ( ('WordPress Default' == $name || 'WordPress Classic' == $name) && + ('default' == $stylesheet || 'classic' == $stylesheet) ) { + // If another theme has claimed to be one of our default themes, move + // them aside. + $suffix = $themes[$name]['Stylesheet']; + $new_name = "$name/$suffix"; + $themes[$new_name] = $themes[$name]; + $themes[$new_name]['Name'] = $new_name; + } else { + $name = "$name/$stylesheet"; + } + } + + $themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template, 'Stylesheet' => $stylesheet, 'Template Files' => $template_files, 'Stylesheet Files' => $stylesheet_files, 'Template Dir' => $template_dir, 'Stylesheet Dir' => $stylesheet_dir, 'Status' => $theme_data['Status'], 'Screenshot' => $screenshot, 'Tags' => $theme_data['Tags']); + } + + // Resolve theme dependencies. + $theme_names = array_keys($themes); + + foreach ( (array) $theme_names as $theme_name ) { + $themes[$theme_name]['Parent Theme'] = ''; + if ( $themes[$theme_name]['Stylesheet'] != $themes[$theme_name]['Template'] ) { + foreach ( (array) $theme_names as $parent_theme_name ) { + if ( ($themes[$parent_theme_name]['Stylesheet'] == $themes[$parent_theme_name]['Template']) && ($themes[$parent_theme_name]['Template'] == $themes[$theme_name]['Template']) ) { + $themes[$theme_name]['Parent Theme'] = $themes[$parent_theme_name]['Name']; + break; + } + } + } + } + + $wp_themes = $themes; + + return $themes; +} + +/** + * Retrieve theme data. + * + * @since 1.5.0 + * + * @param string $theme Theme name. + * @return array|null Null, if theme name does not exist. Theme data, if exists. + */ +function get_theme($theme) { + $themes = get_themes(); + + if ( array_key_exists($theme, $themes) ) + return $themes[$theme]; + + return null; +} + +/** + * Retrieve current theme display name. + * + * If the 'current_theme' option has already been set, then it will be returned + * instead. If it is not set, then each theme will be iterated over until both + * the current stylesheet and current template name. + * + * @since 1.5.0 + * + * @return string + */ +function get_current_theme() { + if ( $theme = get_option('current_theme') ) + return $theme; + + $themes = get_themes(); + $theme_names = array_keys($themes); + $current_template = get_option('template'); + $current_stylesheet = get_option('stylesheet'); + $current_theme = 'WordPress Default'; + + if ( $themes ) { + foreach ( (array) $theme_names as $theme_name ) { + if ( $themes[$theme_name]['Stylesheet'] == $current_stylesheet && + $themes[$theme_name]['Template'] == $current_template ) { + $current_theme = $themes[$theme_name]['Name']; + break; + } + } + } + + update_option('current_theme', $current_theme); + + return $current_theme; +} + +/** + * Retrieve path to themes directory. + * + * Does not have trailing slash. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'theme_root' filter on path. + * + * @return string Theme path. + */ +function get_theme_root() { + return apply_filters('theme_root', WP_CONTENT_DIR . "/themes"); +} + +/** + * Retrieve URI for themes directory. + * + * Does not have trailing slash. + * + * @since 1.5.0 + * + * @return string Themes URI. + */ +function get_theme_root_uri() { + return apply_filters('theme_root_uri', content_url('themes'), get_option('siteurl')); +} + +/** + * Retrieve path to file without the use of extension. + * + * Used to quickly retrieve the path of file without including the file + * extension. It will also check the parent template, if the file exists, with + * the use of {@link locate_template()}. Allows for more generic file location + * without the use of the other get_*_template() functions. + * + * Can be used with include() or require() to retrieve path. + * + * if( '' != get_query_template( '404' ) ) + * include( get_query_template( '404' ) ); + * + * or the same can be accomplished with + * + * if( '' != get_404_template() ) + * include( get_404_template() ); + * + * + * @since 1.5.0 + * + * @param string $type Filename without extension. + * @return string Full path to file. + */ +function get_query_template($type) { + $type = preg_replace( '|[^a-z0-9-]+|', '', $type ); + return apply_filters("{$type}_template", locate_template(array("{$type}.php"))); +} + +/** + * Retrieve path of 404 template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_404_template() { + return get_query_template('404'); +} + +/** + * Retrieve path of archive template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_archive_template() { + return get_query_template('archive'); +} + +/** + * Retrieve path of author template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_author_template() { + return get_query_template('author'); +} + +/** + * Retrieve path of category template in current or parent template. + * + * Works by retrieving the current category ID, for example 'category-1.php' and + * will fallback to category.php template, if the ID category file doesn't + * exist. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'category_template' on file path of category template. + * + * @return string + */ +function get_category_template() { + $template = locate_template(array("category-" . absint( get_query_var('cat') ) . '.php', 'category.php')); + return apply_filters('category_template', $template); +} + +/** + * Retrieve path of tag template in current or parent template. + * + * Works by retrieving the current tag name, for example 'tag-wordpress.php' and will + * fallback to tag.php template, if the name tag file doesn't exist. + * + * @since 2.3.0 + * @uses apply_filters() Calls 'tag_template' on file path of tag template. + * + * @return string + */ +function get_tag_template() { + $template = locate_template(array("tag-" . get_query_var('tag') . '.php', 'tag.php')); + return apply_filters('tag_template', $template); +} + +/** + * Retrieve path of taxonomy template in current or parent template. + * + * Retrieves the taxonomy and term, if term is available. The template is + * prepended with 'taxonomy-' and followed by both the taxonomy string and + * the taxonomy string followed by a dash and then followed by the term. + * + * The taxonomy and term template is checked and used first, if it exists. + * Second, just the taxonomy template is checked, and then finally, taxonomy.php + * template is used. If none of the files exist, then it will fall back on to + * index.php. + * + * @since unknown (2.6.0 most likely) + * @uses apply_filters() Calls 'taxonomy_template' filter on found path. + * + * @return string + */ +function get_taxonomy_template() { + $taxonomy = get_query_var('taxonomy'); + $term = get_query_var('term'); + + $templates = array(); + if ( $taxonomy && $term ) + $templates[] = "taxonomy-$taxonomy-$term.php"; + if ( $taxonomy ) + $templates[] = "taxonomy-$taxonomy.php"; + + $templates[] = "taxonomy.php"; + + $template = locate_template($templates); + return apply_filters('taxonomy_template', $template); +} + +/** + * Retrieve path of date template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_date_template() { + return get_query_template('date'); +} + +/** + * Retrieve path of home template in current or parent template. + * + * Attempts to locate 'home.php' first before falling back to 'index.php'. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'home_template' on file path of home template. + * + * @return string + */ +function get_home_template() { + $template = locate_template(array('home.php', 'index.php')); + return apply_filters('home_template', $template); +} + +/** + * Retrieve path of page template in current or parent template. + * + * First attempt is to look for the file in the '_wp_page_template' page meta + * data. The second attempt, if the first has a file and is not empty, is to + * look for 'page.php'. + * + * @since 1.5.0 + * + * @return string + */ +function get_page_template() { + global $wp_query; + + $id = (int) $wp_query->post->ID; + $template = get_post_meta($id, '_wp_page_template', true); + + if ( 'default' == $template ) + $template = ''; + + $templates = array(); + if ( !empty($template) && !validate_file($template) ) + $templates[] = $template; + + $templates[] = "page.php"; + + return apply_filters('page_template', locate_template($templates)); +} + +/** + * Retrieve path of paged template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_paged_template() { + return get_query_template('paged'); +} + +/** + * Retrieve path of search template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_search_template() { + return get_query_template('search'); +} + +/** + * Retrieve path of single template in current or parent template. + * + * @since 1.5.0 + * + * @return string + */ +function get_single_template() { + return get_query_template('single'); +} + +/** + * Retrieve path of attachment template in current or parent template. + * + * The attachment path first checks if the first part of the mime type exists. + * The second check is for the second part of the mime type. The last check is + * for both types separated by an underscore. If neither are found then the file + * 'attachment.php' is checked and returned. + * + * Some examples for the 'text/plain' mime type are 'text.php', 'plain.php', and + * finally 'text_plain.php'. + * + * @since 2.0.0 + * + * @return string + */ +function get_attachment_template() { + global $posts; + $type = explode('/', $posts[0]->post_mime_type); + if ( $template = get_query_template($type[0]) ) + return $template; + elseif ( $template = get_query_template($type[1]) ) + return $template; + elseif ( $template = get_query_template("$type[0]_$type[1]") ) + return $template; + else + return get_query_template('attachment'); +} + +/** + * Retrieve path of comment popup template in current or parent template. + * + * Checks for comment popup template in current template, if it exists or in the + * parent template. If it doesn't exist, then it retrieves the comment-popup.php + * file from the default theme. The default theme must then exist for it to + * work. + * + * @since 1.5.0 + * @uses apply_filters() Calls 'comments_popup_template' filter on path. + * + * @return string + */ +function get_comments_popup_template() { + $template = locate_template(array("comments-popup.php")); + if ('' == $template) + $template = get_theme_root() . '/default/comments-popup.php'; + + return apply_filters('comments_popup_template', $template); +} + +/** + * Retrieve the name of the highest priority template file that exists. + * + * Searches in the STYLESHEETPATH before TEMPLATEPATH so that themes which + * inherit from a parent theme can just overload one file. + * + * @since 2.7.0 + * + * @param array $template_names Array of template files to search for in priority order. + * @param bool $load If true the template file will be loaded if it is found. + * @return string The template filename if one is located. + */ +function locate_template($template_names, $load = false) { + if (!is_array($template_names)) + return ''; + + $located = ''; + foreach($template_names as $template_name) { + if ( file_exists(STYLESHEETPATH . '/' . $template_name)) { + $located = STYLESHEETPATH . '/' . $template_name; + break; + } else if ( file_exists(TEMPLATEPATH . '/' . $template_name) ) { + $located = TEMPLATEPATH . '/' . $template_name; + break; + } + } + + if ($load && '' != $located) + load_template($located); + + return $located; +} + +/** + * Require once the template file with WordPress environment. + * + * The globals are set up for the template file to ensure that the WordPress + * environment is available from within the function. The query variables are + * also available. + * + * @since 1.5.0 + * + * @param string $_template_file Path to template file. + */ +function load_template($_template_file) { + global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID; + + if ( is_array($wp_query->query_vars) ) + extract($wp_query->query_vars, EXTR_SKIP); + + require_once($_template_file); +} + +/** + * Display localized stylesheet link element. + * + * @since 2.1.0 + */ +function locale_stylesheet() { + $stylesheet = get_locale_stylesheet_uri(); + if ( empty($stylesheet) ) + return; + echo ''; +} + +/** + * Start preview theme output buffer. + * + * Will only preform task if the user has permissions and template and preview + * query variables exist. + * + * @since 2.5.0 + */ +function preview_theme() { + if ( ! (isset($_GET['template']) && isset($_GET['preview'])) ) + return; + + if ( !current_user_can( 'switch_themes' ) ) + return; + + $_GET['template'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['template']); + + if ( validate_file($_GET['template']) ) + return; + + add_filter( 'template', create_function('', "return '{$_GET['template']}';") ); + + if ( isset($_GET['stylesheet']) ) { + $_GET['stylesheet'] = preg_replace('|[^a-z0-9_./-]|i', '', $_GET['stylesheet']); + if ( validate_file($_GET['stylesheet']) ) + return; + add_filter( 'stylesheet', create_function('', "return '{$_GET['stylesheet']}';") ); + } + + // Prevent theme mods to current theme being used on theme being previewed + add_filter( 'pre_option_mods_' . get_current_theme(), create_function( '', "return array();" ) ); + + ob_start( 'preview_theme_ob_filter' ); +} +add_action('setup_theme', 'preview_theme'); + +/** + * Callback function for ob_start() to capture all links in the theme. + * + * @since unknown + * @access private + * + * @param string $content + * @return string + */ +function preview_theme_ob_filter( $content ) { + return preg_replace_callback( "|()|", 'preview_theme_ob_filter_callback', $content ); +} + +/** + * Manipulates preview theme links in order to control and maintain location. + * + * Callback function for preg_replace_callback() to accept and filter matches. + * + * @since unknown + * @access private + * + * @param array $matches + * @return string + */ +function preview_theme_ob_filter_callback( $matches ) { + if ( strpos($matches[4], 'onclick') !== false ) + $matches[4] = preg_replace('#onclick=([\'"]).*?(?. (? 1, 'template' => $_GET['template'], 'stylesheet' => @$_GET['stylesheet'] ), $matches[3] ); + if ( 0 === strpos($link, 'preview=1') ) + $link = "?$link"; + return $matches[1] . esc_attr( $link ) . $matches[4]; +} + +/** + * Switches current theme to new template and stylesheet names. + * + * @since unknown + * @uses do_action() Calls 'switch_theme' action on updated theme display name. + * + * @param string $template Template name + * @param string $stylesheet Stylesheet name. + */ +function switch_theme($template, $stylesheet) { + update_option('template', $template); + update_option('stylesheet', $stylesheet); + delete_option('current_theme'); + $theme = get_current_theme(); + do_action('switch_theme', $theme); +} + +/** + * Checks that current theme files 'index.php' and 'style.css' exists. + * + * Does not check the 'default' theme. The 'default' theme should always exist + * or should have another theme renamed to that template name and directory + * path. Will switch theme to default if current theme does not validate. + * You can use the 'validate_current_theme' filter to return FALSE to + * disable this functionality. + * + * @since 1.5.0 + * + * @return bool + */ +function validate_current_theme() { + // Don't validate during an install/upgrade. + if ( defined('WP_INSTALLING') || !apply_filters( 'validate_current_theme', true ) ) + return true; + + if ( get_template() != 'default' && !file_exists(get_template_directory() . '/index.php') ) { + switch_theme('default', 'default'); + return false; + } + + if ( get_stylesheet() != 'default' && !file_exists(get_template_directory() . '/style.css') ) { + switch_theme('default', 'default'); + return false; + } + + return true; +} + +/** + * Retrieve theme modification value for the current theme. + * + * If the modification name does not exist, then the $default will be passed + * through {@link http://php.net/sprintf sprintf()} PHP function with the first + * string the template directory URI and the second string the stylesheet + * directory URI. + * + * @since 2.1.0 + * @uses apply_filters() Calls 'theme_mod_$name' filter on the value. + * + * @param string $name Theme modification name. + * @param bool|string $default + * @return string + */ +function get_theme_mod($name, $default = false) { + $theme = get_current_theme(); + + $mods = get_option("mods_$theme"); + + if ( isset($mods[$name]) ) + return apply_filters( "theme_mod_$name", $mods[$name] ); + + return apply_filters( "theme_mod_$name", sprintf($default, get_template_directory_uri(), get_stylesheet_directory_uri()) ); +} + +/** + * Update theme modification value for the current theme. + * + * @since 2.1.0 + * + * @param string $name Theme modification name. + * @param string $value theme modification value. + */ +function set_theme_mod($name, $value) { + $theme = get_current_theme(); + + $mods = get_option("mods_$theme"); + + $mods[$name] = $value; + + update_option("mods_$theme", $mods); + wp_cache_delete("mods_$theme", 'options'); +} + +/** + * Remove theme modification name from current theme list. + * + * If removing the name also removes all elements, then the entire option will + * be removed. + * + * @since 2.1.0 + * + * @param string $name Theme modification name. + * @return null + */ +function remove_theme_mod( $name ) { + $theme = get_current_theme(); + + $mods = get_option("mods_$theme"); + + if ( !isset($mods[$name]) ) + return; + + unset($mods[$name]); + + if ( empty($mods) ) + return remove_theme_mods(); + + update_option("mods_$theme", $mods); + wp_cache_delete("mods_$theme", 'options'); +} + +/** + * Remove theme modifications option for current theme. + * + * @since 2.1.0 + */ +function remove_theme_mods() { + $theme = get_current_theme(); + + delete_option("mods_$theme"); +} + +/** + * Retrieve text color for custom header. + * + * @since 2.1.0 + * @uses HEADER_TEXTCOLOR + * + * @return string + */ +function get_header_textcolor() { + return get_theme_mod('header_textcolor', HEADER_TEXTCOLOR); +} + +/** + * Display text color for custom header. + * + * @since 2.1.0 + */ +function header_textcolor() { + echo get_header_textcolor(); +} + +/** + * Retrieve header image for custom header. + * + * @since 2.1.0 + * @uses HEADER_IMAGE + * + * @return string + */ +function get_header_image() { + return get_theme_mod('header_image', HEADER_IMAGE); +} + +/** + * Display header image path. + * + * @since 2.1.0 + */ +function header_image() { + echo get_header_image(); +} + +/** + * Add callbacks for image header display. + * + * The parameter $header_callback callback will be required to display the + * content for the 'wp_head' action. The parameter $admin_header_callback + * callback will be added to Custom_Image_Header class and that will be added + * to the 'admin_menu' action. + * + * @since 2.1.0 + * @uses Custom_Image_Header Sets up for $admin_header_callback for administration panel display. + * + * @param callback $header_callback Call on 'wp_head' action. + * @param callback $admin_header_callback Call on administration panels. + */ +function add_custom_image_header($header_callback, $admin_header_callback) { + if ( ! empty($header_callback) ) + add_action('wp_head', $header_callback); + + if ( ! is_admin() ) + return; + require_once(ABSPATH . 'wp-admin/custom-header.php'); + $GLOBALS['custom_image_header'] =& new Custom_Image_Header($admin_header_callback); + add_action('admin_menu', array(&$GLOBALS['custom_image_header'], 'init')); +} + +?> diff --git a/wp-includes/update.php b/wp-includes/update.php new file mode 100644 index 0000000..141cecf --- /dev/null +++ b/wp-includes/update.php @@ -0,0 +1,313 @@ +updates = array(); + $current->version_checked = $wp_version; + } + + $locale = apply_filters( 'core_version_check_locale', get_locale() ); + + // Update last_checked for current to prevent multiple blocking requests if request hangs + $current->last_checked = time(); + set_transient( 'update_core', $current ); + + if ( method_exists( $wpdb, 'db_version' ) ) + $mysql_version = preg_replace('/[^0-9.].*/', '', $wpdb->db_version($wpdb->users)); + else + $mysql_version = 'N/A'; + $local_package = isset( $wp_local_package )? $wp_local_package : ''; + $url = "http://api.wordpress.org/core/version-check/1.3/?version=$wp_version&php=$php_version&locale=$locale&mysql=$mysql_version&local_package=$local_package"; + + $options = array( + 'timeout' => 3, + 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) + ); + + $response = wp_remote_get($url, $options); + + if ( is_wp_error( $response ) ) + return false; + + if ( 200 != $response['response']['code'] ) + return false; + + $body = trim( $response['body'] ); + $body = str_replace(array("\r\n", "\r"), "\n", $body); + $new_options = array(); + foreach( explode( "\n\n", $body ) as $entry) { + $returns = explode("\n", $entry); + $new_option = new stdClass(); + $new_option->response = esc_attr( $returns[0] ); + if ( isset( $returns[1] ) ) + $new_option->url = esc_url( $returns[1] ); + if ( isset( $returns[2] ) ) + $new_option->package = esc_url( $returns[2] ); + if ( isset( $returns[3] ) ) + $new_option->current = esc_attr( $returns[3] ); + if ( isset( $returns[4] ) ) + $new_option->locale = esc_attr( $returns[4] ); + $new_options[] = $new_option; + } + + $updates = new stdClass(); + $updates->updates = $new_options; + $updates->last_checked = time(); + $updates->version_checked = $wp_version; + set_transient( 'update_core', $updates); +} + +/** + * Check plugin versions against the latest versions hosted on WordPress.org. + * + * The WordPress version, PHP version, and Locale is sent along with a list of + * all plugins installed. Checks against the WordPress server at + * api.wordpress.org. Will only check if WordPress isn't installing. + * + * @package WordPress + * @since 2.3.0 + * @uses $wp_version Used to notidy the WordPress version. + * + * @return mixed Returns null if update is unsupported. Returns false if check is too soon. + */ +function wp_update_plugins() { + global $wp_version; + + if ( defined('WP_INSTALLING') ) + return false; + + // If running blog-side, bail unless we've not checked in the last 12 hours + if ( !function_exists( 'get_plugins' ) ) + require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); + + $plugins = get_plugins(); + $active = get_option( 'active_plugins' ); + $current = get_transient( 'update_plugins' ); + if ( ! is_object($current) ) + $current = new stdClass; + + $new_option = new stdClass; + $new_option->last_checked = time(); + $timeout = 'load-plugins.php' == current_filter() ? 3600 : 43200; //Check for updated every 60 minutes if hitting the themes page, Else, check every 12 hours + $time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked ); + + $plugin_changed = false; + foreach ( $plugins as $file => $p ) { + $new_option->checked[ $file ] = $p['Version']; + + if ( !isset( $current->checked[ $file ] ) || strval($current->checked[ $file ]) !== strval($p['Version']) ) + $plugin_changed = true; + } + + if ( isset ( $current->response ) && is_array( $current->response ) ) { + foreach ( $current->response as $plugin_file => $update_details ) { + if ( ! isset($plugins[ $plugin_file ]) ) { + $plugin_changed = true; + break; + } + } + } + + // Bail if we've checked in the last 12 hours and if nothing has changed + if ( $time_not_changed && !$plugin_changed ) + return false; + + // Update last_checked for current to prevent multiple blocking requests if request hangs + $current->last_checked = time(); + set_transient( 'update_plugins', $current ); + + $to_send = (object)compact('plugins', 'active'); + + $options = array( + 'timeout' => 3, + 'body' => array( 'plugins' => serialize( $to_send ) ), + 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) + ); + + $raw_response = wp_remote_post('http://api.wordpress.org/plugins/update-check/1.0/', $options); + + if ( is_wp_error( $raw_response ) ) + return false; + + if( 200 != $raw_response['response']['code'] ) + return false; + + $response = unserialize( $raw_response['body'] ); + + if ( false !== $response ) + $new_option->response = $response; + else + $new_option->response = array(); + + set_transient( 'update_plugins', $new_option ); +} + +/** + * Check theme versions against the latest versions hosted on WordPress.org. + * + * A list of all themes installed in sent to WP. Checks against the + * WordPress server at api.wordpress.org. Will only check if WordPress isn't + * installing. + * + * @package WordPress + * @since 2.7.0 + * @uses $wp_version Used to notidy the WordPress version. + * + * @return mixed Returns null if update is unsupported. Returns false if check is too soon. + */ +function wp_update_themes( ) { + global $wp_version; + + if( defined( 'WP_INSTALLING' ) ) + return false; + + if( !function_exists( 'get_themes' ) ) + require_once( ABSPATH . 'wp-includes/theme.php' ); + + $installed_themes = get_themes( ); + $current_theme = get_transient( 'update_themes' ); + if ( ! is_object($current_theme) ) + $current_theme = new stdClass; + + $new_option = new stdClass; + $new_option->last_checked = time( ); + $timeout = 'load-themes.php' == current_filter() ? 3600 : 43200; //Check for updated every 60 minutes if hitting the themes page, Else, check every 12 hours + $time_not_changed = isset( $current_theme->last_checked ) && $timeout > ( time( ) - $current_theme->last_checked ); + + if( $time_not_changed ) + return false; + + // Update last_checked for current to prevent multiple blocking requests if request hangs + $current_theme->last_checked = time(); + set_transient( 'update_themes', $current_theme ); + + $current_theme->template = get_option( 'template' ); + + $themes = array( ); + $themes['current_theme'] = (array) $current_theme; + foreach( (array) $installed_themes as $theme_title => $theme ) { + $themes[$theme['Stylesheet']] = array( ); + + foreach( (array) $theme as $key => $value ) { + $themes[$theme['Stylesheet']][$key] = $value; + } + } + + $options = array( + 'timeout' => 3, + 'body' => array( 'themes' => serialize( $themes ) ), + 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) + ); + + $raw_response = wp_remote_post( 'http://api.wordpress.org/themes/update-check/1.0/', $options ); + + if( is_wp_error( $raw_response ) ) + return false; + + if( 200 != $raw_response['response']['code'] ) + return false; + + $response = unserialize( $raw_response['body'] ); + if( $response ) + $new_option->response = $response; + + set_transient( 'update_themes', $new_option ); +} + +function _maybe_update_core() { + global $wp_version; + + $current = get_transient( 'update_core' ); + + if ( isset( $current->last_checked ) && + 43200 > ( time() - $current->last_checked ) && + isset( $current->version_checked ) && + $current->version_checked == $wp_version ) + return; + + wp_version_check(); +} +/** + * Check the last time plugins were run before checking plugin versions. + * + * This might have been backported to WordPress 2.6.1 for performance reasons. + * This is used for the wp-admin to check only so often instead of every page + * load. + * + * @since 2.7.0 + * @access private + */ +function _maybe_update_plugins() { + $current = get_transient( 'update_plugins' ); + if ( isset( $current->last_checked ) && 43200 > ( time() - $current->last_checked ) ) + return; + wp_update_plugins(); +} + +/** + * Check themes versions only after a duration of time. + * + * This is for performance reasons to make sure that on the theme version + * checker is not run on every page load. + * + * @since 2.7.0 + * @access private + */ +function _maybe_update_themes( ) { + $current = get_transient( 'update_themes' ); + if( isset( $current->last_checked ) && 43200 > ( time( ) - $current->last_checked ) ) + return; + + wp_update_themes( ); +} + +add_action( 'admin_init', '_maybe_update_core' ); +add_action( 'wp_version_check', 'wp_version_check' ); + +add_action( 'load-plugins.php', 'wp_update_plugins' ); +add_action( 'load-update.php', 'wp_update_plugins' ); +add_action( 'admin_init', '_maybe_update_plugins' ); +add_action( 'wp_update_plugins', 'wp_update_plugins' ); + +add_action( 'load-themes.php', 'wp_update_themes' ); +add_action( 'load-update.php', 'wp_update_themes' ); +add_action( 'admin_init', '_maybe_update_themes' ); +add_action( 'wp_update_themes', 'wp_update_themes' ); + +if ( !wp_next_scheduled('wp_version_check') && !defined('WP_INSTALLING') ) + wp_schedule_event(time(), 'twicedaily', 'wp_version_check'); + +if ( !wp_next_scheduled('wp_update_plugins') && !defined('WP_INSTALLING') ) + wp_schedule_event(time(), 'twicedaily', 'wp_update_plugins'); + +if ( !wp_next_scheduled('wp_update_themes') && !defined('WP_INSTALLING') ) + wp_schedule_event(time(), 'twicedaily', 'wp_update_themes'); + +?> diff --git a/wp-includes/user.php b/wp-includes/user.php new file mode 100644 index 0000000..483b3bc --- /dev/null +++ b/wp-includes/user.php @@ -0,0 +1,603 @@ +get_error_codes() == array('empty_username', 'empty_password') ) { + $user = new WP_Error('', ''); + } + + return $user; + } + + wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie); + do_action('wp_login', $credentials['user_login']); + return $user; +} + + +/** + * Authenticate the user using the username and password. + */ +add_filter('authenticate', 'wp_authenticate_username_password', 20, 3); +function wp_authenticate_username_password($user, $username, $password) { + if ( is_a($user, 'WP_User') ) { return $user; } + + if ( empty($username) || empty($password) ) { + $error = new WP_Error(); + + if ( empty($username) ) + $error->add('empty_username', __('ERROR: The username field is empty.')); + + if ( empty($password) ) + $error->add('empty_password', __('ERROR: The password field is empty.')); + + return $error; + } + + $userdata = get_userdatabylogin($username); + + if ( !$userdata ) { + return new WP_Error('invalid_username', sprintf(__('ERROR: Invalid username. Lost your password?'), site_url('wp-login.php?action=lostpassword', 'login'))); + } + + $userdata = apply_filters('wp_authenticate_user', $userdata, $password); + if ( is_wp_error($userdata) ) { + return $userdata; + } + + if ( !wp_check_password($password, $userdata->user_pass, $userdata->ID) ) { + return new WP_Error('incorrect_password', sprintf(__('ERROR: Incorrect password. Lost your password?'), site_url('wp-login.php?action=lostpassword', 'login'))); + } + + $user = new WP_User($userdata->ID); + return $user; +} + +/** + * Authenticate the user using the WordPress auth cookie. + */ +function wp_authenticate_cookie($user, $username, $password) { + if ( is_a($user, 'WP_User') ) { return $user; } + + if ( empty($username) && empty($password) ) { + $user_id = wp_validate_auth_cookie(); + if ( $user_id ) + return new WP_User($user_id); + + global $auth_secure_cookie; + + if ( $auth_secure_cookie ) + $auth_cookie = SECURE_AUTH_COOKIE; + else + $auth_cookie = AUTH_COOKIE; + + if ( !empty($_COOKIE[$auth_cookie]) ) + return new WP_Error('expired_session', __('Please log in again.')); + + // If the cookie is not set, be silent. + } + + return $user; +} + +/** + * Retrieve user data based on field. + * + * Use get_profile() will make a database query to get the value of the table + * column. The value might be cached using the query cache, but care should be + * taken when using the function to not make a lot of queries for retrieving + * user profile information. + * + * If the $user parameter is not used, then the user will be retrieved from a + * cookie of the user. Therefore, if the cookie does not exist, then no value + * might be returned. Sanity checking must be done to ensure that when using + * get_profile() that empty/null/false values are handled and that something is + * at least displayed. + * + * @since 1.5.0 + * @uses $wpdb WordPress database object to create queries. + * + * @param string $field User field to retrieve. + * @param string $user Optional. User username. + * @return string The value in the field. + */ +function get_profile($field, $user = false) { + global $wpdb; + if ( !$user ) + $user = $wpdb->escape($_COOKIE[USER_COOKIE]); + return $wpdb->get_var( $wpdb->prepare("SELECT $field FROM $wpdb->users WHERE user_login = %s", $user) ); +} + +/** + * Number of posts user has written. + * + * @since 0.71 + * @uses $wpdb WordPress database object for queries. + * + * @param int $userid User ID. + * @return int Amount of posts user has written. + */ +function get_usernumposts($userid) { + global $wpdb; + $userid = (int) $userid; + $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = %d AND post_type = 'post' AND ", $userid) . get_private_posts_cap_sql('post')); + return apply_filters('get_usernumposts', $count, $userid); +} + +/** + * Check that the user login name and password is correct. + * + * @since 0.71 + * @todo xmlrpc only. Maybe move to xmlrpc.php. + * + * @param string $user_login User name. + * @param string $user_pass User password. + * @return bool False if does not authenticate, true if username and password authenticates. + */ +function user_pass_ok($user_login, $user_pass) { + $user = wp_authenticate($user_login, $user_pass); + if ( is_wp_error($user) ) + return false; + + return true; +} + +// +// User option functions +// + +/** + * Retrieve user option that can be either global, user, or blog. + * + * If the user ID is not given, then the current user will be used instead. If + * the user ID is given, then the user data will be retrieved. The filter for + * the result, will also pass the original option name and finally the user data + * object as the third parameter. + * + * The option will first check for the non-global name, then the global name, + * and if it still doesn't find it, it will try the blog option. The option can + * either be modified or set by a plugin. + * + * @since 2.0.0 + * @uses $wpdb WordPress database object for queries. + * @uses apply_filters() Calls 'get_user_option_$option' hook with result, + * option parameter, and user data object. + * + * @param string $option User option name. + * @param int $user Optional. User ID. + * @param bool $check_blog_options Whether to check for an option in the options table if a per-user option does not exist. Default is true. + * @return mixed + */ +function get_user_option( $option, $user = 0, $check_blog_options = true ) { + global $wpdb; + + $option = preg_replace('|[^a-z0-9_]|i', '', $option); + if ( empty($user) ) + $user = wp_get_current_user(); + else + $user = get_userdata($user); + + if ( isset( $user->{$wpdb->prefix . $option} ) ) // Blog specific + $result = $user->{$wpdb->prefix . $option}; + elseif ( isset( $user->{$option} ) ) // User specific and cross-blog + $result = $user->{$option}; + elseif ( $check_blog_options ) // Blog global + $result = get_option( $option ); + else + $result = false; + + return apply_filters("get_user_option_{$option}", $result, $option, $user); +} + +/** + * Update user option with global blog capability. + * + * User options are just like user metadata except that they have support for + * global blog options. If the 'global' parameter is false, which it is by default + * it will prepend the WordPress table prefix to the option name. + * + * @since 2.0.0 + * @uses $wpdb WordPress database object for queries + * + * @param int $user_id User ID + * @param string $option_name User option name. + * @param mixed $newvalue User option value. + * @param bool $global Optional. Whether option name is blog specific or not. + * @return unknown + */ +function update_user_option( $user_id, $option_name, $newvalue, $global = false ) { + global $wpdb; + if ( !$global ) + $option_name = $wpdb->prefix . $option_name; + return update_usermeta( $user_id, $option_name, $newvalue ); +} + +/** + * Get users for the blog. + * + * For setups that use the multi-blog feature. Can be used outside of the + * multi-blog feature. + * + * @since 2.2.0 + * @uses $wpdb WordPress database object for queries + * @uses $blog_id The Blog id of the blog for those that use more than one blog + * + * @param int $id Blog ID. + * @return array List of users that are part of that Blog ID + */ +function get_users_of_blog( $id = '' ) { + global $wpdb, $blog_id; + if ( empty($id) ) + $id = (int) $blog_id; + $users = $wpdb->get_results( "SELECT user_id, user_id AS ID, user_login, display_name, user_email, meta_value FROM $wpdb->users, $wpdb->usermeta WHERE {$wpdb->users}.ID = {$wpdb->usermeta}.user_id AND meta_key = '{$wpdb->prefix}capabilities' ORDER BY {$wpdb->usermeta}.user_id" ); + return $users; +} + +// +// User meta functions +// + +/** + * Remove user meta data. + * + * @since 2.0.0 + * @uses $wpdb WordPress database object for queries. + * + * @param int $user_id User ID. + * @param string $meta_key Metadata key. + * @param mixed $meta_value Metadata value. + * @return bool True deletion completed and false if user_id is not a number. + */ +function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) { + global $wpdb; + if ( !is_numeric( $user_id ) ) + return false; + $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); + + if ( is_array($meta_value) || is_object($meta_value) ) + $meta_value = serialize($meta_value); + $meta_value = trim( $meta_value ); + + if ( ! empty($meta_value) ) + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s AND meta_value = %s", $user_id, $meta_key, $meta_value) ); + else + $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); + + wp_cache_delete($user_id, 'users'); + + return true; +} + +/** + * Retrieve user metadata. + * + * If $user_id is not a number, then the function will fail over with a 'false' + * boolean return value. Other returned values depend on whether there is only + * one item to be returned, which be that single item type. If there is more + * than one metadata value, then it will be list of metadata values. + * + * @since 2.0.0 + * @uses $wpdb WordPress database object for queries. + * + * @param int $user_id User ID + * @param string $meta_key Optional. Metadata key. + * @return mixed + */ +function get_usermeta( $user_id, $meta_key = '') { + global $wpdb; + $user_id = (int) $user_id; + + if ( !$user_id ) + return false; + + if ( !empty($meta_key) ) { + $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); + $user = wp_cache_get($user_id, 'users'); + // Check the cached user object + if ( false !== $user && isset($user->$meta_key) ) + $metas = array($user->$meta_key); + else + $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); + } else { + $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d", $user_id) ); + } + + if ( empty($metas) ) { + if ( empty($meta_key) ) + return array(); + else + return ''; + } + + $metas = array_map('maybe_unserialize', $metas); + + if ( count($metas) == 1 ) + return $metas[0]; + else + return $metas; +} + +/** + * Update metadata of user. + * + * There is no need to serialize values, they will be serialized if it is + * needed. The metadata key can only be a string with underscores. All else will + * be removed. + * + * Will remove the metadata, if the meta value is empty. + * + * @since 2.0.0 + * @uses $wpdb WordPress database object for queries + * + * @param int $user_id User ID + * @param string $meta_key Metadata key. + * @param mixed $meta_value Metadata value. + * @return bool True on successful update, false on failure. + */ +function update_usermeta( $user_id, $meta_key, $meta_value ) { + global $wpdb; + if ( !is_numeric( $user_id ) ) + return false; + $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); + + /** @todo Might need fix because usermeta data is assumed to be already escaped */ + if ( is_string($meta_value) ) + $meta_value = stripslashes($meta_value); + $meta_value = maybe_serialize($meta_value); + + if (empty($meta_value)) { + return delete_usermeta($user_id, $meta_key); + } + + $cur = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); + if ( !$cur ) + $wpdb->insert($wpdb->usermeta, compact('user_id', 'meta_key', 'meta_value') ); + else if ( $cur->meta_value != $meta_value ) + $wpdb->update($wpdb->usermeta, compact('meta_value'), compact('user_id', 'meta_key') ); + else + return false; + + wp_cache_delete($user_id, 'users'); + + return true; +} + +// +// Private helper functions +// + +/** + * Setup global user vars. + * + * Used by set_current_user() for back compat. Might be deprecated in the + * future. + * + * @since 2.0.4 + * @global string $userdata User description. + * @global string $user_login The user username for logging in + * @global int $user_level The level of the user + * @global int $user_ID The ID of the user + * @global string $user_email The email address of the user + * @global string $user_url The url in the user's profile + * @global string $user_pass_md5 MD5 of the user's password + * @global string $user_identity The display name of the user + * + * @param int $user_id Optional. User ID to setup global data. + */ +function setup_userdata($user_id = '') { + global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity; + + if ( '' == $user_id ) + $user = wp_get_current_user(); + else + $user = new WP_User($user_id); + + if ( 0 == $user->ID ) + return; + + $userdata = $user->data; + $user_login = $user->user_login; + $user_level = (int) isset($user->user_level) ? $user->user_level : 0; + $user_ID = (int) $user->ID; + $user_email = $user->user_email; + $user_url = $user->user_url; + $user_pass_md5 = md5($user->user_pass); + $user_identity = $user->display_name; +} + +/** + * Create dropdown HTML content of users. + * + * The content can either be displayed, which it is by default or retrieved by + * setting the 'echo' argument. The 'include' and 'exclude' arguments do not + * need to be used; all users will be displayed in that case. Only one can be + * used, either 'include' or 'exclude', but not both. + * + * The available arguments are as follows: + *
      + *
    1. show_option_all - Text to show all and whether HTML option exists.
    2. + *
    3. show_option_none - Text for show none and whether HTML option exists. + *
    4. + *
    5. orderby - SQL order by clause for what order the users appear. Default is + * 'display_name'.
    6. + *
    7. order - Default is 'ASC'. Can also be 'DESC'.
    8. + *
    9. include - User IDs to include.
    10. + *
    11. exclude - User IDs to exclude.
    12. + *
    13. multi - Default is 'false'. Whether to skip the ID attribute on the 'select' element.
    14. + *
    15. show - Default is 'display_name'. User table column to display. If the selected item is empty then the user_login will be displayed in parentesis
    16. + *
    17. echo - Default is '1'. Whether to display or retrieve content.
    18. + *
    19. selected - Which User ID is selected.
    20. + *
    21. name - Default is 'user'. Name attribute of select element.
    22. + *
    23. class - Class attribute of select element.
    24. + *
    + * + * @since 2.3.0 + * @uses $wpdb WordPress database object for queries + * + * @param string|array $args Optional. Override defaults. + * @return string|null Null on display. String of HTML content on retrieve. + */ +function wp_dropdown_users( $args = '' ) { + global $wpdb; + $defaults = array( + 'show_option_all' => '', 'show_option_none' => '', + 'orderby' => 'display_name', 'order' => 'ASC', + 'include' => '', 'exclude' => '', 'multi' => 0, + 'show' => 'display_name', 'echo' => 1, + 'selected' => 0, 'name' => 'user', 'class' => '' + ); + + $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0; + + $r = wp_parse_args( $args, $defaults ); + extract( $r, EXTR_SKIP ); + + $query = "SELECT * FROM $wpdb->users"; + + $query_where = array(); + + if ( is_array($include) ) + $include = join(',', $include); + $include = preg_replace('/[^0-9,]/', '', $include); // (int) + if ( $include ) + $query_where[] = "ID IN ($include)"; + + if ( is_array($exclude) ) + $exclude = join(',', $exclude); + $exclude = preg_replace('/[^0-9,]/', '', $exclude); // (int) + if ( $exclude ) + $query_where[] = "ID NOT IN ($exclude)"; + + if ( $query_where ) + $query .= " WHERE " . join(' AND', $query_where); + + $query .= " ORDER BY $orderby $order"; + + $users = $wpdb->get_results( $query ); + + $output = ''; + if ( !empty($users) ) { + $id = $multi ? "" : "id='$name'"; + + $output = ""; + } + + $output = apply_filters('wp_dropdown_users', $output); + + if ( $echo ) + echo $output; + + return $output; +} + +/** + * Add user meta data as properties to given user object. + * + * The finished user data is cached, but the cache is not used to fill in the + * user data for the given object. Once the function has been used, the cache + * should be used to retrieve user data. The purpose seems then to be to ensure + * that the data in the object is always fresh. + * + * @access private + * @since 2.5.0 + * @uses $wpdb WordPress database object for queries + * + * @param object $user The user data object. + */ +function _fill_user( &$user ) { + global $wpdb; + + $show = $wpdb->hide_errors(); + $metavalues = $wpdb->get_results($wpdb->prepare("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = %d", $user->ID)); + $wpdb->show_errors($show); + + if ( $metavalues ) { + foreach ( (array) $metavalues as $meta ) { + $value = maybe_unserialize($meta->meta_value); + $user->{$meta->meta_key} = $value; + } + } + + $level = $wpdb->prefix . 'user_level'; + if ( isset( $user->{$level} ) ) + $user->user_level = $user->{$level}; + + // For backwards compat. + if ( isset($user->first_name) ) + $user->user_firstname = $user->first_name; + if ( isset($user->last_name) ) + $user->user_lastname = $user->last_name; + if ( isset($user->description) ) + $user->user_description = $user->description; + + wp_cache_add($user->ID, $user, 'users'); + wp_cache_add($user->user_login, $user->ID, 'userlogins'); + wp_cache_add($user->user_email, $user->ID, 'useremail'); + wp_cache_add($user->user_nicename, $user->ID, 'userslugs'); +} + +?> diff --git a/wp-includes/vars.php b/wp-includes/vars.php new file mode 100644 index 0000000..b66b313 --- /dev/null +++ b/wp-includes/vars.php @@ -0,0 +1,84 @@ + \ No newline at end of file diff --git a/wp-includes/version.php b/wp-includes/version.php new file mode 100644 index 0000000..22b8636 --- /dev/null +++ b/wp-includes/version.php @@ -0,0 +1,32 @@ +' . __('There are no options for this widget.') . '

    '; + return 'noform'; + } + + // Functions you'll need to call. + + /** + * PHP4 constructor + */ + function WP_Widget( $id_base = false, $name, $widget_options = array(), $control_options = array() ) { + $this->__construct( $id_base, $name, $widget_options, $control_options ); + } + + /** + * PHP5 constructor + * + * @param string $id_base Optional Base ID for the widget, lower case, + * if left empty a portion of the widget's class name will be used. Has to be unique. + * @param string $name Name for the widget displayed on the configuration page. + * @param array $widget_options Optional Passed to wp_register_sidebar_widget() + * - description: shown on the configuration page + * - classname + * @param array $control_options Optional Passed to wp_register_widget_control() + * - width: required if more than 250px + * - height: currently not used but may be needed in the future + */ + function __construct( $id_base = false, $name, $widget_options = array(), $control_options = array() ) { + $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base); + $this->name = $name; + $this->option_name = 'widget_' . $this->id_base; + $this->widget_options = wp_parse_args( $widget_options, array('classname' => $this->option_name) ); + $this->control_options = wp_parse_args( $control_options, array('id_base' => $this->id_base) ); + } + + /** + * Constructs name attributes for use in form() fields + * + * This function should be used in form() methods to create name attributes for fields to be saved by update() + * + * @param string $field_name Field name + * @return string Name attribute for $field_name + */ + function get_field_name($field_name) { + return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']'; + } + + /** + * Constructs id attributes for use in form() fields + * + * This function should be used in form() methods to create id attributes for fields to be saved by update() + * + * @param string $field_name Field name + * @return string ID attribute for $field_name + */ + function get_field_id($field_name) { + return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name; + } + + // Private Functions. Don't worry about these. + + function _register() { + $settings = $this->get_settings(); + + if ( empty($settings) ) { + // If there are none, we register the widget's existance with a + // generic template + $this->_set(1); + $this->_register_one(); + } elseif ( is_array($settings) ) { + foreach ( array_keys($settings) as $number ) { + if ( is_numeric($number) ) { + $this->_set($number); + $this->_register_one($number); + } + } + } + } + + function _set($number) { + $this->number = $number; + $this->id = $this->id_base . '-' . $number; + } + + function _get_display_callback() { + return array(&$this, 'display_callback'); + } + + function _get_update_callback() { + return array(&$this, 'update_callback'); + } + + function _get_form_callback() { + return array(&$this, 'form_callback'); + } + + /** Generate the actual widget content. + * Just finds the instance and calls widget(). + * Do NOT over-ride this function. */ + function display_callback( $args, $widget_args = 1 ) { + if ( is_numeric($widget_args) ) + $widget_args = array( 'number' => $widget_args ); + + $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); + $this->_set( $widget_args['number'] ); + $instance = $this->get_settings(); + + if ( array_key_exists( $this->number, $instance ) ) { + $instance = $instance[$this->number]; + // filters the widget's settings, return false to stop displaying the widget + $instance = apply_filters('widget_display_callback', $instance, $this, $args); + if ( false !== $instance ) + $this->widget($args, $instance); + } + } + + /** Deal with changed settings. + * Do NOT over-ride this function. */ + function update_callback( $widget_args = 1 ) { + global $wp_registered_widgets; + + if ( is_numeric($widget_args) ) + $widget_args = array( 'number' => $widget_args ); + + $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); + $all_instances = $this->get_settings(); + + // We need to update the data + if ( $this->updated ) + return; + + $sidebars_widgets = wp_get_sidebars_widgets(); + + if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) { + // Delete the settings for this instance of the widget + if ( isset($_POST['the-widget-id']) ) + $del_id = $_POST['the-widget-id']; + else + return; + + if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) { + $number = $wp_registered_widgets[$del_id]['params'][0]['number']; + + if ( $this->id_base . '-' . $number == $del_id ) + unset($all_instances[$number]); + } + } else { + if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) { + $settings = $_POST['widget-' . $this->id_base]; + } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) { + $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number']; + $settings = array( $num => array() ); + } else { + return; + } + + foreach ( $settings as $number => $new_instance ) { + $new_instance = stripslashes_deep($new_instance); + $this->_set($number); + + $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array(); + + $instance = $this->update($new_instance, $old_instance); + + // filters the widget's settings before saving, return false to cancel saving (keep the old settings if updating) + $instance = apply_filters('widget_update_callback', $instance, $new_instance, $old_instance, $this); + if ( false !== $instance ) + $all_instances[$number] = $instance; + + break; // run only once + } + } + + $this->save_settings($all_instances); + $this->updated = true; + } + + /** Generate the control form. + * Do NOT over-ride this function. */ + function form_callback( $widget_args = 1 ) { + if ( is_numeric($widget_args) ) + $widget_args = array( 'number' => $widget_args ); + + $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); + $all_instances = $this->get_settings(); + + if ( -1 == $widget_args['number'] ) { + // We echo out a form where 'number' can be set later + $this->_set('__i__'); + $instance = array(); + } else { + $this->_set($widget_args['number']); + $instance = $all_instances[ $widget_args['number'] ]; + } + + // filters the widget admin form before displaying, return false to stop displaying it + $instance = apply_filters('widget_form_callback', $instance, $this); + + $return = null; + if ( false !== $instance ) { + $return = $this->form($instance); + // add extra fields in the widget form - be sure to set $return to null if you add any + // if the widget has no form the text echoed from the default form method can be hidden using css + do_action_ref_array( 'in_widget_form', array(&$this, &$return, $instance) ); + } + return $return; + } + + /** Helper function: Registers a single instance. */ + function _register_one($number = -1) { + wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) ); + _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) ); + _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) ); + } + + function save_settings($settings) { + $settings['_multiwidget'] = 1; + update_option( $this->option_name, $settings ); + } + + function get_settings() { + $settings = get_option($this->option_name); + + if ( false === $settings && isset($this->alt_option_name) ) + $settings = get_option($this->alt_option_name); + + if ( !is_array($settings) ) + $settings = array(); + + if ( !array_key_exists('_multiwidget', $settings) ) { + // old format, conver if single widget + $settings = wp_convert_widget_settings($this->id_base, $this->option_name, $settings); + } + + unset($settings['_multiwidget'], $settings['__i__']); + return $settings; + } +} + +/** + * Singleton that registers and instantiates WP_Widget classes. + * + * @package WordPress + * @subpackage Widgets + * @since 2.8 + */ +class WP_Widget_Factory { + var $widgets = array(); + + function WP_Widget_Factory() { + add_action( 'widgets_init', array( &$this, '_register_widgets' ), 100 ); + } + + function register($widget_class) { + $this->widgets[$widget_class] = & new $widget_class(); + } + + function unregister($widget_class) { + if ( isset($this->widgets[$widget_class]) ) + unset($this->widgets[$widget_class]); + } + + function _register_widgets() { + global $wp_registered_widgets; + $keys = array_keys($this->widgets); + $registered = array_keys($wp_registered_widgets); + $registered = array_map('_get_widget_id_base', $registered); + + foreach ( $keys as $key ) { + // don't register new widget if old widget with the same id is already registered + if ( in_array($this->widgets[$key]->id_base, $registered, true) ) { + unset($this->widgets[$key]); + continue; + } + + $this->widgets[$key]->_register(); + } + } +} + +/* Global Variables */ + +/** @ignore */ +global $wp_registered_sidebars, $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates; + +/** + * Stores the sidebars, since many themes can have more than one. + * + * @global array $wp_registered_sidebars + * @since 2.2.0 + */ +$wp_registered_sidebars = array(); + +/** + * Stores the registered widgets. + * + * @global array $wp_registered_widgets + * @since 2.2.0 + */ +$wp_registered_widgets = array(); + +/** + * Stores the registered widget control (options). + * + * @global array $wp_registered_widget_controls + * @since 2.2.0 + */ +$wp_registered_widget_controls = array(); +$wp_registered_widget_updates = array(); + +/** + * Private + */ +$_wp_sidebars_widgets = array(); + +/** + * Private + */ + $_wp_deprecated_widgets_callbacks = array( + 'wp_widget_pages', + 'wp_widget_pages_control', + 'wp_widget_calendar', + 'wp_widget_calendar_control', + 'wp_widget_archives', + 'wp_widget_archives_control', + 'wp_widget_links', + 'wp_widget_meta', + 'wp_widget_meta_control', + 'wp_widget_search', + 'wp_widget_recent_entries', + 'wp_widget_recent_entries_control', + 'wp_widget_tag_cloud', + 'wp_widget_tag_cloud_control', + 'wp_widget_categories', + 'wp_widget_categories_control', + 'wp_widget_text', + 'wp_widget_text_control', + 'wp_widget_rss', + 'wp_widget_rss_control', + 'wp_widget_recent_comments', + 'wp_widget_recent_comments_control' + ); + +/* Template tags & API functions */ + +/** + * Register a widget + * + * Registers a WP_Widget widget + * + * @since 2.8.0 + * + * @see WP_Widget + * @see WP_Widget_Factory + * @uses WP_Widget_Factory + * + * @param string $widget_class The name of a class that extends WP_Widget + */ +function register_widget($widget_class) { + global $wp_widget_factory; + + $wp_widget_factory->register($widget_class); +} + +/** + * Unregister a widget + * + * Unregisters a WP_Widget widget. Useful for unregistering default widgets. + * Run within a function hooked to the widgets_init action. + * + * @since 2.8.0 + * + * @see WP_Widget + * @see WP_Widget_Factory + * @uses WP_Widget_Factory + * + * @param string $widget_class The name of a class that extends WP_Widget + */ +function unregister_widget($widget_class) { + global $wp_widget_factory; + + $wp_widget_factory->unregister($widget_class); +} + +/** + * Creates multiple sidebars. + * + * If you wanted to quickly create multiple sidebars for a theme or internally. + * This function will allow you to do so. If you don't pass the 'name' and/or + * 'id' in $args, then they will be built for you. + * + * The default for the name is "Sidebar #", with '#' being replaced with the + * number the sidebar is currently when greater than one. If first sidebar, the + * name will be just "Sidebar". The default for id is "sidebar-" followed by the + * number the sidebar creation is currently at. + * + * @since 2.2.0 + * + * @see register_sidebar() The second parameter is documented by register_sidebar() and is the same here. + * @uses parse_str() Converts a string to an array to be used in the rest of the function. + * @uses register_sidebar() Sends single sidebar information [name, id] to this + * function to handle building the sidebar. + * + * @param int $number Number of sidebars to create. + * @param string|array $args Builds Sidebar based off of 'name' and 'id' values. + */ +function register_sidebars($number = 1, $args = array()) { + global $wp_registered_sidebars; + $number = (int) $number; + + if ( is_string($args) ) + parse_str($args, $args); + + for ( $i=1; $i <= $number; $i++ ) { + $_args = $args; + + if ( $number > 1 ) { + $_args['name'] = isset($args['name']) ? sprintf($args['name'], $i) : sprintf(__('Sidebar %d'), $i); + } else { + $_args['name'] = isset($args['name']) ? $args['name'] : __('Sidebar'); + } + + if (isset($args['id'])) { + $_args['id'] = $args['id']; + } else { + $n = count($wp_registered_sidebars); + do { + $n++; + $_args['id'] = "sidebar-$n"; + } while (isset($wp_registered_sidebars[$_args['id']])); + } + + register_sidebar($_args); + } +} + +/** + * Builds the definition for a single sidebar and returns the ID. + * + * The $args parameter takes either a string or an array with 'name' and 'id' + * contained in either usage. It will be noted that the values will be applied + * to all sidebars, so if creating more than one, it will be advised to allow + * for WordPress to create the defaults for you. + * + * Example for string would be 'name=whatever;id=whatever1' and for + * the array it would be array( + * 'name' => 'whatever', + * 'id' => 'whatever1'). + * + * name - The name of the sidebar, which presumably the title which will be + * displayed. + * id - The unique identifier by which the sidebar will be called by. + * before_widget - The content that will prepended to the widgets when they are + * displayed. + * after_widget - The content that will be appended to the widgets when they are + * displayed. + * before_title - The content that will be prepended to the title when displayed. + * after_title - the content that will be appended to the title when displayed. + * + * Content is assumed to be HTML and should be formatted as such, but + * doesn't have to be. + * + * @since 2.2.0 + * @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID. + * @uses parse_str() Converts a string to an array to be used in the rest of the function. + * @usedby register_sidebars() + * + * @param string|array $args Builds Sidebar based off of 'name' and 'id' values + * @return string The sidebar id that was added. + */ +function register_sidebar($args = array()) { + global $wp_registered_sidebars; + + if ( is_string($args) ) + parse_str($args, $args); + + $i = count($wp_registered_sidebars) + 1; + + $defaults = array( + 'name' => sprintf(__('Sidebar %d'), $i ), + 'id' => "sidebar-$i", + 'before_widget' => '
  • ', + 'after_widget' => "
  • \n", + 'before_title' => '

    ', + 'after_title' => "

    \n", + ); + + $sidebar = array_merge($defaults, (array) $args); + + $wp_registered_sidebars[$sidebar['id']] = $sidebar; + + return $sidebar['id']; +} + +/** + * Removes a sidebar from the list. + * + * @since 2.2.0 + * + * @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID. + * + * @param string $name The ID of the sidebar when it was added. + */ +function unregister_sidebar( $name ) { + global $wp_registered_sidebars; + + if ( isset( $wp_registered_sidebars[$name] ) ) + unset( $wp_registered_sidebars[$name] ); +} + +/** + * Register widget for use in sidebars. + * + * The default widget option is 'classname' that can be override. + * + * The function can also be used to unregister widgets when $output_callback + * parameter is an empty string. + * + * @since 2.2.0 + * + * @uses $wp_registered_widgets Uses stored registered widgets. + * @uses $wp_register_widget_defaults Retrieves widget defaults. + * + * @param int|string $id Widget ID. + * @param string $name Widget display title. + * @param callback $output_callback Run when widget is called. + * @param array|string Optional. $options Widget Options. + * @param mixed $params,... Widget parameters to add to widget. + * @return null Will return if $output_callback is empty after removing widget. + */ +function wp_register_sidebar_widget($id, $name, $output_callback, $options = array()) { + global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates, $_wp_deprecated_widgets_callbacks; + + $id = strtolower($id); + + if ( empty($output_callback) ) { + unset($wp_registered_widgets[$id]); + return; + } + + $id_base = _get_widget_id_base($id); + if ( in_array($output_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($output_callback) ) { + if ( isset($wp_registered_widget_controls[$id]) ) + unset($wp_registered_widget_controls[$id]); + + if ( isset($wp_registered_widget_updates[$id_base]) ) + unset($wp_registered_widget_updates[$id_base]); + + return; + } + + $defaults = array('classname' => $output_callback); + $options = wp_parse_args($options, $defaults); + $widget = array( + 'name' => $name, + 'id' => $id, + 'callback' => $output_callback, + 'params' => array_slice(func_get_args(), 4) + ); + $widget = array_merge($widget, $options); + + if ( is_callable($output_callback) && ( !isset($wp_registered_widgets[$id]) || did_action( 'widgets_init' ) ) ) + $wp_registered_widgets[$id] = $widget; +} + +/** + * Retrieve description for widget. + * + * When registering widgets, the options can also include 'description' that + * describes the widget for display on the widget administration panel or + * in the theme. + * + * @since 2.5.0 + * + * @param int|string $id Widget ID. + * @return string Widget description, if available. Null on failure to retrieve description. + */ +function wp_widget_description( $id ) { + if ( !is_scalar($id) ) + return; + + global $wp_registered_widgets; + + if ( isset($wp_registered_widgets[$id]['description']) ) + return esc_html( $wp_registered_widgets[$id]['description'] ); +} + +/** + * Remove widget from sidebar. + * + * @since 2.2.0 + * + * @param int|string $id Widget ID. + */ +function wp_unregister_sidebar_widget($id) { + wp_register_sidebar_widget($id, '', ''); + wp_unregister_widget_control($id); +} + +/** + * Registers widget control callback for customizing options. + * + * The options contains the 'height', 'width', and 'id_base' keys. The 'height' + * option is never used. The 'width' option is the width of the fully expanded + * control form, but try hard to use the default width. The 'id_base' is for + * multi-widgets (widgets which allow multiple instances such as the text + * widget), an id_base must be provided. The widget id will end up looking like + * {$id_base}-{$unique_number}. + * + * @since 2.2.0 + * + * @param int|string $id Sidebar ID. + * @param string $name Sidebar display name. + * @param callback $control_callback Run when sidebar is displayed. + * @param array|string $options Optional. Widget options. See above long description. + * @param mixed $params,... Optional. Additional parameters to add to widget. + */ +function wp_register_widget_control($id, $name, $control_callback, $options = array()) { + global $wp_registered_widget_controls, $wp_registered_widget_updates, $wp_registered_widgets, $_wp_deprecated_widgets_callbacks; + + $id = strtolower($id); + $id_base = _get_widget_id_base($id); + + if ( empty($control_callback) ) { + unset($wp_registered_widget_controls[$id]); + unset($wp_registered_widget_updates[$id_base]); + return; + } + + if ( in_array($control_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($control_callback) ) { + if ( isset($wp_registered_widgets[$id]) ) + unset($wp_registered_widgets[$id]); + + return; + } + + if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) ) + return; + + $defaults = array('width' => 250, 'height' => 200 ); // height is never used + $options = wp_parse_args($options, $defaults); + $options['width'] = (int) $options['width']; + $options['height'] = (int) $options['height']; + + $widget = array( + 'name' => $name, + 'id' => $id, + 'callback' => $control_callback, + 'params' => array_slice(func_get_args(), 4) + ); + $widget = array_merge($widget, $options); + + $wp_registered_widget_controls[$id] = $widget; + + if ( isset($wp_registered_widget_updates[$id_base]) ) + return; + + if ( isset($widget['params'][0]['number']) ) + $widget['params'][0]['number'] = -1; + + unset($widget['width'], $widget['height'], $widget['name'], $widget['id']); + $wp_registered_widget_updates[$id_base] = $widget; +} + +function _register_widget_update_callback($id_base, $update_callback, $options = array()) { + global $wp_registered_widget_updates; + + if ( isset($wp_registered_widget_updates[$id_base]) ) { + if ( empty($update_callback) ) + unset($wp_registered_widget_updates[$id_base]); + return; + } + + $widget = array( + 'callback' => $update_callback, + 'params' => array_slice(func_get_args(), 3) + ); + + $widget = array_merge($widget, $options); + $wp_registered_widget_updates[$id_base] = $widget; +} + +function _register_widget_form_callback($id, $name, $form_callback, $options = array()) { + global $wp_registered_widget_controls; + + $id = strtolower($id); + + if ( empty($form_callback) ) { + unset($wp_registered_widget_controls[$id]); + return; + } + + if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) ) + return; + + $defaults = array('width' => 250, 'height' => 200 ); + $options = wp_parse_args($options, $defaults); + $options['width'] = (int) $options['width']; + $options['height'] = (int) $options['height']; + + $widget = array( + 'name' => $name, + 'id' => $id, + 'callback' => $form_callback, + 'params' => array_slice(func_get_args(), 4) + ); + $widget = array_merge($widget, $options); + + $wp_registered_widget_controls[$id] = $widget; +} + +/** + * Remove control callback for widget. + * + * @since 2.2.0 + * @uses wp_register_widget_control() Unregisters by using empty callback. + * + * @param int|string $id Widget ID. + */ +function wp_unregister_widget_control($id) { + return wp_register_widget_control($id, '', ''); +} + +/** + * Display dynamic sidebar. + * + * By default it displays the default sidebar or 'sidebar-1'. The 'sidebar-1' is + * not named by the theme, the actual name is '1', but 'sidebar-' is added to + * the registered sidebars for the name. If you named your sidebar 'after-post', + * then the parameter $index will still be 'after-post', but the lookup will be + * for 'sidebar-after-post'. + * + * It is confusing for the $index parameter, but just know that it should just + * work. When you register the sidebar in the theme, you will use the same name + * for this function or "Pay no heed to the man behind the curtain." Just accept + * it as an oddity of WordPress sidebar register and display. + * + * @since 2.2.0 + * + * @param int|string $index Optional, default is 1. Name or ID of dynamic sidebar. + * @return bool True, if widget sidebar was found and called. False if not found or not called. + */ +function dynamic_sidebar($index = 1) { + global $wp_registered_sidebars, $wp_registered_widgets; + + if ( is_int($index) ) { + $index = "sidebar-$index"; + } else { + $index = sanitize_title($index); + foreach ( (array) $wp_registered_sidebars as $key => $value ) { + if ( sanitize_title($value['name']) == $index ) { + $index = $key; + break; + } + } + } + + $sidebars_widgets = wp_get_sidebars_widgets(); + + if ( empty($wp_registered_sidebars[$index]) || !array_key_exists($index, $sidebars_widgets) || !is_array($sidebars_widgets[$index]) || empty($sidebars_widgets[$index]) ) + return false; + + $sidebar = $wp_registered_sidebars[$index]; + + $did_one = false; + foreach ( (array) $sidebars_widgets[$index] as $id ) { + + if ( !isset($wp_registered_widgets[$id]) ) continue; + + $params = array_merge( + array( array_merge( $sidebar, array('widget_id' => $id, 'widget_name' => $wp_registered_widgets[$id]['name']) ) ), + (array) $wp_registered_widgets[$id]['params'] + ); + + // Substitute HTML id and class attributes into before_widget + $classname_ = ''; + foreach ( (array) $wp_registered_widgets[$id]['classname'] as $cn ) { + if ( is_string($cn) ) + $classname_ .= '_' . $cn; + elseif ( is_object($cn) ) + $classname_ .= '_' . get_class($cn); + } + $classname_ = ltrim($classname_, '_'); + $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_); + + $params = apply_filters( 'dynamic_sidebar_params', $params ); + + $callback = $wp_registered_widgets[$id]['callback']; + + if ( is_callable($callback) ) { + call_user_func_array($callback, $params); + $did_one = true; + } + } + + return $did_one; +} + +/** + * Whether widget is displayied on the front-end. + * + * Either $callback or $id_base can be used + * $id_base is the first argument when extending WP_Widget class + * Without the optional $widget_id parameter, returns the ID of the first sidebar + * in which the first instance of the widget with the given callback or $id_base is found. + * With the $widget_id parameter, returns the ID of the sidebar where + * the widget with that callback/$id_base AND that ID is found. + * + * NOTE: $widget_id and $id_base are the same for single widgets. To be effective + * this function has to run after widgets have initialized, at action 'init' or later. + * + * @since 2.2.0 + * + * @param callback Optional, Widget callback to check. + * @param int $widget_id Optional, but needed for checking. Widget ID. + * @param string $id_base Optional, the base ID of a widget created by extending WP_Widget. + * @param bool $skip_inactive Optional, whether to check in 'wp_inactive_widgets'. + * @return mixed false if widget is not active or id of sidebar in which the widget is active. + */ +function is_active_widget($callback = false, $widget_id = false, $id_base = false, $skip_inactive = true) { + global $wp_registered_widgets; + + $sidebars_widgets = wp_get_sidebars_widgets(); + + if ( is_array($sidebars_widgets) ) { + foreach ( $sidebars_widgets as $sidebar => $widgets ) { + if ( $skip_inactive && 'wp_inactive_widgets' == $sidebar ) + continue; + + if ( is_array($widgets) ) { + foreach ( $widgets as $widget ) { + if ( ( $callback && isset($wp_registered_widgets[$widget]['callback']) && $wp_registered_widgets[$widget]['callback'] == $callback ) || ( $id_base && _get_widget_id_base($widget) == $id_base ) ) { + if ( !$widget_id || $widget_id == $wp_registered_widgets[$widget]['id'] ) + return $sidebar; + } + } + } + } + } + return false; +} + +/** + * Whether the dynamic sidebar is enabled and used by theme. + * + * @since 2.2.0 + * + * @return bool True, if using widgets. False, if not using widgets. + */ +function is_dynamic_sidebar() { + global $wp_registered_widgets, $wp_registered_sidebars; + $sidebars_widgets = get_option('sidebars_widgets'); + foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) { + if ( count($sidebars_widgets[$index]) ) { + foreach ( (array) $sidebars_widgets[$index] as $widget ) + if ( array_key_exists($widget, $wp_registered_widgets) ) + return true; + } + } + return false; +} + +/** + * Whether a sidebar is in use. + * + * @since 2.8 + * + * @param mixed $index, sidebar name, id or number to check. + * @return bool true if the sidebar is in use, false otherwise. + */ +function is_active_sidebar( $index ) { + $index = ( is_int($index) ) ? "sidebar-$index" : sanitize_title($index); + $sidebars_widgets = wp_get_sidebars_widgets(); + if ( isset($sidebars_widgets[$index]) && !empty($sidebars_widgets[$index]) ) + return true; + + return false; +} + +/* Internal Functions */ + +/** + * Retrieve full list of sidebars and their widgets. + * + * Will upgrade sidebar widget list, if needed. Will also save updated list, if + * needed. + * + * @since 2.2.0 + * @access private + * + * @param bool $update Optional, deprecated. + * @return array Upgraded list of widgets to version 3 array format when called from the admin. + */ +function wp_get_sidebars_widgets($deprecated = true) { + global $wp_registered_widgets, $wp_registered_sidebars, $_wp_sidebars_widgets; + + // If loading from front page, consult $_wp_sidebars_widgets rather than options + // to see if wp_convert_widget_settings() has made manipulations in memory. + if ( !is_admin() ) { + if ( empty($_wp_sidebars_widgets) ) + $_wp_sidebars_widgets = get_option('sidebars_widgets', array()); + + $sidebars_widgets = $_wp_sidebars_widgets; + } else { + $sidebars_widgets = get_option('sidebars_widgets', array()); + $_sidebars_widgets = array(); + + if ( isset($sidebars_widgets['wp_inactive_widgets']) ) + $sidebars_widgets['array_version'] = 3; + elseif ( !isset($sidebars_widgets['array_version']) ) + $sidebars_widgets['array_version'] = 1; + + switch ( $sidebars_widgets['array_version'] ) { + case 1 : + foreach ( (array) $sidebars_widgets as $index => $sidebar ) + if ( is_array($sidebar) ) + foreach ( (array) $sidebar as $i => $name ) { + $id = strtolower($name); + if ( isset($wp_registered_widgets[$id]) ) { + $_sidebars_widgets[$index][$i] = $id; + continue; + } + $id = sanitize_title($name); + if ( isset($wp_registered_widgets[$id]) ) { + $_sidebars_widgets[$index][$i] = $id; + continue; + } + + $found = false; + + foreach ( $wp_registered_widgets as $widget_id => $widget ) { + if ( strtolower($widget['name']) == strtolower($name) ) { + $_sidebars_widgets[$index][$i] = $widget['id']; + $found = true; + break; + } elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) { + $_sidebars_widgets[$index][$i] = $widget['id']; + $found = true; + break; + } + } + + if ( $found ) + continue; + + unset($_sidebars_widgets[$index][$i]); + } + $_sidebars_widgets['array_version'] = 2; + $sidebars_widgets = $_sidebars_widgets; + unset($_sidebars_widgets); + + case 2 : + $sidebars = array_keys( $wp_registered_sidebars ); + if ( !empty( $sidebars ) ) { + // Move the known-good ones first + foreach ( (array) $sidebars as $id ) { + if ( array_key_exists( $id, $sidebars_widgets ) ) { + $_sidebars_widgets[$id] = $sidebars_widgets[$id]; + unset($sidebars_widgets[$id], $sidebars[$id]); + } + } + + // move the rest to wp_inactive_widgets + if ( !isset($_sidebars_widgets['wp_inactive_widgets']) ) + $_sidebars_widgets['wp_inactive_widgets'] = array(); + + if ( !empty($sidebars_widgets) ) { + foreach ( $sidebars_widgets as $lost => $val ) { + if ( is_array($val) ) + $_sidebars_widgets['wp_inactive_widgets'] = array_merge( (array) $_sidebars_widgets['wp_inactive_widgets'], $val ); + } + } + + $sidebars_widgets = $_sidebars_widgets; + unset($_sidebars_widgets); + } + } + } + + if ( isset($sidebars_widgets['array_version']) ) + unset($sidebars_widgets['array_version']); + + $sidebars_widgets = apply_filters('sidebars_widgets', $sidebars_widgets); + return $sidebars_widgets; +} + +/** + * Set the sidebar widget option to update sidebars. + * + * @since 2.2.0 + * @access private + * + * @param array $sidebars_widgets Sidebar widgets and their settings. + */ +function wp_set_sidebars_widgets( $sidebars_widgets ) { + if ( !isset( $sidebars_widgets['array_version'] ) ) + $sidebars_widgets['array_version'] = 3; + update_option( 'sidebars_widgets', $sidebars_widgets ); +} + +/** + * Retrieve default registered sidebars list. + * + * @since 2.2.0 + * @access private + * + * @return array + */ +function wp_get_widget_defaults() { + global $wp_registered_sidebars; + + $defaults = array(); + + foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) + $defaults[$index] = array(); + + return $defaults; +} + +/** + * Convert the widget settings from single to multi-widget format. + * + * @since 2.8.0 + * + * @return array + */ +function wp_convert_widget_settings($base_name, $option_name, $settings) { + // This test may need expanding. + $single = $changed = false; + if ( empty($settings) ) { + $single = true; + } else { + foreach ( array_keys($settings) as $number ) { + if ( 'number' == $number ) + continue; + if ( !is_numeric($number) ) { + $single = true; + break; + } + } + } + + if ( $single ) { + $settings = array( 2 => $settings ); + + // If loading from the front page, update sidebar in memory but don't save to options + if ( is_admin() ) { + $sidebars_widgets = get_option('sidebars_widgets'); + } else { + if ( empty($GLOBALS['_wp_sidebars_widgets']) ) + $GLOBALS['_wp_sidebars_widgets'] = get_option('sidebars_widgets', array()); + $sidebars_widgets = &$GLOBALS['_wp_sidebars_widgets']; + } + + foreach ( (array) $sidebars_widgets as $index => $sidebar ) { + if ( is_array($sidebar) ) { + foreach ( $sidebar as $i => $name ) { + if ( $base_name == $name ) { + $sidebars_widgets[$index][$i] = "$name-2"; + $changed = true; + break 2; + } + } + } + } + + if ( is_admin() && $changed ) + update_option('sidebars_widgets', $sidebars_widgets); + } + + $settings['_multiwidget'] = 1; + if ( is_admin() ) + update_option( $option_name, $settings ); + + return $settings; +} + +/** + * Deprecated API + */ + +/** + * Register widget for sidebar with backwards compatibility. + * + * Allows $name to be an array that accepts either three elements to grab the + * first element and the third for the name or just uses the first element of + * the array for the name. + * + * Passes to {@link wp_register_sidebar_widget()} after argument list and + * backwards compatibility is complete. + * + * @since 2.2.0 + * @uses wp_register_sidebar_widget() Passes the compiled arguments. + * + * @param string|int $name Widget ID. + * @param callback $output_callback Run when widget is called. + * @param string $classname Classname widget option. + * @param mixed $params,... Widget parameters. + */ +function register_sidebar_widget($name, $output_callback, $classname = '') { + // Compat + if ( is_array($name) ) { + if ( count($name) == 3 ) + $name = sprintf($name[0], $name[2]); + else + $name = $name[0]; + } + + $id = sanitize_title($name); + $options = array(); + if ( !empty($classname) && is_string($classname) ) + $options['classname'] = $classname; + $params = array_slice(func_get_args(), 2); + $args = array($id, $name, $output_callback, $options); + if ( !empty($params) ) + $args = array_merge($args, $params); + + call_user_func_array('wp_register_sidebar_widget', $args); +} + +/** + * Alias of {@link wp_unregister_sidebar_widget()}. + * + * @see wp_unregister_sidebar_widget() + * + * @since 2.2.0 + * + * @param int|string $id Widget ID. + */ +function unregister_sidebar_widget($id) { + return wp_unregister_sidebar_widget($id); +} + +/** + * Registers widget control callback for customizing options. + * + * Allows $name to be an array that accepts either three elements to grab the + * first element and the third for the name or just uses the first element of + * the array for the name. + * + * Passes to {@link wp_register_widget_control()} after the argument list has + * been compiled. + * + * @since 2.2.0 + * + * @param int|string $name Sidebar ID. + * @param callback $control_callback Widget control callback to display and process form. + * @param int $width Widget width. + * @param int $height Widget height. + */ +function register_widget_control($name, $control_callback, $width = '', $height = '') { + // Compat + if ( is_array($name) ) { + if ( count($name) == 3 ) + $name = sprintf($name[0], $name[2]); + else + $name = $name[0]; + } + + $id = sanitize_title($name); + $options = array(); + if ( !empty($width) ) + $options['width'] = $width; + if ( !empty($height) ) + $options['height'] = $height; + $params = array_slice(func_get_args(), 4); + $args = array($id, $name, $control_callback, $options); + if ( !empty($params) ) + $args = array_merge($args, $params); + + call_user_func_array('wp_register_widget_control', $args); +} + +/** + * Alias of {@link wp_unregister_widget_control()}. + * + * @since 2.2.0 + * @see wp_unregister_widget_control() + * + * @param int|string $id Widget ID. + */ +function unregister_widget_control($id) { + return wp_unregister_widget_control($id); +} + +/** + * Output an arbitrary widget as a template tag + * + * @since 2.8 + * + * @param string $widget the widget's PHP class name (see default-widgets.php) + * @param array $instance the widget's instance settings + * @param array $args the widget's sidebar args + * @return void + **/ +function the_widget($widget, $instance = array(), $args = array()) { + global $wp_widget_factory; + + $widget_obj = $wp_widget_factory->widgets[$widget]; + if ( !is_a($widget_obj, 'WP_Widget') ) + return; + + $before_widget = sprintf('
    ', $widget_obj->widget_options['classname']); + $default_args = array('before_widget' => $before_widget, 'after_widget' => "
    ", 'before_title' => '

    ', 'after_title' => '

    '); + + $args = wp_parse_args($args, $default_args); + $instance = wp_parse_args($instance); + + $widget_obj->_set(-1); + $widget_obj->widget($args, $instance); +} + +/** + * Private + */ +function _get_widget_id_base($id) { + return preg_replace( '/-[0-9]+$/', '', $id ); +} diff --git a/wp-includes/wlwmanifest.xml b/wp-includes/wlwmanifest.xml new file mode 100644 index 0000000..eb13147 --- /dev/null +++ b/wp-includes/wlwmanifest.xml @@ -0,0 +1,44 @@ + + + + + + WordPress + Yes + Yes + + + + WordPress + images/wlw/wp-icon.png + images/wlw/wp-watermark.png + View site + Dashboard + + + + + + + + + + + + + + + diff --git a/wp-includes/wp-db.php b/wp-includes/wp-db.php new file mode 100644 index 0000000..a4ff757 --- /dev/null +++ b/wp-includes/wp-db.php @@ -0,0 +1,1113 @@ + '%d' + * + * @since 2.8.0 + * @see wpdb:prepare() + * @see wpdb:insert() + * @see wpdb:update() + * @access public + * @war array + */ + var $field_types = array(); + + /** + * Database table columns charset + * + * @since 2.2.0 + * @access public + * @var string + */ + var $charset; + + /** + * Database table columns collate + * + * @since 2.2.0 + * @access public + * @var string + */ + var $collate; + + /** + * Whether to use mysql_real_escape_string + * + * @since 2.8.0 + * @access public + * @var bool + */ + var $real_escape = false; + + /** + * Connects to the database server and selects a database + * + * PHP4 compatibility layer for calling the PHP5 constructor. + * + * @uses wpdb::__construct() Passes parameters and returns result + * @since 0.71 + * + * @param string $dbuser MySQL database user + * @param string $dbpassword MySQL database password + * @param string $dbname MySQL database name + * @param string $dbhost MySQL database host + */ + function wpdb($dbuser, $dbpassword, $dbname, $dbhost) { + return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost); + } + + /** + * Connects to the database server and selects a database + * + * PHP5 style constructor for compatibility with PHP5. Does + * the actual setting up of the class properties and connection + * to the database. + * + * @since 2.0.8 + * + * @param string $dbuser MySQL database user + * @param string $dbpassword MySQL database password + * @param string $dbname MySQL database name + * @param string $dbhost MySQL database host + */ + function __construct($dbuser, $dbpassword, $dbname, $dbhost) { + register_shutdown_function(array(&$this, "__destruct")); + + if ( defined('WP_DEBUG') and WP_DEBUG == true ) + $this->show_errors(); + + if ( defined('DB_CHARSET') ) + $this->charset = DB_CHARSET; + + if ( defined('DB_COLLATE') ) + $this->collate = DB_COLLATE; + + $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true); + if (!$this->dbh) { + $this->bail(sprintf(/*WP_I18N_DB_CONN_ERROR*/" +

    Error establishing a database connection

    +

    This either means that the username and password information in your wp-config.php file is incorrect or we can't contact the database server at %s. This could mean your host's database server is down.

    +
      +
    • Are you sure you have the correct username and password?
    • +
    • Are you sure that you have typed the correct hostname?
    • +
    • Are you sure that the database server is running?
    • +
    +

    If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress Support Forums.

    +"/*/WP_I18N_DB_CONN_ERROR*/, $dbhost)); + return; + } + + $this->ready = true; + + if ( $this->has_cap( 'collation' ) ) { + if ( !empty($this->charset) ) { + if ( function_exists('mysql_set_charset') ) { + mysql_set_charset($this->charset, $this->dbh); + $this->real_escape = true; + } else { + $collation_query = "SET NAMES '{$this->charset}'"; + if ( !empty($this->collate) ) + $collation_query .= " COLLATE '{$this->collate}'"; + $this->query($collation_query); + } + } + } + + $this->select($dbname); + } + + /** + * PHP5 style destructor and will run when database object is destroyed. + * + * @since 2.0.8 + * + * @return bool Always true + */ + function __destruct() { + return true; + } + + /** + * Sets the table prefix for the WordPress tables. + * + * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to + * override the WordPress users and usersmeta tables that would otherwise be determined by the $prefix. + * + * @since 2.5.0 + * + * @param string $prefix Alphanumeric name for the new prefix. + * @return string|WP_Error Old prefix or WP_Error on error + */ + function set_prefix($prefix) { + + if ( preg_match('|[^a-z0-9_]|i', $prefix) ) + return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/); + + $old_prefix = $this->prefix; + $this->prefix = $prefix; + + foreach ( (array) $this->tables as $table ) + $this->$table = $this->prefix . $table; + + if ( defined('CUSTOM_USER_TABLE') ) + $this->users = CUSTOM_USER_TABLE; + + if ( defined('CUSTOM_USER_META_TABLE') ) + $this->usermeta = CUSTOM_USER_META_TABLE; + + return $old_prefix; + } + + /** + * Selects a database using the current database connection. + * + * The database name will be changed based on the current database + * connection. On failure, the execution will bail and display an DB error. + * + * @since 0.71 + * + * @param string $db MySQL database name + * @return null Always null. + */ + function select($db) { + if (!@mysql_select_db($db, $this->dbh)) { + $this->ready = false; + $this->bail(sprintf(/*WP_I18N_DB_SELECT_DB*/' +

    Can’t select database

    +

    We were able to connect to the database server (which means your username and password is okay) but not able to select the %1$s database.

    +
      +
    • Are you sure it exists?
    • +
    • Does the user %2$s have permission to use the %1$s database?
    • +
    • On some systems the name of your database is prefixed with your username, so it would be like username_%1$s. Could that be the problem?
    • +
    +

    If you don\'t know how to setup a database you should contact your host. If all else fails you may find help at the WordPress Support Forums.

    '/*/WP_I18N_DB_SELECT_DB*/, $db, DB_USER)); + return; + } + } + + function _weak_escape($string) { + return addslashes($string); + } + + function _real_escape($string) { + if ( $this->dbh && $this->real_escape ) + return mysql_real_escape_string( $string, $this->dbh ); + else + return addslashes( $string ); + } + + function _escape($data) { + if ( is_array($data) ) { + foreach ( (array) $data as $k => $v ) { + if ( is_array($v) ) + $data[$k] = $this->_escape( $v ); + else + $data[$k] = $this->_real_escape( $v ); + } + } else { + $data = $this->_real_escape( $data ); + } + + return $data; + } + + /** + * Escapes content for insertion into the database using addslashes(), for security + * + * @since 0.71 + * + * @param string|array $data + * @return string query safe string + */ + function escape($data) { + if ( is_array($data) ) { + foreach ( (array) $data as $k => $v ) { + if ( is_array($v) ) + $data[$k] = $this->escape( $v ); + else + $data[$k] = $this->_weak_escape( $v ); + } + } else { + $data = $this->_weak_escape( $data ); + } + + return $data; + } + + /** + * Escapes content by reference for insertion into the database, for security + * + * @since 2.3.0 + * + * @param string $s + */ + function escape_by_ref(&$string) { + $string = $this->_real_escape( $string ); + } + + /** + * Prepares a SQL query for safe execution. Uses sprintf()-like syntax. + * + * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string). + * Does not support sign, padding, alignment, width or precision specifiers. + * Does not support argument numbering/swapping. + * + * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}. + * + * Both %d and %s should be left unquoted in the query string. + * + * + * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", "foo", 1337 ) + * + * + * @link http://php.net/sprintf Description of syntax. + * @since 2.3.0 + * + * @param string $query Query statement with sprintf()-like placeholders + * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}. + * @param mixed $args,... further variables to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}. + * @return null|string Sanitized query string + */ + function prepare($query = null) { // ( $query, *$args ) + if ( is_null( $query ) ) + return; + $args = func_get_args(); + array_shift($args); + // If args were passed as an array (as in vsprintf), move them up + if ( isset($args[0]) && is_array($args[0]) ) + $args = $args[0]; + $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it + $query = str_replace('"%s"', '%s', $query); // doublequote unquoting + $query = str_replace('%s', "'%s'", $query); // quote the strings + array_walk($args, array(&$this, 'escape_by_ref')); + return @vsprintf($query, $args); + } + + /** + * Print SQL/DB error. + * + * @since 0.71 + * @global array $EZSQL_ERROR Stores error information of query and error string + * + * @param string $str The error to display + * @return bool False if the showing of errors is disabled. + */ + function print_error($str = '') { + global $EZSQL_ERROR; + + if (!$str) $str = mysql_error($this->dbh); + $EZSQL_ERROR[] = array ('query' => $this->last_query, 'error_str' => $str); + + if ( $this->suppress_errors ) + return false; + + if ( $caller = $this->get_caller() ) + $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR_FULL*/'WordPress database error %1$s for query %2$s made by %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller); + else + $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR*/'WordPress database error %1$s for query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query); + + $log_error = true; + if ( ! function_exists('error_log') ) + $log_error = false; + + $log_file = @ini_get('error_log'); + if ( !empty($log_file) && ('syslog' != $log_file) && !@is_writable($log_file) ) + $log_error = false; + + if ( $log_error ) + @error_log($error_str, 0); + + // Is error output turned on or not.. + if ( !$this->show_errors ) + return false; + + $str = htmlspecialchars($str, ENT_QUOTES); + $query = htmlspecialchars($this->last_query, ENT_QUOTES); + + // If there is an error then take note of it + print "
    +

    WordPress database error: [$str]
    + $query

    +
    "; + } + + /** + * Enables showing of database errors. + * + * This function should be used only to enable showing of errors. + * wpdb::hide_errors() should be used instead for hiding of errors. However, + * this function can be used to enable and disable showing of database + * errors. + * + * @since 0.71 + * + * @param bool $show Whether to show or hide errors + * @return bool Old value for showing errors. + */ + function show_errors( $show = true ) { + $errors = $this->show_errors; + $this->show_errors = $show; + return $errors; + } + + /** + * Disables showing of database errors. + * + * @since 0.71 + * + * @return bool Whether showing of errors was active or not + */ + function hide_errors() { + $show = $this->show_errors; + $this->show_errors = false; + return $show; + } + + /** + * Whether to suppress database errors. + * + * @param unknown_type $suppress + * @return unknown + */ + function suppress_errors( $suppress = true ) { + $errors = $this->suppress_errors; + $this->suppress_errors = $suppress; + return $errors; + } + + /** + * Kill cached query results. + * + * @since 0.71 + */ + function flush() { + $this->last_result = array(); + $this->col_info = null; + $this->last_query = null; + } + + /** + * Perform a MySQL database query, using current database connection. + * + * More information can be found on the codex page. + * + * @since 0.71 + * + * @param string $query + * @return int|false Number of rows affected/selected or false on error + */ + function query($query) { + if ( ! $this->ready ) + return false; + + // filter the query, if filters are available + // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method + if ( function_exists('apply_filters') ) + $query = apply_filters('query', $query); + + // initialise return + $return_val = 0; + $this->flush(); + + // Log how the function was called + $this->func_call = "\$db->query(\"$query\")"; + + // Keep track of the last query for debug.. + $this->last_query = $query; + + // Perform the query via std mysql_query function.. + if ( defined('SAVEQUERIES') && SAVEQUERIES ) + $this->timer_start(); + + $this->result = @mysql_query($query, $this->dbh); + ++$this->num_queries; + + if ( defined('SAVEQUERIES') && SAVEQUERIES ) + $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() ); + + // If there is an error then take note of it.. + if ( $this->last_error = mysql_error($this->dbh) ) { + $this->print_error(); + return false; + } + + if ( preg_match("/^\\s*(insert|delete|update|replace|alter) /i",$query) ) { + $this->rows_affected = mysql_affected_rows($this->dbh); + // Take note of the insert_id + if ( preg_match("/^\\s*(insert|replace) /i",$query) ) { + $this->insert_id = mysql_insert_id($this->dbh); + } + // Return number of rows affected + $return_val = $this->rows_affected; + } else { + $i = 0; + while ($i < @mysql_num_fields($this->result)) { + $this->col_info[$i] = @mysql_fetch_field($this->result); + $i++; + } + $num_rows = 0; + while ( $row = @mysql_fetch_object($this->result) ) { + $this->last_result[$num_rows] = $row; + $num_rows++; + } + + @mysql_free_result($this->result); + + // Log number of rows the query returned + $this->num_rows = $num_rows; + + // Return number of rows selected + $return_val = $this->num_rows; + } + + return $return_val; + } + + /** + * Insert a row into a table. + * + * + * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) + * + * + * @since 2.5.0 + * @see wpdb::prepare() + * + * @param string $table table name + * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). + * @param array|string $format (optional) An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings. + * @return int|false The number of rows inserted, or false on error. + */ + function insert($table, $data, $format = null) { + $formats = $format = (array) $format; + $fields = array_keys($data); + $formatted_fields = array(); + foreach ( $fields as $field ) { + if ( !empty($format) ) + $form = ( $form = array_shift($formats) ) ? $form : $format[0]; + elseif ( isset($this->field_types[$field]) ) + $form = $this->field_types[$field]; + else + $form = '%s'; + $formatted_fields[] = $form; + } + $sql = "INSERT INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')"; + return $this->query( $this->prepare( $sql, $data) ); + } + + + /** + * Update a row in the table + * + * + * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) ) + * + * + * @since 2.5.0 + * @see wpdb::prepare() + * + * @param string $table table name + * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). + * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw". + * @param array|string $format (optional) An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data. A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings. + * @param array|string $format_where (optional) An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $where will be treated as strings. + * @return int|false The number of rows updated, or false on error. + */ + function update($table, $data, $where, $format = null, $where_format = null) { + if ( !is_array( $where ) ) + return false; + + $formats = $format = (array) $format; + $bits = $wheres = array(); + foreach ( (array) array_keys($data) as $field ) { + if ( !empty($format) ) + $form = ( $form = array_shift($formats) ) ? $form : $format[0]; + elseif ( isset($this->field_types[$field]) ) + $form = $this->field_types[$field]; + else + $form = '%s'; + $bits[] = "`$field` = {$form}"; + } + + $where_formats = $where_format = (array) $where_format; + foreach ( (array) array_keys($where) as $field ) { + if ( !empty($where_format) ) + $form = ( $form = array_shift($where_formats) ) ? $form : $where_format[0]; + elseif ( isset($this->field_types[$field]) ) + $form = $this->field_types[$field]; + else + $form = '%s'; + $wheres[] = "`$field` = {$form}"; + } + + $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ); + return $this->query( $this->prepare( $sql, array_merge(array_values($data), array_values($where))) ); + } + + /** + * Retrieve one variable from the database. + * + * Executes a SQL query and returns the value from the SQL result. + * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified. + * If $query is null, this function returns the value in the specified column and row from the previous SQL result. + * + * @since 0.71 + * + * @param string|null $query SQL query. If null, use the result from the previous query. + * @param int $x (optional) Column of value to return. Indexed from 0. + * @param int $y (optional) Row of value to return. Indexed from 0. + * @return string Database query result + */ + function get_var($query=null, $x = 0, $y = 0) { + $this->func_call = "\$db->get_var(\"$query\",$x,$y)"; + if ( $query ) + $this->query($query); + + // Extract var out of cached results based x,y vals + if ( !empty( $this->last_result[$y] ) ) { + $values = array_values(get_object_vars($this->last_result[$y])); + } + + // If there is a value return it else return null + return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null; + } + + /** + * Retrieve one row from the database. + * + * Executes a SQL query and returns the row from the SQL result. + * + * @since 0.71 + * + * @param string|null $query SQL query. + * @param string $output (optional) one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...), a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively. + * @param int $y (optional) Row to return. Indexed from 0. + * @return mixed Database query result in format specifed by $output + */ + function get_row($query = null, $output = OBJECT, $y = 0) { + $this->func_call = "\$db->get_row(\"$query\",$output,$y)"; + if ( $query ) + $this->query($query); + else + return null; + + if ( !isset($this->last_result[$y]) ) + return null; + + if ( $output == OBJECT ) { + return $this->last_result[$y] ? $this->last_result[$y] : null; + } elseif ( $output == ARRAY_A ) { + return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null; + } elseif ( $output == ARRAY_N ) { + return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null; + } else { + $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N"/*/WP_I18N_DB_GETROW_ERROR*/); + } + } + + /** + * Retrieve one column from the database. + * + * Executes a SQL query and returns the column from the SQL result. + * If the SQL result contains more than one column, this function returns the column specified. + * If $query is null, this function returns the specified column from the previous SQL result. + * + * @since 0.71 + * + * @param string|null $query SQL query. If null, use the result from the previous query. + * @param int $x Column to return. Indexed from 0. + * @return array Database query result. Array indexed from 0 by SQL result row number. + */ + function get_col($query = null , $x = 0) { + if ( $query ) + $this->query($query); + + $new_array = array(); + // Extract the column values + for ( $i=0; $i < count($this->last_result); $i++ ) { + $new_array[$i] = $this->get_var(null, $x, $i); + } + return $new_array; + } + + /** + * Retrieve an entire SQL result set from the database (i.e., many rows) + * + * Executes a SQL query and returns the entire SQL result. + * + * @since 0.71 + * + * @param string $query SQL query. + * @param string $output (optional) ane of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number. Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively. With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded. + * @return mixed Database query results + */ + function get_results($query = null, $output = OBJECT) { + $this->func_call = "\$db->get_results(\"$query\", $output)"; + + if ( $query ) + $this->query($query); + else + return null; + + if ( $output == OBJECT ) { + // Return an integer-keyed array of row objects + return $this->last_result; + } elseif ( $output == OBJECT_K ) { + // Return an array of row objects with keys from column 1 + // (Duplicates are discarded) + foreach ( $this->last_result as $row ) { + $key = array_shift( get_object_vars( $row ) ); + if ( !isset( $new_array[ $key ] ) ) + $new_array[ $key ] = $row; + } + return $new_array; + } elseif ( $output == ARRAY_A || $output == ARRAY_N ) { + // Return an integer-keyed array of... + if ( $this->last_result ) { + $i = 0; + foreach( (array) $this->last_result as $row ) { + if ( $output == ARRAY_N ) { + // ...integer-keyed row arrays + $new_array[$i] = array_values( get_object_vars( $row ) ); + } else { + // ...column name-keyed row arrays + $new_array[$i] = get_object_vars( $row ); + } + ++$i; + } + return $new_array; + } + } + } + + /** + * Retrieve column metadata from the last query. + * + * @since 0.71 + * + * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill + * @param int $col_offset 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type + * @return mixed Column Results + */ + function get_col_info($info_type = 'name', $col_offset = -1) { + if ( $this->col_info ) { + if ( $col_offset == -1 ) { + $i = 0; + foreach( (array) $this->col_info as $col ) { + $new_array[$i] = $col->{$info_type}; + $i++; + } + return $new_array; + } else { + return $this->col_info[$col_offset]->{$info_type}; + } + } + } + + /** + * Starts the timer, for debugging purposes. + * + * @since 1.5.0 + * + * @return true + */ + function timer_start() { + $mtime = microtime(); + $mtime = explode(' ', $mtime); + $this->time_start = $mtime[1] + $mtime[0]; + return true; + } + + /** + * Stops the debugging timer. + * + * @since 1.5.0 + * + * @return int Total time spent on the query, in milliseconds + */ + function timer_stop() { + $mtime = microtime(); + $mtime = explode(' ', $mtime); + $time_end = $mtime[1] + $mtime[0]; + $time_total = $time_end - $this->time_start; + return $time_total; + } + + /** + * Wraps errors in a nice header and footer and dies. + * + * Will not die if wpdb::$show_errors is true + * + * @since 1.5.0 + * + * @param string $message + * @return false|void + */ + function bail($message) { + if ( !$this->show_errors ) { + if ( class_exists('WP_Error') ) + $this->error = new WP_Error('500', $message); + else + $this->error = $message; + return false; + } + wp_die($message); + } + + /** + * Whether or not MySQL database is at least the required minimum version. + * + * @since 2.5.0 + * @uses $wp_version + * + * @return WP_Error + */ + function check_database_version() + { + global $wp_version; + // Make sure the server has MySQL 4.0 + if ( version_compare($this->db_version(), '4.0.0', '<') ) + return new WP_Error('database_version',sprintf(__('ERROR: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version)); + } + + /** + * Whether of not the database supports collation. + * + * Called when WordPress is generating the table scheme. + * + * @since 2.5.0 + * + * @return bool True if collation is supported, false if version does not + */ + function supports_collation() + { + return $this->has_cap( 'collation' ); + } + + /** + * Generic function to determine if a database supports a particular feature + * @param string $db_cap the feature + * @param false|string|resource $dbh_or_table (not implemented) Which database to test. False = the currently selected database, string = the database containing the specified table, resource = the database corresponding to the specified mysql resource. + * @return bool + */ + function has_cap( $db_cap ) { + $version = $this->db_version(); + + switch ( strtolower( $db_cap ) ) : + case 'collation' : // @since 2.5.0 + case 'group_concat' : // @since 2.7 + case 'subqueries' : // @since 2.7 + return version_compare($version, '4.1', '>='); + break; + endswitch; + + return false; + } + + /** + * Retrieve the name of the function that called wpdb. + * + * Requires PHP 4.3 and searches up the list of functions until it reaches + * the one that would most logically had called this method. + * + * @since 2.5.0 + * + * @return string The name of the calling function + */ + function get_caller() { + // requires PHP 4.3+ + if ( !is_callable('debug_backtrace') ) + return ''; + + $bt = debug_backtrace(); + $caller = array(); + + $bt = array_reverse( $bt ); + foreach ( (array) $bt as $call ) { + if ( @$call['class'] == __CLASS__ ) + continue; + $function = $call['function']; + if ( isset( $call['class'] ) ) + $function = $call['class'] . "->$function"; + $caller[] = $function; + } + $caller = join( ', ', $caller ); + + return $caller; + } + + /** + * The database version number + * @param false|string|resource $dbh_or_table (not implemented) Which database to test. False = the currently selected database, string = the database containing the specified table, resource = the database corresponding to the specified mysql resource. + * @return false|string false on failure, version number on success + */ + function db_version() { + return preg_replace('/[^0-9.].*/', '', mysql_get_server_info( $this->dbh )); + } +} + +if ( ! isset($wpdb) ) { + /** + * WordPress Database Object, if it isn't set already in wp-content/db.php + * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database + * @since 0.71 + */ + $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); +} +?> diff --git a/wp-includes/wp-diff.php b/wp-includes/wp-diff.php new file mode 100644 index 0000000..3843223 --- /dev/null +++ b/wp-includes/wp-diff.php @@ -0,0 +1,471 @@ +$parent( $params ); + } + + /** + * @ignore + * + * @param string $header + * @return string + */ + function _startBlock( $header ) { + return ''; + } + + /** + * @ignore + * + * @param array $lines + * @param string $prefix + */ + function _lines( $lines, $prefix=' ' ) { + } + + /** + * @ignore + * + * @param string $line HTML-escape the value. + * @return string + */ + function addedLine( $line ) { + return "+{$line}"; + } + + /** + * @ignore + * + * @param string $line HTML-escape the value. + * @return string + */ + function deletedLine( $line ) { + return "-{$line}"; + } + + /** + * @ignore + * + * @param string $line HTML-escape the value. + * @return string + */ + function contextLine( $line ) { + return " {$line}"; + } + + /** + * @ignore + * + * @return string + */ + function emptyLine() { + return ' '; + } + + /** + * @ignore + * @access private + * + * @param array $lines + * @param bool $encode + * @return string + */ + function _added( $lines, $encode = true ) { + $r = ''; + foreach ($lines as $line) { + if ( $encode ) + $line = htmlspecialchars( $line ); + $r .= '' . $this->emptyLine() . $this->addedLine( $line ) . "\n"; + } + return $r; + } + + /** + * @ignore + * @access private + * + * @param array $lines + * @param bool $encode + * @return string + */ + function _deleted( $lines, $encode = true ) { + $r = ''; + foreach ($lines as $line) { + if ( $encode ) + $line = htmlspecialchars( $line ); + $r .= '' . $this->deletedLine( $line ) . $this->emptyLine() . "\n"; + } + return $r; + } + + /** + * @ignore + * @access private + * + * @param array $lines + * @param bool $encode + * @return string + */ + function _context( $lines, $encode = true ) { + $r = ''; + foreach ($lines as $line) { + if ( $encode ) + $line = htmlspecialchars( $line ); + $r .= '' . + $this->contextLine( $line ) . $this->contextLine( $line ) . "\n"; + } + return $r; + } + + /** + * Process changed lines to do word-by-word diffs for extra highlighting. + * + * (TRAC style) sometimes these lines can actually be deleted or added rows. + * We do additional processing to figure that out + * + * @access private + * @since 2.6.0 + * + * @param array $orig + * @param array $final + * @return string + */ + function _changed( $orig, $final ) { + $r = ''; + + // Does the aforementioned additional processing + // *_matches tell what rows are "the same" in orig and final. Those pairs will be diffed to get word changes + // match is numeric: an index in other column + // match is 'X': no match. It is a new row + // *_rows are column vectors for the orig column and the final column. + // row >= 0: an indix of the $orig or $final array + // row < 0: a blank row for that column + list($orig_matches, $final_matches, $orig_rows, $final_rows) = $this->interleave_changed_lines( $orig, $final ); + + + // These will hold the word changes as determined by an inline diff + $orig_diffs = array(); + $final_diffs = array(); + + // Compute word diffs for each matched pair using the inline diff + foreach ( $orig_matches as $o => $f ) { + if ( is_numeric($o) && is_numeric($f) ) { + $text_diff = new Text_Diff( 'auto', array( array($orig[$o]), array($final[$f]) ) ); + $renderer = new $this->inline_diff_renderer; + $diff = $renderer->render( $text_diff ); + + // If they're too different, don't include any or + if ( $diff_count = preg_match_all( '!(.*?|.*?)!', $diff, $diff_matches ) ) { + // length of all text between or + $stripped_matches = strlen(strip_tags( join(' ', $diff_matches[0]) )); + // since we count lengith of text between or (instead of picking just one), + // we double the length of chars not in those tags. + $stripped_diff = strlen(strip_tags( $diff )) * 2 - $stripped_matches; + $diff_ratio = $stripped_matches / $stripped_diff; + if ( $diff_ratio > $this->_diff_threshold ) + continue; // Too different. Don't save diffs. + } + + // Un-inline the diffs by removing del or ins + $orig_diffs[$o] = preg_replace( '|.*?|', '', $diff ); + $final_diffs[$f] = preg_replace( '|.*?|', '', $diff ); + } + } + + foreach ( array_keys($orig_rows) as $row ) { + // Both columns have blanks. Ignore them. + if ( $orig_rows[$row] < 0 && $final_rows[$row] < 0 ) + continue; + + // If we have a word based diff, use it. Otherwise, use the normal line. + $orig_line = isset($orig_diffs[$orig_rows[$row]]) + ? $orig_diffs[$orig_rows[$row]] + : htmlspecialchars($orig[$orig_rows[$row]]); + $final_line = isset($final_diffs[$final_rows[$row]]) + ? $final_diffs[$final_rows[$row]] + : htmlspecialchars($final[$final_rows[$row]]); + + if ( $orig_rows[$row] < 0 ) { // Orig is blank. This is really an added row. + $r .= $this->_added( array($final_line), false ); + } elseif ( $final_rows[$row] < 0 ) { // Final is blank. This is really a deleted row. + $r .= $this->_deleted( array($orig_line), false ); + } else { // A true changed row. + $r .= '' . $this->deletedLine( $orig_line ) . $this->addedLine( $final_line ) . "\n"; + } + } + + return $r; + } + + /** + * Takes changed blocks and matches which rows in orig turned into which rows in final. + * + * Returns + * *_matches ( which rows match with which ) + * *_rows ( order of rows in each column interleaved with blank rows as + * necessary ) + * + * @since 2.6.0 + * + * @param unknown_type $orig + * @param unknown_type $final + * @return unknown + */ + function interleave_changed_lines( $orig, $final ) { + + // Contains all pairwise string comparisons. Keys are such that this need only be a one dimensional array. + $matches = array(); + foreach ( array_keys($orig) as $o ) { + foreach ( array_keys($final) as $f ) { + $matches["$o,$f"] = $this->compute_string_distance( $orig[$o], $final[$f] ); + } + } + asort($matches); // Order by string distance. + + $orig_matches = array(); + $final_matches = array(); + + foreach ( $matches as $keys => $difference ) { + list($o, $f) = explode(',', $keys); + $o = (int) $o; + $f = (int) $f; + + // Already have better matches for these guys + if ( isset($orig_matches[$o]) && isset($final_matches[$f]) ) + continue; + + // First match for these guys. Must be best match + if ( !isset($orig_matches[$o]) && !isset($final_matches[$f]) ) { + $orig_matches[$o] = $f; + $final_matches[$f] = $o; + continue; + } + + // Best match of this final is already taken? Must mean this final is a new row. + if ( isset($orig_matches[$o]) ) + $final_matches[$f] = 'x'; + + // Best match of this orig is already taken? Must mean this orig is a deleted row. + elseif ( isset($final_matches[$f]) ) + $orig_matches[$o] = 'x'; + } + + // We read the text in this order + ksort($orig_matches); + ksort($final_matches); + + + // Stores rows and blanks for each column. + $orig_rows = $orig_rows_copy = array_keys($orig_matches); + $final_rows = array_keys($final_matches); + + // Interleaves rows with blanks to keep matches aligned. + // We may end up with some extraneous blank rows, but we'll just ignore them later. + foreach ( $orig_rows_copy as $orig_row ) { + $final_pos = array_search($orig_matches[$orig_row], $final_rows, true); + $orig_pos = (int) array_search($orig_row, $orig_rows, true); + + if ( false === $final_pos ) { // This orig is paired with a blank final. + array_splice( $final_rows, $orig_pos, 0, -1 ); + } elseif ( $final_pos < $orig_pos ) { // This orig's match is up a ways. Pad final with blank rows. + $diff_pos = $final_pos - $orig_pos; + while ( $diff_pos < 0 ) + array_splice( $final_rows, $orig_pos, 0, $diff_pos++ ); + } elseif ( $final_pos > $orig_pos ) { // This orig's match is down a ways. Pad orig with blank rows. + $diff_pos = $orig_pos - $final_pos; + while ( $diff_pos < 0 ) + array_splice( $orig_rows, $orig_pos, 0, $diff_pos++ ); + } + } + + + // Pad the ends with blank rows if the columns aren't the same length + $diff_count = count($orig_rows) - count($final_rows); + if ( $diff_count < 0 ) { + while ( $diff_count < 0 ) + array_push($orig_rows, $diff_count++); + } elseif ( $diff_count > 0 ) { + $diff_count = -1 * $diff_count; + while ( $diff_count < 0 ) + array_push($final_rows, $diff_count++); + } + + return array($orig_matches, $final_matches, $orig_rows, $final_rows); + +/* + // Debug + echo "\n\n\n\n\n"; + + echo "-- DEBUG Matches: Orig -> Final --"; + + foreach ( $orig_matches as $o => $f ) { + echo "\n\n\n\n\n"; + echo "ORIG: $o, FINAL: $f\n"; + var_dump($orig[$o],$final[$f]); + } + echo "\n\n\n\n\n"; + + echo "-- DEBUG Matches: Final -> Orig --"; + + foreach ( $final_matches as $f => $o ) { + echo "\n\n\n\n\n"; + echo "FINAL: $f, ORIG: $o\n"; + var_dump($final[$f],$orig[$o]); + } + echo "\n\n\n\n\n"; + + echo "-- DEBUG Rows: Orig -- Final --"; + + echo "\n\n\n\n\n"; + foreach ( $orig_rows as $row => $o ) { + if ( $o < 0 ) + $o = 'X'; + $f = $final_rows[$row]; + if ( $f < 0 ) + $f = 'X'; + echo "$o -- $f\n"; + } + echo "\n\n\n\n\n"; + + echo "-- END DEBUG --"; + + echo "\n\n\n\n\n"; + + return array($orig_matches, $final_matches, $orig_rows, $final_rows); +*/ + } + + /** + * Computes a number that is intended to reflect the "distance" between two strings. + * + * @since 2.6.0 + * + * @param string $string1 + * @param string $string2 + * @return int + */ + function compute_string_distance( $string1, $string2 ) { + // Vectors containing character frequency for all chars in each string + $chars1 = count_chars($string1); + $chars2 = count_chars($string2); + + // L1-norm of difference vector. + $difference = array_sum( array_map( array(&$this, 'difference'), $chars1, $chars2 ) ); + + // $string1 has zero length? Odd. Give huge penalty by not dividing. + if ( !$string1 ) + return $difference; + + // Return distance per charcter (of string1) + return $difference / strlen($string1); + } + + /** + * @ignore + * @since 2.6.0 + * + * @param int $a + * @param int $b + * @return int + */ + function difference( $a, $b ) { + return abs( $a - $b ); + } + +} + +/** + * Better word splitting than the PEAR package provides. + * + * @since 2.6.0 + * @uses Text_Diff_Renderer_inline Extends + */ +class WP_Text_Diff_Renderer_inline extends Text_Diff_Renderer_inline { + + /** + * @ignore + * @since 2.6.0 + * + * @param string $string + * @param string $newlineEscape + * @return string + */ + function _splitOnWords($string, $newlineEscape = "\n") { + $string = str_replace("\0", '', $string); + $words = preg_split( '/([^\w])/u', $string, -1, PREG_SPLIT_DELIM_CAPTURE ); + $words = str_replace( "\n", $newlineEscape, $words ); + return $words; + } + +} + +?> diff --git a/wp-links-opml.php b/wp-links-opml.php new file mode 100644 index 0000000..b917052 --- /dev/null +++ b/wp-links-opml.php @@ -0,0 +1,65 @@ +\n"; ?> + + + + Links for <?php echo esc_attr(get_bloginfo('name', 'display').$cat_name); ?> + GMT + + +name); + +?> + +term_id}"); + foreach ((array) $bookmarks as $bookmark) { + $title = esc_attr(apply_filters('link_title', $bookmark->link_name)); +?> + + + + + + diff --git a/wp-load.php b/wp-load.php new file mode 100644 index 0000000..aee3b39 --- /dev/null +++ b/wp-load.php @@ -0,0 +1,54 @@ +wp-config.php file. I need this before we can get started. Need more help? We got it. You can create a wp-config.php file through a web interface, but this doesn't work for all server setups. The safest way is to manually create the file.

    Create a Configuration File"/*/WP_I18N_NO_CONFIG*/, $path), /*WP_I18N_ERROR_TITLE*/"WordPress › Error"/*/WP_I18N_ERROR_TITLE*/, array('text_direction' => $text_direction)); + +} + +?> diff --git a/wp-login.php b/wp-login.php new file mode 100644 index 0000000..5378204 --- /dev/null +++ b/wp-login.php @@ -0,0 +1,556 @@ + element. + * @param string $message Optional. Message to display in header. + * @param WP_Error $wp_error Optional. WordPress Error Object + */ +function login_header($title = 'Log In', $message = '', $wp_error = '') { + global $error, $is_iphone; + + // Don't index any of these forms + add_filter( 'pre_option_blog_public', create_function( '$a', 'return 0;' ) ); + add_action( 'login_head', 'noindex' ); + + if ( empty($wp_error) ) + $wp_error = new WP_Error(); + ?> + +> + + <?php bloginfo('name'); ?> › <?php echo $title; ?> + + + + + + + + +

    +add('error', $error); + unset($error); + } + + if ( $wp_error->get_error_code() ) { + $errors = ''; + $messages = ''; + foreach ( $wp_error->get_error_codes() as $code ) { + $severity = $wp_error->get_error_data($code); + foreach ( $wp_error->get_error_messages($code) as $error ) { + if ( 'message' == $severity ) + $messages .= ' ' . $error . "
    \n"; + else + $errors .= ' ' . $error . "
    \n"; + } + } + if ( !empty($errors) ) + echo '
    ' . apply_filters('login_errors', $errors) . "
    \n"; + if ( !empty($messages) ) + echo '

    ' . apply_filters('login_messages', $messages) . "

    \n"; + } +} // End of login_header() + +/** + * Handles sending password retrieval email to user. + * + * @uses $wpdb WordPress Database object + * + * @return bool|WP_Error True: when finish. WP_Error on error + */ +function retrieve_password() { + global $wpdb; + + $errors = new WP_Error(); + + if ( empty( $_POST['user_login'] ) && empty( $_POST['user_email'] ) ) + $errors->add('empty_username', __('ERROR: Enter a username or e-mail address.')); + + if ( strpos($_POST['user_login'], '@') ) { + $user_data = get_user_by_email(trim($_POST['user_login'])); + if ( empty($user_data) ) + $errors->add('invalid_email', __('ERROR: There is no user registered with that email address.')); + } else { + $login = trim($_POST['user_login']); + $user_data = get_userdatabylogin($login); + } + + do_action('lostpassword_post'); + + if ( $errors->get_error_code() ) + return $errors; + + if ( !$user_data ) { + $errors->add('invalidcombo', __('ERROR: Invalid username or e-mail.')); + return $errors; + } + + // redefining user_login ensures we return the right case in the email + $user_login = $user_data->user_login; + $user_email = $user_data->user_email; + + do_action('retreive_password', $user_login); // Misspelled and deprecated + do_action('retrieve_password', $user_login); + + $allow = apply_filters('allow_password_reset', true, $user_data->ID); + + if ( ! $allow ) + return new WP_Error('no_password_reset', __('Password reset is not allowed for this user')); + else if ( is_wp_error($allow) ) + return $allow; + + $key = $wpdb->get_var($wpdb->prepare("SELECT user_activation_key FROM $wpdb->users WHERE user_login = %s", $user_login)); + if ( empty($key) ) { + // Generate something random for a key... + $key = wp_generate_password(20, false); + do_action('retrieve_password_key', $user_login, $key); + // Now insert the new md5 key into the db + $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login)); + } + $message = __('Someone has asked to reset the password for the following site and username.') . "\r\n\r\n"; + $message .= get_option('siteurl') . "\r\n\r\n"; + $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n"; + $message .= __('To reset your password visit the following address, otherwise just ignore this email and nothing will happen.') . "\r\n\r\n"; + $message .= site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n"; + + $title = sprintf(__('[%s] Password Reset'), get_option('blogname')); + + $title = apply_filters('retrieve_password_title', $title); + $message = apply_filters('retrieve_password_message', $message, $key); + + if ( $message && !wp_mail($user_email, $title, $message) ) + die('

    ' . __('The e-mail could not be sent.') . "
    \n" . __('Possible reason: your host may have disabled the mail() function...') . '

    '); + + return true; +} + +/** + * Handles resetting the user's password. + * + * @uses $wpdb WordPress Database object + * + * @param string $key Hash to validate sending user's password + * @return bool|WP_Error + */ +function reset_password($key, $login) { + global $wpdb; + + $key = preg_replace('/[^a-z0-9]/i', '', $key); + + if ( empty( $key ) || !is_string( $key ) ) + return new WP_Error('invalid_key', __('Invalid key')); + + if ( empty($login) || !is_string($login) ) + return new WP_Error('invalid_key', __('Invalid key')); + + $user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->users WHERE user_activation_key = %s AND user_login = %s", $key, $login)); + if ( empty( $user ) ) + return new WP_Error('invalid_key', __('Invalid key')); + + // Generate something random for a password... + $new_pass = wp_generate_password(); + + do_action('password_reset', $user, $new_pass); + + wp_set_password($new_pass, $user->ID); + update_usermeta($user->ID, 'default_password_nag', true); //Set up the Password change nag. + $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n"; + $message .= sprintf(__('Password: %s'), $new_pass) . "\r\n"; + $message .= site_url('wp-login.php', 'login') . "\r\n"; + + $title = sprintf(__('[%s] Your new password'), get_option('blogname')); + + $title = apply_filters('password_reset_title', $title); + $message = apply_filters('password_reset_message', $message, $new_pass); + + if ( $message && !wp_mail($user->user_email, $title, $message) ) + die('

    ' . __('The e-mail could not be sent.') . "
    \n" . __('Possible reason: your host may have disabled the mail() function...') . '

    '); + + wp_password_change_notification($user); + + return true; +} + +/** + * Handles registering a new user. + * + * @param string $user_login User's username for logging in + * @param string $user_email User's email address to send password and add + * @return int|WP_Error Either user's ID or error on failure. + */ +function register_new_user($user_login, $user_email) { + $errors = new WP_Error(); + + $user_login = sanitize_user( $user_login ); + $user_email = apply_filters( 'user_registration_email', $user_email ); + + // Check the username + if ( $user_login == '' ) + $errors->add('empty_username', __('ERROR: Please enter a username.')); + elseif ( !validate_username( $user_login ) ) { + $errors->add('invalid_username', __('ERROR: This username is invalid. Please enter a valid username.')); + $user_login = ''; + } elseif ( username_exists( $user_login ) ) + $errors->add('username_exists', __('ERROR: This username is already registered, please choose another one.')); + + // Check the e-mail address + if ($user_email == '') { + $errors->add('empty_email', __('ERROR: Please type your e-mail address.')); + } elseif ( !is_email( $user_email ) ) { + $errors->add('invalid_email', __('ERROR: The email address isn’t correct.')); + $user_email = ''; + } elseif ( email_exists( $user_email ) ) + $errors->add('email_exists', __('ERROR: This email is already registered, please choose another one.')); + + do_action('register_post', $user_login, $user_email, $errors); + + $errors = apply_filters( 'registration_errors', $errors ); + + if ( $errors->get_error_code() ) + return $errors; + + $user_pass = wp_generate_password(); + $user_id = wp_create_user( $user_login, $user_pass, $user_email ); + if ( !$user_id ) { + $errors->add('registerfail', sprintf(__('ERROR: Couldn’t register you... please contact the webmaster !'), get_option('admin_email'))); + return $errors; + } + + wp_new_user_notification($user_id, $user_pass); + + return $user_id; +} + +// +// Main +// + +$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'login'; +$errors = new WP_Error(); + +if ( isset($_GET['key']) ) + $action = 'resetpass'; + +// validate action so as to default to the login screen +if ( !in_array($action, array('logout', 'lostpassword', 'retrievepassword', 'resetpass', 'rp', 'register', 'login')) && false === has_filter('login_form_' . $action) ) + $action = 'login'; + +nocache_headers(); + +header('Content-Type: '.get_bloginfo('html_type').'; charset='.get_bloginfo('charset')); + +if ( defined('RELOCATE') ) { // Move flag is set + if ( isset( $_SERVER['PATH_INFO'] ) && ($_SERVER['PATH_INFO'] != $_SERVER['PHP_SELF']) ) + $_SERVER['PHP_SELF'] = str_replace( $_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF'] ); + + $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://'; + if ( dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) != get_option('siteurl') ) + update_option('siteurl', dirname($schema . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']) ); +} + +//Set a cookie now to see if they are supported by the browser. +setcookie(TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN); +if ( SITECOOKIEPATH != COOKIEPATH ) + setcookie(TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN); + +// allow plugins to override the default actions, and to add extra actions if they want +do_action('login_form_' . $action); + +$http_post = ('POST' == $_SERVER['REQUEST_METHOD']); +switch ($action) { + +case 'logout' : + check_admin_referer('log-out'); + wp_logout(); + + $redirect_to = 'wp-login.php?loggedout=true'; + if ( isset( $_REQUEST['redirect_to'] ) ) + $redirect_to = $_REQUEST['redirect_to']; + + wp_safe_redirect($redirect_to); + exit(); + +break; + +case 'lostpassword' : +case 'retrievepassword' : + if ( $http_post ) { + $errors = retrieve_password(); + if ( !is_wp_error($errors) ) { + wp_redirect('wp-login.php?checkemail=confirm'); + exit(); + } + } + + if ( isset($_GET['error']) && 'invalidkey' == $_GET['error'] ) $errors->add('invalidkey', __('Sorry, that key does not appear to be valid.')); + + do_action('lost_password'); + login_header(__('Lost Password'), '

    ' . __('Please enter your username or e-mail address. You will receive a new password via e-mail.') . '

    ', $errors); + + $user_login = isset($_POST['user_login']) ? stripslashes($_POST['user_login']) : ''; + +?> + +
    +

    + +

    + +

    +
    + + + +
    + +

    + + + + +' . __('Register For This Site') . '

    ', $errors); +?> + +
    +

    + +

    +

    + +

    + +

    +
    +

    +
    + + + +
    + +

    + + + + +ID) ) { + $secure_cookie = true; + force_ssl_admin(true); + } + } + } + + if ( isset( $_REQUEST['redirect_to'] ) ) { + $redirect_to = $_REQUEST['redirect_to']; + // Redirect to https if user wants ssl + if ( $secure_cookie && false !== strpos($redirect_to, 'wp-admin') ) + $redirect_to = preg_replace('|^http://|', 'https://', $redirect_to); + } else { + $redirect_to = admin_url(); + } + + if ( !$secure_cookie && is_ssl() && force_ssl_login() && !force_ssl_admin() && ( 0 !== strpos($redirect_to, 'https') ) && ( 0 === strpos($redirect_to, 'http') ) ) + $secure_cookie = false; + + $user = wp_signon('', $secure_cookie); + + $redirect_to = apply_filters('login_redirect', $redirect_to, isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '', $user); + + if ( !is_wp_error($user) ) { + // If the user can't edit posts, send them to their profile. + if ( !$user->has_cap('edit_posts') && ( empty( $redirect_to ) || $redirect_to == 'wp-admin/' || $redirect_to == admin_url() ) ) + $redirect_to = admin_url('profile.php'); + wp_safe_redirect($redirect_to); + exit(); + } + + $errors = $user; + // Clear errors if loggedout is set. + if ( !empty($_GET['loggedout']) ) + $errors = new WP_Error(); + + // If cookies are disabled we can't log in even with a valid user+pass + if ( isset($_POST['testcookie']) && empty($_COOKIE[TEST_COOKIE]) ) + $errors->add('test_cookie', __("ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.")); + + // Some parts of this script use the main login form to display a message + if ( isset($_GET['loggedout']) && TRUE == $_GET['loggedout'] ) $errors->add('loggedout', __('You are now logged out.'), 'message'); + elseif ( isset($_GET['registration']) && 'disabled' == $_GET['registration'] ) $errors->add('registerdisabled', __('User registration is currently not allowed.')); + elseif ( isset($_GET['checkemail']) && 'confirm' == $_GET['checkemail'] ) $errors->add('confirm', __('Check your e-mail for the confirmation link.'), 'message'); + elseif ( isset($_GET['checkemail']) && 'newpass' == $_GET['checkemail'] ) $errors->add('newpass', __('Check your e-mail for your new password.'), 'message'); + elseif ( isset($_GET['checkemail']) && 'registered' == $_GET['checkemail'] ) $errors->add('registered', __('Registration complete. Please check your e-mail.'), 'message'); + + login_header(__('Log In'), '', $errors); + + if ( isset($_POST['log']) ) + $user_login = ( 'incorrect_password' == $errors->get_error_code() || 'empty_password' == $errors->get_error_code() ) ? esc_attr(stripslashes($_POST['log'])) : ''; +?> + + +
    +

    + +

    +

    + +

    + +

    +

    + + + +

    +
    + + + + + + +

    + + + + + diff --git a/wp-mail.php b/wp-mail.php new file mode 100644 index 0000000..4dc4ed0 --- /dev/null +++ b/wp-mail.php @@ -0,0 +1,213 @@ + Writing + * + * @package WordPress + */ + +/** Make sure that the WordPress bootstrap has run before continuing. */ +require(dirname(__FILE__) . '/wp-load.php'); + +/** Get the POP3 class with which to access the mailbox. */ +require_once( ABSPATH . WPINC . '/class-pop3.php' ); + +$time_difference = get_option('gmt_offset') * 3600; + +$phone_delim = '::'; + +$pop3 = new POP3(); + +if ( ! $pop3->connect(get_option('mailserver_url'), get_option('mailserver_port') ) || + ! $pop3->user(get_option('mailserver_login')) || + ( ! $count = $pop3->pass(get_option('mailserver_pass')) ) ) { + $pop3->quit(); + wp_die( ( 0 === $count ) ? __('There doesn’t seem to be any new mail.') : esc_html($pop3->ERROR) ); +} + +for ( $i = 1; $i <= $count; $i++ ) { + + $message = $pop3->get($i); + + $bodysignal = false; + $boundary = ''; + $charset = ''; + $content = ''; + $content_type = ''; + $content_transfer_encoding = ''; + $post_author = 1; + $author_found = false; + $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); + foreach ($message as $line) { + // body signal + if ( strlen($line) < 3 ) + $bodysignal = true; + if ( $bodysignal ) { + $content .= $line; + } else { + if ( preg_match('/Content-Type: /i', $line) ) { + $content_type = trim($line); + $content_type = substr($content_type, 14, strlen($content_type) - 14); + $content_type = explode(';', $content_type); + if ( ! empty( $content_type[1] ) ) { + $charset = explode('=', $content_type[1]); + $charset = ( ! empty( $charset[1] ) ) ? trim($charset[1]) : ''; + } + $content_type = $content_type[0]; + } + if ( preg_match('/Content-Transfer-Encoding: /i', $line) ) { + $content_transfer_encoding = trim($line); + $content_transfer_encoding = substr($content_transfer_encoding, 27, strlen($content_transfer_encoding) - 27); + $content_transfer_encoding = explode(';', $content_transfer_encoding); + $content_transfer_encoding = $content_transfer_encoding[0]; + } + if ( ( $content_type == 'multipart/alternative' ) && ( false !== strpos($line, 'boundary="') ) && ( '' == $boundary ) ) { + $boundary = trim($line); + $boundary = explode('"', $boundary); + $boundary = $boundary[1]; + } + if (preg_match('/Subject: /i', $line)) { + $subject = trim($line); + $subject = substr($subject, 9, strlen($subject) - 9); + // Captures any text in the subject before $phone_delim as the subject + if ( function_exists('iconv_mime_decode') ) { + $subject = iconv_mime_decode($subject, 2, get_option('blog_charset')); + } else { + $subject = wp_iso_descrambler($subject); + } + $subject = explode($phone_delim, $subject); + $subject = $subject[0]; + } + + // Set the author using the email address (From or Reply-To, the last used) + // otherwise use the site admin + if ( preg_match('/(From|Reply-To): /', $line) ) { + if ( preg_match('|[a-z0-9_.-]+@[a-z0-9_.-]+(?!.*<)|i', $line, $matches) ) + $author = $matches[0]; + else + $author = trim($line); + $author = sanitize_email($author); + if ( is_email($author) ) { + echo '

    ' . sprintf(__('Author is %s'), $author) . '

    '; + $userdata = get_user_by_email($author); + if ( empty($userdata) ) { + $author_found = false; + } else { + $post_author = $userdata->ID; + $author_found = true; + } + } else { + $author_found = false; + } + } + + if (preg_match('/Date: /i', $line)) { // of the form '20 Mar 2002 20:32:37' + $ddate = trim($line); + $ddate = str_replace('Date: ', '', $ddate); + if (strpos($ddate, ',')) { + $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate))); + } + $date_arr = explode(' ', $ddate); + $date_time = explode(':', $date_arr[3]); + + $ddate_H = $date_time[0]; + $ddate_i = $date_time[1]; + $ddate_s = $date_time[2]; + + $ddate_m = $date_arr[1]; + $ddate_d = $date_arr[0]; + $ddate_Y = $date_arr[2]; + for ( $j = 0; $j < 12; $j++ ) { + if ( $ddate_m == $dmonths[$j] ) { + $ddate_m = $j+1; + } + } + + $time_zn = intval($date_arr[4]) * 36; + $ddate_U = gmmktime($ddate_H, $ddate_i, $ddate_s, $ddate_m, $ddate_d, $ddate_Y); + $ddate_U = $ddate_U - $time_zn; + $post_date = gmdate('Y-m-d H:i:s', $ddate_U + $time_difference); + $post_date_gmt = gmdate('Y-m-d H:i:s', $ddate_U); + } + } + } + + // Set $post_status based on $author_found and on author's publish_posts capability + if ( $author_found ) { + $user = new WP_User($post_author); + $post_status = ( $user->has_cap('publish_posts') ) ? 'publish' : 'pending'; + } else { + // Author not found in DB, set status to pending. Author already set to admin. + $post_status = 'pending'; + } + + $subject = trim($subject); + + if ( $content_type == 'multipart/alternative' ) { + $content = explode('--'.$boundary, $content); + $content = $content[2]; + // match case-insensitive content-transfer-encoding + if ( preg_match( '/Content-Transfer-Encoding: quoted-printable/i', $content, $delim) ) { + $content = explode($delim[0], $content); + $content = $content[1]; + } + $content = strip_tags($content, '


    '); + } + $content = trim($content); + + //Give Post-By-Email extending plugins full access to the content + //Either the raw content or the content of the last quoted-printable section + $content = apply_filters('wp_mail_original_content', $content); + + if ( false !== stripos($content_transfer_encoding, "quoted-printable") ) { + $content = quoted_printable_decode($content); + } + + if ( function_exists('iconv') && ! empty( $charset ) ) { + $content = iconv($charset, get_option('blog_charset'), $content); + } + + // Captures any text in the body after $phone_delim as the body + $content = explode($phone_delim, $content); + $content = empty( $content[1] ) ? $content[0] : $content[1]; + + $content = trim($content); + + $post_content = apply_filters('phone_content', $content); + + $post_title = xmlrpc_getposttitle($content); + + if ($post_title == '') $post_title = $subject; + + $post_category = array(get_option('default_email_category')); + + $post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status'); + $post_data = add_magic_quotes($post_data); + + $post_ID = wp_insert_post($post_data); + if ( is_wp_error( $post_ID ) ) + echo "\n" . $post_ID->get_error_message(); + + // We couldn't post, for whatever reason. Better move forward to the next email. + if ( empty( $post_ID ) ) + continue; + + do_action('publish_phone', $post_ID); + + echo "\n

    " . sprintf(__('Author: %s'), esc_html($post_author)) . '

    '; + echo "\n

    " . sprintf(__('Posted title: %s'), esc_html($post_title)) . '

    '; + + if(!$pop3->delete($i)) { + echo '

    ' . sprintf(__('Oops: %s'), esc_html($pop3->ERROR)) . '

    '; + $pop3->reset(); + exit; + } else { + echo '

    ' . sprintf(__('Mission complete. Message %s deleted.'), $i) . '

    '; + } + +} + +$pop3->quit(); + +?> diff --git a/wp-pass.php b/wp-pass.php new file mode 100644 index 0000000..0ad6e5e --- /dev/null +++ b/wp-pass.php @@ -0,0 +1,19 @@ + \ No newline at end of file diff --git a/wp-rdf.php b/wp-rdf.php new file mode 100644 index 0000000..3c8f005 --- /dev/null +++ b/wp-rdf.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/wp-register.php b/wp-register.php new file mode 100644 index 0000000..caad4f2 --- /dev/null +++ b/wp-register.php @@ -0,0 +1,15 @@ + \ No newline at end of file diff --git a/wp-rss.php b/wp-rss.php new file mode 100644 index 0000000..0ae63a2 --- /dev/null +++ b/wp-rss.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/wp-rss2.php b/wp-rss2.php new file mode 100644 index 0000000..78daa6d --- /dev/null +++ b/wp-rss2.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/wp-settings.php b/wp-settings.php new file mode 100644 index 0000000..af78449 --- /dev/null +++ b/wp-settings.php @@ -0,0 +1,691 @@ + $v ) + if ( !in_array($k, $noUnset) && isset($GLOBALS[$k]) ) { + $GLOBALS[$k] = NULL; + unset($GLOBALS[$k]); + } +} + +wp_unregister_GLOBALS(); + +unset( $wp_filter, $cache_lastcommentmodified, $cache_lastpostdate ); + +// Force REQUEST to be GET + POST. If SERVER, COOKIE, or ENV are needed, use those superglobals directly. +$_REQUEST = array_merge($_GET, $_POST); + +/** + * The $blog_id global, which you can change in the config allows you to create a simple + * multiple blog installation using just one WordPress and changing $blog_id around. + * + * @global int $blog_id + * @since 2.0.0 + */ +if ( ! isset($blog_id) ) + $blog_id = 1; + +// Fix for IIS when running with PHP ISAPI +if ( empty( $_SERVER['REQUEST_URI'] ) || ( php_sapi_name() != 'cgi-fcgi' && preg_match( '/^Microsoft-IIS\//', $_SERVER['SERVER_SOFTWARE'] ) ) ) { + + // IIS Mod-Rewrite + if (isset($_SERVER['HTTP_X_ORIGINAL_URL'])) { + $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL']; + } + // IIS Isapi_Rewrite + else if (isset($_SERVER['HTTP_X_REWRITE_URL'])) { + $_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL']; + } + else + { + // Use ORIG_PATH_INFO if there is no PATH_INFO + if ( !isset($_SERVER['PATH_INFO']) && isset($_SERVER['ORIG_PATH_INFO']) ) + $_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO']; + + // Some IIS + PHP configurations puts the script-name in the path-info (No need to append it twice) + if ( isset($_SERVER['PATH_INFO']) ) { + if ( $_SERVER['PATH_INFO'] == $_SERVER['SCRIPT_NAME'] ) + $_SERVER['REQUEST_URI'] = $_SERVER['PATH_INFO']; + else + $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO']; + } + + // Append the query string if it exists and isn't null + if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) { + $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING']; + } + } +} + +// Fix for PHP as CGI hosts that set SCRIPT_FILENAME to something ending in php.cgi for all requests +if ( isset($_SERVER['SCRIPT_FILENAME']) && ( strpos($_SERVER['SCRIPT_FILENAME'], 'php.cgi') == strlen($_SERVER['SCRIPT_FILENAME']) - 7 ) ) + $_SERVER['SCRIPT_FILENAME'] = $_SERVER['PATH_TRANSLATED']; + +// Fix for Dreamhost and other PHP as CGI hosts +if (strpos($_SERVER['SCRIPT_NAME'], 'php.cgi') !== false) + unset($_SERVER['PATH_INFO']); + +// Fix empty PHP_SELF +$PHP_SELF = $_SERVER['PHP_SELF']; +if ( empty($PHP_SELF) ) + $_SERVER['PHP_SELF'] = $PHP_SELF = preg_replace("/(\?.*)?$/",'',$_SERVER["REQUEST_URI"]); + +if ( version_compare( '4.3', phpversion(), '>' ) ) { + die( sprintf( /*WP_I18N_OLD_PHP*/'Your server is running PHP version %s but WordPress requires at least 4.3.'/*/WP_I18N_OLD_PHP*/, phpversion() ) ); +} + +if ( !defined('WP_CONTENT_DIR') ) + define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' ); // no trailing slash, full paths only - WP_CONTENT_URL is defined further down + +if ( file_exists(ABSPATH . '.maintenance') && !defined('WP_INSTALLING') ) { + include(ABSPATH . '.maintenance'); + // If the $upgrading timestamp is older than 10 minutes, don't die. + if ( ( time() - $upgrading ) < 600 ) { + if ( file_exists( WP_CONTENT_DIR . '/maintenance.php' ) ) { + require_once( WP_CONTENT_DIR . '/maintenance.php' ); + die(); + } + + $protocol = $_SERVER["SERVER_PROTOCOL"]; + if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol ) + $protocol = 'HTTP/1.0'; + header( "$protocol 503 Service Unavailable", true, 503 ); + header( 'Content-Type: text/html; charset=utf-8' ); +?> + + + + + Maintenance + + + +

    Briefly unavailable for scheduled maintenance. Check back in a minute.

    + + + + * $nTimePageTookToExecute = timer_stop(); + * echo $nTimePageTookToExecute; + * + * + * Or instead, you can do: + * + * timer_stop(1); + * + * which will do what the above does. If you need the result, you can assign it to a variable, but + * most cases, you only need to echo it. + * + * @since 0.71 + * @global int $timestart Seconds and Microseconds added together from when timer_start() is called + * @global int $timeend Seconds and Microseconds added together from when function is called + * + * @param int $display Use '0' or null to not echo anything and 1 to echo the total time + * @param int $precision The amount of digits from the right of the decimal to display. Default is 3. + * @return float The "second.microsecond" finished time calculation + */ +function timer_stop($display = 0, $precision = 3) { //if called like timer_stop(1), will echo $timetotal + global $timestart, $timeend; + $mtime = microtime(); + $mtime = explode(' ',$mtime); + $mtime = $mtime[1] + $mtime[0]; + $timeend = $mtime; + $timetotal = $timeend-$timestart; + $r = ( function_exists('number_format_i18n') ) ? number_format_i18n($timetotal, $precision) : number_format($timetotal, $precision); + if ( $display ) + echo $r; + return $r; +} +timer_start(); + +// Add define('WP_DEBUG',true); to wp-config.php to enable display of notices during development. +if (defined('WP_DEBUG') and WP_DEBUG == true) { + error_reporting(E_ALL); +} else { + if ( defined('E_RECOVERABLE_ERROR') ) + error_reporting(E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR); + else + error_reporting(E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING); +} + +// For an advanced caching plugin to use, static because you would only want one +if ( defined('WP_CACHE') ) + @include WP_CONTENT_DIR . '/advanced-cache.php'; + +/** + * Stores the location of the WordPress directory of functions, classes, and core content. + * + * @since 1.0.0 + */ +define('WPINC', 'wp-includes'); + +if ( !defined('WP_LANG_DIR') ) { + /** + * Stores the location of the language directory. First looks for language folder in WP_CONTENT_DIR + * and uses that folder if it exists. Or it uses the "languages" folder in WPINC. + * + * @since 2.1.0 + */ + if ( file_exists(WP_CONTENT_DIR . '/languages') && @is_dir(WP_CONTENT_DIR . '/languages') ) { + define('WP_LANG_DIR', WP_CONTENT_DIR . '/languages'); // no leading slash, no trailing slash, full path, not relative to ABSPATH + if (!defined('LANGDIR')) { + // Old static relative path maintained for limited backwards compatibility - won't work in some cases + define('LANGDIR', 'wp-content/languages'); + } + } else { + define('WP_LANG_DIR', ABSPATH . WPINC . '/languages'); // no leading slash, no trailing slash, full path, not relative to ABSPATH + if (!defined('LANGDIR')) { + // Old relative path maintained for backwards compatibility + define('LANGDIR', WPINC . '/languages'); + } + } +} + +require (ABSPATH . WPINC . '/compat.php'); +require (ABSPATH . WPINC . '/functions.php'); +require (ABSPATH . WPINC . '/classes.php'); + +require_wp_db(); + +if ( !empty($wpdb->error) ) + dead_db(); + +/** + * Format specifiers for DB columns. Columns not listed here default to %s. + * @since 2.8.0 + * @see wpdb:$field_types + * @see wpdb:prepare() + * @see wpdb:insert() + * @see wpdb:update() + */ +$wpdb->field_types = array( 'post_author' => '%d', 'post_parent' => '%d', 'menu_order' => '%d', 'term_id' => '%d', 'term_group' => '%d', 'term_taxonomy_id' => '%d', + 'parent' => '%d', 'count' => '%d','object_id' => '%d', 'term_order' => '%d', 'ID' => '%d', 'commment_ID' => '%d', 'comment_post_ID' => '%d', 'comment_parent' => '%d', + 'user_id' => '%d', 'link_id' => '%d', 'link_owner' => '%d', 'link_rating' => '%d', 'option_id' => '%d', 'blog_id' => '%d', 'meta_id' => '%d', 'post_id' => '%d', + 'user_status' => '%d', 'umeta_id' => '%d', 'comment_karma' => '%d', 'comment_count' => '%d'); + +$prefix = $wpdb->set_prefix($table_prefix); + +if ( is_wp_error($prefix) ) + wp_die(/*WP_I18N_BAD_PREFIX*/'ERROR: $table_prefix in wp-config.php can only contain numbers, letters, and underscores.'/*/WP_I18N_BAD_PREFIX*/); + +/** + * Copy an object. + * + * Returns a cloned copy of an object. + * + * @since 2.7.0 + * + * @param object $object The object to clone + * @return object The cloned object + */ +function wp_clone( $object ) { + static $can_clone; + if ( !isset( $can_clone ) ) { + $can_clone = version_compare( phpversion(), '5.0', '>=' ); + } + return $can_clone ? clone( $object ) : $object; +} + +if ( file_exists(WP_CONTENT_DIR . '/object-cache.php') ) { + require_once (WP_CONTENT_DIR . '/object-cache.php'); + $_wp_using_ext_object_cache = true; +} else { + require_once (ABSPATH . WPINC . '/cache.php'); + $_wp_using_ext_object_cache = false; +} + +wp_cache_init(); +if ( function_exists('wp_cache_add_global_groups') ) { + wp_cache_add_global_groups(array ('users', 'userlogins', 'usermeta')); + wp_cache_add_non_persistent_groups(array( 'comment', 'counts', 'plugins' )); +} + +require (ABSPATH . WPINC . '/plugin.php'); +require (ABSPATH . WPINC . '/default-filters.php'); +include_once(ABSPATH . WPINC . '/pomo/mo.php'); +require_once (ABSPATH . WPINC . '/l10n.php'); + +if ( !is_blog_installed() && (strpos($_SERVER['PHP_SELF'], 'install.php') === false && !defined('WP_INSTALLING')) ) { + if ( defined('WP_SITEURL') ) + $link = WP_SITEURL . '/wp-admin/install.php'; + elseif (strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false) + $link = preg_replace('|/wp-admin/?.*?$|', '/', $_SERVER['PHP_SELF']) . 'wp-admin/install.php'; + else + $link = preg_replace('|/[^/]+?$|', '/', $_SERVER['PHP_SELF']) . 'wp-admin/install.php'; + require_once(ABSPATH . WPINC . '/kses.php'); + require_once(ABSPATH . WPINC . '/pluggable.php'); + require_once(ABSPATH . WPINC . '/formatting.php'); + wp_redirect($link); + die(); // have to die here ~ Mark +} + +require (ABSPATH . WPINC . '/formatting.php'); +require (ABSPATH . WPINC . '/capabilities.php'); +require (ABSPATH . WPINC . '/query.php'); +require (ABSPATH . WPINC . '/theme.php'); +require (ABSPATH . WPINC . '/user.php'); +require (ABSPATH . WPINC . '/general-template.php'); +require (ABSPATH . WPINC . '/link-template.php'); +require (ABSPATH . WPINC . '/author-template.php'); +require (ABSPATH . WPINC . '/post.php'); +require (ABSPATH . WPINC . '/post-template.php'); +require (ABSPATH . WPINC . '/category.php'); +require (ABSPATH . WPINC . '/category-template.php'); +require (ABSPATH . WPINC . '/comment.php'); +require (ABSPATH . WPINC . '/comment-template.php'); +require (ABSPATH . WPINC . '/rewrite.php'); +require (ABSPATH . WPINC . '/feed.php'); +require (ABSPATH . WPINC . '/bookmark.php'); +require (ABSPATH . WPINC . '/bookmark-template.php'); +require (ABSPATH . WPINC . '/kses.php'); +require (ABSPATH . WPINC . '/cron.php'); +require (ABSPATH . WPINC . '/version.php'); +require (ABSPATH . WPINC . '/deprecated.php'); +require (ABSPATH . WPINC . '/script-loader.php'); +require (ABSPATH . WPINC . '/taxonomy.php'); +require (ABSPATH . WPINC . '/update.php'); +require (ABSPATH . WPINC . '/canonical.php'); +require (ABSPATH . WPINC . '/shortcodes.php'); +require (ABSPATH . WPINC . '/media.php'); +require (ABSPATH . WPINC . '/http.php'); +require (ABSPATH . WPINC . '/widgets.php'); + +if ( !defined('WP_CONTENT_URL') ) + define( 'WP_CONTENT_URL', get_option('siteurl') . '/wp-content'); // full url - WP_CONTENT_DIR is defined further up + +/** + * Allows for the plugins directory to be moved from the default location. + * + * @since 2.6.0 + */ +if ( !defined('WP_PLUGIN_DIR') ) + define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' ); // full path, no trailing slash + +/** + * Allows for the plugins directory to be moved from the default location. + * + * @since 2.6.0 + */ +if ( !defined('WP_PLUGIN_URL') ) + define( 'WP_PLUGIN_URL', WP_CONTENT_URL . '/plugins' ); // full url, no trailing slash + +/** + * Allows for the plugins directory to be moved from the default location. + * + * @since 2.1.0 + */ +if ( !defined('PLUGINDIR') ) + define( 'PLUGINDIR', 'wp-content/plugins' ); // Relative to ABSPATH. For back compat. + +/** + * Allows for the mu-plugins directory to be moved from the default location. + * + * @since 2.8.0 + */ +if ( !defined('WPMU_PLUGIN_DIR') ) + define( 'WPMU_PLUGIN_DIR', WP_CONTENT_DIR . '/mu-plugins' ); // full path, no trailing slash + +/** + * Allows for the mu-plugins directory to be moved from the default location. + * + * @since 2.8.0 + */ +if ( !defined('WPMU_PLUGIN_URL') ) + define( 'WPMU_PLUGIN_URL', WP_CONTENT_URL . '/mu-plugins' ); // full url, no trailing slash + +/** + * Allows for the mu-plugins directory to be moved from the default location. + * + * @since 2.8.0 + */ +if ( !defined( 'MUPLUGINDIR' ) ) + define( 'MUPLUGINDIR', 'wp-content/mu-plugins' ); // Relative to ABSPATH. For back compat. + +if ( is_dir( WPMU_PLUGIN_DIR ) ) { + if ( $dh = opendir( WPMU_PLUGIN_DIR ) ) { + while ( ( $plugin = readdir( $dh ) ) !== false ) { + if ( substr( $plugin, -4 ) == '.php' ) { + include_once( WPMU_PLUGIN_DIR . '/' . $plugin ); + } + } + } +} +do_action('muplugins_loaded'); + +/** + * Used to guarantee unique hash cookies + * @since 1.5 + */ +define('COOKIEHASH', md5(get_option('siteurl'))); + +/** + * Should be exactly the same as the default value of SECRET_KEY in wp-config-sample.php + * @since 2.5.0 + */ +$wp_default_secret_key = 'put your unique phrase here'; + +/** + * It is possible to define this in wp-config.php + * @since 2.0.0 + */ +if ( !defined('USER_COOKIE') ) + define('USER_COOKIE', 'wordpressuser_' . COOKIEHASH); + +/** + * It is possible to define this in wp-config.php + * @since 2.0.0 + */ +if ( !defined('PASS_COOKIE') ) + define('PASS_COOKIE', 'wordpresspass_' . COOKIEHASH); + +/** + * It is possible to define this in wp-config.php + * @since 2.5.0 + */ +if ( !defined('AUTH_COOKIE') ) + define('AUTH_COOKIE', 'wordpress_' . COOKIEHASH); + +/** + * It is possible to define this in wp-config.php + * @since 2.6.0 + */ +if ( !defined('SECURE_AUTH_COOKIE') ) + define('SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH); + +/** + * It is possible to define this in wp-config.php + * @since 2.6.0 + */ +if ( !defined('LOGGED_IN_COOKIE') ) + define('LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH); + +/** + * It is possible to define this in wp-config.php + * @since 2.3.0 + */ +if ( !defined('TEST_COOKIE') ) + define('TEST_COOKIE', 'wordpress_test_cookie'); + +/** + * It is possible to define this in wp-config.php + * @since 1.2.0 + */ +if ( !defined('COOKIEPATH') ) + define('COOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('home') . '/' ) ); + +/** + * It is possible to define this in wp-config.php + * @since 1.5.0 + */ +if ( !defined('SITECOOKIEPATH') ) + define('SITECOOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('siteurl') . '/' ) ); + +/** + * It is possible to define this in wp-config.php + * @since 2.6.0 + */ +if ( !defined('ADMIN_COOKIE_PATH') ) + define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' ); + +/** + * It is possible to define this in wp-config.php + * @since 2.6.0 + */ +if ( !defined('PLUGINS_COOKIE_PATH') ) + define( 'PLUGINS_COOKIE_PATH', preg_replace('|https?://[^/]+|i', '', WP_PLUGIN_URL) ); + +/** + * It is possible to define this in wp-config.php + * @since 2.0.0 + */ +if ( !defined('COOKIE_DOMAIN') ) + define('COOKIE_DOMAIN', false); + +/** + * It is possible to define this in wp-config.php + * @since 2.6.0 + */ +if ( !defined('FORCE_SSL_ADMIN') ) + define('FORCE_SSL_ADMIN', false); +force_ssl_admin(FORCE_SSL_ADMIN); + +/** + * It is possible to define this in wp-config.php + * @since 2.6.0 + */ +if ( !defined('FORCE_SSL_LOGIN') ) + define('FORCE_SSL_LOGIN', false); +force_ssl_login(FORCE_SSL_LOGIN); + +/** + * It is possible to define this in wp-config.php + * @since 2.5.0 + */ +if ( !defined( 'AUTOSAVE_INTERVAL' ) ) + define( 'AUTOSAVE_INTERVAL', 60 ); + + +require (ABSPATH . WPINC . '/vars.php'); + +// make taxonomies available to plugins and themes +// @plugin authors: warning: this gets registered again on the init hook +create_initial_taxonomies(); + +// Check for hacks file if the option is enabled +if ( get_option('hack_file') ) { + if ( file_exists(ABSPATH . 'my-hacks.php') ) + require(ABSPATH . 'my-hacks.php'); +} + +$current_plugins = get_option('active_plugins'); +if ( is_array($current_plugins) && !defined('WP_INSTALLING') ) { + foreach ( $current_plugins as $plugin ) { + // check the $plugin filename + // Validate plugin filename + if ( validate_file($plugin) // $plugin must validate as file + || '.php' != substr($plugin, -4) // $plugin must end with '.php' + || !file_exists(WP_PLUGIN_DIR . '/' . $plugin) // $plugin must exist + ) + continue; + + include_once(WP_PLUGIN_DIR . '/' . $plugin); + } + unset($plugin); +} +unset($current_plugins); + +require (ABSPATH . WPINC . '/pluggable.php'); + +/* + * In most cases the default internal encoding is latin1, which is of no use, + * since we want to use the mb_ functions for utf-8 strings + */ +if (function_exists('mb_internal_encoding')) { + if (!@mb_internal_encoding(get_option('blog_charset'))) + mb_internal_encoding('UTF-8'); +} + + +if ( defined('WP_CACHE') && function_exists('wp_cache_postload') ) + wp_cache_postload(); + +do_action('plugins_loaded'); + +$default_constants = array( 'WP_POST_REVISIONS' => true ); +foreach ( $default_constants as $c => $v ) + @define( $c, $v ); // will fail if the constant is already defined +unset($default_constants, $c, $v); + +// If already slashed, strip. +if ( get_magic_quotes_gpc() ) { + $_GET = stripslashes_deep($_GET ); + $_POST = stripslashes_deep($_POST ); + $_COOKIE = stripslashes_deep($_COOKIE); +} + +// Escape with wpdb. +$_GET = add_magic_quotes($_GET ); +$_POST = add_magic_quotes($_POST ); +$_COOKIE = add_magic_quotes($_COOKIE); +$_SERVER = add_magic_quotes($_SERVER); + +do_action('sanitize_comment_cookies'); + +/** + * WordPress Query object + * @global object $wp_the_query + * @since 2.0.0 + */ +$wp_the_query =& new WP_Query(); + +/** + * Holds the reference to @see $wp_the_query + * Use this global for WordPress queries + * @global object $wp_query + * @since 1.5.0 + */ +$wp_query =& $wp_the_query; + +/** + * Holds the WordPress Rewrite object for creating pretty URLs + * @global object $wp_rewrite + * @since 1.5.0 + */ +$wp_rewrite =& new WP_Rewrite(); + +/** + * WordPress Object + * @global object $wp + * @since 2.0.0 + */ +$wp =& new WP(); + +/** + * WordPress Widget Factory Object + * @global object $wp_widget_factory + * @since 2.8.0 + */ +$wp_widget_factory =& new WP_Widget_Factory(); + +do_action('setup_theme'); + +/** + * Web Path to the current active template directory + * @since 1.5.0 + */ +define('TEMPLATEPATH', get_template_directory()); + +/** + * Web Path to the current active template stylesheet directory + * @since 2.1.0 + */ +define('STYLESHEETPATH', get_stylesheet_directory()); + +// Load the default text localization domain. +load_default_textdomain(); + +/** + * The locale of the blog + * @since 1.5.0 + */ +$locale = get_locale(); +$locale_file = WP_LANG_DIR . "/$locale.php"; +if ( is_readable($locale_file) ) + require_once($locale_file); + +// Pull in locale data after loading text domain. +require_once(ABSPATH . WPINC . '/locale.php'); + +/** + * WordPress Locale object for loading locale domain date and various strings. + * @global object $wp_locale + * @since 2.1.0 + */ +$wp_locale =& new WP_Locale(); + +// Load functions for active theme. +if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists(STYLESHEETPATH . '/functions.php') ) + include(STYLESHEETPATH . '/functions.php'); +if ( file_exists(TEMPLATEPATH . '/functions.php') ) + include(TEMPLATEPATH . '/functions.php'); + +/** + * Runs just before PHP shuts down execution. + * + * @access private + * @since 1.2.0 + */ +function shutdown_action_hook() { + do_action('shutdown'); + wp_cache_close(); +} +register_shutdown_function('shutdown_action_hook'); + +$wp->init(); // Sets up current user. + +// Everything is loaded and initialized. +do_action('init'); + +?> diff --git a/wp-trackback.php b/wp-trackback.php new file mode 100644 index 0000000..58886f8 --- /dev/null +++ b/wp-trackback.php @@ -0,0 +1,111 @@ +\n"; + echo "\n"; + echo "1\n"; + echo "$error_message\n"; + echo ""; + die(); + } else { + echo '\n"; + echo "\n"; + echo "0\n"; + echo ""; + } +} + +// trackback is done by a POST +$request_array = 'HTTP_POST_VARS'; + +if ( !$_GET['tb_id'] ) { + $tb_id = explode('/', $_SERVER['REQUEST_URI']); + $tb_id = intval( $tb_id[ count($tb_id) - 1 ] ); +} + +$tb_url = $_POST['url']; +$charset = $_POST['charset']; + +// These three are stripslashed here so that they can be properly escaped after mb_convert_encoding() +$title = stripslashes($_POST['title']); +$excerpt = stripslashes($_POST['excerpt']); +$blog_name = stripslashes($_POST['blog_name']); + +if ($charset) + $charset = strtoupper( trim($charset) ); +else + $charset = 'ASCII, UTF-8, ISO-8859-1, JIS, EUC-JP, SJIS'; + +// No valid uses for UTF-7 +if ( false !== strpos($charset, 'UTF-7') ) + die; + +if ( function_exists('mb_convert_encoding') ) { // For international trackbacks + $title = mb_convert_encoding($title, get_option('blog_charset'), $charset); + $excerpt = mb_convert_encoding($excerpt, get_option('blog_charset'), $charset); + $blog_name = mb_convert_encoding($blog_name, get_option('blog_charset'), $charset); +} + +// Now that mb_convert_encoding() has been given a swing, we need to escape these three +$title = $wpdb->escape($title); +$excerpt = $wpdb->escape($excerpt); +$blog_name = $wpdb->escape($blog_name); + +if ( is_single() || is_page() ) + $tb_id = $posts[0]->ID; + +if ( !intval( $tb_id ) ) + trackback_response(1, 'I really need an ID for this to work.'); + +if (empty($title) && empty($tb_url) && empty($blog_name)) { + // If it doesn't look like a trackback at all... + wp_redirect(get_permalink($tb_id)); + exit; +} + +if ( !empty($tb_url) && !empty($title) ) { + header('Content-Type: text/xml; charset=' . get_option('blog_charset') ); + + if ( !pings_open($tb_id) ) + trackback_response(1, 'Sorry, trackbacks are closed for this item.'); + + $title = wp_html_excerpt( $title, 250 ).'...'; + $excerpt = wp_html_excerpt( $excerpt, 252 ).'...'; + + $comment_post_ID = (int) $tb_id; + $comment_author = $blog_name; + $comment_author_email = ''; + $comment_author_url = $tb_url; + $comment_content = "$title\n\n$excerpt"; + $comment_type = 'trackback'; + + $dupe = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $comment_post_ID, $comment_author_url) ); + if ( $dupe ) + trackback_response(1, 'We already have a ping from that URL for this post.'); + + $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type'); + + wp_new_comment($commentdata); + + do_action('trackback_post', $wpdb->insert_id); + trackback_response(0); +} +?> \ No newline at end of file diff --git a/xmlrpc.php b/xmlrpc.php new file mode 100644 index 0000000..e8d8a2e --- /dev/null +++ b/xmlrpc.php @@ -0,0 +1,3407 @@ + + * @package WordPress + */ + +/** + * Whether this is a XMLRPC Request + * + * @var bool + */ +define('XMLRPC_REQUEST', true); + +// Some browser-embedded clients send cookies. We don't want them. +$_COOKIE = array(); + +// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default, +// but we can do it ourself. +if ( !isset( $HTTP_RAW_POST_DATA ) ) { + $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' ); +} + +// fix for mozBlog and other cases where ' +'; ?> + + + WordPress + http://wordpress.org/ + + + + + + + + + + +methods = array( + // WordPress API + 'wp.getUsersBlogs' => 'this:wp_getUsersBlogs', + 'wp.getPage' => 'this:wp_getPage', + 'wp.getPages' => 'this:wp_getPages', + 'wp.newPage' => 'this:wp_newPage', + 'wp.deletePage' => 'this:wp_deletePage', + 'wp.editPage' => 'this:wp_editPage', + 'wp.getPageList' => 'this:wp_getPageList', + 'wp.getAuthors' => 'this:wp_getAuthors', + 'wp.getCategories' => 'this:mw_getCategories', // Alias + 'wp.getTags' => 'this:wp_getTags', + 'wp.newCategory' => 'this:wp_newCategory', + 'wp.deleteCategory' => 'this:wp_deleteCategory', + 'wp.suggestCategories' => 'this:wp_suggestCategories', + 'wp.uploadFile' => 'this:mw_newMediaObject', // Alias + 'wp.getCommentCount' => 'this:wp_getCommentCount', + 'wp.getPostStatusList' => 'this:wp_getPostStatusList', + 'wp.getPageStatusList' => 'this:wp_getPageStatusList', + 'wp.getPageTemplates' => 'this:wp_getPageTemplates', + 'wp.getOptions' => 'this:wp_getOptions', + 'wp.setOptions' => 'this:wp_setOptions', + 'wp.getComment' => 'this:wp_getComment', + 'wp.getComments' => 'this:wp_getComments', + 'wp.deleteComment' => 'this:wp_deleteComment', + 'wp.editComment' => 'this:wp_editComment', + 'wp.newComment' => 'this:wp_newComment', + 'wp.getCommentStatusList' => 'this:wp_getCommentStatusList', + + // Blogger API + 'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs', + 'blogger.getUserInfo' => 'this:blogger_getUserInfo', + 'blogger.getPost' => 'this:blogger_getPost', + 'blogger.getRecentPosts' => 'this:blogger_getRecentPosts', + 'blogger.getTemplate' => 'this:blogger_getTemplate', + 'blogger.setTemplate' => 'this:blogger_setTemplate', + 'blogger.newPost' => 'this:blogger_newPost', + 'blogger.editPost' => 'this:blogger_editPost', + 'blogger.deletePost' => 'this:blogger_deletePost', + + // MetaWeblog API (with MT extensions to structs) + 'metaWeblog.newPost' => 'this:mw_newPost', + 'metaWeblog.editPost' => 'this:mw_editPost', + 'metaWeblog.getPost' => 'this:mw_getPost', + 'metaWeblog.getRecentPosts' => 'this:mw_getRecentPosts', + 'metaWeblog.getCategories' => 'this:mw_getCategories', + 'metaWeblog.newMediaObject' => 'this:mw_newMediaObject', + + // MetaWeblog API aliases for Blogger API + // see http://www.xmlrpc.com/stories/storyReader$2460 + 'metaWeblog.deletePost' => 'this:blogger_deletePost', + 'metaWeblog.getTemplate' => 'this:blogger_getTemplate', + 'metaWeblog.setTemplate' => 'this:blogger_setTemplate', + 'metaWeblog.getUsersBlogs' => 'this:blogger_getUsersBlogs', + + // MovableType API + 'mt.getCategoryList' => 'this:mt_getCategoryList', + 'mt.getRecentPostTitles' => 'this:mt_getRecentPostTitles', + 'mt.getPostCategories' => 'this:mt_getPostCategories', + 'mt.setPostCategories' => 'this:mt_setPostCategories', + 'mt.supportedMethods' => 'this:mt_supportedMethods', + 'mt.supportedTextFilters' => 'this:mt_supportedTextFilters', + 'mt.getTrackbackPings' => 'this:mt_getTrackbackPings', + 'mt.publishPost' => 'this:mt_publishPost', + + // PingBack + 'pingback.ping' => 'this:pingback_ping', + 'pingback.extensions.getPingbacks' => 'this:pingback_extensions_getPingbacks', + + 'demo.sayHello' => 'this:sayHello', + 'demo.addTwoNumbers' => 'this:addTwoNumbers' + ); + + $this->initialise_blog_option_info( ); + $this->methods = apply_filters('xmlrpc_methods', $this->methods); + $this->IXR_Server($this->methods); + } + + /** + * Test XMLRPC API by saying, "Hello!" to client. + * + * @since 1.5.0 + * + * @param array $args Method Parameters. + * @return string + */ + function sayHello($args) { + return 'Hello!'; + } + + /** + * Test XMLRPC API by adding two numbers for client. + * + * @since 1.5.0 + * + * @param array $args Method Parameters. + * @return int + */ + function addTwoNumbers($args) { + $number1 = $args[0]; + $number2 = $args[1]; + return $number1 + $number2; + } + + /** + * Check user's credentials. + * + * @since 1.5.0 + * + * @param string $user_login User's username. + * @param string $user_pass User's password. + * @return bool Whether authentication passed. + * @deprecated use wp_xmlrpc_server::login + * @see wp_xmlrpc_server::login + */ + function login_pass_ok($user_login, $user_pass) { + if ( !get_option( 'enable_xmlrpc' ) ) { + $this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this blog. An admin user can enable them at %s'), admin_url('options-writing.php') ) ); + return false; + } + + if (!user_pass_ok($user_login, $user_pass)) { + $this->error = new IXR_Error(403, __('Bad login/pass combination.')); + return false; + } + return true; + } + + /** + * Log user in. + * + * @since 2.8 + * + * @param string $username User's username. + * @param string $password User's password. + * @return mixed WP_User object if authentication passed, false otherwise + */ + function login($username, $password) { + if ( !get_option( 'enable_xmlrpc' ) ) { + $this->error = new IXR_Error( 405, sprintf( __( 'XML-RPC services are disabled on this blog. An admin user can enable them at %s'), admin_url('options-writing.php') ) ); + return false; + } + + $user = wp_authenticate($username, $password); + + if (is_wp_error($user)) { + $this->error = new IXR_Error(403, __('Bad login/pass combination.')); + return false; + } + + set_current_user( $user->ID ); + return $user; + } + + /** + * Sanitize string or array of strings for database. + * + * @since 1.5.2 + * + * @param string|array $array Sanitize single string or array of strings. + * @return string|array Type matches $array and sanitized for the database. + */ + function escape(&$array) { + global $wpdb; + + if(!is_array($array)) { + return($wpdb->escape($array)); + } + else { + foreach ( (array) $array as $k => $v ) { + if (is_array($v)) { + $this->escape($array[$k]); + } else if (is_object($v)) { + //skip + } else { + $array[$k] = $wpdb->escape($v); + } + } + } + } + + /** + * Retrieve custom fields for post. + * + * @since 2.5.0 + * + * @param int $post_id Post ID. + * @return array Custom fields, if exist. + */ + function get_custom_fields($post_id) { + $post_id = (int) $post_id; + + $custom_fields = array(); + + foreach ( (array) has_meta($post_id) as $meta ) { + // Don't expose protected fields. + if ( strpos($meta['meta_key'], '_wp_') === 0 ) { + continue; + } + + $custom_fields[] = array( + "id" => $meta['meta_id'], + "key" => $meta['meta_key'], + "value" => $meta['meta_value'] + ); + } + + return $custom_fields; + } + + /** + * Set custom fields for post. + * + * @since 2.5.0 + * + * @param int $post_id Post ID. + * @param array $fields Custom fields. + */ + function set_custom_fields($post_id, $fields) { + $post_id = (int) $post_id; + + foreach ( (array) $fields as $meta ) { + if ( isset($meta['id']) ) { + $meta['id'] = (int) $meta['id']; + + if ( isset($meta['key']) ) { + update_meta($meta['id'], $meta['key'], $meta['value']); + } + else { + delete_meta($meta['id']); + } + } + else { + $_POST['metakeyinput'] = $meta['key']; + $_POST['metavalue'] = $meta['value']; + add_meta($post_id); + } + } + } + + /** + * Setup blog options property. + * + * Passes property through 'xmlrpc_blog_options' filter. + * + * @since 2.6.0 + */ + function initialise_blog_option_info( ) { + global $wp_version; + + $this->blog_options = array( + // Read only options + 'software_name' => array( + 'desc' => __( 'Software Name' ), + 'readonly' => true, + 'value' => 'WordPress' + ), + 'software_version' => array( + 'desc' => __( 'Software Version' ), + 'readonly' => true, + 'value' => $wp_version + ), + 'blog_url' => array( + 'desc' => __( 'Blog URL' ), + 'readonly' => true, + 'option' => 'siteurl' + ), + + // Updatable options + 'time_zone' => array( + 'desc' => __( 'Time Zone' ), + 'readonly' => false, + 'option' => 'gmt_offset' + ), + 'blog_title' => array( + 'desc' => __( 'Blog Title' ), + 'readonly' => false, + 'option' => 'blogname' + ), + 'blog_tagline' => array( + 'desc' => __( 'Blog Tagline' ), + 'readonly' => false, + 'option' => 'blogdescription' + ), + 'date_format' => array( + 'desc' => __( 'Date Format' ), + 'readonly' => false, + 'option' => 'date_format' + ), + 'time_format' => array( + 'desc' => __( 'Time Format' ), + 'readonly' => false, + 'option' => 'time_format' + ) + ); + + $this->blog_options = apply_filters( 'xmlrpc_blog_options', $this->blog_options ); + } + + /** + * Retrieve the blogs of the user. + * + * @since 2.6.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getUsersBlogs( $args ) { + // If this isn't on WPMU then just use blogger_getUsersBlogs + if( !function_exists( 'is_site_admin' ) ) { + array_unshift( $args, 1 ); + return $this->blogger_getUsersBlogs( $args ); + } + + $this->escape( $args ); + + $username = $args[0]; + $password = $args[1]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action( 'xmlrpc_call', 'wp.getUsersBlogs' ); + + $blogs = (array) get_blogs_of_user( $user->ID ); + $struct = array( ); + + foreach( $blogs as $blog ) { + // Don't include blogs that aren't hosted at this site + if( $blog->site_id != $current_site->id ) + continue; + + $blog_id = $blog->userblog_id; + switch_to_blog($blog_id); + $is_admin = current_user_can('level_8'); + + $struct[] = array( + 'isAdmin' => $is_admin, + 'url' => get_option( 'home' ) . '/', + 'blogid' => $blog_id, + 'blogName' => get_option( 'blogname' ), + 'xmlrpc' => site_url( 'xmlrpc.php' ) + ); + + restore_current_blog( ); + } + + return $struct; + } + + /** + * Retrieve page. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getPage($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $page_id = (int) $args[1]; + $username = $args[2]; + $password = $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_page', $page_id ) ) + return new IXR_Error( 401, __( 'Sorry, you cannot edit this page.' ) ); + + do_action('xmlrpc_call', 'wp.getPage'); + + // Lookup page info. + $page = get_page($page_id); + + // If we found the page then format the data. + if($page->ID && ($page->post_type == "page")) { + // Get all of the page content and link. + $full_page = get_extended($page->post_content); + $link = post_permalink($page->ID); + + // Get info the page parent if there is one. + $parent_title = ""; + if(!empty($page->post_parent)) { + $parent = get_page($page->post_parent); + $parent_title = $parent->post_title; + } + + // Determine comment and ping settings. + $allow_comments = comments_open($page->ID) ? 1 : 0; + $allow_pings = pings_open($page->ID) ? 1 : 0; + + // Format page date. + $page_date = mysql2date("Ymd\TH:i:s", $page->post_date, false); + $page_date_gmt = mysql2date("Ymd\TH:i:s", $page->post_date_gmt, false); + + // Pull the categories info together. + $categories = array(); + foreach(wp_get_post_categories($page->ID) as $cat_id) { + $categories[] = get_cat_name($cat_id); + } + + // Get the author info. + $author = get_userdata($page->post_author); + + $page_template = get_post_meta( $page->ID, '_wp_page_template', true ); + if( empty( $page_template ) ) + $page_template = 'default'; + + $page_struct = array( + "dateCreated" => new IXR_Date($page_date), + "userid" => $page->post_author, + "page_id" => $page->ID, + "page_status" => $page->post_status, + "description" => $full_page["main"], + "title" => $page->post_title, + "link" => $link, + "permaLink" => $link, + "categories" => $categories, + "excerpt" => $page->post_excerpt, + "text_more" => $full_page["extended"], + "mt_allow_comments" => $allow_comments, + "mt_allow_pings" => $allow_pings, + "wp_slug" => $page->post_name, + "wp_password" => $page->post_password, + "wp_author" => $author->display_name, + "wp_page_parent_id" => $page->post_parent, + "wp_page_parent_title" => $parent_title, + "wp_page_order" => $page->menu_order, + "wp_author_id" => $author->ID, + "wp_author_display_name" => $author->display_name, + "date_created_gmt" => new IXR_Date($page_date_gmt), + "custom_fields" => $this->get_custom_fields($page_id), + "wp_page_template" => $page_template + ); + + return($page_struct); + } + // If the page doesn't exist indicate that. + else { + return(new IXR_Error(404, __("Sorry, no such page."))); + } + } + + /** + * Retrieve Pages. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getPages($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $num_pages = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_pages' ) ) + return new IXR_Error( 401, __( 'Sorry, you cannot edit pages.' ) ); + + do_action('xmlrpc_call', 'wp.getPages'); + + $page_limit = 10; + if( isset( $num_pages ) ) { + $page_limit = $num_pages; + } + + $pages = get_posts( array('post_type' => 'page', 'post_status' => 'all', 'numberposts' => $page_limit) ); + $num_pages = count($pages); + + // If we have pages, put together their info. + if($num_pages >= 1) { + $pages_struct = array(); + + for($i = 0; $i < $num_pages; $i++) { + $page = wp_xmlrpc_server::wp_getPage(array( + $blog_id, $pages[$i]->ID, $username, $password + )); + $pages_struct[] = $page; + } + + return($pages_struct); + } + // If no pages were found return an error. + else { + return(array()); + } + } + + /** + * Create new page. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return unknown + */ + function wp_newPage($args) { + // Items not escaped here will be escaped in newPost. + $username = $this->escape($args[1]); + $password = $this->escape($args[2]); + $page = $args[3]; + $publish = $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'wp.newPage'); + + // Make sure the user is allowed to add new pages. + if(!current_user_can("publish_pages")) { + return(new IXR_Error(401, __("Sorry, you cannot add new pages."))); + } + + // Mark this as content for a page. + $args[3]["post_type"] = "page"; + + // Let mw_newPost do all of the heavy lifting. + return($this->mw_newPost($args)); + } + + /** + * Delete page. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return bool True, if success. + */ + function wp_deletePage($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $page_id = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'wp.deletePage'); + + // Get the current page based on the page_id and + // make sure it is a page and not a post. + $actual_page = wp_get_single_post($page_id, ARRAY_A); + if( + !$actual_page + || ($actual_page["post_type"] != "page") + ) { + return(new IXR_Error(404, __("Sorry, no such page."))); + } + + // Make sure the user can delete pages. + if(!current_user_can("delete_page", $page_id)) { + return(new IXR_Error(401, __("Sorry, you do not have the right to delete this page."))); + } + + // Attempt to delete the page. + $result = wp_delete_post($page_id); + if(!$result) { + return(new IXR_Error(500, __("Failed to delete the page."))); + } + + return(true); + } + + /** + * Edit page. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return unknown + */ + function wp_editPage($args) { + // Items not escaped here will be escaped in editPost. + $blog_id = (int) $args[0]; + $page_id = (int) $this->escape($args[1]); + $username = $this->escape($args[2]); + $password = $this->escape($args[3]); + $content = $args[4]; + $publish = $args[5]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'wp.editPage'); + + // Get the page data and make sure it is a page. + $actual_page = wp_get_single_post($page_id, ARRAY_A); + if( + !$actual_page + || ($actual_page["post_type"] != "page") + ) { + return(new IXR_Error(404, __("Sorry, no such page."))); + } + + // Make sure the user is allowed to edit pages. + if(!current_user_can("edit_page", $page_id)) { + return(new IXR_Error(401, __("Sorry, you do not have the right to edit this page."))); + } + + // Mark this as content for a page. + $content["post_type"] = "page"; + + // Arrange args in the way mw_editPost understands. + $args = array( + $page_id, + $username, + $password, + $content, + $publish + ); + + // Let mw_editPost do all of the heavy lifting. + return($this->mw_editPost($args)); + } + + /** + * Retrieve page list. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return unknown + */ + function wp_getPageList($args) { + global $wpdb; + + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_pages' ) ) + return new IXR_Error( 401, __( 'Sorry, you cannot edit pages.' ) ); + + do_action('xmlrpc_call', 'wp.getPageList'); + + // Get list of pages ids and titles + $page_list = $wpdb->get_results(" + SELECT ID page_id, + post_title page_title, + post_parent page_parent_id, + post_date_gmt, + post_date + FROM {$wpdb->posts} + WHERE post_type = 'page' + ORDER BY ID + "); + + // The date needs to be formated properly. + $num_pages = count($page_list); + for($i = 0; $i < $num_pages; $i++) { + $post_date = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date, false); + $post_date_gmt = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date_gmt, false); + + $page_list[$i]->dateCreated = new IXR_Date($post_date); + $page_list[$i]->date_created_gmt = new IXR_Date($post_date_gmt); + + unset($page_list[$i]->post_date_gmt); + unset($page_list[$i]->post_date); + } + + return($page_list); + } + + /** + * Retrieve authors list. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getAuthors($args) { + + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if(!current_user_can("edit_posts")) { + return(new IXR_Error(401, __("Sorry, you cannot edit posts on this blog."))); + } + + do_action('xmlrpc_call', 'wp.getAuthors'); + + $authors = array(); + foreach( (array) get_users_of_blog() as $row ) { + $authors[] = array( + "user_id" => $row->user_id, + "user_login" => $row->user_login, + "display_name" => $row->display_name + ); + } + + return($authors); + } + + /** + * Get list of all tags + * + * @since 2.7 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getTags( $args ) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) { + return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view tags.' ) ); + } + + do_action( 'xmlrpc_call', 'wp.getKeywords' ); + + $tags = array( ); + + if( $all_tags = get_tags( ) ) { + foreach( (array) $all_tags as $tag ) { + $struct['tag_id'] = $tag->term_id; + $struct['name'] = $tag->name; + $struct['count'] = $tag->count; + $struct['slug'] = $tag->slug; + $struct['html_url'] = esc_html( get_tag_link( $tag->term_id ) ); + $struct['rss_url'] = esc_html( get_tag_feed_link( $tag->term_id ) ); + + $tags[] = $struct; + } + } + + return $tags; + } + + /** + * Create new category. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return int Category ID. + */ + function wp_newCategory($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $category = $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'wp.newCategory'); + + // Make sure the user is allowed to add a category. + if(!current_user_can("manage_categories")) { + return(new IXR_Error(401, __("Sorry, you do not have the right to add a category."))); + } + + // If no slug was provided make it empty so that + // WordPress will generate one. + if(empty($category["slug"])) { + $category["slug"] = ""; + } + + // If no parent_id was provided make it empty + // so that it will be a top level page (no parent). + if ( !isset($category["parent_id"]) ) + $category["parent_id"] = ""; + + // If no description was provided make it empty. + if(empty($category["description"])) { + $category["description"] = ""; + } + + $new_category = array( + "cat_name" => $category["name"], + "category_nicename" => $category["slug"], + "category_parent" => $category["parent_id"], + "category_description" => $category["description"] + ); + + $cat_id = wp_insert_category($new_category); + if(!$cat_id) { + return(new IXR_Error(500, __("Sorry, the new category failed."))); + } + + return($cat_id); + } + + /** + * Remove category. + * + * @since 2.5.0 + * + * @param array $args Method parameters. + * @return mixed See {@link wp_delete_category()} for return info. + */ + function wp_deleteCategory($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $category_id = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'wp.deleteCategory'); + + if( !current_user_can("manage_categories") ) { + return new IXR_Error( 401, __( "Sorry, you do not have the right to delete a category." ) ); + } + + return wp_delete_category( $category_id ); + } + + /** + * Retrieve category list. + * + * @since 2.2.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_suggestCategories($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $category = $args[3]; + $max_results = (int) $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) + return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts to this blog in order to view categories.' ) ); + + do_action('xmlrpc_call', 'wp.suggestCategories'); + + $category_suggestions = array(); + $args = array('get' => 'all', 'number' => $max_results, 'name__like' => $category); + foreach ( (array) get_categories($args) as $cat ) { + $category_suggestions[] = array( + "category_id" => $cat->cat_ID, + "category_name" => $cat->cat_name + ); + } + + return($category_suggestions); + } + + /** + * Retrieve comment. + * + * @since 2.7.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getComment($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $comment_id = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if ( !current_user_can( 'moderate_comments' ) ) + return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) ); + + do_action('xmlrpc_call', 'wp.getComment'); + + if ( ! $comment = get_comment($comment_id) ) + return new IXR_Error( 404, __( 'Invalid comment ID.' ) ); + + // Format page date. + $comment_date = mysql2date("Ymd\TH:i:s", $comment->comment_date, false); + $comment_date_gmt = mysql2date("Ymd\TH:i:s", $comment->comment_date_gmt, false); + + if ( 0 == $comment->comment_approved ) + $comment_status = 'hold'; + else if ( 'spam' == $comment->comment_approved ) + $comment_status = 'spam'; + else if ( 1 == $comment->comment_approved ) + $comment_status = 'approve'; + else + $comment_status = $comment->comment_approved; + + $link = get_comment_link($comment); + + $comment_struct = array( + "date_created_gmt" => new IXR_Date($comment_date_gmt), + "user_id" => $comment->user_id, + "comment_id" => $comment->comment_ID, + "parent" => $comment->comment_parent, + "status" => $comment_status, + "content" => $comment->comment_content, + "link" => $link, + "post_id" => $comment->comment_post_ID, + "post_title" => get_the_title($comment->comment_post_ID), + "author" => $comment->comment_author, + "author_url" => $comment->comment_author_url, + "author_email" => $comment->comment_author_email, + "author_ip" => $comment->comment_author_IP, + "type" => $comment->comment_type, + ); + + return $comment_struct; + } + + /** + * Retrieve comments. + * + * @since 2.7.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getComments($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $struct = $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if ( !current_user_can( 'moderate_comments' ) ) + return new IXR_Error( 401, __( 'Sorry, you cannot edit comments.' ) ); + + do_action('xmlrpc_call', 'wp.getComments'); + + if ( isset($struct['status']) ) + $status = $struct['status']; + else + $status = ''; + + $post_id = ''; + if ( isset($struct['post_id']) ) + $post_id = absint($struct['post_id']); + + $offset = 0; + if ( isset($struct['offset']) ) + $offset = absint($struct['offset']); + + $number = 10; + if ( isset($struct['number']) ) + $number = absint($struct['number']); + + $comments = get_comments( array('status' => $status, 'post_id' => $post_id, 'offset' => $offset, 'number' => $number ) ); + $num_comments = count($comments); + + if ( ! $num_comments ) + return array(); + + $comments_struct = array(); + + for ( $i = 0; $i < $num_comments; $i++ ) { + $comment = wp_xmlrpc_server::wp_getComment(array( + $blog_id, $username, $password, $comments[$i]->comment_ID, + )); + $comments_struct[] = $comment; + } + + return $comments_struct; + } + + /** + * Remove comment. + * + * @since 2.7.0 + * + * @param array $args Method parameters. + * @return mixed {@link wp_delete_comment()} + */ + function wp_deleteComment($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $comment_ID = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if ( !current_user_can( 'moderate_comments' ) ) + return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) ); + + do_action('xmlrpc_call', 'wp.deleteComment'); + + if ( ! get_comment($comment_ID) ) + return new IXR_Error( 404, __( 'Invalid comment ID.' ) ); + + return wp_delete_comment($comment_ID); + } + + /** + * Edit comment. + * + * @since 2.7.0 + * + * @param array $args Method parameters. + * @return bool True, on success. + */ + function wp_editComment($args) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $comment_ID = (int) $args[3]; + $content_struct = $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if ( !current_user_can( 'moderate_comments' ) ) + return new IXR_Error( 403, __( 'You are not allowed to moderate comments on this blog.' ) ); + + do_action('xmlrpc_call', 'wp.editComment'); + + if ( ! get_comment($comment_ID) ) + return new IXR_Error( 404, __( 'Invalid comment ID.' ) ); + + if ( isset($content_struct['status']) ) { + $statuses = get_comment_statuses(); + $statuses = array_keys($statuses); + + if ( ! in_array($content_struct['status'], $statuses) ) + return new IXR_Error( 401, __( 'Invalid comment status.' ) ); + $comment_approved = $content_struct['status']; + } + + // Do some timestamp voodoo + if ( !empty( $content_struct['date_created_gmt'] ) ) { + $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force + $comment_date = get_date_from_gmt(iso8601_to_datetime($dateCreated)); + $comment_date_gmt = iso8601_to_datetime($dateCreated, GMT); + } + + if ( isset($content_struct['content']) ) + $comment_content = $content_struct['content']; + + if ( isset($content_struct['author']) ) + $comment_author = $content_struct['author']; + + if ( isset($content_struct['author_url']) ) + $comment_author_url = $content_struct['author_url']; + + if ( isset($content_struct['author_email']) ) + $comment_author_email = $content_struct['author_email']; + + // We've got all the data -- post it: + $comment = compact('comment_ID', 'comment_content', 'comment_approved', 'comment_date', 'comment_date_gmt', 'comment_author', 'comment_author_email', 'comment_author_url'); + + $result = wp_update_comment($comment); + if ( is_wp_error( $result ) ) + return new IXR_Error(500, $result->get_error_message()); + + if ( !$result ) + return new IXR_Error(500, __('Sorry, the comment could not be edited. Something wrong happened.')); + + return true; + } + + /** + * Create new comment. + * + * @since 2.7.0 + * + * @param array $args Method parameters. + * @return mixed {@link wp_new_comment()} + */ + function wp_newComment($args) { + global $wpdb; + + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $post = $args[3]; + $content_struct = $args[4]; + + $allow_anon = apply_filters('xmlrpc_allow_anonymous_comments', false); + + $user = $this->login($username, $password); + + if ( !$user ) { + $logged_in = false; + if ( $allow_anon && get_option('comment_registration') ) + return new IXR_Error( 403, __( 'You must be registered to comment' ) ); + else if ( !$allow_anon ) + return $this->error; + } else { + $logged_in = true; + } + + if ( is_numeric($post) ) + $post_id = absint($post); + else + $post_id = url_to_postid($post); + + if ( ! $post_id ) + return new IXR_Error( 404, __( 'Invalid post ID.' ) ); + + if ( ! get_post($post_id) ) + return new IXR_Error( 404, __( 'Invalid post ID.' ) ); + + $comment['comment_post_ID'] = $post_id; + + if ( $logged_in ) { + $comment['comment_author'] = $wpdb->escape( $user->display_name ); + $comment['comment_author_email'] = $wpdb->escape( $user->user_email ); + $comment['comment_author_url'] = $wpdb->escape( $user->user_url ); + $comment['user_ID'] = $user->ID; + } else { + $comment['comment_author'] = ''; + if ( isset($content_struct['author']) ) + $comment['comment_author'] = $content_struct['author']; + + $comment['comment_author_email'] = ''; + if ( isset($content_struct['author_email']) ) + $comment['comment_author_email'] = $content_struct['author_email']; + + $comment['comment_author_url'] = ''; + if ( isset($content_struct['author_url']) ) + $comment['comment_author_url'] = $content_struct['author_url']; + + $comment['user_ID'] = 0; + + if ( get_option('require_name_email') ) { + if ( 6 > strlen($comment['comment_author_email']) || '' == $comment['comment_author'] ) + return new IXR_Error( 403, __( 'Comment author name and email are required' ) ); + elseif ( !is_email($comment['comment_author_email']) ) + return new IXR_Error( 403, __( 'A valid email address is required' ) ); + } + } + + $comment['comment_parent'] = isset($content_struct['comment_parent']) ? absint($content_struct['comment_parent']) : 0; + + $comment['comment_content'] = $content_struct['content']; + + do_action('xmlrpc_call', 'wp.newComment'); + + return wp_new_comment($comment); + } + + /** + * Retrieve all of the comment status. + * + * @since 2.7.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getCommentStatusList($args) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if ( !current_user_can( 'moderate_comments' ) ) + return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) ); + + do_action('xmlrpc_call', 'wp.getCommentStatusList'); + + return get_comment_statuses( ); + } + + /** + * Retrieve comment count. + * + * @since 2.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getCommentCount( $args ) { + $this->escape($args); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $post_id = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) { + return new IXR_Error( 403, __( 'You are not allowed access to details about comments.' ) ); + } + + do_action('xmlrpc_call', 'wp.getCommentCount'); + + $count = wp_count_comments( $post_id ); + return array( + "approved" => $count->approved, + "awaiting_moderation" => $count->moderated, + "spam" => $count->spam, + "total_comments" => $count->total_comments + ); + } + + /** + * Retrieve post statuses. + * + * @since 2.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getPostStatusList( $args ) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) { + return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) ); + } + + do_action('xmlrpc_call', 'wp.getPostStatusList'); + + return get_post_statuses( ); + } + + /** + * Retrieve page statuses. + * + * @since 2.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getPageStatusList( $args ) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) { + return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) ); + } + + do_action('xmlrpc_call', 'wp.getPageStatusList'); + + return get_page_statuses( ); + } + + /** + * Retrieve page templates. + * + * @since 2.6.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getPageTemplates( $args ) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_pages' ) ) { + return new IXR_Error( 403, __( 'You are not allowed access to details about this blog.' ) ); + } + + $templates = get_page_templates( ); + $templates['Default'] = 'default'; + + return $templates; + } + + /** + * Retrieve blog options. + * + * @since 2.6.0 + * + * @param array $args Method parameters. + * @return array + */ + function wp_getOptions( $args ) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $options = (array) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + // If no specific options where asked for, return all of them + if (count( $options ) == 0 ) { + $options = array_keys($this->blog_options); + } + + return $this->_getOptions($options); + } + + /** + * Retrieve blog options value from list. + * + * @since 2.6.0 + * + * @param array $options Options to retrieve. + * @return array + */ + function _getOptions($options) + { + $data = array( ); + foreach( $options as $option ) { + if( array_key_exists( $option, $this->blog_options ) ) + { + $data[$option] = $this->blog_options[$option]; + //Is the value static or dynamic? + if( isset( $data[$option]['option'] ) ) { + $data[$option]['value'] = get_option( $data[$option]['option'] ); + unset($data[$option]['option']); + } + } + } + + return $data; + } + + /** + * Update blog options. + * + * @since 2.6.0 + * + * @param array $args Method parameters. + * @return unknown + */ + function wp_setOptions( $args ) { + $this->escape( $args ); + + $blog_id = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $options = (array) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'manage_options' ) ) + return new IXR_Error( 403, __( 'You are not allowed to update options.' ) ); + + foreach( $options as $o_name => $o_value ) { + $option_names[] = $o_name; + if( empty( $o_value ) ) + continue; + + if( !array_key_exists( $o_name, $this->blog_options ) ) + continue; + + if( $this->blog_options[$o_name]['readonly'] == true ) + continue; + + update_option( $this->blog_options[$o_name]['option'], $o_value ); + } + + //Now return the updated values + return $this->_getOptions($option_names); + } + + /* Blogger API functions. + * specs on http://plant.blogger.com/api and http://groups.yahoo.com/group/bloggerDev/ + */ + + /** + * Retrieve blogs that user owns. + * + * Will make more sense once we support multiple blogs. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function blogger_getUsersBlogs($args) { + + $this->escape($args); + + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.getUsersBlogs'); + + $is_admin = current_user_can('manage_options'); + + $struct = array( + 'isAdmin' => $is_admin, + 'url' => get_option('home') . '/', + 'blogid' => '1', + 'blogName' => get_option('blogname'), + 'xmlrpc' => site_url( 'xmlrpc.php' ) + ); + + return array($struct); + } + + /** + * Retrieve user's data. + * + * Gives your client some info about you, so you don't have to. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function blogger_getUserInfo($args) { + + $this->escape($args); + + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) + return new IXR_Error( 401, __( 'Sorry, you do not have access to user data on this blog.' ) ); + + do_action('xmlrpc_call', 'blogger.getUserInfo'); + + $struct = array( + 'nickname' => $user->nickname, + 'userid' => $user->ID, + 'url' => $user->user_url, + 'lastname' => $user->last_name, + 'firstname' => $user->first_name + ); + + return $struct; + } + + /** + * Retrieve post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function blogger_getPost($args) { + + $this->escape($args); + + $post_ID = (int) $args[1]; + $username = $args[2]; + $password = $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_post', $post_ID ) ) + return new IXR_Error( 401, __( 'Sorry, you cannot edit this post.' ) ); + + do_action('xmlrpc_call', 'blogger.getPost'); + + $post_data = wp_get_single_post($post_ID, ARRAY_A); + + $categories = implode(',', wp_get_post_categories($post_ID)); + + $content = ''.stripslashes($post_data['post_title']).''; + $content .= ''.$categories.''; + $content .= stripslashes($post_data['post_content']); + + $struct = array( + 'userid' => $post_data['post_author'], + 'dateCreated' => new IXR_Date(mysql2date('Ymd\TH:i:s', $post_data['post_date'], false)), + 'content' => $content, + 'postid' => $post_data['ID'] + ); + + return $struct; + } + + /** + * Retrieve list of recent posts. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function blogger_getRecentPosts($args) { + + $this->escape($args); + + $blog_ID = (int) $args[1]; /* though we don't use it yet */ + $username = $args[2]; + $password = $args[3]; + $num_posts = $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.getRecentPosts'); + + $posts_list = wp_get_recent_posts($num_posts); + + if (!$posts_list) { + $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.')); + return $this->error; + } + + foreach ($posts_list as $entry) { + if( !current_user_can( 'edit_post', $entry['ID'] ) ) + continue; + + $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date'], false); + $categories = implode(',', wp_get_post_categories($entry['ID'])); + + $content = ''.stripslashes($entry['post_title']).''; + $content .= ''.$categories.''; + $content .= stripslashes($entry['post_content']); + + $struct[] = array( + 'userid' => $entry['post_author'], + 'dateCreated' => new IXR_Date($post_date), + 'content' => $content, + 'postid' => $entry['ID'], + ); + + } + + $recent_posts = array(); + for ($j=0; $jescape($args); + + $blog_ID = (int) $args[1]; + $username = $args[2]; + $password = $args[3]; + $template = $args[4]; /* could be 'main' or 'archiveIndex', but we don't use it */ + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.getTemplate'); + + if ( !current_user_can('edit_themes') ) { + return new IXR_Error(401, __('Sorry, this user can not edit the template.')); + } + + /* warning: here we make the assumption that the blog's URL is on the same server */ + $filename = get_option('home') . '/'; + $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename); + + $f = fopen($filename, 'r'); + $content = fread($f, filesize($filename)); + fclose($f); + + /* so it is actually editable with a windows/mac client */ + // FIXME: (or delete me) do we really want to cater to bad clients at the expense of good ones by BEEPing up their line breaks? commented. $content = str_replace("\n", "\r\n", $content); + + return $content; + } + + /** + * Updates the content of blog_filename. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return bool True when done. + */ + function blogger_setTemplate($args) { + + $this->escape($args); + + $blog_ID = (int) $args[1]; + $username = $args[2]; + $password = $args[3]; + $content = $args[4]; + $template = $args[5]; /* could be 'main' or 'archiveIndex', but we don't use it */ + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.setTemplate'); + + if ( !current_user_can('edit_themes') ) { + return new IXR_Error(401, __('Sorry, this user cannot edit the template.')); + } + + /* warning: here we make the assumption that the blog's URL is on the same server */ + $filename = get_option('home') . '/'; + $filename = preg_replace('#https?://.+?/#', $_SERVER['DOCUMENT_ROOT'].'/', $filename); + + if ($f = fopen($filename, 'w+')) { + fwrite($f, $content); + fclose($f); + } else { + return new IXR_Error(500, __('Either the file is not writable, or something wrong happened. The file has not been updated.')); + } + + return true; + } + + /** + * Create new post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return int + */ + function blogger_newPost($args) { + + $this->escape($args); + + $blog_ID = (int) $args[1]; /* though we don't use it yet */ + $username = $args[2]; + $password = $args[3]; + $content = $args[4]; + $publish = $args[5]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.newPost'); + + $cap = ($publish) ? 'publish_posts' : 'edit_posts'; + if ( !current_user_can($cap) ) + return new IXR_Error(401, __('Sorry, you are not allowed to post on this blog.')); + + $post_status = ($publish) ? 'publish' : 'draft'; + + $post_author = $user->ID; + + $post_title = xmlrpc_getposttitle($content); + $post_category = xmlrpc_getpostcategory($content); + $post_content = xmlrpc_removepostdata($content); + + $post_date = current_time('mysql'); + $post_date_gmt = current_time('mysql', 1); + + $post_data = compact('blog_ID', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status'); + + $post_ID = wp_insert_post($post_data); + if ( is_wp_error( $post_ID ) ) + return new IXR_Error(500, $post_ID->get_error_message()); + + if (!$post_ID) + return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.')); + + $this->attach_uploads( $post_ID, $post_content ); + + logIO('O', "Posted ! ID: $post_ID"); + + return $post_ID; + } + + /** + * Edit a post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return bool true when done. + */ + function blogger_editPost($args) { + + $this->escape($args); + + $post_ID = (int) $args[1]; + $username = $args[2]; + $password = $args[3]; + $content = $args[4]; + $publish = $args[5]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.editPost'); + + $actual_post = wp_get_single_post($post_ID,ARRAY_A); + + if (!$actual_post || $actual_post['post_type'] != 'post') { + return new IXR_Error(404, __('Sorry, no such post.')); + } + + $this->escape($actual_post); + + if ( !current_user_can('edit_post', $post_ID) ) + return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.')); + + extract($actual_post, EXTR_SKIP); + + if ( ('publish' == $post_status) && !current_user_can('publish_posts') ) + return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.')); + + $post_title = xmlrpc_getposttitle($content); + $post_category = xmlrpc_getpostcategory($content); + $post_content = xmlrpc_removepostdata($content); + + $postdata = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt'); + + $result = wp_update_post($postdata); + + if (!$result) { + return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be edited.')); + } + $this->attach_uploads( $ID, $post_content ); + + return true; + } + + /** + * Remove a post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return bool True when post is deleted. + */ + function blogger_deletePost($args) { + $this->escape($args); + + $post_ID = (int) $args[1]; + $username = $args[2]; + $password = $args[3]; + $publish = $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'blogger.deletePost'); + + $actual_post = wp_get_single_post($post_ID,ARRAY_A); + + if (!$actual_post || $actual_post['post_type'] != 'post') { + return new IXR_Error(404, __('Sorry, no such post.')); + } + + if ( !current_user_can('edit_post', $post_ID) ) + return new IXR_Error(401, __('Sorry, you do not have the right to delete this post.')); + + $result = wp_delete_post($post_ID); + + if (!$result) { + return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be deleted.')); + } + + return true; + } + + /* MetaWeblog API functions + * specs on wherever Dave Winer wants them to be + */ + + /** + * Create a new post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return int + */ + function mw_newPost($args) { + $this->escape($args); + + $blog_ID = (int) $args[0]; // we will support this in the near future + $username = $args[1]; + $password = $args[2]; + $content_struct = $args[3]; + $publish = $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'metaWeblog.newPost'); + + $cap = ( $publish ) ? 'publish_posts' : 'edit_posts'; + $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' ); + $post_type = 'post'; + $page_template = ''; + if( !empty( $content_struct['post_type'] ) ) { + if( $content_struct['post_type'] == 'page' ) { + $cap = ( $publish ) ? 'publish_pages' : 'edit_pages'; + $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' ); + $post_type = 'page'; + if( !empty( $content_struct['wp_page_template'] ) ) + $page_template = $content_struct['wp_page_template']; + } + elseif( $content_struct['post_type'] == 'post' ) { + // This is the default, no changes needed + } + else { + // No other post_type values are allowed here + return new IXR_Error( 401, __( 'Invalid post type.' ) ); + } + } + + if( !current_user_can( $cap ) ) { + return new IXR_Error( 401, $error_message ); + } + + // Let WordPress generate the post_name (slug) unless + // one has been provided. + $post_name = ""; + if(isset($content_struct["wp_slug"])) { + $post_name = $content_struct["wp_slug"]; + } + + // Only use a password if one was given. + if(isset($content_struct["wp_password"])) { + $post_password = $content_struct["wp_password"]; + } + + // Only set a post parent if one was provided. + if(isset($content_struct["wp_page_parent_id"])) { + $post_parent = $content_struct["wp_page_parent_id"]; + } + + // Only set the menu_order if it was provided. + if(isset($content_struct["wp_page_order"])) { + $menu_order = $content_struct["wp_page_order"]; + } + + $post_author = $user->ID; + + // If an author id was provided then use it instead. + if( + isset($content_struct["wp_author_id"]) + && ($user->ID != $content_struct["wp_author_id"]) + ) { + switch($post_type) { + case "post": + if(!current_user_can("edit_others_posts")) { + return(new IXR_Error(401, __("You are not allowed to post as this user"))); + } + break; + case "page": + if(!current_user_can("edit_others_pages")) { + return(new IXR_Error(401, __("You are not allowed to create pages as this user"))); + } + break; + default: + return(new IXR_Error(401, __("Invalid post type."))); + break; + } + $post_author = $content_struct["wp_author_id"]; + } + + $post_title = $content_struct['title']; + $post_content = apply_filters( 'content_save_pre', $content_struct['description'] ); + + $post_status = $publish ? 'publish' : 'draft'; + + if( isset( $content_struct["{$post_type}_status"] ) ) { + switch( $content_struct["{$post_type}_status"] ) { + case 'draft': + case 'private': + case 'publish': + $post_status = $content_struct["{$post_type}_status"]; + break; + case 'pending': + // Pending is only valid for posts, not pages. + if( $post_type === 'post' ) { + $post_status = $content_struct["{$post_type}_status"]; + } + break; + default: + $post_status = $publish ? 'publish' : 'draft'; + break; + } + } + + $post_excerpt = $content_struct['mt_excerpt']; + $post_more = $content_struct['mt_text_more']; + + $tags_input = $content_struct['mt_keywords']; + + if(isset($content_struct["mt_allow_comments"])) { + if(!is_numeric($content_struct["mt_allow_comments"])) { + switch($content_struct["mt_allow_comments"]) { + case "closed": + $comment_status = "closed"; + break; + case "open": + $comment_status = "open"; + break; + default: + $comment_status = get_option("default_comment_status"); + break; + } + } + else { + switch((int) $content_struct["mt_allow_comments"]) { + case 0: + case 2: + $comment_status = "closed"; + break; + case 1: + $comment_status = "open"; + break; + default: + $comment_status = get_option("default_comment_status"); + break; + } + } + } + else { + $comment_status = get_option("default_comment_status"); + } + + if(isset($content_struct["mt_allow_pings"])) { + if(!is_numeric($content_struct["mt_allow_pings"])) { + switch($content_struct['mt_allow_pings']) { + case "closed": + $ping_status = "closed"; + break; + case "open": + $ping_status = "open"; + break; + default: + $ping_status = get_option("default_ping_status"); + break; + } + } + else { + switch((int) $content_struct["mt_allow_pings"]) { + case 0: + $ping_status = "closed"; + break; + case 1: + $ping_status = "open"; + break; + default: + $ping_status = get_option("default_ping_status"); + break; + } + } + } + else { + $ping_status = get_option("default_ping_status"); + } + + if ($post_more) { + $post_content = $post_content . "" . $post_more; + } + + $to_ping = $content_struct['mt_tb_ping_urls']; + if ( is_array($to_ping) ) + $to_ping = implode(' ', $to_ping); + + // Do some timestamp voodoo + if ( !empty( $content_struct['date_created_gmt'] ) ) + $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force + elseif ( !empty( $content_struct['dateCreated']) ) + $dateCreated = $content_struct['dateCreated']->getIso(); + + if ( !empty( $dateCreated ) ) { + $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated)); + $post_date_gmt = iso8601_to_datetime($dateCreated, GMT); + } else { + $post_date = current_time('mysql'); + $post_date_gmt = current_time('mysql', 1); + } + + $catnames = $content_struct['categories']; + logIO('O', 'Post cats: ' . var_export($catnames,true)); + $post_category = array(); + + if (is_array($catnames)) { + foreach ($catnames as $cat) { + $post_category[] = get_cat_ID($cat); + } + } + + // We've got all the data -- post it: + $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping', 'post_type', 'post_name', 'post_password', 'post_parent', 'menu_order', 'tags_input', 'page_template'); + + $post_ID = wp_insert_post($postdata, true); + if ( is_wp_error( $post_ID ) ) + return new IXR_Error(500, $post_ID->get_error_message()); + + if (!$post_ID) { + return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.')); + } + + // Only posts can be sticky + if ( $post_type == 'post' && isset( $content_struct['sticky'] ) ) + if ( $content_struct['sticky'] == true ) + stick_post( $post_ID ); + elseif ( $content_struct['sticky'] == false ) + unstick_post( $post_ID ); + + if ( isset($content_struct['custom_fields']) ) { + $this->set_custom_fields($post_ID, $content_struct['custom_fields']); + } + + // Handle enclosures + $this->add_enclosure_if_new($post_ID, $content_struct['enclosure']); + + $this->attach_uploads( $post_ID, $post_content ); + + logIO('O', "Posted ! ID: $post_ID"); + + return strval($post_ID); + } + + function add_enclosure_if_new($post_ID, $enclosure) { + if( is_array( $enclosure ) && isset( $enclosure['url'] ) && isset( $enclosure['length'] ) && isset( $enclosure['type'] ) ) { + + $encstring = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type']; + $found = false; + foreach ( (array) get_post_custom($post_ID) as $key => $val) { + if ($key == 'enclosure') { + foreach ( (array) $val as $enc ) { + if ($enc == $encstring) { + $found = true; + break 2; + } + } + } + } + if (!$found) { + add_post_meta( $post_ID, 'enclosure', $encstring ); + } + } + } + + /** + * Attach upload to a post. + * + * @since 2.1.0 + * + * @param int $post_ID Post ID. + * @param string $post_content Post Content for attachment. + */ + function attach_uploads( $post_ID, $post_content ) { + global $wpdb; + + // find any unattached files + $attachments = $wpdb->get_results( "SELECT ID, guid FROM {$wpdb->posts} WHERE post_parent = '-1' AND post_type = 'attachment'" ); + if( is_array( $attachments ) ) { + foreach( $attachments as $file ) { + if( strpos( $post_content, $file->guid ) !== false ) { + $wpdb->update($wpdb->posts, array('post_parent' => $post_ID), array('ID' => $file->ID) ); + } + } + } + } + + /** + * Edit a post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return bool True on success. + */ + function mw_editPost($args) { + + $this->escape($args); + + $post_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $content_struct = $args[3]; + $publish = $args[4]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'metaWeblog.editPost'); + + $cap = ( $publish ) ? 'publish_posts' : 'edit_posts'; + $error_message = __( 'Sorry, you are not allowed to publish posts on this blog.' ); + $post_type = 'post'; + $page_template = ''; + if( !empty( $content_struct['post_type'] ) ) { + if( $content_struct['post_type'] == 'page' ) { + $cap = ( $publish ) ? 'publish_pages' : 'edit_pages'; + $error_message = __( 'Sorry, you are not allowed to publish pages on this blog.' ); + $post_type = 'page'; + if( !empty( $content_struct['wp_page_template'] ) ) + $page_template = $content_struct['wp_page_template']; + } + elseif( $content_struct['post_type'] == 'post' ) { + // This is the default, no changes needed + } + else { + // No other post_type values are allowed here + return new IXR_Error( 401, __( 'Invalid post type.' ) ); + } + } + + if( !current_user_can( $cap ) ) { + return new IXR_Error( 401, $error_message ); + } + + $postdata = wp_get_single_post($post_ID, ARRAY_A); + + // If there is no post data for the give post id, stop + // now and return an error. Other wise a new post will be + // created (which was the old behavior). + if(empty($postdata["ID"])) { + return(new IXR_Error(404, __("Invalid post ID."))); + } + + $this->escape($postdata); + extract($postdata, EXTR_SKIP); + + // Let WordPress manage slug if none was provided. + $post_name = ""; + if(isset($content_struct["wp_slug"])) { + $post_name = $content_struct["wp_slug"]; + } + + // Only use a password if one was given. + if(isset($content_struct["wp_password"])) { + $post_password = $content_struct["wp_password"]; + } + + // Only set a post parent if one was given. + if(isset($content_struct["wp_page_parent_id"])) { + $post_parent = $content_struct["wp_page_parent_id"]; + } + + // Only set the menu_order if it was given. + if(isset($content_struct["wp_page_order"])) { + $menu_order = $content_struct["wp_page_order"]; + } + + $post_author = $postdata["post_author"]; + + // Only set the post_author if one is set. + if( + isset($content_struct["wp_author_id"]) + && ($user->ID != $content_struct["wp_author_id"]) + ) { + switch($post_type) { + case "post": + if(!current_user_can("edit_others_posts")) { + return(new IXR_Error(401, __("You are not allowed to change the post author as this user."))); + } + break; + case "page": + if(!current_user_can("edit_others_pages")) { + return(new IXR_Error(401, __("You are not allowed to change the page author as this user."))); + } + break; + default: + return(new IXR_Error(401, __("Invalid post type."))); + break; + } + $post_author = $content_struct["wp_author_id"]; + } + + if(isset($content_struct["mt_allow_comments"])) { + if(!is_numeric($content_struct["mt_allow_comments"])) { + switch($content_struct["mt_allow_comments"]) { + case "closed": + $comment_status = "closed"; + break; + case "open": + $comment_status = "open"; + break; + default: + $comment_status = get_option("default_comment_status"); + break; + } + } + else { + switch((int) $content_struct["mt_allow_comments"]) { + case 0: + case 2: + $comment_status = "closed"; + break; + case 1: + $comment_status = "open"; + break; + default: + $comment_status = get_option("default_comment_status"); + break; + } + } + } + + if(isset($content_struct["mt_allow_pings"])) { + if(!is_numeric($content_struct["mt_allow_pings"])) { + switch($content_struct["mt_allow_pings"]) { + case "closed": + $ping_status = "closed"; + break; + case "open": + $ping_status = "open"; + break; + default: + $ping_status = get_option("default_ping_status"); + break; + } + } + else { + switch((int) $content_struct["mt_allow_pings"]) { + case 0: + $ping_status = "closed"; + break; + case 1: + $ping_status = "open"; + break; + default: + $ping_status = get_option("default_ping_status"); + break; + } + } + } + + $post_title = $content_struct['title']; + $post_content = apply_filters( 'content_save_pre', $content_struct['description'] ); + $catnames = $content_struct['categories']; + + $post_category = array(); + + if (is_array($catnames)) { + foreach ($catnames as $cat) { + $post_category[] = get_cat_ID($cat); + } + } + + $post_excerpt = $content_struct['mt_excerpt']; + $post_more = $content_struct['mt_text_more']; + + $post_status = $publish ? 'publish' : 'draft'; + if( isset( $content_struct["{$post_type}_status"] ) ) { + switch( $content_struct["{$post_type}_status"] ) { + case 'draft': + case 'private': + case 'publish': + $post_status = $content_struct["{$post_type}_status"]; + break; + case 'pending': + // Pending is only valid for posts, not pages. + if( $post_type === 'post' ) { + $post_status = $content_struct["{$post_type}_status"]; + } + break; + default: + $post_status = $publish ? 'publish' : 'draft'; + break; + } + } + + $tags_input = $content_struct['mt_keywords']; + + if ( ('publish' == $post_status) ) { + if ( ( 'page' == $post_type ) && !current_user_can('publish_pages') ) + return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.')); + else if ( !current_user_can('publish_posts') ) + return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.')); + } + + if ($post_more) { + $post_content = $post_content . "" . $post_more; + } + + $to_ping = $content_struct['mt_tb_ping_urls']; + if ( is_array($to_ping) ) + $to_ping = implode(' ', $to_ping); + + // Do some timestamp voodoo + if ( !empty( $content_struct['date_created_gmt'] ) ) + $dateCreated = str_replace( 'Z', '', $content_struct['date_created_gmt']->getIso() ) . 'Z'; // We know this is supposed to be GMT, so we're going to slap that Z on there by force + elseif ( !empty( $content_struct['dateCreated']) ) + $dateCreated = $content_struct['dateCreated']->getIso(); + + if ( !empty( $dateCreated ) ) { + $post_date = get_date_from_gmt(iso8601_to_datetime($dateCreated)); + $post_date_gmt = iso8601_to_datetime($dateCreated, GMT); + } else { + $post_date = $postdata['post_date']; + $post_date_gmt = $postdata['post_date_gmt']; + } + + // We've got all the data -- post it: + $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author', 'tags_input', 'page_template'); + + $result = wp_update_post($newpost, true); + if ( is_wp_error( $result ) ) + return new IXR_Error(500, $result->get_error_message()); + + if (!$result) { + return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.')); + } + + // Only posts can be sticky + if ( $post_type == 'post' && isset( $content_struct['sticky'] ) ) + if ( $content_struct['sticky'] == true ) + stick_post( $post_ID ); + elseif ( $content_struct['sticky'] == false ) + unstick_post( $post_ID ); + + if ( isset($content_struct['custom_fields']) ) { + $this->set_custom_fields($post_ID, $content_struct['custom_fields']); + } + + // Handle enclosures + $this->add_enclosure_if_new($post_ID, $content_struct['enclosure']); + + $this->attach_uploads( $ID, $post_content ); + + logIO('O',"(MW) Edited ! ID: $post_ID"); + + return true; + } + + /** + * Retrieve post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function mw_getPost($args) { + + $this->escape($args); + + $post_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_post', $post_ID ) ) + return new IXR_Error( 401, __( 'Sorry, you cannot edit this post.' ) ); + + do_action('xmlrpc_call', 'metaWeblog.getPost'); + + $postdata = wp_get_single_post($post_ID, ARRAY_A); + + if ($postdata['post_date'] != '') { + $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date'], false); + $post_date_gmt = mysql2date('Ymd\TH:i:s', $postdata['post_date_gmt'], false); + + // For drafts use the GMT version of the post date + if ( $postdata['post_status'] == 'draft' ) { + $post_date_gmt = get_gmt_from_date( mysql2date( 'Y-m-d H:i:s', $postdata['post_date'] ) ); + $post_date_gmt = preg_replace( '|\-|', '', $post_date_gmt ); + $post_date_gmt = preg_replace( '| |', 'T', $post_date_gmt ); + } + + $categories = array(); + $catids = wp_get_post_categories($post_ID); + foreach($catids as $catid) + $categories[] = get_cat_name($catid); + + $tagnames = array(); + $tags = wp_get_post_tags( $post_ID ); + if ( !empty( $tags ) ) { + foreach ( $tags as $tag ) + $tagnames[] = $tag->name; + $tagnames = implode( ', ', $tagnames ); + } else { + $tagnames = ''; + } + + $post = get_extended($postdata['post_content']); + $link = post_permalink($postdata['ID']); + + // Get the author info. + $author = get_userdata($postdata['post_author']); + + $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0; + $allow_pings = ('open' == $postdata['ping_status']) ? 1 : 0; + + // Consider future posts as published + if( $postdata['post_status'] === 'future' ) { + $postdata['post_status'] = 'publish'; + } + + $sticky = false; + if ( is_sticky( $post_ID ) ) + $sticky = true; + + $enclosure = array(); + foreach ( (array) get_post_custom($post_ID) as $key => $val) { + if ($key == 'enclosure') { + foreach ( (array) $val as $enc ) { + $encdata = split("\n", $enc); + $enclosure['url'] = trim(htmlspecialchars($encdata[0])); + $enclosure['length'] = trim($encdata[1]); + $enclosure['type'] = trim($encdata[2]); + break 2; + } + } + } + + $resp = array( + 'dateCreated' => new IXR_Date($post_date), + 'userid' => $postdata['post_author'], + 'postid' => $postdata['ID'], + 'description' => $post['main'], + 'title' => $postdata['post_title'], + 'link' => $link, + 'permaLink' => $link, + // commented out because no other tool seems to use this + // 'content' => $entry['post_content'], + 'categories' => $categories, + 'mt_excerpt' => $postdata['post_excerpt'], + 'mt_text_more' => $post['extended'], + 'mt_allow_comments' => $allow_comments, + 'mt_allow_pings' => $allow_pings, + 'mt_keywords' => $tagnames, + 'wp_slug' => $postdata['post_name'], + 'wp_password' => $postdata['post_password'], + 'wp_author_id' => $author->ID, + 'wp_author_display_name' => $author->display_name, + 'date_created_gmt' => new IXR_Date($post_date_gmt), + 'post_status' => $postdata['post_status'], + 'custom_fields' => $this->get_custom_fields($post_ID), + 'sticky' => $sticky + ); + + if (!empty($enclosure)) $resp['enclosure'] = $enclosure; + + return $resp; + } else { + return new IXR_Error(404, __('Sorry, no such post.')); + } + } + + /** + * Retrieve list of recent posts. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function mw_getRecentPosts($args) { + + $this->escape($args); + + $blog_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $num_posts = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'metaWeblog.getRecentPosts'); + + $posts_list = wp_get_recent_posts($num_posts); + + if (!$posts_list) { + return array( ); + } + + foreach ($posts_list as $entry) { + if( !current_user_can( 'edit_post', $entry['ID'] ) ) + continue; + + $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date'], false); + $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt'], false); + + $categories = array(); + $catids = wp_get_post_categories($entry['ID']); + foreach($catids as $catid) { + $categories[] = get_cat_name($catid); + } + + $tagnames = array(); + $tags = wp_get_post_tags( $entry['ID'] ); + if ( !empty( $tags ) ) { + foreach ( $tags as $tag ) { + $tagnames[] = $tag->name; + } + $tagnames = implode( ', ', $tagnames ); + } else { + $tagnames = ''; + } + + $post = get_extended($entry['post_content']); + $link = post_permalink($entry['ID']); + + // Get the post author info. + $author = get_userdata($entry['post_author']); + + $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0; + $allow_pings = ('open' == $entry['ping_status']) ? 1 : 0; + + // Consider future posts as published + if( $entry['post_status'] === 'future' ) { + $entry['post_status'] = 'publish'; + } + + $struct[] = array( + 'dateCreated' => new IXR_Date($post_date), + 'userid' => $entry['post_author'], + 'postid' => $entry['ID'], + 'description' => $post['main'], + 'title' => $entry['post_title'], + 'link' => $link, + 'permaLink' => $link, + // commented out because no other tool seems to use this + // 'content' => $entry['post_content'], + 'categories' => $categories, + 'mt_excerpt' => $entry['post_excerpt'], + 'mt_text_more' => $post['extended'], + 'mt_allow_comments' => $allow_comments, + 'mt_allow_pings' => $allow_pings, + 'mt_keywords' => $tagnames, + 'wp_slug' => $entry['post_name'], + 'wp_password' => $entry['post_password'], + 'wp_author_id' => $author->ID, + 'wp_author_display_name' => $author->display_name, + 'date_created_gmt' => new IXR_Date($post_date_gmt), + 'post_status' => $entry['post_status'], + 'custom_fields' => $this->get_custom_fields($entry['ID']) + ); + + } + + $recent_posts = array(); + for ($j=0; $jescape($args); + + $blog_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) + return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) ); + + do_action('xmlrpc_call', 'metaWeblog.getCategories'); + + $categories_struct = array(); + + if ( $cats = get_categories('get=all') ) { + foreach ( $cats as $cat ) { + $struct['categoryId'] = $cat->term_id; + $struct['parentId'] = $cat->parent; + $struct['description'] = $cat->name; + $struct['categoryDescription'] = $cat->description; + $struct['categoryName'] = $cat->name; + $struct['htmlUrl'] = esc_html(get_category_link($cat->term_id)); + $struct['rssUrl'] = esc_html(get_category_feed_link($cat->term_id, 'rss2')); + + $categories_struct[] = $struct; + } + } + + return $categories_struct; + } + + /** + * Uploads a file, following your settings. + * + * Adapted from a patch by Johann Richard. + * + * @link http://mycvs.org/archives/2004/06/30/file-upload-to-wordpress-in-ecto/ + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function mw_newMediaObject($args) { + global $wpdb; + + $blog_ID = (int) $args[0]; + $username = $wpdb->escape($args[1]); + $password = $wpdb->escape($args[2]); + $data = $args[3]; + + $name = sanitize_file_name( $data['name'] ); + $type = $data['type']; + $bits = $data['bits']; + + logIO('O', '(MW) Received '.strlen($bits).' bytes'); + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'metaWeblog.newMediaObject'); + + if ( !current_user_can('upload_files') ) { + logIO('O', '(MW) User does not have upload_files capability'); + $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.')); + return $this->error; + } + + if ( $upload_err = apply_filters( "pre_upload_error", false ) ) + return new IXR_Error(500, $upload_err); + + if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) { + // Get postmeta info on the object. + $old_file = $wpdb->get_row(" + SELECT ID + FROM {$wpdb->posts} + WHERE post_title = '{$name}' + AND post_type = 'attachment' + "); + + // Delete previous file. + wp_delete_attachment($old_file->ID); + + // Make sure the new name is different by pre-pending the + // previous post id. + $filename = preg_replace("/^wpid\d+-/", "", $name); + $name = "wpid{$old_file->ID}-{$filename}"; + } + + $upload = wp_upload_bits($name, $type, $bits); + if ( ! empty($upload['error']) ) { + $errorString = sprintf(__('Could not write file %1$s (%2$s)'), $name, $upload['error']); + logIO('O', '(MW) ' . $errorString); + return new IXR_Error(500, $errorString); + } + // Construct the attachment array + // attach to post_id -1 + $post_id = -1; + $attachment = array( + 'post_title' => $name, + 'post_content' => '', + 'post_type' => 'attachment', + 'post_parent' => $post_id, + 'post_mime_type' => $type, + 'guid' => $upload[ 'url' ] + ); + + // Save the data + $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id ); + wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) ); + + return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) ); + } + + /* MovableType API functions + * specs on http://www.movabletype.org/docs/mtmanual_programmatic.html + */ + + /** + * Retrieve the post titles of recent posts. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function mt_getRecentPostTitles($args) { + + $this->escape($args); + + $blog_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $num_posts = (int) $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'mt.getRecentPostTitles'); + + $posts_list = wp_get_recent_posts($num_posts); + + if (!$posts_list) { + $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.')); + return $this->error; + } + + foreach ($posts_list as $entry) { + if( !current_user_can( 'edit_post', $entry['ID'] ) ) + continue; + + $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date'], false); + $post_date_gmt = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt'], false); + + $struct[] = array( + 'dateCreated' => new IXR_Date($post_date), + 'userid' => $entry['post_author'], + 'postid' => $entry['ID'], + 'title' => $entry['post_title'], + 'date_created_gmt' => new IXR_Date($post_date_gmt) + ); + + } + + $recent_posts = array(); + for ($j=0; $jescape($args); + + $blog_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_posts' ) ) + return new IXR_Error( 401, __( 'Sorry, you must be able to edit posts on this blog in order to view categories.' ) ); + + do_action('xmlrpc_call', 'mt.getCategoryList'); + + $categories_struct = array(); + + if ( $cats = get_categories('hide_empty=0&hierarchical=0') ) { + foreach ($cats as $cat) { + $struct['categoryId'] = $cat->term_id; + $struct['categoryName'] = $cat->name; + + $categories_struct[] = $struct; + } + } + + return $categories_struct; + } + + /** + * Retrieve post categories. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function mt_getPostCategories($args) { + + $this->escape($args); + + $post_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + if( !current_user_can( 'edit_post', $post_ID ) ) + return new IXR_Error( 401, __( 'Sorry, you can not edit this post.' ) ); + + do_action('xmlrpc_call', 'mt.getPostCategories'); + + $categories = array(); + $catids = wp_get_post_categories(intval($post_ID)); + // first listed category will be the primary category + $isPrimary = true; + foreach($catids as $catid) { + $categories[] = array( + 'categoryName' => get_cat_name($catid), + 'categoryId' => (string) $catid, + 'isPrimary' => $isPrimary + ); + $isPrimary = false; + } + + return $categories; + } + + /** + * Sets categories for a post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return bool True on success. + */ + function mt_setPostCategories($args) { + + $this->escape($args); + + $post_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + $categories = $args[3]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'mt.setPostCategories'); + + if ( !current_user_can('edit_post', $post_ID) ) + return new IXR_Error(401, __('Sorry, you cannot edit this post.')); + + foreach($categories as $cat) { + $catids[] = $cat['categoryId']; + } + + wp_set_post_categories($post_ID, $catids); + + return true; + } + + /** + * Retrieve an array of methods supported by this server. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function mt_supportedMethods($args) { + + do_action('xmlrpc_call', 'mt.supportedMethods'); + + $supported_methods = array(); + foreach($this->methods as $key=>$value) { + $supported_methods[] = $key; + } + + return $supported_methods; + } + + /** + * Retrieve an empty array because we don't support per-post text filters. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + */ + function mt_supportedTextFilters($args) { + do_action('xmlrpc_call', 'mt.supportedTextFilters'); + return apply_filters('xmlrpc_text_filters', array()); + } + + /** + * Retrieve trackbacks sent to a given post. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return mixed + */ + function mt_getTrackbackPings($args) { + + global $wpdb; + + $post_ID = intval($args); + + do_action('xmlrpc_call', 'mt.getTrackbackPings'); + + $actual_post = wp_get_single_post($post_ID, ARRAY_A); + + if (!$actual_post) { + return new IXR_Error(404, __('Sorry, no such post.')); + } + + $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) ); + + if (!$comments) { + return array(); + } + + $trackback_pings = array(); + foreach($comments as $comment) { + if ( 'trackback' == $comment->comment_type ) { + $content = $comment->comment_content; + $title = substr($content, 8, (strpos($content, '
    ') - 8)); + $trackback_pings[] = array( + 'pingTitle' => $title, + 'pingURL' => $comment->comment_author_url, + 'pingIP' => $comment->comment_author_IP + ); + } + } + + return $trackback_pings; + } + + /** + * Sets a post's publish status to 'publish'. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return int + */ + function mt_publishPost($args) { + + $this->escape($args); + + $post_ID = (int) $args[0]; + $username = $args[1]; + $password = $args[2]; + + if ( !$user = $this->login($username, $password) ) { + return $this->error; + } + + do_action('xmlrpc_call', 'mt.publishPost'); + + if ( !current_user_can('edit_post', $post_ID) ) + return new IXR_Error(401, __('Sorry, you cannot edit this post.')); + + $postdata = wp_get_single_post($post_ID,ARRAY_A); + + $postdata['post_status'] = 'publish'; + + // retain old cats + $cats = wp_get_post_categories($post_ID); + $postdata['post_category'] = $cats; + $this->escape($postdata); + + $result = wp_update_post($postdata); + + return $result; + } + + /* PingBack functions + * specs on www.hixie.ch/specs/pingback/pingback + */ + + /** + * Retrieves a pingback and registers it. + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function pingback_ping($args) { + global $wpdb; + + do_action('xmlrpc_call', 'pingback.ping'); + + $this->escape($args); + + $pagelinkedfrom = $args[0]; + $pagelinkedto = $args[1]; + + $title = ''; + + $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); + $pagelinkedto = str_replace('&', '&', $pagelinkedto); + $pagelinkedto = str_replace('&', '&', $pagelinkedto); + + // Check if the page linked to is in our site + $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home'))); + if( !$pos1 ) + return new IXR_Error(0, __('Is there no link to us?')); + + // let's find which post is linked to + // FIXME: does url_to_postid() cover all these cases already? + // if so, then let's use it and drop the old code. + $urltest = parse_url($pagelinkedto); + if ($post_ID = url_to_postid($pagelinkedto)) { + $way = 'url_to_postid()'; + } elseif (preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { + // the path defines the post_ID (archives/p/XXXX) + $blah = explode('/', $match[0]); + $post_ID = (int) $blah[1]; + $way = 'from the path'; + } elseif (preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { + // the querystring defines the post_ID (?p=XXXX) + $blah = explode('=', $match[0]); + $post_ID = (int) $blah[1]; + $way = 'from the querystring'; + } elseif (isset($urltest['fragment'])) { + // an #anchor is there, it's either... + if (intval($urltest['fragment'])) { + // ...an integer #XXXX (simpliest case) + $post_ID = (int) $urltest['fragment']; + $way = 'from the fragment (numeric)'; + } elseif (preg_match('/post-[0-9]+/',$urltest['fragment'])) { + // ...a post id in the form 'post-###' + $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); + $way = 'from the fragment (post-###)'; + } elseif (is_string($urltest['fragment'])) { + // ...or a string #title, a little more complicated + $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']); + $sql = $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title RLIKE %s", $title); + if (! ($post_ID = $wpdb->get_var($sql)) ) { + // returning unknown error '0' is better than die()ing + return new IXR_Error(0, ''); + } + $way = 'from the fragment (title)'; + } + } else { + // TODO: Attempt to extract a post ID from the given URL + return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); + } + $post_ID = (int) $post_ID; + + + logIO("O","(PB) URL='$pagelinkedto' ID='$post_ID' Found='$way'"); + + $post = get_post($post_ID); + + if ( !$post ) // Post_ID not found + return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); + + if ( $post_ID == url_to_postid($pagelinkedfrom) ) + return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.')); + + // Check if pings are on + if ( !pings_open($post) ) + return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); + + // Let's check that the remote site didn't already pingback this entry + $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom) ); + + if ( $wpdb->num_rows ) // We already have a Pingback from this URL + return new IXR_Error(48, __('The pingback has already been registered.')); + + // very stupid, but gives time to the 'from' server to publish ! + sleep(1); + + // Let's check the remote site + $linea = wp_remote_fopen( $pagelinkedfrom ); + if ( !$linea ) + return new IXR_Error(16, __('The source URL does not exist.')); + + $linea = apply_filters('pre_remote_source', $linea, $pagelinkedto); + + // Work around bug in strip_tags(): + $linea = str_replace(']*>/", "\n\n", $linea ); + + preg_match('|([^<]*?)|is', $linea, $matchtitle); + $title = $matchtitle[1]; + if ( empty( $title ) ) + return new IXR_Error(32, __('We cannot find a title on that page.')); + + $linea = strip_tags( $linea, '' ); // just keep the tag we need + + $p = explode( "\n\n", $linea ); + + $preg_target = preg_quote($pagelinkedto, '|'); + + foreach ( $p as $para ) { + if ( strpos($para, $pagelinkedto) !== false ) { // it exists, but is it a link? + preg_match("|]+?".$preg_target."[^>]*>([^>]+?)|", $para, $context); + + // If the URL isn't in a link context, keep looking + if ( empty($context) ) + continue; + + // We're going to use this fake tag to mark the context in a bit + // the marker is needed in case the link text appears more than once in the paragraph + $excerpt = preg_replace('|\|', '', $para); + + // prevent really long link text + if ( strlen($context[1]) > 100 ) + $context[1] = substr($context[1], 0, 100) . '...'; + + $marker = ''.$context[1].''; // set up our marker + $excerpt= str_replace($context[0], $marker, $excerpt); // swap out the link for our marker + $excerpt = strip_tags($excerpt, ''); // strip all tags but our context marker + $excerpt = trim($excerpt); + $preg_marker = preg_quote($marker, '|'); + $excerpt = preg_replace("|.*?\s(.{0,100}$preg_marker.{0,100})\s.*|s", '$1', $excerpt); + $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper + break; + } + } + + if ( empty($context) ) // Link to target not found + return new IXR_Error(17, __('The source URL does not contain a link to the target URL, and so cannot be used as a source.')); + + $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); + + $context = '[...] ' . esc_html( $excerpt ) . ' [...]'; + $pagelinkedfrom = $wpdb->escape( $pagelinkedfrom ); + + $comment_post_ID = (int) $post_ID; + $comment_author = $title; + $this->escape($comment_author); + $comment_author_url = $pagelinkedfrom; + $comment_content = $context; + $this->escape($comment_content); + $comment_type = 'pingback'; + + $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_content', 'comment_type'); + + $comment_ID = wp_new_comment($commentdata); + do_action('pingback_post', $comment_ID); + + return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto); + } + + /** + * Retrieve array of URLs that pingbacked the given URL. + * + * Specs on http://www.aquarionics.com/misc/archives/blogite/0198.html + * + * @since 1.5.0 + * + * @param array $args Method parameters. + * @return array + */ + function pingback_extensions_getPingbacks($args) { + + global $wpdb; + + do_action('xmlrpc_call', 'pingback.extensions.getPingbacks'); + + $this->escape($args); + + $url = $args; + + $post_ID = url_to_postid($url); + if (!$post_ID) { + // We aren't sure that the resource is available and/or pingback enabled + return new IXR_Error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); + } + + $actual_post = wp_get_single_post($post_ID, ARRAY_A); + + if (!$actual_post) { + // No such post = resource not found + return new IXR_Error(32, __('The specified target URL does not exist.')); + } + + $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_author_url, comment_content, comment_author_IP, comment_type FROM $wpdb->comments WHERE comment_post_ID = %d", $post_ID) ); + + if (!$comments) { + return array(); + } + + $pingbacks = array(); + foreach($comments as $comment) { + if ( 'pingback' == $comment->comment_type ) + $pingbacks[] = $comment->comment_author_url; + } + + return $pingbacks; + } +} + +$wp_xmlrpc_server = new wp_xmlrpc_server(); + +?>