la til pluginer

This commit is contained in:
Øyvind Bakkeli committed 2011-07-05 12:43:41 +02:00
1 parent ba315a55e5
commit b7db8c96be
42 files changed
+5384

No files matched your search

Binary file not shown.
@@ -0,0 +1,13 @@
div#cat-selector { margin-bottom:5px; }
div#available-posts,div#related-posts { height:250px; overflow:auto; padding:4px; }
div#related-posts div.thepost { cursor:pointer; background: #f1f1f1 url(sortable.png) no-repeat right 10px; }
div.thepost { overflow:hidden; background:#f1f1f1; border:solid 1px #ededed; margin-bottom:4px; padding:3px; }
div.thepost p { width:70%; float:left; padding:0 0 0 10px; }
div.thepost a { float:left; width:100px; display:block; text-align:center; padding:10px 0; color:#fff; text-decoration:none; color:#fff; }
div.thepost a:hover { text-decoration:underline; }
div.thepost a.addme { background:#679c47; }
div.thepost a.addme:hover { background:#466f2e; }
div.thepost a.removeme { background:#ef3737; }
div.thepost a.removeme:hover { background:#b82e2e; }
div.thepost a.added { background:#fb9606; }
div.thepost a.added:hover { background:#e08c15; }
@@ -0,0 +1,64 @@
jQuery(document).ready(function($) {
// make the related posts list sortable
jQuery('#related-posts').sortable();
// once a category is selected, give the user the option to filter the results
$("#filtered").keyup(function() {
var value = $(this).val();
value = $.trim(value);
value = value.replace(/ /gi, '|');
$("#available-posts div").each(function () {
if ($(this).attr('title').search(new RegExp(value, "i")) < 0) { $(this).fadeOut('fast'); } else { $(this).fadeIn('fast'); }
});
})
// fetch posts per category selected
$('.cpr_button').click(function(){
// make the call (Yo, Wazzzaaaaaa?)
$.ajax({
type: "post",
url: AjaxHandler.ajaxurl,
data: { action: 'cpr-cats', catID: $('#cpr_filters').val(), postID: $('#h_pid').val(), howMany: $('#howmany').val(), orderBy: $('#orderby').val(), orderIn: $('#orderin').val() },
beforeSend: function() {$("#available-posts").html('Loading...');},
success: function(response){
//dump the list with post from the category selected
$('div#available-posts').html(response);
//highlight as added the ones already in the list
var $set2 = $('#related-posts');
var $duplicates = $.grep($('#available-posts > div'), function(el) {
return $set2.children('#' + el.id).length > 0;
});
$($duplicates).find('a').removeClass('addme').addClass('added').html('Added');
}//success
});//ajax
}); //change
// clone items (avoid duplicates as well)
$('.addme').live('click', function() {
var post = $(this).parents('div.thepost');
var postId = post.attr("id");
if ( $("#related-posts").find( "#" + postId ).size() ) return false;
post.clone().fadeIn('normal').appendTo('#related-posts').find('a.addme').html('Remove').removeClass('addme').addClass('removeme').siblings('input').attr('name','reladded[]');
$(this).removeClass('addme').addClass('added').html('Added');
return false;
});
// remove items
$('.removeme').live('click', function() {
var post = $(this).parents('div.thepost');
var postId = post.attr("id");
post.fadeOut('normal', function() {$(this).remove(); });
$('#available-posts div#' + postId).find('a').removeClass('added').addClass('addme').html('Add');
return false;
});
// oh well, people do click a lot
$('.added').live('click', function() {
alert('This post is already in your list');
return false;
});
}); //ready
@@ -0,0 +1,166 @@
<?php
/*
Plugin Name: Custom Posts Relationships (CPR)
Plugin URI: http://webtoolkit4.me/2010/06/10/wordpress-plugin-custom-post-relationships-cpr-v1-0/
Description: An easy way to create post relationships in Wordpress
Version: 1.01
Author: Gerasimos Tsiamalos
Author URI: http://webtoolkit4.me/
Copyright 2010 Gerasimos Tsiamalos (email : tsiger@gmail.com)
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
define('CPR_VERSION','1.01');
function cpr_scripts_styles() {
wp_enqueue_script('jquery-ui-core');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_style('cpr-css', plugin_dir_url( __FILE__ ) . 'cpr.css', true, CPR_VERSION , 'all' );
wp_enqueue_script('category-ajax-request', plugin_dir_url( __FILE__ ) . 'cpr.js', array( 'jquery' ) );
wp_localize_script('category-ajax-request', 'AjaxHandler', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function cpr_box() {
add_meta_box( 'post-meta-boxes', 'Custom Post Relationships (CPR)', 'cpr_category_selector', 'post', 'normal','high' );
}
function cpr_category_selector() {
global $post_ID;
echo "<div id='cat-selector'>";
echo "<select id='howmany' name='howmany'><option value='10'>10</option><option value='50'>50</option><option value='100'>100</option><option value='-1'>All</option></select> posts from ";
wp_dropdown_categories('hide_empty=0&hierarchical=1&name=cpr_filters&show_count=1&show_option_all=All categories');
echo " ordered by <select id='orderby' name='orderby'><option value='title'>Title</option><option value='date'>Date</option></select> in ";
echo " <select id='orderin' name='orderin'><option value='ASC'>Ascending</option><option value='DESC'>Descending</option></select> order &nbsp;";
echo " <input type='button' class='cpr_button button' value='Search posts' />";
echo " &nbsp; Filter results: <input type='text' id='filtered' name='filtered' /><input type='hidden' id='h_pid' name='h_pid' value='". $post_ID ."'/>";
echo "</div>";
echo '<div class="postbox">
<h3>Available Posts</h3>
<div id="available-posts">Please select a category</div>
<h3>Related Posts (Drag to reorder)</h3>
<div id="related-posts">';
$relations = get_post_meta($post_ID, 'cpr_related', true);
if (!empty($relations)) :
foreach($relations as $relation) :
$post = get_post($relation);
echo "<div title='" . $post->post_title . "' class='thepost' id='post-".$post->ID ."'>
<a href='#' class='removeme'>Remove</a>
<p><strong>" . $post->post_title . "</strong></p>
<input type='hidden' name='reladded[]' value='" . $post->ID . "' />
</div>";
endforeach;
endif;
echo '<input type="hidden" name="myplugin_noncename" id="myplugin_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
echo "</div></div>";
}
// Where's Dukey? Wa zaaaaaaaaaaaa (the call)
function cpr_cats() {
$catID = $_POST['catID'];
$postID = $_POST['postID'];
$howMany = $_POST['howMany'];
$orderBy = $_POST['orderBy'];
$orderIn = $_POST['orderIn'];
if ($catID >= 0) {
// if all categories selected
if ($catID == 0) {
$args = array(
'post_type' => 'post',
'numberposts' => $howMany,
'post_status' => 'publish',
'orderby' => $orderBy,
'order' => $orderIn,
'post__not_in' => array($postID)
);
$catPosts = get_posts($args);
}
else {
$args = array(
'post_type' => 'post',
'numberposts' => $howMany,
'post_status' => 'publish',
'orderby' => $orderBy,
'order' => $orderIn,
'category__in' => array($catID),
'post__not_in' => array($postID)
);
$catPosts = get_posts($args);
}
if (!empty($catPosts)) {
foreach ( $catPosts as $catPost ) {
setup_postdata($post);
echo "<div title='" . $catPost->post_title . "' class='thepost' id='post-".$catPost->ID ."'>
<a href='#' class='addme'>Add</a>
<p><strong>" . $catPost->post_title . "</strong></p>
<input type='hidden' name='related[]' value='" . $catPost->ID . "' />
</div>";
}// foreach
}// if !empty
else { echo "<div class='thepost'>This category is empty</div>"; }
}//if
else { echo "<div class='thepost'>Please select a category</div>"; }
exit;
}// function cpr_cats
function cpr_save() {
global $post_ID;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id;
if (!wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__))) return $post_id;
if (!current_user_can( 'edit_post', $post_id ) ) return $post_id;
$id = $_POST['post_ID'];
$related = $_POST['reladded'];
update_post_meta($id, 'cpr_related', $related);
}
function cpr_populate($id) {
global $wpdb;
$related_meta = get_post_meta($id, 'cpr_related', true);
$related_posts = array();
if (!empty($related_meta)) {
foreach ($related_meta as $related) {
$post = get_post($related);
$related_posts[] = $post;
}
return $related_posts;
}
}
// oi! wait! where are you going? are you sure? 100%? a second thought? come on let's talk about it. oh well.
function cpr_uninstall() {
global $wpdb;
$wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = 'cpr_related'"));
}
add_action('admin_menu', 'cpr_box');
add_action('wp_ajax_cpr-cats', 'cpr_cats');
add_action('admin_menu', 'cpr_scripts_styles');
add_action('save_post', 'cpr_save');
add_action('wt4_show','cpr_populate');
register_uninstall_hook(__FILE__, 'cpr_uninstall');
?>
@@ -0,0 +1,48 @@
=== Custom Post Relationships (CPR) ===
Contributors: Gerasimos Tsiamalos
Donate link: http://webtoolkit4.me
Tags: related posts, custom related posts, custom relations, post relationships, related, post
Requires at least: 2.9.0
Tested up to: 3.0
Stable tag: 1.0.1
This plugin will let you create custom post relationships.
== Description ==
Most of the "related posts" plugins out there while they provide some kind of control on how to create related posts, they all rely on an algorithm
and the results are automatic. With CPR you get total control as you can manually select the posts that you want to relate.
== Installation ==
1. Upload the folder to the `/wp-content/plugins/` directory
2. Activate the plugin through the 'Plugins' menu in WordPress
3. In the Posts page you will see the main screen of the plugin.
== Frequently Asked Questions ==
= How do i display the related posts then? =
Check http://webtoolkit4.me/2010/06/10/wordpress-plugin-custom-post-relationships-cpr-v1-0/ for info on how to display your related posts.
Have in mind that you can display anything you want, even custom fields.
== Screenshots ==
1. The Custom related posts (CPR) screen. Search, select, relate, done.
== Changelog ==
= 1.0.1 =
* "All categories" option added.
= 1.0 =
* Initial Release
== Upgrade Notice ==
= 1.0.1 =
"All Categories" option has been added.
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 B

Binary file not shown.
+45
View File
@@ -0,0 +1,45 @@
/* Begin Debug Queries CSS */
.transparent {
filter: alpha(opacity=90);
opacity: 0.9;
}
#debugqueries {
width: 90%;
margin: 1em auto;
padding: 15px 35px;
border: 1px solid #000;
background: #464646;
color: #fff;
text-align: left;
z-index: 999;
}
#debugqueries h2, #debugqueries p, #debugqueries a {
color: #fff;
}
#debugqueries li {
padding: 5px 0;
}
#debugqueries ul {
margin-top: 1em;
}
#debugqueries ol li ul li, #debugqueries ul li {
padding: 0 5px;
}
#debugqueries ol li ul li:hover, #debugqueries ul li:hover {
color: #000;
background-color: #DFDFDF;
}
#debugqueries li.alt {
color: #D98500;
}
#debugqueries li.none_list {
list-style-type: none;
}
/* End Debug Queries CSS */
+207
View File
@@ -0,0 +1,207 @@
<?php
/**
* @package Debug Queries
* @author Frank B&uuml;ltge
*/
/*
Plugin Name: Debug Queries
Plugin URI: http://bueltge.de/wordpress-performance-analysieren-plugin/558/
Description: List query-actions only for admins; for debug purposes
Author: Frank B&uuml;ltge
Author URI: http://bueltge.de/
Version: 1.0.1
License: GPLv2
Last Change: 23.03.2011 21:00
*/
//avoid direct calls to this file, because now WP core and framework has been used
if ( !function_exists( 'add_action' ) ) {
header( 'Status: 403 Forbidden' );
header( 'HTTP/1.1 403 Forbidden' );
exit();
}
if ( function_exists( 'add_action' ) ) {
//WordPress definitions
if ( !defined( 'WP_CONTENT_URL' ) )
define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
if ( !defined( 'WP_CONTENT_DIR' ) )
define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );
if ( !defined( 'WP_PLUGIN_URL' ) )
define( 'WP_PLUGIN_URL', WP_CONTENT_URL . '/plugins' );
}
// disable mySQL Session Cache
define( 'QUERY_CACHE_TYPE_OFF', TRUE );
if ( !defined( 'SAVEQUERIES' ) )
define( 'SAVEQUERIES', TRUE );
if ( !class_exists( 'Debug_Queries' ) ) {
class Debug_Queries {
// constructor
function debug_queries() {
if ( function_exists( 'register_activation_hook' ) )
register_activation_hook(__FILE__, array( &$this, 'activate' ) );
if ( function_exists( 'register_uninstall_hook' ) )
register_uninstall_hook(__FILE__, array( 'Debug_Queries', 'deactivate' ) );
if ( function_exists( 'register_deactivation_hook' ) )
register_deactivation_hook(__FILE__, array( &$this, 'deactivate' ) );
add_action( 'wp_head', array( $this, 'wp_head' ) );
add_action( 'wp_footer', array( $this, 'the_queries' ) );
}
// core
function get_queries() {
global $wpdb;
// disabled session cache of mySQL
if ( QUERY_CACHE_TYPE_OFF )
$wpdb->query( 'SET SESSION query_cache_type = 0;' );
$debug_queries = '';
if ( $wpdb->queries ) {
$x = 0;
$total_time = timer_stop( FALSE, 22 );
$total_query_time = 0;
$class = '';
$debug_queries .= '<ol>' . "\n";
foreach ( $wpdb->queries as $q ) {
if ( $x % 2 != 0 )
$class = '';
else
$class = ' class="alt"';
$q[0] = trim( ereg_replace( '[[:space:]]+', ' ', $q[0]) );
$total_query_time += $q[1];
$debug_queries .= '<li' . $class . '><ul>';
$debug_queries .= '<li><strong>' . __( 'Time:' ) . '</strong> ' . $q[1] . '</li>';
if ( isset($q[1]) )
$debug_queries .= '<li><strong>' . __( 'Query:' ) . '</strong> ' . htmlentities( $q[0] ) . '</li>';
if ( isset($q[2]) )
$debug_queries .= '<li><strong>' . __( 'Call from:' ) . '</strong> ' . htmlentities( $q[2] ) . '</li>';
$debug_queries .= '</ul></li>' . "\n";
$x++;
}
$debug_queries .= '</ol>' . "\n\n";
}
$php_time = $total_time - $total_query_time;
// Create the percentages
$mysqlper = number_format_i18n( $total_query_time / $total_time * 100, 2 );
$phpper = number_format_i18n( $php_time / $total_time * 100, 2 );
$debug_queries .= '<ul>' . "\n";
$debug_queries .= '<li><strong>' . __( 'Total query time:' ) . ' ' . number_format_i18n( $total_query_time, 5 ) . __( 's for' ) . ' ' . count($wpdb->queries) . ' ' . __( 'queries.' ) . '</strong></li>';
if ( count($wpdb->queries) != get_num_queries() ) {
$debug_queries .= '<li><strong>' . __( 'Total num_query time:' ) . ' ' . timer_stop() . ' ' . __( 'for' ) . ' ' . get_num_queries() . ' ' . __( 'num_queries.' ) . '</strong></li>' . "\n";
$debug_queries .= '<li class="none_list">' . __( '&raquo; Different values in num_query and query? - please set the constant' ) . ' <code>define(\'SAVEQUERIES\', true);</code>' . __( 'in your' ) . ' <code>wp-config.php</code></li>' . "\n";
}
if ( $total_query_time == 0 )
$debug_queries .= '<li class="none_list">' . __( '&raquo; Query time is null (0)? - please set the constant' ) . ' <code>SAVEQUERIES</code>' . ' ' . __( 'at' ) . ' <code>TRUE</code> ' . __( 'in your' ) . ' <code>wp-config.php</code></li>' . "\n";
$debug_queries .= '<li>' . __( 'Page generated in' ). ' ' . number_format_i18n( $total_time, 5 ) . __( 's, ' ) . $phpper . __( '% PHP' ) . ', ' . $mysqlper . __( '% MySQL' ) . '</li>' . "\n";
$debug_queries .= '</ul>' . "\n";
return $debug_queries;
}
// echo in html-comment
function html_comment_queries() {
if ( ! current_user_can( 'DebugQueries' ) )
return;
$echo = '';
$echo .= "\n\n" . __( '<!-- Debug Queries by Frank Bueltge, bueltge.de' );
$echo .= "\n\t" . __( '! Deactivate after analysis !' );
$echo .= "\n" . $this->get_queries() . "\n" . ' -->' . "\n\n";
echo $echo;
}
// echo in frontend
function the_queries() {
if ( ! current_user_can( 'DebugQueries' ) )
return;
$echo = '';
$echo .= '<div id="debugqueries" class="transparent">' . "\n";
$echo .= '<h3><a href="http://bueltge.de/wordpress-performance-analysieren-plugin/558/">Debug Queries</a> ' . __( 'by Frank B&uuml;ltge' ) . ', <a href="http://bueltge.de/">bueltge.de</a></h3>' . "\n";
$echo .= '<p>' . __( '&raquo; Deactivate after analysis!' ). '</p>' . "\n";
$echo .= $this->get_queries();
$echo .= '</div>' . "\n\n";
echo $echo;
}
// add user rights
function activate() {
global $wp_roles;
$wp_roles->add_cap( 'administrator', 'DebugQueries' );
}
// delete user rights
function deactivate() {
global $wp_roles;
$wp_roles->remove_cap( 'administrator', 'DebugQueries' );
}
// function for WP < 2.8
function plugins_url( $path = '', $plugin = '' ) {
if ( function_exists( 'is_ssl' ) )
$scheme = ( is_ssl() ? 'https' : 'http' );
else
$scheme = 'http';
$url = WP_PLUGIN_URL;
if ( 0 === strpos( $url, 'http' ) ) {
if ( function_exists( 'is_ssl' ) && is_ssl() )
$url = str_replace( 'http://', "{$scheme}://", $url );
}
if ( ! empty( $plugin ) && is_string( $plugin ) ) {
$folder = dirname( plugin_basename( $plugin ) );
if ( '.' != $folder)
$url .= '/' . ltrim($folder, '/' );
}
if ( ! empty( $path ) && FALSE === is_string( $path ) && strpos( $path, '..' ) )
$url .= '/' . ltrim( $path, '/' );
return apply_filters( 'plugins_url', $url, $path, $plugin );
}
// infos in frontend, add css to head
function wp_head() {
global $wp_version;
if ( ! current_user_can( 'DebugQueries' ) )
return NULL;
if ( version_compare( $wp_version, '2.8dev', '>' ) )
$style = plugins_url( 'css/style-frontend.css', __FILE__ );
else
$style = $this->plugins_url( 'css/style-frontend.css', __FILE__ );
$return = '<link rel="stylesheet" href="' . $style . '" type="text/css" media="screen" />';
echo $return;
}
}
$debug_queries = new Debug_Queries();
}
?>
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+81
View File
@@ -0,0 +1,81 @@
=== Debug Queries ===
Contributors: Bueltge
Donate link: http://bueltge.de/wunschliste/
Tags: query, queries, database, performance, analyse, sql, debug, tuning
Requires at least: 1.5
Tested up to: 3.1
Stable tag: 1.0.1
List query-actions only for admins; for debug purposes
== Description ==
List query-actions only for admins; for debug purposes. See all queries on the frontend of the blog and find the slowest part.
Since version 1.0.0 the plugin disable the MySQL query cache for the current connected session. That will show you the real execution time for a query. To disable this behavior set the constant `QUERY_CACHE_TYPE_OFF` to `FALSE`.
The plugin is perfect for WordPress developers, plugin and theme developers and site administrators who are trying to find out why the blog is too slow.
Please visit [the official website](http://bueltge.de/wordpress-performance-analysieren-plugin/558/ "Debug Queries") for further details and the latest information on this plugin.
= More Plugins =
Please see also my [Premium Plugins](http://wpplugins.com/author/malo.conny/). Maybe you find an solution for your requirement.
= Interested in WordPress tips and tricks =
You may also be interested in WordPress tips and tricks at [WP Engineer](http://wpengineer.com/) or for german people [bueltge.de](http://bueltge.de/)
== Installation ==
1. Unpack the download-package
1. Upload all files to the `/wp-content/plugins/` directory, without folder
1. Activate the plugin through the 'Plugins' menu in WordPress
1. That's it! Now you are all set to go on to thr frontend of your weblog and see the list of queries. You find the querie-analysis on end of the blog. Only logged administrators can see the result.
See on [the official website](http://bueltge.de/wordpress-performance-analysieren-plugin/558/ "Debug Queries").
== Screenshots ==
1. List queries in frontend on a example blog
== Other Notes ==
= Params =
The plugin has since version 1.0.0 a constant to disable the mySQL Session cache. On defoult is the value on true and the cache is off for an better analyse! For change this, set the constant `QUERY_CACHE_TYPE_OFF` to `FALSE`.
= Example =
This is a example for analysis.
`# Time: 0.00198888778687
Query: SELECT option_name, option_value FROM wp_options WHERE autoload = 'yes'
Call from: require, require_once, require_once, require_once, is_blog_installed, wp_load_alloptions
# Time: 0.000695943832397
Query: UPDATE `wp_options` SET `option_value` = 'a:3:{i:0;b:0;s:25:\"adminimize/adminimize.php\";a:2:{i:0;O:10:\"adminimize\":1:{s:12:\"wp_filter_id\";i:0;}i:1;s:12:\"on_deinstall\";}s:31:\"debug_queries/debug_queries.php\";a:2:{i:0;O:12:\"DebugQueries\":1:{s:12:\"wp_filter_id\";i:0;}i:1;s:10:\"deactivate\";}}' WHERE `option_name` = 'uninstall_plugins'`
`Call from: require, require_once, require_once, require_once, include_once, adminimize->adminimize, register_uninstall_hook, update_option`
`
. . .
`
` Total query time: 0.0155501365662 for 23 queries.
Total num_query time: 0.392 for 23 num_queries.`
= Acknowledgements =
Thanks to Joost de Valk on [yoast.com](http://yoast.com/ "yoast.com") for small modifed on the plugin for some extra info.
= Licence =
Good news, this plugin is free for everyone! Since it's released under the GPL, you can use it free of charge on your personal or commercial blog. But if you enjoy this plugin, you can thank me and leave a [small donation](http://bueltge.de/wunschliste/ "Wishliste and Donate") for the time I've spent writing and supporting this plugin. And I really don't want to know how many hours of my life this plugin has already eaten ;)
== Frequently Asked Questions ==
= Where can I get more information? =
Please visit [the official website](http://bueltge.de/wordpress-performance-analysieren-plugin/558/ "Debug Queries") for the latest information on this plugin.
= I love this plugin! How can I show the developer how much I appreciate his work? =
Please visit [the official website](http://bueltge.de/wordpress-performance-analysieren-plugin/558/ "Debug Queries") and let him know your care or see the [wishlist](http://bueltge.de/wunschliste/ "Wishlist") of the author.
== Changelog ==
= v1.0.1 (03/23/2011) =
* fixes for changed functions of WP 3.1
* changes on markup for better use on frontend
* small changes for WP Codex
= v1.0.0 (12/01/2010) =
* Feature: add constant for disable mySQL Session Cache; The plugin has since version 1.0.0 a constant to disable the mySQL Session cache. On defoult is the value on true and the cache is off for an better analyse! For change this, set the constant `QUERY_CACHE_TYPE_OFF` to `FALSE`.
= v0.6 (01/19/2010) =
* Convert all applicable characters in queries to HTML entities
Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.
+270
View File
@@ -0,0 +1,270 @@
<?php
/**
* Register a connection between two post types.
* This creates the appropriate meta box in the admin edit screen
*
* @param array $args Can be:
* - 'from' string The first end of the connection.
* - 'to' string The second end of the connection.
* - 'fields' array Additional metadata fields (optional).
* - 'prevent_duplicates' bool Wether to disallow duplicate connections between the same two posts. Default: true.
* - 'reciprocal' bool Wether to show the box on both sides of the connection. Default: false.
* - 'title' string The box's title. Default: 'Connected {$post_type}s'
* - 'context' string Where should the box show up by default. Possible values: 'advanced' or 'side'
* - 'box' string A class that handles displaying and saving connections. Default: P2P_Box_Multiple
*/
function p2p_register_connection_type( $args ) {
$argv = func_get_args();
if ( count( $argv ) > 1 ) {
$args = array();
@list( $args['from'], $args['to'], $args['reciprocal'] ) = $argv;
}
$defaults = array(
'from' => '',
'to' => '',
'fields' => array(),
'prevent_duplicates' => true,
'reciprocal' => false,
'title' => '',
'context' => 'side',
'box' => 'P2P_Box_Multiple',
);
$args = wp_parse_args( $args, $defaults );
P2P_Connection_Types::register( $args );
}
/**
* Connect a post to one or more other posts.
*
* @param int|array $from The first end of the connection
* @param int|array $to The second end of the connection
* @param array $data additional data about the connection
*/
function p2p_connect( $from, $to, $data = array() ) {
foreach ( (array) $from as $from ) {
foreach ( (array) $to as $to ) {
P2P_Connections::connect( $from, $to, $data );
}
}
}
/**
* Disconnect a post from or more other posts.
*
* @param int|array $from The first end of the connection
* @param int|array|string $to The second end of the connection
* @param array $data additional data about the connection to filter against
*/
function p2p_disconnect( $from, $to, $data = array() ) {
foreach ( (array) $from as $from ) {
foreach ( (array) $to as $to ) {
P2P_Connections::disconnect( $from, $to, $data );
}
}
}
/**
* Get a list of connected posts.
*
* Low-level function. Use new WP_Query( array( 'connected' => $post_id ) ) instead.
*
* @param int $post_id One end of the connection
* @param string $direction The direction of the connection. Can be 'to', 'from' or 'any'
* @param array $data additional data about the connection to filter against
*
* @return array( p2p_id => post_id )
*/
function p2p_get_connected( $post_id, $direction = 'any', $data = array() ) {
return P2P_Connections::get( $post_id, $direction, $data );
}
/**
* See if a certain post is connected to another one
*
* @param int $from The first end of the connection
* @param int $to The second end of the connection
* @param array $data additional data about the connection to filter against
*
* @return bool True if the connection exists, false otherwise
*/
function p2p_is_connected( $from, $to, $data = array() ) {
$ids = p2p_get_connected( $from, $to, $data );
return !empty( $ids );
}
/**
* Delete one or more connections
*
* @param int|array $p2p_id Connection ids
*
* @return int Number of connections deleted
*/
function p2p_delete_connection( $p2p_id ) {
return P2P_Connections::delete( $p2p_id );
}
/**
* Optimized inner query, after the outer query was executed.
*
* Populates each of the outer querie's $post objects with a property containing a list of connected posts
*
* @param string $direction The direction of the connection. Can be 'to', 'from' or 'any'
* @param string $prop_name The property name; will be prefixed with 'connected_'
* @param string|array $args The query vars for the inner query
* @param object $query (optional) The outer query. Defaults to the global $wp_query
*/
function p2p_each_connected( $direction, $prop_name, $search, $query = null ) {
if ( is_null( $query ) )
$query = $GLOBALS['wp_query'];
if ( empty( $query->posts ) )
return;
if ( empty( $prop_name ) )
$prop_name = 'connected';
else
$prop_name = 'connected_' . $prop_name;
// re-index by ID
$posts = array();
foreach ( $query->posts as $post ) {
$post->$prop_name = array();
$posts[ $post->ID ] = $post;
}
// ignore other 'connected' query vars for the inner query
foreach ( array_keys( P2P_Query::$qv_map ) as $qv )
unset( $search[ $qv ] );
if ( 'any' == $direction )
$key = 'connected';
else
$key = 'connected_' . $direction;
$search[ $key ] = array_keys( $posts );
$search[ 'suppress_filters' ] = false;
foreach ( get_posts( $search ) as $inner_post ) {
if ( $inner_post->ID == $inner_post->p2p_from )
$outer_post_id = $inner_post->p2p_to;
elseif ( $inner_post->ID == $inner_post->p2p_to )
$outer_post_id = $inner_post->p2p_from;
else
throw new Exception( 'Corrupted data.' );
if ( $outer_post_id == $inner_post->ID )
throw new Exception( 'Post connected to itself.' );
array_push( $posts[ $outer_post_id ]->$prop_name, $inner_post );
}
}
// Allows you to write query_posts( array( 'connected' => 123 ) );
class P2P_Query {
static $qv_map = array(
'connected' => 'any',
'connected_to' => 'to',
'connected_from' => 'from',
);
function init() {
new scbQueryManipulation( array( __CLASS__, 'query' ), false ); // 'posts_clauses'
add_filter( 'the_posts', array( __CLASS__, 'the_posts' ), 11, 2 );
}
function query( $clauses, $wp_query ) {
global $wpdb;
$found = self::find_qv( $wp_query );
if ( !$found )
return $clauses;
list( $search, $key, $direction ) = $found;
$clauses['fields'] .= ", $wpdb->p2p.*";
$clauses['join'] .= " INNER JOIN $wpdb->p2p";
if ( 'any' == $search ) {
$search = false;
} else {
$search = implode( ',', array_map( 'absint', (array) $search ) );
}
switch ( $direction ) {
case 'from':
$clauses['where'] .= " AND $wpdb->posts.ID = $wpdb->p2p.p2p_to";
if ( $search ) {
$clauses['where'] .= " AND $wpdb->p2p.p2p_from IN ($search)";
}
break;
case 'to':
$clauses['where'] .= " AND $wpdb->posts.ID = $wpdb->p2p.p2p_from";
if ( $search ) {
$clauses['where'] .= " AND $wpdb->p2p.p2p_to IN ($search)";
}
break;
case 'any':
if ( $search ) {
$clauses['where'] .= " AND (
($wpdb->posts.ID = $wpdb->p2p.p2p_to AND $wpdb->p2p.p2p_from IN ($search) ) OR
($wpdb->posts.ID = $wpdb->p2p.p2p_from AND $wpdb->p2p.p2p_to IN ($search) )
)";
} else {
$clauses['where'] .= " AND ($wpdb->posts.ID = $wpdb->p2p.p2p_to OR $wpdb->posts.ID = $wpdb->p2p.p2p_from)";
}
break;
}
$connected_meta = $wp_query->get( 'connected_meta' );
if ( !empty( $connected_meta ) ) {
$meta_clauses = _p2p_meta_sql_helper( $connected_meta );
foreach ( $meta_clauses as $key => $value ) {
$clauses[ $key ] .= $value;
}
}
return $clauses;
}
function the_posts( $the_posts, $wp_query ) {
if ( empty( $the_posts ) )
return $the_posts;
$found = self::find_qv( $wp_query, 'each_' );
if ( !$found )
return $the_posts;
list( $search, $qv, $direction ) = $found;
$qv = explode('_', $qv);
$key = isset( $qv[1] ) ? $qv[1] : '';
p2p_each_connected( $direction, $key, $search, $wp_query );
return $the_posts;
}
private function find_qv( $wp_query, $prefix = '' ) {
foreach ( self::$qv_map as $qv => $direction ) {
$search = $wp_query->get( $prefix . $qv );
if ( !empty( $search ) )
break;
}
if ( empty( $search ) )
return false;
return array( $search, $qv, $direction );
}
}
@@ -0,0 +1,72 @@
# Translation of the WordPress plugin Posts 2 Posts 0.3 by scribu.
# Copyright (C) 2010 scribu
# This file is distributed under the same license as the Posts 2 Posts package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2010.
#
msgid ""
msgstr ""
"Project-Id-Version: Posts 2 Posts 0.4\n"
"Report-Msgid-Bugs-To: http://wordpress.org/tag/posts-to-posts\n"
"POT-Creation-Date: 2010-10-11 13:40+0300\n"
"PO-Revision-Date: 2010-10-18 22:03-0500\n"
"Last-Translator: \n"
"Language-Team: wikichaves.com <info@wikichaves.com>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Poedit-Language: Spanish\n"
"X-Poedit-Country: ARGENTINA\n"
"X-Poedit-Basepath: ..\n"
#: scb/AdminPage.php:164
msgid "Settings <strong>saved</strong>."
msgstr "Preferencias <strong>guardado</strong>."
#: scb/AdminPage.php:176
#: scb/AdminPage.php:186
msgid "Save Changes"
msgstr "Guardar Cambios"
#: scb/AdminPage.php:368
msgid "Settings"
msgstr "Preferencias"
#: ui/boxes.php:59
msgid "No connections."
msgstr "Sin conexiones."
#: ui/boxes.php:71
msgid "Search"
msgstr "Buscar"
#: ui/boxes.php:79
msgid "Start typing the title of a post you want to connect and then click on to connect it."
msgstr "Comenzar a escribir el título de la entrada a la que se quiera conectar y luego clickear para conectarla."
#: ui/boxes.php:89
msgid "Enter IDs of posts to connect, separated by commas."
msgstr "Ingresar los IDs de las entradas a conectar, separadas por comas."
#. Plugin Name of the plugin/theme
msgid "Posts 2 Posts"
msgstr ""
#. Plugin URI of the plugin/theme
msgid "http://scribu.net/wordpress/posts-to-posts"
msgstr ""
#. Description of the plugin/theme
msgid "Create many-to-many relationships between all types of posts"
msgstr ""
#. Author of the plugin/theme
msgid "scribu"
msgstr ""
#. Author URI of the plugin/theme
msgid "http://scribu.net/"
msgstr ""
#~ msgid "Connected"
#~ msgstr "Conectat"
@@ -0,0 +1,106 @@
# Translation of the WordPress plugin Posts 2 Posts 0.3 by scribu.
# Copyright (C) 2010 scribu
# This file is distributed under the same license as the Posts 2 Posts package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2010.
#
msgid ""
msgstr ""
"Project-Id-Version: Posts 2 Posts 0.3\n"
"Report-Msgid-Bugs-To: http://wordpress.org/tag/posts-to-posts\n"
"POT-Creation-Date: 2011-03-30 21:56+0300\n"
"PO-Revision-Date: 2011-03-30 21:56+0200\n"
"Last-Translator: scribu <mail@scribu.net>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: scb/AdminPage.php:164
msgid "Settings <strong>saved</strong>."
msgstr "Setări <strong>salvate</strong>."
#: scb/AdminPage.php:176
#: scb/AdminPage.php:186
msgid "Save Changes"
msgstr "Salvează schimbările"
#: scb/AdminPage.php:368
msgid "Settings"
msgstr "Setări"
#: ui/boxes.php:88
msgid "Create connections:"
msgstr "Creează conexiuni:"
#: ui/boxes.php:108
msgid "Previous"
msgstr "Anterioare"
#: ui/boxes.php:109
msgid "of"
msgstr "din"
#: ui/boxes.php:110
msgid "Next"
msgstr "Următoare"
#: ui/boxes.php:114
msgid "Recent"
msgstr "Recente"
#: ui/boxes.php:174
#: ui/boxes.php:175
msgid "Create connection"
msgstr "Crează conexiune"
#: ui/boxes.php:182
#: ui/boxes.php:183
msgid "Delete connection"
msgstr "Șterge conexiune"
#: ui/boxes.php:189
#: ui/boxes.php:190
msgid "Delete all connections"
msgstr "Șterge toate conexiunile"
#: ui/ui.php:40
#, php-format
msgid "Connected %s"
msgstr "%s conectate"
#: ui/ui.php:87
msgid "Are you sure you want to delete all connections?"
msgstr "Sigur vreți să ștergeți toate conexiunile?"
#. Plugin Name of the plugin/theme
msgid "Posts 2 Posts"
msgstr ""
#. Plugin URI of the plugin/theme
msgid "http://scribu.net/wordpress/posts-to-posts"
msgstr ""
#. Description of the plugin/theme
msgid "Create many-to-many relationships between all types of posts"
msgstr ""
#. Author of the plugin/theme
msgid "scribu"
msgstr ""
#. Author URI of the plugin/theme
msgid "http://scribu.net/"
msgstr ""
#~ msgid "Search"
#~ msgstr "Căutare"
#~ msgid ""
#~ "Start typing the title of a post you want to connect and then click on to "
#~ "connect it."
#~ msgstr ""
#~ "Începe să scrii titlul post-ului de conectat și apoi fă click pentru a-l "
#~ "conecta."
#~ msgid "Enter IDs of posts to connect, separated by commas."
#~ msgstr "Intrdu ID-uri ale post-urilor de conectat, separate prin virgulă."
@@ -0,0 +1,91 @@
# Translation of the WordPress plugin Posts 2 Posts 0.7-beta by scribu.
# Copyright (C) 2011 scribu
# This file is distributed under the same license as the Posts 2 Posts package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2011.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Posts 2 Posts 0.7-beta\n"
"Report-Msgid-Bugs-To: http://wordpress.org/tag/posts-to-posts\n"
"POT-Creation-Date: 2011-03-30 21:56+0300\n"
"PO-Revision-Date: 2011-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: scb/AdminPage.php:164
msgid "Settings <strong>saved</strong>."
msgstr ""
#: scb/AdminPage.php:176 scb/AdminPage.php:186
msgid "Save Changes"
msgstr ""
#: scb/AdminPage.php:368
msgid "Settings"
msgstr ""
#: ui/boxes.php:88
msgid "Create connections:"
msgstr ""
#: ui/boxes.php:108
msgid "Previous"
msgstr ""
#: ui/boxes.php:109
msgid "of"
msgstr ""
#: ui/boxes.php:110
msgid "Next"
msgstr ""
#: ui/boxes.php:114
msgid "Recent"
msgstr ""
#: ui/boxes.php:174 ui/boxes.php:175
msgid "Create connection"
msgstr ""
#: ui/boxes.php:182 ui/boxes.php:183
msgid "Delete connection"
msgstr ""
#: ui/boxes.php:189 ui/boxes.php:190
msgid "Delete all connections"
msgstr ""
#: ui/ui.php:40
#, php-format
msgid "Connected %s"
msgstr ""
#: ui/ui.php:87
msgid "Are you sure you want to delete all connections?"
msgstr ""
#. Plugin Name of the plugin/theme
msgid "Posts 2 Posts"
msgstr ""
#. Plugin URI of the plugin/theme
msgid "http://scribu.net/wordpress/posts-to-posts"
msgstr ""
#. Description of the plugin/theme
msgid "Create many-to-many relationships between all types of posts"
msgstr ""
#. Author of the plugin/theme
msgid "scribu"
msgstr ""
#. Author URI of the plugin/theme
msgid "http://scribu.net/"
msgstr ""
@@ -0,0 +1,77 @@
<?php
/*
Plugin Name: Posts 2 Posts
Version: 0.7
Plugin Author: scribu
Description: Create many-to-many relationships between all types of posts
Author URI: http://scribu.net/
Plugin URI: http://scribu.net/wordpress/posts-to-posts
Text Domain: posts-to-posts
Domain Path: /lang
Copyright (C) 2010 Cristi Burcă (scribu@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
require dirname( __FILE__ ) . '/scb/load.php';
function _p2p_init() {
load_plugin_textdomain( 'posts-to-posts', '', dirname( plugin_basename( __FILE__ ) ) . '/lang' );
require_once dirname( __FILE__ ) . '/storage.php';
require_once dirname( __FILE__ ) . '/api.php';
require_once dirname( __FILE__ ) . '/ui/ui.php';
require_once dirname( __FILE__ ) . '/ui/boxes.php';
P2P_Connections::init( __FILE__ );
P2P_Query::init();
P2P_Connection_Types::init();
P2P_Migrate::init();
}
scb_init( '_p2p_init' );
class P2P_Migrate {
function init() {
add_action( 'admin_notices', array( __CLASS__, 'migrate' ) );
}
function migrate() {
if ( !isset( $_GET['migrate_p2p'] ) || !current_user_can( 'administrator' ) )
return;
$tax = 'p2p';
register_taxonomy( $tax, 'post', array( 'public' => false ) );
$count = 0;
foreach ( get_terms( $tax ) as $term ) {
$post_b = (int) substr( $term->slug, 1 );
$post_a = get_objects_in_term( $term->term_id, $tax );
p2p_connect( $post_a, $post_b );
wp_delete_term( $term->term_id, $tax );
$count += count( $post_a );
}
printf( "<div class='updated'><p>Migrated %d connections.</p></div>", $count );
}
}
@@ -0,0 +1,92 @@
=== Posts 2 Posts ===
Contributors: scribu, ciobi
Donate link: http://scribu.net/paypal
Tags: cms, custom post types, relationships, many-to-many
Requires at least: 3.0
Tested up to: 3.1
Stable tag: 0.7
Create connections between posts
== Description ==
This plugin allows you to create many-to-many relationships between posts of all types.
You can use it to manually create lists of related posts.
Or, if you have a 'product' post type, you can make a by-directional connection to a 'review' post type.
The possibilities are endless.
Head out to the [Wiki](https://github.com/scribu/wp-posts-to-posts/wiki) for tutorials and other resources.
Links: [Plugin News](http://scribu.net/wordpress/posts-to-posts) | [Author's Site](http://scribu.net)
== Installation ==
You can either install it automatically from the WordPress admin, or do it manually:
1. Unzip the "Posts 2 Posts" archive and put the folder into your plugins folder (/wp-content/plugins/).
1. Activate the plugin from the Plugins menu.
== Frequently Asked Questions ==
= Error on activation: "Parse error: syntax error, unexpected..." =
Make sure your host is running PHP 5. The only foolproof way to do this is to add this line to wp-config.php:
`var_dump(PHP_VERSION);`
<br>
== Screenshots ==
1. Simple connection metabox
2. Advanced connection metabox
== Changelog ==
= 0.7 =
* improved UI
* added 'fields', 'context' and 'prevent_duplicates' args to p2p_register_connection_type()
* [more info](http://scribu.net/wordpress/posts-to-posts/p2p-0-7.html)
= 0.6 =
* added p2p_each_connected()
* fixed p2p_is_connected()
* made p2p_get_connected() return p2p_ids even with `$direction = 'any'`
* made compatible with [Proper Network Activation](http://wordpress.org/extend/plugins/proper-network-activation)
* [more info](http://scribu.net/wordpress/posts-to-posts/version-0-6.html)
= 0.5.1 =
* fixed fatal error on Menus screen
= 0.5 =
* added 'connected_meta' var to WP_Query
* attach p2p_id to each post found via WP_Query
* 'connected_to' => 'any' etc.
* $data parameter can also be a meta_query
* metabox bugfixes
* fixed l10n loading
* [more info](http://scribu.net/wordpress/posts-to-posts/p2p-0-5.html)
= 0.4 =
* introduced 'connected_from', 'connected_to', 'connected' vars to WP_Query
* replaced $reciprocal with $data as the third argument
* p2p_register_connection_type() accepts an associative array as arguments
* removed p2p_list_connected()
* added p2p_delete_connection()
* [more info](http://scribu.net/wordpress/posts-to-posts/p2p-0-4.html)
= 0.3 =
* store connections using a taxonomy instead of postmeta
* [more info](http://scribu.net/wordpress/posts-to-posts/p2p-0-3.html)
= 0.2 =
* UI that supports multiple related posts. props [Patrik Bón](http://www.mrhead.sk/)
* added p2p_list_connected() template tag
* [more info](http://scribu.net/wordpress/posts-to-posts/p2p-0-2.html)
= 0.1 =
* initial release
* [more info](http://scribu.net/wordpress/posts-to-posts/p2p-0-1.html)
@@ -0,0 +1,460 @@
<?php
/*
Creates an admin page
You must set $this->args and define the page_content() method
*/
abstract class scbAdminPage {
/** Page args
* $toplevel string If not empty, will create a new top level menu
* $icon string Path to an icon for the top level menu
* $parent string ( default: options-general.php )
* $capability string ( default: 'manage_options' )
* $page_title string ( mandatory )
* $menu_title string ( default: $page_title )
* $page_slug string ( default: sanitized $page_title )
* $nonce string ( default: $page_slug )
* $action_link string|bool Text of the action link on the Plugins page ( default: 'Settings' )
*/
protected $args;
// URL to the current plugin directory.
// Useful for adding css and js files
protected $plugin_url;
// Created at page init
protected $pagehook;
// scbOptions object holder
// Normally, it's used for storing formdata
protected $options;
protected $option_name;
// l10n
protected $textdomain;
// ____________REGISTRATION COMPONENT____________
private static $registered = array();
static function register( $class, $file, $options = null ) {
if ( isset( self::$registered[$class] ) )
return false;
self::$registered[$class] = array( $file, $options );
add_action( '_admin_menu', array( __CLASS__, '_pages_init' ) );
return true;
}
static function replace( $old_class, $new_class ) {
if ( ! isset( self::$registered[$old_class] ) )
return false;
self::$registered[$new_class] = self::$registered[$old_class];
unset( self::$registered[$old_class] );
return true;
}
static function remove( $class ) {
if ( ! isset( self::$registered[$class] ) )
return false;
unset( self::$registered[$class] );
return true;
}
static function _pages_init() {
foreach ( self::$registered as $class => $args )
new $class( $args[0], $args[1] );
}
// ____________MAIN METHODS____________
// Constructor
function __construct( $file, $options = NULL ) {
if ( is_a( $options, 'scbOptions' ) )
$this->options = $options;
$this->file = $file;
$this->plugin_url = plugin_dir_url( $file );
$this->setup();
$this->check_args();
if ( isset( $this->option_name ) ) {
add_action( 'admin_init', array( $this, 'option_init' ) );
if ( function_exists( 'settings_errors' ) )
add_action( 'admin_notices', 'settings_errors' );
}
add_action( 'admin_menu', array( $this, 'page_init' ) );
add_filter( 'contextual_help', array( $this, '_contextual_help' ), 10, 2 );
if ( $this->args['action_link'] )
add_filter( 'plugin_action_links_' . plugin_basename( $file ), array( $this, '_action_link' ) );
}
// This is where all the page args can be set
function setup(){}
// This is where the css and js go
// Both wp_enqueue_*() and inline code can be added
function page_head(){}
// This is where the contextual help goes
// @return string
function page_help(){}
// A generic page header
function page_header() {
echo "<div class='wrap'>\n";
screen_icon();
echo "<h2>" . $this->args['page_title'] . "</h2>\n";
}
// This is where the page content goes
abstract function page_content();
// A generic page footer
function page_footer() {
echo "</div>\n";
}
// This is where the form data should be validated
function validate( $new_data, $old_data ) {
return $new_data;
}
// Manually handle option saving ( use Settings API instead )
function form_handler() {
if ( empty( $_POST['action'] ) )
return false;
check_admin_referer( $this->nonce );
if ( !isset($this->options) ) {
trigger_error('options handler not set', E_USER_WARNING);
return false;
}
$new_data = scbUtil::array_extract( $_POST, array_keys( $this->options->get_defaults() ) );
$new_data = stripslashes_deep( $new_data );
$new_data = $this->validate( $new_data, $this->options->get() );
$this->options->set( $new_data );
$this->admin_msg();
}
// Manually generate a standard admin notice ( use Settings API instead )
function admin_msg( $msg = '', $class = "updated" ) {
if ( empty( $msg ) )
$msg = __( 'Settings <strong>saved</strong>.', $this->textdomain );
echo "<div class='$class fade'><p>$msg</p></div>\n";
}
// ____________UTILITIES____________
// Generates a form submit button
function submit_button( $value = '', $action = 'action', $class = "button" ) {
if ( is_array( $value ) ) {
extract( wp_parse_args( $value, array( 'value' => __( 'Save Changes', $this->textdomain ),
'action' => 'action',
'class' => 'button',
'ajax' => true ) ) );
if ( ! $ajax )
$class .= ' no-ajax';
}
else {
if ( empty( $value ) )
$value = __( 'Save Changes', $this->textdomain );
}
$input_args = array( 'type' => 'submit',
'names' => $action,
'values' => $value,
'extra' => '',
'desc' => false );
if ( ! empty( $class ) )
$input_args['extra'] = "class='{$class}'";
$output = "<p class='submit'>\n" . scbForms::input( $input_args ) . "</p>\n";
return $output;
}
/*
Mimics scbForms::form_wrap()
$this->form_wrap( $content ); // generates a form with a default submit button
$this->form_wrap( $content, false ); // generates a form with no submit button
// the second argument is sent to submit_button()
$this->form_wrap( $content, array( 'text' => 'Save changes',
'name' => 'action',
'ajax' => true,
) );
*/
function form_wrap( $content, $submit_button = true ) {
if ( is_array( $submit_button ) ) {
$content .= call_user_func( array( $this, 'submit_button' ), $submit_button );
} elseif ( true === $submit_button ) {
$content .= $this->submit_button();
} elseif ( false !== strpos( $submit_button, '<input' ) ) {
$content .= $submit_button;
} elseif ( false !== $submit_button ) {
$button_args = array_slice( func_get_args(), 1 );
$content .= call_user_func_array( array( $this, 'submit_button' ), $button_args );
}
return scbForms::form_wrap( $content, $this->nonce );
}
// See scbForms::form()
function form( $rows, $formdata = array() ) {
return scbForms::form( $rows, $formdata, $this->nonce );
}
// Generates a table wrapped in a form
function form_table( $rows, $formdata = array() ) {
$output = '';
foreach ( $rows as $row )
$output .= $this->table_row( $row, $formdata );
$output = $this->form_table_wrap( $output );
return $output;
}
// Wraps the given content in a <form><table>
function form_table_wrap( $content ) {
$output = $this->table_wrap( $content );
$output = $this->form_wrap( $output, $this->nonce );
return $output;
}
// Generates a form table
function table( $rows, $formdata = array() ) {
$output = '';
foreach ( $rows as $row )
$output .= $this->table_row( $row, $formdata );
$output = $this->table_wrap( $output );
return $output;
}
// Generates a table row
function table_row( $args, $formdata = array() ) {
return $this->row_wrap( $args['title'], $this->input( $args, $formdata ) );
}
// Wraps the given content in a <table>
function table_wrap( $content ) {
return
html( 'table class="form-table"', $content );
}
// Wraps the given content in a <tr><td>
function row_wrap( $title, $content ) {
return
html( 'tr',
html( 'th scope="row"', $title )
.html( 'td', $content ) );
}
function input( $args, $formdata = array() ) {
if ( empty( $formdata ) && isset( $this->options ) )
$formdata = $this->options->get();
if ( isset( $args['name_tree'] ) ) {
$tree = ( array ) $args['name_tree'];
unset( $args['name_tree'] );
$value = $formdata;
$name = $this->option_name;
foreach ( $tree as $key ) {
$value = $value[$key];
$name .= '[' . $key . ']';
}
$args['name'] = $name;
unset( $args['names'] );
unset( $args['values'] );
$formdata = array( $name => $value );
}
return scbForms::input( $args, $formdata );
}
// Mimic scbForms inheritance
function __call( $method, $args ) {
return call_user_func_array( array( 'scbForms', $method ), $args );
}
// Wraps a string in a <script> tag
function js_wrap( $string ) {
return "\n<script type='text/javascript'>\n" . $string . "\n</script>\n";
}
// Wraps a string in a <style> tag
function css_wrap( $string ) {
return "\n<style type='text/css'>\n" . $string . "\n</style>\n";
}
// ____________INTERNAL METHODS____________
// Registers a page
function page_init() {
extract( $this->args );
if ( ! $toplevel ) {
$this->pagehook = add_submenu_page( $parent, $page_title, $menu_title, $capability, $page_slug, array( $this, '_page_content_hook' ) );
} else {
$func = 'add_' . $toplevel . '_page';
$this->pagehook = $func( $page_title, $menu_title, $capability, $page_slug, array( $this, '_page_content_hook' ), $icon_url );
}
if ( ! $this->pagehook )
return;
if ( $ajax_submit ) {
$this->ajax_response();
add_action( 'admin_footer', array( $this, 'ajax_submit' ), 20 );
}
add_action( 'admin_print_styles-' . $this->pagehook, array( $this, 'page_head' ) );
}
function option_init() {
register_setting( $this->option_name, $this->option_name, array( $this, 'validate' ) );
}
private function check_args() {
if ( empty( $this->args['page_title'] ) )
trigger_error( 'Page title cannot be empty', E_USER_WARNING );
$this->args = wp_parse_args( $this->args, array(
'toplevel' => '',
'icon' => '',
'parent' => 'options-general.php',
'capability' => 'manage_options',
'menu_title' => $this->args['page_title'],
'page_slug' => '',
'nonce' => '',
'action_link' => __( 'Settings', $this->textdomain ),
'ajax_submit' => false,
) );
if ( empty( $this->args['page_slug'] ) )
$this->args['page_slug'] = sanitize_title_with_dashes( $this->args['menu_title'] );
if ( empty( $this->args['nonce'] ) )
$this->nonce = $this->args['page_slug'];
}
function _contextual_help( $help, $screen ) {
if ( is_object( $screen ) )
$screen = $screen->id;
$actual_help = $this->page_help();
if ( $screen == $this->pagehook && $actual_help )
return $actual_help;
return $help;
}
function ajax_response() {
if ( ! isset( $_POST['_ajax_submit'] ) || $_POST['_ajax_submit'] != $this->pagehook )
return;
$this->form_handler();
die;
}
function ajax_submit() {
global $page_hook;
if ( $page_hook != $this->pagehook )
return;
?>
<script type="text/javascript">
jQuery( document ).ready( function( $ ){
var $spinner = $( new Image() ).attr( 'src', '<?php echo admin_url( "images/wpspin_light.gif" ); ?>' );
$( ':submit' ).click( function( ev ){
var $submit = $( this );
var $form = $submit.parents( 'form' );
if ( $submit.hasClass( 'no-ajax' ) || $form.attr( 'method' ).toLowerCase() != 'post' )
return true;
var $this_spinner = $spinner.clone();
$submit.before( $this_spinner ).hide();
var data = $form.serializeArray();
data.push( {name: $submit.attr( 'name' ), value: $submit.val()} );
data.push( {name: '_ajax_submit', value: '<?php echo $this->pagehook; ?>'} );
$.post( location.href, data, function( response ){
var $prev = $( '.wrap > .updated, .wrap > .error' );
var $msg = $( response ).hide().insertAfter( $( '.wrap h2' ) );
if ( $prev.length > 0 )
$prev.fadeOut( 'slow', function(){ $msg.fadeIn( 'slow' ); } );
else
$msg.fadeIn( 'slow' );
$this_spinner.hide();
$submit.show();
} );
ev.stopPropagation();
ev.preventDefault();
} );
} );
</script>
<?php
}
function _page_content_hook() {
$this->form_handler();
$this->page_header();
$this->page_content();
$this->page_footer();
}
function _action_link( $links ) {
$url = add_query_arg( 'page', $this->args['page_slug'], admin_url( $this->args['parent'] ) );
$links[] = html_link( $url, $this->args['action_link'] );
return $links;
}
}
@@ -0,0 +1,246 @@
<?php
/*
Creates an admin page with widgets, similar to the dashboard
For example, if you defined the boxes like this:
$this->boxes = array( array( 'settings', 'Settings box', 'normal' )
... );
You must also define two methods in your class for each box:
function settings_box() - this is where the box content is echoed
function settings_handler() - this is where the box settings are saved
...
*/
abstract class scbBoxesPage extends scbAdminPage {
/*
A box definition looks like this:
array( $slug, $title, $column );
Available columns: normal, side, column3, column4
*/
protected $boxes = array();
function __construct( $file, $options = null ) {
parent::__construct( $file, $options );
// too late
scbUtil::add_uninstall_hook( $this->file, array( $this, 'uninstall' ) );
}
function page_init() {
if ( !isset( $this->args['columns'] ) )
$this->args['columns'] = 2;
parent::page_init();
add_action( 'load-' . $this->pagehook, array( $this, 'boxes_init' ) );
add_filter( 'screen_layout_columns', array( $this, 'columns' ) );
}
function default_css() {
?>
<style type="text/css">
.postbox-container + .postbox-container {
margin-left: 18px;
}
.postbox-container {
padding-right: 0;
}
.inside {
clear: both;
overflow: hidden;
padding: 10px 10px 0 !important;
}
.inside table {
margin: 0 !important;
padding: 0 !important;
}
.inside table td {
vertical-align: middle !important;
}
.inside table .regular-text {
width: 100% !important;
}
.inside .form-table th {
width: 30%;
max-width: 200px;
padding: 10px 0 !important;
}
.inside .widefat .check-column {
padding-bottom: 7px !important;
}
.inside p,
.inside table {
margin: 0 0 10px !important;
}
.inside p.submit {
float: left !important;
padding: 0 !important;
}
</style>
<?php
}
function page_content() {
$this->default_css();
global $screen_layout_columns;
if ( isset( $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;';
}
}
?>
<div id='<?php echo $this->pagehook ?>-widgets' class='metabox-holder'>
<?php
echo "\t<div class='postbox-container' style='$width'>\n";
do_meta_boxes( $this->pagehook, 'normal', '' );
echo "\t</div><div class='postbox-container' style='{$hide2}$width'>\n";
do_meta_boxes( $this->pagehook, 'side', '' );
echo "\t</div><div class='postbox-container' style='{$hide3}$width'>\n";
do_meta_boxes( $this->pagehook, 'column3', '' );
echo "\t</div><div class='postbox-container' style='{$hide4}$width'>\n";
do_meta_boxes( $this->pagehook, 'column4', '' );
?>
</div></div>
<?php
}
function page_footer() {
parent::page_footer();
$this->_boxes_js_init();
}
function form_handler() {
if ( empty( $_POST ) )
return;
check_admin_referer( $this->nonce );
// Box handler
foreach ( $this->boxes as $box ) {
$args = isset( $box[4] ) ? $box[4] : array();
$handler = $box[0] . '_handler';
if ( method_exists( $this, $handler ) )
call_user_func_array( array( $this, $handler ), $args );
}
}
function columns( $columns ) {
$columns[$this->pagehook] = $this->args['columns'];
return $columns;
}
function uninstall() {
global $wpdb;
$hook = str_replace( '-', '', $this->pagehook );
foreach ( array( 'metaboxhidden', 'closedpostboxes', 'wp_metaboxorder', 'screen_layout' ) as $option )
$keys[] = "'{$option}_{$hook}'";
$keys = '( ' . implode( ', ', $keys ) . ' )';
$wpdb->query( "
DELETE FROM {$wpdb->usermeta}
WHERE meta_key IN {$keys}
" );
}
function boxes_init() {
wp_enqueue_script( 'common' );
wp_enqueue_script( 'wp-lists' );
wp_enqueue_script( 'postbox' );
$registered = array();
foreach( $this->boxes as $box_args ) {
@list( $name, $title, $context, $priority, $args ) = $box_args;
if ( empty( $title ) )
$title = ucfirst( $name );
if ( empty( $context ) )
$context = 'normal';
if ( empty( $priority ) )
$priority = 'default';
if ( empty( $args ) )
$args = array();
if ( isset( $registered[$name] ) ) {
if ( empty( $args ) )
trigger_error( "Duplicate box name: $name", E_USER_NOTICE );
$name = $this->_increment( $name );
} else {
$registered[$name] = true;
}
add_meta_box( $name, $title, array( $this, '_intermediate_callback' ), $this->pagehook, $context, $priority, $args );
}
}
// Make it so that $args is actually what's passed to the callback
function _intermediate_callback( $_, $box ) {
list( $name ) = explode( '-', $box['id'] );
call_user_func_array( array( $this, $name . '_box' ), $box['args'] );
}
private function _increment( $name ) {
$parts = explode( '-', $name );
if ( isset( $parts[1] ) )
$parts[1]++;
else
$parts[1] = 2;
return implode( '-', $parts );
}
// Adds necesary code for JS to work
function _boxes_js_init() {
echo $this->js_wrap( <<<EOT
jQuery( document ).ready( function( $ ){
// close postboxes that should be closed
$( '.if-js-closed' ).removeClass( 'if-js-closed' ).addClass( 'closed' );
// postboxes setup
postboxes.add_postbox_toggles( '$this->pagehook' );
} );
EOT
);
?>
<form style='display: none' method='get' action=''>
<p>
<?php
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
?>
</p>
</form>
<?php
}
}
@@ -0,0 +1,168 @@
<?php
class scbCron {
protected $schedule;
protected $interval;
protected $time;
protected $hook;
protected $callback_args;
/**
* Create a new cron job
*
* @param string Reference to main plugin file
* @param array List of args:
string $action OR callback $callback
string $schedule OR number $interval
array $callback_args ( optional )
*/
function __construct( $file, $args ) {
extract( $args, EXTR_SKIP );
// Set time & schedule
if ( isset( $time ) )
$this->time = $time;
if ( isset( $interval ) ) {
$this->schedule = $interval . 'secs';
$this->interval = $interval;
} elseif ( isset( $schedule ) ) {
$this->schedule = $schedule;
}
// Set hook
if ( isset( $action ) ) {
$this->hook = $action;
} elseif ( isset( $callback ) ) {
$this->hook = self::_callback_to_string( $callback );
add_action( $this->hook, $callback );
} elseif ( method_exists( $this, 'callback' ) ) {
$this->hook = self::_callback_to_string( array( $this, 'callback' ) );
add_action( $this->hook, $callback );
} else {
trigger_error( '$action OR $callback not set', E_USER_WARNING );
}
if ( isset( $callback_args ) )
$this->callback_args = ( array ) $callback_args;
if ( $this->schedule ) {
scbUtil::add_activation_hook( $file, array( $this, 'reset' ) );
register_deactivation_hook( $file, array( $this, 'unschedule' ) );
}
add_filter( 'cron_schedules', array( $this, '_add_timing' ) );
}
/* Change the interval of the cron job
*
* @param array List of args:
string $schedule OR number $interval
timestamp $time ( optional )
*/
function reschedule( $args ) {
extract( $args );
if ( $schedule && $this->schedule != $schedule ) {
$this->schedule = $schedule;
} elseif ( $interval && $this->interval != $interval ) {
$this->schedule = $interval . 'secs';
$this->interval = $interval;
}
$this->time = $time;
$this->reset();
}
/**
* Reset the schedule
*/
function reset() {
$this->unschedule();
$this->schedule();
}
/**
* Clear the cron job
*/
function unschedule() {
# wp_clear_scheduled_hook( $this->hook, $this->callback_args );
self::really_clear_scheduled_hook( $this->hook );
}
/**
* Execute the job now
* @param array $args List of arguments to pass to the callback
*/
function do_now( $args = null ) {
if ( is_null( $args ) )
$args = $this->callback_args;
do_action_ref_array( $this->hook, $args );
}
/**
* Execute the job with a given delay
* @param int $delay in seconds
* @param array $args List of arguments to pass to the callback
*/
function do_once( $delay = 0, $args = null ) {
if ( is_null( $args ) )
$args = $this->callback_args;
wp_clear_scheduled_hook( $this->hook, $args );
wp_schedule_single_event( time() + $delay, $this->hook, $args );
}
//_____INTERNAL METHODS_____
function _add_timing( $schedules ) {
if ( isset( $schedules[$this->schedule] ) )
return $schedules;
$schedules[$this->schedule] = array( 'interval' => $this->interval,
'display' => $this->interval . ' seconds' );
return $schedules;
}
protected function schedule() {
if ( ! $this->time )
$this->time = time();
wp_schedule_event( $this->time, $this->schedule, $this->hook, $this->callback_args );
}
protected static function really_clear_scheduled_hook( $name ) {
$crons = _get_cron_array();
foreach ( $crons as $timestamp => $hooks ) {
foreach ( $hooks as $hook => $args )
if ( $hook == $name )
unset( $crons[$timestamp][$hook] );
if ( empty( $hooks ) )
unset( $crons[$timestamp] );
}
_set_cron_array( $crons );
}
protected static function _callback_to_string( $callback ) {
if ( ! is_array( $callback ) )
$str = $callback;
elseif ( ! is_string( $callback[0] ) )
$str = get_class( $callback[0] ) . '_' . $callback[1];
else
$str = $callback[0] . '::' . $callback[1];
$str .= '_hook';
return $str;
}
}
@@ -0,0 +1,427 @@
<?php
// Documentation: http://scribu.net/wordpress/scb-framework/scb-forms.html
class scbForms {
const token = '%input%';
protected static $args;
protected static $formdata = array();
static function input( $args, $formdata = array() ) {
$args = self::validate_data( $args );
$error = false;
foreach ( array( 'name', 'value' ) as $key ) {
$old = $key . 's';
if ( isset( $args[$old] ) ) {
$args[$key] = $args[$old];
unset( $args[$old] );
}
}
if ( empty( $args['name'] ) )
return trigger_error( 'Empty name', E_USER_WARNING );
self::$args = $args;
self::$formdata = self::validate_data( $formdata );
if ( 'select' == $args['type'] )
return self::_select();
else
return self::_input();
}
// ____________UTILITIES____________
// Generates a table wrapped in a form
static function form_table( $rows, $formdata = NULL ) {
$output = '';
foreach ( $rows as $row )
$output .= self::table_row( $row, $formdata );
$output = self::form_table_wrap( $output );
return $output;
}
// Generates a form
static function form( $inputs, $formdata = NULL, $nonce ) {
$output = '';
foreach ( $inputs as $input )
$output .= self::input( $input, $formdata );
$output = self::form_wrap( $output, $nonce );
return $output;
}
// Generates a table
static function table( $rows, $formdata = NULL ) {
$output = '';
foreach ( $rows as $row )
$output .= self::table_row( $row, $formdata );
$output = self::table_wrap( $output );
return $output;
}
// Generates a table row
static function table_row( $args, $formdata = NULL ) {
return self::row_wrap( $args['title'], self::input( $args, $formdata ) );
}
// ____________WRAPPERS____________
// Wraps the given content in a <form><table>
static function form_table_wrap( $content, $nonce = 'update_options' ) {
$output = self::table_wrap( $content );
$output = self::form_wrap( $output, $nonce );
return $output;
}
// Wraps the given content in a <form> tag
static function form_wrap( $content, $nonce = 'update_options' ) {
$output = "\n<form method='post' action=''>\n";
$output .= $content;
$output .= wp_nonce_field( $action = $nonce, $name = "_wpnonce", $referer = true , $echo = false );
$output .= "\n</form>\n";
return $output;
}
// Wraps the given content in a <table>
static function table_wrap( $content ) {
$output = "\n<table class='form-table'>\n" . $content . "\n</table>\n";
return $output;
}
// Wraps the given content in a <tr><td>
static function row_wrap( $title, $content ) {
return "\n<tr>\n\t<th scope='row'>" . $title . "</th>\n\t<td>\n\t\t" . $content . "\t</td>\n\n</tr>";
}
// ____________PRIVATE METHODS____________
// Recursivly transform empty arrays to ''
private static function validate_data( $data ) {
if ( !is_array( $data ) )
return $data;
if ( empty( $data ) )
return '';
foreach ( $data as $key => &$value )
$value = self::validate_data( $value );
return $data;
}
// From multiple inputs to single inputs
private static function _input() {
extract( wp_parse_args( self::$args, array(
'name' => NULL,
'value' => NULL,
'desc' => NULL,
'checked' => NULL,
) ) );
$m_name = is_array( $name );
$m_value = is_array( $value );
$m_desc = is_array( $desc );
// Correct name
if ( !$m_name && $m_value
&& 'checkbox' == $type
&& false === strpos( $name, '[' )
)
$args['name'] = $name = $name . '[]';
// Expand names or values
if ( !$m_name && !$m_value ) {
$a = array( $name => $value );
}
elseif ( $m_name && !$m_value ) {
$a = array_fill_keys( $name, $value );
}
elseif ( !$m_name && $m_value ) {
$a = array_fill_keys( $value, $name );
}
else {
$a = array_combine( $name, $value );
}
// Correct descriptions
$_after = '';
if ( isset( $desc ) && !$m_desc && false === strpos( $desc, self::token ) ) {
if ( $m_value ) {
$_after = $desc;
$args['desc'] = $desc = $value;
}
elseif ( $m_name ) {
$_after = $desc;
$args['desc'] = $desc = $name;
}
}
// Determine what goes where
if ( !$m_name && $m_value ) {
$i1 = 'val';
$i2 = 'name';
} else {
$i1 = 'name';
$i2 = 'val';
}
$func = in_array( $type, array( 'checkbox', 'radio' ) ) ? '_checkbox_single' : '_input_single';
// Set constant args
$const_args = self::array_extract( self::$args, array( 'type', 'desc_pos', 'checked' ) );
if ( isset( $extra ) ) {
if ( !is_array( $extra ) )
$extra = self::attr_to_array( $extra );
$const_args['extra'] = $extra;
}
$i = 0;
foreach ( $a as $name => $val ) {
$cur_args = $const_args;
if ( $$i1 !== NULL )
$cur_args['name'] = $$i1;
if ( $$i2 !== NULL )
$cur_args['value'] = $$i2;
// Set desc
if ( is_array( $desc ) )
$cur_args['desc'] = $desc[$i];
elseif ( isset( $desc ) )
$cur_args['desc'] = $desc;
// Find relevant formdata
$match = NULL;
if ( $checked === NULL ) {
$key = str_replace( '[]', '', $$i1 );
if ( isset( self::$formdata[ $key ] ) ) {
$match = self::$formdata[ $key ];
if ( is_array( $match ) ) {
$match = $match[$i];
}
}
} else if ( is_array( $checked ) ) {
$cur_args['checked'] = isset( $checked[$i] ) && $checked[$i];
}
$output[] = self::$func( $cur_args, $match );
$i++;
}
return implode( "\n", $output ) . $_after;
}
// Handle args for checkboxes and radio inputs
private static function _checkbox_single( $args, $data ) {
$args = wp_parse_args( $args, array(
'name' => NULL,
'value' => true,
'desc_pos' => 'after',
'desc' => NULL,
'checked' => NULL,
'extra' => array(),
) );
foreach ( $args as $key => &$val )
$$key = &$val;
unset( $val );
if ( $checked === NULL && $value == $data )
$checked = true;
if ( $checked )
$extra['checked'] = 'checked';
if ( is_null( $desc ) && !is_bool( $value ) )
$desc = str_replace( '[]', '', $value );
return self::_input_gen( $args );
}
// Handle args for text inputs
private static function _input_single( $args, $data ) {
$args = wp_parse_args( $args, array(
'value' => $data,
'desc_pos' => 'after',
'extra' => array( 'class' => 'regular-text' ),
) );
foreach ( $args as $key => &$val )
$$key = &$val;
unset( $val );
if ( FALSE === strpos( $name, '[' ) )
$extra['id'] = $name;
return self::_input_gen( $args );
}
// Generate html with the final args
private static function _input_gen( $args ) {
extract( wp_parse_args( $args, array(
'name' => NULL,
'value' => NULL,
'desc' => NULL,
'extra' => array()
) ) );
$extra = self::array_to_attr( $extra );
if ( 'textarea' == $type ) {
$value = esc_html( $value );
$input = "<textarea name='{$name}'{$extra}>{$value}</textarea>\n";
}
else {
$value = esc_attr( $value );
$input = "<input name='{$name}' value='{$value}' type='{$type}'{$extra} /> ";
}
return self::add_label( $input, $desc, $desc_pos );
}
private static function _select() {
extract( wp_parse_args( self::$args, array(
'name' => '',
'value' => array(),
'text' => '',
'selected' => array( 'foo' ), // hack to make default blank
'extra' => array(),
'numeric' => false, // use numeric array instead of associative
'desc' => '',
'desc_pos' => '',
) ), EXTR_SKIP );
if ( empty( $value ) )
$value = array( '' => '' );
if ( !is_array( $value ) )
return trigger_error( "'value' argument is expected to be an array", E_USER_WARNING );
if ( !self::is_associative( $value ) && !$numeric )
$value = array_combine( $value, $value );
if ( isset( self::$formdata[$name] ) )
$cur_val = self::$formdata[$name];
else
$cur_val = $selected;
if ( false === $text ) {
$opts = '';
} else {
$opts = "\t<option value=''" . selected( $cur_val, array( 'foo' ), false ) . ">{$text}</option>\n";
}
foreach ( $value as $key => $value ) {
if ( empty( $key ) || empty( $value ) )
continue;
$opts .= "\t<option value='{$key}'" . selected( (string) $key, (string) $cur_val, false) . '>' . $value . "</option>\n";
}
if ( !is_array( $extra ) )
$extra = self::attr_to_array( $extra );
$extra = self::array_to_attr( $extra );
$input = "<select name='{$name}'$extra>\n{$opts}</select>";
return self::add_label( $input, $desc, $desc_pos );
}
private static function add_label( $input, $desc, $desc_pos ) {
if ( empty( $desc_pos ) )
$desc_pos = 'after';
$label = '';
if ( false === strpos( $desc, self::token ) ) {
switch ( $desc_pos ) {
case 'before': $label = $desc . ' ' . self::token; break;
case 'after': $label = self::token . ' ' . $desc;
}
} else {
$label = $desc;
}
$label = trim( str_replace( self::token, $input, $label ) );
if ( empty( $desc ) )
$output = $input . "\n";
else
$output = "<label>{$label}</label>\n";
return $output;
}
// Utilities
private static function attr_to_array( $html ) {
return shortcode_parse_atts( $html );
}
private static function array_to_attr( $attr ) {
$attr = array_filter( (array) $attr );
$out = '';
foreach ( $attr as $key => $value )
$out .= ' ' . $key . '=' . '"' . esc_attr( $value ) . '"';
return $out;
}
private static function is_associative( $array ) {
if ( !is_array( $array ) || empty( $array ) )
return false;
$keys = array_keys( $array );
return array_keys( $keys ) !== $keys;
}
private static function array_extract( $array, $keys ) {
$r = array();
foreach ( $keys as $key )
if ( isset( $array[$key] ) )
$r[$key] = $array[$key];
return $r;
}
}
// PHP < 5.2
if ( !function_exists( 'array_fill_keys' ) ) :
function array_fill_keys( $keys, $value ) {
if ( !is_array( $keys ) )
trigger_error( 'First argument is expected to be an array.' . gettype( $keys ) . 'given', E_USER_WARNING );
$r = array();
foreach ( $keys as $key )
$r[$key] = $value;
return $r;
}
endif;
@@ -0,0 +1,172 @@
<?php
// Documentation: http://scribu.net/wordpress/scb-framework/scb-options.html
class scbOptions {
protected $key; // the option name
protected $defaults; // the default value( s )
public $wp_filter_id; // used by WP hooks
/**
* Create a new set of options
*
* @param string $key Option name
* @param string $file Reference to main plugin file
* @param array $defaults An associative array of default values ( optional )
*/
public function __construct( $key, $file, $defaults = '' ) {
$this->key = $key;
$this->defaults = $defaults;
scbUtil::add_activation_hook( $file, array( $this, '_update_reset' ) );
scbUtil::add_uninstall_hook( $file, array( $this, 'delete' ) );
}
/**
* Get option name
*/
public function get_key() {
return $this->key;
}
/**
* Get option values for one, many or all fields
*
* @param string|array $field The field( s ) to get
* @return mixed Whatever is in those fields
*/
public function get( $field = '' ) {
$data = get_option( $this->key );
if ( is_array( $this->defaults ) )
$data = ( array ) $data;
return $this->_get( $field, $data );
}
/**
* Get default values for one, many or all fields
*
* @param string|array $field The field( s ) to get
* @return mixed Whatever is in those fields
*/
public function get_defaults( $field = '' ) {
return $this->_get( $field, $this->defaults );
}
/**
* Set all data fields, certain fields or a single field
*
* @param string|array $field The field to update or an associative array
* @param mixed $value The new value ( ignored if $field is array )
* @return null
*/
public function set( $field, $value = '' ) {
if ( is_array( $field ) )
$newdata = $field;
else
$newdata = array( $field => $value );
$this->update( array_merge( $this->get(), $newdata ) );
}
/**
* Reset option to defaults
*
* @return null
*/
public function reset() {
$this->update( $this->defaults, false );
}
/**
* Remove any keys that are not in the defaults array
*
* @return bool
*/
public function cleanup() {
$this->update( $this->_clean( $this->get() ) );
}
/**
* Update raw data
*
* @param mixed $newdata
* @param bool $clean wether to remove unrecognized keys or not
* @return null
*/
public function update( $newdata, $clean = true ) {
if ( $clean )
$newdata = $this->_clean( $newdata );
update_option( $this->key, $newdata );
}
/**
* Delete the option
*
* @return null
*/
public function delete() {
delete_option( $this->key );
}
//_____INTERNAL METHODS_____
// Add new fields with their default values
function _update_reset() {
if ( is_array( $this->defaults ) )
$this->update( array_merge( $this->defaults, $this->get() ) );
else
add_option( $this->key, $this->defaults );
}
private function _clean( $data ) {
if ( !is_array( $data ) || !is_array( $this->defaults ) )
return $data;
$r = array();
foreach ( array_keys( $this->defaults ) as $key )
$r[$key] = @$data[$key];
return $r;
}
// Get one, more or all fields from an array
private function &_get( $field, $data ) {
if ( empty( $field ) )
return $data;
if ( is_string( $field ) )
return $data[$field];
foreach ( $field as $key )
if ( isset( $data[$key] ) )
$result[] = $data[$key];
return $result;
}
// Magic method: $options->field
function __get( $field ) {
return $this->get( $field );
}
// Magic method: $options->field = $value
function __set( $field, $value ) {
$this->set( $field, $value );
}
// Magic method: isset( $options->field )
function __isset( $field ) {
$data = $this->get();
return isset( $data[$field] );
}
}
@@ -0,0 +1,93 @@
<?php
class scbQueryManipulation {
private $bits = array();
private $wp_query;
private static $filters = array(
'posts_where',
'posts_join',
'posts_groupby',
'posts_orderby',
'posts_distinct',
'post_limits',
'posts_fields'
);
public function __construct( $callback, $once = true ) {
global $wp_version;
if ( version_compare( $wp_version, '3.1-alpha', '>=' ) ) {
if ( !$once ) {
add_filter( 'posts_clauses', $callback, 10, 2 );
return;
}
}
$this->callback = $callback;
$this->enable();
if ( $once )
add_filter( 'posts_request', array( $this, '_disable' ) );
}
function _disable( $request ) {
remove_filter( 'posts_request', array( $this, '_disable' ) );
$this->disable();
return $request;
}
public function enable() {
foreach ( self::$filters as $filter ) {
add_filter( $filter, array( $this, 'collect' ), 999, 2 );
add_filter( $filter . '_request' , array( $this, 'update' ), 9 );
}
add_action( 'posts_selection' , array( $this, 'alter' ) );
}
public function disable() {
foreach ( self::$filters as $filter ) {
remove_filter( $filter, array( $this, 'collect' ), 999, 2 );
remove_filter( $filter . '_request' , array( $this, 'update' ), 9 );
}
remove_action( 'posts_selection' , array( $this, 'alter' ) );
}
function collect( $value, $wp_query ) {
// remove 'posts_'
$key = explode( '_', current_filter() );
$key = array_slice( $key, 1 );
$key = implode( '_', $key );
$this->bits[ $key ] = $value;
$this->wp_query = $wp_query;
return $value;
}
function alter( $query ) {
// suppress_filters => true
if ( is_null( $this->wp_query ) ) {
return;
}
$this->bits = call_user_func( $this->callback, $this->bits, $this->wp_query );
}
function update( $value ) {
// remove 'posts_' and '_request'
$key = explode( '_', current_filter() );
$key = array_slice( $key, 1, -1 );
$key = implode( '_', $key );
return $this->bits[ $key ];
}
}
@@ -0,0 +1,52 @@
<?php
// Takes care of creating, updating and deleting database tables
class scbTable {
protected $name;
protected $columns;
protected $upgrade_method;
function __construct( $name, $file, $columns, $upgrade_method = 'dbDelta' ) {
global $wpdb;
$this->name = $wpdb->prefix . $name;
$this->columns = $columns;
$this->upgrade_method = $upgrade_method;
$wpdb->tables[] = $name;
$wpdb->$name = $this->name;
scbUtil::add_activation_hook( $file, array( $this, 'install' ) );
scbUtil::add_uninstall_hook( $file, array( $this, 'uninstall' ) );
}
function install() {
global $wpdb;
$charset_collate = '';
if ( $wpdb->has_cap( 'collation' ) ) {
if ( ! empty( $wpdb->charset ) )
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty( $wpdb->collate ) )
$charset_collate .= " COLLATE $wpdb->collate";
}
if ( 'dbDelta' == $this->upgrade_method ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( "CREATE TABLE $this->name ( $this->columns ) $charset_collate" );
return;
}
if ( 'delete_first' == $this->upgrade_method )
$wpdb->query( "DROP TABLE IF EXISTS $this->name;" );
$wpdb->query( "CREATE TABLE IF NOT EXISTS $this->name ( $this->columns ) $charset_collate;" );
}
function uninstall() {
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS $this->name" );
}
}
@@ -0,0 +1,176 @@
<?php
class scbUtil {
// Force script enqueue
static function do_scripts( $handles ) {
global $wp_scripts;
if ( ! is_a( $wp_scripts, 'WP_Scripts' ) )
$wp_scripts = new WP_Scripts();
$wp_scripts->do_items( ( array ) $handles );
}
// Force style enqueue
static function do_styles( $handles ) {
self::do_scripts( 'jquery' );
global $wp_styles;
if ( ! is_a( $wp_styles, 'WP_Styles' ) )
$wp_styles = new WP_Styles();
ob_start();
$wp_styles->do_items( ( array ) $handles );
$content = str_replace( array( '"', "\n" ), array( "'", '' ), ob_get_clean() );
echo "<script type='text/javascript'>\n";
echo "jQuery( document ).ready( function( $ ) {\n";
echo "$( 'head' ).prepend( \"$content\" );\n";
echo "} );\n";
echo "</script>";
}
// Enable delayed activation ( to be used with scb_init() )
static function add_activation_hook( $plugin, $callback ) {
add_action( 'scb_activation_' . plugin_basename( $plugin ), $callback );
}
// Have more than one uninstall hooks; also prevents an UPDATE query on each page load
static function add_uninstall_hook( $plugin, $callback ) {
register_uninstall_hook( $plugin, '__return_false' ); // dummy
add_action( 'uninstall_' . plugin_basename( $plugin ), $callback );
}
// Apply a function to each element of a ( nested ) array recursively
static function array_map_recursive( $callback, $array ) {
array_walk_recursive( $array, array( __CLASS__, 'array_map_recursive_helper' ), $callback );
return $array;
}
static function array_map_recursive_helper( &$val, $key, $callback ) {
$val = call_user_func( $callback, $val );
}
// Extract certain $keys from $array
static function array_extract( $array, $keys ) {
$r = array();
foreach ( $keys as $key )
if ( array_key_exists( $key, $array ) )
$r[$key] = $array[$key];
return $r;
}
// Extract a certain value from a list of arrays
static function array_pluck( $array, $key ) {
$r = array();
foreach ( $array as $value ) {
if ( is_object( $value ) )
$value = get_object_vars( $value );
if ( array_key_exists( $key, $value ) )
$r[] = $value[$key];
}
return $r;
}
// Transform a list of objects into an associative array
static function objects_to_assoc( $objects, $key, $value ) {
$r = array();
foreach ( $objects as $obj )
$r[$obj->$key] = $obj->$value;
return $r;
}
// Prepare an array for an IN statement
static function array_to_sql( $values ) {
foreach ( $values as &$val )
$val = "'" . esc_sql( trim( $val ) ) . "'";
return implode( ',', $values );
}
// Example: split_at( '</', '<a></a>' ) => array( '<a>', '</a>' )
static function split_at( $delim, $str ) {
$i = strpos( $str, $delim );
if ( false === $i )
return false;
$start = substr( $str, 0, $i );
$finish = substr( $str, $i );
return array( $start, $finish );
}
}
//_____Minimalist HTML framework_____
/*
* Examples:
*
* html( 'p', 'Hello world!' ); <p>Hello world!</p>
* html( 'a', array( 'href' => 'http://example.com' ), 'A link' ); <a href="http://example.com">A link</a>
* html( 'img', array( 'src' => 'http://example.com/f.jpg' ) ); <img src="http://example.com/f.jpg" />
* html( 'ul', html( 'li', 'a' ), html( 'li', 'b' ) ); <ul><li>a</li><li>b</li></ul>
*/
if ( ! function_exists( 'html' ) ):
function html( $tag ) {
$args = func_get_args();
$tag = array_shift( $args );
if ( is_array( $args[0] ) ) {
$closing = $tag;
$attributes = array_shift( $args );
foreach ( $attributes as $key => $value ) {
$tag .= ' ' . $key . '="' . htmlspecialchars( $value, ENT_QUOTES ) . '"';
}
} else {
list( $closing ) = explode( ' ', $tag, 2 );
}
if ( in_array( $closing, array( 'area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta' ) ) ) {
return "<{$tag} />";
}
$content = implode( '', $args );
return "<{$tag}>{$content}</{$closing}>";
}
endif;
// Generate an <a> tag
if ( ! function_exists( 'html_link' ) ):
function html_link( $url, $title = '' ) {
if ( empty( $title ) )
$title = $url;
return sprintf( "<a href='%s'>%s</a>", esc_url( $url ), $title );
}
endif;
//_____Compatibility layer_____
// WP < ?
if ( ! function_exists( 'set_post_field' ) ) :
function set_post_field( $field, $value, $post_id ) {
global $wpdb;
$post_id = absint( $post_id );
$value = sanitize_post_field( $field, $value, $post_id, 'db' );
return $wpdb->update( $wpdb->posts, array( $field => $value ), array( 'ID' => $post_id ) );
}
endif;
@@ -0,0 +1,89 @@
<?php
// Adds compatibility methods between WP_Widget and scbForms
abstract class scbWidget extends WP_Widget {
protected $defaults = array();
private static $scb_widgets = array();
static function init( $class, $file = '', $base = '' ) {
self::$scb_widgets[] = $class;
add_action( 'widgets_init', array( __CLASS__, '_scb_register' ) );
// for auto-uninstall
if ( $file && $base && class_exists( 'scbOptions' ) )
new scbOptions( "widget_$base", $file );
}
static function _scb_register() {
foreach ( self::$scb_widgets as $widget )
register_widget( $widget );
}
// A pre-filled method, for convenience
function widget( $args, $instance ) {
$instance = wp_parse_args( $instance, $this->defaults );
extract( $args );
echo $before_widget;
$title = apply_filters( 'widget_title', isset( $instance['title'] ) ? $instance['title'] : '', $instance, $this->id_base );
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
$this->content( $instance );
echo $after_widget;
}
// This is where the actual widget content goes
function content( $instance ) {}
//_____HELPER METHODS_____
// See scbForms::input()
// Allows extra parameter $args['title']
protected function input( $args, $formdata = array() ) {
// Add default class
if ( !isset( $args['extra'] ) )
$args['extra'] = 'class="regular-text"';
// Add default label position
if ( !in_array( $args['type'], array( 'checkbox', 'radio' ) ) && empty( $args['desc_pos'] ) )
$args['desc_pos'] = 'before';
// Then add prefix to names and formdata
$new_formdata = array();
foreach ( ( array ) $args['name'] as $name )
$new_formdata[$this->scb_get_field_name( $name )] = @$formdata[$name];
$new_names = array_keys( $new_formdata );
// Finally, replace the old names
if ( 1 == count( $new_names ) )
$args['name'] = $new_names[0];
else
$args['name'] = $new_names;
return scbForms::input( $args, $new_formdata );
}
//_____INTERNAL METHODS_____
private function scb_get_field_name( $name ) {
if ( $split = scbUtil::split_at( '[', $name ) )
list( $basename, $extra ) = $split;
else
return $this->get_field_name( $name );
return str_replace( '[]', '', $this->get_field_name( $basename ) ) . $extra;
}
}
@@ -0,0 +1,86 @@
<?php
$GLOBALS['_scb_data'] = array( 30, __FILE__, array(
'scbUtil', 'scbOptions', 'scbForms', 'scbTable',
'scbWidget', 'scbAdminPage', 'scbBoxesPage',
'scbQueryManipulation', 'scbCron',
) );
if ( !class_exists( 'scbLoad4' ) ) :
class scbLoad4 {
private static $candidates;
private static $classes;
private static $callbacks = array();
private static $loaded;
static function init( $callback = '' ) {
list( $rev, $file, $classes ) = $GLOBALS['_scb_data'];
self::$candidates[$file] = $rev;
self::$classes[$file] = $classes;
if ( !empty( $callback ) ) {
self::$callbacks[$file] = $callback;
add_action( 'activate_plugin', array( __CLASS__, 'delayed_activation' ) );
}
// TODO: don't load when activating a plugin ?
add_action( 'plugins_loaded', array( __CLASS__, 'load' ), 9, 0 );
}
static function delayed_activation( $plugin ) {
$plugin_dir = dirname( $plugin );
if ( '.' == $plugin_dir )
return;
foreach ( self::$callbacks as $file => $callback ) {
if ( dirname( dirname( plugin_basename( $file ) ) ) == $plugin_dir ) {
self::load( false );
call_user_func( $callback );
do_action( 'scb_activation_' . $plugin );
break;
}
}
}
static function load( $do_callbacks = true ) {
arsort( self::$candidates );
$file = key( self::$candidates );
$path = dirname( $file ) . '/';
foreach ( self::$classes[$file] as $class_name ) {
if ( class_exists( $class_name ) )
continue;
$fpath = $path . substr( $class_name, 3 ) . '.php';
if ( file_exists( $fpath ) ) {
include $fpath;
self::$loaded[] = $fpath;
}
}
if ( $do_callbacks )
foreach ( self::$callbacks as $callback )
call_user_func( $callback );
}
static function get_info() {
arsort( self::$candidates );
return array( self::$loaded, self::$candidates );
}
}
endif;
if ( !function_exists( 'scb_init' ) ) :
function scb_init( $callback = '' ) {
scbLoad4::init( $callback );
}
endif;
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

@@ -0,0 +1,282 @@
<?php
class P2P_Connections {
function init( $file ) {
$table = new scbTable( 'p2p', $file, "
p2p_id bigint(20) unsigned NOT NULL auto_increment,
p2p_from bigint(20) unsigned NOT NULL,
p2p_to bigint(20) unsigned NOT NULL,
PRIMARY KEY (p2p_id),
KEY p2p_from (p2p_from),
KEY p2p_to (p2p_to)
" );
$table2 = new scbTable( 'p2pmeta', $file, "
meta_id bigint(20) unsigned NOT NULL auto_increment,
p2p_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY p2p_id (p2p_id),
KEY meta_key (meta_key)
" );
// FORCE UPDATE
#add_action('init', array($table, 'install'));
#add_action('init', array($table2, 'install'));
add_action( 'delete_post', array( __CLASS__, 'delete_post' ) );
}
function delete_post( $post_id ) {
self::disconnect( $post_id, 'from' );
self::disconnect( $post_id, 'to' );
}
/**
* Get a list of connections, given a certain post id
*
* @param int $from post id
* @param int|string $to post id or direction: 'from' or 'to'
* @param array $data additional data about the connection to filter against
*
* @return array( p2p_id => post_id ) if $to is string
* @return array( p2p_id ) if $to is int
*/
function get( $post_id, $direction, $data = array() ) {
if ( 'any' == $direction ) {
$from = self::_get( $post_id, 'from', $data );
$to = self::_get( $post_id, 'to', $data );
foreach ( $to as $p2p_id => $post_id ) {
$from[ $p2p_id ] = $post_id;
}
return $from;
}
return self::_get( $post_id, $direction, $data );
}
private function _get( $from, $to, $data = array() ) {
global $wpdb;
$fields = "$wpdb->p2p.p2p_id";
$where = '';
$join = '';
$_return_p2p_ids = false;
switch ( $to ) {
case 'from':
$fields .= ', p2p_to AS post_id';
$where .= $wpdb->prepare( "p2p_from = %d", $from );
break;
case 'to':
$fields .= ', p2p_from AS post_id';
$where .= $wpdb->prepare( "p2p_to = %d", $from );
break;
default:
$where .= $wpdb->prepare( "p2p_from = %d AND p2p_to = %d", $from, $to );
$_return_p2p_ids = true;
}
if ( !empty( $data ) ) {
$clauses = _p2p_meta_sql_helper( $data );
$join .= $clauses['join'];
$where .= $clauses['where'];
}
$query = "SELECT $fields FROM $wpdb->p2p $join WHERE $where";
if ( $_return_p2p_ids )
return $wpdb->get_col( $query );
$results = $wpdb->get_results( $query );
$r = array();
foreach ( $results as $row )
$r[ $row->p2p_id ] = $row->post_id;
return $r;
}
/**
* Connect two posts
*
* @param int $from post id
* @param int $to post id
* @param array $data additional data about the connection
* @param string $duplicates Duplicate prevention strategy: 'none', 'matching_data', 'strict'
*
* @return int|bool connection id or False on failure
*/
function connect( $from, $to, $data = array(), $duplicates = 'matching_data' ) {
global $wpdb;
$from = absint( $from );
$to = absint( $to );
if ( !$from || !$to )
return false;
$wpdb->insert( $wpdb->p2p, array( 'p2p_from' => $from, 'p2p_to' => $to ), '%d' );
$p2p_id = $wpdb->insert_id;
foreach ( $data as $key => $value )
p2p_add_meta( $p2p_id, $key, $value );
return $p2p_id;
}
/**
* Disconnect two posts
*
* @param int $from post id
* @param int|string $to post id or direction: 'from' or 'to'
* @param array $data additional data about the connection to filter against
*
* @return int Number of connections deleted
*/
function disconnect( $from, $to, $data = array() ) {
$connections = self::get( $from, $to, $data );
// We're interested in the p2p_ids
if ( !(int) $to )
$connections = array_keys( $connections );
return self::delete( $connections );
}
/**
* Delete one or more connections
*
* @param int|array $p2p_id Connection ids
*
* @return int Number of connections deleted
*/
function delete( $p2p_id ) {
global $wpdb;
if ( empty( $p2p_id ) )
return 0;
$p2p_ids = array_map( 'absint', (array) $p2p_id );
$where = "WHERE p2p_id IN (" . implode( ',', $p2p_ids ) . ")";
$wpdb->query( "DELETE FROM $wpdb->p2p $where" );
$wpdb->query( "DELETE FROM $wpdb->p2pmeta $where" );
return count( $p2p_ids );
}
}
function p2p_get_meta($p2p_id, $key, $single = false) {
return get_metadata('p2p', $p2p_id, $key, $single);
}
function p2p_update_meta($p2p_id, $meta_key, $meta_value, $prev_value = '') {
return update_metadata('p2p', $p2p_id, $meta_key, $meta_value, $prev_value);
}
function p2p_add_meta($p2p_id, $meta_key, $meta_value, $unique = false) {
return add_metadata('p2p', $p2p_id, $meta_key, $meta_value, $unique);
}
function p2p_delete_meta($p2p_id, $meta_key, $meta_value = '') {
return delete_metadata('p2p', $p2p_id, $meta_key, $meta_value);
}
function _p2p_meta_sql_helper( $data ) {
global $wpdb;
if ( isset( $data[0] ) ) {
$meta_query = $data;
}
else {
$meta_query = array();
foreach ( $data as $key => $value ) {
$meta_query[] = compact( 'key', 'value' );
}
}
return p2p_get_meta_sql( $meta_query, 'p2p', $wpdb->p2p, 'p2p_id' );
}
// WP < 3.1-alpha
function p2p_get_meta_sql( $meta_query, $meta_type, $primary_table, $primary_id_column ) {
global $wpdb;
if ( ! $meta_table = _get_meta_table( $meta_type ) )
return false;
$meta_id_column = esc_sql( $meta_type . '_id' );
$clauses = array();
$join = '';
$where = '';
$i = 0;
foreach ( $meta_query as $q ) {
$meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
$meta_value = isset( $q['value'] ) ? $q['value'] : '';
$meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
$meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
$meta_compare = '=';
if ( 'NUMERIC' == $meta_type )
$meta_type = 'SIGNED';
elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
$meta_type = 'CHAR';
if ( empty( $meta_key ) && empty( $meta_value ) )
continue;
$alias = $i ? 'mt' . $i : $meta_table;
$join .= "\nINNER JOIN $meta_table";
$join .= $i ? " AS $alias" : '';
$join .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
$i++;
if ( !empty( $meta_key ) )
$where .= $wpdb->prepare( " AND $alias.meta_key = %s", $meta_key );
if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
if ( ! is_array( $meta_value ) )
$meta_value = preg_split( '/[,\s]+/', $meta_value );
} else {
$meta_value = trim( $meta_value );
}
if ( empty( $meta_value ) )
continue;
if ( 'IN' == substr( $meta_compare, -2) ) {
$meta_field_types = substr( str_repeat( ',%s', count( $meta_value ) ), 1 );
$meta_compare_string = "($meta_field_types)";
unset( $meta_field_types );
} elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
$meta_value = array_slice( $meta_value, 0, 2 );
$meta_compare_string = '%s AND %s';
} elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
$meta_value = '%' . like_escape( $meta_value ) . '%';
$meta_compare_string = '%s';
} else {
$meta_compare_string = '%s';
}
$where .= $wpdb->prepare( " AND CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string}", $meta_value );
unset( $meta_compare_string );
}
return compact( 'join', 'where' );
}
+250
View File
@@ -0,0 +1,250 @@
<?php
// Automated testing suite for the Posts 2 Posts plugin
class P2P_Test {
function init() {
if ( !function_exists('p2p_register_connection_type') )
return;
add_action('init', array(__CLASS__, '_init'));
# add_action('admin_init', array(__CLASS__, 'setup'));
add_action('load-index.php', array(__CLASS__, 'test'));
# add_action('load-index.php', array(__CLASS__, 'debug'));
}
function _init() {
register_post_type('actor', array(
'public' => true,
'labels' => array(
'name' => 'Actors',
'singular_name' => 'Actor',
'search_items' => 'Search Actors',
'not_found' => 'No actors found.'
),
'has_archive' => 'actors'
));
register_post_type('movie', array(
'public' => true,
'labels' => array(
'name' => 'Movies',
'singular_name' => 'Movie',
'search_items' => 'Search movies',
'not_found' => 'No movies found.',
)
) );
p2p_register_connection_type( array(
'from' => 'actor',
'to' => 'actor',
'reciprocal' => true,
'title' => array( 'from' => 'Doubles', 'to' => 'Main Actor' )
) );
p2p_register_connection_type( array(
'from' => 'actor',
'to' => 'movie',
'reciprocal' => true,
'fields' => array(
'role' => 'Role',
'role_type' => 'Role Type'
),
'prevent_duplicates' => false,
'title' => array( 'from' => 'Played In', 'to' => 'Cast' ),
) );
p2p_register_connection_type('actor', 'post');
}
function setup() {
global $wpdb;
$wpdb->query("DELETE FROM $wpdb->posts WHERE post_type IN ('actor', 'movie')");
$movie_ids = $actor_ids = array();
for ( $i=0; $i<20; $i++ ) {
$actor_ids[] = wp_insert_post(array(
'post_type' => 'actor',
'post_title' => "Actor $i",
'post_status' => 'publish'
));
$movie_ids[] = wp_insert_post(array(
'post_type' => 'movie',
'post_title' => "Movie $i",
'post_status' => 'publish'
));
}
}
function test() {
global $wpdb;
$wpdb->query("TRUNCATE $wpdb->p2p");
$wpdb->query("TRUNCATE $wpdb->p2pmeta");
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 1);
$failed = false;
assert_options(ASSERT_CALLBACK, function ($file, $line, $code) use ( &$failed ) {
$failed = true;
echo "<hr>Assertion Failed (line $line):<br />
<code>$code</code><br /><hr />";
add_action('admin_notices', array(__CLASS__, 'debug'));
});
$actor_ids = get_posts( array(
'fields' => 'ids',
'post_type' => 'actor',
'post_status' => 'any',
'orderby' => 'post_title',
'order' => 'asc',
'nopaging' => true
) );
$movie_ids = get_posts( array(
'fields' => 'ids',
'post_type' => 'movie',
'post_status' => 'any',
'orderby' => 'post_title',
'order' => 'asc',
'nopaging' => true
) );
// basic API correctness
p2p_connect( array_slice( $actor_ids, 0, 5 ), array_slice( $movie_ids, 0, 3 ) );
p2p_connect( $movie_ids[0], $actor_ids[10] );
$result = array_values( p2p_get_connected( $actor_ids[0], 'from' ) );
sort( $result );
$expected = array_slice( $movie_ids, 0, 3 );
sort($expected);
assert( '$expected == $result' );
$result = array_values( p2p_get_connected( $movie_ids[0], 'any' ) );
sort( $result );
$expected = array( $actor_ids[0], $actor_ids[10] );
sort( $expected );
assert( '$expected == $result' );
assert( 'true == p2p_is_connected( $actor_ids[0], $movie_ids[0] )' );
assert( 'false == p2p_is_connected( $actor_ids[0], $movie_ids[10] )' );
// 'actor' => 'actor'
$posts = get_posts( array(
'connected' => $actor_ids[0],
'post_type' => 'actor',
'post_status' => 'any',
'suppress_filters' => false,
'fields' => 'ids',
) );
assert( 'array() == $posts' );
// compare p2p_get_connected() to 'connected' => 123
p2p_connect( $actor_ids[2], $actor_ids[10] );
p2p_connect( $actor_ids[10], $actor_ids[2] );
$raw = p2p_get_connected($actor_ids[2], 'any');
$posts = get_posts( array(
'connected' => $actor_ids[2],
'post_type' => 'actor',
'post_status' => 'any',
'suppress_filters' => false,
'cache_results' => false,
) );
$r = array();
foreach ( $posts as $post ) {
$r[ $post->p2p_id ] = $post->ID;
}
assert( 'array_intersect_assoc($r, $raw) == $r' );
// test 'each_*' query vars
$posts = get_posts( array(
'post_type' => 'actor',
'post_status' => 'any',
'nopaging' => true,
'each_connected' => array(
'post_type' => 'movie',
'post_status' => 'any',
'nopaging' => true,
),
'suppress_filters' => false
) );
# self::walk( $posts );
# // test 'each_*' query vars
# $posts = get_posts( array(
# 'post_type' => 'actor',
# 'post_status' => 'any',
# 'nopaging' => true,
# 'each_connected' => array(
# 'post_type' => 'actor',
# 'post_status' => 'any',
# 'nopaging' => true,
# 'each_connected' => array(
# 'post_type' => 'actor',
# 'post_status' => 'any',
# 'nopaging' => true,
# ),
# ),
# 'suppress_filters' => false
# ) );
# self::walk( $posts );
# // test p2p_each_connected()
# $query = new WP_Query( array(
# 'post_type' => 'actor',
# 'post_status' => 'any',
# 'nopaging' => true,
# ) );
# p2p_each_connected( 'any', 'movies', array( 'post_type' => 'movie' ), $query );
# self::walk( $query->posts, 'movies' );
if ( $failed )
self::debug();
}
private function walk( $posts, $key = '', $level = 0 ) {
if ( 0 == $level )
echo '<pre>';
foreach ( $posts as $post ) {
echo str_repeat( "\t", $level ) . "$post->ID: $post->post_title\n";
self::walk( (array) @$post->{"connected_$key"}, $key, $level+1 );
}
if ( 0 == $level )
echo '</pre>';
}
function debug() {
global $wpdb;
$rows = $wpdb->get_results("SELECT * FROM $wpdb->p2p");
foreach ( $rows as $row ) {
echo html_link( get_edit_post_link( $row->p2p_from ), $row->p2p_from ) . ' -> ';
echo html_link( get_edit_post_link( $row->p2p_to ), $row->p2p_to );
echo '<br>';
}
die;
}
}
add_action( 'plugins_loaded', array('P2P_Test', 'init'), 11 );
@@ -0,0 +1,244 @@
<?php
class P2P_Box_Multiple extends P2P_Box {
function setup() {
$ptype_obj = get_post_type_object( $this->to );
$this->columns = array_merge(
array( 'delete' => $this->clear_connections_link() ),
array( 'title' => $ptype_obj->labels->singular_name ),
$this->fields
);
}
function connect() {
$from = absint( $_POST['from'] );
$to = absint( $_POST['to'] );
if ( !$from || !$to )
die(-1);
$args = array( $from, $to );
if ( $this->reversed )
$args = array_reverse( $args );
$p2p_id = false;
if ( $this->prevent_duplicates ) {
$p2p_ids = P2P_Connections::get( $args[0], $args[1] );
if ( !empty( $p2p_ids ) )
$p2p_id = $p2p_ids[0];
}
if ( !$p2p_id )
$p2p_id = P2P_Connections::connect( $args[0], $args[1] );
$this->connection_row( $p2p_id, $to );
}
function disconnect() {
$p2p_id = absint( $_POST['p2p_id'] );
p2p_delete_connection( $p2p_id );
die(1);
}
function clear_connections() {
$post_id = absint( $_POST['post_id'] );
p2p_disconnect( $post_id, $this->direction );
die(1);
}
function box( $post_id ) {
$connected_ids = $this->get_connected_ids( $post_id );
$data_attr = array();
foreach ( array( 'box_id', 'direction', 'prevent_duplicates' ) as $key )
$data_attr[] = "data-$key='" . $this->$key . "'";
$data_attr = implode( ' ', $data_attr );
?>
<div class="p2p-box">
<table class="p2p-connections" <?php if ( empty( $connected_ids ) ) echo 'style="display:none"'; ?>>
<thead>
<tr>
<?php
foreach ( $this->columns as $key => $title ) {
echo html( 'th', array( 'class' => "p2p-col-$key" ), $title );
}
?>
</tr>
</thead>
<tbody>
<?php
foreach ( $connected_ids as $p2p_id => $post_b ) {
$this->connection_row( $p2p_id, $post_b );
}
?>
</tbody>
</table>
<div class="p2p-add-new" <?php echo $data_attr; ?>>
<p><strong><?php _e( 'Create connections:', 'posts-to-posts' ); ?></strong></p>
<div class="p2p-search">
<?php echo html( 'input', array(
'type' => 'text',
'name' => 'p2p_search_' . $this->to,
'autocomplete' => 'off',
'placeholder' => get_post_type_object( $this->to )->labels->search_items
) ); ?>
</div>
<table class="p2p-results">
<tbody>
</tbody>
</table>
</div><!--.p2p-add-new-->
</div><!--.p2p-box-->
<div class="p2p-footer">
<div class="p2p-nav">
<div class="p2p-prev button" title="<?php _e( 'Previous', 'p2p-textdomain' ); ?>">&lsaquo;</div>
<div><span class="p2p-current"></span> <? _e( 'of', 'p2p-textdomain' ); ?> <span class="p2p-total"></span></div>
<div class="p2p-next button" title="<?php _e( 'Next', 'p2p-textdomain' ); ?>">&rsaquo;</div>
</div>
<a href="#" class="p2p-recent button" name="p2p-recent">
<?php _e( 'Recent', 'posts-to-posts' ); ?>
</a>
<div class="clear">
<!-- Clearfix would be better -->
</div>
</div>
<?php
}
protected function connection_row( $p2p_id, $post_id ) {
echo '<tr>';
foreach ( array_keys( $this->columns ) as $key ) {
switch ( $key ) {
case 'title':
$value = $this->column_title( $post_id );
break;
case 'delete':
$value = $this->column_delete( $p2p_id );
break;
default:
$value = html( 'input', array(
'type' => 'text',
'name' => "p2p_meta[$p2p_id][$key]",
'value' => p2p_get_meta( $p2p_id, $key, true )
) );
}
echo html( 'td', array( 'class' => "p2p-col-$key" ), $value );
}
echo '</tr>';
}
public function results_row( $post ) {
echo '<tr>';
foreach ( array( 'add', 'title' ) as $key ) {
$method = "column_$key";
echo html( 'td', array( 'class' => "p2p-col-$key" ), $this->$method( $post->ID ) );
}
echo '</tr>';
}
protected function column_title( $post_id ) {
return html( 'a', array(
'href' => str_replace( '&amp;', '&', get_edit_post_link( $post_id ) ),
'title' => get_post_type_object( get_post_type( $post_id ) )->labels->edit_item,
), get_post_field( 'post_title', $post_id ) );
}
protected function column_add( $post_id ) {
return html( 'a', array(
'data-post_id' => $post_id,
'href' => '#',
'title' => __( 'Create connection', 'posts-to-posts' )
), __( 'Create connection', 'posts-to-posts' ) );
}
protected function column_delete( $p2p_id ) {
return html( 'a', array(
'data-p2p_id' => $p2p_id,
'href' => '#',
'title' => __( 'Delete connection', 'posts-to-posts' )
), __( 'Delete connection', 'posts-to-posts' ) );
}
protected function clear_connections_link() {
return html( 'a', array(
'href' => '#',
'title' => __( 'Delete all connections', 'posts-to-posts' )
), __( 'Delete all connections', 'posts-to-posts' ) );
}
protected function get_connected_ids( $post_id ) {
$connected_posts = p2p_get_connected( $post_id, $this->direction );
if ( empty( $connected_posts ) )
return array();
$args = array(
'post__in' => $connected_posts,
'post_type'=> $this->to,
'post_status' => 'any',
'nopaging' => true,
'suppress_filters' => false,
);
$post_ids = scbUtil::array_pluck( get_posts($args), 'ID' );
return array_intersect( $connected_posts, $post_ids ); // to preserve p2p_id keys
}
function get_search_args( $args, $post_id ) {
$args = array_merge( $args, array(
'post_type' => $this->to,
'post_status' => 'any',
'posts_per_page' => 5,
'suppress_filters' => false,
'update_post_term_cache' => false,
'update_post_meta_cache' => false
) );
if ( $this->prevent_duplicates )
$args['post__not_in'] = p2p_get_connected( $post_id, $this->direction );
return $args;
}
function get_recent_args( $post_id ) {
$args = array(
'numberposts' => 10,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => $this->to,
'post_status' => 'publish',
'suppress_filters' => false //true
);
if ( $this->prevent_duplicates )
$args['post__not_in'] = p2p_get_connected( $post_id, $this->direction );
return $args;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 127 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 B

+168
View File
@@ -0,0 +1,168 @@
/* General */
.button.inactive, .button.inactive:hover {
border-color: #bbb;
color: #aaa;
background: #f6f6f6;
text-shadow: none;
cursor: default;
}
.p2p-footer {
background-color: #f1f1f1;
border-top: 1px solid #ddd;
clear: both;
padding: 7px;
margin: 0 -6px -8px;
}
.p2p-footer .p2p-recent {
float: right;
}
.p2p-placeholder {
color: #AAA;
}
.p2p-connections,
.p2p-search,
.p2p-results {
margin-bottom: 8px;
}
/* Connections */
.p2p-results,
.p2p-connections {
background-color: #F9F9F9;
border-color: #DFDFDF;
border-radius: 3px;
border-spacing: 0;
border-style: solid;
border-width: 1px;
}
.p2p-results {
display: none;
}
.p2p-results td,
.p2p-connections td {
border-top: 1px solid #DFDFDF;
}
.p2p-connections th,
.p2p-connections td,
.p2p-results td {
padding-left: 6px;
padding-right: 6px;
}
th.p2p-col-delete,
td.p2p-col-delete,
td.p2p-col-add {
padding: 0;
}
.p2p-col-delete a,
.p2p-col-add a,
.p2p-col-delete img,
.p2p-col-add img {
padding: 5px 6px;
}
th.p2p-col-delete a {
padding-bottom: 8px;
}
.p2p-results tr:first-child td {
border-top: 0;
}
.p2p-connections {
width: 100%;
}
.p2p-connections th {
background-color: #F1F1F1;
text-align: left;
}
.p2p-connections td input {
width: 100%;
}
.p2p-col-add,
.p2p-col-delete {
width: 16px;
}
.p2p-col-add a,
.p2p-col-delete a {
display: block;
height: 16px;
margin-top: 1px;
opacity: 0.5;
text-indent: -9999px;
width: 16px;
}
.p2p-col-add a:hover,
.p2p-col-delete a:hover {
background-color: #f5f5f5;
border-right: 1px solid #ddd;
opacity: 1;
width: 15px;
}
.p2p-col-add a {
background: url("images/add.png") no-repeat scroll 50% 50% transparent;
}
.p2p-col-delete a {
background: url("images/delete.png") no-repeat scroll 50% 50% transparent;
}
#poststuff .p2p-box .p2p-add-new p {
margin-left: 5px;
}
.p2p-search .waiting {
margin-left: -20px;
opacity: 0.8;
vertical-align: -0.3em;
}
.p2p-search input {
background-color: transparent;
width: 150px;
padding-right: 22px;
margin: 0;
}
.p2p-notice {
margin-left: 5px;
}
#side-sortables .p2p-notice {
display: block;
margin-top: 10px;
}
.p2p-footer .waiting {
float: right;
margin: 3px 6px 0;
}
.p2p-nav {
display: none;
}
.p2p-nav > * {
float: left;
line-height: 13px;
padding-top: 3px;
padding-bottom: 3px;
margin-right: 5px;
}
+254
View File
@@ -0,0 +1,254 @@
jQuery(document).ready(function($) {
// Placeholder support for IE
if (!jQuery('<input placeholder="1" />')[0].placeholder) {
jQuery('.p2p-search input[placeholder]').each(function(){
var $this = $(this);
if (!$this.val()) {
$this.val($this.attr('placeholder'));
$this.addClass('p2p-placeholder');
}
}).focus(function(e){
var $this = $(this);
if ($this.hasClass('p2p-placeholder')) {
$this.val('');
$this.removeClass('p2p-placeholder');
}
}).blur(function(e){
var $this = $(this);
if (!$this.val()) {
$this.addClass('p2p-placeholder');
$this.val($this.attr('placeholder'));
}
});
}
$('.p2p-add-new').each(function() {
var $metabox = $(this).closest('.inside'),
$connections = $metabox.find('.p2p-connections'),
$results = $metabox.find('.p2p-results'),
$searchInput = $metabox.find('.p2p-search :text'),
$pagination = $metabox.find('.p2p-nav'),
$addNew = $metabox.find('.p2p-add-new'),
base_data = {
box_id: $addNew.attr('data-box_id'),
direction: $addNew.attr('data-direction')
};
// Save the wp-spinner
var $spinner = $('#publishing-action .ajax-loading')
.clone()
.removeAttr('id')
.removeClass('ajax-loading')
.addClass('waiting');
// Delete all connections
$metabox.delegate('th.p2p-col-delete a', 'click', function() {
if ( !confirm(P2PAdmin_I18n.deleteConfirmMessage) )
return false;
var $self = $(this),
$td = $self.closest('td'),
data = $.extend( base_data, {
action: 'p2p_connections',
subaction: 'clear_connections',
post_id: $('#post_ID').val()
} );
$td.html( $spinner.show() );
$.post(ajaxurl, data, function(response) {
$connections.hide()
.find('tbody').html('');
$td.html( $self );
});
return false;
});
// Delete connection
$metabox.delegate('td.p2p-col-delete a', 'click', function() {
var $self = $(this),
$td = $self.closest('td'),
data = $.extend( base_data, {
action: 'p2p_connections',
subaction: 'disconnect',
p2p_id: $self.attr('data-p2p_id')
} );
$td.html( $spinner.show() );
$.post(ajaxurl, data, function(response) {
$td.closest('tr').remove();
if ( !$connections.find('tbody tr').length )
$connections.hide();
});
return false;
});
// Create connection
$metabox.delegate('td.p2p-col-add a', 'click', function() {
var $self = $(this),
$td = $self.closest('td'),
data = $.extend( base_data, {
action: 'p2p_connections',
subaction: 'connect',
from: $('#post_ID').val(),
to: $self.attr('data-post_id')
} );
$td.html( $spinner.show() );
$.post(ajaxurl, data, function(response) {
$connections.show()
.find('tbody').append(response);
if ( $addNew.attr('data-prevent_duplicates') ) {
$td.closest('tr').remove();
if ( !$results.find('tbody tr').length )
$results.hide();
} else {
$td.html( $self );
}
});
return false;
});
// Pagination
var current_page = 1,
total_pages = 0;
function find_posts(new_page, action, callback) {
new_page = new_page ? ( new_page > total_pages ? current_page : new_page ) : current_page;
var data = $.extend( base_data, {
action: 'p2p_search',
s: $searchInput.val(),
paged: new_page,
post_id: $('#post_ID').val()
} );
// show spinner
if ( 'search' === action ) {
$spinner.insertAfter( $searchInput );
} else {
$spinner.insertAfter( $metabox.find('.p2p-recent') );
}
$spinner.show();
$.getJSON(ajaxurl, data, function(response) {
$spinner.remove();
current_page = new_page;
$metabox.find('.p2p-search').find('.p2p-notice').remove();
$pagination.hide();
if ( 'undefined' === typeof response.rows ) {
$metabox.find('.p2p-search').append('<p class="p2p-notice">' + response.msg + '</p>');
$results.hide()
.find('tbody').html('');
} else {
$results.show()
.find('tbody').html(response.rows);
total_pages = response.pages;
// update pagination
if ( total_pages > 1 ) {
$pagination.show();
}
if ( 1 === current_page ) {
$metabox.find('.p2p-prev').addClass('inactive');
} else {
$metabox.find('.p2p-prev').removeClass('inactive');
}
if ( total_pages === current_page ) {
$metabox.find('.p2p-next').addClass('inactive');
} else {
$metabox.find('.p2p-next').removeClass('inactive');
}
$metabox.find('.p2p-current').html(current_page);
$metabox.find('.p2p-total').html(total_pages);
if ( undefined !== callback )
callback();
}
});
}
// Delegate recent
$metabox.delegate('.p2p-recent', 'click', function() {
var $button = $(this);
if ( $button.hasClass('inactive') )
return false;
$metabox.find('.p2p-search :text')
.val('')
.blur(); // so that placeholder is shown again in IE
$button.addClass('inactive');
find_posts(1, 'recent', function() {
$button.removeClass('inactive');
});
return false;
});
// Search posts
var delayed, old_value = '';
$metabox.find('.p2p-search :text')
.keypress(function (ev) {
if ( 13 === ev.keyCode )
return false;
})
.keyup(function (ev) {
if ( undefined !== delayed ) {
clearTimeout(delayed);
}
var $self = $(this);
delayed = setTimeout(function() {
if ( $self.val() === old_value ) {
return;
}
old_value = $self.val();
find_posts(1, 'search');
}, 400);
});
// Pagination
$metabox.delegate('.p2p-prev, .p2p-next', 'click', function() {
var $self = $(this),
new_page = current_page;
if ( $self.hasClass('inactive') )
return false;
if ( $self.hasClass('p2p-prev') )
new_page--;
else
new_page++;
find_posts(new_page, 'paginate');
return false;
});
});
});
+211
View File
@@ -0,0 +1,211 @@
<?php
abstract class P2P_Box {
public $from;
public $to;
protected $reversed;
protected $direction;
protected $box_id;
abstract function box( $post_id );
function setup() {}
// Internal stuff
public function __construct( $args, $direction, $box_id ) {
foreach ( $args as $key => $value )
$this->$key = $value;
$this->box_id = $box_id;
$this->direction = $direction;
$this->reversed = ( 'to' == $direction );
if ( $this->reversed )
list( $this->to, $this->from ) = array( $this->from, $this->to );
$this->setup();
}
function _register( $from ) {
if ( is_array( $this->title ) ) {
$key = $this->reversed ? 'to' : 'from';
if ( isset( $this->title[ $key ] ) )
$title = $this->title[ $key ];
else
$title = '';
} else {
$title = $this->title;
}
if ( empty( $title ) ) {
$title = sprintf( __( 'Connected %s', 'posts-to-posts' ), get_post_type_object( $this->to )->labels->name );
}
add_meta_box(
'p2p-connections-' . $this->box_id,
$title,
array( $this, '_box' ),
$from,
$this->context,
'default'
);
}
function _box( $post ) {
$this->box( $post->ID );
}
}
class P2P_Connection_Types {
private static $ctypes = array();
static public function register( $args ) {
self::$ctypes[] = $args;
}
static function init() {
add_action( 'add_meta_boxes', array( __CLASS__, '_register' ) );
add_action( 'save_post', array( __CLASS__, 'save' ), 10, 2 );
add_action( 'wp_ajax_p2p_search', array( __CLASS__, 'ajax_search' ) );
add_action( 'wp_ajax_p2p_connections', array( __CLASS__, 'ajax_connections' ) );
}
static function _register( $from ) {
$filtered = self::filter_ctypes( $from );
if ( empty( $filtered ) )
return;
foreach ( $filtered as $ctype ) {
$ctype->_register( $from );
}
wp_enqueue_style( 'p2p-admin', plugins_url( 'ui.css', __FILE__ ), array(), '0.7-beta' );
wp_enqueue_script( 'p2p-admin', plugins_url( 'ui.js', __FILE__ ), array( 'jquery' ), '0.7-beta', true );
wp_localize_script( 'p2p-admin', 'P2PAdmin_I18n', array(
'deleteConfirmMessage' => __( 'Are you sure you want to delete all connections?', 'posts-to-posts' ),
) );
}
function save( $post_id, $post ) {
if ( 'revision' == $post->post_type || !isset( $_POST['p2p_meta'] ) )
return;
foreach ( $_POST['p2p_meta'] as $p2p_id => $data ) {
foreach ( $data as $key => $value ) {
p2p_update_meta( $p2p_id, $key, $value );
}
}
}
function ajax_connections() {
$box = self::ajax_make_box();
$ptype_obj = get_post_type_object( $box->from );
if ( !current_user_can( $ptype_obj->cap->edit_posts ) )
die(-1);
$subaction = $_POST['subaction'];
$box->$subaction();
}
function ajax_disconnect() {
$box = self::ajax_make_box();
$box->disconnect();
}
function ajax_search() {
add_filter( 'posts_search', array( __CLASS__, '_search_by_title' ), 10, 2 );
$box = self::ajax_make_box();
$args = array(
's' => $_GET['s'],
'paged' => $_GET['paged']
);
$query = new WP_Query( $box->get_search_args( $args, $_GET['post_id'] ) );
if ( !$query->have_posts() ) {
$results = array(
'msg' => get_post_type_object( $box->to )->labels->not_found,
);
} else {
ob_start();
foreach ( $query->posts as $post ) {
$box->results_row( $post );
}
$results = array(
'rows' => ob_get_clean(),
'pages' => $query->max_num_pages
);
}
echo json_encode( $results );
die;
}
function _search_by_title( $sql, $wp_query ) {
remove_filter( current_filter(), array( __CLASS__, __FUNCTION__ ) );
if ( $wp_query->is_search ) {
list( $sql ) = explode( ' OR ', $sql, 2 );
return $sql . '))';
}
return $sql;
}
private static function ajax_make_box() {
$box_id = absint( $_REQUEST['box_id'] );
$direction = $_REQUEST['direction'];
if ( !isset( self::$ctypes[ $box_id ] ) )
die(0);
$args = self::$ctypes[ $box_id ];
return new $args['box']($args, $direction, $box_id);
}
private static function filter_ctypes( $post_type ) {
$r = array();
foreach ( self::$ctypes as $box_id => $args ) {
$direction = false;
if ( $args['reciprocal'] && $post_type == $args['from'] && $args['from'] == $args['to'] ) {
$direction = 'any';
} elseif ( $args['reciprocal'] && $post_type == $args['to'] ) {
$direction = 'to';
} elseif ( $post_type == $args['from'] ) {
$direction = 'from';
} else {
continue;
}
if ( !$direction )
continue;
$r[ $box_id ] = new $args['box']($args, $direction, $box_id);
}
return $r;
}
}