Welcome. WordPress is a very special project to me. Every developer and contributor adds something unique to the mix, and together we create something beautiful that I'm proud to be a part of. Thousands of hours have gone into WordPress, and we're dedicated to making it better every day. Thank you for making it part of your world.
— Matt Mullenweg
Installation: Famous 5-minute install
Unzip the package in an empty directory.
Open up wp-config-sample.php with a text editor like WordPad or similar and fill in your database connection details.
Save the file as wp-config.php
Upload everything.
Open /wp-admin/install.php in your browser. This should setup the tables needed for your blog. If there is an error, double check your wp-config.php file, and try again. If it fails again, please go to the support forums with as much data as you can gather.
Note the password given to you.
The install script should then send you to the login page. Sign in with the username admin and the password generated during the installation. You can then click on 'Profile' to change the password.
Upgrading
Before you upgrade anything, make sure you have backup copies of any files you may have modified such as index.php.
Upgrading from any previous WordPress to 2.8.1:
Delete your old WP files, saving ones you've modified.
If you have customized your templates you will probably have to make some changes to them. If you're converting your 1.2 or earlier templates, we've created a special guide for you.
Online Resources
If you have any questions that aren't addressed in this document, please take advantage of WordPress' numerous online resources:
If you've looked everywhere and still can't find an answer, the support forums are very active and have a large community ready to help. To help them help you be sure to use a descriptive thread title and describe your question in as much detail as possible.
Finally, there is an online chat channel that is used for discussion among people who use WordPress and occasionally support topics. The above wiki page should point you in the right direction. (irc.freenode.net #wordpress)
WordPress is the official continuation of b2/cafélog, which came from Michel V. The work has been continued by the WordPress developers. If you would like to support WordPress, please consider donating.
You can post from an email client! To set this up go to your "Writing" options screen and fill in the connection details for your secret POP3 account. Then you need to set up wp-mail.php to execute periodically to check the mailbox for new posts. You can do it with Cron-jobs, or if your host doesn't support it you can look into the various website-monitoring services, and make them check your wp-mail.php URL.
Posting is easy: Any email sent to the address you specify will be posted, with the subject as the title. It is best to keep the address discrete. The script will delete emails that are successfully posted.
If you have any suggestions, ideas, comments, or if you (gasp!) found a bug, join us in the Support Forums.
WordPress now has a robust plugin API that makes extending the code easy. If you are a developer interested in utilizing this see the plugin documentation in the Codex. In most all cases you shouldn't modify any of the core code.
Share the Love
WordPress has no multi-million dollar marketing campaign or celebrity sponsors, but we do have something even better—you. If you enjoy WordPress please consider telling a friend, setting it up for someone less knowledgable than yourself, or writing the author of a media article that overlooks us.
Copyright
WordPress is released under the GPL (see license.txt).
larscapo/wp-admin/js/dashboard.js 0000644 0041054 0041055 00000003222 11225447103 017510 0 ustar lacunaus lacunaus var ajaxWidgets,ajaxPopulateWidgets,quickPressLoad;jQuery(document).ready(function(a){ajaxWidgets=["dashboard_incoming_links","dashboard_primary","dashboard_secondary","dashboard_plugins"];ajaxPopulateWidgets=function(b){show=function(g,c){var f,d=a("#"+g+" div.inside:visible").find(".widget-loading");if(d.length){f=d.parent();setTimeout(function(){f.load("index-extra.php?jax="+g,"",function(){f.hide().slideDown("normal",function(){a(this).css("display","");if("dashboard_plugins"==g&&a.isFunction(tb_init)){tb_init("#dashboard_plugins a.thickbox")}})})},c*500)}};if(b){b=b.toString();if(a.inArray(b,ajaxWidgets)!=-1){show(b,0)}}else{a.each(ajaxWidgets,function(c){show(this,c)})}};ajaxPopulateWidgets();postboxes.add_postbox_toggles("dashboard",{pbshow:ajaxPopulateWidgets});quickPressLoad=function(){var b=a("#quickpost-action"),c;c=a("#quick-press").submit(function(){a("#dashboard_quick_press h3").append('');a('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr("disabled","disabled");if("post"==b.val()){b.val("post-quickpress-publish")}a("#dashboard_quick_press div.inside").load(c.attr("action"),c.serializeArray(),function(){a("#dashboard_quick_press h3 img").remove();a('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr("disabled","");a("#dashboard_quick_press ul").find("li").each(function(){a("#dashboard_recent_drafts ul").prepend(this)}).end().remove();tb_init("a.thickbox");quickPressLoad()});return false});a("#publish").click(function(){b.val("post-quickpress-publish")})};quickPressLoad()}); larscapo/wp-admin/js/edit-comments.dev.js 0000644 0041054 0041055 00000026724 11225447103 021122 0 ustar lacunaus lacunaus var theList, theExtraList, toggleWithKeyboard = false;
(function($) {
setCommentsList = function() {
var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter;
totalInput = $('#comments-form .tablenav :input[name="_total"]');
perPageInput = $('#comments-form .tablenav :input[name="_per_page"]');
pageInput = $('#comments-form .tablenav :input[name="_page"]');
dimAfter = function( r, settings ) {
var c = $('#' + settings.element);
if ( c.is('.unapproved') )
c.find('div.comment_status').html('0')
else
c.find('div.comment_status').html('1')
$('span.pending-count').each( function() {
var a = $(this), n;
n = a.html().replace(/[ ,.]+/g, '');
n = parseInt(n,10);
if ( isNaN(n) ) return;
n = n + ( $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1 );
if ( n < 0 ) { n = 0; }
a.parents('#awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
n = n.toString();
if ( n.length > 3 )
n = n.substr(0, n.length-3)+' '+n.substr(-3);
a.html(n);
});
};
// Send current total, page, per_page and url
delBefore = function( settings ) {
settings.data._total = totalInput.val();
settings.data._per_page = perPageInput.val();
settings.data._page = pageInput.val();
settings.data._url = document.location.href;
if ( 'undefined' != showNotice && settings.data.action && settings.data.action == 'delete-comment' && !settings.data.spam )
return showNotice.warn() ? settings : false;
return settings;
};
/* Updates the current total (as displayed visibly)
*/
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime ) {
return;
}
totalInput.val( total.toString() );
if ( setConfidentTime ) {
lastConfidentTime = time;
}
$('span.total-type-count').each( function() {
var a = $(this), n;
n = totalInput.val().toString();
if ( n.length > 3 )
n = n.substr(0, n.length-3)+' '+n.substr(-3);
a.html(n);
});
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
$('span.pending-count').each( function() {
var a = $(this), n;
n = a.html().replace(/[ ,.]+/g, '');
n = parseInt(n,10);
if ( isNaN(n) ) return;
if ( $('#' + settings.element).is('.unapproved') ) { // we deleted a formerly unapproved comment
n = n - 1;
} else if ( $(settings.target).parents( 'span.unapprove' ).size() ) { // we "deleted" an approved comment from the approved list by clicking "Unapprove"
n = n + 1;
}
if ( n < 0 ) { n = 0; }
a.parents('#awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
n = n.toString();
if ( n.length > 3 )
n = n.substr(0, n.length-3)+' '+n.substr(-3);
a.html(n);
});
$('span.spam-count').each( function() {
var a = $(this), n;
n = a.html().replace(/[ ,.]+/g, '');
n = parseInt(n,10);
if ( isNaN(n) ) return;
if ( $(settings.target).parents( 'span.spam' ).size() ) { // we marked a comment as spam
n = n + 1;
} else if ( $('#' + settings.element).is('.spam') ) { // we approved or deleted a comment marked as spam
n = n - 1;
}
if ( n < 0 ) { n = 0; }
n = n.toString();
if ( n.length > 3 )
n = n.substr(0, n.length-3)+' '+n.substr(-3);
a.html(n);
});
// XML response
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
// Set the total to the known good value (even if this value is a little old, newer values should only be a few less, and so shouldn't mess up the page links)
updateTotalCount( settings.parsed.responses[0].supplemental.total, settings.parsed.responses[0].supplemental.time, true );
if ( $.trim( settings.parsed.responses[0].supplemental.pageLinks ) ) {
$('.tablenav-pages').find( '.page-numbers' ).remove().end().append( $( settings.parsed.responses[0].supplemental.pageLinks ) );
} else if ( 'undefined' != typeof settings.parsed.responses[0].supplemental.pageLinks ) {
$('.tablenav-pages').find( '.page-numbers' ).remove();
}
} else {
// Decrement the total
var total = parseInt( totalInput.val(), 10 );
if ( total-- < 0 )
total = 0;
updateTotalCount( total, r, false );
}
if ( theExtraList.size() == 0 || theExtraList.children().size() == 0 ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
$('#get-extra-comments').submit();
};
theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } );
};
commentReply = {
init : function() {
var row = $('#replyrow');
$('a.cancel', row).click(function() { return commentReply.revert(); });
$('a.save', row).click(function() { return commentReply.send(); });
$('input#author, input#author-email, input#author-url', row).keypress(function(e){
if ( e.which == 13 ) {
commentReply.send();
e.preventDefault();
return false;
}
});
// add events
$('#the-comment-list .column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
$('#doaction, #doaction2, #post-query-submit').click(function(e){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
},
addEvents : function(r) {
r.each(function() {
$(this).find('.column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
});
},
toggle : function(el) {
if ( $(el).css('display') != 'none' )
$(el).find('a.vim-q').click();
},
revert : function() {
if ( $('#the-comment-list #replyrow').length < 1 )
return false;
$('#replyrow').fadeOut('fast', function(){
commentReply.close();
});
return false;
},
close : function() {
$(this.o).fadeIn('fast').css('backgroundColor', '');
$('#com-reply').append( $('#replyrow') );
$('#replycontent').val('');
$('#edithead input').val('');
$('#replysubmit .error').html('').hide();
$('#replysubmit .waiting').hide();
if ( $.browser.msie )
$('#replycontainer, #replycontent').css('height', '120px');
else
$('#replycontainer').resizable('destroy').css('height', '120px');
},
open : function(id, p, a) {
var t = this, editRow, act, h;
t.close();
t.o = '#comment-'+id;
$('#replyrow td').attr('colspan', $('.widefat thead th:visible').length);
editRow = $('#replyrow'), rowData = $('#inline-'+id);
act = t.act = (a == 'edit') ? 'edit-comment' : 'replyto-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(p);
$('#comment_ID', editRow).val(id);
if ( a == 'edit' ) {
$('#author', editRow).val( $('div.author', rowData).text() );
$('#author-email', editRow).val( $('div.author-email', rowData).text() );
$('#author-url', editRow).val( $('div.author-url', rowData).text() );
$('#status', editRow).val( $('div.comment_status', rowData).text() );
$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
$('#edithead, #savebtn', editRow).show();
$('#replyhead, #replybtn', editRow).hide();
h = $(t.o).height();
if ( h > 220 )
if ( $.browser.msie )
$('#replycontainer, #replycontent', editRow).height(h-105);
else
$('#replycontainer', editRow).height(h-105);
$(t.o).after(editRow.hide()).fadeOut('fast', function(){
$('#replyrow').fadeIn('fast');
});
} else {
$('#edithead, #savebtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
$(t.o).after(editRow);
$('#replyrow').hide().fadeIn('fast');
}
if ( ! $.browser.msie )
$('#replycontainer').resizable({
handles : 's',
axis : 'y',
minHeight : 80,
stop : function() {
$('#replycontainer').width('auto');
}
});
setTimeout(function() {
var rtop, rbottom, scrollTop, vp, scrollBottom;
rtop = $('#replyrow').offset().top;
rbottom = rtop + $('#replyrow').height();
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
vp = document.documentElement.clientHeight || self.innerHeight || 0;
scrollBottom = scrollTop + vp;
if ( scrollBottom - 20 < rbottom )
window.scroll(0, rbottom - vp + 35);
else if ( rtop - 20 < scrollTop )
window.scroll(0, rtop - 35);
$('#replycontent').focus().keyup(function(e){
if (e.which == 27) commentReply.revert(); // close on Escape
});
}, 600);
return false;
},
send : function() {
var post = {};
$('#replysubmit .waiting').show();
$('#replyrow input').each(function() {
post[ $(this).attr('name') ] = $(this).val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
$.ajax({
type : 'POST',
url : wpListL10n.url,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var r, c, id, bg;
if ( typeof(xml) == 'string' ) {
this.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
this.error({'responseText': wpAjax.broken});
return false;
}
if ( 'edit-comment' == this.act )
$(this.o).remove();
r = r.responses[0];
c = r.data;
$(c).hide()
$('#replyrow').after(c);
this.o = id = '#comment-'+r.id;
this.revert();
this.addEvents($(id));
bg = $(id).hasClass('unapproved') ? '#ffffe0' : '#fff';
$(id)
.animate( { 'backgroundColor':'#CCEEBB' }, 600 )
.animate( { 'backgroundColor': bg }, 600 );
$.fn.wpList.process($(id))
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .waiting').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$('span.delete a.delete').click(function(){return false;});
if ( typeof QTags != 'undefined' )
ed_reply = new QTags('ed_reply', 'replycontent', 'replycontainer', 'more');
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.'+which+'.page-numbers');
if (l.length)
window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
}
};
edit_comment = function(event, current_row) {
window.location = $('span.edit a', current_row).attr('href');
};
toggle_all = function() {
toggleWithKeyboard = true;
$('#comments-form thead #cb input:checkbox').click().attr('checked', '');
toggleWithKeyboard = false;
}
make_bulk = function(value) {
return function(event, _) {
$('option[value='+value+']').attr('selected', 'selected');
$('form#comments-form')[0].submit();
}
};
$.table_hotkeys($('table.widefat'),['a', 'u', 's', 'd', 'r', 'q', ['e', edit_comment],
['shift+a', make_bulk('approve')], ['shift+s', make_bulk('markspam')],
['shift+d', make_bulk('delete')], ['shift+x', toggle_all],
['shift+u', make_bulk('unapprove')]],
{highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last,
prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next')}
);
}
});
})(jQuery);
larscapo/wp-admin/js/postbox.js 0000644 0041054 0041055 00000005343 11225447103 017265 0 ustar lacunaus lacunaus var postboxes;(function(a){postboxes={add_postbox_toggles:function(c,b){this.init(c,b);a(".postbox h3, .postbox .handlediv").click(function(){var e=a(this).parent(".postbox"),f=e.attr("id");e.toggleClass("closed");postboxes.save_state(c);if(f){if(!e.hasClass("closed")&&a.isFunction(postboxes.pbshow)){postboxes.pbshow(f)}else{if(e.hasClass("closed")&&a.isFunction(postboxes.pbhide)){postboxes.pbhide(f)}}}});a(".postbox h3 a").click(function(f){f.stopPropagation()});a(".hide-postbox-tog").click(function(){var e=a(this).val();if(a(this).attr("checked")){a("#"+e).show();if(a.isFunction(postboxes.pbshow)){postboxes.pbshow(e)}}else{a("#"+e).hide();if(a.isFunction(postboxes.pbhide)){postboxes.pbhide(e)}}postboxes.save_state(c)});a('.columns-prefs input[type="radio"]').click(function(){var e=a(this).val(),f,g,h=a("#poststuff");if(h.length){if(e==2){h.addClass("has-right-sidebar");a("#side-sortables").addClass("temp-border")}else{if(e==1){h.removeClass("has-right-sidebar");a("#normal-sortables").append(a("#side-sortables").children(".postbox"))}}}else{for(f=4;(f>e&&f>1);f--){g=a("#"+d(f)+"-sortables");a("#"+d(f-1)+"-sortables").append(g.children(".postbox"));g.parent().hide()}for(f=1;f<=e;f++){g=a("#"+d(f)+"-sortables");if(g.parent().is(":hidden")){g.addClass("temp-border").parent().show()}}a(".postbox-container:visible").css("width",98/e+"%")}postboxes.save_order(c)});function d(e){switch(e){case 1:return"normal";break;case 2:return"side";break;case 3:return"column3";break;case 4:return"column4";break;default:return""}}},init:function(c,b){a.extend(this,b||{});a("#wpbody-content").css("overflow","hidden");a(".meta-box-sortables").sortable({placeholder:"sortable-placeholder",connectWith:".meta-box-sortables",items:".postbox",handle:".hndle",cursor:"move",distance:2,tolerance:"pointer",forcePlaceholderSize:true,helper:"clone",opacity:0.65,start:function(f,d){a("body").css({WebkitUserSelect:"none",KhtmlUserSelect:"none"})},stop:function(f,d){postboxes.save_order(c);d.item.parent().removeClass("temp-border");a("body").css({WebkitUserSelect:"",KhtmlUserSelect:""})}})},save_state:function(d){var b=a(".postbox").filter(".closed").map(function(){return this.id}).get().join(","),c=a(".postbox").filter(":hidden").map(function(){return this.id}).get().join(",");a.post(postboxL10n.requestFile,{action:"closed-postboxes",closed:b,hidden:c,closedpostboxesnonce:jQuery("#closedpostboxesnonce").val(),page:d})},save_order:function(c){var b,d=a(".columns-prefs input:checked").val()||0;b={action:"meta-box-order",_ajax_nonce:a("#meta-box-order-nonce").val(),page_columns:d,page:c};a(".meta-box-sortables").each(function(){b["order["+this.id.split("-")[0]+"]"]=a(this).sortable("toArray").join(",")});a.post(postboxL10n.requestFile,b)},pbshow:false,pbhide:false}}(jQuery)); larscapo/wp-admin/js/dashboard.dev.js 0000644 0041054 0041055 00000004122 11225447103 020265 0 ustar lacunaus lacunaus var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad;
jQuery(document).ready( function($) {
// These widgets are sometimes populated via ajax
ajaxWidgets = [
'dashboard_incoming_links',
'dashboard_primary',
'dashboard_secondary',
'dashboard_plugins'
];
ajaxPopulateWidgets = function(el) {
show = function(id, i) {
var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading');
if ( e.length ) {
p = e.parent();
setTimeout( function(){
p.load('index-extra.php?jax=' + id, '', function() {
p.hide().slideDown('normal', function(){
$(this).css('display', '');
if ( 'dashboard_plugins' == id && $.isFunction(tb_init) )
tb_init('#dashboard_plugins a.thickbox');
});
});
}, i * 500 );
}
}
if ( el ) {
el = el.toString();
if ( $.inArray(el, ajaxWidgets) != -1 )
show(el, 0);
} else {
$.each( ajaxWidgets, function(i) {
show(this, i);
});
}
};
ajaxPopulateWidgets();
postboxes.add_postbox_toggles('dashboard', { pbshow: ajaxPopulateWidgets } );
/* QuickPress */
quickPressLoad = function() {
var act = $('#quickpost-action'), t;
t = $('#quick-press').submit( function() {
$('#dashboard_quick_press h3').append( '' );
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr('disabled','disabled');
if ( 'post' == act.val() ) {
act.val( 'post-quickpress-publish' );
}
$('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() {
$('#dashboard_quick_press h3 img').remove();
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').attr('disabled','');
$('#dashboard_quick_press ul').find('li').each( function() {
$('#dashboard_recent_drafts ul').prepend( this );
} ).end().remove();
tb_init('a.thickbox');
quickPressLoad();
} );
return false;
} );
$('#publish').click( function() { act.val( 'post-quickpress-publish' ); } );
};
quickPressLoad();
} );
larscapo/wp-admin/js/postbox.dev.js 0000644 0041054 0041055 00000007663 11225447103 020051 0 ustar lacunaus lacunaus var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page,args) {
this.init(page,args);
$('.postbox h3, .postbox .handlediv').click( function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
p.toggleClass('closed');
postboxes.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
postboxes.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
postboxes.pbhide(id);
}
} );
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
} );
$('.hide-postbox-tog').click( function() {
var box = $(this).val();
if ( $(this).attr('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
postboxes.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
postboxes.pbhide( box );
}
postboxes.save_state(page);
} );
$('.columns-prefs input[type="radio"]').click(function(){
var num = $(this).val(), i, el, p = $('#poststuff');
if ( p.length ) { // write pages
if ( num == 2 ) {
p.addClass('has-right-sidebar');
$('#side-sortables').addClass('temp-border');
} else if ( num == 1 ) {
p.removeClass('has-right-sidebar');
$('#normal-sortables').append($('#side-sortables').children('.postbox'));
}
} else { // dashboard
for ( i = 4; ( i > num && i > 1 ); i-- ) {
el = $('#' + colname(i) + '-sortables');
$('#' + colname(i-1) + '-sortables').append(el.children('.postbox'));
el.parent().hide();
}
for ( i = 1; i <= num; i++ ) {
el = $('#' + colname(i) + '-sortables');
if ( el.parent().is(':hidden') )
el.addClass('temp-border').parent().show();
}
$('.postbox-container:visible').css('width', 98/num + '%');
}
postboxes.save_order(page);
});
function colname(n) {
switch (n) {
case 1:
return 'normal';
break
case 2:
return 'side';
break
case 3:
return 'column3';
break
case 4:
return 'column4';
break
default:
return '';
}
}
},
init : function(page, args) {
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
start: function(e,ui) {
$('body').css({
WebkitUserSelect: 'none',
KhtmlUserSelect: 'none'
});
/*
if ( $.browser.msie )
return;
ui.item.addClass('noclick');
*/
},
stop: function(e,ui) {
postboxes.save_order(page);
ui.item.parent().removeClass('temp-border');
$('body').css({
WebkitUserSelect: '',
KhtmlUserSelect: ''
});
}
});
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(postboxL10n.requestFile, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
}
$('.meta-box-sortables').each( function() {
postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(',');
} );
$.post( postboxL10n.requestFile, postVars );
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
larscapo/wp-admin/js/post.dev.js 0000644 0041054 0041055 00000034740 11225447103 017334 0 ustar lacunaus lacunaus // return an array with any duplicate, whitespace or values removed
function array_unique_noempty(a) {
var out = [];
jQuery.each( a, function(key, val) {
val = jQuery.trim(val);
if ( val && jQuery.inArray(val, out) == -1 )
out.push(val);
} );
return out;
}
function new_tag_remove_tag() {
var id = jQuery( this ).attr( 'id' ), num = id.split('-check-num-')[1], taxbox = jQuery(this).parents('.tagsdiv'), current_tags = taxbox.find( '.the-tags' ).val().split(','), new_tags = [];
delete current_tags[num];
jQuery.each( current_tags, function(key, val) {
val = jQuery.trim(val);
if ( val ) {
new_tags.push(val);
}
});
taxbox.find('.the-tags').val( new_tags.join(',').replace(/\s*,+\s*/, ',').replace(/,+/, ',').replace(/,+\s+,+/, ',').replace(/,+\s*$/, '').replace(/^\s*,+/, '') );
tag_update_quickclicks(taxbox);
return false;
}
function tag_update_quickclicks(taxbox) {
if ( jQuery(taxbox).find('.the-tags').length == 0 )
return;
var current_tags = jQuery(taxbox).find('.the-tags').val().split(',');
jQuery(taxbox).find('.tagchecklist').empty();
shown = false;
jQuery.each( current_tags, function( key, val ) {
var txt, button_id;
val = jQuery.trim(val);
if ( !val.match(/^\s+$/) && '' != val ) {
button_id = jQuery(taxbox).attr('id') + '-check-num-' + key;
txt = 'X ' + val + ' ';
jQuery(taxbox).find('.tagchecklist').append(txt);
jQuery( '#' + button_id ).click( new_tag_remove_tag );
}
});
if ( shown )
jQuery(taxbox).find('.tagchecklist').prepend(''+postL10n.tagsUsed+' ');
}
function tag_flush_to_text(id, a) {
a = a || false;
var taxbox, text, tags, newtags;
taxbox = jQuery('#'+id);
text = a ? jQuery(a).text() : taxbox.find('input.newtag').val();
// is the input box empty (i.e. showing the 'Add new tag' tip)?
if ( taxbox.find('input.newtag').hasClass('form-input-tip') && ! a )
return false;
tags = taxbox.find('.the-tags').val();
newtags = tags ? tags + ',' + text : text;
// massage
newtags = newtags.replace(/\s+,+\s*/g, ',').replace(/,+/g, ',').replace(/,+\s+,+/g, ',').replace(/,+\s*$/g, '').replace(/^\s*,+/g, '');
newtags = array_unique_noempty(newtags.split(',')).join(',');
taxbox.find('.the-tags').val(newtags);
tag_update_quickclicks(taxbox);
if ( ! a )
taxbox.find('input.newtag').val('').focus();
return false;
}
function tag_save_on_publish() {
jQuery('.tagsdiv').each( function(i) {
if ( !jQuery(this).find('input.newtag').hasClass('form-input-tip') )
tag_flush_to_text(jQuery(this).parents('.tagsdiv').attr('id'));
} );
}
function tag_press_key( e ) {
if ( 13 == e.which ) {
tag_flush_to_text(jQuery(e.target).parents('.tagsdiv').attr('id'));
return false;
}
};
function tag_init() {
jQuery('.ajaxtag').show();
jQuery('.tagsdiv').each( function(i) {
tag_update_quickclicks(this);
} );
// add the quickadd form
jQuery('.ajaxtag input.tagadd').click(function(){tag_flush_to_text(jQuery(this).parents('.tagsdiv').attr('id'));});
jQuery('.ajaxtag input.newtag').focus(function() {
if ( !this.cleared ) {
this.cleared = true;
jQuery(this).val( '' ).removeClass( 'form-input-tip' );
}
});
jQuery('.ajaxtag input.newtag').blur(function() {
if ( this.value == '' ) {
this.cleared = false;
jQuery(this).val( postL10n.addTag ).addClass( 'form-input-tip' );
}
});
// auto-save tags on post save/publish
jQuery('#publish').click( tag_save_on_publish );
jQuery('#save-post').click( tag_save_on_publish );
// catch the enter key
jQuery('.ajaxtag input.newtag').keypress( tag_press_key );
}
var commentsBox, tagCloud;
(function($){
commentsBox = {
st : 0,
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$('#commentsdiv img.waiting').show();
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'post_ID' : $('#post_ID').val(),
'start' : st,
'num' : num
};
$.post(ajaxurl, data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$('#commentsdiv img.waiting').hide();
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$("a[className*=':']").unbind();
setCommentsList();
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').html(postL10n.showcomm);
return;
} else if ( 1 == r ) {
$('#show-comments').parent().html(postL10n.endcomm);
return;
}
$('#the-comment-list').append('
'+wpAjax.broken+'
');
}
);
return false;
}
};
tagCloud = {
init : function() {
$('.tagcloud-link').click(function(){
tagCloud.get($(this).attr('id'));
$(this).unbind().click(function(){
$(this).siblings('.the-tagcloud').toggle();
return false;
});
return false;
});
},
get : function(id) {
var tax = id.substr(id.indexOf('-')+1);
$.post(ajaxurl, {'action':'get-tagcloud','tax':tax}, function(r, stat) {
if ( 0 == r || 'success' != stat )
r = wpAjax.broken;
r = $('
response as $file => $plugin ) {
if ( $plugin->slug === $api->slug ) {
$type = 'update_available';
$update_file = $file;
break;
}
}
}
if ( 'install' == $type && is_dir( WP_PLUGIN_DIR . '/' . $api->slug ) ) {
$installed_plugin = get_plugins('/' . $api->slug);
if ( ! empty($installed_plugin) ) {
$key = array_shift( $key = array_keys($installed_plugin) ); //Use the first plugin regardless of the name, Could have issues for multiple-plugins in one directory if they share different version numbers
if ( version_compare($api->version, $installed_plugin[ $key ]['Version'], '=') ){
$type = 'latest_installed';
} elseif ( version_compare($api->version, $installed_plugin[ $key ]['Version'], '<') ) {
$type = 'newer_installed';
$newer_version = $installed_plugin[ $key ]['Version'];
} else {
//If the above update check failed, Then that probably means that the update checker has out-of-date information, force a refresh
delete_transient('update_plugins');
$update_file = $api->slug . '/' . $key; //This code branch only deals with a plugin which is in a folder the same name as its slug, Doesnt support plugins which have 'non-standard' names
$type = 'update_available';
}
}
}
switch ( $type ) :
default:
case 'install':
if ( current_user_can('install_plugins') ) :
?>
\n";
iframe_footer();
exit;
}
larscapo/wp-admin/includes/plugin.php 0000644 0041054 0041055 00000110206 11225447103 020425 0 ustar lacunaus lacunaus
* /*
* Plugin Name: Name of Plugin
* Plugin URI: Link to plugin information
* Description: Plugin Description
* Author: Plugin author's name
* Author URI: Link to the author's web site
* Version: Must be set in the plugin for WordPress 2.3+
* Text Domain: Optional. Unique identifier, should be same as the one used in
* plugin_text_domain()
* Domain Path: Optional. Only useful if the translations are located in a
* folder above the plugin's base path. For example, if .mo files are
* located in the locale folder then Domain Path will be "/locale/" and
* must have the first slash. Defaults to the base folder the plugin is
* located in.
* * / # Remove the space to close comment
*
*
* Plugin data returned array contains the following:
* 'Name' - Name of the plugin, must be unique.
* 'Title' - Title of the plugin and the link to the plugin's web site.
* 'Description' - Description of what the plugin does and/or notes
* from the author.
* 'Author' - The author's name
* 'AuthorURI' - The authors web site address.
* 'Version' - The plugin version number.
* 'PluginURI' - Plugin web site address.
* 'TextDomain' - Plugin's text domain for localization.
* 'DomainPath' - Plugin's relative directory path to .mo files.
*
* Some users have issues with opening large files and manipulating the contents
* for want is usually the first 1kiB or 2kiB. This function stops pulling in
* the plugin contents when it has all of the required plugin data.
*
* The first 8kiB of the file will be pulled in and if the plugin data is not
* within that first 8kiB, then the plugin author should correct their plugin
* and move the plugin data headers to the top.
*
* The plugin file is assumed to have permissions to allow for scripts to read
* the file. This is not checked however and the file is only opened for
* reading.
*
* @link http://trac.wordpress.org/ticket/5651 Previous Optimizations.
* @link http://trac.wordpress.org/ticket/7372 Further and better Optimizations.
* @since 1.5.0
*
* @param string $plugin_file Path to the plugin file
* @param bool $markup If the returned data should have HTML markup applied
* @param bool $translate If the returned data should be translated
* @return array See above for description.
*/
function get_plugin_data( $plugin_file, $markup = true, $translate = true ) {
// We don't need to write to the file, so just open for reading.
$fp = fopen($plugin_file, 'r');
// Pull only the first 8kiB of the file in.
$plugin_data = fread( $fp, 8192 );
// PHP will close file handle, but we are good citizens.
fclose($fp);
preg_match( '|Plugin Name:(.*)$|mi', $plugin_data, $name );
preg_match( '|Plugin URI:(.*)$|mi', $plugin_data, $uri );
preg_match( '|Version:(.*)|i', $plugin_data, $version );
preg_match( '|Description:(.*)$|mi', $plugin_data, $description );
preg_match( '|Author:(.*)$|mi', $plugin_data, $author_name );
preg_match( '|Author URI:(.*)$|mi', $plugin_data, $author_uri );
preg_match( '|Text Domain:(.*)$|mi', $plugin_data, $text_domain );
preg_match( '|Domain Path:(.*)$|mi', $plugin_data, $domain_path );
foreach ( array( 'name', 'uri', 'version', 'description', 'author_name', 'author_uri', 'text_domain', 'domain_path' ) as $field ) {
if ( !empty( ${$field} ) )
${$field} = _cleanup_header_comment(${$field}[1]);
else
${$field} = '';
}
$plugin_data = array(
'Name' => $name, 'Title' => $name, 'PluginURI' => $uri, 'Description' => $description,
'Author' => $author_name, 'AuthorURI' => $author_uri, 'Version' => $version,
'TextDomain' => $text_domain, 'DomainPath' => $domain_path
);
if ( $markup || $translate )
$plugin_data = _get_plugin_data_markup_translate($plugin_file, $plugin_data, $markup, $translate);
return $plugin_data;
}
function _get_plugin_data_markup_translate($plugin_file, $plugin_data, $markup = true, $translate = true) {
//Translate fields
if( $translate && ! empty($plugin_data['TextDomain']) ) {
if( ! empty( $plugin_data['DomainPath'] ) )
load_plugin_textdomain($plugin_data['TextDomain'], dirname($plugin_file). $plugin_data['DomainPath']);
else
load_plugin_textdomain($plugin_data['TextDomain'], dirname($plugin_file));
foreach ( array('Name', 'PluginURI', 'Description', 'Author', 'AuthorURI', 'Version') as $field )
$plugin_data[ $field ] = translate($plugin_data[ $field ], $plugin_data['TextDomain']);
}
//Apply Markup
if ( $markup ) {
if ( ! empty($plugin_data['PluginURI']) && ! empty($plugin_data['Name']) )
$plugin_data['Title'] = '' . $plugin_data['Name'] . '';
else
$plugin_data['Title'] = $plugin_data['Name'];
if ( ! empty($plugin_data['AuthorURI']) && ! empty($plugin_data['Author']) )
$plugin_data['Author'] = '' . $plugin_data['Author'] . '';
$plugin_data['Description'] = wptexturize( $plugin_data['Description'] );
if( ! empty($plugin_data['Author']) )
$plugin_data['Description'] .= ' ' . sprintf( __('By %s'), $plugin_data['Author'] ) . '.';
}
$plugins_allowedtags = array('a' => array('href' => array(),'title' => array()),'abbr' => array('title' => array()),'acronym' => array('title' => array()),'code' => array(),'em' => array(),'strong' => array());
// Sanitize all displayed data
$plugin_data['Title'] = wp_kses($plugin_data['Title'], $plugins_allowedtags);
$plugin_data['Version'] = wp_kses($plugin_data['Version'], $plugins_allowedtags);
$plugin_data['Description'] = wp_kses($plugin_data['Description'], $plugins_allowedtags);
$plugin_data['Author'] = wp_kses($plugin_data['Author'], $plugins_allowedtags);
return $plugin_data;
}
/**
* Get a list of a plugin's files.
*
* @since 2.8.0
*
* @param string $plugin Plugin ID
* @return array List of files relative to the plugin root.
*/
function get_plugin_files($plugin) {
$plugin_file = WP_PLUGIN_DIR . '/' . $plugin;
$dir = dirname($plugin_file);
$plugin_files = array($plugin);
if ( is_dir($dir) && $dir != WP_PLUGIN_DIR ) {
$plugins_dir = @ opendir( $dir );
if ( $plugins_dir ) {
while (($file = readdir( $plugins_dir ) ) !== false ) {
if ( substr($file, 0, 1) == '.' )
continue;
if ( is_dir( $dir . '/' . $file ) ) {
$plugins_subdir = @ opendir( $dir . '/' . $file );
if ( $plugins_subdir ) {
while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( substr($subfile, 0, 1) == '.' )
continue;
$plugin_files[] = plugin_basename("$dir/$file/$subfile");
}
@closedir( $plugins_subdir );
}
} else {
if ( plugin_basename("$dir/$file") != $plugin )
$plugin_files[] = plugin_basename("$dir/$file");
}
}
@closedir( $plugins_dir );
}
}
return $plugin_files;
}
/**
* Check the plugins directory and retrieve all plugin files with plugin data.
*
* WordPress only supports plugin files in the base plugins directory
* (wp-content/plugins) and in one directory above the plugins directory
* (wp-content/plugins/my-plugin). The file it looks for has the plugin data and
* must be found in those two locations. It is recommended that do keep your
* plugin files in directories.
*
* The file with the plugin data is the file that will be included and therefore
* needs to have the main execution for the plugin. This does not mean
* everything must be contained in the file and it is recommended that the file
* be split for maintainability. Keep everything in one file for extreme
* optimization purposes.
*
* @since unknown
*
* @param string $plugin_folder Optional. Relative path to single plugin folder.
* @return array Key is the plugin file path and the value is an array of the plugin data.
*/
function get_plugins($plugin_folder = '') {
if ( ! $cache_plugins = wp_cache_get('plugins', 'plugins') )
$cache_plugins = array();
if ( isset($cache_plugins[ $plugin_folder ]) )
return $cache_plugins[ $plugin_folder ];
$wp_plugins = array ();
$plugin_root = WP_PLUGIN_DIR;
if( !empty($plugin_folder) )
$plugin_root .= $plugin_folder;
// Files in wp-content/plugins directory
$plugins_dir = @ opendir( $plugin_root);
$plugin_files = array();
if ( $plugins_dir ) {
while (($file = readdir( $plugins_dir ) ) !== false ) {
if ( substr($file, 0, 1) == '.' )
continue;
if ( is_dir( $plugin_root.'/'.$file ) ) {
$plugins_subdir = @ opendir( $plugin_root.'/'.$file );
if ( $plugins_subdir ) {
while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( substr($subfile, 0, 1) == '.' )
continue;
if ( substr($subfile, -4) == '.php' )
$plugin_files[] = "$file/$subfile";
}
}
} else {
if ( substr($file, -4) == '.php' )
$plugin_files[] = $file;
}
}
}
@closedir( $plugins_dir );
@closedir( $plugins_subdir );
if ( !$plugins_dir || empty($plugin_files) )
return $wp_plugins;
foreach ( $plugin_files as $plugin_file ) {
if ( !is_readable( "$plugin_root/$plugin_file" ) )
continue;
$plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false ); //Do not apply markup/translate as it'll be cached.
if ( empty ( $plugin_data['Name'] ) )
continue;
$wp_plugins[plugin_basename( $plugin_file )] = $plugin_data;
}
uasort( $wp_plugins, create_function( '$a, $b', 'return strnatcasecmp( $a["Name"], $b["Name"] );' ));
$cache_plugins[ $plugin_folder ] = $wp_plugins;
wp_cache_set('plugins', $cache_plugins, 'plugins');
return $wp_plugins;
}
/**
* Check whether the plugin is active by checking the active_plugins list.
*
* @since 2.5.0
*
* @param string $plugin Base plugin path from plugins directory.
* @return bool True, if in the active plugins list. False, not in the list.
*/
function is_plugin_active($plugin) {
return in_array($plugin, get_option('active_plugins'));
}
/**
* Attempts activation of plugin in a "sandbox" and redirects on success.
*
* A plugin that is already activated will not attempt to be activated again.
*
* The way it works is by setting the redirection to the error before trying to
* include the plugin file. If the plugin fails, then the redirection will not
* be overwritten with the success message. Also, the options will not be
* updated and the activation hook will not be called on plugin error.
*
* It should be noted that in no way the below code will actually prevent errors
* within the file. The code should not be used elsewhere to replicate the
* "sandbox", which uses redirection to work.
* {@source 13 1}
*
* If any errors are found or text is outputted, then it will be captured to
* ensure that the success redirection will update the error redirection.
*
* @since unknown
*
* @param string $plugin Plugin path to main plugin file with plugin data.
* @param string $redirect Optional. URL to redirect to.
* @return WP_Error|null WP_Error on invalid file or null on success.
*/
function activate_plugin($plugin, $redirect = '') {
$current = get_option('active_plugins');
$plugin = plugin_basename(trim($plugin));
$valid = validate_plugin($plugin);
if ( is_wp_error($valid) )
return $valid;
if ( !in_array($plugin, $current) ) {
if ( !empty($redirect) )
wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); // we'll override this later if the plugin can be included without fatal error
ob_start();
@include(WP_PLUGIN_DIR . '/' . $plugin);
$current[] = $plugin;
sort($current);
update_option('active_plugins', $current);
do_action('activate_' . $plugin);
ob_end_clean();
}
return null;
}
/**
* Deactivate a single plugin or multiple plugins.
*
* The deactivation hook is disabled by the plugin upgrader by using the $silent
* parameter.
*
* @since unknown
*
* @param string|array $plugins Single plugin or list of plugins to deactivate.
* @param bool $silent Optional, default is false. Prevent calling deactivate hook.
*/
function deactivate_plugins($plugins, $silent= false) {
$current = get_option('active_plugins');
if ( !is_array($plugins) )
$plugins = array($plugins);
foreach ( $plugins as $plugin ) {
$plugin = plugin_basename($plugin);
if( ! is_plugin_active($plugin) )
continue;
array_splice($current, array_search( $plugin, $current), 1 ); // Fixed Array-fu!
if ( ! $silent ) //Used by Plugin updater to internally deactivate plugin, however, not to notify plugins of the fact to prevent plugin output.
do_action('deactivate_' . trim( $plugin ));
}
update_option('active_plugins', $current);
}
/**
* Activate multiple plugins.
*
* When WP_Error is returned, it does not mean that one of the plugins had
* errors. It means that one or more of the plugins file path was invalid.
*
* The execution will be halted as soon as one of the plugins has an error.
*
* @since unknown
*
* @param string|array $plugins
* @param string $redirect Redirect to page after successful activation.
* @return bool|WP_Error True when finished or WP_Error if there were errors during a plugin activation.
*/
function activate_plugins($plugins, $redirect = '') {
if ( !is_array($plugins) )
$plugins = array($plugins);
$errors = array();
foreach ( (array) $plugins as $plugin ) {
if ( !empty($redirect) )
$redirect = add_query_arg('plugin', $plugin, $redirect);
$result = activate_plugin($plugin, $redirect);
if ( is_wp_error($result) )
$errors[$plugin] = $result;
}
if ( !empty($errors) )
return new WP_Error('plugins_invalid', __('One of the plugins is invalid.'), $errors);
return true;
}
/**
* Remove directory and files of a plugin for a single or list of plugin(s).
*
* If the plugins parameter list is empty, false will be returned. True when
* completed.
*
* @since unknown
*
* @param array $plugins List of plugin
* @param string $redirect Redirect to page when complete.
* @return mixed
*/
function delete_plugins($plugins, $redirect = '' ) {
global $wp_filesystem;
if( empty($plugins) )
return false;
$checked = array();
foreach( $plugins as $plugin )
$checked[] = 'checked[]=' . $plugin;
ob_start();
$url = wp_nonce_url('plugins.php?action=delete-selected&verify-delete=1&' . implode('&', $checked), 'bulk-manage-plugins');
if ( false === ($credentials = request_filesystem_credentials($url)) ) {
$data = ob_get_contents();
ob_end_clean();
if( ! empty($data) ){
include_once( ABSPATH . 'wp-admin/admin-header.php');
echo $data;
include( ABSPATH . 'wp-admin/admin-footer.php');
exit;
}
return;
}
if ( ! WP_Filesystem($credentials) ) {
request_filesystem_credentials($url, '', true); //Failed to connect, Error and request again
$data = ob_get_contents();
ob_end_clean();
if( ! empty($data) ){
include_once( ABSPATH . 'wp-admin/admin-header.php');
echo $data;
include( ABSPATH . 'wp-admin/admin-footer.php');
exit;
}
return;
}
if ( ! is_object($wp_filesystem) )
return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
return new WP_Error('fs_error', __('Filesystem error'), $wp_filesystem->errors);
//Get the base plugin folder
$plugins_dir = $wp_filesystem->wp_plugins_dir();
if ( empty($plugins_dir) )
return new WP_Error('fs_no_plugins_dir', __('Unable to locate WordPress Plugin directory.'));
$plugins_dir = trailingslashit( $plugins_dir );
$errors = array();
foreach( $plugins as $plugin_file ) {
// Run Uninstall hook
if ( is_uninstallable_plugin( $plugin_file ) )
uninstall_plugin($plugin_file);
$this_plugin_dir = trailingslashit( dirname($plugins_dir . $plugin_file) );
// If plugin is in its own directory, recursively delete the directory.
if ( strpos($plugin_file, '/') && $this_plugin_dir != $plugins_dir ) //base check on if plugin includes directory seperator AND that its not the root plugin folder
$deleted = $wp_filesystem->delete($this_plugin_dir, true);
else
$deleted = $wp_filesystem->delete($plugins_dir . $plugin_file);
if ( ! $deleted )
$errors[] = $plugin_file;
}
if ( ! empty($errors) )
return new WP_Error('could_not_remove_plugin', sprintf(__('Could not fully remove the plugin(s) %s'), implode(', ', $errors)) );
// Force refresh of plugin update information
if ( $current = get_transient('update_plugins') ) {
unset( $current->response[ $plugin_file ] );
set_transient('update_plugins', $current);
}
return true;
}
function validate_active_plugins() {
$check_plugins = get_option('active_plugins');
// Sanity check. If the active plugin list is not an array, make it an
// empty array.
if ( !is_array($check_plugins) ) {
update_option('active_plugins', array());
return;
}
//Invalid is any plugin that is deactivated due to error.
$invalid = array();
// If a plugin file does not exist, remove it from the list of active
// plugins.
foreach ( $check_plugins as $check_plugin ) {
$result = validate_plugin($check_plugin);
if ( is_wp_error( $result ) ) {
$invalid[$check_plugin] = $result;
deactivate_plugins( $check_plugin, true);
}
}
return $invalid;
}
/**
* Validate the plugin path.
*
* Checks that the file exists and {@link validate_file() is valid file}.
*
* @since unknown
*
* @param string $plugin Plugin Path
* @return WP_Error|int 0 on success, WP_Error on failure.
*/
function validate_plugin($plugin) {
if ( validate_file($plugin) )
return new WP_Error('plugin_invalid', __('Invalid plugin path.'));
if ( ! file_exists(WP_PLUGIN_DIR . '/' . $plugin) )
return new WP_Error('plugin_not_found', __('Plugin file does not exist.'));
$installed_plugins = get_plugins();
if ( ! isset($installed_plugins[$plugin]) )
return new WP_Error('no_plugin_header', __('The plugin does not have a valid header.'));
return 0;
}
/**
* Whether the plugin can be uninstalled.
*
* @since 2.7.0
*
* @param string $plugin Plugin path to check.
* @return bool Whether plugin can be uninstalled.
*/
function is_uninstallable_plugin($plugin) {
$file = plugin_basename($plugin);
$uninstallable_plugins = (array) get_option('uninstall_plugins');
if ( isset( $uninstallable_plugins[$file] ) || file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) )
return true;
return false;
}
/**
* Uninstall a single plugin.
*
* Calls the uninstall hook, if it is available.
*
* @since 2.7.0
*
* @param string $plugin Relative plugin path from Plugin Directory.
*/
function uninstall_plugin($plugin) {
$file = plugin_basename($plugin);
$uninstallable_plugins = (array) get_option('uninstall_plugins');
if ( file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) ) {
if ( isset( $uninstallable_plugins[$file] ) ) {
unset($uninstallable_plugins[$file]);
update_option('uninstall_plugins', $uninstallable_plugins);
}
unset($uninstallable_plugins);
define('WP_UNINSTALL_PLUGIN', $file);
include WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php';
return true;
}
if ( isset( $uninstallable_plugins[$file] ) ) {
$callable = $uninstallable_plugins[$file];
unset($uninstallable_plugins[$file]);
update_option('uninstall_plugins', $uninstallable_plugins);
unset($uninstallable_plugins);
include WP_PLUGIN_DIR . '/' . $file;
add_action( 'uninstall_' . $file, $callable );
do_action( 'uninstall_' . $file );
}
}
//
// Menu
//
function add_menu_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '' ) {
global $menu, $admin_page_hooks, $_registered_pages;
$file = plugin_basename( $file );
$admin_page_hooks[$file] = sanitize_title( $menu_title );
$hookname = get_plugin_page_hookname( $file, '' );
if (!empty ( $function ) && !empty ( $hookname ))
add_action( $hookname, $function );
if ( empty($icon_url) )
$icon_url = 'images/generic.png';
elseif ( is_ssl() && 0 === strpos($icon_url, 'http://') )
$icon_url = 'https://' . substr($icon_url, 7);
$menu[] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url );
$_registered_pages[$hookname] = true;
return $hookname;
}
function add_object_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '') {
global $menu, $admin_page_hooks, $_wp_last_object_menu, $_registered_pages;
$file = plugin_basename( $file );
$admin_page_hooks[$file] = sanitize_title( $menu_title );
$hookname = get_plugin_page_hookname( $file, '' );
if (!empty ( $function ) && !empty ( $hookname ))
add_action( $hookname, $function );
if ( empty($icon_url) )
$icon_url = 'images/generic.png';
$_wp_last_object_menu++;
$menu[$_wp_last_object_menu] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url );
$_registered_pages[$hookname] = true;
return $hookname;
}
function add_utility_page( $page_title, $menu_title, $access_level, $file, $function = '', $icon_url = '') {
global $menu, $admin_page_hooks, $_wp_last_utility_menu, $_registered_pages;
$file = plugin_basename( $file );
$admin_page_hooks[$file] = sanitize_title( $menu_title );
$hookname = get_plugin_page_hookname( $file, '' );
if (!empty ( $function ) && !empty ( $hookname ))
add_action( $hookname, $function );
if ( empty($icon_url) )
$icon_url = 'images/generic.png';
elseif ( is_ssl() && 0 === strpos($icon_url, 'http://') )
$icon_url = 'https://' . substr($icon_url, 7);
$_wp_last_utility_menu++;
$menu[$_wp_last_utility_menu] = array ( $menu_title, $access_level, $file, $page_title, 'menu-top ' . $hookname, $hookname, $icon_url );
$_registered_pages[$hookname] = true;
return $hookname;
}
function add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function = '' ) {
global $submenu;
global $menu;
global $_wp_real_parent_file;
global $_wp_submenu_nopriv;
global $_registered_pages;
$file = plugin_basename( $file );
$parent = plugin_basename( $parent);
if ( isset( $_wp_real_parent_file[$parent] ) )
$parent = $_wp_real_parent_file[$parent];
if ( !current_user_can( $access_level ) ) {
$_wp_submenu_nopriv[$parent][$file] = true;
return false;
}
// If the parent doesn't already have a submenu, add a link to the parent
// as the first item in the submenu. If the submenu file is the same as the
// parent file someone is trying to link back to the parent manually. In
// this case, don't automatically add a link back to avoid duplication.
if (!isset( $submenu[$parent] ) && $file != $parent ) {
foreach ( (array)$menu as $parent_menu ) {
if ( $parent_menu[2] == $parent && current_user_can( $parent_menu[1] ) )
$submenu[$parent][] = $parent_menu;
}
}
$submenu[$parent][] = array ( $menu_title, $access_level, $file, $page_title );
$hookname = get_plugin_page_hookname( $file, $parent);
if (!empty ( $function ) && !empty ( $hookname ))
add_action( $hookname, $function );
$_registered_pages[$hookname] = true;
// backwards-compatibility for plugins using add_management page. See wp-admin/admin.php for redirect from edit.php to tools.php
if ( 'tools.php' == $parent )
$_registered_pages[get_plugin_page_hookname( $file, 'edit.php')] = true;
return $hookname;
}
/**
* Add sub menu page to the tools main menu.
*
* @param string $page_title
* @param unknown_type $menu_title
* @param unknown_type $access_level
* @param unknown_type $file
* @param unknown_type $function
* @return unknown
*/
function add_management_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'tools.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_options_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'options-general.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_theme_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'themes.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_users_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
if ( current_user_can('edit_users') )
$parent = 'users.php';
else
$parent = 'profile.php';
return add_submenu_page( $parent, $page_title, $menu_title, $access_level, $file, $function );
}
function add_dashboard_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'index.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_posts_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'edit.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_media_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'upload.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_links_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'link-manager.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_pages_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'edit-pages.php', $page_title, $menu_title, $access_level, $file, $function );
}
function add_comments_page( $page_title, $menu_title, $access_level, $file, $function = '' ) {
return add_submenu_page( 'edit-comments.php', $page_title, $menu_title, $access_level, $file, $function );
}
//
// Pluggable Menu Support -- Private
//
function get_admin_page_parent( $parent = '' ) {
global $parent_file;
global $menu;
global $submenu;
global $pagenow;
global $plugin_page;
global $_wp_real_parent_file;
global $_wp_menu_nopriv;
global $_wp_submenu_nopriv;
if ( !empty ( $parent ) && 'admin.php' != $parent ) {
if ( isset( $_wp_real_parent_file[$parent] ) )
$parent = $_wp_real_parent_file[$parent];
return $parent;
}
/*
if ( !empty ( $parent_file ) ) {
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
*/
if ( $pagenow == 'admin.php' && isset( $plugin_page ) ) {
foreach ( (array)$menu as $parent_menu ) {
if ( $parent_menu[2] == $plugin_page ) {
$parent_file = $plugin_page;
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
}
if ( isset( $_wp_menu_nopriv[$plugin_page] ) ) {
$parent_file = $plugin_page;
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) ) {
$parent_file = $pagenow;
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
foreach (array_keys( (array)$submenu ) as $parent) {
foreach ( $submenu[$parent] as $submenu_array ) {
if ( isset( $_wp_real_parent_file[$parent] ) )
$parent = $_wp_real_parent_file[$parent];
if ( $submenu_array[2] == $pagenow ) {
$parent_file = $parent;
return $parent;
} else
if ( isset( $plugin_page ) && ($plugin_page == $submenu_array[2] ) ) {
$parent_file = $parent;
return $parent;
}
}
}
if ( empty($parent_file) )
$parent_file = '';
return '';
}
function get_admin_page_title() {
global $title;
global $menu;
global $submenu;
global $pagenow;
global $plugin_page;
if ( isset( $title ) && !empty ( $title ) ) {
return $title;
}
$hook = get_plugin_page_hook( $plugin_page, $pagenow );
$parent = $parent1 = get_admin_page_parent();
if ( empty ( $parent) ) {
foreach ( (array)$menu as $menu_array ) {
if ( isset( $menu_array[3] ) ) {
if ( $menu_array[2] == $pagenow ) {
$title = $menu_array[3];
return $menu_array[3];
} else
if ( isset( $plugin_page ) && ($plugin_page == $menu_array[2] ) && ($hook == $menu_array[3] ) ) {
$title = $menu_array[3];
return $menu_array[3];
}
} else {
$title = $menu_array[0];
return $title;
}
}
} else {
foreach (array_keys( $submenu ) as $parent) {
foreach ( $submenu[$parent] as $submenu_array ) {
if ( isset( $plugin_page ) &&
($plugin_page == $submenu_array[2] ) &&
(($parent == $pagenow ) || ($parent == $plugin_page ) || ($plugin_page == $hook ) || (($pagenow == 'admin.php' ) && ($parent1 != $submenu_array[2] ) ) )
) {
$title = $submenu_array[3];
return $submenu_array[3];
}
if ( $submenu_array[2] != $pagenow || isset( $_GET['page'] ) ) // not the current page
continue;
if ( isset( $submenu_array[3] ) ) {
$title = $submenu_array[3];
return $submenu_array[3];
} else {
$title = $submenu_array[0];
return $title;
}
}
}
if ( !isset($title) || empty ( $title ) ) {
foreach ( $menu as $menu_array ) {
if ( isset( $plugin_page ) &&
($plugin_page == $menu_array[2] ) &&
($pagenow == 'admin.php' ) &&
($parent1 == $menu_array[2] ) )
{
$title = $menu_array[3];
return $menu_array[3];
}
}
}
}
return $title;
}
function get_plugin_page_hook( $plugin_page, $parent_page ) {
$hook = get_plugin_page_hookname( $plugin_page, $parent_page );
if ( has_action($hook) )
return $hook;
else
return null;
}
function get_plugin_page_hookname( $plugin_page, $parent_page ) {
global $admin_page_hooks;
$parent = get_admin_page_parent( $parent_page );
$page_type = 'admin';
if ( empty ( $parent_page ) || 'admin.php' == $parent_page || isset( $admin_page_hooks[$plugin_page] ) ) {
if ( isset( $admin_page_hooks[$plugin_page] ) )
$page_type = 'toplevel';
else
if ( isset( $admin_page_hooks[$parent] ))
$page_type = $admin_page_hooks[$parent];
} else if ( isset( $admin_page_hooks[$parent] ) ) {
$page_type = $admin_page_hooks[$parent];
}
$plugin_name = preg_replace( '!\.php!', '', $plugin_page );
return $page_type.'_page_'.$plugin_name;
}
function user_can_access_admin_page() {
global $pagenow;
global $menu;
global $submenu;
global $_wp_menu_nopriv;
global $_wp_submenu_nopriv;
global $plugin_page;
global $_registered_pages;
$parent = get_admin_page_parent();
if ( !isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$pagenow] ) )
return false;
if ( isset( $plugin_page ) ) {
if ( isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) )
return false;
$hookname = get_plugin_page_hookname($plugin_page, $parent);
if ( !isset($_registered_pages[$hookname]) )
return false;
}
if ( empty( $parent) ) {
if ( isset( $_wp_menu_nopriv[$pagenow] ) )
return false;
if ( isset( $_wp_submenu_nopriv[$pagenow][$pagenow] ) )
return false;
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) )
return false;
if ( isset( $plugin_page ) && isset( $_wp_menu_nopriv[$plugin_page] ) )
return false;
foreach (array_keys( $_wp_submenu_nopriv ) as $key ) {
if ( isset( $_wp_submenu_nopriv[$key][$pagenow] ) )
return false;
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$key][$plugin_page] ) )
return false;
}
return true;
}
if ( isset( $plugin_page ) && ( $plugin_page == $parent ) && isset( $_wp_menu_nopriv[$plugin_page] ) )
return false;
if ( isset( $submenu[$parent] ) ) {
foreach ( $submenu[$parent] as $submenu_array ) {
if ( isset( $plugin_page ) && ( $submenu_array[2] == $plugin_page ) ) {
if ( current_user_can( $submenu_array[1] ))
return true;
else
return false;
} else if ( $submenu_array[2] == $pagenow ) {
if ( current_user_can( $submenu_array[1] ))
return true;
else
return false;
}
}
}
foreach ( $menu as $menu_array ) {
if ( $menu_array[2] == $parent) {
if ( current_user_can( $menu_array[1] ))
return true;
else
return false;
}
}
return true;
}
/* Whitelist functions */
/**
* Register a setting and its sanitization callback
*
* @since 2.7.0
*
* @param string $option_group A settings group name. Can be anything.
* @param string $option_name The name of an option to sanitize and save.
* @param unknown_type $sanitize_callback A callback function that sanitizes the option's value.
* @return unknown
*/
function register_setting($option_group, $option_name, $sanitize_callback = '') {
return add_option_update_handler($option_group, $option_name, $sanitize_callback);
}
/**
* Unregister a setting
*
* @since 2.7.0
*
* @param unknown_type $option_group
* @param unknown_type $option_name
* @param unknown_type $sanitize_callback
* @return unknown
*/
function unregister_setting($option_group, $option_name, $sanitize_callback = '') {
return remove_option_update_handler($option_group, $option_name, $sanitize_callback);
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $option_group
* @param unknown_type $option_name
* @param unknown_type $sanitize_callback
*/
function add_option_update_handler($option_group, $option_name, $sanitize_callback = '') {
global $new_whitelist_options;
$new_whitelist_options[ $option_group ][] = $option_name;
if ( $sanitize_callback != '' )
add_filter( "sanitize_option_{$option_name}", $sanitize_callback );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $option_group
* @param unknown_type $option_name
* @param unknown_type $sanitize_callback
*/
function remove_option_update_handler($option_group, $option_name, $sanitize_callback = '') {
global $new_whitelist_options;
$pos = array_search( $option_name, (array) $new_whitelist_options );
if ( $pos !== false )
unset( $new_whitelist_options[ $option_group ][ $pos ] );
if ( $sanitize_callback != '' )
remove_filter( "sanitize_option_{$option_name}", $sanitize_callback );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $options
* @return unknown
*/
function option_update_filter( $options ) {
global $new_whitelist_options;
if ( is_array( $new_whitelist_options ) )
$options = add_option_whitelist( $new_whitelist_options, $options );
return $options;
}
add_filter( 'whitelist_options', 'option_update_filter' );
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $new_options
* @param unknown_type $options
* @return unknown
*/
function add_option_whitelist( $new_options, $options = '' ) {
if( $options == '' ) {
global $whitelist_options;
} else {
$whitelist_options = $options;
}
foreach( $new_options as $page => $keys ) {
foreach( $keys as $key ) {
if ( !isset($whitelist_options[ $page ]) || !is_array($whitelist_options[ $page ]) ) {
$whitelist_options[ $page ] = array();
$whitelist_options[ $page ][] = $key;
} else {
$pos = array_search( $key, $whitelist_options[ $page ] );
if ( $pos === false )
$whitelist_options[ $page ][] = $key;
}
}
}
return $whitelist_options;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $del_options
* @param unknown_type $options
* @return unknown
*/
function remove_option_whitelist( $del_options, $options = '' ) {
if( $options == '' ) {
global $whitelist_options;
} else {
$whitelist_options = $options;
}
foreach( $del_options as $page => $keys ) {
foreach( $keys as $key ) {
if ( isset($whitelist_options[ $page ]) && is_array($whitelist_options[ $page ]) ) {
$pos = array_search( $key, $whitelist_options[ $page ] );
if( $pos !== false )
unset( $whitelist_options[ $page ][ $pos ] );
}
}
}
return $whitelist_options;
}
/**
* Output nonce, action, and option_page fields for a settings page.
*
* @since 2.7.0
*
* @param string $option_group A settings group name. This should match the group name used in register_setting().
*/
function settings_fields($option_group) {
echo "";
echo '';
wp_nonce_field("$option_group-options");
}
?>
larscapo/wp-admin/includes/class-wp-filesystem-direct.php 0000644 0041054 0041055 00000016107 11225447103 024317 0 ustar lacunaus lacunaus method = 'direct';
$this->errors = new WP_Error();
}
function connect() {
return true;
}
function setDefaultPermissions($perm) {
$this->permission = $perm;
}
function get_contents($file) {
return @file_get_contents($file);
}
function get_contents_array($file) {
return @file($file);
}
function put_contents($file, $contents, $mode = false, $type = '') {
if ( ! ($fp = @fopen($file, 'w' . $type)) )
return false;
@fwrite($fp, $contents);
@fclose($fp);
$this->chmod($file,$mode);
return true;
}
function cwd() {
return @getcwd();
}
function chdir($dir) {
return @chdir($dir);
}
function chgrp($file, $group, $recursive = false) {
if ( ! $this->exists($file) )
return false;
if ( ! $recursive )
return @chgrp($file, $group);
if ( ! $this->is_dir($file) )
return @chgrp($file, $group);
//Is a directory, and we want recursive
$file = trailingslashit($file);
$filelist = $this->dirlist($file);
foreach ($filelist as $filename)
$this->chgrp($file . $filename, $group, $recursive);
return true;
}
function chmod($file, $mode = false, $recursive = false) {
if ( ! $this->exists($file) )
return false;
if ( ! $mode ) {
if ( $this->permission )
$mode = $this->permission;
elseif ( $this->is_file($file) )
$mode = FS_CHMOD_FILE;
elseif ( $this->is_dir($file) )
$mode = FS_CHMOD_DIR;
else
return false;
}
if ( ! $recursive )
return @chmod($file, $mode);
if ( ! $this->is_dir($file) )
return @chmod($file, $mode);
//Is a directory, and we want recursive
$file = trailingslashit($file);
$filelist = $this->dirlist($file);
foreach ($filelist as $filename)
$this->chmod($file . $filename, $mode, $recursive);
return true;
}
function chown($file, $owner, $recursive = false) {
if ( ! $this->exists($file) )
return false;
if ( ! $recursive )
return @chown($file, $owner);
if ( ! $this->is_dir($file) )
return @chown($file, $owner);
//Is a directory, and we want recursive
$filelist = $this->dirlist($file);
foreach ($filelist as $filename){
$this->chown($file . '/' . $filename, $owner, $recursive);
}
return true;
}
function owner($file) {
$owneruid = @fileowner($file);
if ( ! $owneruid )
return false;
if ( ! function_exists('posix_getpwuid') )
return $owneruid;
$ownerarray = posix_getpwuid($owneruid);
return $ownerarray['name'];
}
function getchmod($file) {
return substr(decoct(@fileperms($file)),3);
}
function group($file) {
$gid = @filegroup($file);
if ( ! $gid )
return false;
if ( ! function_exists('posix_getgrgid') )
return $gid;
$grouparray = posix_getgrgid($gid);
return $grouparray['name'];
}
function copy($source, $destination, $overwrite = false) {
if ( ! $overwrite && $this->exists($destination) )
return false;
return copy($source, $destination);
}
function move($source, $destination, $overwrite = false) {
//Possible to use rename()?
if ( $this->copy($source, $destination, $overwrite) && $this->exists($destination) ){
$this->delete($source);
return true;
} else {
return false;
}
}
function delete($file, $recursive = false) {
if ( empty($file) ) //Some filesystems report this as /, which can cause non-expected recursive deletion of all files in the filesystem.
return false;
$file = str_replace('\\', '/', $file); //for win32, occasional problems deleteing files otherwise
if ( $this->is_file($file) )
return @unlink($file);
if ( ! $recursive && $this->is_dir($file) )
return @rmdir($file);
//At this point its a folder, and we're in recursive mode
$file = trailingslashit($file);
$filelist = $this->dirlist($file, true);
$retval = true;
if ( is_array($filelist) ) //false if no files, So check first.
foreach ($filelist as $filename => $fileinfo)
if ( ! $this->delete($file . $filename, $recursive) )
$retval = false;
if ( file_exists($file) && ! @rmdir($file) )
$retval = false;
return $retval;
}
function exists($file) {
return @file_exists($file);
}
function is_file($file) {
return @is_file($file);
}
function is_dir($path) {
return @is_dir($path);
}
function is_readable($file) {
return @is_readable($file);
}
function is_writable($file) {
return @is_writable($file);
}
function atime($file) {
return @fileatime($file);
}
function mtime($file) {
return @filemtime($file);
}
function size($file) {
return @filesize($file);
}
function touch($file, $time = 0, $atime = 0){
if ($time == 0)
$time = time();
if ($atime == 0)
$atime = time();
return @touch($file, $time, $atime);
}
function mkdir($path, $chmod = false, $chown = false, $chgrp = false){
if ( ! @mkdir($path) )
return false;
$this->chmod($path, $chmod);
if ( $chown )
$this->chown($path, $chown);
if ( $chgrp )
$this->chgrp($path, $chgrp);
return true;
}
function rmdir($path, $recursive = false) {
//Currently unused and untested, Use delete() instead.
if ( ! $recursive )
return @rmdir($path);
//recursive:
$filelist = $this->dirlist($path);
foreach ($filelist as $filename => $det) {
if ( '/' == substr($filename, -1, 1) )
$this->rmdir($path . '/' . $filename, $recursive);
@rmdir($filename);
}
return @rmdir($path);
}
function dirlist($path, $incdot = false, $recursive = false) {
if ( $this->is_file($path) ) {
$limitFile = basename($path);
$path = dirname($path);
} else {
$limitFile = false;
}
if ( ! $this->is_dir($path) )
return false;
$ret = array();
$dir = @dir($path);
if ( ! $dir )
return false;
while (false !== ($entry = $dir->read()) ) {
$struc = array();
$struc['name'] = $entry;
if ( '.' == $struc['name'] || '..' == $struc['name'] )
continue; //Do not care about these folders.
if ( '.' == $struc['name'][0] && !$incdot)
continue;
if ( $limitFile && $struc['name'] != $limitFile)
continue;
$struc['perms'] = $this->gethchmod($path.'/'.$entry);
$struc['permsn'] = $this->getnumchmodfromh($struc['perms']);
$struc['number'] = false;
$struc['owner'] = $this->owner($path.'/'.$entry);
$struc['group'] = $this->group($path.'/'.$entry);
$struc['size'] = $this->size($path.'/'.$entry);
$struc['lastmodunix']= $this->mtime($path.'/'.$entry);
$struc['lastmod'] = date('M j',$struc['lastmodunix']);
$struc['time'] = date('h:i:s',$struc['lastmodunix']);
$struc['type'] = $this->is_dir($path.'/'.$entry) ? 'd' : 'f';
if ( 'd' == $struc['type'] ) {
if ( $recursive )
$struc['files'] = $this->dirlist($path . '/' . $struc['name'], $incdot, $recursive);
else
$struc['files'] = array();
}
$ret[ $struc['name'] ] = $struc;
}
$dir->close();
unset($dir);
return $ret;
}
}
?>
larscapo/wp-admin/includes/manifest.php 0000644 0041054 0041055 00000025320 11225447103 020737 0 ustar lacunaus lacunaus id || $wp_roles->role_objects[$_POST['role']]->has_cap( 'edit_users' ) ) {
// If the new role isn't editable by the logged-in user die with error
$editable_roles = get_editable_roles();
if (!$editable_roles[$_POST['role']])
wp_die(__('You can’t give users that role.'));
$user = new WP_User( $user_id );
$user->set_role( $_POST['role'] );
}
}
} else {
add_action( 'user_register', 'add_user' ); // See above
return edit_user();
}
}
/**
* Edit user settings based on contents of $_POST
*
* Used on user-edit.php and profile.php to manage and process user options, passwords etc.
*
* @since 2.0
*
* @param int $user_id Optional. User ID.
* @return int user id of the updated user
*/
function edit_user( $user_id = 0 ) {
global $current_user, $wp_roles, $wpdb;
if ( $user_id != 0 ) {
$update = true;
$user->ID = (int) $user_id;
$userdata = get_userdata( $user_id );
$user->user_login = $wpdb->escape( $userdata->user_login );
} else {
$update = false;
$user = '';
}
if ( isset( $_POST['user_login'] ))
$user->user_login = esc_html( trim( $_POST['user_login'] ));
$pass1 = $pass2 = '';
if ( isset( $_POST['pass1'] ))
$pass1 = $_POST['pass1'];
if ( isset( $_POST['pass2'] ))
$pass2 = $_POST['pass2'];
if ( isset( $_POST['role'] ) && current_user_can( 'edit_users' ) ) {
// Don't let anyone with 'edit_users' (admins) edit their own role to something without it.
if( $user_id != $current_user->id || $wp_roles->role_objects[$_POST['role']]->has_cap( 'edit_users' ))
$user->role = $_POST['role'];
// If the new role isn't editable by the logged-in user die with error
$editable_roles = get_editable_roles();
if (!$editable_roles[$_POST['role']])
wp_die(__('You can’t give users that role.'));
}
if ( isset( $_POST['email'] ))
$user->user_email = esc_html( trim( $_POST['email'] ));
if ( isset( $_POST['url'] ) ) {
if ( empty ( $_POST['url'] ) || $_POST['url'] == 'http://' ) {
$user->user_url = '';
} else {
$user->user_url = esc_url( trim( $_POST['url'] ));
$user->user_url = preg_match('/^(https?|ftps?|mailto|news|irc|gopher|nntp|feed|telnet):/is', $user->user_url) ? $user->user_url : 'http://'.$user->user_url;
}
}
if ( isset( $_POST['first_name'] ))
$user->first_name = esc_html( trim( $_POST['first_name'] ));
if ( isset( $_POST['last_name'] ))
$user->last_name = esc_html( trim( $_POST['last_name'] ));
if ( isset( $_POST['nickname'] ))
$user->nickname = esc_html( trim( $_POST['nickname'] ));
if ( isset( $_POST['display_name'] ))
$user->display_name = esc_html( trim( $_POST['display_name'] ));
if ( isset( $_POST['description'] ))
$user->description = trim( $_POST['description'] );
if ( isset( $_POST['jabber'] ))
$user->jabber = esc_html( trim( $_POST['jabber'] ));
if ( isset( $_POST['aim'] ))
$user->aim = esc_html( trim( $_POST['aim'] ));
if ( isset( $_POST['yim'] ))
$user->yim = esc_html( trim( $_POST['yim'] ));
if ( !$update )
$user->rich_editing = 'true'; // Default to true for new users.
else if ( isset( $_POST['rich_editing'] ) )
$user->rich_editing = $_POST['rich_editing'];
else
$user->rich_editing = 'true';
$user->comment_shortcuts = isset( $_POST['comment_shortcuts'] )? $_POST['comment_shortcuts'] : '';
$user->use_ssl = 0;
if ( !empty($_POST['use_ssl']) )
$user->use_ssl = 1;
if ( !$update )
$user->admin_color = 'fresh'; // Default to fresh for new users.
else if ( isset( $_POST['admin_color'] ) )
$user->admin_color = $_POST['admin_color'];
else
$user->admin_color = 'fresh';
$errors = new WP_Error();
/* checking that username has been typed */
if ( $user->user_login == '' )
$errors->add( 'user_login', __( 'ERROR: Please enter a username.' ));
/* checking the password has been typed twice */
do_action_ref_array( 'check_passwords', array ( $user->user_login, & $pass1, & $pass2 ));
if ( $update ) {
if ( empty($pass1) && !empty($pass2) )
$errors->add( 'pass', __( 'ERROR: You entered your new password only once.' ), array( 'form-field' => 'pass1' ) );
elseif ( !empty($pass1) && empty($pass2) )
$errors->add( 'pass', __( 'ERROR: You entered your new password only once.' ), array( 'form-field' => 'pass2' ) );
} else {
if ( empty($pass1) )
$errors->add( 'pass', __( 'ERROR: Please enter your password.' ), array( 'form-field' => 'pass1' ) );
elseif ( empty($pass2) )
$errors->add( 'pass', __( 'ERROR: Please enter your password twice.' ), array( 'form-field' => 'pass2' ) );
}
/* Check for "\" in password */
if ( false !== strpos( stripslashes($pass1), "\\" ) )
$errors->add( 'pass', __( 'ERROR: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) );
/* checking the password has been typed twice the same */
if ( $pass1 != $pass2 )
$errors->add( 'pass', __( 'ERROR: Please enter the same password in the two password fields.' ), array( 'form-field' => 'pass1' ) );
if (!empty ( $pass1 ))
$user->user_pass = $pass1;
if ( !$update && !validate_username( $user->user_login ) )
$errors->add( 'user_login', __( 'ERROR: This username is invalid. Please enter a valid username.' ));
if (!$update && username_exists( $user->user_login ))
$errors->add( 'user_login', __( 'ERROR: This username is already registered. Please choose another one.' ));
/* checking e-mail address */
if ( empty ( $user->user_email ) ) {
$errors->add( 'empty_email', __( 'ERROR: Please enter an e-mail address.' ), array( 'form-field' => 'email' ) );
} elseif (!is_email( $user->user_email ) ) {
$errors->add( 'invalid_email', __( 'ERROR: The e-mail address isn’t correct.' ), array( 'form-field' => 'email' ) );
} elseif ( ( $owner_id = email_exists($user->user_email) ) && $owner_id != $user->ID ) {
$errors->add( 'email_exists', __('ERROR: This email is already registered, please choose another one.'), array( 'form-field' => 'email' ) );
}
// Allow plugins to return there own errors.
do_action_ref_array('user_profile_update_errors', array ( &$errors, $update, &$user ) );
if ( $errors->get_error_codes() )
return $errors;
if ( $update ) {
$user_id = wp_update_user( get_object_vars( $user ));
} else {
$user_id = wp_insert_user( get_object_vars( $user ));
wp_new_user_notification( $user_id, isset($_POST['send_password']) ? $pass1 : '' );
}
return $user_id;
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
*
* @return array List of user IDs.
*/
function get_author_user_ids() {
global $wpdb;
$level_key = $wpdb->prefix . 'user_level';
return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value != '0'", $level_key) );
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
*
* @param int $user_id User ID.
* @return array|bool List of editable authors. False if no editable users.
*/
function get_editable_authors( $user_id ) {
global $wpdb;
$editable = get_editable_user_ids( $user_id );
if( !$editable ) {
return false;
} else {
$editable = join(',', $editable);
$authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" );
}
return apply_filters('get_editable_authors', $authors);
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
*
* @param int $user_id User ID.
* @param bool $exclude_zeros Optional, default is true. Whether to exclude zeros.
* @return unknown
*/
function get_editable_user_ids( $user_id, $exclude_zeros = true, $post_type = 'post' ) {
global $wpdb;
$user = new WP_User( $user_id );
if ( ! $user->has_cap("edit_others_{$post_type}s") ) {
if ( $user->has_cap("edit_{$post_type}s") || $exclude_zeros == false )
return array($user->id);
else
return array();
}
$level_key = $wpdb->prefix . 'user_level';
$query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s", $level_key);
if ( $exclude_zeros )
$query .= " AND meta_value != '0'";
return $wpdb->get_col( $query );
}
/**
* Fetch a filtered list of user roles that the current user is
* allowed to edit.
*
* Simple function who's main purpose is to allow filtering of the
* list of roles in the $wp_roles object so that plugins can remove
* innappropriate ones depending on the situation or user making edits.
* Specifically because without filtering anyone with the edit_users
* capability can edit others to be administrators, even if they are
* only editors or authors. This filter allows admins to delegate
* user management.
*
* @since 2.8
*
* @return unknown
*/
function get_editable_roles() {
global $wp_roles;
$all_roles = $wp_roles->roles;
$editable_roles = apply_filters('editable_roles', $all_roles);
return $editable_roles;
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
*
* @return unknown
*/
function get_nonauthor_user_ids() {
global $wpdb;
$level_key = $wpdb->prefix . 'user_level';
return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) );
}
/**
* Retrieve editable posts from other users.
*
* @since unknown
*
* @param int $user_id User ID to not retrieve posts from.
* @param string $type Optional, defaults to 'any'. Post type to retrieve, can be 'draft' or 'pending'.
* @return array List of posts from others.
*/
function get_others_unpublished_posts($user_id, $type='any') {
global $wpdb;
$editable = get_editable_user_ids( $user_id );
if ( in_array($type, array('draft', 'pending')) )
$type_sql = " post_status = '$type' ";
else
$type_sql = " ( post_status = 'draft' OR post_status = 'pending' ) ";
$dir = ( 'pending' == $type ) ? 'ASC' : 'DESC';
if( !$editable ) {
$other_unpubs = '';
} else {
$editable = join(',', $editable);
$other_unpubs = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title, post_author FROM $wpdb->posts WHERE post_type = 'post' AND $type_sql AND post_author IN ($editable) AND post_author != %d ORDER BY post_modified $dir", $user_id) );
}
return apply_filters('get_others_drafts', $other_unpubs);
}
/**
* Retrieve drafts from other users.
*
* @since unknown
*
* @param int $user_id User ID.
* @return array List of drafts from other users.
*/
function get_others_drafts($user_id) {
return get_others_unpublished_posts($user_id, 'draft');
}
/**
* Retrieve pending review posts from other users.
*
* @since unknown
*
* @param int $user_id User ID.
* @return array List of posts with pending review post type from other users.
*/
function get_others_pending($user_id) {
return get_others_unpublished_posts($user_id, 'pending');
}
/**
* Retrieve user data and filter it.
*
* @since unknown
*
* @param int $user_id User ID.
* @return object WP_User object with user data.
*/
function get_user_to_edit( $user_id ) {
$user = new WP_User( $user_id );
$user->user_login = esc_attr($user->user_login);
$user->user_email = esc_attr($user->user_email);
$user->user_url = esc_url($user->user_url);
$user->first_name = esc_attr($user->first_name);
$user->last_name = esc_attr($user->last_name);
$user->display_name = esc_attr($user->display_name);
$user->nickname = esc_attr($user->nickname);
$user->aim = isset( $user->aim ) && !empty( $user->aim ) ? esc_attr($user->aim) : '';
$user->yim = isset( $user->yim ) && !empty( $user->yim ) ? esc_attr($user->yim) : '';
$user->jabber = isset( $user->jabber ) && !empty( $user->jabber ) ? esc_attr($user->jabber) : '';
$user->description = isset( $user->description ) && !empty( $user->description ) ? esc_html($user->description) : '';
return $user;
}
/**
* Retrieve the user's drafts.
*
* @since unknown
*
* @param int $user_id User ID.
* @return array
*/
function get_users_drafts( $user_id ) {
global $wpdb;
$query = $wpdb->prepare("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id);
$query = apply_filters('get_users_drafts', $query);
return $wpdb->get_results( $query );
}
/**
* Remove user and optionally reassign posts and links to another user.
*
* If the $reassign parameter is not assigned to an User ID, then all posts will
* be deleted of that user. The action 'delete_user' that is passed the User ID
* being deleted will be run after the posts are either reassigned or deleted.
* The user meta will also be deleted that are for that User ID.
*
* @since unknown
*
* @param int $id User ID.
* @param int $reassign Optional. Reassign posts and links to new User ID.
* @return bool True when finished.
*/
function wp_delete_user($id, $reassign = 'novalue') {
global $wpdb;
$id = (int) $id;
$user = new WP_User($id);
// allow for transaction statement
do_action('delete_user', $id);
if ($reassign == 'novalue') {
$post_ids = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id) );
if ($post_ids) {
foreach ($post_ids as $post_id)
wp_delete_post($post_id);
}
// Clean links
$link_ids = $wpdb->get_col( $wpdb->prepare("SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id) );
if ( $link_ids ) {
foreach ( $link_ids as $link_id )
wp_delete_link($link_id);
}
} else {
$reassign = (int) $reassign;
$wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $id) );
$wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $id) );
}
// FINALLY, delete user
$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d", $id) );
$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->users WHERE ID = %d", $id) );
wp_cache_delete($id, 'users');
wp_cache_delete($user->user_login, 'userlogins');
wp_cache_delete($user->user_email, 'useremail');
wp_cache_delete($user->user_nicename, 'userslugs');
// allow for commit transaction
do_action('deleted_user', $id);
return true;
}
/**
* Remove all capabilities from user.
*
* @since unknown
*
* @param int $id User ID.
*/
function wp_revoke_user($id) {
$id = (int) $id;
$user = new WP_User($id);
$user->remove_all_caps();
}
if ( !class_exists('WP_User_Search') ) :
/**
* WordPress User Search class.
*
* @since unknown
* @author Mark Jaquith
*/
class WP_User_Search {
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $results;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $search_term;
/**
* Page number.
*
* @since unknown
* @access private
* @var int
*/
var $page;
/**
* Role name that users have.
*
* @since unknown
* @access private
* @var string
*/
var $role;
/**
* Raw page number.
*
* @since unknown
* @access private
* @var int|bool
*/
var $raw_page;
/**
* Amount of users to display per page.
*
* @since unknown
* @access public
* @var int
*/
var $users_per_page = 50;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $first_user;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var int
*/
var $last_user;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $query_limit;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $query_sort;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $query_from_where;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var int
*/
var $total_users_for_query = 0;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var bool
*/
var $too_many_total_users = false;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $search_errors;
/**
* {@internal Missing Description}}
*
* @since unknown
* @access private
* @var unknown_type
*/
var $paging_text;
/**
* PHP4 Constructor - Sets up the object properties.
*
* @since unknown
*
* @param string $search_term Search terms string.
* @param int $page Optional. Page ID.
* @param string $role Role name.
* @return WP_User_Search
*/
function WP_User_Search ($search_term = '', $page = '', $role = '') {
$this->search_term = $search_term;
$this->raw_page = ( '' == $page ) ? false : (int) $page;
$this->page = (int) ( '' == $page ) ? 1 : $page;
$this->role = $role;
$this->prepare_query();
$this->query();
$this->prepare_vars_for_template_usage();
$this->do_paging();
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
* @access public
*/
function prepare_query() {
global $wpdb;
$this->first_user = ($this->page - 1) * $this->users_per_page;
$this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page);
$this->query_sort = ' ORDER BY user_login';
$search_sql = '';
if ( $this->search_term ) {
$searches = array();
$search_sql = 'AND (';
foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col )
$searches[] = $col . " LIKE '%$this->search_term%'";
$search_sql .= implode(' OR ', $searches);
$search_sql .= ')';
}
$this->query_from_where = "FROM $wpdb->users";
if ( $this->role )
$this->query_from_where .= $wpdb->prepare(" INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id WHERE $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%');
else
$this->query_from_where .= " WHERE 1=1";
$this->query_from_where .= " $search_sql";
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
* @access public
*/
function query() {
global $wpdb;
$this->results = $wpdb->get_col('SELECT ID ' . $this->query_from_where . $this->query_sort . $this->query_limit);
if ( $this->results )
$this->total_users_for_query = $wpdb->get_var('SELECT COUNT(ID) ' . $this->query_from_where); // no limit
else
$this->search_errors = new WP_Error('no_matching_users_found', __('No matching users were found!'));
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
* @access public
*/
function prepare_vars_for_template_usage() {
$this->search_term = stripslashes($this->search_term); // done with DB, from now on we want slashes gone
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
* @access public
*/
function do_paging() {
if ( $this->total_users_for_query > $this->users_per_page ) { // have to page the results
$args = array();
if( ! empty($this->search_term) )
$args['usersearch'] = urlencode($this->search_term);
if( ! empty($this->role) )
$args['role'] = urlencode($this->role);
$this->paging_text = paginate_links( array(
'total' => ceil($this->total_users_for_query / $this->users_per_page),
'current' => $this->page,
'base' => 'users.php?%_%',
'format' => 'userspage=%#%',
'add_args' => $args
) );
if ( $this->paging_text ) {
$this->paging_text = sprintf( '' . __( 'Displaying %s–%s of %s' ) . '%s',
number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ),
number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ),
number_format_i18n( $this->total_users_for_query ),
$this->paging_text
);
}
}
}
/**
* {@internal Missing Short Description}}
*
* {@internal Missing Long Description}}
*
* @since unknown
* @access public
*
* @return unknown
*/
function get_results() {
return (array) $this->results;
}
/**
* Displaying paging text.
*
* @see do_paging() Builds paging text.
*
* @since unknown
* @access public
*/
function page_links() {
echo $this->paging_text;
}
/**
* Whether paging is enabled.
*
* @see do_paging() Builds paging text.
*
* @since unknown
* @access public
*
* @return bool
*/
function results_are_paged() {
if ( $this->paging_text )
return true;
return false;
}
/**
* Whether there are search terms.
*
* @since unknown
* @access public
*
* @return bool
*/
function is_search() {
if ( $this->search_term )
return true;
return false;
}
}
endif;
add_action('admin_init', 'default_password_nag_handler');
function default_password_nag_handler($errors = false) {
global $user_ID;
if ( ! get_usermeta($user_ID, 'default_password_nag') ) //Short circuit it.
return;
//get_user_setting = JS saved UI setting. else no-js-falback code.
if ( 'hide' == get_user_setting('default_password_nag') || isset($_GET['default_password_nag']) && '0' == $_GET['default_password_nag'] ) {
delete_user_setting('default_password_nag');
update_usermeta($user_ID, 'default_password_nag', false);
}
}
add_action('profile_update', 'default_password_nag_edit_user', 10, 2);
function default_password_nag_edit_user($user_ID, $old_data) {
global $user_ID;
if ( ! get_usermeta($user_ID, 'default_password_nag') ) //Short circuit it.
return;
$new_data = get_userdata($user_ID);
if ( $new_data->user_pass != $old_data->user_pass ) { //Remove the nag if the password has been changed.
delete_user_setting('default_password_nag');
update_usermeta($user_ID, 'default_password_nag', false);
}
}
add_action('admin_notices', 'default_password_nag');
function default_password_nag() {
global $user_ID;
if ( ! get_usermeta($user_ID, 'default_password_nag') )
return;
echo '
';
printf(__("Notice: you're using the auto-generated password for your account. Would you like to change it to something you'll remember easier? Yes, Take me to my profile page | No Thanks, Do not remind me again."), admin_url('profile.php') . '#password', '?default_password_nag=0');
echo '
\n";
}
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $id
* @param unknown_type $alt
* @param unknown_type $title
* @param unknown_type $align
* @param unknown_type $url
* @param unknown_type $rel
* @param unknown_type $size
* @return unknown
*/
function get_image_send_to_editor($id, $alt, $title, $align, $url='', $rel = false, $size='medium') {
$htmlalt = ( empty($alt) ) ? $title : $alt;
$html = get_image_tag($id, $htmlalt, $title, $align, $size);
$rel = $rel ? ' rel="attachment wp-att-' . esc_attr($id).'"' : '';
if ( $url )
$html = '$html";
$html = apply_filters( 'image_send_to_editor', $html, $id, $alt, $title, $align, $url, $size );
return $html;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $html
* @param unknown_type $id
* @param unknown_type $alt
* @param unknown_type $title
* @param unknown_type $align
* @param unknown_type $url
* @param unknown_type $size
* @return unknown
*/
function image_add_caption( $html, $id, $alt, $title, $align, $url, $size ) {
if ( empty($alt) || apply_filters( 'disable_captions', '' ) )
return $html;
$id = ( 0 < (int) $id ) ? 'attachment_' . $id : '';
preg_match( '/width="([0-9]+)/', $html, $matches );
if ( ! isset($matches[1]) )
return $html;
$width = $matches[1];
$html = preg_replace( '/(class=["\'][^\'"]*)align(none|left|right|center)\s?/', '$1', $html );
if ( empty($align) )
$align = 'none';
$alt = ! empty($alt) ? addslashes($alt) : '';
$shcode = '[caption id="' . $id . '" align="align' . $align
. '" width="' . $width . '" caption="' . $alt . '"]' . $html . '[/caption]';
return apply_filters( 'image_add_caption_shortcode', $shcode, $html );
}
add_filter( 'image_send_to_editor', 'image_add_caption', 20, 7 );
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $html
*/
function media_send_to_editor($html) {
?>
false);
$time = current_time('mysql');
if ( $post = get_post($post_id) ) {
if ( substr( $post->post_date, 0, 4 ) > 0 )
$time = $post->post_date;
}
$name = $_FILES[$file_id]['name'];
$file = wp_handle_upload($_FILES[$file_id], $overrides, $time);
if ( isset($file['error']) )
return new WP_Error( 'upload_error', $file['error'] );
$name_parts = pathinfo($name);
$name = trim( substr( $name, 0, -(1 + strlen($name_parts['extension'])) ) );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = $name;
$content = '';
// use image exif/iptc data for title and caption defaults if possible
if ( $image_meta = @wp_read_image_metadata($file) ) {
if ( trim($image_meta['title']) )
$title = $image_meta['title'];
if ( trim($image_meta['caption']) )
$content = $image_meta['caption'];
}
// Construct the attachment array
$attachment = array_merge( array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
), $post_data );
// Save the data
$id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($id) ) {
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
}
return $id;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $file_array
* @param unknown_type $post_id
* @param unknown_type $desc
* @param unknown_type $post_data
* @return unknown
*/
function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) {
$overrides = array('test_form'=>false);
$file = wp_handle_sideload($file_array, $overrides);
if ( isset($file['error']) )
return new WP_Error( 'upload_error', $file['error'] );
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$title = preg_replace('/\.[^.]+$/', '', basename($file));
$content = '';
// use image exif/iptc data for title and caption defaults if possible
if ( $image_meta = @wp_read_image_metadata($file) ) {
if ( trim($image_meta['title']) )
$title = $image_meta['title'];
if ( trim($image_meta['caption']) )
$content = $image_meta['caption'];
}
$title = @$desc;
// Construct the attachment array
$attachment = array_merge( array(
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => $content,
), $post_data );
// Save the data
$id = wp_insert_attachment($attachment, $file, $post_id);
if ( !is_wp_error($id) ) {
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
return $url;
}
return $id;
}
/**
* {@internal Missing Short Description}}
*
* Wrap iframe content (produced by $content_func) in a doctype, html head/body
* etc any additional function args will be passed to content_func.
*
* @since unknown
*
* @param unknown_type $content_func
*/
function wp_iframe($content_func /* ... */) {
?>
>
› —
>
EOF;
printf($context, $out);
}
add_action( 'media_buttons', 'media_buttons' );
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_form_handler() {
check_admin_referer('media-form');
$errors = null;
if ( isset($_POST['send']) ) {
$keys = array_keys($_POST['send']);
$send_id = (int) array_shift($keys);
}
if ( !empty($_POST['attachments']) ) foreach ( $_POST['attachments'] as $attachment_id => $attachment ) {
$post = $_post = get_post($attachment_id, ARRAY_A);
if ( isset($attachment['post_content']) )
$post['post_content'] = $attachment['post_content'];
if ( isset($attachment['post_title']) )
$post['post_title'] = $attachment['post_title'];
if ( isset($attachment['post_excerpt']) )
$post['post_excerpt'] = $attachment['post_excerpt'];
if ( isset($attachment['menu_order']) )
$post['menu_order'] = $attachment['menu_order'];
if ( isset($send_id) && $attachment_id == $send_id ) {
if ( isset($attachment['post_parent']) )
$post['post_parent'] = $attachment['post_parent'];
}
$post = apply_filters('attachment_fields_to_save', $post, $attachment);
if ( isset($post['errors']) ) {
$errors[$attachment_id] = $post['errors'];
unset($post['errors']);
}
if ( $post != $_post )
wp_update_post($post);
foreach ( get_attachment_taxonomies($post) as $t )
if ( isset($attachment[$t]) )
wp_set_object_terms($attachment_id, array_map('trim', preg_split('/,+/', $attachment[$t])), $t, false);
}
if ( isset($_POST['insert-gallery']) || isset($_POST['update-gallery']) ) { ?>
$html";
}
$html = apply_filters('media_send_to_editor', $html, $send_id, $attachment);
return media_send_to_editor($html);
}
return $errors;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_image() {
$errors = array();
$id = 0;
if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
// Upload File button was clicked
$id = media_handle_upload('async-upload', $_REQUEST['post_id']);
unset($_FILES);
if ( is_wp_error($id) ) {
$errors['upload_error'] = $id;
$id = false;
}
}
if ( !empty($_POST['insertonlybutton']) ) {
$src = $_POST['insertonly']['src'];
if ( !empty($src) && !strpos($src, '://') )
$src = "http://$src";
$alt = esc_attr($_POST['insertonly']['alt']);
if ( isset($_POST['insertonly']['align']) ) {
$align = esc_attr($_POST['insertonly']['align']);
$class = " class='align$align'";
}
if ( !empty($src) )
$html = "";
$html = apply_filters('image_send_to_editor_url', $html, $src, $alt, $align);
return media_send_to_editor($html);
}
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
if ( isset($_POST['save']) ) {
$errors['upload_notice'] = __('Saved.');
return media_upload_gallery();
}
if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' )
return wp_iframe( 'media_upload_type_url_form', 'image', $errors, $id );
return wp_iframe( 'media_upload_type_form', 'image', $errors, $id );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $file
* @param unknown_type $post_id
* @param unknown_type $desc
* @return unknown
*/
function media_sideload_image($file, $post_id, $desc = null) {
if (!empty($file) ) {
$file_array['name'] = basename($file);
$tmp = download_url($file);
$file_array['tmp_name'] = $tmp;
$desc = @$desc;
if ( is_wp_error($tmp) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
$id = media_handle_sideload($file_array, $post_id, $desc);
$src = $id;
if ( is_wp_error($id) ) {
@unlink($file_array['tmp_name']);
return $id;
}
}
if ( !empty($src) ) {
$alt = @$desc;
$html = "";
return $html;
}
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_audio() {
$errors = array();
$id = 0;
if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
// Upload File button was clicked
$id = media_handle_upload('async-upload', $_REQUEST['post_id']);
unset($_FILES);
if ( is_wp_error($id) ) {
$errors['upload_error'] = $id;
$id = false;
}
}
if ( !empty($_POST['insertonlybutton']) ) {
$href = $_POST['insertonly']['href'];
if ( !empty($href) && !strpos($href, '://') )
$href = "http://$href";
$title = esc_attr($_POST['insertonly']['title']);
if ( empty($title) )
$title = basename($href);
if ( !empty($title) && !empty($href) )
$html = "$title";
$html = apply_filters('audio_send_to_editor_url', $html, $href, $title);
return media_send_to_editor($html);
}
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
if ( isset($_POST['save']) ) {
$errors['upload_notice'] = __('Saved.');
return media_upload_gallery();
}
if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' )
return wp_iframe( 'media_upload_type_url_form', 'audio', $errors, $id );
return wp_iframe( 'media_upload_type_form', 'audio', $errors, $id );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_video() {
$errors = array();
$id = 0;
if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
// Upload File button was clicked
$id = media_handle_upload('async-upload', $_REQUEST['post_id']);
unset($_FILES);
if ( is_wp_error($id) ) {
$errors['upload_error'] = $id;
$id = false;
}
}
if ( !empty($_POST['insertonlybutton']) ) {
$href = $_POST['insertonly']['href'];
if ( !empty($href) && !strpos($href, '://') )
$href = "http://$href";
$title = esc_attr($_POST['insertonly']['title']);
if ( empty($title) )
$title = basename($href);
if ( !empty($title) && !empty($href) )
$html = "$title";
$html = apply_filters('video_send_to_editor_url', $html, $href, $title);
return media_send_to_editor($html);
}
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
if ( isset($_POST['save']) ) {
$errors['upload_notice'] = __('Saved.');
return media_upload_gallery();
}
if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' )
return wp_iframe( 'media_upload_type_url_form', 'video', $errors, $id );
return wp_iframe( 'media_upload_type_form', 'video', $errors, $id );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_file() {
$errors = array();
$id = 0;
if ( isset($_POST['html-upload']) && !empty($_FILES) ) {
// Upload File button was clicked
$id = media_handle_upload('async-upload', $_REQUEST['post_id']);
unset($_FILES);
if ( is_wp_error($id) ) {
$errors['upload_error'] = $id;
$id = false;
}
}
if ( !empty($_POST['insertonlybutton']) ) {
$href = $_POST['insertonly']['href'];
if ( !empty($href) && !strpos($href, '://') )
$href = "http://$href";
$title = esc_attr($_POST['insertonly']['title']);
if ( empty($title) )
$title = basename($href);
if ( !empty($title) && !empty($href) )
$html = "$title";
$html = apply_filters('file_send_to_editor_url', $html, $href, $title);
return media_send_to_editor($html);
}
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
if ( isset($_POST['save']) ) {
$errors['upload_notice'] = __('Saved.');
return media_upload_gallery();
}
if ( isset($_GET['tab']) && $_GET['tab'] == 'type_url' )
return wp_iframe( 'media_upload_type_url_form', 'file', $errors, $id );
return wp_iframe( 'media_upload_type_form', 'file', $errors, $id );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_gallery() {
$errors = array();
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
wp_enqueue_script('admin-gallery');
return wp_iframe( 'media_upload_gallery_form', $errors );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @return unknown
*/
function media_upload_library() {
$errors = array();
if ( !empty($_POST) ) {
$return = media_upload_form_handler();
if ( is_string($return) )
return $return;
if ( is_array($return) )
$errors = $return;
}
return wp_iframe( 'media_upload_library_form', $errors );
}
/**
* Retrieve HTML for the image alignment radio buttons with the specified one checked.
*
* @since unknown
*
* @param unknown_type $post
* @param unknown_type $checked
* @return unknown
*/
function image_align_input_fields( $post, $checked = '' ) {
$alignments = array('none' => __('None'), 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right'));
if ( !array_key_exists( (string) $checked, $alignments ) )
$checked = 'none';
$out = array();
foreach ($alignments as $name => $label) {
$name = esc_attr($name);
$out[] = "";
}
return join("\n", $out);
}
/**
* Retrieve HTML for the size radio buttons with the specified one checked.
*
* @since unknown
*
* @param unknown_type $post
* @param unknown_type $checked
* @return unknown
*/
function image_size_input_fields( $post, $checked = '' ) {
// get a list of the actual pixel dimensions of each possible intermediate version of this image
$size_names = array('thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full size'));
foreach ( $size_names as $size => $name ) {
$downsize = image_downsize($post->ID, $size);
// is this size selectable?
$enabled = ( $downsize[3] || 'full' == $size );
$css_id = "image-size-{$size}-{$post->ID}";
// if this size is the default but that's not available, don't select it
if ( $checked && !$enabled )
$checked = '';
// if $checked was not specified, default to the first available size that's bigger than a thumbnail
if ( !$checked && $enabled && 'thumbnail' != $size )
$checked = $size;
$html = "
ID][image-size]' id='{$css_id}' value='{$size}'".( $checked == $size ? " checked='checked'" : '') ." />";
$html .= "";
// only show the dimensions if that choice is available
if ( $enabled )
$html .= " ";
$html .= '
';
$out[] = $html;
}
return array(
'label' => __('Size'),
'input' => 'html',
'html' => join("\n", $out),
);
}
/**
* Retrieve HTML for the Link URL buttons with the default link type as specified.
*
* @since unknown
*
* @param unknown_type $post
* @param unknown_type $url_type
* @return unknown
*/
function image_link_input_fields($post, $url_type='') {
$file = wp_get_attachment_url($post->ID);
$link = get_attachment_link($post->ID);
$url = '';
if ( $url_type == 'file' )
$url = $file;
elseif ( $url_type == 'post' )
$url = $link;
return "
";
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $form_fields
* @param unknown_type $post
* @return unknown
*/
function image_attachment_fields_to_edit($form_fields, $post) {
if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
$form_fields['post_title']['required'] = true;
$file = wp_get_attachment_url($post->ID);
$form_fields['image_url']['value'] = $file;
$form_fields['post_excerpt']['label'] = __('Caption');
$form_fields['post_excerpt']['helps'][] = __('Also used as alternate text for the image');
$form_fields['post_content']['label'] = __('Description');
$form_fields['align'] = array(
'label' => __('Alignment'),
'input' => 'html',
'html' => image_align_input_fields($post, get_option('image_default_align')),
);
$form_fields['image-size'] = image_size_input_fields($post, get_option('image_default_size'));
}
return $form_fields;
}
add_filter('attachment_fields_to_edit', 'image_attachment_fields_to_edit', 10, 2);
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $form_fields
* @param unknown_type $post
* @return unknown
*/
function media_single_attachment_fields_to_edit( $form_fields, $post ) {
unset($form_fields['url'], $form_fields['align'], $form_fields['image-size']);
return $form_fields;
}
function media_post_single_attachment_fields_to_edit( $form_fields, $post ) {
unset($form_fields['image_url']);
return $form_fields;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $post
* @param unknown_type $attachment
* @return unknown
*/
function image_attachment_fields_to_save($post, $attachment) {
if ( substr($post['post_mime_type'], 0, 5) == 'image' ) {
if ( strlen(trim($post['post_title'])) == 0 ) {
$post['post_title'] = preg_replace('/\.\w+$/', '', basename($post['guid']));
$post['errors']['post_title']['errors'][] = __('Empty Title filled from filename.');
}
}
return $post;
}
add_filter('attachment_fields_to_save', 'image_attachment_fields_to_save', 10, 2);
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $html
* @param unknown_type $attachment_id
* @param unknown_type $attachment
* @return unknown
*/
function image_media_send_to_editor($html, $attachment_id, $attachment) {
$post =& get_post($attachment_id);
if ( substr($post->post_mime_type, 0, 5) == 'image' ) {
$url = $attachment['url'];
if ( isset($attachment['align']) )
$align = $attachment['align'];
else
$align = 'none';
if ( !empty($attachment['image-size']) )
$size = $attachment['image-size'];
else
$size = 'medium';
$rel = ( $url == get_attachment_link($attachment_id) );
return get_image_send_to_editor($attachment_id, $attachment['post_excerpt'], $attachment['post_title'], $align, $url, $rel, $size);
}
return $html;
}
add_filter('media_send_to_editor', 'image_media_send_to_editor', 10, 3);
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $post
* @param unknown_type $errors
* @return unknown
*/
function get_attachment_fields_to_edit($post, $errors = null) {
if ( is_int($post) )
$post =& get_post($post);
if ( is_array($post) )
$post = (object) $post;
$image_url = wp_get_attachment_url($post->ID);
$edit_post = sanitize_post($post, 'edit');
$form_fields = array(
'post_title' => array(
'label' => __('Title'),
'value' => $edit_post->post_title,
),
'post_excerpt' => array(
'label' => __('Caption'),
'value' => $edit_post->post_excerpt,
),
'post_content' => array(
'label' => __('Description'),
'value' => $edit_post->post_content,
'input' => 'textarea',
),
'url' => array(
'label' => __('Link URL'),
'input' => 'html',
'html' => image_link_input_fields($post, get_option('image_default_link_type')),
'helps' => __('Enter a link URL or click above for presets.'),
),
'menu_order' => array(
'label' => __('Order'),
'value' => $edit_post->menu_order
),
'image_url' => array(
'label' => __('File URL'),
'input' => 'html',
'html' => " ",
'value' => isset($edit_post->post_url) ? $edit_post->post_url : '',
'helps' => __('Location of the uploaded file.'),
)
);
foreach ( get_attachment_taxonomies($post) as $taxonomy ) {
$t = (array) get_taxonomy($taxonomy);
if ( empty($t['label']) )
$t['label'] = $taxonomy;
if ( empty($t['args']) )
$t['args'] = array();
$terms = get_object_term_cache($post->ID, $taxonomy);
if ( empty($terms) )
$terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']);
$values = array();
foreach ( $terms as $term )
$values[] = $term->name;
$t['value'] = join(', ', $values);
$form_fields[$taxonomy] = $t;
}
// Merge default fields with their errors, so any key passed with the error (e.g. 'error', 'helps', 'value') will replace the default
// The recursive merge is easily traversed with array casting: foreach( (array) $things as $thing )
$form_fields = array_merge_recursive($form_fields, (array) $errors);
$form_fields = apply_filters('attachment_fields_to_edit', $form_fields, $post);
return $form_fields;
}
/**
* Retrieve HTML for media items of post gallery.
*
* The HTML markup retrieved will be created for the progress of SWF Upload
* component. Will also create link for showing and hiding the form to modify
* the image attachment.
*
* @since unknown
*
* @param int $post_id Optional. Post ID.
* @param array $errors Errors for attachment, if any.
* @return string
*/
function get_media_items( $post_id, $errors ) {
if ( $post_id ) {
$post = get_post($post_id);
if ( $post && $post->post_type == 'attachment' )
$attachments = array($post->ID => $post);
else
$attachments = get_children( array( 'post_parent' => $post_id, 'post_type' => 'attachment', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC') );
} else {
if ( is_array($GLOBALS['wp_the_query']->posts) )
foreach ( $GLOBALS['wp_the_query']->posts as $attachment )
$attachments[$attachment->ID] = $attachment;
}
$output = '';
foreach ( (array) $attachments as $id => $attachment )
if ( $item = get_media_item( $id, array( 'errors' => isset($errors[$id]) ? $errors[$id] : null) ) )
$output .= "\n
$item\n
";
return $output;
}
/**
* Retrieve HTML form for modifying the image attachment.
*
* @since unknown
*
* @param int $attachment_id Attachment ID for modification.
* @param string|array $args Optional. Override defaults.
* @return string HTML form for attachment.
*/
function get_media_item( $attachment_id, $args = null ) {
global $redir_tab;
$default_args = array( 'errors' => null, 'send' => true, 'delete' => true, 'toggle' => true, 'show_title' => true );
$args = wp_parse_args( $args, $default_args );
extract( $args, EXTR_SKIP );
global $post_mime_types;
if ( ( $attachment_id = intval($attachment_id) ) && $thumb_url = get_attachment_icon_src( $attachment_id ) )
$thumb_url = $thumb_url[0];
else
return false;
$toggle_on = __('Show');
$toggle_off = __('Hide');
$post = get_post($attachment_id);
$filename = basename($post->guid);
$title = esc_attr($post->post_title);
if ( $_tags = get_the_tags($attachment_id) ) {
foreach ( $_tags as $tag )
$tags[] = $tag->name;
$tags = esc_attr(join(', ', $tags));
}
$type = '';
if ( isset($post_mime_types) ) {
$keys = array_keys(wp_match_mime_types(array_keys($post_mime_types), $post->post_mime_type));
$type = array_shift($keys);
$type = "";
}
$form_fields = get_attachment_fields_to_edit($post, $errors);
if ( $toggle ) {
$class = empty($errors) ? 'startclosed' : 'startopen';
$toggle_links = "
$toggle_on$toggle_off";
} else {
$class = 'form-table';
$toggle_links = '';
}
$display_title = ( !empty( $title ) ) ? $title : $filename; // $title shouldn't ever be empty, but just in case
$display_title = $show_title ? "
' . __('Link text, e.g. “Ransom Demands (PDF)”') . '
';
}
/**
* {@internal Missing Short Description}}
*
* Support a GET parameter for disabling the flash uploader.
*
* @since unknown
*
* @param unknown_type $flash
* @return unknown
*/
function media_upload_use_flash($flash) {
if ( array_key_exists('flash', $_REQUEST) )
$flash = !empty($_REQUEST['flash']);
return $flash;
}
add_filter('flash_uploader', 'media_upload_use_flash');
/**
* {@internal Missing Short Description}}
*
* @since unknown
*/
function media_upload_flash_bypass() {
echo '
';
printf( __('You are using the Flash uploader. Problems? Try the Browser uploader instead.'), esc_url(add_query_arg('flash', 0)) );
echo '
';
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*/
function media_upload_html_bypass($flash = true) {
echo '
';
_e('You are using the Browser uploader.');
if ( $flash ) {
// the user manually selected the browser uploader, so let them switch back to Flash
echo ' ';
printf( __('Try the Flash uploader instead.'), esc_url(add_query_arg('flash', 1)) );
}
echo "
' . __('This dashboard widget queries Google Blog Search so that when another blog links to your site it will show up here. It has found no incoming links… yet. It’s okay — there is no rush.') . "
\n";
}
}
/**
* Checks to see if all of the feed url in $check_urls are cached.
*
* If $check_urls is empty, look for the rss feed url found in the dashboard
* widget optios of $widget_id. If cached, call $callback, a function that
* echoes out output for this widget. If not cache, echo a "Loading..." stub
* which is later replaced by AJAX call (see top of /wp-admin/index.php)
*
* @since unknown
*
* @param int $widget_id
* @param callback $callback
* @param array $check_urls RSS feeds
* @return bool False on failure. True on success.
*/
function wp_dashboard_cached_rss_widget( $widget_id, $callback, $check_urls = array() ) {
$loading = '
' . __( 'Loading…' ) . '
';
if ( empty($check_urls) ) {
$widgets = get_option( 'dashboard_widget_options' );
if ( empty($widgets[$widget_id]['url']) ) {
echo $loading;
return false;
}
$check_urls = array( $widgets[$widget_id]['url'] );
}
include_once ABSPATH . WPINC . '/class-feed.php';
foreach ( $check_urls as $check_url ) {
$cache = new WP_Feed_Cache_Transient('', md5($check_url), '');
if ( ! $cache->load() ) {
echo $loading;
return false;
}
}
if ( $callback && is_callable( $callback ) ) {
$args = array_slice( func_get_args(), 2 );
array_unshift( $args, $widget_id );
call_user_func_array( $callback, $args );
}
return true;
}
/* Dashboard Widgets Controls */
// Calls widget_control callback
/**
* Calls widget control callback.
*
* @since unknown
*
* @param int $widget_control_id Registered Widget ID.
*/
function wp_dashboard_trigger_widget_control( $widget_control_id = false ) {
global $wp_dashboard_control_callbacks;
if ( is_scalar($widget_control_id) && $widget_control_id && isset($wp_dashboard_control_callbacks[$widget_control_id]) && is_callable($wp_dashboard_control_callbacks[$widget_control_id]) ) {
call_user_func( $wp_dashboard_control_callbacks[$widget_control_id], '', array( 'id' => $widget_control_id, 'callback' => $wp_dashboard_control_callbacks[$widget_control_id] ) );
}
}
/**
* The RSS dashboard widget control.
*
* Sets up $args to be used as input to wp_widget_rss_form(). Handles POST data
* from RSS-type widgets.
*
* @since unknown
*
* @param string widget_id
* @param array form_inputs
*/
function wp_dashboard_rss_control( $widget_id, $form_inputs = array() ) {
if ( !$widget_options = get_option( 'dashboard_widget_options' ) )
$widget_options = array();
if ( !isset($widget_options[$widget_id]) )
$widget_options[$widget_id] = array();
$number = 1; // Hack to use wp_widget_rss_form()
$widget_options[$widget_id]['number'] = $number;
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget-rss'][$number]) ) {
$_POST['widget-rss'][$number] = stripslashes_deep( $_POST['widget-rss'][$number] );
$widget_options[$widget_id] = wp_widget_rss_process( $_POST['widget-rss'][$number] );
// title is optional. If black, fill it if possible
if ( !$widget_options[$widget_id]['title'] && isset($_POST['widget-rss'][$number]['title']) ) {
$rss = fetch_feed($widget_options[$widget_id]['url']);
if ( ! is_wp_error($rss) )
$widget_options[$widget_id]['title'] = htmlentities(strip_tags($rss->get_title()));
else
$widget_options[$widget_id]['title'] = htmlentities(__('Unknown Feed'));
}
update_option( 'dashboard_widget_options', $widget_options );
}
wp_widget_rss_form( $widget_options[$widget_id], $form_inputs );
}
/**
* Empty function usable by plugins to output empty dashboard widget (to be populated later by JS).
*/
function wp_dashboard_empty() {}
?>
larscapo/wp-admin/includes/update-core.php 0000644 0041054 0041055 00000021723 11225447103 021344 0 ustar lacunaus lacunaus exists($from . '/wordpress/wp-settings.php') || !$wp_filesystem->exists($from . '/wordpress/wp-admin/admin.php') ||
!$wp_filesystem->exists($from . '/wordpress/wp-includes/functions.php') ) {
$wp_filesystem->delete($from, true);
return new WP_Error('insane_distro', __('The update could not be unpacked') );
}
apply_filters('update_feedback', __('Installing the latest version'));
// Create maintenance file to signal that we are upgrading
$maintenance_string = '';
$maintenance_file = $to . '.maintenance';
$wp_filesystem->delete($maintenance_file);
$wp_filesystem->put_contents($maintenance_file, $maintenance_string, FS_CHMOD_FILE);
// Copy new versions of WP files into place.
$result = copy_dir($from . '/wordpress', $to);
if ( is_wp_error($result) ) {
$wp_filesystem->delete($maintenance_file);
$wp_filesystem->delete($from, true);
return $result;
}
// Remove old files
foreach ( $_old_files as $old_file ) {
$old_file = $to . $old_file;
if ( !$wp_filesystem->exists($old_file) )
continue;
$wp_filesystem->delete($old_file, true);
}
// Upgrade DB with separate request
apply_filters('update_feedback', __('Upgrading database'));
$db_upgrade_url = admin_url('upgrade.php?step=upgrade_db');
wp_remote_post($db_upgrade_url, array('timeout' => 60));
// Remove working directory
$wp_filesystem->delete($from, true);
// Force refresh of update information
if ( function_exists('delete_transient') )
delete_transient('update_core');
else
delete_option('update_core');
// Remove maintenance file, we're done.
$wp_filesystem->delete($maintenance_file);
}
?>
larscapo/wp-admin/includes/template.php 0000644 0041054 0041055 00000367604 11225447103 020762 0 ustar lacunaus lacunaus 0);
if ( !empty($_GET['s']) )
$args['search'] = $_GET['s'];
$categories = get_categories( $args );
if ( empty($categories) )
return false;
}
$children = _get_term_hierarchy('category');
_cat_rows( $parent, $level, $categories, $children, $page, $per_page, $count );
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $categories
* @param unknown_type $count
* @param unknown_type $parent
* @param unknown_type $level
* @param unknown_type $page
* @param unknown_type $per_page
* @return unknown
*/
function _cat_rows( $parent = 0, $level = 0, $categories, &$children, $page = 1, $per_page = 20, &$count ) {
$start = ($page - 1) * $per_page;
$end = $start + $per_page;
ob_start();
foreach ( $categories as $key => $category ) {
if ( $count >= $end )
break;
if ( $category->parent != $parent && empty($_GET['s']) )
continue;
// If the page starts in a subtree, print the parents.
if ( $count == $start && $category->parent > 0 ) {
$my_parents = array();
$p = $category->parent;
while ( $p ) {
$my_parent = get_category( $p );
$my_parents[] = $my_parent;
if ( $my_parent->parent == 0 )
break;
$p = $my_parent->parent;
}
$num_parents = count($my_parents);
while( $my_parent = array_pop($my_parents) ) {
echo "\t" . _cat_row( $my_parent, $level - $num_parents );
$num_parents--;
}
}
if ( $count >= $start )
echo "\t" . _cat_row( $category, $level );
unset( $categories[ $key ] );
$count++;
if ( isset($children[$category->term_id]) )
_cat_rows( $category->term_id, $level + 1, $categories, $children, $page, $per_page, $count );
}
$output = ob_get_contents();
ob_end_clean();
echo $output;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $category
* @param unknown_type $level
* @param unknown_type $name_override
* @return unknown
*/
function _cat_row( $category, $level, $name_override = false ) {
static $row_class = '';
$category = get_category( $category, OBJECT, 'display' );
$default_cat_id = (int) get_option( 'default_category' );
$pad = str_repeat( '— ', max(0, $level) );
$name = ( $name_override ? $name_override : $pad . ' ' . $category->name );
$edit_link = "categories.php?action=edit&cat_ID=$category->term_id";
if ( current_user_can( 'manage_categories' ) ) {
$edit = "name)) . "'>" . esc_attr( $name ) . ' ';
$actions = array();
$actions['edit'] = '' . __('Edit') . '';
$actions['inline hide-if-no-js'] = '' . __('Quick Edit') . '';
if ( $default_cat_id != $category->term_id )
$actions['delete'] = "term_id) . "'>" . __('Delete') . "";
$actions = apply_filters('cat_row_actions', $actions, $category);
$action_count = count($actions);
$i = 0;
$edit .= '
';
return $output;
}
/**
* Outputs the html checked attribute.
*
* Compares the first two arguments and if identical marks as checked
*
* @since 2.8
*
* @param any $checked One of the values to compare
* @param any $current (true) The other value to compare if not just true
* @param bool $echo Whether or not to echo or just return the string
*/
function checked( $checked, $current = true, $echo = true) {
return __checked_selected_helper( $checked, $current, $echo, 'checked' );
}
/**
* Outputs the html selected attribute.
*
* Compares the first two arguments and if identical marks as selected
*
* @since 2.8
*
* @param any selected One of the values to compare
* @param any $current (true) The other value to compare if not just true
* @param bool $echo Whether or not to echo or just return the string
*/
function selected( $selected, $current = true, $echo = true) {
return __checked_selected_helper( $selected, $current, $echo, 'selected' );
}
/**
* Private helper function for checked and selected.
*
* Compares the first two arguments and if identical marks as $type
*
* @since 2.8
* @access private
*
* @param any $helper One of the values to compare
* @param any $current (true) The other value to compare if not just true
* @param bool $echo Whether or not to echo or just return the string
* @param string $type The type of checked|selected we are doing.
*/
function __checked_selected_helper( $helper, $current, $echo, $type) {
if ( $helper == $current)
$result = " $type='$type'";
else
$result = '';
if ($echo)
echo $result;
return $result;
}
//
// Category Checklists
//
/**
* {@internal Missing Short Description}}
*
* @since unknown
* @deprecated Use {@link wp_link_category_checklist()}
* @see wp_link_category_checklist()
*
* @param unknown_type $default
* @param unknown_type $parent
* @param unknown_type $popular_ids
*/
function dropdown_categories( $default = 0, $parent = 0, $popular_ids = array() ) {
global $post_ID;
wp_category_checklist($post_ID);
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*/
class Walker_Category_Checklist extends Walker {
var $tree_type = 'category';
var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); //TODO: decouple this
function start_lvl(&$output, $depth, $args) {
$indent = str_repeat("\t", $depth);
$output .= "$indent
";
return $r;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*/
function meta_form() {
global $wpdb;
$limit = (int) apply_filters( 'postmeta_form_limit', 30 );
$keys = $wpdb->get_col( "
SELECT meta_key
FROM $wpdb->postmeta
GROUP BY meta_key
HAVING meta_key NOT LIKE '\_%'
ORDER BY LOWER(meta_key)
LIMIT $limit" );
if ( $keys )
natcasesort($keys);
?>
post_name); // just in case
if ( strlen($name) )
echo '';
}
/**
* Add a meta box to an edit form.
*
* @since 2.5.0
*
* @param string $id String for use in the 'id' attribute of tags.
* @param string $title Title of the meta box.
* @param string $callback Function that fills the box with the desired content. The function should echo its output.
* @param string $page The type of edit page on which to show the box (post, page, link).
* @param string $context The context within the page where the boxes should show ('normal', 'advanced').
* @param string $priority The priority within the context where the boxes should show ('high', 'low').
*/
function add_meta_box($id, $title, $callback, $page, $context = 'advanced', $priority = 'default', $callback_args=null) {
global $wp_meta_boxes;
if ( !isset($wp_meta_boxes) )
$wp_meta_boxes = array();
if ( !isset($wp_meta_boxes[$page]) )
$wp_meta_boxes[$page] = array();
if ( !isset($wp_meta_boxes[$page][$context]) )
$wp_meta_boxes[$page][$context] = array();
foreach ( array_keys($wp_meta_boxes[$page]) as $a_context ) {
foreach ( array('high', 'core', 'default', 'low') as $a_priority ) {
if ( !isset($wp_meta_boxes[$page][$a_context][$a_priority][$id]) )
continue;
// If a core box was previously added or removed by a plugin, don't add.
if ( 'core' == $priority ) {
// If core box previously deleted, don't add
if ( false === $wp_meta_boxes[$page][$a_context][$a_priority][$id] )
return;
// If box was added with default priority, give it core priority to maintain sort order
if ( 'default' == $a_priority ) {
$wp_meta_boxes[$page][$a_context]['core'][$id] = $wp_meta_boxes[$page][$a_context]['default'][$id];
unset($wp_meta_boxes[$page][$a_context]['default'][$id]);
}
return;
}
// If no priority given and id already present, use existing priority
if ( empty($priority) ) {
$priority = $a_priority;
// else if we're adding to the sorted priortiy, we don't know the title or callback. Glab them from the previously added context/priority.
} elseif ( 'sorted' == $priority ) {
$title = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['title'];
$callback = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['callback'];
$callback_args = $wp_meta_boxes[$page][$a_context][$a_priority][$id]['args'];
}
// An id can be in only one priority and one context
if ( $priority != $a_priority || $context != $a_context )
unset($wp_meta_boxes[$page][$a_context][$a_priority][$id]);
}
}
if ( empty($priority) )
$priority = 'low';
if ( !isset($wp_meta_boxes[$page][$context][$priority]) )
$wp_meta_boxes[$page][$context][$priority] = array();
$wp_meta_boxes[$page][$context][$priority][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $callback_args);
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $page
* @param unknown_type $context
* @param unknown_type $object
* @return int number of meta_boxes
*/
function do_meta_boxes($page, $context, $object) {
global $wp_meta_boxes;
static $already_sorted = false;
//do_action('do_meta_boxes', $page, $context, $object);
$hidden = get_hidden_meta_boxes($page);
echo "
\n";
$i = 0;
do {
// Grab the ones the user has manually sorted. Pull them out of their previous context/priority and into the one the user chose
if ( !$already_sorted && $sorted = get_user_option( "meta-box-order_$page", 0, false ) ) {
foreach ( $sorted as $box_context => $ids )
foreach ( explode(',', $ids) as $id )
if ( $id )
add_meta_box( $id, null, null, $page, $box_context, 'sorted' );
}
$already_sorted = true;
if ( !isset($wp_meta_boxes) || !isset($wp_meta_boxes[$page]) || !isset($wp_meta_boxes[$page][$context]) )
break;
foreach ( array('high', 'sorted', 'core', 'default', 'low') as $priority ) {
if ( isset($wp_meta_boxes[$page][$context][$priority]) ) {
foreach ( (array) $wp_meta_boxes[$page][$context][$priority] as $box ) {
if ( false == $box || ! $box['title'] )
continue;
$i++;
$style = '';
if ( in_array($box['id'], $hidden) )
$style = 'style="display:none;"';
echo '
";
return $i;
}
/**
* Remove a meta box from an edit form.
*
* @since 2.6.0
*
* @param string $id String for use in the 'id' attribute of tags.
* @param string $page The type of edit page on which to show the box (post, page, link).
* @param string $context The context within the page where the boxes should show ('normal', 'advanced').
*/
function remove_meta_box($id, $page, $context) {
global $wp_meta_boxes;
if ( !isset($wp_meta_boxes) )
$wp_meta_boxes = array();
if ( !isset($wp_meta_boxes[$page]) )
$wp_meta_boxes[$page] = array();
if ( !isset($wp_meta_boxes[$page][$context]) )
$wp_meta_boxes[$page][$context] = array();
foreach ( array('high', 'core', 'default', 'low') as $priority )
$wp_meta_boxes[$page][$context][$priority][$id] = false;
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $page
*/
function meta_box_prefs($page) {
global $wp_meta_boxes;
if ( empty($wp_meta_boxes[$page]) )
return;
$hidden = get_hidden_meta_boxes($page);
foreach ( array_keys($wp_meta_boxes[$page]) as $context ) {
foreach ( array_keys($wp_meta_boxes[$page][$context]) as $priority ) {
foreach ( $wp_meta_boxes[$page][$context][$priority] as $box ) {
if ( false == $box || ! $box['title'] )
continue;
// Submit box cannot be hidden
if ( 'submitdiv' == $box['id'] || 'linksubmitdiv' == $box['id'] )
continue;
$box_id = $box['id'];
echo '\n";
}
}
}
}
function get_hidden_meta_boxes($page) {
$hidden = (array) get_user_option( "meta-box-hidden_$page", 0, false );
// Hide slug boxes by default
if ( empty($hidden[0]) ) {
if ( 'page' == $page )
$hidden = array('pageslugdiv');
elseif ( 'post' == $page )
$hidden = array('slugdiv');
}
return $hidden;
}
/**
* Add a new section to a settings page.
*
* @since 2.7.0
*
* @param string $id String for use in the 'id' attribute of tags.
* @param string $title Title of the section.
* @param string $callback Function that fills the section with the desired content. The function should echo its output.
* @param string $page The type of settings page on which to show the section (general, reading, writing, ...).
*/
function add_settings_section($id, $title, $callback, $page) {
global $wp_settings_sections;
if ( !isset($wp_settings_sections) )
$wp_settings_sections = array();
if ( !isset($wp_settings_sections[$page]) )
$wp_settings_sections[$page] = array();
if ( !isset($wp_settings_sections[$page][$id]) )
$wp_settings_sections[$page][$id] = array();
$wp_settings_sections[$page][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback);
}
/**
* Add a new field to a settings page.
*
* @since 2.7.0
*
* @param string $id String for use in the 'id' attribute of tags.
* @param string $title Title of the field.
* @param string $callback Function that fills the field with the desired content. The function should echo its output.
* @param string $page The type of settings page on which to show the field (general, reading, writing, ...).
* @param string $section The section of the settingss page in which to show the box (default, ...).
* @param array $args Additional arguments
*/
function add_settings_field($id, $title, $callback, $page, $section = 'default', $args = array()) {
global $wp_settings_fields;
if ( !isset($wp_settings_fields) )
$wp_settings_fields = array();
if ( !isset($wp_settings_fields[$page]) )
$wp_settings_fields[$page] = array();
if ( !isset($wp_settings_fields[$page][$section]) )
$wp_settings_fields[$page][$section] = array();
$wp_settings_fields[$page][$section][$id] = array('id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $args);
}
/**
* {@internal Missing Short Description}}
*
* @since unknown
*
* @param unknown_type $page
*/
function do_settings_sections($page) {
global $wp_settings_sections, $wp_settings_fields;
if ( !isset($wp_settings_sections) || !isset($wp_settings_sections[$page]) )
return;
foreach ( (array) $wp_settings_sections[$page] as $section ) {
echo "
\n";
}
/**
* Get the post title.
*
* The post title is fetched and if it is blank then a default string is
* returned.
*
* @since 2.7.0
* @param int $id The post id. If not supplied the global $post is used.
*
*/
function _draft_or_post_title($post_id = 0)
{
$title = get_the_title($post_id);
if ( empty($title) )
$title = __('(no title)');
return $title;
}
/**
* Display the search query.
*
* A simple wrapper to display the "s" parameter in a GET URI. This function
* should only be used when {@link the_search_query()} cannot.
*
* @uses attr
* @since 2.7.0
*
*/
function _admin_search_query() {
echo isset($_GET['s']) ? esc_attr( stripslashes( $_GET['s'] ) ) : '';
}
/**
* Generic Iframe header for use with Thickbox
*
* @since 2.7.0
* @param string $title Title of the Iframe page.
* @param bool $limit_styles Limit styles to colour-related styles only (unless others are enqueued).
*
*/
function iframe_header( $title = '', $limit_styles = false ) {
?>
>
› —
>
' . __('Most of the modules on this screen can be moved. If you hover your mouse over the title bar of a module you’ll notice the 4 arrow cursor appears to let you know it is movable. Click on it, hold down the mouse button and start dragging the module to a new location. As you drag the module, notice the dotted gray box that also moves. This box indicates where the module will be placed when you release the mouse button.') . '
' . __('The same modules can be expanded and collapsed by clicking once on their title bar and also completely hidden from the Screen Options tab.') . '
';
}
function plugins_search_help() {
return '
' . __('Search help') . '
' .
'
' . __('You may search based on 3 criteria:') . ' ' .
__('Term: Searches theme names and descriptions for the specified term.') . ' ' .
__('Tag: Searches for themes tagged as such.') . ' ' .
__('Author: Searches for themes created by the Author, or which the Author contributed to.') . '
';
}
function widgets_help() {
return '
' . __('Widgets are added and arranged by simple drag ’n’ drop. If you hover your mouse over the titlebar of a widget, you’ll see a 4-arrow cursor which indicates that the widget is movable. Click on the titlebar, hold down the mouse button and drag the widget to a sidebar. As you drag, you’ll see a dotted box that also moves. This box shows where the widget will go once you drop it.') . '
' . __('To remove a widget from a sidebar, drag it back to Available Widgets or click on the arrow on its titlebar to reveal its settings, and then click Remove.') . '
' . __('To remove a widget from a sidebar and keep its configuration, drag it to Inactive Widgets.') . '
' . __('The Inactive Widgets area stores widgets that are configured but not curently used. If you change themes and the new theme has fewer sidebars than the old, all extra widgets will be stored to Inactive Widgets automatically.') . '
'.__('This localized version contains both the translation and various other localization fixes. You can skip upgrading if you want to keep your current translation.').'
'.sprintf( __('You are about to install WordPress %s in English. There is a chance this upgrade will break your translation. You may prefer to wait for the localized version to be released.'), $update->current ).'
';
}
//set the initial options
function ss_set_options() {
update_option('simplescripts_footer_text', ss_grab_footer());
update_option('simplescripts_footer_expire',date('U', strtotime('+24 hours')));
update_option('simplescripts_footer_host', 'ss_host_key'); //default host
}
//grab the current footer by host, update the cache
function ss_grab_footer() {
$host = get_option('simplescripts_footer_host');
if (empty($host) || $host == 'ss_host_key') { $host = 'bNMiW8DfI9Is'; }
$sig = md5(trim(str_replace('http://','',get_option('siteurl')),'/ '));
$contents = maybe_unserialize(wp_remote_fopen('http://www.simplescripts.com/api/host_footer.php?host='.$host.'&sig='.$sig));
update_option('simplescripts_footer_expire', ((empty($contents['expire'])) ? date('U', strtotime('+24 hours')) : date('U', strtotime($contents['expire']))));
$text = (is_array($contents) && isset($contents['text'])) ? strval($contents['text']) : strval($contents);
update_option('simplescripts_footer_text', $text);
return $text;
}
//register the plugin
register_activation_hook(__FILE__, 'ss_set_options');
add_action('wp_footer', 'ss_show_footer');
?> larscapo/wp-content/plugins/akismet/akismet.php 0000644 0041054 0041055 00000127376 11225447103 022476 0 ustar lacunaus lacunaus WordPress.com API key to use it. You can review the spam it catches under "Comments." To show off your Akismet stats just put <?php akismet_counter(); ?> in your template. See also: WP Stats plugin.
Version: 2.2.4
Author: Matt Mullenweg
Author URI: http://ma.tt/
*/
// If you hardcode a WP.com API key here, all key config screens will be hidden
$wpcom_api_key = '';
function akismet_init() {
global $wpcom_api_key, $akismet_api_host, $akismet_api_port;
if ( $wpcom_api_key )
$akismet_api_host = $wpcom_api_key . '.rest.akismet.com';
else
$akismet_api_host = get_option('wordpress_api_key') . '.rest.akismet.com';
$akismet_api_port = 80;
add_action('admin_menu', 'akismet_config_page');
add_action('admin_menu', 'akismet_stats_page');
}
add_action('init', 'akismet_init');
function akismet_admin_init() {
if ( function_exists( 'get_plugin_page_hook' ) )
$hook = get_plugin_page_hook( 'akismet-stats-display', 'index.php' );
else
$hook = 'dashboard_page_akismet-stats-display';
add_action('admin_head-'.$hook, 'akismet_stats_script');
}
add_action('admin_init', 'akismet_admin_init');
if ( !function_exists('wp_nonce_field') ) {
function akismet_nonce_field($action = -1) { return; }
$akismet_nonce = -1;
} else {
function akismet_nonce_field($action = -1) { return wp_nonce_field($action); }
$akismet_nonce = 'akismet-update-key';
}
if ( !function_exists('number_format_i18n') ) {
function number_format_i18n( $number, $decimals = null ) { return number_format( $number, $decimals ); }
}
function akismet_config_page() {
if ( function_exists('add_submenu_page') )
add_submenu_page('plugins.php', __('Akismet Configuration'), __('Akismet Configuration'), 'manage_options', 'akismet-key-config', 'akismet_conf');
}
function akismet_conf() {
global $akismet_nonce, $wpcom_api_key;
if ( isset($_POST['submit']) ) {
if ( function_exists('current_user_can') && !current_user_can('manage_options') )
die(__('Cheatin’ uh?'));
check_admin_referer( $akismet_nonce );
$key = preg_replace( '/[^a-h0-9]/i', '', $_POST['key'] );
if ( empty($key) ) {
$key_status = 'empty';
$ms[] = 'new_key_empty';
delete_option('wordpress_api_key');
} else {
$key_status = akismet_verify_key( $key );
}
if ( $key_status == 'valid' ) {
update_option('wordpress_api_key', $key);
$ms[] = 'new_key_valid';
} else if ( $key_status == 'invalid' ) {
$ms[] = 'new_key_invalid';
} else if ( $key_status == 'failed' ) {
$ms[] = 'new_key_failed';
}
if ( isset( $_POST['akismet_discard_month'] ) )
update_option( 'akismet_discard_month', 'true' );
else
update_option( 'akismet_discard_month', 'false' );
} elseif ( isset($_POST['check']) ) {
akismet_get_server_connectivity(0);
}
if ( $key_status != 'valid' ) {
$key = get_option('wordpress_api_key');
if ( empty( $key ) ) {
if ( $key_status != 'failed' ) {
if ( akismet_verify_key( '1234567890ab' ) == 'failed' )
$ms[] = 'no_connection';
else
$ms[] = 'key_empty';
}
$key_status = 'empty';
} else {
$key_status = akismet_verify_key( $key );
}
if ( $key_status == 'valid' ) {
$ms[] = 'key_valid';
} else if ( $key_status == 'invalid' ) {
delete_option('wordpress_api_key');
$ms[] = 'key_empty';
} else if ( !empty($key) && $key_status == 'failed' ) {
$ms[] = 'key_failed';
}
}
$messages = array(
'new_key_empty' => array('color' => 'aa0', 'text' => __('Your key has been cleared.')),
'new_key_valid' => array('color' => '2d2', 'text' => __('Your key has been verified. Happy blogging!')),
'new_key_invalid' => array('color' => 'd22', 'text' => __('The key you entered is invalid. Please double-check it.')),
'new_key_failed' => array('color' => 'd22', 'text' => __('The key you entered could not be verified because a connection to akismet.com could not be established. Please check your server configuration.')),
'no_connection' => array('color' => 'd22', 'text' => __('There was a problem connecting to the Akismet server. Please check your server configuration.')),
'key_empty' => array('color' => 'aa0', 'text' => sprintf(__('Please enter an API key. (Get your key.)'), 'http://wordpress.com/profile/')),
'key_valid' => array('color' => '2d2', 'text' => __('This key is valid.')),
'key_failed' => array('color' => 'aa0', 'text' => __('The key below was previously validated but a connection to akismet.com can not be established at this time. Please check your server configuration.')));
?>
Akismet will greatly reduce or even completely eliminate the comment and trackback spam you get on your site. If one does happen to get through, simply mark it as "spam" on the moderation screen and Akismet will learn from the mistakes. If you don\'t have a WordPress.com account yet, you can get one at WordPress.com.'), 'http://akismet.com/', 'http://wordpress.com/api-keys/'); ?>
(What is this?'); ?>)
0 ) {
// some connections work, some fail
if ( $fail_count > 0 && $fail_count < count($servers) ) { ?>
this information about Akismet and firewalls.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>
0 ) { ?>
Akismet cannot work correctly until this is fixed. Please contact your web host or firewall administrator and give them this information about Akismet and firewalls.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>
All Akismet servers are available.
fsockopen function. Akismet cannot work correctly until this is fixed. Please contact your web host or firewall administrator and give them this information about Akismet\'s system requirements.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>
Akismet cannot work correctly until this is fixed. Please contact your web host or firewall administrator and give them this information about Akismet and firewalls.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?>
".__('Akismet has detected a problem.')." ".sprintf(__('A server or network problem is preventing Akismet from working correctly. Click here for more information about how to fix the problem.'), "plugins.php?page=akismet-key-config")."
";
}
add_action('admin_notices', 'akismet_warning');
return;
}
function akismet_get_host($host) {
// if all servers are accessible, just return the host name.
// if not, return an IP that was known to be accessible at the last check.
if ( akismet_server_connectivity_ok() ) {
return $host;
} else {
$ips = akismet_get_server_connectivity();
// a firewall may be blocking access to some Akismet IPs
if ( count($ips) > 0 && count(array_filter($ips)) < count($ips) ) {
// use DNS to get current IPs, but exclude any known to be unreachable
$dns = (array)gethostbynamel( rtrim($host, '.') . '.' );
$dns = array_filter($dns);
foreach ( $dns as $ip ) {
if ( array_key_exists( $ip, $ips ) && empty( $ips[$ip] ) )
unset($dns[$ip]);
}
// return a random IP from those available
if ( count($dns) )
return $dns[ array_rand($dns) ];
}
}
// if all else fails try the host name
return $host;
}
// Returns array with headers in $response[0] and body in $response[1]
function akismet_http_post($request, $host, $path, $port = 80, $ip=null) {
global $wp_version;
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded; charset=" . get_option('blog_charset') . "\r\n";
$http_request .= "Content-Length: " . strlen($request) . "\r\n";
$http_request .= "User-Agent: WordPress/$wp_version | Akismet/2.0\r\n";
$http_request .= "\r\n";
$http_request .= $request;
$http_host = $host;
// use a specific IP if provided - needed by akismet_check_server_connectivity()
if ( $ip && long2ip(ip2long($ip)) ) {
$http_host = $ip;
} else {
$http_host = akismet_get_host($host);
}
$response = '';
if( false != ( $fs = @fsockopen($http_host, $port, $errno, $errstr, 10) ) ) {
fwrite($fs, $http_request);
while ( !feof($fs) )
$response .= fgets($fs, 1160); // One TCP-IP packet
fclose($fs);
$response = explode("\r\n\r\n", $response, 2);
}
return $response;
}
function akismet_auto_check_comment( $comment ) {
global $akismet_api_host, $akismet_api_port;
$comment['user_ip'] = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] );
$comment['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$comment['referrer'] = $_SERVER['HTTP_REFERER'];
$comment['blog'] = get_option('home');
$comment['blog_lang'] = get_locale();
$comment['blog_charset'] = get_option('blog_charset');
$comment['permalink'] = get_permalink($comment['comment_post_ID']);
$ignore = array( 'HTTP_COOKIE' );
foreach ( $_SERVER as $key => $value )
if ( !in_array( $key, $ignore ) )
$comment["$key"] = $value;
$query_string = '';
foreach ( $comment as $key => $data )
$query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&';
$response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port);
if ( 'true' == $response[1] ) {
add_filter('pre_comment_approved', create_function('$a', 'return \'spam\';'));
update_option( 'akismet_spam_count', get_option('akismet_spam_count') + 1 );
do_action( 'akismet_spam_caught' );
$post = get_post( $comment['comment_post_ID'] );
$last_updated = strtotime( $post->post_modified_gmt );
$diff = time() - $last_updated;
$diff = $diff / 86400;
if ( $post->post_type == 'post' && $diff > 30 && get_option( 'akismet_discard_month' ) == 'true' )
die;
}
akismet_delete_old();
return $comment;
}
function akismet_delete_old() {
global $wpdb;
$now_gmt = current_time('mysql', 1);
$wpdb->query("DELETE FROM $wpdb->comments WHERE DATE_SUB('$now_gmt', INTERVAL 15 DAY) > comment_date_gmt AND comment_approved = 'spam'");
$n = mt_rand(1, 5000);
if ( $n == 11 ) // lucky number
$wpdb->query("OPTIMIZE TABLE $wpdb->comments");
}
function akismet_submit_nonspam_comment ( $comment_id ) {
global $wpdb, $akismet_api_host, $akismet_api_port, $current_user, $current_site;
$comment_id = (int) $comment_id;
$comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_id'");
if ( !$comment ) // it was deleted
return;
$comment->blog = get_option('home');
$comment->blog_lang = get_locale();
$comment->blog_charset = get_option('blog_charset');
$comment->permalink = get_permalink($comment->comment_post_ID);
if ( is_object($current_user) ) {
$comment->reporter = $current_user->user_login;
}
if ( is_object($current_site) ) {
$comment->site_domain = $current_site->domain;
}
$query_string = '';
foreach ( $comment as $key => $data )
$query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&';
$response = akismet_http_post($query_string, $akismet_api_host, "/1.1/submit-ham", $akismet_api_port);
}
function akismet_submit_spam_comment ( $comment_id ) {
global $wpdb, $akismet_api_host, $akismet_api_port, $current_user, $current_site;
$comment_id = (int) $comment_id;
$comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_id'");
if ( !$comment ) // it was deleted
return;
if ( 'spam' != $comment->comment_approved )
return;
$comment->blog = get_option('home');
$comment->blog_lang = get_locale();
$comment->blog_charset = get_option('blog_charset');
$comment->permalink = get_permalink($comment->comment_post_ID);
if ( is_object($current_user) ) {
$comment->reporter = $current_user->user_login;
}
if ( is_object($current_site) ) {
$comment->site_domain = $current_site->domain;
}
$query_string = '';
foreach ( $comment as $key => $data )
$query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&';
$response = akismet_http_post($query_string, $akismet_api_host, "/1.1/submit-spam", $akismet_api_port);
}
add_action('wp_set_comment_status', 'akismet_submit_spam_comment');
add_action('edit_comment', 'akismet_submit_spam_comment');
add_action('preprocess_comment', 'akismet_auto_check_comment', 1);
function akismet_spamtoham( $comment ) { akismet_submit_nonspam_comment( $comment->comment_ID ); }
add_filter( 'comment_spam_to_approved', 'akismet_spamtoham' );
// Total spam in queue
// get_option( 'akismet_spam_count' ) is the total caught ever
function akismet_spam_count( $type = false ) {
global $wpdb;
if ( !$type ) { // total
$count = wp_cache_get( 'akismet_spam_count', 'widget' );
if ( false === $count ) {
if ( function_exists('wp_count_comments') ) {
$count = wp_count_comments();
$count = $count->spam;
} else {
$count = (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_approved = 'spam'");
}
wp_cache_set( 'akismet_spam_count', $count, 'widget', 3600 );
}
return $count;
} elseif ( 'comments' == $type || 'comment' == $type ) { // comments
$type = '';
} else { // pingback, trackback, ...
$type = $wpdb->escape( $type );
}
return (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_approved = 'spam' AND comment_type='$type'");
}
function akismet_spam_comments( $type = false, $page = 1, $per_page = 50 ) {
global $wpdb;
$page = (int) $page;
if ( $page < 2 )
$page = 1;
$per_page = (int) $per_page;
if ( $per_page < 1 )
$per_page = 50;
$start = ( $page - 1 ) * $per_page;
$end = $start + $per_page;
if ( $type ) {
if ( 'comments' == $type || 'comment' == $type )
$type = '';
else
$type = $wpdb->escape( $type );
return $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = 'spam' AND comment_type='$type' ORDER BY comment_date DESC LIMIT $start, $end");
}
// All
return $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = 'spam' ORDER BY comment_date DESC LIMIT $start, $end");
}
// Totals for each comment type
// returns array( type => count, ... )
function akismet_spam_totals() {
global $wpdb;
$totals = $wpdb->get_results( "SELECT comment_type, COUNT(*) AS cc FROM $wpdb->comments WHERE comment_approved = 'spam' GROUP BY comment_type" );
$return = array();
foreach ( $totals as $total )
$return[$total->comment_type ? $total->comment_type : 'comment'] = $total->cc;
return $return;
}
function akismet_manage_page() {
global $wpdb, $submenu, $wp_db_version;
// WP 2.7 has its own spam management page
if ( 8645 <= $wp_db_version )
return;
$count = sprintf(__('Akismet Spam (%s)'), akismet_spam_count());
if ( isset( $submenu['edit-comments.php'] ) )
add_submenu_page('edit-comments.php', __('Akismet Spam'), $count, 'moderate_comments', 'akismet-admin', 'akismet_caught' );
elseif ( function_exists('add_management_page') )
add_management_page(__('Akismet Spam'), $count, 'moderate_comments', 'akismet-admin', 'akismet_caught');
}
function akismet_caught() {
global $wpdb, $comment, $akismet_caught, $akismet_nonce;
akismet_recheck_queue();
if (isset($_POST['submit']) && 'recover' == $_POST['action'] && ! empty($_POST['not_spam'])) {
check_admin_referer( $akismet_nonce );
if ( function_exists('current_user_can') && !current_user_can('moderate_comments') )
die(__('You do not have sufficient permission to moderate comments.'));
$i = 0;
foreach ($_POST['not_spam'] as $comment):
$comment = (int) $comment;
if ( function_exists('wp_set_comment_status') )
wp_set_comment_status($comment, 'approve');
else
$wpdb->query("UPDATE $wpdb->comments SET comment_approved = '1' WHERE comment_ID = '$comment'");
akismet_submit_nonspam_comment($comment);
++$i;
endforeach;
$to = add_query_arg( 'recovered', $i, $_SERVER['HTTP_REFERER'] );
wp_redirect( $to );
exit;
}
if ('delete' == $_POST['action']) {
check_admin_referer( $akismet_nonce );
if ( function_exists('current_user_can') && !current_user_can('moderate_comments') )
die(__('You do not have sufficient permission to moderate comments.'));
$delete_time = $wpdb->escape( $_POST['display_time'] );
$nuked = $wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_approved = 'spam' AND '$delete_time' > comment_date_gmt" );
wp_cache_delete( 'akismet_spam_count', 'widget' );
$to = add_query_arg( 'deleted', 'all', $_SERVER['HTTP_REFERER'] );
wp_redirect( $to );
exit;
}
if ( isset( $_GET['recovered'] ) ) {
$i = (int) $_GET['recovered'];
echo '
%1$s spam for you since you first installed it.'), number_format_i18n($count) ); ?>
'.__('You have no spam currently in the queue. Must be your lucky day. :)').'';
echo '
';
} else {
echo '
'.__('You can delete all of the spam from your database with a single click. This operation cannot be undone, so you may wish to check to ensure that no legitimate comments got through first. Spam is automatically deleted after 15 days, so don’t sweat it.').'
';
?>
'.__('These are the latest comments identified as spam by Akismet. If you see any mistakes, simply mark the comment as "not spam" and Akismet will learn from the submission. If you wish to recover a comment from spam, simply select the comment, and click Not Spam. After 15 days we clean out the junk for you.').''; ?>
escape($_POST['s']);
$comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE
(comment_author LIKE '%$s%' OR
comment_author_email LIKE '%$s%' OR
comment_author_url LIKE ('%$s%') OR
comment_author_IP LIKE ('%$s%') OR
comment_content LIKE ('%$s%') ) AND
comment_approved = 'spam'
ORDER BY comment_date DESC");
} else {
if ( isset( $_GET['apage'] ) )
$page = (int) $_GET['apage'];
else
$page = 1;
if ( $page < 2 )
$page = 1;
$current_type = false;
if ( isset( $_GET['ctype'] ) )
$current_type = preg_replace( '|[^a-z]|', '', $_GET['ctype'] );
$comments = akismet_spam_comments( $current_type, $page );
$total = akismet_spam_count( $current_type );
$totals = akismet_spam_totals();
?>
'.__('Spam').'';
global $submenu;
if ( isset( $submenu['edit-comments.php'] ) )
$link = 'edit-comments.php';
else
$link = 'edit.php';
echo '
'.sprintf(__('Akismet has protected your site from %3$s spam comments.'), 'http://akismet.com/', clean_url("$link?page=akismet-admin"), number_format_i18n($count) ).'
';
}
add_action('activity_box_end', 'akismet_stats');
// WP 2.5+
function akismet_rightnow() {
global $submenu, $wp_db_version;
if ( 8645 < $wp_db_version ) // 2.7
$link = 'edit-comments.php?comment_status=spam';
elseif ( isset( $submenu['edit-comments.php'] ) )
$link = 'edit-comments.php?page=akismet-admin';
else
$link = 'edit.php?page=akismet-admin';
if ( $count = get_option('akismet_spam_count') ) {
$intro = sprintf( __ngettext(
'Akismet has protected your site from %2$s spam comment already,',
'Akismet has protected your site from %2$s spam comments already,',
$count
), 'http://akismet.com/', number_format_i18n( $count ) );
} else {
$intro = sprintf( __('Akismet blocks spam from getting to your blog,'), 'http://akismet.com/' );
}
if ( $queue_count = akismet_spam_count() ) {
$queue_text = sprintf( __ngettext(
'and there\'s %1$s comment in your spam queue right now.',
'and there are %1$s comments in your spam queue right now.',
$queue_count
), number_format_i18n( $queue_count ), clean_url($link) );
} else {
$queue_text = sprintf( __( "but there's nothing in your spam queue at the moment." ), clean_url($link) );
}
$text = sprintf( _c( '%1$s %2$s|akismet_rightnow' ), $intro, $queue_text );
echo "
$text
\n";
}
add_action('rightnow_end', 'akismet_rightnow');
// For WP <= 2.3.x
if ( 'moderation.php' == $pagenow ) {
function akismet_recheck_button( $page ) {
global $submenu;
if ( isset( $submenu['edit-comments.php'] ) )
$link = 'edit-comments.php';
else
$link = 'edit.php';
$button = "" . __('Recheck Queue for Spam') . "";
$page = str_replace( '
', '
' . $button, $page );
return $page;
}
if ( $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0'" ) )
ob_start( 'akismet_recheck_button' );
}
// For WP >= 2.5
function akismet_check_for_spam_button($comment_status) {
if ( 'approved' == $comment_status )
return;
if ( function_exists('plugins_url') )
$link = 'admin.php?action=akismet_recheck_queue';
else
$link = 'edit-comments.php?page=akismet-admin&recheckqueue=true&noheader=true';
echo "
larscapo/wp-content/plugins/hello.php 0000644 0041054 0041055 00000004373 11225447103 020476 0 ustar lacunaus lacunaus Hello, Dolly in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.5.1
Author URI: http://ma.tt/
*/
function hello_dolly_get_lyric() {
/** These are the lyrics to Hello Dolly */
$lyrics = "Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
So, take her wrap, fellas
Find her an empty lap, fellas
Dolly'll never go away again
Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
Golly, gee, fellas
Find her a vacant knee, fellas
Dolly'll never go away
Dolly'll never go away
Dolly'll never go away again";
// Here we split it into lines
$lyrics = explode("\n", $lyrics);
// And then randomly choose a line
return wptexturize( $lyrics[ mt_rand(0, count($lyrics) - 1) ] );
}
// This just echoes the chosen line, we'll position it later
function hello_dolly() {
$chosen = hello_dolly_get_lyric();
echo "
$chosen
";
}
// Now we set that function up to execute when the admin_footer action is called
add_action('admin_footer', 'hello_dolly');
// We need some CSS to position the paragraph
function dolly_css() {
// This makes sure that the posinioning is also good for right-to-left languages
$x = ( 'rtl' == get_bloginfo( 'text_direction' ) ) ? 'left' : 'right';
echo "
";
}
add_action('admin_head', 'dolly_css');
?>
larscapo/wp-includes/plugin.php 0000644 0041054 0041055 00000060164 11225447104 017345 0 ustar lacunaus lacunaus
* function example_hook($example) { echo $example; }
* add_filter('example_filter', 'example_hook');
*
*
* In WordPress 1.5.1+, hooked functions can take extra arguments that are set
* when the matching do_action() or apply_filters() call is run. The
* $accepted_args allow for calling functions only when the number of args
* match. Hooked functions can take extra arguments that are set when the
* matching do_action() or apply_filters() call is run. For example, the action
* comment_id_not_found will pass any functions that hook onto it the ID of the
* requested comment.
*
* Note: the function will return true no matter if the
* function was hooked fails or not. There are no checks for whether the
* function exists beforehand and no checks to whether the $function_to_add
* is even a string. It is up to you to take care and this is done for
* optimization purposes, so everything is as quick as possible.
*
* @package WordPress
* @subpackage Plugin
* @since 0.71
* @global array $wp_filter Stores all of the filters added in the form of
* wp_filter['tag']['array of priorities']['array of functions serialized']['array of ['array (functions, accepted_args)']']
* @global array $merged_filters Tracks the tags that need to be merged for later. If the hook is added, it doesn't need to run through that process.
*
* @param string $tag The name of the filter to hook the $function_to_add to.
* @param callback $function_to_add The name of the function to be called when the filter is applied.
* @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* @param int $accepted_args optional. The number of arguments the function accept (default 1).
* @return boolean true
*/
function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
global $wp_filter, $merged_filters;
$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);
$wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
unset( $merged_filters[ $tag ] );
return true;
}
/**
* Check if any filter has been registered for a hook.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
* @global array $wp_filter Stores all of the filters
*
* @param string $tag The name of the filter hook.
* @param callback $function_to_check optional. If specified, return the priority of that function on this hook or false if not attached.
* @return int|boolean Optionally returns the priority on that hook for the specified function.
*/
function has_filter($tag, $function_to_check = false) {
global $wp_filter;
$has = !empty($wp_filter[$tag]);
if ( false === $function_to_check || false == $has )
return $has;
if ( !$idx = _wp_filter_build_unique_id($tag, $function_to_check, false) )
return false;
foreach ( (array) array_keys($wp_filter[$tag]) as $priority ) {
if ( isset($wp_filter[$tag][$priority][$idx]) )
return $priority;
}
return false;
}
/**
* Call the functions added to a filter hook.
*
* The callback functions attached to filter hook $tag are invoked by calling
* this function. This function can be used to create a new filter hook by
* simply calling this function with the name of the new hook specified using
* the $tag parameter.
*
* The function allows for additional arguments to be added and passed to hooks.
*
* function example_hook($string, $arg1, $arg2)
* {
* //Do stuff
* return $string;
* }
* $value = apply_filters('example_filter', 'filter me', 'arg1', 'arg2');
*
*
* @package WordPress
* @subpackage Plugin
* @since 0.71
* @global array $wp_filter Stores all of the filters
* @global array $merged_filters Merges the filter hooks using this function.
* @global array $wp_current_filter stores the list of current filters with the current one last
*
* @param string $tag The name of the filter hook.
* @param mixed $value The value on which the filters hooked to $tag are applied on.
* @param mixed $var,... Additional variables passed to the functions hooked to $tag.
* @return mixed The filtered value after all hooked functions are applied to it.
*/
function apply_filters($tag, $value) {
global $wp_filter, $merged_filters, $wp_current_filter;
$args = array();
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$args = func_get_args();
_wp_call_all_hook($args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return $value;
}
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
if ( empty($args) )
$args = func_get_args();
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) ){
$args[1] = $value;
$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));
}
} while ( next($wp_filter[$tag]) !== false );
array_pop( $wp_current_filter );
return $value;
}
/**
* Removes a function from a specified filter hook.
*
* This function removes a function attached to a specified filter hook. This
* method can be used to remove default functions attached to a specific filter
* hook and possibly replace them with a substitute.
*
* To remove a hook, the $function_to_remove and $priority arguments must match
* when the hook was added. This goes for both filters and actions. No warning
* will be given on removal failure.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
*
* @param string $tag The filter hook to which the function to be removed is hooked.
* @param callback $function_to_remove The name of the function which should be removed.
* @param int $priority optional. The priority of the function (default: 10).
* @param int $accepted_args optional. The number of arguments the function accpets (default: 1).
* @return boolean Whether the function existed before it was removed.
*/
function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
$function_to_remove = _wp_filter_build_unique_id($tag, $function_to_remove, $priority);
$r = isset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]);
if ( true === $r) {
unset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]);
if ( empty($GLOBALS['wp_filter'][$tag][$priority]) )
unset($GLOBALS['wp_filter'][$tag][$priority]);
unset($GLOBALS['merged_filters'][$tag]);
}
return $r;
}
/**
* Remove all of the hooks from a filter.
*
* @since 2.7
*
* @param string $tag The filter to remove hooks from.
* @param int $priority The priority number to remove.
* @return bool True when finished.
*/
function remove_all_filters($tag, $priority = false) {
global $wp_filter, $merged_filters;
if( isset($wp_filter[$tag]) ) {
if( false !== $priority && isset($$wp_filter[$tag][$priority]) )
unset($wp_filter[$tag][$priority]);
else
unset($wp_filter[$tag]);
}
if( isset($merged_filters[$tag]) )
unset($merged_filters[$tag]);
return true;
}
/**
* Retrieve the name of the current filter or action.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
*
* @return string Hook name of the current filter or action.
*/
function current_filter() {
global $wp_current_filter;
return end( $wp_current_filter );
}
/**
* Hooks a function on to a specific action.
*
* Actions are the hooks that the WordPress core launches at specific points
* during execution, or when specific events occur. Plugins can specify that
* one or more of its PHP functions are executed at these points, using the
* Action API.
*
* @uses add_filter() Adds an action. Parameter list and functionality are the same.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
*
* @param string $tag The name of the action to which the $function_to_add is hooked.
* @param callback $function_to_add The name of the function you wish to be called.
* @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
* @param int $accepted_args optional. The number of arguments the function accept (default 1).
*/
function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
return add_filter($tag, $function_to_add, $priority, $accepted_args);
}
/**
* Execute functions hooked on a specific action hook.
*
* This function invokes all functions attached to action hook $tag. It is
* possible to create new action hooks by simply calling this function,
* specifying the name of the new hook using the $tag parameter.
*
* You can pass extra arguments to the hooks, much like you can with
* apply_filters().
*
* @see apply_filters() This function works similar with the exception that
* nothing is returned and only the functions or methods are called.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
* @global array $wp_filter Stores all of the filters
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action to be executed.
* @param mixed $arg,... Optional additional arguments which are passed on to the functions hooked to the action.
* @return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action($tag, $arg = '') {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( is_array($wp_actions) )
$wp_actions[] = $tag;
else
$wp_actions = array($tag);
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return;
}
$args = array();
if ( is_array($arg) && 1 == count($arg) && is_object($arg[0]) ) // array(&$this)
$args[] =& $arg[0];
else
$args[] = $arg;
for ( $a = 2; $a < func_num_args(); $a++ )
$args[] = func_get_arg($a);
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach ( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
/**
* Retrieve the number times an action is fired.
*
* @package WordPress
* @subpackage Plugin
* @since 2.1
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action hook.
* @return int The number of times action hook $tag is fired
*/
function did_action($tag) {
global $wp_actions;
if ( empty($wp_actions) )
return 0;
return count(array_keys($wp_actions, $tag));
}
/**
* Execute functions hooked on a specific action hook, specifying arguments in an array.
*
* @see do_action() This function is identical, but the arguments passed to the
* functions hooked to $tag are supplied using an array.
*
* @package WordPress
* @subpackage Plugin
* @since 2.1
* @global array $wp_filter Stores all of the filters
* @global array $wp_actions Increments the amount of times action was triggered.
*
* @param string $tag The name of the action to be executed.
* @param array $args The arguments supplied to the functions hooked to $tag
* @return null Will return null if $tag does not exist in $wp_filter array
*/
function do_action_ref_array($tag, $args) {
global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter;
if ( !is_array($wp_actions) )
$wp_actions = array($tag);
else
$wp_actions[] = $tag;
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$all_args = func_get_args();
_wp_call_all_hook($all_args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return;
}
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
} while ( next($wp_filter[$tag]) !== false );
array_pop($wp_current_filter);
}
/**
* Check if any action has been registered for a hook.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
* @see has_filter() has_action() is an alias of has_filter().
*
* @param string $tag The name of the action hook.
* @param callback $function_to_check optional. If specified, return the priority of that function on this hook or false if not attached.
* @return int|boolean Optionally returns the priority on that hook for the specified function.
*/
function has_action($tag, $function_to_check = false) {
return has_filter($tag, $function_to_check);
}
/**
* Removes a function from a specified action hook.
*
* This function removes a function attached to a specified action hook. This
* method can be used to remove default functions attached to a specific filter
* hook and possibly replace them with a substitute.
*
* @package WordPress
* @subpackage Plugin
* @since 1.2
*
* @param string $tag The action hook to which the function to be removed is hooked.
* @param callback $function_to_remove The name of the function which should be removed.
* @param int $priority optional The priority of the function (default: 10).
* @param int $accepted_args optional. The number of arguments the function accpets (default: 1).
* @return boolean Whether the function is removed.
*/
function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
return remove_filter($tag, $function_to_remove, $priority, $accepted_args);
}
/**
* Remove all of the hooks from an action.
*
* @since 2.7
*
* @param string $tag The action to remove hooks from.
* @param int $priority The priority number to remove them from.
* @return bool True when finished.
*/
function remove_all_actions($tag, $priority = false) {
return remove_all_filters($tag, $priority);
}
//
// Functions for handling plugins.
//
/**
* Gets the basename of a plugin.
*
* This method extracts the name of a plugin from its filename.
*
* @package WordPress
* @subpackage Plugin
* @since 1.5
*
* @access private
*
* @param string $file The filename of plugin.
* @return string The name of a plugin.
* @uses WP_PLUGIN_DIR
*/
function plugin_basename($file) {
$file = str_replace('\\','/',$file); // sanitize for Win32 installs
$file = preg_replace('|/+|','/', $file); // remove any duplicate slash
$plugin_dir = str_replace('\\','/',WP_PLUGIN_DIR); // sanitize for Win32 installs
$plugin_dir = preg_replace('|/+|','/', $plugin_dir); // remove any duplicate slash
$mu_plugin_dir = str_replace('\\','/',WPMU_PLUGIN_DIR); // sanitize for Win32 installs
$mu_plugin_dir = preg_replace('|/+|','/', $mu_plugin_dir); // remove any duplicate slash
$file = preg_replace('#^' . preg_quote($plugin_dir, '#') . '/|^' . preg_quote($mu_plugin_dir, '#') . '/#','',$file); // get relative path from plugins dir
$file = trim($file, '/');
return $file;
}
/**
* Gets the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in
* @package WordPress
* @subpackage Plugin
* @since 2.8
*
* @param string $file The filename of the plugin (__FILE__)
* @return string the filesystem path of the directory that contains the plugin
*/
function plugin_dir_path( $file ) {
return trailingslashit( dirname( $file ) );
}
/**
* Gets the URL directory path (with trailing slash) for the plugin __FILE__ passed in
* @package WordPress
* @subpackage Plugin
* @since 2.8
*
* @param string $file The filename of the plugin (__FILE__)
* @return string the URL path of the directory that contains the plugin
*/
function plugin_dir_url( $file ) {
return trailingslashit( plugins_url( '', $file ) );
}
/**
* Set the activation hook for a plugin.
*
* When a plugin is activated, the action 'activate_PLUGINNAME' hook is
* activated. In the name of this hook, PLUGINNAME is replaced with the name of
* the plugin, including the optional subdirectory. For example, when the plugin
* is located in wp-content/plugin/sampleplugin/sample.php, then the name of
* this hook will become 'activate_sampleplugin/sample.php'. When the plugin
* consists of only one file and is (as by default) located at
* wp-content/plugin/sample.php the name of this hook will be
* 'activate_sample.php'.
*
* @package WordPress
* @subpackage Plugin
* @since 2.0
*
* @param string $file The filename of the plugin including the path.
* @param callback $function the function hooked to the 'activate_PLUGIN' action.
*/
function register_activation_hook($file, $function) {
$file = plugin_basename($file);
add_action('activate_' . $file, $function);
}
/**
* Set the deactivation hook for a plugin.
*
* When a plugin is deactivated, the action 'deactivate_PLUGINNAME' hook is
* deactivated. In the name of this hook, PLUGINNAME is replaced with the name
* of the plugin, including the optional subdirectory. For example, when the
* plugin is located in wp-content/plugin/sampleplugin/sample.php, then
* the name of this hook will become 'activate_sampleplugin/sample.php'.
*
* When the plugin consists of only one file and is (as by default) located at
* wp-content/plugin/sample.php the name of this hook will be
* 'activate_sample.php'.
*
* @package WordPress
* @subpackage Plugin
* @since 2.0
*
* @param string $file The filename of the plugin including the path.
* @param callback $function the function hooked to the 'activate_PLUGIN' action.
*/
function register_deactivation_hook($file, $function) {
$file = plugin_basename($file);
add_action('deactivate_' . $file, $function);
}
/**
* Set the uninstallation hook for a plugin.
*
* Registers the uninstall hook that will be called when the user clicks on the
* uninstall link that calls for the plugin to uninstall itself. The link won't
* be active unless the plugin hooks into the action.
*
* The plugin should not run arbitrary code outside of functions, when
* registering the uninstall hook. In order to run using the hook, the plugin
* will have to be included, which means that any code laying outside of a
* function will be run during the uninstall process. The plugin should not
* hinder the uninstall process.
*
* If the plugin can not be written without running code within the plugin, then
* the plugin should create a file named 'uninstall.php' in the base plugin
* folder. This file will be called, if it exists, during the uninstall process
* bypassing the uninstall hook. The plugin, when using the 'uninstall.php'
* should always check for the 'WP_UNINSTALL_PLUGIN' constant, before
* executing.
*
* @since 2.7
*
* @param string $file
* @param callback $callback The callback to run when the hook is called.
*/
function register_uninstall_hook($file, $callback) {
// The option should not be autoloaded, because it is not needed in most
// cases. Emphasis should be put on using the 'uninstall.php' way of
// uninstalling the plugin.
$uninstallable_plugins = (array) get_option('uninstall_plugins');
$uninstallable_plugins[plugin_basename($file)] = $callback;
update_option('uninstall_plugins', $uninstallable_plugins);
}
/**
* Calls the 'all' hook, which will process the functions hooked into it.
*
* The 'all' hook passes all of the arguments or parameters that were used for
* the hook, which this function was called for.
*
* This function is used internally for apply_filters(), do_action(), and
* do_action_ref_array() and is not meant to be used from outside those
* functions. This function does not check for the existence of the all hook, so
* it will fail unless the all hook exists prior to this function call.
*
* @package WordPress
* @subpackage Plugin
* @since 2.5
* @access private
*
* @uses $wp_filter Used to process all of the functions in the 'all' hook
*
* @param array $args The collected parameters from the hook that was called.
* @param string $hook Optional. The hook name that was used to call the 'all' hook.
*/
function _wp_call_all_hook($args) {
global $wp_filter;
reset( $wp_filter['all'] );
do {
foreach( (array) current($wp_filter['all']) as $the_ )
if ( !is_null($the_['function']) )
call_user_func_array($the_['function'], $args);
} while ( next($wp_filter['all']) !== false );
}
/**
* Build Unique ID for storage and retrieval.
*
* The old way to serialize the callback caused issues and this function is the
* solution. It works by checking for objects and creating an a new property in
* the class to keep track of the object and new objects of the same class that
* need to be added.
*
* It also allows for the removal of actions and filters for objects after they
* change class properties. It is possible to include the property $wp_filter_id
* in your class and set it to "null" or a number to bypass the workaround.
* However this will prevent you from adding new classes and any new classes
* will overwrite the previous hook by the same class.
*
* Functions and static method callbacks are just returned as strings and
* shouldn't have any speed penalty.
*
* @package WordPress
* @subpackage Plugin
* @access private
* @since 2.2.3
* @link http://trac.wordpress.org/ticket/3875
*
* @global array $wp_filter Storage for all of the filters and actions
* @param string $tag Used in counting how many hooks were applied
* @param callback $function Used for creating unique id
* @param int|bool $priority Used in counting how many hooks were applied. If === false and $function is an object reference, we return the unique id only if it already has one, false otherwise.
* @param string $type filter or action
* @return string|bool Unique ID for usage as array key or false if $priority === false and $function is an object reference, and it does not already have a uniqe id.
*/
function _wp_filter_build_unique_id($tag, $function, $priority) {
global $wp_filter;
static $filter_id_count = 0;
// If function then just skip all of the tests and not overwrite the following.
if ( is_string($function) )
return $function;
// Object Class Calling
else if (is_object($function[0]) ) {
$obj_idx = get_class($function[0]).$function[1];
if ( !isset($function[0]->wp_filter_id) ) {
if ( false === $priority )
return false;
$obj_idx .= isset($wp_filter[$tag][$priority]) ? count((array)$wp_filter[$tag][$priority]) : 0;
$function[0]->wp_filter_id = $filter_id_count++;
} else
$obj_idx .= $function[0]->wp_filter_id;
return $obj_idx;
}
// Static Calling
else if ( is_string($function[0]) )
return $function[0].$function[1];
}
?>
larscapo/wp-includes/js/tinymce/wp-tinymce.php 0000644 0041054 0041055 00000001441 11225447104 022220 0 ustar lacunaus lacunaus '', 'after' => '', 'echo' => true);
$r = wp_parse_args($args, $defaults);
extract( $r, EXTR_SKIP );
$title = $before . $title . $after;
$title = esc_attr(strip_tags($title));
if ( $echo )
echo $title;
else
return $title;
}
/**
* Retrieve post title.
*
* If the post is protected and the visitor is not an admin, then "Protected"
* will be displayed before the post title. If the post is private, then
* "Private" will be located before the post title.
*
* @since 0.71
*
* @param int $id Optional. Post ID.
* @return string
*/
function get_the_title( $id = 0 ) {
$post = &get_post($id);
$title = $post->post_title;
if ( !is_admin() ) {
if ( !empty($post->post_password) ) {
$protected_title_format = apply_filters('protected_title_format', __('Protected: %s'));
$title = sprintf($protected_title_format, $title);
} else if ( isset($post->post_status) && 'private' == $post->post_status ) {
$private_title_format = apply_filters('private_title_format', __('Private: %s'));
$title = sprintf($private_title_format, $title);
}
}
return apply_filters( 'the_title', $title, $post->ID );
}
/**
* Display the Post Global Unique Identifier (guid).
*
* The guid will appear to be a link, but should not be used as an link to the
* post. The reason you should not use it as a link, is because of moving the
* blog across domains.
*
* @since 1.5.0
*
* @param int $id Optional. Post ID.
*/
function the_guid( $id = 0 ) {
echo get_the_guid($id);
}
/**
* Retrieve the Post Global Unique Identifier (guid).
*
* The guid will appear to be a link, but should not be used as an link to the
* post. The reason you should not use it as a link, is because of moving the
* blog across domains.
*
* @since 1.5.0
*
* @param int $id Optional. Post ID.
* @return string
*/
function get_the_guid( $id = 0 ) {
$post = &get_post($id);
return apply_filters('get_the_guid', $post->guid);
}
/**
* Display the post content.
*
* @since 0.71
*
* @param string $more_link_text Optional. Content for when there is more text.
* @param string $stripteaser Optional. Teaser content before the more text.
* @param string $more_file Optional. Not used.
*/
function the_content($more_link_text = null, $stripteaser = 0, $more_file = '') {
$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
}
/**
* Retrieve the post content.
*
* @since 0.71
*
* @param string $more_link_text Optional. Content for when there is more text.
* @param string $stripteaser Optional. Teaser content before the more text.
* @param string $more_file Optional. Not used.
* @return string
*/
function get_the_content($more_link_text = null, $stripteaser = 0, $more_file = '') {
global $id, $post, $more, $page, $pages, $multipage, $preview, $pagenow;
if ( null === $more_link_text )
$more_link_text = __( '(more...)' );
$output = '';
$hasTeaser = false;
// If post password required and it doesn't match the cookie.
if ( post_password_required($post) ) {
$output = get_the_password_form();
return $output;
}
if ( $more_file != '' )
$file = $more_file;
else
$file = $pagenow; //$_SERVER['PHP_SELF'];
if ( $page > count($pages) ) // if the requested page doesn't exist
$page = count($pages); // give them the highest numbered page that DOES exist
$content = $pages[$page-1];
if ( preg_match('//', $content, $matches) ) {
$content = explode($matches[0], $content, 2);
if ( !empty($matches[1]) && !empty($more_link_text) )
$more_link_text = strip_tags(wp_kses_no_null(trim($matches[1])));
$hasTeaser = true;
} else {
$content = array($content);
}
if ( (false !== strpos($post->post_content, '') && ((!$multipage) || ($page==1))) )
$stripteaser = 1;
$teaser = $content[0];
if ( ($more) && ($stripteaser) && ($hasTeaser) )
$teaser = '';
$output .= $teaser;
if ( count($content) > 1 ) {
if ( $more ) {
$output .= '' . $content[1];
} else {
if ( ! empty($more_link_text) )
$output .= apply_filters( 'the_content_more_link', ' $more_link_text", $more_link_text );
$output = force_balance_tags($output);
}
}
if ( $preview ) // preview fix for javascript bug with foreign languages
$output = preg_replace_callback('/\%u([0-9A-F]{4})/', create_function('$match', 'return "" . base_convert($match[1], 16, 10) . ";";'), $output);
return $output;
}
/**
* Display the post excerpt.
*
* @since 0.71
* @uses apply_filters() Calls 'the_excerpt' hook on post excerpt.
*/
function the_excerpt() {
echo apply_filters('the_excerpt', get_the_excerpt());
}
/**
* Retrieve the post excerpt.
*
* @since 0.71
*
* @param mixed $deprecated Not used.
* @return string
*/
function get_the_excerpt($deprecated = '') {
global $post;
$output = '';
$output = $post->post_excerpt;
if ( post_password_required($post) ) {
$output = __('There is no excerpt because this is a protected post.');
return $output;
}
return apply_filters('get_the_excerpt', $output);
}
/**
* Whether post has excerpt.
*
* @since 2.3.0
*
* @param int $id Optional. Post ID.
* @return bool
*/
function has_excerpt( $id = 0 ) {
$post = &get_post( $id );
return ( !empty( $post->post_excerpt ) );
}
/**
* Display the classes for the post div.
*
* @since 2.7.0
*
* @param string|array $class One or more classes to add to the class list.
* @param int $post_id An optional post ID.
*/
function post_class( $class = '', $post_id = null ) {
// Separates classes with a single space, collates classes for post DIV
echo 'class="' . join( ' ', get_post_class( $class, $post_id ) ) . '"';
}
/**
* Retrieve the classes for the post div as an array.
*
* The class names are add are many. If the post is a sticky, then the 'sticky'
* class name. The class 'hentry' is always added to each post. For each
* category, the class will be added with 'category-' with category slug is
* added. The tags are the same way as the categories with 'tag-' before the tag
* slug. All classes are passed through the filter, 'post_class' with the list
* of classes, followed by $class parameter value, with the post ID as the last
* parameter.
*
* @since 2.7.0
*
* @param string|array $class One or more classes to add to the class list.
* @param int $post_id An optional post ID.
* @return array Array of classes.
*/
function get_post_class( $class = '', $post_id = null ) {
$post = get_post($post_id);
$classes = array();
$classes[] = 'post-' . $post->ID;
$classes[] = $post->post_type;
// sticky for Sticky Posts
if ( is_sticky($post->ID) && is_home())
$classes[] = 'sticky';
// hentry for hAtom compliace
$classes[] = 'hentry';
// Categories
foreach ( (array) get_the_category($post->ID) as $cat ) {
if ( empty($cat->slug ) )
continue;
$classes[] = 'category-' . sanitize_html_class($cat->slug, $cat->cat_ID);
}
// Tags
foreach ( (array) get_the_tags($post->ID) as $tag ) {
if ( empty($tag->slug ) )
continue;
$classes[] = 'tag-' . sanitize_html_class($tag->slug, $tag->term_id);
}
if ( !empty($class) ) {
if ( !is_array( $class ) )
$class = preg_split('#\s+#', $class);
$classes = array_merge($classes, $class);
}
return apply_filters('post_class', $classes, $class, $post_id);
}
/**
* Display the classes for the body element.
*
* @since 2.8.0
*
* @param string|array $class One or more classes to add to the class list.
*/
function body_class( $class = '' ) {
// Separates classes with a single space, collates classes for body element
echo 'class="' . join( ' ', get_body_class( $class ) ) . '"';
}
/**
* Retrieve the classes for the body element as an array.
*
* @since 2.8.0
*
* @param string|array $class One or more classes to add to the class list.
* @return array Array of classes.
*/
function get_body_class( $class = '' ) {
global $wp_query, $wpdb, $current_user;
$classes = array();
if ( 'rtl' == get_bloginfo('text_direction') )
$classes[] = 'rtl';
if ( is_front_page() )
$classes[] = 'home';
if ( is_home() )
$classes[] = 'blog';
if ( is_archive() )
$classes[] = 'archive';
if ( is_date() )
$classes[] = 'date';
if ( is_search() )
$classes[] = 'search';
if ( is_paged() )
$classes[] = 'paged';
if ( is_attachment() )
$classes[] = 'attachment';
if ( is_404() )
$classes[] = 'error404';
if ( is_single() ) {
$wp_query->post = $wp_query->posts[0];
setup_postdata($wp_query->post);
$postID = $wp_query->post->ID;
$classes[] = 'single postid-' . $postID;
if ( is_attachment() ) {
$mime_type = get_post_mime_type();
$mime_prefix = array( 'application/', 'image/', 'text/', 'audio/', 'video/', 'music/' );
$classes[] = 'attachmentid-' . $postID;
$classes[] = 'attachment-' . str_replace($mime_prefix, '', $mime_type);
}
} elseif ( is_archive() ) {
if ( is_author() ) {
$author = $wp_query->get_queried_object();
$classes[] = 'author';
$classes[] = 'author-' . sanitize_html_class($author->user_nicename , $author->user_id);
} elseif ( is_category() ) {
$cat = $wp_query->get_queried_object();
$classes[] = 'category';
$classes[] = 'category-' . sanitize_html_class($cat->slug, $cat->cat_ID);
} elseif ( is_tag() ) {
$tags = $wp_query->get_queried_object();
$classes[] = 'tag';
$classes[] = 'tag-' . sanitize_html_class($tags->slug, $tags->term_id);
}
} elseif ( is_page() ) {
$classes[] = 'page';
$wp_query->post = $wp_query->posts[0];
setup_postdata($wp_query->post);
$pageID = $wp_query->post->ID;
$classes[] = 'page-id-' . $pageID;
if ( $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' LIMIT 1", $pageID) ) )
$classes[] = 'page-parent';
if ( $wp_query->post->post_parent ) {
$classes[] = 'page-child';
$classes[] = 'parent-pageid-' . $wp_query->post->post_parent;
}
if ( is_page_template() ) {
$classes[] = 'page-template';
$classes[] = 'page-template-' . str_replace( '.php', '-php', get_post_meta( $pageID, '_wp_page_template', true ) );
}
} elseif ( is_search() ) {
if ( !empty($wp_query->posts) )
$classes[] = 'search-results';
else
$classes[] = 'search-no-results';
}
if ( is_user_logged_in() )
$classes[] = 'logged-in';
$page = $wp_query->get('page');
if ( !$page || $page < 2)
$page = $wp_query->get('paged');
if ( $page && $page > 1 ) {
$classes[] = 'paged-' . $page;
if ( is_single() )
$classes[] = 'single-paged-' . $page;
elseif ( is_page() )
$classes[] = 'page-paged-' . $page;
elseif ( is_category() )
$classes[] = 'category-paged-' . $page;
elseif ( is_tag() )
$classes[] = 'tag-paged-' . $page;
elseif ( is_date() )
$classes[] = 'date-paged-' . $page;
elseif ( is_author() )
$classes[] = 'author-paged-' . $page;
elseif ( is_search() )
$classes[] = 'search-paged-' . $page;
}
if ( !empty($class) ) {
if ( !is_array( $class ) )
$class = preg_split('#\s+#', $class);
$classes = array_merge($classes, $class);
}
return apply_filters('body_class', $classes, $class);
}
/**
* Whether post requires password and correct password has been provided.
*
* @since 2.7.0
*
* @param int|object $post An optional post. Global $post used if not provided.
* @return bool false if a password is not required or the correct password cookie is present, true otherwise.
*/
function post_password_required( $post = null ) {
$post = get_post($post);
if ( empty($post->post_password) )
return false;
if ( !isset($_COOKIE['wp-postpass_' . COOKIEHASH]) )
return true;
if ( $_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password )
return true;
return false;
}
/**
* Display "sticky" CSS class, if a post is sticky.
*
* @since 2.7.0
*
* @param int $post_id An optional post ID.
*/
function sticky_class( $post_id = null ) {
if ( !is_sticky($post_id) )
return;
echo " sticky";
}
/**
* Page Template Functions for usage in Themes
*
* @package WordPress
* @subpackage Template
*/
/**
* The formatted output of a list of pages.
*
* Displays page links for paginated posts (i.e. includes the .
* Quicktag one or more times). This tag must be within The Loop.
*
* The defaults for overwriting are:
* 'next_or_number' - Default is 'number' (string). Indicates whether page
* numbers should be used. Valid values are number and next.
* 'nextpagelink' - Default is 'Next Page' (string). Text for link to next page.
* of the bookmark.
* 'previouspagelink' - Default is 'Previous Page' (string). Text for link to
* previous page, if available.
* 'pagelink' - Default is '%' (String).Format string for page numbers. The % in
* the parameter string will be replaced with the page number, so Page %
* generates "Page 1", "Page 2", etc. Defaults to %, just the page number.
* 'before' - Default is '
Pages:' (string). The html or text to prepend to
* each bookmarks.
* 'after' - Default is '
\n";
}
}
//
// Pages
//
/**
* Retrieve or display list of pages as a dropdown (select list).
*
* @since 2.1.0
*
* @param array|string $args Optional. Override default arguments.
* @return string HTML content, if not displaying.
*/
function wp_dropdown_pages($args = '') {
$defaults = array(
'depth' => 0, 'child_of' => 0,
'selected' => 0, 'echo' => 1,
'name' => 'page_id', 'show_option_none' => '', 'show_option_no_change' => '',
'option_none_value' => ''
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
$pages = get_pages($r);
$output = '';
if ( ! empty($pages) ) {
$output = "\n";
}
$output = apply_filters('wp_dropdown_pages', $output);
if ( $echo )
echo $output;
return $output;
}
/**
* Retrieve or display list of pages in list (li) format.
*
* @since 1.5.0
*
* @param array|string $args Optional. Override default arguments.
* @return string HTML content, if not displaying.
*/
function wp_list_pages($args = '') {
$defaults = array(
'depth' => 0, 'show_date' => '',
'date_format' => get_option('date_format'),
'child_of' => 0, 'exclude' => '',
'title_li' => __('Pages'), 'echo' => 1,
'authors' => '', 'sort_column' => 'menu_order, post_title',
'link_before' => '', 'link_after' => ''
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
$output = '';
$current_page = 0;
// sanitize, mostly to keep spaces out
$r['exclude'] = preg_replace('/[^0-9,]/', '', $r['exclude']);
// Allow plugins to filter an array of excluded pages
$r['exclude'] = implode(',', apply_filters('wp_list_pages_excludes', explode(',', $r['exclude'])));
// Query pages.
$r['hierarchical'] = 0;
$pages = get_pages($r);
if ( !empty($pages) ) {
if ( $r['title_li'] )
$output .= '
' . $r['title_li'] . '
';
global $wp_query;
if ( is_page() || is_attachment() || $wp_query->is_posts_page )
$current_page = $wp_query->get_queried_object_id();
$output .= walk_page_tree($pages, $r['depth'], $current_page, $r);
if ( $r['title_li'] )
$output .= '
';
}
$output = apply_filters('wp_list_pages', $output);
if ( $r['echo'] )
echo $output;
else
return $output;
}
/**
* Display or retrieve list of pages with optional home link.
*
* The arguments are listed below and part of the arguments are for {@link
* wp_list_pages()} function. Check that function for more info on those
* arguments.
*
*
*
sort_column - How to sort the list of pages. Defaults
* to page title. Use column for posts table.
*
menu_class - Class to use for the div ID which contains
* the page list. Defaults to 'menu'.
*
echo - Whether to echo list or return it. Defaults to
* echo.
*
link_before - Text before show_home argument text.
*
link_after - Text after show_home argument text.
*
show_home - If you set this argument, then it will
* display the link to the home page. The show_home argument really just needs
* to be set to the value of the text of the link.
';
// If the front page is a page, add it to the exclude list
if (get_option('show_on_front') == 'page') {
if ( !empty( $list_args['exclude'] ) ) {
$list_args['exclude'] .= ',';
} else {
$list_args['exclude'] = '';
}
$list_args['exclude'] .= get_option('page_on_front');
}
}
$list_args['echo'] = false;
$list_args['title_li'] = '';
$menu .= str_replace( array( "\r", "\n", "\t" ), '', wp_list_pages($list_args) );
if ( $menu )
$menu = '
' . $menu . '
';
$menu = '
' . $menu . "
\n";
$menu = apply_filters( 'wp_page_menu', $menu, $args );
if ( $args['echo'] )
echo $menu;
else
return $menu;
}
//
// Page helpers
//
/**
* Retrieve HTML list content for page list.
*
* @uses Walker_Page to create HTML list content.
* @since 2.1.0
* @see Walker_Page::walk() for parameters and return description.
*/
function walk_page_tree($pages, $depth, $current_page, $r) {
if ( empty($r['walker']) )
$walker = new Walker_Page;
else
$walker = $r['walker'];
$args = array($pages, $depth, $r, $current_page);
return call_user_func_array(array(&$walker, 'walk'), $args);
}
/**
* Retrieve HTML dropdown (select) content for page list.
*
* @uses Walker_PageDropdown to create HTML dropdown content.
* @since 2.1.0
* @see Walker_PageDropdown::walk() for parameters and return description.
*/
function walk_page_dropdown_tree() {
$args = func_get_args();
if ( empty($args[2]['walker']) ) // the user's options are the third parameter
$walker = new Walker_PageDropdown;
else
$walker = $args[2]['walker'];
return call_user_func_array(array(&$walker, 'walk'), $args);
}
//
// Attachments
//
/**
* Display an attachment page link using an image or icon.
*
* @since 2.0.0
*
* @param int $id Optional. Post ID.
* @param bool $fullsize Optional, default is false. Whether to use full size.
* @param bool $deprecated Deprecated. Not used.
* @param bool $permalink Optional, default is false. Whether to include permalink.
*/
function the_attachment_link($id = 0, $fullsize = false, $deprecated = false, $permalink = false) {
if ( $fullsize )
echo wp_get_attachment_link($id, 'full', $permalink);
else
echo wp_get_attachment_link($id, 'thumbnail', $permalink);
}
/**
* Retrieve an attachment page link using an image or icon, if possible.
*
* @since 2.5.0
* @uses apply_filters() Calls 'wp_get_attachment_link' filter on HTML content with same parameters as function.
*
* @param int $id Optional. Post ID.
* @param string $size Optional, default is 'thumbnail'. Size of image, either array or string.
* @param bool $permalink Optional, default is false. Whether to add permalink to image.
* @param bool $icon Optional, default is false. Whether to include icon.
* @param string $text Optional, default is false. If string, then will be link text.
* @return string HTML content.
*/
function wp_get_attachment_link($id = 0, $size = 'thumbnail', $permalink = false, $icon = false, $text = false) {
$id = intval($id);
$_post = & get_post( $id );
if ( ('attachment' != $_post->post_type) || !$url = wp_get_attachment_url($_post->ID) )
return __('Missing Attachment');
if ( $permalink )
$url = get_attachment_link($_post->ID);
$post_title = esc_attr($_post->post_title);
if ( $text ) {
$link_text = esc_attr($text);
} elseif ( ( is_int($size) && $size != 0 ) or ( is_string($size) && $size != 'none' ) or $size != false ) {
$link_text = wp_get_attachment_image($id, $size, $icon);
}
if( trim($link_text) == '' )
$link_text = $_post->post_title;
return apply_filters( 'wp_get_attachment_link', "$link_text", $id, $size, $permalink, $icon, $text );
}
/**
* Retrieve HTML content of attachment image with link.
*
* @since 2.0.0
* @deprecated Use {@link wp_get_attachment_link()}
* @see wp_get_attachment_link() Use instead.
*
* @param int $id Optional. Post ID.
* @param bool $fullsize Optional, default is false. Whether to use full size image.
* @param array $max_dims Optional. Max image dimensions.
* @param bool $permalink Optional, default is false. Whether to include permalink to image.
* @return string
*/
function get_the_attachment_link($id = 0, $fullsize = false, $max_dims = false, $permalink = false) {
$id = (int) $id;
$_post = & get_post($id);
if ( ('attachment' != $_post->post_type) || !$url = wp_get_attachment_url($_post->ID) )
return __('Missing Attachment');
if ( $permalink )
$url = get_attachment_link($_post->ID);
$post_title = esc_attr($_post->post_title);
$innerHTML = get_attachment_innerHTML($_post->ID, $fullsize, $max_dims);
return "$innerHTML";
}
/**
* Retrieve icon URL and Path.
*
* @since 2.1.0
* @deprecated Use {@link wp_get_attachment_image_src()}
* @see wp_get_attachment_image_src() Use instead.
*
* @param int $id Optional. Post ID.
* @param bool $fullsize Optional, default to false. Whether to have full image.
* @return array Icon URL and full path to file, respectively.
*/
function get_attachment_icon_src( $id = 0, $fullsize = false ) {
$id = (int) $id;
if ( !$post = & get_post($id) )
return false;
$file = get_attached_file( $post->ID );
if ( !$fullsize && $src = wp_get_attachment_thumb_url( $post->ID ) ) {
// We have a thumbnail desired, specified and existing
$src_file = basename($src);
$class = 'attachmentthumb';
} elseif ( wp_attachment_is_image( $post->ID ) ) {
// We have an image without a thumbnail
$src = wp_get_attachment_url( $post->ID );
$src_file = & $file;
$class = 'attachmentimage';
} elseif ( $src = wp_mime_type_icon( $post->ID ) ) {
// No thumb, no image. We'll look for a mime-related icon instead.
$icon_dir = apply_filters( 'icon_dir', get_template_directory() . '/images' );
$src_file = $icon_dir . '/' . basename($src);
}
if ( !isset($src) || !$src )
return false;
return array($src, $src_file);
}
/**
* Retrieve HTML content of icon attachment image element.
*
* @since 2.0.0
* @deprecated Use {@link wp_get_attachment_image()}
* @see wp_get_attachment_image() Use instead of.
*
* @param int $id Optional. Post ID.
* @param bool $fullsize Optional, default to false. Whether to have full size image.
* @param array $max_dims Optional. Dimensions of image.
* @return string HTML content.
*/
function get_attachment_icon( $id = 0, $fullsize = false, $max_dims = false ) {
$id = (int) $id;
if ( !$post = & get_post($id) )
return false;
if ( !$src = get_attachment_icon_src( $post->ID, $fullsize ) )
return false;
list($src, $src_file) = $src;
// Do we need to constrain the image?
if ( ($max_dims = apply_filters('attachment_max_dims', $max_dims)) && file_exists($src_file) ) {
$imagesize = getimagesize($src_file);
if (($imagesize[0] > $max_dims[0]) || $imagesize[1] > $max_dims[1] ) {
$actual_aspect = $imagesize[0] / $imagesize[1];
$desired_aspect = $max_dims[0] / $max_dims[1];
if ( $actual_aspect >= $desired_aspect ) {
$height = $actual_aspect * $max_dims[0];
$constraint = "width='{$max_dims[0]}' ";
$post->iconsize = array($max_dims[0], $height);
} else {
$width = $max_dims[1] / $actual_aspect;
$constraint = "height='{$max_dims[1]}' ";
$post->iconsize = array($width, $max_dims[1]);
}
} else {
$post->iconsize = array($imagesize[0], $imagesize[1]);
$constraint = '';
}
} else {
$constraint = '';
}
$post_title = esc_attr($post->post_title);
$icon = "";
return apply_filters( 'attachment_icon', $icon, $post->ID );
}
/**
* Retrieve HTML content of image element.
*
* @since 2.0.0
* @deprecated Use {@link wp_get_attachment_image()}
* @see wp_get_attachment_image() Use instead.
*
* @param int $id Optional. Post ID.
* @param bool $fullsize Optional, default to false. Whether to have full size image.
* @param array $max_dims Optional. Dimensions of image.
* @return string
*/
function get_attachment_innerHTML($id = 0, $fullsize = false, $max_dims = false) {
$id = (int) $id;
if ( !$post = & get_post($id) )
return false;
if ( $innerHTML = get_attachment_icon($post->ID, $fullsize, $max_dims))
return $innerHTML;
$innerHTML = esc_attr($post->post_title);
return apply_filters('attachment_innerHTML', $innerHTML, $post->ID);
}
/**
* Wrap attachment in <
> element before content.
*
* @since 2.0.0
* @uses apply_filters() Calls 'prepend_attachment' hook on HTML content.
*
* @param string $content
* @return string
*/
function prepend_attachment($content) {
global $post;
if ( empty($post->post_type) || $post->post_type != 'attachment' )
return $content;
$p = '
';
// show the medium sized image representation of the attachment if available, and link to the raw file
$p .= wp_get_attachment_link(0, 'medium', false);
$p .= '
';
$p = apply_filters('prepend_attachment', $p);
return "$p\n$content";
}
//
// Misc
//
/**
* Retrieve protected post password form content.
*
* @since 1.0.0
* @uses apply_filters() Calls 'the_password_form' filter on output.
*
* @return string HTML content for password form for password protected post.
*/
function get_the_password_form() {
global $post;
$label = 'pwbox-'.(empty($post->ID) ? rand() : $post->ID);
$output = '
' . __("This post is password protected. To view it please enter your password below:") . '
';
return apply_filters('the_password_form', $output);
}
/**
* Whether currently in a page template.
*
* This template tag allows you to determine whether or not you are in a page
* template. You can optional provide a template name and then the check will be
* specific to that template.
*
* @since 2.5.0
* @uses $wp_query
*
* @param string $template The specific template name if specific matching is required.
* @return bool False on failure, true if success.
*/
function is_page_template($template = '') {
if (!is_page()) {
return false;
}
global $wp_query;
$page = $wp_query->get_queried_object();
$custom_fields = get_post_custom_values('_wp_page_template',$page->ID);
$page_template = $custom_fields[0];
// We have no argument passed so just see if a page_template has been specified
if ( empty( $template ) ) {
if (!empty( $page_template ) ) {
return true;
}
} elseif ( $template == $page_template) {
return true;
}
return false;
}
/**
* Retrieve formatted date timestamp of a revision (linked to that revisions's page).
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses date_i18n()
*
* @param int|object $revision Revision ID or revision object.
* @param bool $link Optional, default is true. Link to revisions's page?
* @return string i18n formatted datetimestamp or localized 'Current Revision'.
*/
function wp_post_revision_title( $revision, $link = true ) {
if ( !$revision = get_post( $revision ) )
return $revision;
if ( !in_array( $revision->post_type, array( 'post', 'page', 'revision' ) ) )
return false;
/* translators: revision date format, see http://php.net/date */
$datef = _x( 'j F, Y @ G:i', 'revision date format');
/* translators: 1: date */
$autosavef = __( '%1$s [Autosave]' );
/* translators: 1: date */
$currentf = __( '%1$s [Current Revision]' );
$date = date_i18n( $datef, strtotime( $revision->post_modified_gmt . ' +0000' ) );
if ( $link && current_user_can( 'edit_post', $revision->ID ) && $link = get_edit_post_link( $revision->ID ) )
$date = "$date";
if ( !wp_is_post_revision( $revision ) )
$date = sprintf( $currentf, $date );
elseif ( wp_is_post_autosave( $revision ) )
$date = sprintf( $autosavef, $date );
return $date;
}
/**
* Display list of a post's revisions.
*
* Can output either a UL with edit links or a TABLE with diff interface, and
* restore action links.
*
* Second argument controls parameters:
* (bool) parent : include the parent (the "Current Revision") in the list.
* (string) format : 'list' or 'form-table'. 'list' outputs UL, 'form-table'
* outputs TABLE with UI.
* (int) right : what revision is currently being viewed - used in
* form-table format.
* (int) left : what revision is currently being diffed against right -
* used in form-table format.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses wp_get_post_revisions()
* @uses wp_post_revision_title()
* @uses get_edit_post_link()
* @uses get_the_author_meta()
*
* @todo split into two functions (list, form-table) ?
*
* @param int|object $post_id Post ID or post object.
* @param string|array $args See description {@link wp_parse_args()}.
* @return null
*/
function wp_list_post_revisions( $post_id = 0, $args = null ) {
if ( !$post = get_post( $post_id ) )
return;
$defaults = array( 'parent' => false, 'right' => false, 'left' => false, 'format' => 'list', 'type' => 'all' );
extract( wp_parse_args( $args, $defaults ), EXTR_SKIP );
switch ( $type ) {
case 'autosave' :
if ( !$autosave = wp_get_post_autosave( $post->ID ) )
return;
$revisions = array( $autosave );
break;
case 'revision' : // just revisions - remove autosave later
case 'all' :
default :
if ( !$revisions = wp_get_post_revisions( $post->ID ) )
return;
break;
}
/* translators: post revision: 1: when, 2: author name */
$titlef = _x( '%1$s by %2$s', 'post revision' );
if ( $parent )
array_unshift( $revisions, $post );
$rows = '';
$class = false;
$can_edit_post = current_user_can( 'edit_post', $post->ID );
foreach ( $revisions as $revision ) {
if ( !current_user_can( 'read_post', $revision->ID ) )
continue;
if ( 'revision' === $type && wp_is_post_autosave( $revision ) )
continue;
$date = wp_post_revision_title( $revision );
$name = get_the_author_meta( 'display_name', $revision->post_author );
if ( 'form-table' == $format ) {
if ( $left )
$left_checked = $left == $revision->ID ? ' checked="checked"' : '';
else
$left_checked = $right_checked ? ' checked="checked"' : ''; // [sic] (the next one)
$right_checked = $right == $revision->ID ? ' checked="checked"' : '';
$class = $class ? '' : " class='alternate'";
if ( $post->ID != $revision->ID && $can_edit_post )
$actions = 'ID|$revision->ID" ) . '">' . __( 'Restore' ) . '';
else
$actions = '';
$rows .= "
\n";
echo $rows;
echo "";
endif;
}
larscapo/wp-includes/update.php 0000644 0041054 0041055 00000023150 11225447104 017323 0 ustar lacunaus lacunaus updates = array();
$current->version_checked = $wp_version;
}
$locale = apply_filters( 'core_version_check_locale', get_locale() );
// Update last_checked for current to prevent multiple blocking requests if request hangs
$current->last_checked = time();
set_transient( 'update_core', $current );
if ( method_exists( $wpdb, 'db_version' ) )
$mysql_version = preg_replace('/[^0-9.].*/', '', $wpdb->db_version($wpdb->users));
else
$mysql_version = 'N/A';
$local_package = isset( $wp_local_package )? $wp_local_package : '';
$url = "http://api.wordpress.org/core/version-check/1.3/?version=$wp_version&php=$php_version&locale=$locale&mysql=$mysql_version&local_package=$local_package";
$options = array(
'timeout' => 3,
'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )
);
$response = wp_remote_get($url, $options);
if ( is_wp_error( $response ) )
return false;
if ( 200 != $response['response']['code'] )
return false;
$body = trim( $response['body'] );
$body = str_replace(array("\r\n", "\r"), "\n", $body);
$new_options = array();
foreach( explode( "\n\n", $body ) as $entry) {
$returns = explode("\n", $entry);
$new_option = new stdClass();
$new_option->response = esc_attr( $returns[0] );
if ( isset( $returns[1] ) )
$new_option->url = esc_url( $returns[1] );
if ( isset( $returns[2] ) )
$new_option->package = esc_url( $returns[2] );
if ( isset( $returns[3] ) )
$new_option->current = esc_attr( $returns[3] );
if ( isset( $returns[4] ) )
$new_option->locale = esc_attr( $returns[4] );
$new_options[] = $new_option;
}
$updates = new stdClass();
$updates->updates = $new_options;
$updates->last_checked = time();
$updates->version_checked = $wp_version;
set_transient( 'update_core', $updates);
}
/**
* Check plugin versions against the latest versions hosted on WordPress.org.
*
* The WordPress version, PHP version, and Locale is sent along with a list of
* all plugins installed. Checks against the WordPress server at
* api.wordpress.org. Will only check if WordPress isn't installing.
*
* @package WordPress
* @since 2.3.0
* @uses $wp_version Used to notidy the WordPress version.
*
* @return mixed Returns null if update is unsupported. Returns false if check is too soon.
*/
function wp_update_plugins() {
global $wp_version;
if ( defined('WP_INSTALLING') )
return false;
// If running blog-side, bail unless we've not checked in the last 12 hours
if ( !function_exists( 'get_plugins' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$plugins = get_plugins();
$active = get_option( 'active_plugins' );
$current = get_transient( 'update_plugins' );
if ( ! is_object($current) )
$current = new stdClass;
$new_option = new stdClass;
$new_option->last_checked = time();
$timeout = 'load-plugins.php' == current_filter() ? 3600 : 43200; //Check for updated every 60 minutes if hitting the themes page, Else, check every 12 hours
$time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked );
$plugin_changed = false;
foreach ( $plugins as $file => $p ) {
$new_option->checked[ $file ] = $p['Version'];
if ( !isset( $current->checked[ $file ] ) || strval($current->checked[ $file ]) !== strval($p['Version']) )
$plugin_changed = true;
}
if ( isset ( $current->response ) && is_array( $current->response ) ) {
foreach ( $current->response as $plugin_file => $update_details ) {
if ( ! isset($plugins[ $plugin_file ]) ) {
$plugin_changed = true;
break;
}
}
}
// Bail if we've checked in the last 12 hours and if nothing has changed
if ( $time_not_changed && !$plugin_changed )
return false;
// Update last_checked for current to prevent multiple blocking requests if request hangs
$current->last_checked = time();
set_transient( 'update_plugins', $current );
$to_send = (object)compact('plugins', 'active');
$options = array(
'timeout' => 3,
'body' => array( 'plugins' => serialize( $to_send ) ),
'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )
);
$raw_response = wp_remote_post('http://api.wordpress.org/plugins/update-check/1.0/', $options);
if ( is_wp_error( $raw_response ) )
return false;
if( 200 != $raw_response['response']['code'] )
return false;
$response = unserialize( $raw_response['body'] );
if ( false !== $response )
$new_option->response = $response;
else
$new_option->response = array();
set_transient( 'update_plugins', $new_option );
}
/**
* Check theme versions against the latest versions hosted on WordPress.org.
*
* A list of all themes installed in sent to WP. Checks against the
* WordPress server at api.wordpress.org. Will only check if WordPress isn't
* installing.
*
* @package WordPress
* @since 2.7.0
* @uses $wp_version Used to notidy the WordPress version.
*
* @return mixed Returns null if update is unsupported. Returns false if check is too soon.
*/
function wp_update_themes( ) {
global $wp_version;
if( defined( 'WP_INSTALLING' ) )
return false;
if( !function_exists( 'get_themes' ) )
require_once( ABSPATH . 'wp-includes/theme.php' );
$installed_themes = get_themes( );
$current_theme = get_transient( 'update_themes' );
if ( ! is_object($current_theme) )
$current_theme = new stdClass;
$new_option = new stdClass;
$new_option->last_checked = time( );
$timeout = 'load-themes.php' == current_filter() ? 3600 : 43200; //Check for updated every 60 minutes if hitting the themes page, Else, check every 12 hours
$time_not_changed = isset( $current_theme->last_checked ) && $timeout > ( time( ) - $current_theme->last_checked );
if( $time_not_changed )
return false;
// Update last_checked for current to prevent multiple blocking requests if request hangs
$current_theme->last_checked = time();
set_transient( 'update_themes', $current_theme );
$current_theme->template = get_option( 'template' );
$themes = array( );
$themes['current_theme'] = (array) $current_theme;
foreach( (array) $installed_themes as $theme_title => $theme ) {
$themes[$theme['Stylesheet']] = array( );
foreach( (array) $theme as $key => $value ) {
$themes[$theme['Stylesheet']][$key] = $value;
}
}
$options = array(
'timeout' => 3,
'body' => array( 'themes' => serialize( $themes ) ),
'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' )
);
$raw_response = wp_remote_post( 'http://api.wordpress.org/themes/update-check/1.0/', $options );
if( is_wp_error( $raw_response ) )
return false;
if( 200 != $raw_response['response']['code'] )
return false;
$response = unserialize( $raw_response['body'] );
if( $response )
$new_option->response = $response;
set_transient( 'update_themes', $new_option );
}
function _maybe_update_core() {
global $wp_version;
$current = get_transient( 'update_core' );
if ( isset( $current->last_checked ) &&
43200 > ( time() - $current->last_checked ) &&
isset( $current->version_checked ) &&
$current->version_checked == $wp_version )
return;
wp_version_check();
}
/**
* Check the last time plugins were run before checking plugin versions.
*
* This might have been backported to WordPress 2.6.1 for performance reasons.
* This is used for the wp-admin to check only so often instead of every page
* load.
*
* @since 2.7.0
* @access private
*/
function _maybe_update_plugins() {
$current = get_transient( 'update_plugins' );
if ( isset( $current->last_checked ) && 43200 > ( time() - $current->last_checked ) )
return;
wp_update_plugins();
}
/**
* Check themes versions only after a duration of time.
*
* This is for performance reasons to make sure that on the theme version
* checker is not run on every page load.
*
* @since 2.7.0
* @access private
*/
function _maybe_update_themes( ) {
$current = get_transient( 'update_themes' );
if( isset( $current->last_checked ) && 43200 > ( time( ) - $current->last_checked ) )
return;
wp_update_themes( );
}
add_action( 'admin_init', '_maybe_update_core' );
add_action( 'wp_version_check', 'wp_version_check' );
add_action( 'load-plugins.php', 'wp_update_plugins' );
add_action( 'load-update.php', 'wp_update_plugins' );
add_action( 'admin_init', '_maybe_update_plugins' );
add_action( 'wp_update_plugins', 'wp_update_plugins' );
add_action( 'load-themes.php', 'wp_update_themes' );
add_action( 'load-update.php', 'wp_update_themes' );
add_action( 'admin_init', '_maybe_update_themes' );
add_action( 'wp_update_themes', 'wp_update_themes' );
if ( !wp_next_scheduled('wp_version_check') && !defined('WP_INSTALLING') )
wp_schedule_event(time(), 'twicedaily', 'wp_version_check');
if ( !wp_next_scheduled('wp_update_plugins') && !defined('WP_INSTALLING') )
wp_schedule_event(time(), 'twicedaily', 'wp_update_plugins');
if ( !wp_next_scheduled('wp_update_themes') && !defined('WP_INSTALLING') )
wp_schedule_event(time(), 'twicedaily', 'wp_update_themes');
?>
larscapo/wp-includes/post.php 0000644 0041054 0041055 00000342275 11225447104 017042 0 ustar lacunaus lacunaus (int) $GLOBALS['post']->post_parent );
} else {
return false;
}
} elseif ( is_object( $args ) ) {
$args = array('post_parent' => (int) $args->post_parent );
} elseif ( is_numeric( $args ) ) {
$args = array('post_parent' => (int) $args);
}
$defaults = array(
'numberposts' => -1, 'post_type' => 'any',
'post_status' => 'any', 'post_parent' => 0,
);
$r = wp_parse_args( $args, $defaults );
$children = get_posts( $r );
if ( !$children ) {
$kids = false;
return $kids;
}
update_post_cache($children);
foreach ( $children as $key => $child )
$kids[$child->ID] =& $children[$key];
if ( $output == OBJECT ) {
return $kids;
} elseif ( $output == ARRAY_A ) {
foreach ( (array) $kids as $kid )
$weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
return $weeuns;
} elseif ( $output == ARRAY_N ) {
foreach ( (array) $kids as $kid )
$babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
return $babes;
} else {
return $kids;
}
}
/**
* Get extended entry info ().
*
* There should not be any space after the second dash and before the word
* 'more'. There can be text or space(s) after the word 'more', but won't be
* referenced.
*
* The returned array has 'main' and 'extended' keys. Main has the text before
* the . The 'extended' key has the content after the
* comment.
*
* @since 1.0.0
*
* @param string $post Post content.
* @return array Post before ('main') and after ('extended').
*/
function get_extended($post) {
//Match the new style more links
if ( preg_match('//', $post, $matches) ) {
list($main, $extended) = explode($matches[0], $post, 2);
} else {
$main = $post;
$extended = '';
}
// Strip leading and trailing whitespace
$main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
$extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
return array('main' => $main, 'extended' => $extended);
}
/**
* Retrieves post data given a post ID or post object.
*
* See {@link sanitize_post()} for optional $filter values. Also, the parameter
* $post, must be given as a variable, since it is passed by reference.
*
* @since 1.5.1
* @uses $wpdb
* @link http://codex.wordpress.org/Function_Reference/get_post
*
* @param int|object $post Post ID or post object.
* @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
* @param string $filter Optional, default is raw.
* @return mixed Post data
*/
function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
global $wpdb;
$null = null;
if ( empty($post) ) {
if ( isset($GLOBALS['post']) )
$_post = & $GLOBALS['post'];
else
return $null;
} elseif ( is_object($post) && empty($post->filter) ) {
_get_post_ancestors($post);
wp_cache_add($post->ID, $post, 'posts');
$_post = &$post;
} else {
if ( is_object($post) )
$post = $post->ID;
$post = (int) $post;
if ( ! $_post = wp_cache_get($post, 'posts') ) {
$_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post));
if ( ! $_post )
return $null;
_get_post_ancestors($_post);
wp_cache_add($_post->ID, $_post, 'posts');
}
}
$_post = sanitize_post($_post, $filter);
if ( $output == OBJECT ) {
return $_post;
} elseif ( $output == ARRAY_A ) {
$__post = get_object_vars($_post);
return $__post;
} elseif ( $output == ARRAY_N ) {
$__post = array_values(get_object_vars($_post));
return $__post;
} else {
return $_post;
}
}
/**
* Retrieve ancestors of a post.
*
* @since 2.5.0
*
* @param int|object $post Post ID or post object
* @return array Ancestor IDs or empty array if none are found.
*/
function get_post_ancestors($post) {
$post = get_post($post);
if ( !empty($post->ancestors) )
return $post->ancestors;
return array();
}
/**
* Retrieve data from a post field based on Post ID.
*
* Examples of the post field will be, 'post_type', 'post_status', 'content',
* etc and based off of the post object property or key names.
*
* The context values are based off of the taxonomy filter functions and
* supported values are found within those functions.
*
* @since 2.3.0
* @uses sanitize_post_field() See for possible $context values.
*
* @param string $field Post field name
* @param id $post Post ID
* @param string $context Optional. How to filter the field. Default is display.
* @return WP_Error|string Value in post field or WP_Error on failure
*/
function get_post_field( $field, $post, $context = 'display' ) {
$post = (int) $post;
$post = get_post( $post );
if ( is_wp_error($post) )
return $post;
if ( !is_object($post) )
return '';
if ( !isset($post->$field) )
return '';
return sanitize_post_field($field, $post->$field, $post->ID, $context);
}
/**
* Retrieve the mime type of an attachment based on the ID.
*
* This function can be used with any post type, but it makes more sense with
* attachments.
*
* @since 2.0.0
*
* @param int $ID Optional. Post ID.
* @return bool|string False on failure or returns the mime type
*/
function get_post_mime_type($ID = '') {
$post = & get_post($ID);
if ( is_object($post) )
return $post->post_mime_type;
return false;
}
/**
* Retrieve the post status based on the Post ID.
*
* If the post ID is of an attachment, then the parent post status will be given
* instead.
*
* @since 2.0.0
*
* @param int $ID Post ID
* @return string|bool Post status or false on failure.
*/
function get_post_status($ID = '') {
$post = get_post($ID);
if ( is_object($post) ) {
if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
return get_post_status($post->post_parent);
else
return $post->post_status;
}
return false;
}
/**
* Retrieve all of the WordPress supported post statuses.
*
* Posts have a limited set of valid status values, this provides the
* post_status values and descriptions.
*
* @since 2.5.0
*
* @return array List of post statuses.
*/
function get_post_statuses( ) {
$status = array(
'draft' => __('Draft'),
'pending' => __('Pending Review'),
'private' => __('Private'),
'publish' => __('Published')
);
return $status;
}
/**
* Retrieve all of the WordPress support page statuses.
*
* Pages have a limited set of valid status values, this provides the
* post_status values and descriptions.
*
* @since 2.5.0
*
* @return array List of page statuses.
*/
function get_page_statuses( ) {
$status = array(
'draft' => __('Draft'),
'private' => __('Private'),
'publish' => __('Published')
);
return $status;
}
/**
* Retrieve the post type of the current post or of a given post.
*
* @since 2.1.0
*
* @uses $wpdb
* @uses $posts The Loop post global
*
* @param mixed $post Optional. Post object or post ID.
* @return bool|string post type or false on failure.
*/
function get_post_type($post = false) {
global $posts;
if ( false === $post )
$post = $posts[0];
elseif ( (int) $post )
$post = get_post($post, OBJECT);
if ( is_object($post) )
return $post->post_type;
return false;
}
/**
* Updates the post type for the post ID.
*
* The page or post cache will be cleaned for the post ID.
*
* @since 2.5.0
*
* @uses $wpdb
*
* @param int $post_id Post ID to change post type. Not actually optional.
* @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
* name a few.
* @return int Amount of rows changed. Should be 1 for success and 0 for failure.
*/
function set_post_type( $post_id = 0, $post_type = 'post' ) {
global $wpdb;
$post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
$return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
if ( 'page' == $post_type )
clean_page_cache($post_id);
else
clean_post_cache($post_id);
return $return;
}
/**
* Retrieve list of latest posts or posts matching criteria.
*
* The defaults are as follows:
* 'numberposts' - Default is 5. Total number of posts to retrieve.
* 'offset' - Default is 0. See {@link WP_Query::query()} for more.
* 'category' - What category to pull the posts from.
* 'orderby' - Default is 'post_date'. How to order the posts.
* 'order' - Default is 'DESC'. The order to retrieve the posts.
* 'include' - See {@link WP_Query::query()} for more.
* 'exclude' - See {@link WP_Query::query()} for more.
* 'meta_key' - See {@link WP_Query::query()} for more.
* 'meta_value' - See {@link WP_Query::query()} for more.
* 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
* 'post_parent' - The parent of the post or post type.
* 'post_status' - Default is 'published'. Post status to retrieve.
*
* @since 1.2.0
* @uses $wpdb
* @uses WP_Query::query() See for more default arguments and information.
* @link http://codex.wordpress.org/Template_Tags/get_posts
*
* @param array $args Optional. Overrides defaults.
* @return array List of posts.
*/
function get_posts($args = null) {
$defaults = array(
'numberposts' => 5, 'offset' => 0,
'category' => 0, 'orderby' => 'post_date',
'order' => 'DESC', 'include' => '',
'exclude' => '', 'meta_key' => '',
'meta_value' =>'', 'post_type' => 'post',
'suppress_filters' => true
);
$r = wp_parse_args( $args, $defaults );
if ( empty( $r['post_status'] ) )
$r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
if ( ! empty($r['numberposts']) )
$r['posts_per_page'] = $r['numberposts'];
if ( ! empty($r['category']) )
$r['cat'] = $r['category'];
if ( ! empty($r['include']) ) {
$incposts = preg_split('/[\s,]+/',$r['include']);
$r['posts_per_page'] = count($incposts); // only the number of posts included
$r['post__in'] = $incposts;
} elseif ( ! empty($r['exclude']) )
$r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
$r['caller_get_posts'] = true;
$get_posts = new WP_Query;
return $get_posts->query($r);
}
//
// Post meta functions
//
/**
* Add meta data field to a post.
*
* Post meta data is called "Custom Fields" on the Administration Panels.
*
* @since 1.5.0
* @uses $wpdb
* @link http://codex.wordpress.org/Function_Reference/add_post_meta
*
* @param int $post_id Post ID.
* @param string $key Metadata name.
* @param mixed $value Metadata value.
* @param bool $unique Optional, default is false. Whether the same key should not be added.
* @return bool False for failure. True for success.
*/
function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
if ( !$meta_key )
return false;
global $wpdb;
// make sure meta is added to the post, not a revision
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
// expected_slashed ($meta_key)
$meta_key = stripslashes($meta_key);
if ( $unique && $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) )
return false;
$meta_value = maybe_serialize( stripslashes_deep($meta_value) );
$wpdb->insert( $wpdb->postmeta, compact( 'post_id', 'meta_key', 'meta_value' ) );
wp_cache_delete($post_id, 'post_meta');
return true;
}
/**
* Remove metadata matching criteria from a post.
*
* You can match based on the key, or key and value. Removing based on key and
* value, will keep from removing duplicate metadata with the same key. It also
* allows removing all metadata matching key, if needed.
*
* @since 1.5.0
* @uses $wpdb
* @link http://codex.wordpress.org/Function_Reference/delete_post_meta
*
* @param int $post_id post ID
* @param string $meta_key Metadata name.
* @param mixed $meta_value Optional. Metadata value.
* @return bool False for failure. True for success.
*/
function delete_post_meta($post_id, $meta_key, $meta_value = '') {
global $wpdb;
// make sure meta is added to the post, not a revision
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
// expected_slashed ($meta_key, $meta_value)
$meta_key = stripslashes( $meta_key );
$meta_value = maybe_serialize( stripslashes_deep($meta_value) );
if ( !$meta_key )
return false;
if ( empty( $meta_value ) )
$meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
else
$meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) );
if ( !$meta_id )
return false;
if ( empty( $meta_value ) )
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
else
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) );
wp_cache_delete($post_id, 'post_meta');
return true;
}
/**
* Retrieve post meta field for a post.
*
* @since 1.5.0
* @uses $wpdb
* @link http://codex.wordpress.org/Function_Reference/get_post_meta
*
* @param int $post_id Post ID.
* @param string $key The meta key to retrieve.
* @param bool $single Whether to return a single value.
* @return mixed Will be an array if $single is false. Will be value of meta data field if $single
* is true.
*/
function get_post_meta($post_id, $key, $single = false) {
if ( !$key )
return '';
$post_id = (int) $post_id;
$meta_cache = wp_cache_get($post_id, 'post_meta');
if ( !$meta_cache ) {
update_postmeta_cache($post_id);
$meta_cache = wp_cache_get($post_id, 'post_meta');
}
if ( isset($meta_cache[$key]) ) {
if ( $single ) {
return maybe_unserialize( $meta_cache[$key][0] );
} else {
return array_map('maybe_unserialize', $meta_cache[$key]);
}
}
return '';
}
/**
* Update post meta field based on post ID.
*
* Use the $prev_value parameter to differentiate between meta fields with the
* same key and post ID.
*
* If the meta field for the post does not exist, it will be added.
*
* @since 1.5
* @uses $wpdb
* @link http://codex.wordpress.org/Function_Reference/update_post_meta
*
* @param int $post_id Post ID.
* @param string $key Metadata key.
* @param mixed $value Metadata value.
* @param mixed $prev_value Optional. Previous value to check before removing.
* @return bool False on failure, true if success.
*/
function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
global $wpdb;
// make sure meta is added to the post, not a revision
if ( $the_post = wp_is_post_revision($post_id) )
$post_id = $the_post;
// expected_slashed ($meta_key)
$meta_key = stripslashes($meta_key);
if ( !$meta_key )
return false;
if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) {
return add_post_meta($post_id, $meta_key, $meta_value);
}
$meta_value = maybe_serialize( stripslashes_deep($meta_value) );
$data = compact( 'meta_value' );
$where = compact( 'meta_key', 'post_id' );
if ( !empty( $prev_value ) ) {
$prev_value = maybe_serialize($prev_value);
$where['meta_value'] = $prev_value;
}
$wpdb->update( $wpdb->postmeta, $data, $where );
wp_cache_delete($post_id, 'post_meta');
return true;
}
/**
* Delete everything from post meta matching meta key.
*
* @since 2.3.0
* @uses $wpdb
*
* @param string $post_meta_key Key to search for when deleting.
* @return bool Whether the post meta key was deleted from the database
*/
function delete_post_meta_by_key($post_meta_key) {
if ( !$post_meta_key )
return false;
global $wpdb;
$post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
if ( $post_ids ) {
$wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
foreach ( $post_ids as $post_id )
wp_cache_delete($post_id, 'post_meta');
return true;
}
return false;
}
/**
* Retrieve post meta fields, based on post ID.
*
* The post meta fields are retrieved from the cache, so the function is
* optimized to be called more than once. It also applies to the functions, that
* use this function.
*
* @since 1.2.0
* @link http://codex.wordpress.org/Function_Reference/get_post_custom
*
* @uses $id Current Loop Post ID
*
* @param int $post_id post ID
* @return array
*/
function get_post_custom($post_id = 0) {
global $id;
if ( !$post_id )
$post_id = (int) $id;
$post_id = (int) $post_id;
if ( ! wp_cache_get($post_id, 'post_meta') )
update_postmeta_cache($post_id);
return wp_cache_get($post_id, 'post_meta');
}
/**
* Retrieve meta field names for a post.
*
* If there are no meta fields, then nothing (null) will be returned.
*
* @since 1.2.0
* @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
*
* @param int $post_id post ID
* @return array|null Either array of the keys, or null if keys could not be retrieved.
*/
function get_post_custom_keys( $post_id = 0 ) {
$custom = get_post_custom( $post_id );
if ( !is_array($custom) )
return;
if ( $keys = array_keys($custom) )
return $keys;
}
/**
* Retrieve values for a custom post field.
*
* The parameters must not be considered optional. All of the post meta fields
* will be retrieved and only the meta field key values returned.
*
* @since 1.2.0
* @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
*
* @param string $key Meta field key.
* @param int $post_id Post ID
* @return array Meta field values.
*/
function get_post_custom_values( $key = '', $post_id = 0 ) {
if ( !$key )
return null;
$custom = get_post_custom($post_id);
return isset($custom[$key]) ? $custom[$key] : null;
}
/**
* Check if post is sticky.
*
* Sticky posts should remain at the top of The Loop. If the post ID is not
* given, then The Loop ID for the current post will be used.
*
* @since 2.7.0
*
* @param int $post_id Optional. Post ID.
* @return bool Whether post is sticky (true) or not sticky (false).
*/
function is_sticky($post_id = null) {
global $id;
$post_id = absint($post_id);
if ( !$post_id )
$post_id = absint($id);
$stickies = get_option('sticky_posts');
if ( !is_array($stickies) )
return false;
if ( in_array($post_id, $stickies) )
return true;
return false;
}
/**
* Sanitize every post field.
*
* If the context is 'raw', then the post object or array will get minimal santization of the int fields.
*
* @since 2.3.0
* @uses sanitize_post_field() Used to sanitize the fields.
*
* @param object|array $post The Post Object or Array
* @param string $context Optional, default is 'display'. How to sanitize post fields.
* @return object|array The now sanitized Post Object or Array (will be the same type as $post)
*/
function sanitize_post($post, $context = 'display') {
if ( is_object($post) ) {
if ( !isset($post->ID) )
$post->ID = 0;
foreach ( array_keys(get_object_vars($post)) as $field )
$post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
$post->filter = $context;
} else {
if ( !isset($post['ID']) )
$post['ID'] = 0;
foreach ( array_keys($post) as $field )
$post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
$post['filter'] = $context;
}
return $post;
}
/**
* Sanitize post field based on context.
*
* Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
* 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
* when calling filters.
*
* @since 2.3.0
* @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
* $post_id if $context == 'edit' and field name prefix == 'post_'.
*
* @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
* @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
* @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
*
* @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
* other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
* @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
* 'edit' and 'db' and field name prefix != 'post_'.
*
* @param string $field The Post Object field name.
* @param mixed $value The Post Object value.
* @param int $post_id Post ID.
* @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
* 'attribute' and 'js'.
* @return mixed Sanitized value.
*/
function sanitize_post_field($field, $value, $post_id, $context) {
$int_fields = array('ID', 'post_parent', 'menu_order');
if ( in_array($field, $int_fields) )
$value = (int) $value;
if ( 'raw' == $context )
return $value;
$prefixed = false;
if ( false !== strpos($field, 'post_') ) {
$prefixed = true;
$field_no_prefix = str_replace('post_', '', $field);
}
if ( 'edit' == $context ) {
$format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
if ( $prefixed ) {
$value = apply_filters("edit_$field", $value, $post_id);
// Old school
$value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
} else {
$value = apply_filters("edit_post_$field", $value, $post_id);
}
if ( in_array($field, $format_to_edit) ) {
if ( 'post_content' == $field )
$value = format_to_edit($value, user_can_richedit());
else
$value = format_to_edit($value);
} else {
$value = esc_attr($value);
}
} else if ( 'db' == $context ) {
if ( $prefixed ) {
$value = apply_filters("pre_$field", $value);
$value = apply_filters("${field_no_prefix}_save_pre", $value);
} else {
$value = apply_filters("pre_post_$field", $value);
$value = apply_filters("${field}_pre", $value);
}
} else {
// Use display filters by default.
if ( $prefixed )
$value = apply_filters($field, $value, $post_id, $context);
else
$value = apply_filters("post_$field", $value, $post_id, $context);
}
if ( 'attribute' == $context )
$value = esc_attr($value);
else if ( 'js' == $context )
$value = esc_js($value);
return $value;
}
/**
* Make a post sticky.
*
* Sticky posts should be displayed at the top of the front page.
*
* @since 2.7.0
*
* @param int $post_id Post ID.
*/
function stick_post($post_id) {
$stickies = get_option('sticky_posts');
if ( !is_array($stickies) )
$stickies = array($post_id);
if ( ! in_array($post_id, $stickies) )
$stickies[] = $post_id;
update_option('sticky_posts', $stickies);
}
/**
* Unstick a post.
*
* Sticky posts should be displayed at the top of the front page.
*
* @since 2.7.0
*
* @param int $post_id Post ID.
*/
function unstick_post($post_id) {
$stickies = get_option('sticky_posts');
if ( !is_array($stickies) )
return;
if ( ! in_array($post_id, $stickies) )
return;
$offset = array_search($post_id, $stickies);
if ( false === $offset )
return;
array_splice($stickies, $offset, 1);
update_option('sticky_posts', $stickies);
}
/**
* Count number of posts of a post type and is user has permissions to view.
*
* This function provides an efficient method of finding the amount of post's
* type a blog has. Another method is to count the amount of items in
* get_posts(), but that method has a lot of overhead with doing so. Therefore,
* when developing for 2.5+, use this function instead.
*
* The $perm parameter checks for 'readable' value and if the user can read
* private posts, it will display that for the user that is signed in.
*
* @since 2.5.0
* @link http://codex.wordpress.org/Template_Tags/wp_count_posts
*
* @param string $type Optional. Post type to retrieve count
* @param string $perm Optional. 'readable' or empty.
* @return object Number of posts for each status
*/
function wp_count_posts( $type = 'post', $perm = '' ) {
global $wpdb;
$user = wp_get_current_user();
$cache_key = $type;
$query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
if ( 'readable' == $perm && is_user_logged_in() ) {
if ( !current_user_can("read_private_{$type}s") ) {
$cache_key .= '_' . $perm . '_' . $user->ID;
$query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
}
}
$query .= ' GROUP BY post_status';
$count = wp_cache_get($cache_key, 'counts');
if ( false !== $count )
return $count;
$count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
$stats = array( 'publish' => 0, 'private' => 0, 'draft' => 0, 'pending' => 0, 'future' => 0 );
foreach( (array) $count as $row_num => $row ) {
$stats[$row['post_status']] = $row['num_posts'];
}
$stats = (object) $stats;
wp_cache_set($cache_key, $stats, 'counts');
return $stats;
}
/**
* Count number of attachments for the mime type(s).
*
* If you set the optional mime_type parameter, then an array will still be
* returned, but will only have the item you are looking for. It does not give
* you the number of attachments that are children of a post. You can get that
* by counting the number of children that post has.
*
* @since 2.5.0
*
* @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
* @return array Number of posts for each mime type.
*/
function wp_count_attachments( $mime_type = '' ) {
global $wpdb;
$and = wp_post_mime_type_where( $mime_type );
$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' $and GROUP BY post_mime_type", ARRAY_A );
$stats = array( );
foreach( (array) $count as $row ) {
$stats[$row['post_mime_type']] = $row['num_posts'];
}
return (object) $stats;
}
/**
* Check a MIME-Type against a list.
*
* If the wildcard_mime_types parameter is a string, it must be comma separated
* list. If the real_mime_types is a string, it is also comma separated to
* create the list.
*
* @since 2.5.0
*
* @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
* flash (same as *flash*).
* @param string|array $real_mime_types post_mime_type values
* @return array array(wildcard=>array(real types))
*/
function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
$matches = array();
if ( is_string($wildcard_mime_types) )
$wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
if ( is_string($real_mime_types) )
$real_mime_types = array_map('trim', explode(',', $real_mime_types));
$wild = '[-._a-z0-9]*';
foreach ( (array) $wildcard_mime_types as $type ) {
$type = str_replace('*', $wild, $type);
$patternses[1][$type] = "^$type$";
if ( false === strpos($type, '/') ) {
$patternses[2][$type] = "^$type/";
$patternses[3][$type] = $type;
}
}
asort($patternses);
foreach ( $patternses as $patterns )
foreach ( $patterns as $type => $pattern )
foreach ( (array) $real_mime_types as $real )
if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
$matches[$type][] = $real;
return $matches;
}
/**
* Convert MIME types into SQL.
*
* @since 2.5.0
*
* @param string|array $mime_types List of mime types or comma separated string of mime types.
* @return string The SQL AND clause for mime searching.
*/
function wp_post_mime_type_where($post_mime_types) {
$where = '';
$wildcards = array('', '%', '%/%');
if ( is_string($post_mime_types) )
$post_mime_types = array_map('trim', explode(',', $post_mime_types));
foreach ( (array) $post_mime_types as $mime_type ) {
$mime_type = preg_replace('/\s/', '', $mime_type);
$slashpos = strpos($mime_type, '/');
if ( false !== $slashpos ) {
$mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
$mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
if ( empty($mime_subgroup) )
$mime_subgroup = '*';
else
$mime_subgroup = str_replace('/', '', $mime_subgroup);
$mime_pattern = "$mime_group/$mime_subgroup";
} else {
$mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
if ( false === strpos($mime_pattern, '*') )
$mime_pattern .= '/*';
}
$mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
if ( in_array( $mime_type, $wildcards ) )
return '';
if ( false !== strpos($mime_pattern, '%') )
$wheres[] = "post_mime_type LIKE '$mime_pattern'";
else
$wheres[] = "post_mime_type = '$mime_pattern'";
}
if ( !empty($wheres) )
$where = ' AND (' . join(' OR ', $wheres) . ') ';
return $where;
}
/**
* Removes a post, attachment, or page.
*
* When the post and page goes, everything that is tied to it is deleted also.
* This includes comments, post meta fields, and terms associated with the post.
*
* @since 1.0.0
* @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
* @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
* @uses wp_delete_attachment() if post type is 'attachment'.
*
* @param int $postid Post ID.
* @return mixed False on failure
*/
function wp_delete_post($postid = 0) {
global $wpdb, $wp_rewrite;
if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
return $post;
if ( 'attachment' == $post->post_type )
return wp_delete_attachment($postid);
do_action('delete_post', $postid);
/** @todo delete for pluggable post taxonomies too */
wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
$parent_data = array( 'post_parent' => $post->post_parent );
$parent_where = array( 'post_parent' => $postid );
if ( 'page' == $post->post_type) {
// if the page is defined in option page_on_front or post_for_posts,
// adjust the corresponding options
if ( get_option('page_on_front') == $postid ) {
update_option('show_on_front', 'posts');
delete_option('page_on_front');
}
if ( get_option('page_for_posts') == $postid ) {
delete_option('page_for_posts');
}
// Point children of this page to its parent, also clean the cache of affected children
$children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
$children = $wpdb->get_results($children_query);
$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
} else {
unstick_post($postid);
}
// Do raw query. wp_get_post_revisions() is filtered
$revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
// Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
foreach ( $revision_ids as $revision_id )
wp_delete_post_revision( $revision_id );
// Point all attachments to this post up one level
$wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d", $postid ));
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
if ( 'page' == $post->post_type ) {
clean_page_cache($postid);
foreach ( (array) $children as $child )
clean_page_cache($child->ID);
$wp_rewrite->flush_rules(false);
} else {
clean_post_cache($postid);
}
wp_clear_scheduled_hook('publish_future_post', $postid);
do_action('deleted_post', $postid);
return $post;
}
/**
* Retrieve the list of categories for a post.
*
* Compatibility layer for themes and plugins. Also an easy layer of abstraction
* away from the complexity of the taxonomy layer.
*
* @since 2.1.0
*
* @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
*
* @param int $post_id Optional. The Post ID.
* @param array $args Optional. Overwrite the defaults.
* @return array
*/
function wp_get_post_categories( $post_id = 0, $args = array() ) {
$post_id = (int) $post_id;
$defaults = array('fields' => 'ids');
$args = wp_parse_args( $args, $defaults );
$cats = wp_get_object_terms($post_id, 'category', $args);
return $cats;
}
/**
* Retrieve the tags for a post.
*
* There is only one default for this function, called 'fields' and by default
* is set to 'all'. There are other defaults that can be overridden in
* {@link wp_get_object_terms()}.
*
* @package WordPress
* @subpackage Post
* @since 2.3.0
*
* @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
*
* @param int $post_id Optional. The Post ID
* @param array $args Optional. Overwrite the defaults
* @return array List of post tags.
*/
function wp_get_post_tags( $post_id = 0, $args = array() ) {
return wp_get_post_terms( $post_id, 'post_tag', $args);
}
/**
* Retrieve the terms for a post.
*
* There is only one default for this function, called 'fields' and by default
* is set to 'all'. There are other defaults that can be overridden in
* {@link wp_get_object_terms()}.
*
* @package WordPress
* @subpackage Post
* @since 2.8.0
*
* @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
*
* @param int $post_id Optional. The Post ID
* @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
* @param array $args Optional. Overwrite the defaults
* @return array List of post tags.
*/
function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
$post_id = (int) $post_id;
$defaults = array('fields' => 'all');
$args = wp_parse_args( $args, $defaults );
$tags = wp_get_object_terms($post_id, $taxonomy, $args);
return $tags;
}
/**
* Retrieve number of recent posts.
*
* @since 1.0.0
* @uses $wpdb
*
* @param int $num Optional, default is 10. Number of posts to get.
* @return array List of posts.
*/
function wp_get_recent_posts($num = 10) {
global $wpdb;
// Set the limit clause, if we got a limit
$num = (int) $num;
if ($num) {
$limit = "LIMIT $num";
}
$sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit";
$result = $wpdb->get_results($sql,ARRAY_A);
return $result ? $result : array();
}
/**
* Retrieve a single post, based on post ID.
*
* Has categories in 'post_category' property or key. Has tags in 'tags_input'
* property or key.
*
* @since 1.0.0
*
* @param int $postid Post ID.
* @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
* @return object|array Post object or array holding post contents and information
*/
function wp_get_single_post($postid = 0, $mode = OBJECT) {
$postid = (int) $postid;
$post = get_post($postid, $mode);
// Set categories and tags
if($mode == OBJECT) {
$post->post_category = wp_get_post_categories($postid);
$post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
}
else {
$post['post_category'] = wp_get_post_categories($postid);
$post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
}
return $post;
}
/**
* Insert a post.
*
* If the $postarr parameter has 'ID' set to a value, then post will be updated.
*
* You can set the post date manually, but setting the values for 'post_date'
* and 'post_date_gmt' keys. You can close the comments or open the comments by
* setting the value for 'comment_status' key.
*
* The defaults for the parameter $postarr are:
* 'post_status' - Default is 'draft'.
* 'post_type' - Default is 'post'.
* 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post.
* 'ping_status' - Default is the value in 'default_ping_status' option.
* Whether the attachment can accept pings.
* 'post_parent' - Default is 0. Set this for the post it belongs to, if any.
* 'menu_order' - Default is 0. The order it is displayed.
* 'to_ping' - Whether to ping.
* 'pinged' - Default is empty string.
* 'post_password' - Default is empty string. The password to access the attachment.
* 'guid' - Global Unique ID for referencing the attachment.
* 'post_content_filtered' - Post content filtered.
* 'post_excerpt' - Post excerpt.
*
* @since 1.0.0
* @link http://core.trac.wordpress.org/ticket/9084 Bug report on 'wp_insert_post_data' filter.
* @uses $wpdb
* @uses $wp_rewrite
* @uses $user_ID
*
* @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
* @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
* @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before
* returning.
*
* @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database
* update or insert.
* @uses wp_transition_post_status()
*
* @param array $postarr Optional. Overrides defaults.
* @param bool $wp_error Optional. Allow return of WP_Error on failure.
* @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
*/
function wp_insert_post($postarr = array(), $wp_error = false) {
global $wpdb, $wp_rewrite, $user_ID;
$defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
$postarr = wp_parse_args($postarr, $defaults);
$postarr = sanitize_post($postarr, 'db');
// export array as variables
extract($postarr, EXTR_SKIP);
// Are we updating or creating?
$update = false;
if ( !empty($ID) ) {
$update = true;
$previous_status = get_post_field('post_status', $ID);
} else {
$previous_status = 'new';
}
if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) ) {
if ( $wp_error )
return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
else
return 0;
}
// Make sure we set a valid category
if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
$post_category = array(get_option('default_category'));
}
//Set the default tag list
if ( !isset($tags_input) )
$tags_input = array();
if ( empty($post_author) )
$post_author = $user_ID;
if ( empty($post_status) )
$post_status = 'draft';
if ( empty($post_type) )
$post_type = 'post';
$post_ID = 0;
// Get the post ID and GUID
if ( $update ) {
$post_ID = (int) $ID;
$guid = get_post_field( 'guid', $post_ID );
}
// Don't allow contributors to set to set the post slug for pending review posts
if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
$post_name = '';
// Create a valid post name. Drafts and pending posts are allowed to have an empty
// post name.
if ( !isset($post_name) || empty($post_name) ) {
if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
$post_name = sanitize_title($post_title);
else
$post_name = '';
} else {
$post_name = sanitize_title($post_name);
}
// If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now
if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
$post_date = current_time('mysql');
if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
$post_date_gmt = get_gmt_from_date($post_date);
else
$post_date_gmt = '0000-00-00 00:00:00';
}
if ( $update || '0000-00-00 00:00:00' == $post_date ) {
$post_modified = current_time( 'mysql' );
$post_modified_gmt = current_time( 'mysql', 1 );
} else {
$post_modified = $post_date;
$post_modified_gmt = $post_date_gmt;
}
if ( 'publish' == $post_status ) {
$now = gmdate('Y-m-d H:i:59');
if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
$post_status = 'future';
}
if ( empty($comment_status) ) {
if ( $update )
$comment_status = 'closed';
else
$comment_status = get_option('default_comment_status');
}
if ( empty($ping_status) )
$ping_status = get_option('default_ping_status');
if ( isset($to_ping) )
$to_ping = preg_replace('|\s+|', "\n", $to_ping);
else
$to_ping = '';
if ( ! isset($pinged) )
$pinged = '';
if ( isset($post_parent) )
$post_parent = (int) $post_parent;
else
$post_parent = 0;
if ( !empty($post_ID) ) {
if ( $post_parent == $post_ID ) {
// Post can't be its own parent
$post_parent = 0;
} elseif ( !empty($post_parent) ) {
$parent_post = get_post($post_parent);
// Check for circular dependency
if ( $parent_post->post_parent == $post_ID )
$post_parent = 0;
}
}
if ( isset($menu_order) )
$menu_order = (int) $menu_order;
else
$menu_order = 0;
if ( !isset($post_password) || 'private' == $post_status )
$post_password = '';
$post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
// expected_slashed (everything!)
$data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) );
$data = apply_filters('wp_insert_post_data', $data, $postarr);
$data = stripslashes_deep( $data );
$where = array( 'ID' => $post_ID );
if ($update) {
do_action( 'pre_post_update', $post_ID );
if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
if ( $wp_error )
return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
else
return 0;
}
} else {
if ( isset($post_mime_type) )
$data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
// If there is a suggested ID, use it if not already present
if ( !empty($import_id) ) {
$import_id = (int) $import_id;
if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
$data['ID'] = $import_id;
}
}
if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
if ( $wp_error )
return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
else
return 0;
}
$post_ID = (int) $wpdb->insert_id;
// use the newly generated $post_ID
$where = array( 'ID' => $post_ID );
}
if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending' ) ) ) {
$data['post_name'] = sanitize_title($data['post_title'], $post_ID);
$wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
}
wp_set_post_categories( $post_ID, $post_category );
// old-style tags_input
if ( !empty($tags_input) )
wp_set_post_tags( $post_ID, $tags_input );
// new-style support for all tag-like taxonomies
if ( !empty($tax_input) ) {
foreach ( $tax_input as $taxonomy => $tags ) {
wp_set_post_terms( $post_ID, $tags, $taxonomy );
}
}
$current_guid = get_post_field( 'guid', $post_ID );
if ( 'page' == $data['post_type'] )
clean_page_cache($post_ID);
else
clean_post_cache($post_ID);
// Set GUID
if ( !$update && '' == $current_guid )
$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
$post = get_post($post_ID);
if ( !empty($page_template) && 'page' == $data['post_type'] ) {
$post->page_template = $page_template;
$page_templates = get_page_templates();
if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
if ( $wp_error )
return new WP_Error('invalid_page_template', __('The page template is invalid.'));
else
return 0;
}
update_post_meta($post_ID, '_wp_page_template', $page_template);
}
wp_transition_post_status($data['post_status'], $previous_status, $post);
if ( $update)
do_action('edit_post', $post_ID, $post);
do_action('save_post', $post_ID, $post);
do_action('wp_insert_post', $post_ID, $post);
return $post_ID;
}
/**
* Update a post with new post data.
*
* The date does not have to be set for drafts. You can set the date and it will
* not be overridden.
*
* @since 1.0.0
*
* @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
* @return int 0 on failure, Post ID on success.
*/
function wp_update_post($postarr = array()) {
if ( is_object($postarr) ) {
// non-escaped post was passed
$postarr = get_object_vars($postarr);
$postarr = add_magic_quotes($postarr);
}
// First, get all of the original fields
$post = wp_get_single_post($postarr['ID'], ARRAY_A);
// Escape data pulled from DB.
$post = add_magic_quotes($post);
// Passed post category list overwrites existing category list if not empty.
if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
&& 0 != count($postarr['post_category']) )
$post_cats = $postarr['post_category'];
else
$post_cats = $post['post_category'];
// Drafts shouldn't be assigned a date unless explicitly done so by the user
if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
('0000-00-00 00:00:00' == $post['post_date_gmt']) )
$clear_date = true;
else
$clear_date = false;
// Merge old and new fields with new fields overwriting old ones.
$postarr = array_merge($post, $postarr);
$postarr['post_category'] = $post_cats;
if ( $clear_date ) {
$postarr['post_date'] = current_time('mysql');
$postarr['post_date_gmt'] = '';
}
if ($postarr['post_type'] == 'attachment')
return wp_insert_attachment($postarr);
return wp_insert_post($postarr);
}
/**
* Publish a post by transitioning the post status.
*
* @since 2.1.0
* @uses $wpdb
* @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
*
* @param int $post_id Post ID.
* @return null
*/
function wp_publish_post($post_id) {
global $wpdb;
$post = get_post($post_id);
if ( empty($post) )
return;
if ( 'publish' == $post->post_status )
return;
$wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
$old_status = $post->post_status;
$post->post_status = 'publish';
wp_transition_post_status('publish', $old_status, $post);
// Update counts for the post's terms.
foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
$tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
wp_update_term_count($tt_ids, $taxonomy);
}
do_action('edit_post', $post_id, $post);
do_action('save_post', $post_id, $post);
do_action('wp_insert_post', $post_id, $post);
}
/**
* Publish future post and make sure post ID has future post status.
*
* Invoked by cron 'publish_future_post' event. This safeguard prevents cron
* from publishing drafts, etc.
*
* @since 2.5.0
*
* @param int $post_id Post ID.
* @return null Nothing is returned. Which can mean that no action is required or post was published.
*/
function check_and_publish_future_post($post_id) {
$post = get_post($post_id);
if ( empty($post) )
return;
if ( 'future' != $post->post_status )
return;
$time = strtotime( $post->post_date_gmt . ' GMT' );
if ( $time > time() ) { // Uh oh, someone jumped the gun!
wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
return;
}
return wp_publish_post($post_id);
}
/**
* Given the desired slug and some post details computes a unique slug for the post.
*
* @param string $slug the desired slug (post_name)
* @param integer $post_ID
* @param string $post_status no uniqueness checks are made if the post is still draft or pending
* @param string $post_type
* @param integer $post_parent
* @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
*/
function wp_unique_post_slug($slug, $post_ID, $post_status, $post_type, $post_parent) {
if ( in_array( $post_status, array( 'draft', 'pending' ) ) )
return $slug;
global $wpdb, $wp_rewrite;
$hierarchical_post_types = apply_filters('hierarchical_post_types', array('page'));
if ( 'attachment' == $post_type ) {
// Attachment slugs must be unique across all types.
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID));
if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
$suffix = 2;
do {
$alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID));
$suffix++;
} while ($post_name_check);
$slug = $alt_post_name;
}
} elseif ( in_array($post_type, $hierarchical_post_types) ) {
// Page slugs must be unique within their own trees. Pages are in a
// separate namespace than posts so page slugs are allowed to overlap post slugs.
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode("', '", $wpdb->escape($hierarchical_post_types)) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID, $post_parent));
if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
$suffix = 2;
do {
$alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID, $post_parent));
$suffix++;
} while ($post_name_check);
$slug = $alt_post_name;
}
} else {
// Post slugs must be unique across all posts.
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_type, $post_ID));
if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
$suffix = 2;
do {
$alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_type, $post_ID));
$suffix++;
} while ($post_name_check);
$slug = $alt_post_name;
}
}
return $slug;
}
/**
* Adds tags to a post.
*
* @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
*
* @package WordPress
* @subpackage Post
* @since 2.3.0
*
* @param int $post_id Post ID
* @param string $tags The tags to set for the post, separated by commas.
* @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
*/
function wp_add_post_tags($post_id = 0, $tags = '') {
return wp_set_post_tags($post_id, $tags, true);
}
/**
* Set the tags for a post.
*
* @since 2.3.0
* @uses wp_set_object_terms() Sets the tags for the post.
*
* @param int $post_id Post ID.
* @param string $tags The tags to set for the post, separated by commas.
* @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
* @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
*/
function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
}
/**
* Set the terms for a post.
*
* @since 2.8.0
* @uses wp_set_object_terms() Sets the tags for the post.
*
* @param int $post_id Post ID.
* @param string $tags The tags to set for the post, separated by commas.
* @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
* @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
*/
function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
$post_id = (int) $post_id;
if ( !$post_id )
return false;
if ( empty($tags) )
$tags = array();
$tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
wp_set_object_terms($post_id, $tags, $taxonomy, $append);
}
/**
* Set categories for a post.
*
* If the post categories parameter is not set, then the default category is
* going used.
*
* @since 2.1.0
*
* @param int $post_ID Post ID.
* @param array $post_categories Optional. List of categories.
* @return bool|mixed
*/
function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
$post_ID = (int) $post_ID;
// If $post_categories isn't already an array, make it one:
if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
$post_categories = array(get_option('default_category'));
else if ( 1 == count($post_categories) && '' == $post_categories[0] )
return true;
$post_categories = array_map('intval', $post_categories);
$post_categories = array_unique($post_categories);
return wp_set_object_terms($post_ID, $post_categories, 'category');
}
/**
* Transition the post status of a post.
*
* Calls hooks to transition post status.
*
* The first is 'transition_post_status' with new status, old status, and post data.
*
* The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
* $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
* post data.
*
* The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
* parameter and POSTTYPE is post_type post data.
*
* @since 2.3.0
* @link http://codex.wordpress.org/Post_Status_Transitions
*
* @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
* $post if there is a status change.
* @uses do_action() Calls '${old_status}_to_$new_status' on $post if there is a status change.
* @uses do_action() Calls '${new_status}_$post->post_type' on post ID and $post.
*
* @param string $new_status Transition to this post status.
* @param string $old_status Previous post status.
* @param object $post Post data.
*/
function wp_transition_post_status($new_status, $old_status, $post) {
do_action('transition_post_status', $new_status, $old_status, $post);
do_action("${old_status}_to_$new_status", $post);
do_action("${new_status}_$post->post_type", $post->ID, $post);
}
//
// Trackback and ping functions
//
/**
* Add a URL to those already pung.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID.
* @param string $uri Ping URI.
* @return int How many rows were updated.
*/
function add_ping($post_id, $uri) {
global $wpdb;
$pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
$pung = trim($pung);
$pung = preg_split('/\s/', $pung);
$pung[] = $uri;
$new = implode("\n", $pung);
$new = apply_filters('add_ping', $new);
// expected_slashed ($new)
$new = stripslashes($new);
return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
}
/**
* Retrieve enclosures already enclosed for a post.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID.
* @return array List of enclosures
*/
function get_enclosed($post_id) {
$custom_fields = get_post_custom( $post_id );
$pung = array();
if ( !is_array( $custom_fields ) )
return $pung;
foreach ( $custom_fields as $key => $val ) {
if ( 'enclosure' != $key || !is_array( $val ) )
continue;
foreach( $val as $enc ) {
$enclosure = split( "\n", $enc );
$pung[] = trim( $enclosure[ 0 ] );
}
}
$pung = apply_filters('get_enclosed', $pung);
return $pung;
}
/**
* Retrieve URLs already pinged for a post.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID.
* @return array
*/
function get_pung($post_id) {
global $wpdb;
$pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
$pung = trim($pung);
$pung = preg_split('/\s/', $pung);
$pung = apply_filters('get_pung', $pung);
return $pung;
}
/**
* Retrieve URLs that need to be pinged.
*
* @since 1.5.0
* @uses $wpdb
*
* @param int $post_id Post ID
* @return array
*/
function get_to_ping($post_id) {
global $wpdb;
$to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
$to_ping = trim($to_ping);
$to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
$to_ping = apply_filters('get_to_ping', $to_ping);
return $to_ping;
}
/**
* Do trackbacks for a list of URLs.
*
* @since 1.0.0
*
* @param string $tb_list Comma separated list of URLs
* @param int $post_id Post ID
*/
function trackback_url_list($tb_list, $post_id) {
if ( ! empty( $tb_list ) ) {
// get post data
$postdata = wp_get_single_post($post_id, ARRAY_A);
// import postdata as variables
extract($postdata, EXTR_SKIP);
// form an excerpt
$excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
if (strlen($excerpt) > 255) {
$excerpt = substr($excerpt,0,252) . '...';
}
$trackback_urls = explode(',', $tb_list);
foreach( (array) $trackback_urls as $tb_url) {
$tb_url = trim($tb_url);
trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
}
}
}
//
// Page functions
//
/**
* Get a list of page IDs.
*
* @since 2.0.0
* @uses $wpdb
*
* @return array List of page IDs.
*/
function get_all_page_ids() {
global $wpdb;
if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
$page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
wp_cache_add('all_page_ids', $page_ids, 'posts');
}
return $page_ids;
}
/**
* Retrieves page data given a page ID or page object.
*
* @since 1.5.1
*
* @param mixed $page Page object or page ID. Passed by reference.
* @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
* @param string $filter How the return value should be filtered.
* @return mixed Page data.
*/
function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
if ( empty($page) ) {
if ( isset( $GLOBALS['page'] ) && isset( $GLOBALS['page']->ID ) ) {
return get_post($GLOBALS['page'], $output, $filter);
} else {
$page = null;
return $page;
}
}
$the_page = get_post($page, $output, $filter);
return $the_page;
}
/**
* Retrieves a page given its path.
*
* @since 2.1.0
* @uses $wpdb
*
* @param string $page_path Page path
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* @return mixed Null when complete.
*/
function get_page_by_path($page_path, $output = OBJECT) {
global $wpdb;
$page_path = rawurlencode(urldecode($page_path));
$page_path = str_replace('%2F', '/', $page_path);
$page_path = str_replace('%20', ' ', $page_path);
$page_paths = '/' . trim($page_path, '/');
$leaf_path = sanitize_title(basename($page_paths));
$page_paths = explode('/', $page_paths);
$full_path = '';
foreach( (array) $page_paths as $pathdir)
$full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
$pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = 'page' OR post_type = 'attachment')", $leaf_path ));
if ( empty($pages) )
return null;
foreach ($pages as $page) {
$path = '/' . $leaf_path;
$curpage = $page;
while ($curpage->post_parent != 0) {
$curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type='page'", $curpage->post_parent ));
$path = '/' . $curpage->post_name . $path;
}
if ( $path == $full_path )
return get_page($page->ID, $output);
}
return null;
}
/**
* Retrieve a page given its title.
*
* @since 2.1.0
* @uses $wpdb
*
* @param string $page_title Page title
* @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
* @return mixed
*/
function get_page_by_title($page_title, $output = OBJECT) {
global $wpdb;
$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
if ( $page )
return get_page($page, $output);
return null;
}
/**
* Retrieve child pages from list of pages matching page ID.
*
* Matches against the pages parameter against the page ID. Also matches all
* children for the same to retrieve all children of a page. Does not make any
* SQL queries to get the children.
*
* @since 1.5.1
*
* @param int $page_id Page ID.
* @param array $pages List of pages' objects.
* @return array
*/
function &get_page_children($page_id, $pages) {
$page_list = array();
foreach ( (array) $pages as $page ) {
if ( $page->post_parent == $page_id ) {
$page_list[] = $page;
if ( $children = get_page_children($page->ID, $pages) )
$page_list = array_merge($page_list, $children);
}
}
return $page_list;
}
/**
* Order the pages with children under parents in a flat list.
*
* @since 2.0.0
*
* @param array $posts Posts array.
* @param int $parent Parent page ID.
* @return array A list arranged by hierarchy. Children immediately follow their parents.
*/
function get_page_hierarchy($posts, $parent = 0) {
$result = array ( );
if ($posts) { foreach ( (array) $posts as $post) {
if ($post->post_parent == $parent) {
$result[$post->ID] = $post->post_name;
$children = get_page_hierarchy($posts, $post->ID);
$result += $children; //append $children to $result
}
} }
return $result;
}
/**
* Builds URI for a page.
*
* Sub pages will be in the "directory" under the parent page post name.
*
* @since 1.5.0
*
* @param int $page_id Page ID.
* @return string Page URI.
*/
function get_page_uri($page_id) {
$page = get_page($page_id);
$uri = $page->post_name;
// A page cannot be it's own parent.
if ( $page->post_parent == $page->ID )
return $uri;
while ($page->post_parent != 0) {
$page = get_page($page->post_parent);
$uri = $page->post_name . "/" . $uri;
}
return $uri;
}
/**
* Retrieve a list of pages.
*
* The defaults that can be overridden are the following: 'child_of',
* 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
* 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
*
* @since 1.5.0
* @uses $wpdb
*
* @param mixed $args Optional. Array or string of options that overrides defaults.
* @return array List of pages matching defaults or $args
*/
function &get_pages($args = '') {
global $wpdb;
$defaults = array(
'child_of' => 0, 'sort_order' => 'ASC',
'sort_column' => 'post_title', 'hierarchical' => 1,
'exclude' => '', 'include' => '',
'meta_key' => '', 'meta_value' => '',
'authors' => '', 'parent' => -1, 'exclude_tree' => '',
'number' => '', 'offset' => 0
);
$r = wp_parse_args( $args, $defaults );
extract( $r, EXTR_SKIP );
$number = (int) $number;
$offset = (int) $offset;
$cache = array();
$key = md5( serialize( compact(array_keys($defaults)) ) );
if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
if ( is_array($cache) && isset( $cache[ $key ] ) ) {
$pages = apply_filters('get_pages', $cache[ $key ], $r );
return $pages;
}
}
if ( !is_array($cache) )
$cache = array();
$inclusions = '';
if ( !empty($include) ) {
$child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
$parent = -1;
$exclude = '';
$meta_key = '';
$meta_value = '';
$hierarchical = false;
$incpages = preg_split('/[\s,]+/',$include);
if ( count($incpages) ) {
foreach ( $incpages as $incpage ) {
if (empty($inclusions))
$inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
else
$inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
}
}
}
if (!empty($inclusions))
$inclusions .= ')';
$exclusions = '';
if ( !empty($exclude) ) {
$expages = preg_split('/[\s,]+/',$exclude);
if ( count($expages) ) {
foreach ( $expages as $expage ) {
if (empty($exclusions))
$exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
else
$exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
}
}
}
if (!empty($exclusions))
$exclusions .= ')';
$author_query = '';
if (!empty($authors)) {
$post_authors = preg_split('/[\s,]+/',$authors);
if ( count($post_authors) ) {
foreach ( $post_authors as $post_author ) {
//Do we have an author id or an author login?
if ( 0 == intval($post_author) ) {
$post_author = get_userdatabylogin($post_author);
if ( empty($post_author) )
continue;
if ( empty($post_author->ID) )
continue;
$post_author = $post_author->ID;
}
if ( '' == $author_query )
$author_query = $wpdb->prepare(' post_author = %d ', $post_author);
else
$author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
}
if ( '' != $author_query )
$author_query = " AND ($author_query)";
}
}
$join = '';
$where = "$exclusions $inclusions ";
if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
$join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
// meta_key and meta_value might be slashed
$meta_key = stripslashes($meta_key);
$meta_value = stripslashes($meta_value);
if ( ! empty( $meta_key ) )
$where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
if ( ! empty( $meta_value ) )
$where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
}
if ( $parent >= 0 )
$where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
$query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
$query .= $author_query;
$query .= " ORDER BY " . $sort_column . " " . $sort_order ;
if ( !empty($number) )
$query .= ' LIMIT ' . $offset . ',' . $number;
$pages = $wpdb->get_results($query);
if ( empty($pages) ) {
$pages = apply_filters('get_pages', array(), $r);
return $pages;
}
// Update cache.
update_page_cache($pages);
if ( $child_of || $hierarchical )
$pages = & get_page_children($child_of, $pages);
if ( !empty($exclude_tree) ) {
$exclude = array();
$exclude = (int) $exclude_tree;
$children = get_page_children($exclude, $pages);
$excludes = array();
foreach ( $children as $child )
$excludes[] = $child->ID;
$excludes[] = $exclude;
$total = count($pages);
for ( $i = 0; $i < $total; $i++ ) {
if ( in_array($pages[$i]->ID, $excludes) )
unset($pages[$i]);
}
}
$cache[ $key ] = $pages;
wp_cache_set( 'get_pages', $cache, 'posts' );
$pages = apply_filters('get_pages', $pages, $r);
return $pages;
}
//
// Attachment functions
//
/**
* Check if the attachment URI is local one and is really an attachment.
*
* @since 2.0.0
*
* @param string $url URL to check
* @return bool True on success, false on failure.
*/
function is_local_attachment($url) {
if (strpos($url, get_bloginfo('url')) === false)
return false;
if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
return true;
if ( $id = url_to_postid($url) ) {
$post = & get_post($id);
if ( 'attachment' == $post->post_type )
return true;
}
return false;
}
/**
* Insert an attachment.
*
* If you set the 'ID' in the $object parameter, it will mean that you are
* updating and attempt to update the attachment. You can also set the
* attachment name or title by setting the key 'post_name' or 'post_title'.
*
* You can set the dates for the attachment manually by setting the 'post_date'
* and 'post_date_gmt' keys' values.
*
* By default, the comments will use the default settings for whether the
* comments are allowed. You can close them manually or keep them open by
* setting the value for the 'comment_status' key.
*
* The $object parameter can have the following:
* 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post.
* 'post_type' - Default is 'post', will be set to attachment. Can not override.
* 'post_author' - Default is current user ID. The ID of the user, who added the attachment.
* 'ping_status' - Default is the value in default ping status option. Whether the attachment
* can accept pings.
* 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs
* to, if any.
* 'menu_order' - Default is 0. The order it is displayed.
* 'to_ping' - Whether to ping.
* 'pinged' - Default is empty string.
* 'post_password' - Default is empty string. The password to access the attachment.
* 'guid' - Global Unique ID for referencing the attachment.
* 'post_content_filtered' - Attachment post content filtered.
* 'post_excerpt' - Attachment excerpt.
*
* @since 2.0.0
* @uses $wpdb
* @uses $user_ID
* @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
* @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
*
* @param string|array $object Arguments to override defaults.
* @param string $file Optional filename.
* @param int $post_parent Parent post ID.
* @return int Attachment ID.
*/
function wp_insert_attachment($object, $file = false, $parent = 0) {
global $wpdb, $user_ID;
$defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
$object = wp_parse_args($object, $defaults);
if ( !empty($parent) )
$object['post_parent'] = $parent;
$object = sanitize_post($object, 'db');
// export array as variables
extract($object, EXTR_SKIP);
// Make sure we set a valid category
if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
$post_category = array(get_option('default_category'));
}
if ( empty($post_author) )
$post_author = $user_ID;
$post_type = 'attachment';
$post_status = 'inherit';
// Are we updating or creating?
if ( !empty($ID) ) {
$update = true;
$post_ID = (int) $ID;
} else {
$update = false;
$post_ID = 0;
}
// Create a valid post name.
if ( empty($post_name) )
$post_name = sanitize_title($post_title);
else
$post_name = sanitize_title($post_name);
// expected_slashed ($post_name)
$post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
if ( empty($post_date) )
$post_date = current_time('mysql');
if ( empty($post_date_gmt) )
$post_date_gmt = current_time('mysql', 1);
if ( empty($post_modified) )
$post_modified = $post_date;
if ( empty($post_modified_gmt) )
$post_modified_gmt = $post_date_gmt;
if ( empty($comment_status) ) {
if ( $update )
$comment_status = 'closed';
else
$comment_status = get_option('default_comment_status');
}
if ( empty($ping_status) )
$ping_status = get_option('default_ping_status');
if ( isset($to_ping) )
$to_ping = preg_replace('|\s+|', "\n", $to_ping);
else
$to_ping = '';
if ( isset($post_parent) )
$post_parent = (int) $post_parent;
else
$post_parent = 0;
if ( isset($menu_order) )
$menu_order = (int) $menu_order;
else
$menu_order = 0;
if ( !isset($post_password) )
$post_password = '';
if ( ! isset($pinged) )
$pinged = '';
// expected_slashed (everything!)
$data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' ) );
$data = stripslashes_deep( $data );
if ( $update ) {
$wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
} else {
// If there is a suggested ID, use it if not already present
if ( !empty($import_id) ) {
$import_id = (int) $import_id;
if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
$data['ID'] = $import_id;
}
}
$wpdb->insert( $wpdb->posts, $data );
$post_ID = (int) $wpdb->insert_id;
}
if ( empty($post_name) ) {
$post_name = sanitize_title($post_title, $post_ID);
$wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
}
wp_set_post_categories($post_ID, $post_category);
if ( $file )
update_attached_file( $post_ID, $file );
clean_post_cache($post_ID);
if ( $update) {
do_action('edit_attachment', $post_ID);
} else {
do_action('add_attachment', $post_ID);
}
return $post_ID;
}
/**
* Delete an attachment.
*
* Will remove the file also, when the attachment is removed. Removes all post
* meta fields, taxonomy, comments, etc associated with the attachment (except
* the main post).
*
* @since 2.0.0
* @uses $wpdb
* @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
*
* @param int $postid Attachment ID.
* @return mixed False on failure. Post data on success.
*/
function wp_delete_attachment($postid) {
global $wpdb;
if ( !$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
return $post;
if ( 'attachment' != $post->post_type )
return false;
$meta = wp_get_attachment_metadata( $postid );
$file = get_attached_file( $postid );
do_action('delete_attachment', $postid);
/** @todo Delete for pluggable post taxonomies too */
wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
$wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
$uploadPath = wp_upload_dir();
if ( ! empty($meta['thumb']) ) {
// Don't delete the thumb if another attachment uses it
if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%'.$meta['thumb'].'%', $postid)) ) {
$thumbfile = str_replace(basename($file), $meta['thumb'], $file);
$thumbfile = apply_filters('wp_delete_file', $thumbfile);
@ unlink( path_join($uploadPath['basedir'], $thumbfile) );
}
}
// remove intermediate images if there are any
$sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
foreach ( $sizes as $size ) {
if ( $intermediate = image_get_intermediate_size($postid, $size) ) {
$intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
@ unlink( path_join($uploadPath['basedir'], $intermediate_file) );
}
}
$file = apply_filters('wp_delete_file', $file);
if ( ! empty($file) )
@ unlink($file);
clean_post_cache($postid);
return $post;
}
/**
* Retrieve attachment meta field for attachment ID.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID
* @param bool $unfiltered Optional, default is false. If true, filters are not run.
* @return string|bool Attachment meta field. False on failure.
*/
function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;
$data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
if ( $unfiltered )
return $data;
return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
}
/**
* Update metadata for an attachment.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID.
* @param array $data Attachment data.
* @return int
*/
function wp_update_attachment_metadata( $post_id, $data ) {
$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;
$data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
}
/**
* Retrieve the URL for an attachment.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID.
* @return string
*/
function wp_get_attachment_url( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;
$url = '';
if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
$url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
elseif ( false !== strpos($file, 'wp-content/uploads') )
$url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
else
$url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
}
}
if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recomended to rely upon this.
$url = get_the_guid( $post->ID );
if ( 'attachment' != $post->post_type || empty($url) )
return false;
return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
}
/**
* Retrieve thumbnail for an attachment.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID.
* @return mixed False on failure. Thumbnail file path on success.
*/
function wp_get_attachment_thumb_file( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;
if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
return false;
$file = get_attached_file( $post->ID );
if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
return false;
}
/**
* Retrieve URL for an attachment thumbnail.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID
* @return string|bool False on failure. Thumbnail URL on success.
*/
function wp_get_attachment_thumb_url( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;
if ( !$url = wp_get_attachment_url( $post->ID ) )
return false;
$sized = image_downsize( $post_id, 'thumbnail' );
if ( $sized )
return $sized[0];
if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
return false;
$url = str_replace(basename($url), basename($thumb), $url);
return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
}
/**
* Check if the attachment is an image.
*
* @since 2.1.0
*
* @param int $post_id Attachment ID
* @return bool
*/
function wp_attachment_is_image( $post_id = 0 ) {
$post_id = (int) $post_id;
if ( !$post =& get_post( $post_id ) )
return false;
if ( !$file = get_attached_file( $post->ID ) )
return false;
$ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
$image_exts = array('jpg', 'jpeg', 'gif', 'png');
if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
return true;
return false;
}
/**
* Retrieve the icon for a MIME type.
*
* @since 2.1.0
*
* @param string $mime MIME type
* @return string|bool
*/
function wp_mime_type_icon( $mime = 0 ) {
if ( !is_numeric($mime) )
$icon = wp_cache_get("mime_type_icon_$mime");
if ( empty($icon) ) {
$post_id = 0;
$post_mimes = array();
if ( is_numeric($mime) ) {
$mime = (int) $mime;
if ( $post =& get_post( $mime ) ) {
$post_id = (int) $post->ID;
$ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
if ( !empty($ext) ) {
$post_mimes[] = $ext;
if ( $ext_type = wp_ext2type( $ext ) )
$post_mimes[] = $ext_type;
}
$mime = $post->post_mime_type;
} else {
$mime = 0;
}
} else {
$post_mimes[] = $mime;
}
$icon_files = wp_cache_get('icon_files');
if ( !is_array($icon_files) ) {
$icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
$icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
$dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
$icon_files = array();
while ( $dirs ) {
$dir = array_shift($keys = array_keys($dirs));
$uri = array_shift($dirs);
if ( $dh = opendir($dir) ) {
while ( false !== $file = readdir($dh) ) {
$file = basename($file);
if ( substr($file, 0, 1) == '.' )
continue;
if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
if ( is_dir("$dir/$file") )
$dirs["$dir/$file"] = "$uri/$file";
continue;
}
$icon_files["$dir/$file"] = "$uri/$file";
}
closedir($dh);
}
}
wp_cache_set('icon_files', $icon_files, 600);
}
// Icon basename - extension = MIME wildcard
foreach ( $icon_files as $file => $uri )
$types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
if ( ! empty($mime) ) {
$post_mimes[] = substr($mime, 0, strpos($mime, '/'));
$post_mimes[] = substr($mime, strpos($mime, '/') + 1);
$post_mimes[] = str_replace('/', '_', $mime);
}
$matches = wp_match_mime_types(array_keys($types), $post_mimes);
$matches['default'] = array('default');
foreach ( $matches as $match => $wilds ) {
if ( isset($types[$wilds[0]])) {
$icon = $types[$wilds[0]];
if ( !is_numeric($mime) )
wp_cache_set("mime_type_icon_$mime", $icon);
break;
}
}
}
return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
}
/**
* Checked for changed slugs for published posts and save old slug.
*
* The function is used along with form POST data. It checks for the wp-old-slug
* POST field. Will only be concerned with published posts and the slug actually
* changing.
*
* If the slug was changed and not already part of the old slugs then it will be
* added to the post meta field ('_wp_old_slug') for storing old slugs for that
* post.
*
* The most logically usage of this function is redirecting changed posts, so
* that those that linked to an changed post will be redirected to the new post.
*
* @since 2.1.0
*
* @param int $post_id Post ID.
* @return int Same as $post_id
*/
function wp_check_for_changed_slugs($post_id) {
if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
return $post_id;
$post = &get_post($post_id);
// we're only concerned with published posts
if ( $post->post_status != 'publish' || $post->post_type != 'post' )
return $post_id;
// only bother if the slug has changed
if ( $post->post_name == $_POST['wp-old-slug'] )
return $post_id;
$old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
// if we haven't added this old slug before, add it now
if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
// if the new slug was used previously, delete it from the list
if ( in_array($post->post_name, $old_slugs) )
delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
return $post_id;
}
/**
* Retrieve the private post SQL based on capability.
*
* This function provides a standardized way to appropriately select on the
* post_status of posts/pages. The function will return a piece of SQL code that
* can be added to a WHERE clause; this SQL is constructed to allow all
* published posts, and all private posts to which the user has access.
*
* It also allows plugins that define their own post type to control the cap by
* using the hook 'pub_priv_sql_capability'. The plugin is expected to return
* the capability the user must have to read the private post type.
*
* @since 2.2.0
*
* @uses $user_ID
* @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
*
* @param string $post_type currently only supports 'post' or 'page'.
* @return string SQL code that can be added to a where clause.
*/
function get_private_posts_cap_sql($post_type) {
global $user_ID;
$cap = '';
// Private posts
if ($post_type == 'post') {
$cap = 'read_private_posts';
// Private pages
} elseif ($post_type == 'page') {
$cap = 'read_private_pages';
// Dunno what it is, maybe plugins have their own post type?
} else {
$cap = apply_filters('pub_priv_sql_capability', $cap);
if (empty($cap)) {
// We don't know what it is, filters don't change anything,
// so set the SQL up to return nothing.
return '1 = 0';
}
}
$sql = '(post_status = \'publish\'';
if (current_user_can($cap)) {
// Does the user have the capability to view private posts? Guess so.
$sql .= ' OR post_status = \'private\'';
} elseif (is_user_logged_in()) {
// Users can view their own private posts.
$sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
}
$sql .= ')';
return $sql;
}
/**
* Retrieve the date the the last post was published.
*
* The server timezone is the default and is the difference between GMT and
* server time. The 'blog' value is the date when the last post was posted. The
* 'gmt' is when the last post was posted in GMT formatted date.
*
* @since 0.71
*
* @uses $wpdb
* @uses $blog_id
* @uses apply_filters() Calls 'get_lastpostdate' filter
*
* @global mixed $cache_lastpostdate Stores the last post date
* @global mixed $pagenow The current page being viewed
*
* @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
* @return string The date of the last post.
*/
function get_lastpostdate($timezone = 'server') {
global $cache_lastpostdate, $wpdb, $blog_id;
$add_seconds_server = date('Z');
if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
switch(strtolower($timezone)) {
case 'gmt':
$lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
break;
case 'blog':
$lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
break;
case 'server':
$lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
break;
}
$cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
} else {
$lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
}
return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
}
/**
* Retrieve last post modified date depending on timezone.
*
* The server timezone is the default and is the difference between GMT and
* server time. The 'blog' value is just when the last post was modified. The
* 'gmt' is when the last post was modified in GMT time.
*
* @since 1.2.0
* @uses $wpdb
* @uses $blog_id
* @uses apply_filters() Calls 'get_lastpostmodified' filter
*
* @global mixed $cache_lastpostmodified Stores the date the last post was modified
*
* @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
* @return string The date the post was last modified.
*/
function get_lastpostmodified($timezone = 'server') {
global $cache_lastpostmodified, $wpdb, $blog_id;
$add_seconds_server = date('Z');
if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
switch(strtolower($timezone)) {
case 'gmt':
$lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
break;
case 'blog':
$lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
break;
case 'server':
$lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
break;
}
$lastpostdate = get_lastpostdate($timezone);
if ( $lastpostdate > $lastpostmodified ) {
$lastpostmodified = $lastpostdate;
}
$cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
} else {
$lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
}
return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
}
/**
* Updates posts in cache.
*
* @usedby update_page_cache() Aliased by this function.
*
* @package WordPress
* @subpackage Cache
* @since 1.5.1
*
* @param array $posts Array of post objects
*/
function update_post_cache(&$posts) {
if ( !$posts )
return;
foreach ( $posts as $post )
wp_cache_add($post->ID, $post, 'posts');
}
/**
* Will clean the post in the cache.
*
* Cleaning means delete from the cache of the post. Will call to clean the term
* object cache associated with the post ID.
*
* clean_post_cache() will call itself recursively for each child post.
*
* This function not run if $_wp_suspend_cache_invalidation is not empty. See
* wp_suspend_cache_invalidation().
*
* @package WordPress
* @subpackage Cache
* @since 2.0.0
*
* @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
*
* @param int $id The Post ID in the cache to clean
*/
function clean_post_cache($id) {
global $_wp_suspend_cache_invalidation, $wpdb;
if ( !empty($_wp_suspend_cache_invalidation) )
return;
$id = (int) $id;
wp_cache_delete($id, 'posts');
wp_cache_delete($id, 'post_meta');
clean_object_term_cache($id, 'post');
wp_cache_delete( 'wp_get_archives', 'general' );
do_action('clean_post_cache', $id);
if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
foreach( $children as $cid )
clean_post_cache( $cid );
}
}
/**
* Alias of update_post_cache().
*
* @see update_post_cache() Posts and pages are the same, alias is intentional
*
* @package WordPress
* @subpackage Cache
* @since 1.5.1
*
* @param array $pages list of page objects
*/
function update_page_cache(&$pages) {
update_post_cache($pages);
}
/**
* Will clean the page in the cache.
*
* Clean (read: delete) page from cache that matches $id. Will also clean cache
* associated with 'all_page_ids' and 'get_pages'.
*
* @package WordPress
* @subpackage Cache
* @since 2.0.0
*
* @uses do_action() Will call the 'clean_page_cache' hook action.
*
* @param int $id Page ID to clean
*/
function clean_page_cache($id) {
clean_post_cache($id);
wp_cache_delete( 'all_page_ids', 'posts' );
wp_cache_delete( 'get_pages', 'posts' );
do_action('clean_page_cache', $id);
}
/**
* Call major cache updating functions for list of Post objects.
*
* @package WordPress
* @subpackage Cache
* @since 1.5.0
*
* @uses $wpdb
* @uses update_post_cache()
* @uses update_object_term_cache()
* @uses update_postmeta_cache()
*
* @param array $posts Array of Post objects
*/
function update_post_caches(&$posts) {
// No point in doing all this work if we didn't match any posts.
if ( !$posts )
return;
update_post_cache($posts);
$post_ids = array();
for ($i = 0; $i < count($posts); $i++)
$post_ids[] = $posts[$i]->ID;
update_object_term_cache($post_ids, 'post');
update_postmeta_cache($post_ids);
}
/**
* Updates metadata cache for list of post IDs.
*
* Performs SQL query to retrieve the metadata for the post IDs and updates the
* metadata cache for the posts. Therefore, the functions, which call this
* function, do not need to perform SQL queries on their own.
*
* @package WordPress
* @subpackage Cache
* @since 2.1.0
*
* @uses $wpdb
*
* @param array $post_ids List of post IDs.
* @return bool|array Returns false if there is nothing to update or an array of metadata.
*/
function update_postmeta_cache($post_ids) {
global $wpdb;
if ( empty( $post_ids ) )
return false;
if ( !is_array($post_ids) ) {
$post_ids = preg_replace('|[^0-9,]|', '', $post_ids);
$post_ids = explode(',', $post_ids);
}
$post_ids = array_map('intval', $post_ids);
$ids = array();
foreach ( (array) $post_ids as $id ) {
if ( false === wp_cache_get($id, 'post_meta') )
$ids[] = $id;
}
if ( empty( $ids ) )
return false;
// Get post-meta info
$id_list = join(',', $ids);
$cache = array();
if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN ($id_list)", ARRAY_A) ) {
foreach ( (array) $meta_list as $metarow) {
$mpid = (int) $metarow['post_id'];
$mkey = $metarow['meta_key'];
$mval = $metarow['meta_value'];
// Force subkeys to be array type:
if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
$cache[$mpid] = array();
if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
$cache[$mpid][$mkey] = array();
// Add a value to the current pid/key:
$cache[$mpid][$mkey][] = $mval;
}
}
foreach ( (array) $ids as $id ) {
if ( ! isset($cache[$id]) )
$cache[$id] = array();
}
foreach ( (array) array_keys($cache) as $post)
wp_cache_set($post, $cache[$post], 'post_meta');
return $cache;
}
//
// Hooks
//
/**
* Hook for managing future post transitions to published.
*
* @since 2.3.0
* @access private
* @uses $wpdb
* @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
* @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
*
* @param string $new_status New post status
* @param string $old_status Previous post status
* @param object $post Object type containing the post information
*/
function _transition_post_status($new_status, $old_status, $post) {
global $wpdb;
if ( $old_status != 'publish' && $new_status == 'publish' ) {
// Reset GUID if transitioning to publish and it is empty
if ( '' == get_the_guid($post->ID) )
$wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
// do generic pings once per hour at most
if ( !wp_next_scheduled('do_generic_ping') )
wp_schedule_single_event(time() + 3600, 'do_generic_ping');
}
// Always clears the hook in case the post status bounced from future to draft.
wp_clear_scheduled_hook('publish_future_post', $post->ID);
}
/**
* Hook used to schedule publication for a post marked for the future.
*
* The $post properties used and must exist are 'ID' and 'post_date_gmt'.
*
* @since 2.3.0
* @access private
*
* @param int $deprecated Not Used. Can be set to null.
* @param object $post Object type containing the post information
*/
function _future_post_hook($deprecated = '', $post) {
wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
}
/**
* Hook to schedule pings and enclosures when a post is published.
*
* @since 2.3.0
* @access private
* @uses $wpdb
* @uses XMLRPC_REQUEST and APP_REQUEST constants.
* @uses do_action() Calls 'xmlprc_publish_post' on post ID if XMLRPC_REQUEST is defined.
* @uses do_action() Calls 'app_publish_post' on post ID if APP_REQUEST is defined.
*
* @param int $post_id The ID in the database table of the post being published
*/
function _publish_post_hook($post_id) {
global $wpdb;
if ( defined('XMLRPC_REQUEST') )
do_action('xmlrpc_publish_post', $post_id);
if ( defined('APP_REQUEST') )
do_action('app_publish_post', $post_id);
if ( defined('WP_IMPORTING') )
return;
$data = array( 'post_id' => $post_id, 'meta_value' => '1' );
if ( get_option('default_pingback_flag') )
$wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
$wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
wp_schedule_single_event(time(), 'do_pings');
}
/**
* Hook used to prevent page/post cache and rewrite rules from staying dirty.
*
* Does two things. If the post is a page and has a template then it will
* update/add that template to the meta. For both pages and posts, it will clean
* the post cache to make sure that the cache updates to the changes done
* recently. For pages, the rewrite rules of WordPress are flushed to allow for
* any changes.
*
* The $post parameter, only uses 'post_type' property and 'page_template'
* property.
*
* @since 2.3.0
* @access private
* @uses $wp_rewrite Flushes Rewrite Rules.
*
* @param int $post_id The ID in the database table for the $post
* @param object $post Object type containing the post information
*/
function _save_post_hook($post_id, $post) {
if ( $post->post_type == 'page' ) {
clean_page_cache($post_id);
// Avoid flushing rules for every post during import.
if ( !defined('WP_IMPORTING') ) {
global $wp_rewrite;
$wp_rewrite->flush_rules(false);
}
} else {
clean_post_cache($post_id);
}
}
/**
* Retrieve post ancestors and append to post ancestors property.
*
* Will only retrieve ancestors once, if property is already set, then nothing
* will be done. If there is not a parent post, or post ID and post parent ID
* are the same then nothing will be done.
*
* The parameter is passed by reference, so nothing needs to be returned. The
* property will be updated and can be referenced after the function is
* complete. The post parent will be an ancestor and the parent of the post
* parent will be an ancestor. There will only be two ancestors at the most.
*
* @since unknown
* @access private
* @uses $wpdb
*
* @param object $_post Post data.
* @return null When nothing needs to be done.
*/
function _get_post_ancestors(&$_post) {
global $wpdb;
if ( isset($_post->ancestors) )
return;
$_post->ancestors = array();
if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
return;
$id = $_post->ancestors[] = $_post->post_parent;
while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
if ( $id == $ancestor )
break;
$id = $_post->ancestors[] = $ancestor;
}
}
/**
* Determines which fields of posts are to be saved in revisions.
*
* Does two things. If passed a post *array*, it will return a post array ready
* to be insterted into the posts table as a post revision. Otherwise, returns
* an array whose keys are the post fields to be saved for post revisions.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
* @access private
* @uses apply_filters() Calls '_wp_post_revision_fields' on 'title', 'content' and 'excerpt' fields.
*
* @param array $post Optional a post array to be processed for insertion as a post revision.
* @param bool $autosave optional Is the revision an autosave?
* @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
*/
function _wp_post_revision_fields( $post = null, $autosave = false ) {
static $fields = false;
if ( !$fields ) {
// Allow these to be versioned
$fields = array(
'post_title' => __( 'Title' ),
'post_content' => __( 'Content' ),
'post_excerpt' => __( 'Excerpt' ),
);
// Runs only once
$fields = apply_filters( '_wp_post_revision_fields', $fields );
// WP uses these internally either in versioning or elsewhere - they cannot be versioned
foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
unset( $fields[$protect] );
}
if ( !is_array($post) )
return $fields;
$return = array();
foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
$return[$field] = $post[$field];
$return['post_parent'] = $post['ID'];
$return['post_status'] = 'inherit';
$return['post_type'] = 'revision';
$return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
$return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
$return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
return $return;
}
/**
* Saves an already existing post as a post revision.
*
* Typically used immediately prior to post updates.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses _wp_put_post_revision()
*
* @param int $post_id The ID of the post to save as a revision.
* @return mixed Null or 0 if error, new revision ID, if success.
*/
function wp_save_post_revision( $post_id ) {
// We do autosaves manually with wp_create_post_autosave()
if ( @constant( 'DOING_AUTOSAVE' ) )
return;
// WP_POST_REVISIONS = 0, false
if ( !constant('WP_POST_REVISIONS') )
return;
if ( !$post = get_post( $post_id, ARRAY_A ) )
return;
if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
return;
$return = _wp_put_post_revision( $post );
// WP_POST_REVISIONS = true (default), -1
if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
return $return;
// all revisions and (possibly) one autosave
$revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
// WP_POST_REVISIONS = (int) (# of autasaves to save)
$delete = count($revisions) - WP_POST_REVISIONS;
if ( $delete < 1 )
return $return;
$revisions = array_slice( $revisions, 0, $delete );
for ( $i = 0; isset($revisions[$i]); $i++ ) {
if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
continue;
wp_delete_post_revision( $revisions[$i]->ID );
}
return $return;
}
/**
* Retrieve the autosaved data of the specified post.
*
* Returns a post object containing the information that was autosaved for the
* specified post.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @param int $post_id The post ID.
* @return object|bool The autosaved data or false on failure or when no autosave exists.
*/
function wp_get_post_autosave( $post_id ) {
if ( !$post = get_post( $post_id ) )
return false;
$q = array(
'name' => "{$post->ID}-autosave",
'post_parent' => $post->ID,
'post_type' => 'revision',
'post_status' => 'inherit'
);
// Use WP_Query so that the result gets cached
$autosave_query = new WP_Query;
add_action( 'parse_query', '_wp_get_post_autosave_hack' );
$autosave = $autosave_query->query( $q );
remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
return $autosave[0];
return false;
}
/**
* Internally used to hack WP_Query into submission.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @param object $query WP_Query object
*/
function _wp_get_post_autosave_hack( $query ) {
$query->is_single = false;
}
/**
* Determines if the specified post is a revision.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @param int|object $post Post ID or post object.
* @return bool|int False if not a revision, ID of revision's parent otherwise.
*/
function wp_is_post_revision( $post ) {
if ( !$post = wp_get_post_revision( $post ) )
return false;
return (int) $post->post_parent;
}
/**
* Determines if the specified post is an autosave.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @param int|object $post Post ID or post object.
* @return bool|int False if not a revision, ID of autosave's parent otherwise
*/
function wp_is_post_autosave( $post ) {
if ( !$post = wp_get_post_revision( $post ) )
return false;
if ( "{$post->post_parent}-autosave" !== $post->post_name )
return false;
return (int) $post->post_parent;
}
/**
* Inserts post data into the posts table as a post revision.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses wp_insert_post()
*
* @param int|object|array $post Post ID, post object OR post array.
* @param bool $autosave Optional. Is the revision an autosave?
* @return mixed Null or 0 if error, new revision ID if success.
*/
function _wp_put_post_revision( $post = null, $autosave = false ) {
if ( is_object($post) )
$post = get_object_vars( $post );
elseif ( !is_array($post) )
$post = get_post($post, ARRAY_A);
if ( !$post || empty($post['ID']) )
return;
if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
$post = _wp_post_revision_fields( $post, $autosave );
$post = add_magic_quotes($post); //since data is from db
$revision_id = wp_insert_post( $post );
if ( is_wp_error($revision_id) )
return $revision_id;
if ( $revision_id )
do_action( '_wp_put_post_revision', $revision_id );
return $revision_id;
}
/**
* Gets a post revision.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses get_post()
*
* @param int|object $post Post ID or post object
* @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
* @param string $filter Optional sanitation filter. @see sanitize_post()
* @return mixed Null if error or post object if success
*/
function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
$null = null;
if ( !$revision = get_post( $post, OBJECT, $filter ) )
return $revision;
if ( 'revision' !== $revision->post_type )
return $null;
if ( $output == OBJECT ) {
return $revision;
} elseif ( $output == ARRAY_A ) {
$_revision = get_object_vars($revision);
return $_revision;
} elseif ( $output == ARRAY_N ) {
$_revision = array_values(get_object_vars($revision));
return $_revision;
}
return $revision;
}
/**
* Restores a post to the specified revision.
*
* Can restore a past revision using all fields of the post revision, or only selected fields.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses wp_get_post_revision()
* @uses wp_update_post()
* @uses do_action() Calls 'wp_restore_post_revision' on post ID and revision ID if wp_update_post()
* is successful.
*
* @param int|object $revision_id Revision ID or revision object.
* @param array $fields Optional. What fields to restore from. Defaults to all.
* @return mixed Null if error, false if no fields to restore, (int) post ID if success.
*/
function wp_restore_post_revision( $revision_id, $fields = null ) {
if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
return $revision;
if ( !is_array( $fields ) )
$fields = array_keys( _wp_post_revision_fields() );
$update = array();
foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
$update[$field] = $revision[$field];
if ( !$update )
return false;
$update['ID'] = $revision['post_parent'];
$update = add_magic_quotes( $update ); //since data is from db
$post_id = wp_update_post( $update );
if ( is_wp_error( $post_id ) )
return $post_id;
if ( $post_id )
do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
return $post_id;
}
/**
* Deletes a revision.
*
* Deletes the row from the posts table corresponding to the specified revision.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses wp_get_post_revision()
* @uses wp_delete_post()
*
* @param int|object $revision_id Revision ID or revision object.
* @param array $fields Optional. What fields to restore from. Defaults to all.
* @return mixed Null if error, false if no fields to restore, (int) post ID if success.
*/
function wp_delete_post_revision( $revision_id ) {
if ( !$revision = wp_get_post_revision( $revision_id ) )
return $revision;
$delete = wp_delete_post( $revision->ID );
if ( is_wp_error( $delete ) )
return $delete;
if ( $delete )
do_action( 'wp_delete_post_revision', $revision->ID, $revision );
return $delete;
}
/**
* Returns all revisions of specified post.
*
* @package WordPress
* @subpackage Post_Revisions
* @since 2.6.0
*
* @uses get_children()
*
* @param int|object $post_id Post ID or post object
* @return array empty if no revisions
*/
function wp_get_post_revisions( $post_id = 0, $args = null ) {
if ( !constant('WP_POST_REVISIONS') )
return array();
if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
return array();
$defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
$args = wp_parse_args( $args, $defaults );
$args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
if ( !$revisions = get_children( $args ) )
return array();
return $revisions;
}
function _set_preview($post) {
if ( ! is_object($post) )
return $post;
$preview = wp_get_post_autosave($post->ID);
if ( ! is_object($preview) )
return $post;
$preview = sanitize_post($preview);
$post->post_content = $preview->post_content;
$post->post_title = $preview->post_title;
$post->post_excerpt = $preview->post_excerpt;
return $post;
}
function _show_post_preview() {
if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
$id = (int) $_GET['preview_id'];
if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
wp_die( __('You do not have permission to preview drafts.') );
add_filter('the_preview', '_set_preview');
}
}
larscapo/wp-includes/script-loader.php 0000644 0041054 0041055 00000074031 11225447104 020615 0 ustar lacunaus lacunaus add_data( 'script-handle', 'group', 1 ); queues the script for the footer
*
* @since 2.6.0
*
* @param object $scripts WP_Scripts object.
*/
function wp_default_scripts( &$scripts ) {
if ( !$guessurl = site_url() )
$guessurl = wp_guess_url();
$scripts->base_url = $guessurl;
$scripts->content_url = defined('WP_CONTENT_URL')? WP_CONTENT_URL : '';
$scripts->default_version = get_bloginfo( 'version' );
$scripts->default_dirs = array('/wp-admin/js/', '/wp-includes/js/');
$suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '.dev' : '';
$scripts->add( 'utils', "/wp-admin/js/utils$suffix.js", false, '20090102' );
$scripts->add( 'common', "/wp-admin/js/common$suffix.js", array('jquery', 'hoverIntent', 'utils'), '20090609' );
$scripts->add_data( 'common', 'group', 1 );
$scripts->localize( 'common', 'commonL10n', array(
'warnDelete' => __("You are about to delete the selected items.\n 'Cancel' to stop, 'OK' to delete."),
'l10n_print_after' => 'try{convertEntities(commonL10n);}catch(e){};'
) );
$scripts->add( 'sack', "/wp-includes/js/tw-sack$suffix.js", false, '1.6.1' );
$scripts->add_data( 'sack', 'group', 1 );
$scripts->add( 'quicktags', "/wp-includes/js/quicktags$suffix.js", false, '20090307' );
$scripts->localize( 'quicktags', 'quicktagsL10n', array(
'quickLinks' => __('(Quick Links)'),
'wordLookup' => __('Enter a word to look up:'),
'dictionaryLookup' => esc_attr(__('Dictionary lookup')),
'lookup' => esc_attr(__('lookup')),
'closeAllOpenTags' => esc_attr(__('Close all open tags')),
'closeTags' => esc_attr(__('close tags')),
'enterURL' => __('Enter the URL'),
'enterImageURL' => __('Enter the URL of the image'),
'enterImageDescription' => __('Enter a description of the image'),
'l10n_print_after' => 'try{convertEntities(quicktagsL10n);}catch(e){};'
) );
$scripts->add( 'colorpicker', "/wp-includes/js/colorpicker$suffix.js", array('prototype'), '3517m' );
$scripts->add( 'editor', "/wp-admin/js/editor$suffix.js", false, '20090503' );
$scripts->add( 'prototype', '/wp-includes/js/prototype.js', false, '1.6');
$scripts->add( 'wp-ajax-response', "/wp-includes/js/wp-ajax-response$suffix.js", array('jquery'), '20090128' );
$scripts->add_data( 'wp-ajax-response', 'group', 1 );
$scripts->localize( 'wp-ajax-response', 'wpAjax', array(
'noPerm' => __('You do not have permission to do that.'),
'broken' => __('An unidentified error has occurred.'),
'l10n_print_after' => 'try{convertEntities(wpAjax);}catch(e){};'
) );
$scripts->add( 'autosave', "/wp-includes/js/autosave$suffix.js", array('schedule', 'wp-ajax-response'), '20090526' );
$scripts->add_data( 'autosave', 'group', 1 );
$scripts->add( 'wp-lists', "/wp-includes/js/wp-lists$suffix.js", array('wp-ajax-response'), '20090504' );
$scripts->add_data( 'wp-lists', 'group', 1 );
$scripts->localize( 'wp-lists', 'wpListL10n', array(
'url' => admin_url('admin-ajax.php')
) );
$scripts->add( 'scriptaculous-root', '/wp-includes/js/scriptaculous/wp-scriptaculous.js', array('prototype'), '1.8.0');
$scripts->add( 'scriptaculous-builder', '/wp-includes/js/scriptaculous/builder.js', array('scriptaculous-root'), '1.8.0');
$scripts->add( 'scriptaculous-dragdrop', '/wp-includes/js/scriptaculous/dragdrop.js', array('scriptaculous-builder', 'scriptaculous-effects'), '1.8.0');
$scripts->add( 'scriptaculous-effects', '/wp-includes/js/scriptaculous/effects.js', array('scriptaculous-root'), '1.8.0');
$scripts->add( 'scriptaculous-slider', '/wp-includes/js/scriptaculous/slider.js', array('scriptaculous-effects'), '1.8.0');
$scripts->add( 'scriptaculous-sound', '/wp-includes/js/scriptaculous/sound.js', array( 'scriptaculous-root' ), '1.8.0' );
$scripts->add( 'scriptaculous-controls', '/wp-includes/js/scriptaculous/controls.js', array('scriptaculous-root'), '1.8.0');
$scripts->add( 'scriptaculous', '', array('scriptaculous-dragdrop', 'scriptaculous-slider', 'scriptaculous-controls'), '1.8.0');
$scripts->add( 'cropper', '/wp-includes/js/crop/cropper.js', array('scriptaculous-dragdrop'), '20070118');
$scripts->add( 'jquery', '/wp-includes/js/jquery/jquery.js', false, '1.3.2');
$scripts->add( 'jquery-ui-core', '/wp-includes/js/jquery/ui.core.js', array('jquery'), '1.7.1' );
$scripts->add_data( 'jquery-ui-core', 'group', 1 );
$scripts->add( 'jquery-ui-tabs', '/wp-includes/js/jquery/ui.tabs.js', array('jquery-ui-core'), '1.7.1' );
$scripts->add_data( 'jquery-ui-tabs', 'group', 1 );
$scripts->add( 'jquery-ui-sortable', '/wp-includes/js/jquery/ui.sortable.js', array('jquery-ui-core'), '1.7.1' );
$scripts->add_data( 'jquery-ui-sortable', 'group', 1 );
$scripts->add( 'jquery-ui-draggable', '/wp-includes/js/jquery/ui.draggable.js', array('jquery-ui-core'), '1.7.1' );
$scripts->add_data( 'jquery-ui-draggable', 'group', 1 );
$scripts->add( 'jquery-ui-droppable', '/wp-includes/js/jquery/ui.droppable.js', array('jquery-ui-core'), '1.7.1' );
$scripts->add_data( 'jquery-ui-droppable', 'group', 1 );
$scripts->add( 'jquery-ui-selectable', '/wp-includes/js/jquery/ui.selectable.js', array('jquery-ui-core'), '1.7.1' );
$scripts->add_data( 'jquery-ui-selectable', 'group', 1 );
$scripts->add( 'jquery-ui-resizable', '/wp-includes/js/jquery/ui.resizable.js', array('jquery-ui-core'), '1.7.1' );
$scripts->add_data( 'jquery-ui-resizable', 'group', 1 );
$scripts->add( 'jquery-ui-dialog', '/wp-includes/js/jquery/ui.dialog.js', array('jquery-ui-resizable', 'jquery-ui-draggable'), '1.7.1' );
$scripts->add_data( 'jquery-ui-dialog', 'group', 1 );
$scripts->add( 'jquery-form', "/wp-includes/js/jquery/jquery.form$suffix.js", array('jquery'), '2.02m');
$scripts->add_data( 'jquery-form', 'group', 1 );
$scripts->add( 'jquery-color', "/wp-includes/js/jquery/jquery.color$suffix.js", array('jquery'), '2.0-4561m');
$scripts->add_data( 'jquery-color', 'group', 1 );
$scripts->add( 'interface', '/wp-includes/js/jquery/interface.js', array('jquery'), '1.2' );
$scripts->add( 'suggest', "/wp-includes/js/jquery/suggest$suffix.js", array('jquery'), '1.1-20090125');
$scripts->add_data( 'suggest', 'group', 1 );
$scripts->add( 'schedule', '/wp-includes/js/jquery/jquery.schedule.js', array('jquery'), '20m');
$scripts->add_data( 'schedule', 'group', 1 );
$scripts->add( 'jquery-hotkeys', "/wp-includes/js/jquery/jquery.hotkeys$suffix.js", array('jquery'), '0.0.2m' );
$scripts->add_data( 'jquery-hotkeys', 'group', 1 );
$scripts->add( 'jquery-table-hotkeys', "/wp-includes/js/jquery/jquery.table-hotkeys$suffix.js", array('jquery', 'jquery-hotkeys'), '20090102' );
$scripts->add_data( 'jquery-table-hotkeys', 'group', 1 );
$scripts->add( 'thickbox', "/wp-includes/js/thickbox/thickbox.js", array('jquery'), '3.1-20090123');
$scripts->add_data( 'thickbox', 'group', 1 );
$scripts->add( 'jcrop', "/wp-includes/js/jcrop/jquery.Jcrop$suffix.js", array('jquery'), '0.9.8');
$scripts->add( 'swfobject', "/wp-includes/js/swfobject.js", false, '2.1');
$scripts->add( 'swfupload', '/wp-includes/js/swfupload/swfupload.js', false, '2201');
$scripts->add( 'swfupload-swfobject', '/wp-includes/js/swfupload/plugins/swfupload.swfobject.js', array('swfupload', 'swfobject'), '2201');
$scripts->add( 'swfupload-queue', '/wp-includes/js/swfupload/plugins/swfupload.queue.js', array('swfupload'), '2201');
$scripts->add( 'swfupload-speed', '/wp-includes/js/swfupload/plugins/swfupload.speed.js', array('swfupload'), '2201');
if ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) {
// queue all SWFUpload scripts that are used by default
$scripts->add( 'swfupload-all', false, array('swfupload', 'swfupload-swfobject', 'swfupload-queue'), '2201');
} else {
$scripts->add( 'swfupload-all', '/wp-includes/js/swfupload/swfupload-all.js', array(), '2201');
}
$scripts->add( 'swfupload-handlers', "/wp-includes/js/swfupload/handlers$suffix.js", array('swfupload-all', 'jquery'), '2201-20090515');
// these error messages came from the sample swfupload js, they might need changing.
$scripts->localize( 'swfupload-handlers', 'swfuploadL10n', array(
'queue_limit_exceeded' => __('You have attempted to queue too many files.'),
'file_exceeds_size_limit' => sprintf(__('This file is too big. Your php.ini upload_max_filesize is %s.'), @ini_get('upload_max_filesize')),
'zero_byte_file' => __('This file is empty. Please try another.'),
'invalid_filetype' => __('This file type is not allowed. Please try another.'),
'default_error' => __('An error occurred in the upload. Please try again later.'),
'missing_upload_url' => __('There was a configuration error. Please contact the server administrator.'),
'upload_limit_exceeded' => __('You may only upload 1 file.'),
'http_error' => __('HTTP error.'),
'upload_failed' => __('Upload failed.'),
'io_error' => __('IO error.'),
'security_error' => __('Security error.'),
'file_cancelled' => __('File cancelled.'),
'upload_stopped' => __('Upload stopped.'),
'dismiss' => __('Dismiss'),
'crunching' => __('Crunching…'),
'deleted' => __('Deleted'),
'l10n_print_after' => 'try{convertEntities(swfuploadL10n);}catch(e){};'
) );
$scripts->add( 'comment-reply', "/wp-includes/js/comment-reply$suffix.js", false, '20090102');
if ( is_admin() ) {
$scripts->add( 'ajaxcat', "/wp-admin/js/cat$suffix.js", array( 'wp-lists' ), '20090102' );
$scripts->add_data( 'ajaxcat', 'group', 1 );
$scripts->localize( 'ajaxcat', 'catL10n', array(
'add' => esc_attr(__('Add')),
'how' => __('Separate multiple categories with commas.'),
'l10n_print_after' => 'try{convertEntities(catL10n);}catch(e){};'
) );
$scripts->add( 'admin-categories', "/wp-admin/js/categories$suffix.js", array('wp-lists'), '20090207' );
$scripts->add_data( 'admin-categories', 'group', 1 );
$scripts->add( 'admin-tags', "/wp-admin/js/tags$suffix.js", array('wp-lists'), '20090211' );
$scripts->add_data( 'admin-tags', 'group', 1 );
$scripts->add( 'admin-custom-fields', "/wp-admin/js/custom-fields$suffix.js", array('wp-lists'), '20090106' );
$scripts->add_data( 'admin-custom-fields', 'group', 1 );
$scripts->add( 'password-strength-meter', "/wp-admin/js/password-strength-meter$suffix.js", array('jquery'), '20090102' );
$scripts->add_data( 'password-strength-meter', 'group', 1 );
$scripts->localize( 'password-strength-meter', 'pwsL10n', array(
'empty' => __('Strength indicator'),
'short' => __('Very weak'),
'bad' => __('Weak'),
/* translators: password strength */
'good' => _x('Medium', 'password strength'),
'strong' => __('Strong'),
'l10n_print_after' => 'try{convertEntities(pwsL10n);}catch(e){};'
) );
$scripts->add( 'user-profile', "/wp-admin/js/user-profile$suffix.js", array('jquery'), '20090514' );
$scripts->add_data( 'user-profile', 'group', 1 );
$scripts->add( 'admin-comments', "/wp-admin/js/edit-comments$suffix.js", array('wp-lists', 'jquery-ui-resizable', 'quicktags'), '20090627' );
$scripts->add_data( 'admin-comments', 'group', 1 );
$scripts->localize( 'admin-comments', 'adminCommentsL10n', array(
'hotkeys_highlight_first' => isset($_GET['hotkeys_highlight_first']),
'hotkeys_highlight_last' => isset($_GET['hotkeys_highlight_last'])
) );
$scripts->add( 'xfn', "/wp-admin/js/xfn$suffix.js", false, '3517m' );
$scripts->add( 'postbox', "/wp-admin/js/postbox$suffix.js", array('jquery-ui-sortable'), '20090618' );
$scripts->add_data( 'postbox', 'group', 1 );
$scripts->localize( 'postbox', 'postboxL10n', array(
'requestFile' => admin_url('admin-ajax.php')
) );
$scripts->add( 'slug', "/wp-admin/js/slug$suffix.js", array('jquery'), '20090207' );
$scripts->add_data( 'slug', 'group', 1 );
$scripts->localize( 'slug', 'slugL10n', array(
'requestFile' => admin_url('admin-ajax.php'),
'save' => __('Save'),
'cancel' => __('Cancel'),
'l10n_print_after' => 'try{convertEntities(slugL10n);}catch(e){};'
) );
$scripts->add( 'post', "/wp-admin/js/post$suffix.js", array('suggest', 'wp-lists', 'postbox', 'slug'), '20090624' );
$scripts->add_data( 'post', 'group', 1 );
$scripts->localize( 'post', 'postL10n', array(
'tagsUsed' => __('Tags used on this post:'),
'add' => esc_attr(__('Add')),
'addTag' => esc_attr(__('Add new tag')),
'separate' => __('Separate tags with commas'),
'cancel' => __('Cancel'),
'edit' => __('Edit'),
'publishOn' => __('Publish on:'),
'publishOnFuture' => __('Schedule for:'),
'publishOnPast' => __('Published on:'),
'showcomm' => __('Show more comments'),
'endcomm' => __('No more comments found.'),
'publish' => __('Publish'),
'schedule' => __('Schedule'),
'update' => __('Update Post'),
'savePending' => __('Save as Pending'),
'saveDraft' => __('Save Draft'),
'private' => __('Private'),
'public' => __('Public'),
'publicSticky' => __('Public, Sticky'),
'password' => __('Password Protected'),
'privatelyPublished' => __('Privately Published'),
'published' => __('Published'),
'l10n_print_after' => 'try{convertEntities(postL10n);}catch(e){};'
) );
$scripts->add( 'page', "/wp-admin/js/page$suffix.js", array('jquery', 'slug', 'wp-lists', 'postbox'), '20090526' );
$scripts->add_data( 'page', 'group', 1 );
$scripts->localize( 'page', 'postL10n', array(
'cancel' => __('Cancel'),
'edit' => __('Edit'),
'publishOn' => __('Publish on:'),
'publishOnFuture' => __('Schedule for:'),
'publishOnPast' => __('Published on:'),
'showcomm' => __('Show more comments'),
'endcomm' => __('No more comments found.'),
'publish' => __('Publish'),
'schedule' => __('Schedule'),
'update' => __('Update Page'),
'savePending' => __('Save as Pending'),
'saveDraft' => __('Save Draft'),
'private' => __('Private'),
'public' => __('Public'),
'password' => __('Password Protected'),
'privatelyPublished' => __('Privately Published'),
'published' => __('Published'),
'l10n_print_after' => 'try{convertEntities(postL10n);}catch(e){};'
) );
$scripts->add( 'link', "/wp-admin/js/link$suffix.js", array('wp-lists', 'postbox'), '20090506' );
$scripts->add_data( 'link', 'group', 1 );
$scripts->add( 'comment', "/wp-admin/js/comment$suffix.js", array('jquery'), '20090102' );
$scripts->add_data( 'comment', 'group', 1 );
$scripts->localize( 'comment', 'commentL10n', array(
'cancel' => __('Cancel'),
'edit' => __('Edit'),
'submittedOn' => __('Submitted on:'),
'l10n_print_after' => 'try{convertEntities(commentL10n);}catch(e){};'
) );
$scripts->add( 'admin-gallery', "/wp-admin/js/gallery$suffix.js", array( 'jquery-ui-sortable' ), '20090516' );
$scripts->add( 'media-upload', "/wp-admin/js/media-upload$suffix.js", array( 'thickbox' ), '20090114' );
$scripts->add_data( 'media-upload', 'group', 1 );
$scripts->add( 'admin-widgets', "/wp-admin/js/widgets$suffix.js", array( 'jquery-ui-sortable', 'jquery-ui-draggable', 'jquery-ui-droppable' ), '20090601' );
$scripts->add_data( 'admin-widgets', 'group', 1 );
$scripts->add( 'word-count', "/wp-admin/js/word-count$suffix.js", array( 'jquery' ), '20090422' );
$scripts->add_data( 'word-count', 'group', 1 );
$scripts->localize( 'word-count', 'wordCountL10n', array(
'count' => __('Word count: %d'),
'l10n_print_after' => 'try{convertEntities(wordCountL10n);}catch(e){};'
));
$scripts->add( 'wp-gears', "/wp-admin/js/wp-gears$suffix.js", false, '20090102' );
$scripts->localize( 'wp-gears', 'wpGearsL10n', array(
'updateCompleted' => __('Update completed.'),
'error' => __('Error:'),
'l10n_print_after' => 'try{convertEntities(wpGearsL10n);}catch(e){};'
));
$scripts->add( 'theme-preview', "/wp-admin/js/theme-preview$suffix.js", array( 'thickbox', 'jquery' ), '20090319' );
$scripts->add_data( 'theme-preview', 'group', 1 );
$scripts->add( 'inline-edit-post', "/wp-admin/js/inline-edit-post$suffix.js", array( 'jquery-form', 'suggest' ), '20090125' );
$scripts->add_data( 'inline-edit-post', 'group', 1 );
$scripts->localize( 'inline-edit-post', 'inlineEditL10n', array(
'error' => __('Error while saving the changes.'),
'ntdeltitle' => __('Remove From Bulk Edit'),
'notitle' => __('(no title)'),
'l10n_print_after' => 'try{convertEntities(inlineEditL10n);}catch(e){};'
) );
$scripts->add( 'inline-edit-tax', "/wp-admin/js/inline-edit-tax$suffix.js", array( 'jquery-form' ), '20090211' );
$scripts->add_data( 'inline-edit-tax', 'group', 1 );
$scripts->localize( 'inline-edit-tax', 'inlineEditL10n', array(
'error' => __('Error while saving the changes.'),
'l10n_print_after' => 'try{convertEntities(inlineEditL10n);}catch(e){};'
) );
$scripts->add( 'plugin-install', "/wp-admin/js/plugin-install$suffix.js", array( 'jquery' ), '20090520' );
$scripts->add_data( 'plugin-install', 'group', 1 );
$scripts->localize( 'plugin-install', 'plugininstallL10n', array(
'plugin_information' => __('Plugin Information:'),
'l10n_print_after' => 'try{convertEntities(plugininstallL10n);}catch(e){};'
) );
$scripts->add( 'farbtastic', '/wp-admin/js/farbtastic.js', array('jquery'), '1.2' );
$scripts->add( 'dashboard', "/wp-admin/js/dashboard$suffix.js", array( 'jquery', 'admin-comments', 'postbox' ), '20090618' );
$scripts->add_data( 'dashboard', 'group', 1 );
$scripts->add( 'hoverIntent', "/wp-includes/js/hoverIntent$suffix.js", array('jquery'), '20090102' );
$scripts->add_data( 'hoverIntent', 'group', 1 );
$scripts->add( 'media', "/wp-admin/js/media$suffix.js", array( 'jquery-ui-draggable' ), '20090415' );
$scripts->add_data( 'media', 'group', 1 );
$scripts->add( 'codepress', '/wp-includes/js/codepress/codepress.js', false, '0.9.6' );
$scripts->add_data( 'codepress', 'group', 1 );
}
}
/**
* Assign default styles to $styles object.
*
* Nothing is returned, because the $styles parameter is passed by reference.
* Meaning that whatever object is passed will be updated without having to
* reassign the variable that was passed back to the same value. This saves
* memory.
*
* Adding default styles is not the only task, it also assigns the base_url
* property, the default version, and text direction for the object.
*
* @since 2.6.0
*
* @param object $styles
*/
function wp_default_styles( &$styles ) {
// This checks to see if site_url() returns something and if it does not
// then it assigns $guess_url to wp_guess_url(). Strange format, but it works.
if ( ! $guessurl = site_url() )
$guessurl = wp_guess_url();
$styles->base_url = $guessurl;
$styles->content_url = defined('WP_CONTENT_URL')? WP_CONTENT_URL : '';
$styles->default_version = get_bloginfo( 'version' );
$styles->text_direction = 'rtl' == get_bloginfo( 'text_direction' ) ? 'rtl' : 'ltr';
$styles->default_dirs = array('/wp-admin/');
$rtl_styles = array( 'global', 'colors', 'dashboard', 'ie', 'install', 'login', 'media', 'theme-editor', 'upload', 'widgets', 'press-this', 'plugin-install', 'farbtastic' );
// all colors stylesheets need to have the same query strings (cache manifest compat)
$colors_version = '20090625';
$styles->add( 'wp-admin', '/wp-admin/wp-admin.css', array(), '20090625' );
$styles->add_data( 'wp-admin', 'rtl', '/wp-admin/rtl.css' );
$styles->add( 'ie', '/wp-admin/css/ie.css', array(), '20090630' );
$styles->add_data( 'ie', 'conditional', 'lte IE 7' );
// Register "meta" stylesheet for admin colors. All colors-* style sheets should have the same version string.
$styles->add( 'colors', true, array(), $colors_version );
// do not refer to these directly, the right one is queued by the above "meta" colors handle
$styles->add( 'colors-fresh', '/wp-admin/css/colors-fresh.css', array(), $colors_version);
$styles->add_data( 'colors-fresh', 'rtl', true );
$styles->add( 'colors-classic', '/wp-admin/css/colors-classic.css', array(), $colors_version);
$styles->add_data( 'colors-classic', 'rtl', true );
$styles->add( 'global', '/wp-admin/css/global.css', array(), '20090630' );
$styles->add( 'media', '/wp-admin/css/media.css', array(), '20090516' );
$styles->add( 'widgets', '/wp-admin/css/widgets.css', array(), '20090603' );
$styles->add( 'dashboard', '/wp-admin/css/dashboard.css', array(), '20090514' );
$styles->add( 'install', '/wp-admin/css/install.css', array(), '20090514' );
$styles->add( 'theme-editor', '/wp-admin/css/theme-editor.css', array(), '20090625' );
$styles->add( 'press-this', '/wp-admin/css/press-this.css', array(), '20090514' );
$styles->add( 'thickbox', '/wp-includes/js/thickbox/thickbox.css', array(), '20090514' );
$styles->add( 'login', '/wp-admin/css/login.css', array(), '20090514' );
$styles->add( 'plugin-install', '/wp-admin/css/plugin-install.css', array(), '20090514' );
$styles->add( 'theme-install', '/wp-admin/css/theme-install.css', array(), '20090610' );
$styles->add( 'farbtastic', '/wp-admin/css/farbtastic.css', array(), '1.2' );
$styles->add( 'jcrop', '/wp-includes/js/jcrop/jquery.Jcrop.css', array(), '0.9.8' );
foreach ( $rtl_styles as $rtl_style )
$styles->add_data( $rtl_style, 'rtl', true );
}
/**
* Reorder JavaScript scripts array to place prototype before jQuery.
*
* @since 2.3.1
*
* @param array $js_array JavaScript scripst array
* @return array Reordered array, if needed.
*/
function wp_prototype_before_jquery( $js_array ) {
if ( false === $jquery = array_search( 'jquery', $js_array, true ) )
return $js_array;
if ( false === $prototype = array_search( 'prototype', $js_array, true ) )
return $js_array;
if ( $prototype < $jquery )
return $js_array;
unset($js_array[$prototype]);
array_splice( $js_array, $jquery, 0, 'prototype' );
return $js_array;
}
/**
* Load localized script just in time for MCE.
*
* These localizations require information that may not be loaded even by init.
*
* @since 2.5.0
*/
function wp_just_in_time_script_localization() {
wp_localize_script( 'autosave', 'autosaveL10n', array(
'autosaveInterval' => AUTOSAVE_INTERVAL,
'previewPageText' => __('Preview this Page'),
'previewPostText' => __('Preview this Post'),
'requestFile' => admin_url('admin-ajax.php'),
'savingText' => __('Saving Draft…'),
'saveAlert' => __('The changes you made will be lost if you navigate away from this page.'),
'l10n_print_after' => 'try{convertEntities(autosaveL10n);}catch(e){};'
) );
}
/**
* Administration Panel CSS for changing the styles.
*
* If installing the 'wp-admin/' directory will be replaced with './'.
*
* The $_wp_admin_css_colors global manages the Administration Panels CSS
* stylesheet that is loaded. The option that is set is 'admin_color' and is the
* color and key for the array. The value for the color key is an object with
* a 'url' parameter that has the URL path to the CSS file.
*
* The query from $src parameter will be appended to the URL that is given from
* the $_wp_admin_css_colors array value URL.
*
* @since 2.6.0
* @uses $_wp_admin_css_colors
*
* @param string $src Source URL.
* @param string $handle Either 'colors' or 'colors-rtl'.
* @return string URL path to CSS stylesheet for Administration Panels.
*/
function wp_style_loader_src( $src, $handle ) {
if ( defined('WP_INSTALLING') )
return preg_replace( '#^wp-admin/#', './', $src );
if ( 'colors' == $handle || 'colors-rtl' == $handle ) {
global $_wp_admin_css_colors;
$color = get_user_option('admin_color');
if ( empty($color) || !isset($_wp_admin_css_colors[$color]) )
$color = 'fresh';
$color = $_wp_admin_css_colors[$color];
$parsed = parse_url( $src );
$url = $color->url;
if ( isset($parsed['query']) && $parsed['query'] ) {
wp_parse_str( $parsed['query'], $qv );
$url = add_query_arg( $qv, $url );
}
return $url;
}
return $src;
}
/**
* Prints the script queue in the HTML head on admin pages.
*
* Postpones the scripts that were queued for the footer.
* print_footer_scripts() is called in the footer to print these scripts.
*
* @since 2.8
* @see wp_print_scripts()
*/
function print_head_scripts() {
global $wp_scripts, $concatenate_scripts;
if ( ! did_action('wp_print_scripts') )
do_action('wp_print_scripts');
if ( !is_a($wp_scripts, 'WP_Scripts') )
$wp_scripts = new WP_Scripts();
script_concat_settings();
$wp_scripts->do_concat = $concatenate_scripts;
$wp_scripts->do_head_items();
if ( apply_filters('print_head_scripts', true) )
_print_scripts();
$wp_scripts->reset();
return $wp_scripts->done;
}
/**
* Prints the scripts that were queued for the footer on admin pages.
*
* @since 2.8
*/
function print_footer_scripts() {
global $wp_scripts, $concatenate_scripts;
if ( ! did_action('wp_print_footer_scripts') )
do_action('wp_print_footer_scripts');
if ( !is_a($wp_scripts, 'WP_Scripts') )
return array(); // No need to run if not instantiated.
script_concat_settings();
$wp_scripts->do_concat = $concatenate_scripts;
$wp_scripts->do_footer_items();
if ( apply_filters('print_footer_scripts', true) )
_print_scripts();
$wp_scripts->reset();
return $wp_scripts->done;
}
function _print_scripts() {
global $wp_scripts, $compress_scripts;
$zip = $compress_scripts ? 1 : 0;
if ( $zip && defined('ENFORCE_GZIP') && ENFORCE_GZIP )
$zip = 'gzip';
if ( !empty($wp_scripts->concat) ) {
if ( !empty($wp_scripts->print_code) ) {
echo "\n";
}
$ver = md5("$wp_scripts->concat_version");
$src = $wp_scripts->base_url . "/wp-admin/load-scripts.php?c={$zip}&load=" . trim($wp_scripts->concat, ', ') . "&ver=$ver";
echo "\n";
}
if ( !empty($wp_scripts->print_html) )
echo $wp_scripts->print_html;
}
/**
* Prints the script queue in the HTML head on the front end.
*
* Postpones the scripts that were queued for the footer.
* wp_print_footer_scripts() is called in the footer to print these scripts.
*
* @since 2.8
*/
function wp_print_head_scripts() {
if ( ! did_action('wp_print_scripts') )
do_action('wp_print_scripts');
global $wp_scripts;
if ( !is_a($wp_scripts, 'WP_Scripts') )
return array(); // no need to run if nothing is queued
return print_head_scripts();
}
/**
* Prints the scripts that were queued for the footer on the front end.
*
* @since 2.8
*/
function wp_print_footer_scripts() {
return print_footer_scripts();
}
/**
* Wrapper for do_action('wp_enqueue_scripts')
*
* Allows plugins to queue scripts for the front end using wp_enqueue_script().
* Runs first in wp_head() where all is_home(), is_page(), etc. functions are available.
*
* @since 2.8
*/
function wp_enqueue_scripts() {
do_action('wp_enqueue_scripts');
}
function print_admin_styles() {
global $wp_styles, $concatenate_scripts, $compress_css;
if ( !is_a($wp_styles, 'WP_Styles') )
$wp_styles = new WP_Styles();
script_concat_settings();
$wp_styles->do_concat = $concatenate_scripts;
$zip = $compress_css ? 1 : 0;
if ( $zip && defined('ENFORCE_GZIP') && ENFORCE_GZIP )
$zip = 'gzip';
$wp_styles->do_items(false);
if ( apply_filters('print_admin_styles', true) ) {
if ( !empty($wp_styles->concat) ) {
$dir = $wp_styles->text_direction;
$ver = md5("$wp_styles->concat_version{$dir}");
$href = $wp_styles->base_url . "/wp-admin/load-styles.php?c={$zip}&dir={$dir}&load=" . trim($wp_styles->concat, ', ') . "&ver=$ver";
echo "\n";
}
if ( !empty($wp_styles->print_html) )
echo $wp_styles->print_html;
}
$wp_styles->do_concat = false;
$wp_styles->concat = $wp_styles->concat_version = $wp_styles->print_html = '';
return $wp_styles->done;
}
function script_concat_settings() {
global $concatenate_scripts, $compress_scripts, $compress_css;
$compressed_output = ( ini_get('zlib.output_compression') || 'ob_gzhandler' == ini_get('output_handler') );
if ( ! isset($concatenate_scripts) ) {
$concatenate_scripts = defined('CONCATENATE_SCRIPTS') ? CONCATENATE_SCRIPTS : true;
if ( ! is_admin() || ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) )
$concatenate_scripts = false;
}
if ( ! isset($compress_scripts) ) {
$compress_scripts = defined('COMPRESS_SCRIPTS') ? COMPRESS_SCRIPTS : true;
if ( $compress_scripts && ( ! get_site_option('can_compress_scripts') || $compressed_output ) )
$compress_scripts = false;
}
if ( ! isset($compress_css) ) {
$compress_css = defined('COMPRESS_CSS') ? COMPRESS_CSS : true;
if ( $compress_css && ( ! get_site_option('can_compress_scripts') || $compressed_output ) )
$compress_css = false;
}
}
add_action( 'wp_default_scripts', 'wp_default_scripts' );
add_filter( 'wp_print_scripts', 'wp_just_in_time_script_localization' );
add_filter( 'print_scripts_array', 'wp_prototype_before_jquery' );
add_action( 'wp_default_styles', 'wp_default_styles' );
add_filter( 'style_loader_src', 'wp_style_loader_src', 10, 2 );
larscapo/wp-includes/functions.wp-styles.php 0000644 0041054 0041055 00000005057 11225447104 022025 0 ustar lacunaus lacunaus do_items( $handles );
}
/**
* Register CSS style file.
*
* @since r79
* @see WP_Styles::add() For parameter and additional information.
*/
function wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
global $wp_styles;
if ( !is_a($wp_styles, 'WP_Styles') )
$wp_styles = new WP_Styles();
$wp_styles->add( $handle, $src, $deps, $ver, $media );
}
/**
* Remove a registered CSS file.
*
* @since r79
* @see WP_Styles::remove() For parameter and additional information.
*/
function wp_deregister_style( $handle ) {
global $wp_styles;
if ( !is_a($wp_styles, 'WP_Styles') )
$wp_styles = new WP_Styles();
$wp_styles->remove( $handle );
}
/**
* Enqueue a CSS style file.
*
* @since r79
* @see WP_Styles::add(), WP_Styles::enqueue()
*/
function wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = false ) {
global $wp_styles;
if ( !is_a($wp_styles, 'WP_Styles') )
$wp_styles = new WP_Styles();
if ( $src ) {
$_handle = explode('?', $handle);
$wp_styles->add( $_handle[0], $src, $deps, $ver, $media );
}
$wp_styles->enqueue( $handle );
}
/**
* Check whether style has been added to WordPress Styles.
*
* The values for list defaults to 'queue', which is the same as enqueue for
* styles.
*
* @since WP unknown; BP unknown
*
* @param string $handle Handle used to add style.
* @param string $list Optional, defaults to 'queue'. Others values are 'registered', 'queue', 'done', 'to_do'
* @return bool
*/
function wp_style_is( $handle, $list = 'queue' ) {
global $wp_styles;
if ( !is_a($wp_styles, 'WP_Styles') )
$wp_styles = new WP_Styles();
$query = $wp_styles->query( $handle, $list );
if ( is_object( $query ) )
return true;
return $query;
}
larscapo/wp-includes/link-template.php 0000644 0041054 0041055 00000145464 11225447104 020624 0 ustar lacunaus lacunaus use_trailing_slashes )
$string = trailingslashit($string);
else
$string = untrailingslashit($string);
// Note that $type_of_url can be one of following:
// single, single_trackback, single_feed, single_paged, feed, category, page, year, month, day, paged
$string = apply_filters('user_trailingslashit', $string, $type_of_url);
return $string;
}
/**
* Display permalink anchor for current post.
*
* The permalink mode title will use the post title for the 'a' element 'id'
* attribute. The id mode uses 'post-' with the post ID for the 'id' attribute.
*
* @since 0.71
*
* @param string $mode Permalink mode can be either 'title', 'id', or default, which is 'id'.
*/
function permalink_anchor($mode = 'id') {
global $post;
switch ( strtolower($mode) ) {
case 'title':
$title = sanitize_title($post->post_title) . '-' . $post->ID;
echo '';
break;
case 'id':
default:
echo '';
break;
}
}
/**
* Retrieve full permalink for current post or post ID.
*
* @since 1.0.0
*
* @param int $id Optional. Post ID.
* @param bool $leavename Optional, defaults to false. Whether to keep post name or page name.
* @return string
*/
function get_permalink($id = 0, $leavename = false) {
$rewritecode = array(
'%year%',
'%monthnum%',
'%day%',
'%hour%',
'%minute%',
'%second%',
$leavename? '' : '%postname%',
'%post_id%',
'%category%',
'%author%',
$leavename? '' : '%pagename%',
);
if ( is_object($id) && isset($id->filter) && 'sample' == $id->filter ) {
$post = $id;
$sample = true;
} else {
$post = &get_post($id);
$sample = false;
}
if ( empty($post->ID) ) return false;
if ( $post->post_type == 'page' )
return get_page_link($post->ID, $leavename, $sample);
elseif ($post->post_type == 'attachment')
return get_attachment_link($post->ID);
$permalink = get_option('permalink_structure');
if ( '' != $permalink && !in_array($post->post_status, array('draft', 'pending')) ) {
$unixtime = strtotime($post->post_date);
$category = '';
if ( strpos($permalink, '%category%') !== false ) {
$cats = get_the_category($post->ID);
if ( $cats ) {
usort($cats, '_usort_terms_by_ID'); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent )
$category = get_category_parents($parent, false, '/', true) . $category;
}
// show default category in permalinks, without
// having to assign it explicitly
if ( empty($category) ) {
$default_category = get_category( get_option( 'default_category' ) );
$category = is_wp_error( $default_category ) ? '' : $default_category->slug;
}
}
$author = '';
if ( strpos($permalink, '%author%') !== false ) {
$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
}
$date = explode(" ",date('Y m d H i s', $unixtime));
$rewritereplace =
array(
$date[0],
$date[1],
$date[2],
$date[3],
$date[4],
$date[5],
$post->post_name,
$post->ID,
$category,
$author,
$post->post_name,
);
$permalink = get_option('home') . str_replace($rewritecode, $rewritereplace, $permalink);
$permalink = user_trailingslashit($permalink, 'single');
return apply_filters('post_link', $permalink, $post, $leavename);
} else { // if they're not using the fancy permalink option
$permalink = trailingslashit(get_option('home')) . '?p=' . $post->ID;
return apply_filters('post_link', $permalink, $post, $leavename);
}
}
/**
* Retrieve permalink from post ID.
*
* @since 1.0.0
*
* @param int $post_id Optional. Post ID.
* @param mixed $deprecated Not used.
* @return string
*/
function post_permalink($post_id = 0, $deprecated = '') {
return get_permalink($post_id);
}
/**
* Retrieve the permalink for current page or page ID.
*
* Respects page_on_front. Use this one.
*
* @since 1.5.0
*
* @param int $id Optional. Post ID.
* @param bool $leavename Optional, defaults to false. Whether to keep page name.
* @param bool $sample Optional, defaults to false. Is it a sample permalink.
* @return string
*/
function get_page_link( $id = false, $leavename = false, $sample = false ) {
global $post;
$id = (int) $id;
if ( !$id )
$id = (int) $post->ID;
if ( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') )
$link = get_option('home');
else
$link = _get_page_link( $id , $leavename, $sample );
return apply_filters('page_link', $link, $id);
}
/**
* Retrieve the page permalink.
*
* Ignores page_on_front. Internal use only.
*
* @since 2.1.0
* @access private
*
* @param int $id Optional. Post ID.
* @param bool $leavename Optional. Leave name.
* @param bool $sample Optional. Sample permalink.
* @return string
*/
function _get_page_link( $id = false, $leavename = false, $sample = false ) {
global $post, $wp_rewrite;
if ( !$id )
$id = (int) $post->ID;
else
$post = &get_post($id);
$pagestruct = $wp_rewrite->get_page_permastruct();
if ( '' != $pagestruct && ( ( isset($post->post_status) && 'draft' != $post->post_status ) || $sample ) ) {
$link = get_page_uri($id);
$link = ( $leavename ) ? $pagestruct : str_replace('%pagename%', $link, $pagestruct);
$link = trailingslashit(get_option('home')) . "$link";
$link = user_trailingslashit($link, 'page');
} else {
$link = trailingslashit(get_option('home')) . "?page_id=$id";
}
return apply_filters( '_get_page_link', $link, $id );
}
/**
* Retrieve permalink for attachment.
*
* This can be used in the WordPress Loop or outside of it.
*
* @since 2.0.0
*
* @param int $id Optional. Post ID.
* @return string
*/
function get_attachment_link($id = false) {
global $post, $wp_rewrite;
$link = false;
if (! $id) {
$id = (int) $post->ID;
}
$object = get_post($id);
if ( $wp_rewrite->using_permalinks() && ($object->post_parent > 0) && ($object->post_parent != $id) ) {
$parent = get_post($object->post_parent);
if ( 'page' == $parent->post_type )
$parentlink = _get_page_link( $object->post_parent ); // Ignores page_on_front
else
$parentlink = get_permalink( $object->post_parent );
if ( is_numeric($object->post_name) || false !== strpos(get_option('permalink_structure'), '%category%') )
$name = 'attachment/' . $object->post_name; // // is paged so we use the explicit attachment marker
else
$name = $object->post_name;
if (strpos($parentlink, '?') === false)
$link = user_trailingslashit( trailingslashit($parentlink) . $name );
}
if (! $link ) {
$link = trailingslashit(get_bloginfo('url')) . "?attachment_id=$id";
}
return apply_filters('attachment_link', $link, $id);
}
/**
* Retrieve the permalink for the year archives.
*
* @since 1.5.0
*
* @param int|bool $year False for current year or year for permalink.
* @return string
*/
function get_year_link($year) {
global $wp_rewrite;
if ( !$year )
$year = gmdate('Y', time()+(get_option('gmt_offset') * 3600));
$yearlink = $wp_rewrite->get_year_permastruct();
if ( !empty($yearlink) ) {
$yearlink = str_replace('%year%', $year, $yearlink);
return apply_filters('year_link', get_option('home') . user_trailingslashit($yearlink, 'year'), $year);
} else {
return apply_filters('year_link', trailingslashit(get_option('home')) . '?m=' . $year, $year);
}
}
/**
* Retrieve the permalink for the month archives with year.
*
* @since 1.0.0
*
* @param bool|int $year False for current year. Integer of year.
* @param bool|int $month False for current month. Integer of month.
* @return string
*/
function get_month_link($year, $month) {
global $wp_rewrite;
if ( !$year )
$year = gmdate('Y', time()+(get_option('gmt_offset') * 3600));
if ( !$month )
$month = gmdate('m', time()+(get_option('gmt_offset') * 3600));
$monthlink = $wp_rewrite->get_month_permastruct();
if ( !empty($monthlink) ) {
$monthlink = str_replace('%year%', $year, $monthlink);
$monthlink = str_replace('%monthnum%', zeroise(intval($month), 2), $monthlink);
return apply_filters('month_link', get_option('home') . user_trailingslashit($monthlink, 'month'), $year, $month);
} else {
return apply_filters('month_link', trailingslashit(get_option('home')) . '?m=' . $year . zeroise($month, 2), $year, $month);
}
}
/**
* Retrieve the permalink for the day archives with year and month.
*
* @since 1.0.0
*
* @param bool|int $year False for current year. Integer of year.
* @param bool|int $month False for current month. Integer of month.
* @param bool|int $day False for current day. Integer of day.
* @return string
*/
function get_day_link($year, $month, $day) {
global $wp_rewrite;
if ( !$year )
$year = gmdate('Y', time()+(get_option('gmt_offset') * 3600));
if ( !$month )
$month = gmdate('m', time()+(get_option('gmt_offset') * 3600));
if ( !$day )
$day = gmdate('j', time()+(get_option('gmt_offset') * 3600));
$daylink = $wp_rewrite->get_day_permastruct();
if ( !empty($daylink) ) {
$daylink = str_replace('%year%', $year, $daylink);
$daylink = str_replace('%monthnum%', zeroise(intval($month), 2), $daylink);
$daylink = str_replace('%day%', zeroise(intval($day), 2), $daylink);
return apply_filters('day_link', get_option('home') . user_trailingslashit($daylink, 'day'), $year, $month, $day);
} else {
return apply_filters('day_link', trailingslashit(get_option('home')) . '?m=' . $year . zeroise($month, 2) . zeroise($day, 2), $year, $month, $day);
}
}
/**
* Retrieve the permalink for the feed type.
*
* @since 1.5.0
*
* @param string $feed Optional, defaults to default feed. Feed type.
* @return string
*/
function get_feed_link($feed = '') {
global $wp_rewrite;
$permalink = $wp_rewrite->get_feed_permastruct();
if ( '' != $permalink ) {
if ( false !== strpos($feed, 'comments_') ) {
$feed = str_replace('comments_', '', $feed);
$permalink = $wp_rewrite->get_comment_feed_permastruct();
}
if ( get_default_feed() == $feed )
$feed = '';
$permalink = str_replace('%feed%', $feed, $permalink);
$permalink = preg_replace('#/+#', '/', "/$permalink");
$output = get_option('home') . user_trailingslashit($permalink, 'feed');
} else {
if ( empty($feed) )
$feed = get_default_feed();
if ( false !== strpos($feed, 'comments_') )
$feed = str_replace('comments_', 'comments-', $feed);
$output = trailingslashit(get_option('home')) . "?feed={$feed}";
}
return apply_filters('feed_link', $output, $feed);
}
/**
* Retrieve the permalink for the post comments feed.
*
* @since 2.2.0
*
* @param int $post_id Optional. Post ID.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_post_comments_feed_link($post_id = '', $feed = '') {
global $id;
if ( empty($post_id) )
$post_id = (int) $id;
if ( empty($feed) )
$feed = get_default_feed();
if ( '' != get_option('permalink_structure') ) {
$url = trailingslashit( get_permalink($post_id) ) . 'feed';
if ( $feed != get_default_feed() )
$url .= "/$feed";
$url = user_trailingslashit($url, 'single_feed');
} else {
$type = get_post_field('post_type', $post_id);
if ( 'page' == $type )
$url = trailingslashit(get_option('home')) . "?feed=$feed&page_id=$post_id";
else
$url = trailingslashit(get_option('home')) . "?feed=$feed&p=$post_id";
}
return apply_filters('post_comments_feed_link', $url);
}
/**
* Display the comment feed link for a post.
*
* Prints out the comment feed link for a post. Link text is placed in the
* anchor. If no link text is specified, default text is used. If no post ID is
* specified, the current post is used.
*
* @package WordPress
* @subpackage Feed
* @since 2.5.0
*
* @param string $link_text Descriptive text.
* @param int $post_id Optional post ID. Default to current post.
* @param string $feed Optional. Feed format.
* @return string Link to the comment feed for the current post.
*/
function post_comments_feed_link( $link_text = '', $post_id = '', $feed = '' ) {
$url = get_post_comments_feed_link($post_id, $feed);
if ( empty($link_text) )
$link_text = __('Comments Feed');
echo apply_filters( 'post_comments_feed_link_html', "$link_text", $post_id, $feed );
}
/**
* Retrieve the feed link for a given author.
*
* Returns a link to the feed for all posts by a given author. A specific feed
* can be requested or left blank to get the default feed.
*
* @package WordPress
* @subpackage Feed
* @since 2.5.0
*
* @param int $author_id ID of an author.
* @param string $feed Optional. Feed type.
* @return string Link to the feed for the author specified by $author_id.
*/
function get_author_feed_link( $author_id, $feed = '' ) {
$author_id = (int) $author_id;
$permalink_structure = get_option('permalink_structure');
if ( empty($feed) )
$feed = get_default_feed();
if ( '' == $permalink_structure ) {
$link = trailingslashit(get_option('home')) . "?feed=$feed&author=" . $author_id;
} else {
$link = get_author_posts_url($author_id);
if ( $feed == get_default_feed() )
$feed_link = 'feed';
else
$feed_link = "feed/$feed";
$link = trailingslashit($link) . user_trailingslashit($feed_link, 'feed');
}
$link = apply_filters('author_feed_link', $link, $feed);
return $link;
}
/**
* Retrieve the feed link for a category.
*
* Returns a link to the feed for all post in a given category. A specific feed
* can be requested or left blank to get the default feed.
*
* @package WordPress
* @subpackage Feed
* @since 2.5.0
*
* @param int $cat_id ID of a category.
* @param string $feed Optional. Feed type.
* @return string Link to the feed for the category specified by $cat_id.
*/
function get_category_feed_link($cat_id, $feed = '') {
$cat_id = (int) $cat_id;
$category = get_category($cat_id);
if ( empty($category) || is_wp_error($category) )
return false;
if ( empty($feed) )
$feed = get_default_feed();
$permalink_structure = get_option('permalink_structure');
if ( '' == $permalink_structure ) {
$link = trailingslashit(get_option('home')) . "?feed=$feed&cat=" . $cat_id;
} else {
$link = get_category_link($cat_id);
if( $feed == get_default_feed() )
$feed_link = 'feed';
else
$feed_link = "feed/$feed";
$link = trailingslashit($link) . user_trailingslashit($feed_link, 'feed');
}
$link = apply_filters('category_feed_link', $link, $feed);
return $link;
}
/**
* Retrieve permalink for feed of tag.
*
* @since 2.3.0
*
* @param int $tag_id Tag ID.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_tag_feed_link($tag_id, $feed = '') {
$tag_id = (int) $tag_id;
$tag = get_tag($tag_id);
if ( empty($tag) || is_wp_error($tag) )
return false;
$permalink_structure = get_option('permalink_structure');
if ( empty($feed) )
$feed = get_default_feed();
if ( '' == $permalink_structure ) {
$link = trailingslashit(get_option('home')) . "?feed=$feed&tag=" . $tag->slug;
} else {
$link = get_tag_link($tag->term_id);
if ( $feed == get_default_feed() )
$feed_link = 'feed';
else
$feed_link = "feed/$feed";
$link = trailingslashit($link) . user_trailingslashit($feed_link, 'feed');
}
$link = apply_filters('tag_feed_link', $link, $feed);
return $link;
}
/**
* Retrieve edit tag link.
*
* @since 2.7.0
*
* @param int $tag_id Tag ID
* @return string
*/
function get_edit_tag_link( $tag_id = 0, $taxonomy = 'post_tag' ) {
$tag = get_term($tag_id, $taxonomy);
if ( !current_user_can('manage_categories') )
return;
$location = admin_url('edit-tags.php?action=edit&taxonomy=' . $taxonomy . '&tag_ID=' . $tag->term_id);
return apply_filters( 'get_edit_tag_link', $location );
}
/**
* Display or retrieve edit tag link with formatting.
*
* @since 2.7.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param int|object $tag Tag object or ID
* @return string|null HTML content, if $echo is set to false.
*/
function edit_tag_link( $link = '', $before = '', $after = '', $tag = null ) {
$tag = get_term($tag, 'post_tag');
if ( !current_user_can('manage_categories') )
return;
if ( empty($link) )
$link = __('Edit This');
$link = '' . $link . '';
echo $before . apply_filters( 'edit_tag_link', $link, $tag->term_id ) . $after;
}
/**
* Retrieve the permalink for the feed of the search results.
*
* @since 2.5.0
*
* @param string $search_query Optional. Search query.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_search_feed_link($search_query = '', $feed = '') {
if ( empty($search_query) )
$search = esc_attr(get_search_query());
else
$search = esc_attr(stripslashes($search_query));
if ( empty($feed) )
$feed = get_default_feed();
$link = trailingslashit(get_option('home')) . "?s=$search&feed=$feed";
$link = apply_filters('search_feed_link', $link);
return $link;
}
/**
* Retrieve the permalink for the comments feed of the search results.
*
* @since 2.5.0
*
* @param string $search_query Optional. Search query.
* @param string $feed Optional. Feed type.
* @return string
*/
function get_search_comments_feed_link($search_query = '', $feed = '') {
if ( empty($search_query) )
$search = esc_attr(get_search_query());
else
$search = esc_attr(stripslashes($search_query));
if ( empty($feed) )
$feed = get_default_feed();
$link = trailingslashit(get_option('home')) . "?s=$search&feed=comments-$feed";
$link = apply_filters('search_feed_link', $link);
return $link;
}
/**
* Retrieve edit posts link for post.
*
* Can be used within the WordPress loop or outside of it. Can be used with
* pages, posts, attachments, and revisions.
*
* @since 2.3.0
*
* @param int $id Optional. Post ID.
* @param string $context Optional, default to display. How to write the '&', defaults to '&'.
* @return string
*/
function get_edit_post_link( $id = 0, $context = 'display' ) {
if ( !$post = &get_post( $id ) )
return;
if ( 'display' == $context )
$action = 'action=edit&';
else
$action = 'action=edit&';
switch ( $post->post_type ) :
case 'page' :
if ( !current_user_can( 'edit_page', $post->ID ) )
return;
$file = 'page';
$var = 'post';
break;
case 'attachment' :
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
$file = 'media';
$var = 'attachment_id';
break;
case 'revision' :
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
$file = 'revision';
$var = 'revision';
$action = '';
break;
default :
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
$file = 'post';
$var = 'post';
break;
endswitch;
return apply_filters( 'get_edit_post_link', admin_url("$file.php?{$action}$var=$post->ID"), $post->ID, $context );
}
/**
* Display edit post link for post.
*
* @since 1.0.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param int $id Optional. Post ID.
*/
function edit_post_link( $link = 'Edit This', $before = '', $after = '', $id = 0 ) {
if ( !$post = &get_post( $id ) )
return;
if ( !$url = get_edit_post_link( $post->ID ) )
return;
$link = '' . $link . '';
echo $before . apply_filters( 'edit_post_link', $link, $post->ID ) . $after;
}
/**
* Retrieve edit comment link.
*
* @since 2.3.0
*
* @param int $comment_id Optional. Comment ID.
* @return string
*/
function get_edit_comment_link( $comment_id = 0 ) {
$comment = &get_comment( $comment_id );
$post = &get_post( $comment->comment_post_ID );
if ( $post->post_type == 'page' ) {
if ( !current_user_can( 'edit_page', $post->ID ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
}
$location = admin_url('comment.php?action=editcomment&c=') . $comment->comment_ID;
return apply_filters( 'get_edit_comment_link', $location );
}
/**
* Display or retrieve edit comment link with formatting.
*
* @since 1.0.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @return string|null HTML content, if $echo is set to false.
*/
function edit_comment_link( $link = 'Edit This', $before = '', $after = '' ) {
global $comment, $post;
if ( $post->post_type == 'attachment' ) {
} elseif ( $post->post_type == 'page' ) {
if ( !current_user_can( 'edit_page', $post->ID ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
}
$link = '' . $link . '';
echo $before . apply_filters( 'edit_comment_link', $link, $comment->comment_ID ) . $after;
}
/**
* Display edit bookmark (literally a URL external to blog) link.
*
* @since 2.7.0
*
* @param int $link Optional. Bookmark ID.
* @return string
*/
function get_edit_bookmark_link( $link = 0 ) {
$link = get_bookmark( $link );
if ( !current_user_can('manage_links') )
return;
$location = admin_url('link.php?action=edit&link_id=') . $link->link_id;
return apply_filters( 'get_edit_bookmark_link', $location, $link->link_id );
}
/**
* Display edit bookmark (literally a URL external to blog) link anchor content.
*
* @since 2.7.0
*
* @param string $link Optional. Anchor text.
* @param string $before Optional. Display before edit link.
* @param string $after Optional. Display after edit link.
* @param int $bookmark Optional. Bookmark ID.
*/
function edit_bookmark_link( $link = '', $before = '', $after = '', $bookmark = null ) {
$bookmark = get_bookmark($bookmark);
if ( !current_user_can('manage_links') )
return;
if ( empty($link) )
$link = __('Edit This');
$link = '' . $link . '';
echo $before . apply_filters( 'edit_bookmark_link', $link, $bookmark->link_id ) . $after;
}
// Navigation links
/**
* Retrieve previous post link that is adjacent to current post.
*
* @since 1.5.0
*
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @return string
*/
function get_previous_post($in_same_cat = false, $excluded_categories = '') {
return get_adjacent_post($in_same_cat, $excluded_categories);
}
/**
* Retrieve next post link that is adjacent to current post.
*
* @since 1.5.0
*
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @return string
*/
function get_next_post($in_same_cat = false, $excluded_categories = '') {
return get_adjacent_post($in_same_cat, $excluded_categories, false);
}
/**
* Retrieve adjacent post link.
*
* Can either be next or previous post link.
*
* @since 2.5.0
*
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @param bool $previous Optional. Whether to retrieve previous post.
* @return string
*/
function get_adjacent_post($in_same_cat = false, $excluded_categories = '', $previous = true) {
global $post, $wpdb;
if ( empty($post) || !is_single() || is_attachment() )
return null;
$current_post_date = $post->post_date;
$join = '';
$posts_in_ex_cats_sql = '';
if ( $in_same_cat || !empty($excluded_categories) ) {
$join = " INNER JOIN $wpdb->term_relationships AS tr ON p.ID = tr.object_id INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
if ( $in_same_cat ) {
$cat_array = wp_get_object_terms($post->ID, 'category', 'fields=ids');
$join .= " AND tt.taxonomy = 'category' AND tt.term_id IN (" . implode(',', $cat_array) . ")";
}
$posts_in_ex_cats_sql = "AND tt.taxonomy = 'category'";
if ( !empty($excluded_categories) ) {
$excluded_categories = array_map('intval', explode(' and ', $excluded_categories));
if ( !empty($cat_array) ) {
$excluded_categories = array_diff($excluded_categories, $cat_array);
$posts_in_ex_cats_sql = '';
}
if ( !empty($excluded_categories) ) {
$posts_in_ex_cats_sql = " AND tt.taxonomy = 'category' AND tt.term_id NOT IN (" . implode($excluded_categories, ',') . ')';
}
}
}
$adjacent = $previous ? 'previous' : 'next';
$op = $previous ? '<' : '>';
$order = $previous ? 'DESC' : 'ASC';
$join = apply_filters( "get_{$adjacent}_post_join", $join, $in_same_cat, $excluded_categories );
$where = apply_filters( "get_{$adjacent}_post_where", $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = 'post' AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date), $in_same_cat, $excluded_categories );
$sort = apply_filters( "get_{$adjacent}_post_sort", "ORDER BY p.post_date $order LIMIT 1" );
$query = "SELECT p.* FROM $wpdb->posts AS p $join $where $sort";
$query_key = 'adjacent_post_' . md5($query);
$result = wp_cache_get($query_key, 'counts');
if ( false !== $result )
return $result;
$result = $wpdb->get_row("SELECT p.* FROM $wpdb->posts AS p $join $where $sort");
if ( null === $result )
$result = '';
wp_cache_set($query_key, $result, 'counts');
return $result;
}
/**
* Get adjacent post relational link.
*
* Can either be next or previous post relational link.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @param bool $previous Optional, default is true. Whether display link to previous post.
* @return string
*/
function get_adjacent_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '', $previous = true) {
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat,$excluded_categories,$previous);
if ( empty($post) )
return;
if ( empty($post->post_title) )
$post->post_title = $previous ? __('Previous Post') : __('Next Post');
$date = mysql2date(get_option('date_format'), $post->post_date);
$title = str_replace('%title', $post->post_title, $title);
$title = str_replace('%date', $date, $title);
$title = apply_filters('the_title', $title, $post);
$link = $previous ? "\n";
$adjacent = $previous ? 'previous' : 'next';
return apply_filters( "{$adjacent}_post_rel_link", $link );
}
/**
* Display relational links for the posts adjacent to the current post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
*/
function adjacent_posts_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '') {
echo get_adjacent_post_rel_link($title, $in_same_cat, $excluded_categories = '', true);
echo get_adjacent_post_rel_link($title, $in_same_cat, $excluded_categories = '', false);
}
/**
* Display relational link for the next post adjacent to the current post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
*/
function next_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '') {
echo get_adjacent_post_rel_link($title, $in_same_cat, $excluded_categories = '', false);
}
/**
* Display relational link for the previous post adjacent to the current post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
*/
function prev_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '') {
echo get_adjacent_post_rel_link($title, $in_same_cat, $excluded_categories = '', true);
}
/**
* Retrieve boundary post.
*
* Boundary being either the first or last post by publish date within the contraitns specified
* by in same category or excluded categories.
*
* @since 2.8.0
*
* @param bool $in_same_cat Optional. Whether returned post should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @param bool $previous Optional. Whether to retrieve first post.
* @return object
*/
function get_boundary_post($in_same_cat = false, $excluded_categories = '', $start = true) {
global $post, $wpdb;
if ( empty($post) || !is_single() || is_attachment() )
return null;
$cat_array = array();
$excluded_categories = array();
if ( !empty($in_same_cat) || !empty($excluded_categories) ) {
if ( !empty($in_same_cat) ) {
$cat_array = wp_get_object_terms($post->ID, 'category', 'fields=ids');
}
if ( !empty($excluded_categories) ) {
$excluded_categories = array_map('intval', explode(',', $excluded_categories));
if ( !empty($cat_array) )
$excluded_categories = array_diff($excluded_categories, $cat_array);
$inverse_cats = array();
foreach ( $excluded_categories as $excluded_category)
$inverse_cats[] = $excluded_category * -1;
$excluded_categories = $inverse_cats;
}
}
$categories = implode(',', array_merge($cat_array, $excluded_categories) );
$order = $start ? 'ASC' : 'DESC';
return get_posts( array('numberposts' => 1, 'order' => $order, 'orderby' => 'ID', 'category' => $categories) );
}
/**
* Get boundary post relational link.
*
* Can either be start or end post relational link.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @param bool $start Optional, default is true. Whether display link to first post.
* @return string
*/
function get_boundary_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '', $start = true) {
$posts = get_boundary_post($in_same_cat,$excluded_categories,$start);
// Even though we limited get_posts to return only 1 item it still returns an array of objects.
$post = $posts[0];
if ( empty($post) )
return;
if ( empty($post->post_title) )
$post->post_title = $start ? __('First Post') : __('Last Post');
$date = mysql2date(get_option('date_format'), $post->post_date);
$title = str_replace('%title', $post->post_title, $title);
$title = str_replace('%date', $date, $title);
$title = apply_filters('the_title', $title, $post);
$link = $start ? "\n";
$boundary = $start ? 'start' : 'end';
return apply_filters( "{$boundary}_post_rel_link", $link );
}
/**
* Display relational link for the first post.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
*/
function start_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '') {
echo get_boundary_post_rel_link($title, $in_same_cat, $excluded_categories, true);
}
/**
* Get site index relational link.
*
* @since 2.8.0
*
* @return string
*/
function get_index_rel_link() {
$link = "\n";
return apply_filters( "index_rel_link", $link );
}
/**
* Display relational link for the site index.
*
* @since 2.8.0
*/
function index_rel_link() {
echo get_index_rel_link();
}
/**
* Get parent post relational link.
*
* @since 2.8.0
*
* @param string $title Optional. Link title format.
* @return string
*/
function get_parent_post_rel_link($title = '%title') {
if ( ! empty( $GLOBALS['post'] ) && ! empty( $GLOBALS['post']->post_parent ) )
$post = & get_post($GLOBALS['post']->post_parent);
if ( empty($post) )
return;
$date = mysql2date(get_option('date_format'), $post->post_date);
$title = str_replace('%title', $post->post_title, $title);
$title = str_replace('%date', $date, $title);
$title = apply_filters('the_title', $title, $post);
$link = "\n";
return apply_filters( "parent_post_rel_link", $link );
}
/**
* Display relational link for parent item
*
* @since 2.8.0
*/
function parent_post_rel_link($title = '%title') {
echo get_parent_post_rel_link($title);
}
/**
* Display previous post link that is adjacent to the current post.
*
* @since 1.5.0
*
* @param string $format Optional. Link anchor format.
* @param string $link Optional. Link permalink format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
*/
function previous_post_link($format='« %link', $link='%title', $in_same_cat = false, $excluded_categories = '') {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, true);
}
/**
* Display next post link that is adjacent to the current post.
*
* @since 1.5.0
*
* @param string $format Optional. Link anchor format.
* @param string $link Optional. Link permalink format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
*/
function next_post_link($format='%link »', $link='%title', $in_same_cat = false, $excluded_categories = '') {
adjacent_post_link($format, $link, $in_same_cat, $excluded_categories, false);
}
/**
* Display adjacent post link.
*
* Can be either next post link or previous.
*
* @since 2.5.0
*
* @param string $format Link anchor format.
* @param string $link Link permalink format.
* @param bool $in_same_cat Optional. Whether link should be in same category.
* @param string $excluded_categories Optional. Excluded categories IDs.
* @param bool $previous Optional, default is true. Whether display link to previous post.
*/
function adjacent_post_link($format, $link, $in_same_cat = false, $excluded_categories = '', $previous = true) {
if ( $previous && is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_adjacent_post($in_same_cat, $excluded_categories, $previous);
if ( !$post )
return;
$title = $post->post_title;
if ( empty($post->post_title) )
$title = $previous ? __('Previous Post') : __('Next Post');
$title = apply_filters('the_title', $title, $post);
$date = mysql2date(get_option('date_format'), $post->post_date);
$string = '';
$link = str_replace('%title', $title, $link);
$link = str_replace('%date', $date, $link);
$link = $string . $link . '';
$format = str_replace('%link', $link, $format);
$adjacent = $previous ? 'previous' : 'next';
echo apply_filters( "{$adjacent}_post_link", $format, $link );
}
/**
* Retrieve get links for page numbers.
*
* @since 1.5.0
*
* @param int $pagenum Optional. Page ID.
* @return string
*/
function get_pagenum_link($pagenum = 1) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$request = remove_query_arg( 'paged' );
$home_root = parse_url(get_option('home'));
$home_root = ( isset($home_root['path']) ) ? $home_root['path'] : '';
$home_root = preg_quote( trailingslashit( $home_root ), '|' );
$request = preg_replace('|^'. $home_root . '|', '', $request);
$request = preg_replace('|^/+|', '', $request);
if ( !$wp_rewrite->using_permalinks() || is_admin() ) {
$base = trailingslashit( get_bloginfo( 'home' ) );
if ( $pagenum > 1 ) {
$result = add_query_arg( 'paged', $pagenum, $base . $request );
} else {
$result = $base . $request;
}
} else {
$qs_regex = '|\?.*?$|';
preg_match( $qs_regex, $request, $qs_match );
if ( !empty( $qs_match[0] ) ) {
$query_string = $qs_match[0];
$request = preg_replace( $qs_regex, '', $request );
} else {
$query_string = '';
}
$request = preg_replace( '|page/\d+/?$|', '', $request);
$request = preg_replace( '|^index\.php|', '', $request);
$request = ltrim($request, '/');
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $wp_rewrite->using_index_permalinks() && ( $pagenum > 1 || '' != $request ) )
$base .= 'index.php/';
if ( $pagenum > 1 ) {
$request = ( ( !empty( $request ) ) ? trailingslashit( $request ) : $request ) . user_trailingslashit( 'page/' . $pagenum, 'paged' );
}
$result = $base . $request . $query_string;
}
$result = apply_filters('get_pagenum_link', $result);
return $result;
}
/**
* Retrieve next posts pages link.
*
* Backported from 2.1.3 to 2.0.10.
*
* @since 2.0.10
*
* @param int $max_page Optional. Max pages.
* @return string
*/
function get_next_posts_page_link($max_page = 0) {
global $paged;
if ( !is_single() ) {
if ( !$paged )
$paged = 1;
$nextpage = intval($paged) + 1;
if ( !$max_page || $max_page >= $nextpage )
return get_pagenum_link($nextpage);
}
}
/**
* Display or return the next posts pages link.
*
* @since 0.71
*
* @param int $max_page Optional. Max pages.
* @param boolean $echo Optional. Echo or return;
*/
function next_posts( $max_page = 0, $echo = true ) {
$output = esc_url( get_next_posts_page_link( $max_page ) );
if ( $echo )
echo $output;
else
return $output;
}
/**
* Return the next posts pages link.
*
* @since 2.7.0
*
* @param string $label Content for link text.
* @param int $max_page Optional. Max pages.
* @return string|null
*/
function get_next_posts_link( $label = 'Next Page »', $max_page = 0 ) {
global $paged, $wp_query;
if ( !$max_page ) {
$max_page = $wp_query->max_num_pages;
}
if ( !$paged )
$paged = 1;
$nextpage = intval($paged) + 1;
if ( !is_single() && ( empty($paged) || $nextpage <= $max_page) ) {
$attr = apply_filters( 'next_posts_link_attributes', '' );
return '". preg_replace('/&([^#])(?![a-z]{1,8};)/', '&$1', $label) .'';
}
}
/**
* Display the next posts pages link.
*
* @since 0.71
* @uses get_next_posts_link()
*
* @param string $label Content for link text.
* @param int $max_page Optional. Max pages.
*/
function next_posts_link( $label = 'Next Page »', $max_page = 0 ) {
echo get_next_posts_link( $label, $max_page );
}
/**
* Retrieve previous post pages link.
*
* Will only return string, if not on a single page or post.
*
* Backported to 2.0.10 from 2.1.3.
*
* @since 2.0.10
*
* @return string|null
*/
function get_previous_posts_page_link() {
global $paged;
if ( !is_single() ) {
$nextpage = intval($paged) - 1;
if ( $nextpage < 1 )
$nextpage = 1;
return get_pagenum_link($nextpage);
}
}
/**
* Display or return the previous posts pages link.
*
* @since 0.71
*
* @param boolean $echo Optional. Echo or return;
*/
function previous_posts( $echo = true ) {
$output = esc_url( get_previous_posts_page_link() );
if ( $echo )
echo $output;
else
return $output;
}
/**
* Return the previous posts pages link.
*
* @since 2.7.0
*
* @param string $label Optional. Previous page link text.
* @return string|null
*/
function get_previous_posts_link( $label = '« Previous Page' ) {
global $paged;
if ( !is_single() && $paged > 1 ) {
$attr = apply_filters( 'previous_posts_link_attributes', '' );
return '". preg_replace( '/&([^#])(?![a-z]{1,8};)/', '&$1', $label ) .'';
}
}
/**
* Display the previous posts page link.
*
* @since 0.71
* @uses get_previous_posts_link()
*
* @param string $label Optional. Previous page link text.
*/
function previous_posts_link( $label = '« Previous Page' ) {
echo get_previous_posts_link( $label );
}
/**
* Return post pages link navigation for previous and next pages.
*
* @since 2.8
*
* @param string|array $args Optional args.
* @return string The posts link navigation.
*/
function get_posts_nav_link( $args = array() ) {
global $wp_query;
$return = '';
if ( !is_singular() ) {
$defaults = array(
'sep' => ' — ',
'prelabel' => __('« Previous Page'),
'nxtlabel' => __('Next Page »'),
);
$args = wp_parse_args( $args, $defaults );
$max_num_pages = $wp_query->max_num_pages;
$paged = get_query_var('paged');
//only have sep if there's both prev and next results
if ($paged < 2 || $paged >= $max_num_pages) {
$args['sep'] = '';
}
if ( $max_num_pages > 1 ) {
$return = get_previous_posts_link($args['prelabel']);
$return .= preg_replace('/&([^#])(?![a-z]{1,8};)/', '&$1', $args['sep']);
$return .= get_next_posts_link($args['nxtlabel']);
}
}
return $return;
}
/**
* Display post pages link navigation for previous and next pages.
*
* @since 0.71
*
* @param string $sep Optional. Separator for posts navigation links.
* @param string $prelabel Optional. Label for previous pages.
* @param string $nxtlabel Optional Label for next pages.
*/
function posts_nav_link( $sep = '', $prelabel = '', $nxtlabel = '' ) {
$args = array_filter( compact('sep', 'prelabel', 'nxtlabel') );
echo get_posts_nav_link($args);
}
/**
* Retrieve page numbers links.
*
* @since 2.7.0
*
* @param int $pagenum Optional. Page number.
* @return string
*/
function get_comments_pagenum_link( $pagenum = 1, $max_page = 0 ) {
global $post, $wp_rewrite;
$pagenum = (int) $pagenum;
$result = get_permalink( $post->ID );
if ( 'newest' == get_option('default_comments_page') ) {
if ( $pagenum != $max_page ) {
if ( $wp_rewrite->using_permalinks() )
$result = user_trailingslashit( trailingslashit($result) . 'comment-page-' . $pagenum, 'commentpaged');
else
$result = add_query_arg( 'cpage', $pagenum, $result );
}
} elseif ( $pagenum > 1 ) {
if ( $wp_rewrite->using_permalinks() )
$result = user_trailingslashit( trailingslashit($result) . 'comment-page-' . $pagenum, 'commentpaged');
else
$result = add_query_arg( 'cpage', $pagenum, $result );
}
$result .= '#comments';
$result = apply_filters('get_comments_pagenum_link', $result);
return $result;
}
/**
* Return the link to next comments pages.
*
* @since 2.7.1
*
* @param string $label Optional. Label for link text.
* @param int $max_page Optional. Max page.
* @return string|null
*/
function get_next_comments_link( $label = '', $max_page = 0 ) {
global $wp_query;
if ( !is_singular() || !get_option('page_comments') )
return;
$page = get_query_var('cpage');
$nextpage = intval($page) + 1;
if ( empty($max_page) )
$max_page = $wp_query->max_num_comment_pages;
if ( empty($max_page) )
$max_page = get_comment_pages_count();
if ( $nextpage > $max_page )
return;
if ( empty($label) )
$label = __('Newer Comments »');
return ''. preg_replace('/&([^#])(?![a-z]{1,8};)/', '&$1', $label) .'';
}
/**
* Display the link to next comments pages.
*
* @since 2.7.0
*
* @param string $label Optional. Label for link text.
* @param int $max_page Optional. Max page.
*/
function next_comments_link( $label = '', $max_page = 0 ) {
echo get_next_comments_link( $label, $max_page );
}
/**
* Return the previous comments page link.
*
* @since 2.7.1
*
* @param string $label Optional. Label for comments link text.
* @return string|null
*/
function get_previous_comments_link( $label = '' ) {
if ( !is_singular() || !get_option('page_comments') )
return;
$page = get_query_var('cpage');
if ( intval($page) <= 1 )
return;
$prevpage = intval($page) - 1;
if ( empty($label) )
$label = __('« Older Comments');
return '' . preg_replace('/&([^#])(?![a-z]{1,8};)/', '&$1', $label) .'';
}
/**
* Display the previous comments page link.
*
* @since 2.7.0
*
* @param string $label Optional. Label for comments link text.
*/
function previous_comments_link( $label = '' ) {
echo get_previous_comments_link( $label );
}
/**
* Create pagination links for the comments on the current post.
*
* @see paginate_links()
* @since 2.7.0
*
* @param string|array $args Optional args. See paginate_links.
* @return string Markup for pagination links.
*/
function paginate_comments_links($args = array()) {
global $wp_query, $wp_rewrite;
if ( !is_singular() || !get_option('page_comments') )
return;
$page = get_query_var('cpage');
if ( !$page )
$page = 1;
$max_page = get_comment_pages_count();
$defaults = array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'total' => $max_page,
'current' => $page,
'echo' => true,
'add_fragment' => '#comments'
);
if ( $wp_rewrite->using_permalinks() )
$defaults['base'] = user_trailingslashit(trailingslashit(get_permalink()) . 'comment-page-%#%', 'commentpaged');
$args = wp_parse_args( $args, $defaults );
$page_links = paginate_links( $args );
if ( $args['echo'] )
echo $page_links;
else
return $page_links;
}
/**
* Retrieve shortcut link.
*
* Use this in 'a' element 'href' attribute.
*
* @since 2.6.0
*
* @return string
*/
function get_shortcut_link() {
$link = "javascript:
var d=document,
w=window,
e=w.getSelection,
k=d.getSelection,
x=d.selection,
s=(e?e():(k)?k():(x?x.createRange().text:0)),
f='" . admin_url('press-this.php') . "',
l=d.location,
e=encodeURIComponent,
g=f+'?u='+e(l.href)+'&t='+e(d.title)+'&s='+e(s)+'&v=2';
function a(){
if(!w.open(g,'t','toolbar=0,resizable=0,scrollbars=1,status=1,width=720,height=570')){
l.href=g;
}
}";
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Firefox') !== false)
$link .= 'setTimeout(a,0);';
else
$link .= 'a();';
$link .= "void(0);";
$link = str_replace(array("\r", "\n", "\t"), '', $link);
return apply_filters('shortcut_link', $link);
}
/**
* Retrieve the site url.
*
* Returns the 'site_url' option with the appropriate protocol, 'https' if
* is_ssl() and 'http' otherwise. If $scheme is 'http' or 'https', is_ssl() is
* overridden.
*
* @package WordPress
* @since 2.6.0
*
* @param string $path Optional. Path relative to the site url.
* @param string $scheme Optional. Scheme to give the site url context. Currently 'http','https', 'login', 'login_post', or 'admin'.
* @return string Site url link with optional path appended.
*/
function site_url($path = '', $scheme = null) {
// should the list of allowed schemes be maintained elsewhere?
$orig_scheme = $scheme;
if ( !in_array($scheme, array('http', 'https')) ) {
if ( ( 'login_post' == $scheme || 'rpc' == $scheme ) && ( force_ssl_login() || force_ssl_admin() ) )
$scheme = 'https';
elseif ( ('login' == $scheme) && ( force_ssl_admin() ) )
$scheme = 'https';
elseif ( ('admin' == $scheme) && force_ssl_admin() )
$scheme = 'https';
else
$scheme = ( is_ssl() ? 'https' : 'http' );
}
$url = str_replace( 'http://', "{$scheme}://", get_option('siteurl') );
if ( !empty($path) && is_string($path) && strpos($path, '..') === false )
$url .= '/' . ltrim($path, '/');
return apply_filters('site_url', $url, $path, $orig_scheme);
}
/**
* Retrieve the url to the admin area.
*
* @package WordPress
* @since 2.6.0
*
* @param string $path Optional path relative to the admin url
* @return string Admin url link with optional path appended
*/
function admin_url($path = '') {
$url = site_url('wp-admin/', 'admin');
if ( !empty($path) && is_string($path) && strpos($path, '..') === false )
$url .= ltrim($path, '/');
return apply_filters('admin_url', $url, $path);
}
/**
* Retrieve the url to the includes directory.
*
* @package WordPress
* @since 2.6.0
*
* @param string $path Optional. Path relative to the includes url.
* @return string Includes url link with optional path appended.
*/
function includes_url($path = '') {
$url = site_url() . '/' . WPINC . '/';
if ( !empty($path) && is_string($path) && strpos($path, '..') === false )
$url .= ltrim($path, '/');
return apply_filters('includes_url', $url, $path);
}
/**
* Retrieve the url to the content directory.
*
* @package WordPress
* @since 2.6.0
*
* @param string $path Optional. Path relative to the content url.
* @return string Content url link with optional path appended.
*/
function content_url($path = '') {
$scheme = ( is_ssl() ? 'https' : 'http' );
$url = WP_CONTENT_URL;
if ( 0 === strpos($url, 'http') ) {
if ( is_ssl() )
$url = str_replace( 'http://', "{$scheme}://", $url );
}
if ( !empty($path) && is_string($path) && strpos($path, '..') === false )
$url .= '/' . ltrim($path, '/');
return apply_filters('content_url', $url, $path);
}
/**
* Retrieve the url to the plugins directory or to a specific file within that directory.
* You can hardcode the plugin slug in $path or pass __FILE__ as a second argument to get the correct folder name.
*
* @package WordPress
* @since 2.6.0
*
* @param string $path Optional. Path relative to the plugins url.
* @param string $plugin Optional. The plugin file that you want to be relative to - i.e. pass in __FILE__
* @return string Plugins url link with optional path appended.
*/
function plugins_url($path = '', $plugin = '') {
$scheme = ( is_ssl() ? 'https' : 'http' );
if ( $plugin !== '' && preg_match('#^' . preg_quote(WPMU_PLUGIN_DIR . DIRECTORY_SEPARATOR, '#') . '#', $plugin) ) {
$url = WPMU_PLUGIN_URL;
} else {
$url = WP_PLUGIN_URL;
}
if ( 0 === strpos($url, 'http') ) {
if ( 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) && is_string($path) && strpos($path, '..') === false )
$url .= '/' . ltrim($path, '/');
return apply_filters('plugins_url', $url, $path, $plugin);
}
?>
larscapo/wp-includes/l10n.php 0000644 0041054 0041055 00000032126 11225447104 016616 0 ustar lacunaus lacunaus translate($text), $text, $domain);
}
function before_last_bar( $string ) {
$last_bar = strrpos( $string, '|' );
if ( false == $last_bar )
return $string;
else
return substr( $string, 0, $last_bar );
}
/**
* Translates $text like translate(), but assumes that the text
* contains a context after its last vertical bar.
*
* @since 2.5
* @uses translate()
*
* @param string $text Text to translate
* @param string $domain Domain to retrieve the translated text
* @return string Translated text
*/
function translate_with_context( $text, $domain = 'default' ) {
return before_last_bar( translate( $text, $domain ) );
}
function translate_with_gettext_context( $text, $context, $domain = 'default' ) {
$translations = &get_translations_for_domain( $domain );
return apply_filters( 'gettext_with_context', $translations->translate( $text, $context ), $text, $context, $domain);
}
/**
* Retrieves the translation of $text. If there is no translation, or
* the domain isn't loaded the original text is returned.
*
* @see translate() An alias of translate()
* @since 2.1.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
* @return string Translated text
*/
function __( $text, $domain = 'default' ) {
return translate( $text, $domain );
}
/**
* Retrieves the translation of $text and escapes it for safe use in an attribute.
* If there is no translation, or the domain isn't loaded the original text is returned.
*
* @see translate() An alias of translate()
* @see esc_attr()
* @since 2.8.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
* @return string Translated text
*/
function esc_attr__( $text, $domain = 'default' ) {
return esc_attr( translate( $text, $domain ) );
}
/**
* Retrieves the translation of $text and escapes it for safe use in HTML output.
* If there is no translation, or the domain isn't loaded the original text is returned.
*
* @see translate() An alias of translate()
* @see esc_html()
* @since 2.8.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
* @return string Translated text
*/
function esc_html__( $text, $domain = 'default' ) {
return esc_html( translate( $text, $domain ) );
}
/**
* Displays the returned translated text from translate().
*
* @see translate() Echoes returned translate() string
* @since 1.2.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
*/
function _e( $text, $domain = 'default' ) {
echo translate( $text, $domain );
}
/**
* Displays translated text that has been escaped for safe use in an attribute.
*
* @see translate() Echoes returned translate() string
* @see esc_attr()
* @since 2.8.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
*/
function esc_attr_e( $text, $domain = 'default' ) {
echo esc_attr( translate( $text, $domain ) );
}
/**
* Displays translated text that has been escaped for safe use in HTML output.
*
* @see translate() Echoes returned translate() string
* @see esc_html()
* @since 2.8.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
*/
function esc_html_e( $text, $domain = 'default' ) {
echo esc_html( translate( $text, $domain ) );
}
/**
* Retrieve translated string with vertical bar context
*
* Quite a few times, there will be collisions with similar translatable text
* found in more than two places but with different translated context.
*
* In order to use the separate contexts, the _c() function is used and the
* translatable string uses a pipe ('|') which has the context the string is in.
*
* When the translated string is returned, it is everything before the pipe, not
* including the pipe character. If there is no pipe in the translated text then
* everything is returned.
*
* @since 2.2.0
*
* @param string $text Text to translate
* @param string $domain Optional. Domain to retrieve the translated text
* @return string Translated context string without pipe
*/
function _c($text, $domain = 'default') {
return translate_with_context($text, $domain);
}
function _x( $single, $context, $domain = 'default' ) {
return translate_with_gettext_context( $single, $context, $domain );
}
function esc_attr_x( $single, $context, $domain = 'default' ) {
return esc_attr( translate_with_gettext_context( $single, $context, $domain ) );
}
function __ngettext() {
_deprecated_function( __FUNCTION__, '2.8', '_n()' );
$args = func_get_args();
return call_user_func_array('_n', $args);
}
/**
* Retrieve the plural or single form based on the amount.
*
* If the domain is not set in the $l10n list, then a comparison will be made
* and either $plural or $single parameters returned.
*
* If the domain does exist, then the parameters $single, $plural, and $number
* will first be passed to the domain's ngettext method. Then it will be passed
* to the 'ngettext' filter hook along with the same parameters. The expected
* type will be a string.
*
* @since 1.2.0
* @uses $l10n Gets list of domain translated string (gettext_reader) objects
* @uses apply_filters() Calls 'ngettext' hook on domains text returned,
* along with $single, $plural, and $number parameters. Expected to return string.
*
* @param string $single The text that will be used if $number is 1
* @param string $plural The text that will be used if $number is not 1
* @param int $number The number to compare against to use either $single or $plural
* @param string $domain Optional. The domain identifier the text should be retrieved in
* @return string Either $single or $plural translated text
*/
function _n($single, $plural, $number, $domain = 'default') {
$translations = &get_translations_for_domain( $domain );
$translation = $translations->translate_plural( $single, $plural, $number );
return apply_filters( 'ngettext', $translation, $single, $plural, $number, $domain );
}
/**
* @see _n() A version of _n(), which supports contexts --
* strips everything from the translation after the last bar
*
*/
function _nc( $single, $plural, $number, $domain = 'default' ) {
return before_last_bar( _n( $single, $plural, $number, $domain ) );
}
function _nx($single, $plural, $number, $context, $domain = 'default') {
$translations = &get_translations_for_domain( $domain );
$translation = $translations->translate_plural( $single, $plural, $number, $context );
return apply_filters( 'ngettext_with_context ', $translation, $single, $plural, $number, $context, $domain );
}
/**
* @deprecated Use _n_noop()
*/
function __ngettext_noop() {
_deprecated_function( __FUNCTION__, '2.8', '_n_noop()' );
$args = func_get_args();
return call_user_func_array('_n_noop', $args);
}
/**
* Register plural strings in POT file, but don't translate them.
*
* Used when you want do keep structures with translatable plural strings and
* use them later.
*
* Example:
* $messages = array(
* 'post' => _n_noop('%s post', '%s posts'),
* 'page' => _n_noop('%s pages', '%s pages')
* );
* ...
* $message = $messages[$type];
* $usable_text = sprintf(_n($message[0], $message[1], $count), $count);
*
* @since 2.5
* @param $single Single form to be i18ned
* @param $plural Plural form to be i18ned
* @return array array($single, $plural)
*/
function _n_noop( $single, $plural ) {
return array( $single, $plural );
}
/**
* Register plural strings with context in POT file, but don't translate them.
*
* @see _n_noop()
*/
function _nx_noop( $single, $plural, $context ) {
return array( $single, $plural, $context );
}
/**
* Loads a MO file into the domain $domain.
*
* If the domain already exists, the translations will be merged. If both
* sets have the same string, the translation from the original value will be taken.
*
* On success, the .mo file will be placed in the $l10n global by $domain
* and will be a MO object.
*
* @since 1.5.0
* @uses $l10n Gets list of domain translated string objects
*
* @param string $domain Unique identifier for retrieving translated strings
* @param string $mofile Path to the .mo file
* @return bool true on success, false on failure
*/
function load_textdomain($domain, $mofile) {
global $l10n;
if ( !is_readable( $mofile ) ) return false;
$mo = new MO();
if ( !$mo->import_from_file( $mofile ) ) return false;
if ( isset( $l10n[$domain] ) )
$mo->merge_with( $l10n[$domain] );
$l10n[$domain] = &$mo;
return true;
}
/**
* Loads default translated strings based on locale.
*
* Loads the .mo file in WP_LANG_DIR constant path from WordPress root. The
* translated (.mo) file is named based off of the locale.
*
* @since 1.5.0
*/
function load_default_textdomain() {
$locale = get_locale();
$mofile = WP_LANG_DIR . "/$locale.mo";
return load_textdomain('default', $mofile);
}
/**
* Loads the plugin's translated strings.
*
* If the path is not given then it will be the root of the plugin directory.
* The .mo file should be named based on the domain with a dash, and then the locale exactly.
*
* @since 1.5.0
*
* @param string $domain Unique identifier for retrieving translated strings
* @param string $abs_rel_path Optional. Relative path to ABSPATH of a folder,
* where the .mo file resides. Deprecated, but still functional until 2.7
* @param string $plugin_rel_path Optional. Relative path to WP_PLUGIN_DIR. This is the preferred argument to use. It takes precendence over $abs_rel_path
*/
function load_plugin_textdomain($domain, $abs_rel_path = false, $plugin_rel_path = false) {
$locale = get_locale();
if ( false !== $plugin_rel_path )
$path = WP_PLUGIN_DIR . '/' . trim( $plugin_rel_path, '/');
else if ( false !== $abs_rel_path)
$path = ABSPATH . trim( $abs_rel_path, '/');
else
$path = WP_PLUGIN_DIR;
$mofile = $path . '/'. $domain . '-' . $locale . '.mo';
return load_textdomain($domain, $mofile);
}
/**
* Loads the theme's translated strings.
*
* If the current locale exists as a .mo file in the theme's root directory, it
* will be included in the translated strings by the $domain.
*
* The .mo files must be named based on the locale exactly.
*
* @since 1.5.0
*
* @param string $domain Unique identifier for retrieving translated strings
*/
function load_theme_textdomain($domain, $path = false) {
$locale = get_locale();
$path = ( empty( $path ) ) ? get_template_directory() : $path;
$mofile = "$path/$locale.mo";
return load_textdomain($domain, $mofile);
}
/**
* Returns the Translations instance for a domain. If there isn't one,
* returns empty Translations instance.
*
* @param string $domain
* @return object A Translation instance
*/
function &get_translations_for_domain( $domain ) {
global $l10n;
$empty = &new Translations;
if ( isset($l10n[$domain]) )
return $l10n[$domain];
else
return $empty;
}
/**
* Translates role name. Since the role names are in the database and
* not in the source there are dummy gettext calls to get them into the POT
* file and this function properly translates them back.
*
* The before_last_bar() call is needed, because older installs keep the roles
* using the old context format: 'Role name|User role' and just skipping the
* content after the last bar is easier than fixing them in the DB. New installs
* won't suffer from that problem.
*/
function translate_user_role( $name ) {
return translate_with_gettext_context( before_last_bar($name), 'User role' );
}
?>
larscapo/wp-includes/default-widgets.php 0000644 0041054 0041055 00000111427 11225447104 021136 0 ustar lacunaus lacunaus 'widget_pages', 'description' => __( 'Your blog’s WordPress Pages') );
$this->WP_Widget('pages', __('Pages'), $widget_ops);
}
function widget( $args, $instance ) {
extract( $args );
$title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Pages' ) : $instance['title']);
$sortby = empty( $instance['sortby'] ) ? 'menu_order' : $instance['sortby'];
$exclude = empty( $instance['exclude'] ) ? '' : $instance['exclude'];
if ( $sortby == 'menu_order' )
$sortby = 'menu_order, post_title';
$out = wp_list_pages( apply_filters('widget_pages_args', array('title_li' => '', 'echo' => 0, 'sort_column' => $sortby, 'exclude' => $exclude) ) );
if ( !empty( $out ) ) {
echo $before_widget;
if ( $title)
echo $before_title . $title . $after_title;
?>
ID) )
return $current_user;
$current_user = new WP_User($id, $name);
setup_userdata($current_user->ID);
do_action('set_current_user');
return $current_user;
}
endif;
if ( !function_exists('wp_get_current_user') ) :
/**
* Retrieve the current user object.
*
* @since 2.0.3
*
* @return WP_User Current user WP_User object
*/
function wp_get_current_user() {
global $current_user;
get_currentuserinfo();
return $current_user;
}
endif;
if ( !function_exists('get_currentuserinfo') ) :
/**
* Populate global variables with information about the currently logged in user.
*
* Will set the current user, if the current user is not set. The current user
* will be set to the logged in person. If no user is logged in, then it will
* set the current user to 0, which is invalid and won't have any permissions.
*
* @since 0.71
* @uses $current_user Checks if the current user is set
* @uses wp_validate_auth_cookie() Retrieves current logged in user.
*
* @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set
*/
function get_currentuserinfo() {
global $current_user;
if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST )
return false;
if ( ! empty($current_user) )
return;
if ( ! $user = wp_validate_auth_cookie() ) {
if ( empty($_COOKIE[LOGGED_IN_COOKIE]) || !$user = wp_validate_auth_cookie($_COOKIE[LOGGED_IN_COOKIE], 'logged_in') ) {
wp_set_current_user(0);
return false;
}
}
wp_set_current_user($user);
}
endif;
if ( !function_exists('get_userdata') ) :
/**
* Retrieve user info by user ID.
*
* @since 0.71
*
* @param int $user_id User ID
* @return bool|object False on failure, User DB row object
*/
function get_userdata( $user_id ) {
global $wpdb;
$user_id = absint($user_id);
if ( $user_id == 0 )
return false;
$user = wp_cache_get($user_id, 'users');
if ( $user )
return $user;
if ( !$user = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->users WHERE ID = %d LIMIT 1", $user_id)) )
return false;
_fill_user($user);
return $user;
}
endif;
if ( !function_exists('get_user_by') ) :
/**
* Retrieve user info by a given field
*
* @since 2.8.0
*
* @param string $field The field to retrieve the user with. id | slug | email | login
* @param int|string $value A value for $field. A user ID, slug, email address, or login name.
* @return bool|object False on failure, User DB row object
*/
function get_user_by($field, $value) {
global $wpdb;
switch ($field) {
case 'id':
return get_userdata($value);
break;
case 'slug':
$user_id = wp_cache_get($value, 'userslugs');
$field = 'user_nicename';
break;
case 'email':
$user_id = wp_cache_get($value, 'useremail');
$field = 'user_email';
break;
case 'login':
$value = sanitize_user( $value );
$user_id = wp_cache_get($value, 'userlogins');
$field = 'user_login';
break;
default:
return false;
}
if ( false !== $user_id )
return get_userdata($user_id);
if ( !$user = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->users WHERE $field = %s", $value) ) )
return false;
_fill_user($user);
return $user;
}
endif;
if ( !function_exists('get_userdatabylogin') ) :
/**
* Retrieve user info by login name.
*
* @since 0.71
*
* @param string $user_login User's username
* @return bool|object False on failure, User DB row object
*/
function get_userdatabylogin($user_login) {
return get_user_by('login', $user_login);
}
endif;
if ( !function_exists('get_user_by_email') ) :
/**
* Retrieve user info by email.
*
* @since 2.5
*
* @param string $email User's email address
* @return bool|object False on failure, User DB row object
*/
function get_user_by_email($email) {
return get_user_by('email', $email);
}
endif;
if ( !function_exists( 'wp_mail' ) ) :
/**
* Send mail, similar to PHP's mail
*
* A true return value does not automatically mean that the user received the
* email successfully. It just only means that the method used was able to
* process the request without any errors.
*
* Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
* creating a from address like 'Name ' when both are set. If
* just 'wp_mail_from' is set, then just the email address will be used with no
* name.
*
* The default content type is 'text/plain' which does not allow using HTML.
* However, you can set the content type of the email by using the
* 'wp_mail_content_type' filter.
*
* The default charset is based on the charset used on the blog. The charset can
* be set using the 'wp_mail_charset' filter.
*
* @since 1.2.1
* @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters.
* @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address.
* @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name.
* @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type.
* @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset
* @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to
* phpmailer object.
* @uses PHPMailer
* @
*
* @param string $to Email address to send message
* @param string $subject Email subject
* @param string $message Message contents
* @param string|array $headers Optional. Additional headers.
* @param string|array $attachments Optional. Files to attach.
* @return bool Whether the email contents were sent successfully.
*/
function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
// Compact the input, apply the filters, and extract them back out
extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) );
if ( !is_array($attachments) )
$attachments = explode( "\n", $attachments );
global $phpmailer;
// (Re)create it, if it's gone missing
if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) {
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer();
}
// Headers
if ( empty( $headers ) ) {
$headers = array();
} else {
if ( !is_array( $headers ) ) {
// Explode the headers out, so this function can take both
// string headers and an array of headers.
$tempheaders = (array) explode( "\n", $headers );
} else {
$tempheaders = $headers;
}
$headers = array();
// If it's actually got contents
if ( !empty( $tempheaders ) ) {
// Iterate through the raw headers
foreach ( (array) $tempheaders as $header ) {
if ( strpos($header, ':') === false ) {
if ( false !== stripos( $header, 'boundary=' ) ) {
$parts = preg_split('/boundary=/i', trim( $header ) );
$boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
}
continue;
}
// Explode them out
list( $name, $content ) = explode( ':', trim( $header ), 2 );
// Cleanup crew
$name = trim( $name );
$content = trim( $content );
// Mainly for legacy -- process a From: header if it's there
if ( 'from' == strtolower($name) ) {
if ( strpos($content, '<' ) !== false ) {
// So... making my life hard again?
$from_name = substr( $content, 0, strpos( $content, '<' ) - 1 );
$from_name = str_replace( '"', '', $from_name );
$from_name = trim( $from_name );
$from_email = substr( $content, strpos( $content, '<' ) + 1 );
$from_email = str_replace( '>', '', $from_email );
$from_email = trim( $from_email );
} else {
$from_email = trim( $content );
}
} elseif ( 'content-type' == strtolower($name) ) {
if ( strpos( $content,';' ) !== false ) {
list( $type, $charset ) = explode( ';', $content );
$content_type = trim( $type );
if ( false !== stripos( $charset, 'charset=' ) ) {
$charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) );
} elseif ( false !== stripos( $charset, 'boundary=' ) ) {
$boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) );
$charset = '';
}
} else {
$content_type = trim( $content );
}
} elseif ( 'cc' == strtolower($name) ) {
$cc = explode(",", $content);
} elseif ( 'bcc' == strtolower($name) ) {
$bcc = explode(",", $content);
} else {
// Add it to our grand headers array
$headers[trim( $name )] = trim( $content );
}
}
}
}
// Empty out the values that may be set
$phpmailer->ClearAddresses();
$phpmailer->ClearAllRecipients();
$phpmailer->ClearAttachments();
$phpmailer->ClearBCCs();
$phpmailer->ClearCCs();
$phpmailer->ClearCustomHeaders();
$phpmailer->ClearReplyTos();
// From email and name
// If we don't have a name from the input headers
if ( !isset( $from_name ) ) {
$from_name = 'WordPress';
}
/* If we don't have an email from the input headers default to wordpress@$sitename
* Some hosts will block outgoing mail from this address if it doesn't exist but
* there's no easy alternative. Defaulting to admin_email might appear to be another
* option but some hosts may refuse to relay mail from an unknown domain. See
* http://trac.wordpress.org/ticket/5007.
*/
if ( !isset( $from_email ) ) {
// Get the site domain and get rid of www.
$sitename = strtolower( $_SERVER['SERVER_NAME'] );
if ( substr( $sitename, 0, 4 ) == 'www.' ) {
$sitename = substr( $sitename, 4 );
}
$from_email = 'wordpress@' . $sitename;
}
// Plugin authors can override the potentially troublesome default
$phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
$phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
// Set destination address
$phpmailer->AddAddress( $to );
// Set mail's subject and body
$phpmailer->Subject = $subject;
$phpmailer->Body = $message;
// Add any CC and BCC recipients
if ( !empty($cc) ) {
foreach ( (array) $cc as $recipient ) {
$phpmailer->AddCc( trim($recipient) );
}
}
if ( !empty($bcc) ) {
foreach ( (array) $bcc as $recipient) {
$phpmailer->AddBcc( trim($recipient) );
}
}
// Set to use PHP's mail()
$phpmailer->IsMail();
// Set Content-Type and charset
// If we don't have a content-type from the input headers
if ( !isset( $content_type ) ) {
$content_type = 'text/plain';
}
$content_type = apply_filters( 'wp_mail_content_type', $content_type );
$phpmailer->ContentType = $content_type;
// Set whether it's plaintext or not, depending on $content_type
if ( $content_type == 'text/html' ) {
$phpmailer->IsHTML( true );
}
// If we don't have a charset from the input headers
if ( !isset( $charset ) ) {
$charset = get_bloginfo( 'charset' );
}
// Set the content-type and charset
$phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
// Set custom headers
if ( !empty( $headers ) ) {
foreach( (array) $headers as $name => $content ) {
$phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
}
if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) ) {
$phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
}
}
if ( !empty( $attachments ) ) {
foreach ( $attachments as $attachment ) {
$phpmailer->AddAttachment($attachment);
}
}
do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
// Send!
$result = @$phpmailer->Send();
return $result;
}
endif;
if ( !function_exists('wp_authenticate') ) :
/**
* Checks a user's login information and logs them in if it checks out.
*
* @since 2.5.0
*
* @param string $username User's username
* @param string $password User's password
* @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object.
*/
function wp_authenticate($username, $password) {
$username = sanitize_user($username);
$password = trim($password);
$user = apply_filters('authenticate', null, $username, $password);
if ( $user == null ) {
// TODO what should the error message be? (Or would these even happen?)
// Only needed if all authentication handlers fail to return anything.
$user = new WP_Error('authentication_failed', __('ERROR: Invalid username or incorrect password.'));
}
$ignore_codes = array('empty_username', 'empty_password');
if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
do_action('wp_login_failed', $username);
}
return $user;
}
endif;
if ( !function_exists('wp_logout') ) :
/**
* Log the current user out.
*
* @since 2.5.0
*/
function wp_logout() {
wp_clear_auth_cookie();
do_action('wp_logout');
}
endif;
if ( !function_exists('wp_validate_auth_cookie') ) :
/**
* Validates authentication cookie.
*
* The checks include making sure that the authentication cookie is set and
* pulling in the contents (if $cookie is not used).
*
* Makes sure the cookie is not expired. Verifies the hash in cookie is what is
* should be and compares the two.
*
* @since 2.5
*
* @param string $cookie Optional. If used, will validate contents instead of cookie's
* @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
* @return bool|int False if invalid cookie, User ID if valid.
*/
function wp_validate_auth_cookie($cookie = '', $scheme = '') {
if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
do_action('auth_cookie_malformed', $cookie, $scheme);
return false;
}
extract($cookie_elements, EXTR_OVERWRITE);
$expired = $expiration;
// Allow a grace period for POST and AJAX requests
if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] )
$expired += 3600;
// Quick check to see if an honest cookie has expired
if ( $expired < time() ) {
do_action('auth_cookie_expired', $cookie_elements);
return false;
}
$user = get_userdatabylogin($username);
if ( ! $user ) {
do_action('auth_cookie_bad_username', $cookie_elements);
return false;
}
$pass_frag = substr($user->user_pass, 8, 4);
$key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme);
$hash = hash_hmac('md5', $username . '|' . $expiration, $key);
if ( $hmac != $hash ) {
do_action('auth_cookie_bad_hash', $cookie_elements);
return false;
}
do_action('auth_cookie_valid', $cookie_elements, $user);
return $user->ID;
}
endif;
if ( !function_exists('wp_generate_auth_cookie') ) :
/**
* Generate authentication cookie contents.
*
* @since 2.5
* @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID
* and expiration of cookie.
*
* @param int $user_id User ID
* @param int $expiration Cookie expiration in seconds
* @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
* @return string Authentication cookie contents
*/
function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') {
$user = get_userdata($user_id);
$pass_frag = substr($user->user_pass, 8, 4);
$key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme);
$hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key);
$cookie = $user->user_login . '|' . $expiration . '|' . $hash;
return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme);
}
endif;
if ( !function_exists('wp_parse_auth_cookie') ) :
/**
* Parse a cookie into its components
*
* @since 2.7
*
* @param string $cookie
* @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
* @return array Authentication cookie components
*/
function wp_parse_auth_cookie($cookie = '', $scheme = '') {
if ( empty($cookie) ) {
switch ($scheme){
case 'auth':
$cookie_name = AUTH_COOKIE;
break;
case 'secure_auth':
$cookie_name = SECURE_AUTH_COOKIE;
break;
case "logged_in":
$cookie_name = LOGGED_IN_COOKIE;
break;
default:
if ( is_ssl() ) {
$cookie_name = SECURE_AUTH_COOKIE;
$scheme = 'secure_auth';
} else {
$cookie_name = AUTH_COOKIE;
$scheme = 'auth';
}
}
if ( empty($_COOKIE[$cookie_name]) )
return false;
$cookie = $_COOKIE[$cookie_name];
}
$cookie_elements = explode('|', $cookie);
if ( count($cookie_elements) != 3 )
return false;
list($username, $expiration, $hmac) = $cookie_elements;
return compact('username', 'expiration', 'hmac', 'scheme');
}
endif;
if ( !function_exists('wp_set_auth_cookie') ) :
/**
* Sets the authentication cookies based User ID.
*
* The $remember parameter increases the time that the cookie will be kept. The
* default the cookie is kept without remembering is two days. When $remember is
* set, the cookies will be kept for 14 days or two weeks.
*
* @since 2.5
*
* @param int $user_id User ID
* @param bool $remember Whether to remember the user or not
*/
function wp_set_auth_cookie($user_id, $remember = false, $secure = '') {
if ( $remember ) {
$expiration = $expire = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, $remember);
} else {
$expiration = time() + apply_filters('auth_cookie_expiration', 172800, $user_id, $remember);
$expire = 0;
}
if ( '' === $secure )
$secure = is_ssl() ? true : false;
if ( $secure ) {
$auth_cookie_name = SECURE_AUTH_COOKIE;
$scheme = 'secure_auth';
} else {
$auth_cookie_name = AUTH_COOKIE;
$scheme = 'auth';
}
$auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme);
$logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in');
do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme);
do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in');
// Set httponly if the php version is >= 5.2.0
if ( version_compare(phpversion(), '5.2.0', 'ge') ) {
setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, false, true);
if ( COOKIEPATH != SITECOOKIEPATH )
setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, false, true);
} else {
$cookie_domain = COOKIE_DOMAIN;
if ( !empty($cookie_domain) )
$cookie_domain .= '; HttpOnly';
setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, $cookie_domain, $secure);
setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, $cookie_domain, $secure);
setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, $cookie_domain);
if ( COOKIEPATH != SITECOOKIEPATH )
setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, $cookie_domain);
}
}
endif;
if ( !function_exists('wp_clear_auth_cookie') ) :
/**
* Removes all of the cookies associated with authentication.
*
* @since 2.5
*/
function wp_clear_auth_cookie() {
do_action('clear_auth_cookie');
setcookie(AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, ADMIN_COOKIE_PATH, COOKIE_DOMAIN);
setcookie(AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN);
setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(LOGGED_IN_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
// Old cookies
setcookie(AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(SECURE_AUTH_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
// Even older cookies
setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(USER_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
}
endif;
if ( !function_exists('is_user_logged_in') ) :
/**
* Checks if the current visitor is a logged in user.
*
* @since 2.0.0
*
* @return bool True if user is logged in, false if not logged in.
*/
function is_user_logged_in() {
$user = wp_get_current_user();
if ( $user->id == 0 )
return false;
return true;
}
endif;
if ( !function_exists('auth_redirect') ) :
/**
* Checks if a user is logged in, if not it redirects them to the login page.
*
* @since 1.5
*/
function auth_redirect() {
// Checks if a user is logged in, if not redirects them to the login page
if ( is_ssl() || force_ssl_admin() )
$secure = true;
else
$secure = false;
// If https is required and request is http, redirect
if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
exit();
} else {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
}
if ( $user_id = wp_validate_auth_cookie() ) {
do_action('auth_redirect', $user_id);
// If the user wants ssl but the session is not ssl, redirect.
if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
if ( 0 === strpos($_SERVER['REQUEST_URI'], 'http') ) {
wp_redirect(preg_replace('|^http://|', 'https://', $_SERVER['REQUEST_URI']));
exit();
} else {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
}
return; // The cookie is good so we're done
}
// The cookie is no good so force login
nocache_headers();
if ( is_ssl() )
$proto = 'https://';
else
$proto = 'http://';
$redirect = ( strpos($_SERVER['REQUEST_URI'], '/options.php') && wp_get_referer() ) ? wp_get_referer() : $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$login_url = wp_login_url($redirect);
wp_redirect($login_url);
exit();
}
endif;
if ( !function_exists('check_admin_referer') ) :
/**
* Makes sure that a user was referred from another admin page.
*
* To avoid security exploits.
*
* @since 1.2.0
* @uses do_action() Calls 'check_admin_referer' on $action.
*
* @param string $action Action nonce
* @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
*/
function check_admin_referer($action = -1, $query_arg = '_wpnonce') {
$adminurl = strtolower(admin_url());
$referer = strtolower(wp_get_referer());
$result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
if ( !$result && !(-1 == $action && strpos($referer, $adminurl) !== false) ) {
wp_nonce_ays($action);
die();
}
do_action('check_admin_referer', $action, $result);
return $result;
}endif;
if ( !function_exists('check_ajax_referer') ) :
/**
* Verifies the AJAX request to prevent processing requests external of the blog.
*
* @since 2.0.3
*
* @param string $action Action nonce
* @param string $query_arg where to look for nonce in $_REQUEST (since 2.5)
*/
function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
if ( $query_arg )
$nonce = $_REQUEST[$query_arg];
else
$nonce = $_REQUEST['_ajax_nonce'] ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce'];
$result = wp_verify_nonce( $nonce, $action );
if ( $die && false == $result )
die('-1');
do_action('check_ajax_referer', $action, $result);
return $result;
}
endif;
if ( !function_exists('wp_redirect') ) :
/**
* Redirects to another page, with a workaround for the IIS Set-Cookie bug.
*
* @link http://support.microsoft.com/kb/q176113/
* @since 1.5.1
* @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
*
* @param string $location The path to redirect to
* @param int $status Status code to use
* @return bool False if $location is not set
*/
function wp_redirect($location, $status = 302) {
global $is_IIS;
$location = apply_filters('wp_redirect', $location, $status);
$status = apply_filters('wp_redirect_status', $status, $location);
if ( !$location ) // allows the wp_redirect filter to cancel a redirect
return false;
$location = wp_sanitize_redirect($location);
if ( $is_IIS ) {
header("Refresh: 0;url=$location");
} else {
if ( php_sapi_name() != 'cgi-fcgi' )
status_header($status); // This causes problems on IIS and some FastCGI setups
header("Location: $location");
}
}
endif;
if ( !function_exists('wp_sanitize_redirect') ) :
/**
* Sanitizes a URL for use in a redirect.
*
* @since 2.3
*
* @return string redirect-sanitized URL
**/
function wp_sanitize_redirect($location) {
$location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location);
$location = wp_kses_no_null($location);
// remove %0d and %0a from location
$strip = array('%0d', '%0a', '%0D', '%0A');
$location = _deep_replace($strip, $location);
return $location;
}
endif;
if ( !function_exists('wp_safe_redirect') ) :
/**
* Performs a safe (local) redirect, using wp_redirect().
*
* Checks whether the $location is using an allowed host, if it has an absolute
* path. A plugin can therefore set or remove allowed host(s) to or from the
* list.
*
* If the host is not allowed, then the redirect is to wp-admin on the siteurl
* instead. This prevents malicious redirects which redirect to another host,
* but only used in a few places.
*
* @since 2.3
* @uses wp_validate_redirect() To validate the redirect is to an allowed host.
*
* @return void Does not return anything
**/
function wp_safe_redirect($location, $status = 302) {
// Need to look at the URL the way it will end up in wp_redirect()
$location = wp_sanitize_redirect($location);
$location = wp_validate_redirect($location, admin_url());
wp_redirect($location, $status);
}
endif;
if ( !function_exists('wp_validate_redirect') ) :
/**
* Validates a URL for use in a redirect.
*
* Checks whether the $location is using an allowed host, if it has an absolute
* path. A plugin can therefore set or remove allowed host(s) to or from the
* list.
*
* If the host is not allowed, then the redirect is to $default supplied
*
* @since 2.8.1
* @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing
* WordPress host string and $location host string.
*
* @param string $location The redirect to validate
* @param string $default The value to return is $location is not allowed
* @return string redirect-sanitized URL
**/
function wp_validate_redirect($location, $default = '') {
// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
if ( substr($location, 0, 2) == '//' )
$location = 'http:' . $location;
// In php 5 parse_url may fail if the URL query part contains http://, bug #38143
$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
$lp = parse_url($test);
$wpp = parse_url(get_option('home'));
$allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '');
if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
$location = $default;
return $location;
}
endif;
if ( ! function_exists('wp_notify_postauthor') ) :
/**
* Notify an author of a comment/trackback/pingback to one of their posts.
*
* @since 1.0.0
*
* @param int $comment_id Comment ID
* @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback'
* @return bool False if user email does not exist. True on completion.
*/
function wp_notify_postauthor($comment_id, $comment_type='') {
$comment = get_comment($comment_id);
$post = get_post($comment->comment_post_ID);
$user = get_userdata( $post->post_author );
$current_user = wp_get_current_user();
if ( $comment->user_id == $post->post_author ) return false; // The author moderated a comment on his own post
if ('' == $user->user_email) return false; // If there's no email to send the comment to
$comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
$blogname = get_option('blogname');
if ( empty( $comment_type ) ) $comment_type = 'comment';
if ('comment' == $comment_type) {
/* translators: 1: post id, 2: post title */
$notify_message = sprintf( __('New comment on your post #%1$s "%2$s"'), $comment->comment_post_ID, $post->post_title ) . "\r\n";
/* translators: 1: comment author, 2: author IP, 3: author domain */
$notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= sprintf( __('Whois : http://ws.arin.net/cgi-bin/whois.pl?queryinput=%s'), $comment->comment_author_IP ) . "\r\n";
$notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
$notify_message .= __('You can see all comments on this post here: ') . "\r\n";
/* translators: 1: blog name, 2: post title */
$subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
} elseif ('trackback' == $comment_type) {
/* translators: 1: post id, 2: post title */
$notify_message = sprintf( __('New trackback on your post #%1$s "%2$s"'), $comment->comment_post_ID, $post->post_title ) . "\r\n";
/* translators: 1: website name, 2: author IP, 3: author domain */
$notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
$notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n";
/* translators: 1: blog name, 2: post title */
$subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
} elseif ('pingback' == $comment_type) {
/* translators: 1: post id, 2: post title */
$notify_message = sprintf( __('New pingback on your post #%1$s "%2$s"'), $comment->comment_post_ID, $post->post_title ) . "\r\n";
/* translators: 1: comment author, 2: author IP, 3: author domain */
$notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n";
$notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n";
/* translators: 1: blog name, 2: post title */
$subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
}
$notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
$notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=cdc&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=cdc&dt=spam&c=$comment_id") ) . "\r\n";
$wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
if ( '' == $comment->comment_author ) {
$from = "From: \"$blogname\" <$wp_email>";
if ( '' != $comment->comment_author_email )
$reply_to = "Reply-To: $comment->comment_author_email";
} else {
$from = "From: \"$comment->comment_author\" <$wp_email>";
if ( '' != $comment->comment_author_email )
$reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
}
$message_headers = "$from\n"
. "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
if ( isset($reply_to) )
$message_headers .= $reply_to . "\n";
$notify_message = apply_filters('comment_notification_text', $notify_message, $comment_id);
$subject = apply_filters('comment_notification_subject', $subject, $comment_id);
$message_headers = apply_filters('comment_notification_headers', $message_headers, $comment_id);
@wp_mail($user->user_email, $subject, $notify_message, $message_headers);
return true;
}
endif;
if ( !function_exists('wp_notify_moderator') ) :
/**
* Notifies the moderator of the blog about a new comment that is awaiting approval.
*
* @since 1.0
* @uses $wpdb
*
* @param int $comment_id Comment ID
* @return bool Always returns true
*/
function wp_notify_moderator($comment_id) {
global $wpdb;
if( get_option( "moderation_notify" ) == 0 )
return true;
$comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID=%d LIMIT 1", $comment_id));
$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID=%d LIMIT 1", $comment->comment_post_ID));
$comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
$comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
switch ($comment->comment_type)
{
case 'trackback':
$notify_message = sprintf( __('A new trackback on the post #%1$s "%2$s" is waiting for your approval'), $post->ID, $post->post_title ) . "\r\n";
$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
$notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
break;
case 'pingback':
$notify_message = sprintf( __('A new pingback on the post #%1$s "%2$s" is waiting for your approval'), $post->ID, $post->post_title ) . "\r\n";
$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
$notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
break;
default: //Comments
$notify_message = sprintf( __('A new comment on the post #%1$s "%2$s" is waiting for your approval'), $post->ID, $post->post_title ) . "\r\n";
$notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
$notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
$notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n";
$notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n";
$notify_message .= sprintf( __('Whois : http://ws.arin.net/cgi-bin/whois.pl?queryinput=%s'), $comment->comment_author_IP ) . "\r\n";
$notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
break;
}
$notify_message .= sprintf( __('Approve it: %s'), admin_url("comment.php?action=mac&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=cdc&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=cdc&dt=spam&c=$comment_id") ) . "\r\n";
$notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
$notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
$subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), get_option('blogname'), $post->post_title );
$admin_email = get_option('admin_email');
$message_headers = '';
$notify_message = apply_filters('comment_moderation_text', $notify_message, $comment_id);
$subject = apply_filters('comment_moderation_subject', $subject, $comment_id);
$message_headers = apply_filters('comment_moderation_headers', $message_headers);
@wp_mail($admin_email, $subject, $notify_message, $message_headers);
return true;
}
endif;
if ( !function_exists('wp_password_change_notification') ) :
/**
* Notify the blog admin of a user changing password, normally via email.
*
* @since 2.7
*
* @param object $user User Object
*/
function wp_password_change_notification(&$user) {
// send a copy of password change notification to the admin
// but check to see if it's the admin whose password we're changing, and skip this
if ( $user->user_email != get_option('admin_email') ) {
$message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), get_option('blogname')), $message);
}
}
endif;
if ( !function_exists('wp_new_user_notification') ) :
/**
* Notify the blog admin of a new user, normally via email.
*
* @since 2.0
*
* @param int $user_id User ID
* @param string $plaintext_pass Optional. The user's plaintext password
*/
function wp_new_user_notification($user_id, $plaintext_pass = '') {
$user = new WP_User($user_id);
$user_login = stripslashes($user->user_login);
$user_email = stripslashes($user->user_email);
$message = sprintf(__('New user registration on your blog %s:'), get_option('blogname')) . "\r\n\r\n";
$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
$message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";
@wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message);
if ( empty($plaintext_pass) )
return;
$message = sprintf(__('Username: %s'), $user_login) . "\r\n";
$message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n";
$message .= wp_login_url() . "\r\n";
wp_mail($user_email, sprintf(__('[%s] Your username and password'), get_option('blogname')), $message);
}
endif;
if ( !function_exists('wp_nonce_tick') ) :
/**
* Get the time-dependent variable for nonce creation.
*
* A nonce has a lifespan of two ticks. Nonces in their second tick may be
* updated, e.g. by autosave.
*
* @since 2.5
*
* @return int
*/
function wp_nonce_tick() {
$nonce_life = apply_filters('nonce_life', 86400);
return ceil(time() / ( $nonce_life / 2 ));
}
endif;
if ( !function_exists('wp_verify_nonce') ) :
/**
* Verify that correct nonce was used with time limit.
*
* The user is given an amount of time to use the token, so therefore, since the
* UID and $action remain the same, the independent variable is the time.
*
* @since 2.0.3
*
* @param string $nonce Nonce that was used in the form to verify
* @param string|int $action Should give context to what is taking place and be the same when nonce was created.
* @return bool Whether the nonce check passed or failed.
*/
function wp_verify_nonce($nonce, $action = -1) {
$user = wp_get_current_user();
$uid = (int) $user->id;
$i = wp_nonce_tick();
// Nonce generated 0-12 hours ago
if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce )
return 1;
// Nonce generated 12-24 hours ago
if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce )
return 2;
// Invalid nonce
return false;
}
endif;
if ( !function_exists('wp_create_nonce') ) :
/**
* Creates a random, one time use token.
*
* @since 2.0.3
*
* @param string|int $action Scalar value to add context to the nonce.
* @return string The one use form token
*/
function wp_create_nonce($action = -1) {
$user = wp_get_current_user();
$uid = (int) $user->id;
$i = wp_nonce_tick();
return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10);
}
endif;
if ( !function_exists('wp_salt') ) :
/**
* Get salt to add to hashes to help prevent attacks.
*
* The secret key is located in two places: the database in case the secret key
* isn't defined in the second place, which is in the wp-config.php file. If you
* are going to set the secret key, then you must do so in the wp-config.php
* file.
*
* The secret key in the database is randomly generated and will be appended to
* the secret key that is in wp-config.php file in some instances. It is
* important to have the secret key defined or changed in wp-config.php.
*
* If you have installed WordPress 2.5 or later, then you will have the
* SECRET_KEY defined in the wp-config.php already. You will want to change the
* value in it because hackers will know what it is. If you have upgraded to
* WordPress 2.5 or later version from a version before WordPress 2.5, then you
* should add the constant to your wp-config.php file.
*
* Below is an example of how the SECRET_KEY constant is defined with a value.
* You must not copy the below example and paste into your wp-config.php. If you
* need an example, then you can have a
* {@link https://api.wordpress.org/secret-key/1.1/ secret key created} for you.
*
*
* define('SECRET_KEY', 'mAry1HadA15|\/|b17w55w1t3asSn09w');
*
*
* Salting passwords helps against tools which has stored hashed values of
* common dictionary strings. The added values makes it harder to crack if given
* salt string is not weak.
*
* @since 2.5
* @link https://api.wordpress.org/secret-key/1.1/ Create a Secret Key for wp-config.php
*
* @return string Salt value from either 'SECRET_KEY' or 'secret' option
*/
function wp_salt($scheme = 'auth') {
global $wp_default_secret_key;
$secret_key = '';
if ( defined('SECRET_KEY') && ('' != SECRET_KEY) && ( $wp_default_secret_key != SECRET_KEY) )
$secret_key = SECRET_KEY;
if ( 'auth' == $scheme ) {
if ( defined('AUTH_KEY') && ('' != AUTH_KEY) && ( $wp_default_secret_key != AUTH_KEY) )
$secret_key = AUTH_KEY;
if ( defined('AUTH_SALT') ) {
$salt = AUTH_SALT;
} elseif ( defined('SECRET_SALT') ) {
$salt = SECRET_SALT;
} else {
$salt = get_option('auth_salt');
if ( empty($salt) ) {
$salt = wp_generate_password(64);
update_option('auth_salt', $salt);
}
}
} elseif ( 'secure_auth' == $scheme ) {
if ( defined('SECURE_AUTH_KEY') && ('' != SECURE_AUTH_KEY) && ( $wp_default_secret_key != SECURE_AUTH_KEY) )
$secret_key = SECURE_AUTH_KEY;
if ( defined('SECURE_AUTH_SALT') ) {
$salt = SECURE_AUTH_SALT;
} else {
$salt = get_option('secure_auth_salt');
if ( empty($salt) ) {
$salt = wp_generate_password(64);
update_option('secure_auth_salt', $salt);
}
}
} elseif ( 'logged_in' == $scheme ) {
if ( defined('LOGGED_IN_KEY') && ('' != LOGGED_IN_KEY) && ( $wp_default_secret_key != LOGGED_IN_KEY) )
$secret_key = LOGGED_IN_KEY;
if ( defined('LOGGED_IN_SALT') ) {
$salt = LOGGED_IN_SALT;
} else {
$salt = get_option('logged_in_salt');
if ( empty($salt) ) {
$salt = wp_generate_password(64);
update_option('logged_in_salt', $salt);
}
}
} elseif ( 'nonce' == $scheme ) {
if ( defined('NONCE_KEY') && ('' != NONCE_KEY) && ( $wp_default_secret_key != NONCE_KEY) )
$secret_key = NONCE_KEY;
if ( defined('NONCE_SALT') ) {
$salt = NONCE_SALT;
} else {
$salt = get_option('nonce_salt');
if ( empty($salt) ) {
$salt = wp_generate_password(64);
update_option('nonce_salt', $salt);
}
}
} else {
// ensure each auth scheme has its own unique salt
$salt = hash_hmac('md5', $scheme, $secret_key);
}
return apply_filters('salt', $secret_key . $salt, $scheme);
}
endif;
if ( !function_exists('wp_hash') ) :
/**
* Get hash of given string.
*
* @since 2.0.3
* @uses wp_salt() Get WordPress salt
*
* @param string $data Plain text to hash
* @return string Hash of $data
*/
function wp_hash($data, $scheme = 'auth') {
$salt = wp_salt($scheme);
return hash_hmac('md5', $data, $salt);
}
endif;
if ( !function_exists('wp_hash_password') ) :
/**
* Create a hash (encrypt) of a plain text password.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5
* @global object $wp_hasher PHPass object
* @uses PasswordHash::HashPassword
*
* @param string $password Plain text user password to hash
* @return string The hash string of the password
*/
function wp_hash_password($password) {
global $wp_hasher;
if ( empty($wp_hasher) ) {
require_once( ABSPATH . 'wp-includes/class-phpass.php');
// By default, use the portable hash from phpass
$wp_hasher = new PasswordHash(8, TRUE);
}
return $wp_hasher->HashPassword($password);
}
endif;
if ( !function_exists('wp_check_password') ) :
/**
* Checks the plaintext password against the encrypted Password.
*
* Maintains compatibility between old version and the new cookie authentication
* protocol using PHPass library. The $hash parameter is the encrypted password
* and the function compares the plain text password when encypted similarly
* against the already encrypted password to see if they match.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5
* @global object $wp_hasher PHPass object used for checking the password
* against the $hash + $password
* @uses PasswordHash::CheckPassword
*
* @param string $password Plaintext user's password
* @param string $hash Hash of the user's password to check against.
* @return bool False, if the $password does not match the hashed password
*/
function wp_check_password($password, $hash, $user_id = '') {
global $wp_hasher;
// If the hash is still md5...
if ( strlen($hash) <= 32 ) {
$check = ( $hash == md5($password) );
if ( $check && $user_id ) {
// Rehash using new hash.
wp_set_password($password, $user_id);
$hash = wp_hash_password($password);
}
return apply_filters('check_password', $check, $password, $hash, $user_id);
}
// If the stored hash is longer than an MD5, presume the
// new style phpass portable hash.
if ( empty($wp_hasher) ) {
require_once( ABSPATH . 'wp-includes/class-phpass.php');
// By default, use the portable hash from phpass
$wp_hasher = new PasswordHash(8, TRUE);
}
$check = $wp_hasher->CheckPassword($password, $hash);
return apply_filters('check_password', $check, $password, $hash, $user_id);
}
endif;
if ( !function_exists('wp_generate_password') ) :
/**
* Generates a random password drawn from the defined set of characters.
*
* @since 2.5
*
* @param int $length The length of password to generate
* @param bool $special_chars Whether to include standard special characters
* @return string The random password
**/
function wp_generate_password($length = 12, $special_chars = true) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ( $special_chars )
$chars .= '!@#$%^&*()';
$password = '';
for ( $i = 0; $i < $length; $i++ )
$password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
return $password;
}
endif;
if ( !function_exists('wp_rand') ) :
/**
* Generates a random number
*
* @since 2.6.2
*
* @param int $min Lower limit for the generated number (optional, default is 0)
* @param int $max Upper limit for the generated number (optional, default is 4294967295)
* @return int A random number between min and max
*/
function wp_rand( $min = 0, $max = 0 ) {
global $rnd_value;
$seed = get_transient('random_seed');
// Reset $rnd_value after 14 uses
// 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
if ( strlen($rnd_value) < 8 ) {
$rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
$rnd_value .= sha1($rnd_value);
$rnd_value .= sha1($rnd_value . $seed);
$seed = md5($seed . $rnd_value);
set_transient('random_seed', $seed);
}
// Take the first 8 digits for our value
$value = substr($rnd_value, 0, 8);
// Strip the first eight, leaving the remainder for the next call to wp_rand().
$rnd_value = substr($rnd_value, 8);
$value = abs(hexdec($value));
// Reduce the value to be within the min - max range
// 4294967295 = 0xffffffff = max random number
if ( $max != 0 )
$value = $min + (($max - $min + 1) * ($value / (4294967295 + 1)));
return abs(intval($value));
}
endif;
if ( !function_exists('wp_set_password') ) :
/**
* Updates the user's password with a new encrypted one.
*
* For integration with other applications, this function can be overwritten to
* instead use the other package password checking algorithm.
*
* @since 2.5
* @uses $wpdb WordPress database object for queries
* @uses wp_hash_password() Used to encrypt the user's password before passing to the database
*
* @param string $password The plaintext new user password
* @param int $user_id User ID
*/
function wp_set_password( $password, $user_id ) {
global $wpdb;
$hash = wp_hash_password($password);
$wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
wp_cache_delete($user_id, 'users');
}
endif;
if ( !function_exists( 'get_avatar' ) ) :
/**
* Retrieve the avatar for a user who provided a user ID or email address.
*
* @since 2.5
* @param int|string|object $id_or_email A user ID, email address, or comment object
* @param int $size Size of the avatar image
* @param string $default URL to a default image to use if no avatar is available
* @param string $alt Alternate text to use in image tag. Defaults to blank
* @return string tag for the user's avatar
*/
function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
if ( ! get_option('show_avatars') )
return false;
if ( false === $alt)
$safe_alt = '';
else
$safe_alt = esc_attr( $alt );
if ( !is_numeric($size) )
$size = '96';
$email = '';
if ( is_numeric($id_or_email) ) {
$id = (int) $id_or_email;
$user = get_userdata($id);
if ( $user )
$email = $user->user_email;
} elseif ( is_object($id_or_email) ) {
if ( isset($id_or_email->comment_type) && '' != $id_or_email->comment_type && 'comment' != $id_or_email->comment_type )
return false; // No avatar for pingbacks or trackbacks
if ( !empty($id_or_email->user_id) ) {
$id = (int) $id_or_email->user_id;
$user = get_userdata($id);
if ( $user)
$email = $user->user_email;
} elseif ( !empty($id_or_email->comment_author_email) ) {
$email = $id_or_email->comment_author_email;
}
} else {
$email = $id_or_email;
}
if ( empty($default) ) {
$avatar_default = get_option('avatar_default');
if ( empty($avatar_default) )
$default = 'mystery';
else
$default = $avatar_default;
}
if ( is_ssl() )
$host = 'https://secure.gravatar.com';
else
$host = 'http://www.gravatar.com';
if ( 'mystery' == $default )
$default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
elseif ( 'blank' == $default )
$default = includes_url('images/blank.gif');
elseif ( !empty($email) && 'gravatar_default' == $default )
$default = '';
elseif ( 'gravatar_default' == $default )
$default = "$host/avatar/s={$size}";
elseif ( empty($email) )
$default = "$host/avatar/?d=$default&s={$size}";
elseif ( strpos($default, 'http://') === 0 )
$default = add_query_arg( 's', $size, $default );
if ( !empty($email) ) {
$out = "$host/avatar/";
$out .= md5( strtolower( $email ) );
$out .= '?s='.$size;
$out .= '&d=' . urlencode( $default );
$rating = get_option('avatar_rating');
if ( !empty( $rating ) )
$out .= "&r={$rating}";
$avatar = "";
} else {
$avatar = "";
}
return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt);
}
endif;
if ( !function_exists('wp_setcookie') ) :
/**
* Sets a cookie for a user who just logged in.
*
* @since 1.5
* @deprecated Use wp_set_auth_cookie()
* @see wp_set_auth_cookie()
*
* @param string $username The user's username
* @param string $password Optional. The user's password
* @param bool $already_md5 Optional. Whether the password has already been through MD5
* @param string $home Optional. Will be used instead of COOKIEPATH if set
* @param string $siteurl Optional. Will be used instead of SITECOOKIEPATH if set
* @param bool $remember Optional. Remember that the user is logged in
*/
function wp_setcookie($username, $password = '', $already_md5 = false, $home = '', $siteurl = '', $remember = false) {
_deprecated_function( __FUNCTION__, '2.5', 'wp_set_auth_cookie()' );
$user = get_userdatabylogin($username);
wp_set_auth_cookie($user->ID, $remember);
}
endif;
if ( !function_exists('wp_clearcookie') ) :
/**
* Clears the authentication cookie, logging the user out.
*
* @since 1.5
* @deprecated Use wp_clear_auth_cookie()
* @see wp_clear_auth_cookie()
*/
function wp_clearcookie() {
_deprecated_function( __FUNCTION__, '2.5', 'wp_clear_auth_cookie()' );
wp_clear_auth_cookie();
}
endif;
if ( !function_exists('wp_get_cookie_login') ):
/**
* Gets the user cookie login.
*
* This function is deprecated and should no longer be extended as it won't be
* used anywhere in WordPress. Also, plugins shouldn't use it either.
*
* @since 2.0.3
* @deprecated No alternative
*
* @return bool Always returns false
*/
function wp_get_cookie_login() {
_deprecated_function( __FUNCTION__, '2.5', '' );
return false;
}
endif;
if ( !function_exists('wp_login') ) :
/**
* Checks a users login information and logs them in if it checks out.
*
* Use the global $error to get the reason why the login failed. If the username
* is blank, no error will be set, so assume blank username on that case.
*
* Plugins extending this function should also provide the global $error and set
* what the error is, so that those checking the global for why there was a
* failure can utilize it later.
*
* @since 1.2.2
* @deprecated Use wp_signon()
* @global string $error Error when false is returned
*
* @param string $username User's username
* @param string $password User's password
* @param bool $deprecated Not used
* @return bool False on login failure, true on successful check
*/
function wp_login($username, $password, $deprecated = '') {
global $error;
$user = wp_authenticate($username, $password);
if ( ! is_wp_error($user) )
return true;
$error = $user->get_error_message();
return false;
}
endif;
if ( !function_exists( 'wp_text_diff' ) ) :
/**
* Displays a human readable HTML representation of the difference between two strings.
*
* The Diff is available for getting the changes between versions. The output is
* HTML, so the primary use is for displaying the changes. If the two strings
* are equivalent, then an empty string will be returned.
*
* The arguments supported and can be changed are listed below.
*
* 'title' : Default is an empty string. Titles the diff in a manner compatible
* with the output.
* 'title_left' : Default is an empty string. Change the HTML to the left of the
* title.
* 'title_right' : Default is an empty string. Change the HTML to the right of
* the title.
*
* @since 2.6
* @see wp_parse_args() Used to change defaults to user defined settings.
* @uses Text_Diff
* @uses WP_Text_Diff_Renderer_Table
*
* @param string $left_string "old" (left) version of string
* @param string $right_string "new" (right) version of string
* @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
* @return string Empty string if strings are equivalent or HTML with differences.
*/
function wp_text_diff( $left_string, $right_string, $args = null ) {
$defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
$args = wp_parse_args( $args, $defaults );
if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
require( ABSPATH . WPINC . '/wp-diff.php' );
$left_string = normalize_whitespace($left_string);
$right_string = normalize_whitespace($right_string);
$left_lines = split("\n", $left_string);
$right_lines = split("\n", $right_string);
$text_diff = new Text_Diff($left_lines, $right_lines);
$renderer = new WP_Text_Diff_Renderer_Table();
$diff = $renderer->render($text_diff);
if ( !$diff )
return '';
$r = "
\n";
$r .= "
";
if ( $args['title'] || $args['title_left'] || $args['title_right'] )
$r .= "";
if ( $args['title'] )
$r .= "
";
return $r;
}
endif;
?>
larscapo/wp-includes/widgets.php 0000644 0041054 0041055 00000115015 11225447104 017511 0 ustar lacunaus lacunaus ' . __('There are no options for this widget.') . '';
return 'noform';
}
// Functions you'll need to call.
/**
* PHP4 constructor
*/
function WP_Widget( $id_base = false, $name, $widget_options = array(), $control_options = array() ) {
$this->__construct( $id_base, $name, $widget_options, $control_options );
}
/**
* PHP5 constructor
*
* @param string $id_base Optional Base ID for the widget, lower case,
* if left empty a portion of the widget's class name will be used. Has to be unique.
* @param string $name Name for the widget displayed on the configuration page.
* @param array $widget_options Optional Passed to wp_register_sidebar_widget()
* - description: shown on the configuration page
* - classname
* @param array $control_options Optional Passed to wp_register_widget_control()
* - width: required if more than 250px
* - height: currently not used but may be needed in the future
*/
function __construct( $id_base = false, $name, $widget_options = array(), $control_options = array() ) {
$this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base);
$this->name = $name;
$this->option_name = 'widget_' . $this->id_base;
$this->widget_options = wp_parse_args( $widget_options, array('classname' => $this->option_name) );
$this->control_options = wp_parse_args( $control_options, array('id_base' => $this->id_base) );
}
/**
* Constructs name attributes for use in form() fields
*
* This function should be used in form() methods to create name attributes for fields to be saved by update()
*
* @param string $field_name Field name
* @return string Name attribute for $field_name
*/
function get_field_name($field_name) {
return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']';
}
/**
* Constructs id attributes for use in form() fields
*
* This function should be used in form() methods to create id attributes for fields to be saved by update()
*
* @param string $field_name Field name
* @return string ID attribute for $field_name
*/
function get_field_id($field_name) {
return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name;
}
// Private Functions. Don't worry about these.
function _register() {
$settings = $this->get_settings();
if ( empty($settings) ) {
// If there are none, we register the widget's existance with a
// generic template
$this->_set(1);
$this->_register_one();
} elseif ( is_array($settings) ) {
foreach ( array_keys($settings) as $number ) {
if ( is_numeric($number) ) {
$this->_set($number);
$this->_register_one($number);
}
}
}
}
function _set($number) {
$this->number = $number;
$this->id = $this->id_base . '-' . $number;
}
function _get_display_callback() {
return array(&$this, 'display_callback');
}
function _get_update_callback() {
return array(&$this, 'update_callback');
}
function _get_form_callback() {
return array(&$this, 'form_callback');
}
/** Generate the actual widget content.
* Just finds the instance and calls widget().
* Do NOT over-ride this function. */
function display_callback( $args, $widget_args = 1 ) {
if ( is_numeric($widget_args) )
$widget_args = array( 'number' => $widget_args );
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
$this->_set( $widget_args['number'] );
$instance = $this->get_settings();
if ( array_key_exists( $this->number, $instance ) ) {
$instance = $instance[$this->number];
// filters the widget's settings, return false to stop displaying the widget
$instance = apply_filters('widget_display_callback', $instance, $this, $args);
if ( false !== $instance )
$this->widget($args, $instance);
}
}
/** Deal with changed settings.
* Do NOT over-ride this function. */
function update_callback( $widget_args = 1 ) {
global $wp_registered_widgets;
if ( is_numeric($widget_args) )
$widget_args = array( 'number' => $widget_args );
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
$all_instances = $this->get_settings();
// We need to update the data
if ( $this->updated )
return;
$sidebars_widgets = wp_get_sidebars_widgets();
if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) {
// Delete the settings for this instance of the widget
if ( isset($_POST['the-widget-id']) )
$del_id = $_POST['the-widget-id'];
else
return;
if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) {
$number = $wp_registered_widgets[$del_id]['params'][0]['number'];
if ( $this->id_base . '-' . $number == $del_id )
unset($all_instances[$number]);
}
} else {
if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) {
$settings = $_POST['widget-' . $this->id_base];
} elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) {
$num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number'];
$settings = array( $num => array() );
} else {
return;
}
foreach ( $settings as $number => $new_instance ) {
$new_instance = stripslashes_deep($new_instance);
$this->_set($number);
$old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array();
$instance = $this->update($new_instance, $old_instance);
// filters the widget's settings before saving, return false to cancel saving (keep the old settings if updating)
$instance = apply_filters('widget_update_callback', $instance, $new_instance, $old_instance, $this);
if ( false !== $instance )
$all_instances[$number] = $instance;
break; // run only once
}
}
$this->save_settings($all_instances);
$this->updated = true;
}
/** Generate the control form.
* Do NOT over-ride this function. */
function form_callback( $widget_args = 1 ) {
if ( is_numeric($widget_args) )
$widget_args = array( 'number' => $widget_args );
$widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) );
$all_instances = $this->get_settings();
if ( -1 == $widget_args['number'] ) {
// We echo out a form where 'number' can be set later
$this->_set('__i__');
$instance = array();
} else {
$this->_set($widget_args['number']);
$instance = $all_instances[ $widget_args['number'] ];
}
// filters the widget admin form before displaying, return false to stop displaying it
$instance = apply_filters('widget_form_callback', $instance, $this);
$return = null;
if ( false !== $instance ) {
$return = $this->form($instance);
// add extra fields in the widget form - be sure to set $return to null if you add any
// if the widget has no form the text echoed from the default form method can be hidden using css
do_action_ref_array( 'in_widget_form', array(&$this, &$return, $instance) );
}
return $return;
}
/** Helper function: Registers a single instance. */
function _register_one($number = -1) {
wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) );
_register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) );
_register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) );
}
function save_settings($settings) {
$settings['_multiwidget'] = 1;
update_option( $this->option_name, $settings );
}
function get_settings() {
$settings = get_option($this->option_name);
if ( false === $settings && isset($this->alt_option_name) )
$settings = get_option($this->alt_option_name);
if ( !is_array($settings) )
$settings = array();
if ( !array_key_exists('_multiwidget', $settings) ) {
// old format, conver if single widget
$settings = wp_convert_widget_settings($this->id_base, $this->option_name, $settings);
}
unset($settings['_multiwidget'], $settings['__i__']);
return $settings;
}
}
/**
* Singleton that registers and instantiates WP_Widget classes.
*
* @package WordPress
* @subpackage Widgets
* @since 2.8
*/
class WP_Widget_Factory {
var $widgets = array();
function WP_Widget_Factory() {
add_action( 'widgets_init', array( &$this, '_register_widgets' ), 100 );
}
function register($widget_class) {
$this->widgets[$widget_class] = & new $widget_class();
}
function unregister($widget_class) {
if ( isset($this->widgets[$widget_class]) )
unset($this->widgets[$widget_class]);
}
function _register_widgets() {
global $wp_registered_widgets;
$keys = array_keys($this->widgets);
$registered = array_keys($wp_registered_widgets);
$registered = array_map('_get_widget_id_base', $registered);
foreach ( $keys as $key ) {
// don't register new widget if old widget with the same id is already registered
if ( in_array($this->widgets[$key]->id_base, $registered, true) ) {
unset($this->widgets[$key]);
continue;
}
$this->widgets[$key]->_register();
}
}
}
/* Global Variables */
/** @ignore */
global $wp_registered_sidebars, $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates;
/**
* Stores the sidebars, since many themes can have more than one.
*
* @global array $wp_registered_sidebars
* @since 2.2.0
*/
$wp_registered_sidebars = array();
/**
* Stores the registered widgets.
*
* @global array $wp_registered_widgets
* @since 2.2.0
*/
$wp_registered_widgets = array();
/**
* Stores the registered widget control (options).
*
* @global array $wp_registered_widget_controls
* @since 2.2.0
*/
$wp_registered_widget_controls = array();
$wp_registered_widget_updates = array();
/**
* Private
*/
$_wp_sidebars_widgets = array();
/**
* Private
*/
$_wp_deprecated_widgets_callbacks = array(
'wp_widget_pages',
'wp_widget_pages_control',
'wp_widget_calendar',
'wp_widget_calendar_control',
'wp_widget_archives',
'wp_widget_archives_control',
'wp_widget_links',
'wp_widget_meta',
'wp_widget_meta_control',
'wp_widget_search',
'wp_widget_recent_entries',
'wp_widget_recent_entries_control',
'wp_widget_tag_cloud',
'wp_widget_tag_cloud_control',
'wp_widget_categories',
'wp_widget_categories_control',
'wp_widget_text',
'wp_widget_text_control',
'wp_widget_rss',
'wp_widget_rss_control',
'wp_widget_recent_comments',
'wp_widget_recent_comments_control'
);
/* Template tags & API functions */
/**
* Register a widget
*
* Registers a WP_Widget widget
*
* @since 2.8.0
*
* @see WP_Widget
* @see WP_Widget_Factory
* @uses WP_Widget_Factory
*
* @param string $widget_class The name of a class that extends WP_Widget
*/
function register_widget($widget_class) {
global $wp_widget_factory;
$wp_widget_factory->register($widget_class);
}
/**
* Unregister a widget
*
* Unregisters a WP_Widget widget. Useful for unregistering default widgets.
* Run within a function hooked to the widgets_init action.
*
* @since 2.8.0
*
* @see WP_Widget
* @see WP_Widget_Factory
* @uses WP_Widget_Factory
*
* @param string $widget_class The name of a class that extends WP_Widget
*/
function unregister_widget($widget_class) {
global $wp_widget_factory;
$wp_widget_factory->unregister($widget_class);
}
/**
* Creates multiple sidebars.
*
* If you wanted to quickly create multiple sidebars for a theme or internally.
* This function will allow you to do so. If you don't pass the 'name' and/or
* 'id' in $args, then they will be built for you.
*
* The default for the name is "Sidebar #", with '#' being replaced with the
* number the sidebar is currently when greater than one. If first sidebar, the
* name will be just "Sidebar". The default for id is "sidebar-" followed by the
* number the sidebar creation is currently at.
*
* @since 2.2.0
*
* @see register_sidebar() The second parameter is documented by register_sidebar() and is the same here.
* @uses parse_str() Converts a string to an array to be used in the rest of the function.
* @uses register_sidebar() Sends single sidebar information [name, id] to this
* function to handle building the sidebar.
*
* @param int $number Number of sidebars to create.
* @param string|array $args Builds Sidebar based off of 'name' and 'id' values.
*/
function register_sidebars($number = 1, $args = array()) {
global $wp_registered_sidebars;
$number = (int) $number;
if ( is_string($args) )
parse_str($args, $args);
for ( $i=1; $i <= $number; $i++ ) {
$_args = $args;
if ( $number > 1 ) {
$_args['name'] = isset($args['name']) ? sprintf($args['name'], $i) : sprintf(__('Sidebar %d'), $i);
} else {
$_args['name'] = isset($args['name']) ? $args['name'] : __('Sidebar');
}
if (isset($args['id'])) {
$_args['id'] = $args['id'];
} else {
$n = count($wp_registered_sidebars);
do {
$n++;
$_args['id'] = "sidebar-$n";
} while (isset($wp_registered_sidebars[$_args['id']]));
}
register_sidebar($_args);
}
}
/**
* Builds the definition for a single sidebar and returns the ID.
*
* The $args parameter takes either a string or an array with 'name' and 'id'
* contained in either usage. It will be noted that the values will be applied
* to all sidebars, so if creating more than one, it will be advised to allow
* for WordPress to create the defaults for you.
*
* Example for string would be 'name=whatever;id=whatever1' and for
* the array it would be array(
* 'name' => 'whatever',
* 'id' => 'whatever1').
*
* name - The name of the sidebar, which presumably the title which will be
* displayed.
* id - The unique identifier by which the sidebar will be called by.
* before_widget - The content that will prepended to the widgets when they are
* displayed.
* after_widget - The content that will be appended to the widgets when they are
* displayed.
* before_title - The content that will be prepended to the title when displayed.
* after_title - the content that will be appended to the title when displayed.
*
* Content is assumed to be HTML and should be formatted as such, but
* doesn't have to be.
*
* @since 2.2.0
* @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID.
* @uses parse_str() Converts a string to an array to be used in the rest of the function.
* @usedby register_sidebars()
*
* @param string|array $args Builds Sidebar based off of 'name' and 'id' values
* @return string The sidebar id that was added.
*/
function register_sidebar($args = array()) {
global $wp_registered_sidebars;
if ( is_string($args) )
parse_str($args, $args);
$i = count($wp_registered_sidebars) + 1;
$defaults = array(
'name' => sprintf(__('Sidebar %d'), $i ),
'id' => "sidebar-$i",
'before_widget' => '
',
'after_widget' => "
\n",
'before_title' => '
',
'after_title' => "
\n",
);
$sidebar = array_merge($defaults, (array) $args);
$wp_registered_sidebars[$sidebar['id']] = $sidebar;
return $sidebar['id'];
}
/**
* Removes a sidebar from the list.
*
* @since 2.2.0
*
* @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID.
*
* @param string $name The ID of the sidebar when it was added.
*/
function unregister_sidebar( $name ) {
global $wp_registered_sidebars;
if ( isset( $wp_registered_sidebars[$name] ) )
unset( $wp_registered_sidebars[$name] );
}
/**
* Register widget for use in sidebars.
*
* The default widget option is 'classname' that can be override.
*
* The function can also be used to unregister widgets when $output_callback
* parameter is an empty string.
*
* @since 2.2.0
*
* @uses $wp_registered_widgets Uses stored registered widgets.
* @uses $wp_register_widget_defaults Retrieves widget defaults.
*
* @param int|string $id Widget ID.
* @param string $name Widget display title.
* @param callback $output_callback Run when widget is called.
* @param array|string Optional. $options Widget Options.
* @param mixed $params,... Widget parameters to add to widget.
* @return null Will return if $output_callback is empty after removing widget.
*/
function wp_register_sidebar_widget($id, $name, $output_callback, $options = array()) {
global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates, $_wp_deprecated_widgets_callbacks;
$id = strtolower($id);
if ( empty($output_callback) ) {
unset($wp_registered_widgets[$id]);
return;
}
$id_base = _get_widget_id_base($id);
if ( in_array($output_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($output_callback) ) {
if ( isset($wp_registered_widget_controls[$id]) )
unset($wp_registered_widget_controls[$id]);
if ( isset($wp_registered_widget_updates[$id_base]) )
unset($wp_registered_widget_updates[$id_base]);
return;
}
$defaults = array('classname' => $output_callback);
$options = wp_parse_args($options, $defaults);
$widget = array(
'name' => $name,
'id' => $id,
'callback' => $output_callback,
'params' => array_slice(func_get_args(), 4)
);
$widget = array_merge($widget, $options);
if ( is_callable($output_callback) && ( !isset($wp_registered_widgets[$id]) || did_action( 'widgets_init' ) ) )
$wp_registered_widgets[$id] = $widget;
}
/**
* Retrieve description for widget.
*
* When registering widgets, the options can also include 'description' that
* describes the widget for display on the widget administration panel or
* in the theme.
*
* @since 2.5.0
*
* @param int|string $id Widget ID.
* @return string Widget description, if available. Null on failure to retrieve description.
*/
function wp_widget_description( $id ) {
if ( !is_scalar($id) )
return;
global $wp_registered_widgets;
if ( isset($wp_registered_widgets[$id]['description']) )
return esc_html( $wp_registered_widgets[$id]['description'] );
}
/**
* Remove widget from sidebar.
*
* @since 2.2.0
*
* @param int|string $id Widget ID.
*/
function wp_unregister_sidebar_widget($id) {
wp_register_sidebar_widget($id, '', '');
wp_unregister_widget_control($id);
}
/**
* Registers widget control callback for customizing options.
*
* The options contains the 'height', 'width', and 'id_base' keys. The 'height'
* option is never used. The 'width' option is the width of the fully expanded
* control form, but try hard to use the default width. The 'id_base' is for
* multi-widgets (widgets which allow multiple instances such as the text
* widget), an id_base must be provided. The widget id will end up looking like
* {$id_base}-{$unique_number}.
*
* @since 2.2.0
*
* @param int|string $id Sidebar ID.
* @param string $name Sidebar display name.
* @param callback $control_callback Run when sidebar is displayed.
* @param array|string $options Optional. Widget options. See above long description.
* @param mixed $params,... Optional. Additional parameters to add to widget.
*/
function wp_register_widget_control($id, $name, $control_callback, $options = array()) {
global $wp_registered_widget_controls, $wp_registered_widget_updates, $wp_registered_widgets, $_wp_deprecated_widgets_callbacks;
$id = strtolower($id);
$id_base = _get_widget_id_base($id);
if ( empty($control_callback) ) {
unset($wp_registered_widget_controls[$id]);
unset($wp_registered_widget_updates[$id_base]);
return;
}
if ( in_array($control_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($control_callback) ) {
if ( isset($wp_registered_widgets[$id]) )
unset($wp_registered_widgets[$id]);
return;
}
if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) )
return;
$defaults = array('width' => 250, 'height' => 200 ); // height is never used
$options = wp_parse_args($options, $defaults);
$options['width'] = (int) $options['width'];
$options['height'] = (int) $options['height'];
$widget = array(
'name' => $name,
'id' => $id,
'callback' => $control_callback,
'params' => array_slice(func_get_args(), 4)
);
$widget = array_merge($widget, $options);
$wp_registered_widget_controls[$id] = $widget;
if ( isset($wp_registered_widget_updates[$id_base]) )
return;
if ( isset($widget['params'][0]['number']) )
$widget['params'][0]['number'] = -1;
unset($widget['width'], $widget['height'], $widget['name'], $widget['id']);
$wp_registered_widget_updates[$id_base] = $widget;
}
function _register_widget_update_callback($id_base, $update_callback, $options = array()) {
global $wp_registered_widget_updates;
if ( isset($wp_registered_widget_updates[$id_base]) ) {
if ( empty($update_callback) )
unset($wp_registered_widget_updates[$id_base]);
return;
}
$widget = array(
'callback' => $update_callback,
'params' => array_slice(func_get_args(), 3)
);
$widget = array_merge($widget, $options);
$wp_registered_widget_updates[$id_base] = $widget;
}
function _register_widget_form_callback($id, $name, $form_callback, $options = array()) {
global $wp_registered_widget_controls;
$id = strtolower($id);
if ( empty($form_callback) ) {
unset($wp_registered_widget_controls[$id]);
return;
}
if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) )
return;
$defaults = array('width' => 250, 'height' => 200 );
$options = wp_parse_args($options, $defaults);
$options['width'] = (int) $options['width'];
$options['height'] = (int) $options['height'];
$widget = array(
'name' => $name,
'id' => $id,
'callback' => $form_callback,
'params' => array_slice(func_get_args(), 4)
);
$widget = array_merge($widget, $options);
$wp_registered_widget_controls[$id] = $widget;
}
/**
* Remove control callback for widget.
*
* @since 2.2.0
* @uses wp_register_widget_control() Unregisters by using empty callback.
*
* @param int|string $id Widget ID.
*/
function wp_unregister_widget_control($id) {
return wp_register_widget_control($id, '', '');
}
/**
* Display dynamic sidebar.
*
* By default it displays the default sidebar or 'sidebar-1'. The 'sidebar-1' is
* not named by the theme, the actual name is '1', but 'sidebar-' is added to
* the registered sidebars for the name. If you named your sidebar 'after-post',
* then the parameter $index will still be 'after-post', but the lookup will be
* for 'sidebar-after-post'.
*
* It is confusing for the $index parameter, but just know that it should just
* work. When you register the sidebar in the theme, you will use the same name
* for this function or "Pay no heed to the man behind the curtain." Just accept
* it as an oddity of WordPress sidebar register and display.
*
* @since 2.2.0
*
* @param int|string $index Optional, default is 1. Name or ID of dynamic sidebar.
* @return bool True, if widget sidebar was found and called. False if not found or not called.
*/
function dynamic_sidebar($index = 1) {
global $wp_registered_sidebars, $wp_registered_widgets;
if ( is_int($index) ) {
$index = "sidebar-$index";
} else {
$index = sanitize_title($index);
foreach ( (array) $wp_registered_sidebars as $key => $value ) {
if ( sanitize_title($value['name']) == $index ) {
$index = $key;
break;
}
}
}
$sidebars_widgets = wp_get_sidebars_widgets();
if ( empty($wp_registered_sidebars[$index]) || !array_key_exists($index, $sidebars_widgets) || !is_array($sidebars_widgets[$index]) || empty($sidebars_widgets[$index]) )
return false;
$sidebar = $wp_registered_sidebars[$index];
$did_one = false;
foreach ( (array) $sidebars_widgets[$index] as $id ) {
if ( !isset($wp_registered_widgets[$id]) ) continue;
$params = array_merge(
array( array_merge( $sidebar, array('widget_id' => $id, 'widget_name' => $wp_registered_widgets[$id]['name']) ) ),
(array) $wp_registered_widgets[$id]['params']
);
// Substitute HTML id and class attributes into before_widget
$classname_ = '';
foreach ( (array) $wp_registered_widgets[$id]['classname'] as $cn ) {
if ( is_string($cn) )
$classname_ .= '_' . $cn;
elseif ( is_object($cn) )
$classname_ .= '_' . get_class($cn);
}
$classname_ = ltrim($classname_, '_');
$params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_);
$params = apply_filters( 'dynamic_sidebar_params', $params );
$callback = $wp_registered_widgets[$id]['callback'];
if ( is_callable($callback) ) {
call_user_func_array($callback, $params);
$did_one = true;
}
}
return $did_one;
}
/**
* Whether widget is displayied on the front-end.
*
* Either $callback or $id_base can be used
* $id_base is the first argument when extending WP_Widget class
* Without the optional $widget_id parameter, returns the ID of the first sidebar
* in which the first instance of the widget with the given callback or $id_base is found.
* With the $widget_id parameter, returns the ID of the sidebar where
* the widget with that callback/$id_base AND that ID is found.
*
* NOTE: $widget_id and $id_base are the same for single widgets. To be effective
* this function has to run after widgets have initialized, at action 'init' or later.
*
* @since 2.2.0
*
* @param callback Optional, Widget callback to check.
* @param int $widget_id Optional, but needed for checking. Widget ID.
* @param string $id_base Optional, the base ID of a widget created by extending WP_Widget.
* @param bool $skip_inactive Optional, whether to check in 'wp_inactive_widgets'.
* @return mixed false if widget is not active or id of sidebar in which the widget is active.
*/
function is_active_widget($callback = false, $widget_id = false, $id_base = false, $skip_inactive = true) {
global $wp_registered_widgets;
$sidebars_widgets = wp_get_sidebars_widgets();
if ( is_array($sidebars_widgets) ) {
foreach ( $sidebars_widgets as $sidebar => $widgets ) {
if ( $skip_inactive && 'wp_inactive_widgets' == $sidebar )
continue;
if ( is_array($widgets) ) {
foreach ( $widgets as $widget ) {
if ( ( $callback && isset($wp_registered_widgets[$widget]['callback']) && $wp_registered_widgets[$widget]['callback'] == $callback ) || ( $id_base && _get_widget_id_base($widget) == $id_base ) ) {
if ( !$widget_id || $widget_id == $wp_registered_widgets[$widget]['id'] )
return $sidebar;
}
}
}
}
}
return false;
}
/**
* Whether the dynamic sidebar is enabled and used by theme.
*
* @since 2.2.0
*
* @return bool True, if using widgets. False, if not using widgets.
*/
function is_dynamic_sidebar() {
global $wp_registered_widgets, $wp_registered_sidebars;
$sidebars_widgets = get_option('sidebars_widgets');
foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) {
if ( count($sidebars_widgets[$index]) ) {
foreach ( (array) $sidebars_widgets[$index] as $widget )
if ( array_key_exists($widget, $wp_registered_widgets) )
return true;
}
}
return false;
}
/**
* Whether a sidebar is in use.
*
* @since 2.8
*
* @param mixed $index, sidebar name, id or number to check.
* @return bool true if the sidebar is in use, false otherwise.
*/
function is_active_sidebar( $index ) {
$index = ( is_int($index) ) ? "sidebar-$index" : sanitize_title($index);
$sidebars_widgets = wp_get_sidebars_widgets();
if ( isset($sidebars_widgets[$index]) && !empty($sidebars_widgets[$index]) )
return true;
return false;
}
/* Internal Functions */
/**
* Retrieve full list of sidebars and their widgets.
*
* Will upgrade sidebar widget list, if needed. Will also save updated list, if
* needed.
*
* @since 2.2.0
* @access private
*
* @param bool $update Optional, deprecated.
* @return array Upgraded list of widgets to version 3 array format when called from the admin.
*/
function wp_get_sidebars_widgets($deprecated = true) {
global $wp_registered_widgets, $wp_registered_sidebars, $_wp_sidebars_widgets;
// If loading from front page, consult $_wp_sidebars_widgets rather than options
// to see if wp_convert_widget_settings() has made manipulations in memory.
if ( !is_admin() ) {
if ( empty($_wp_sidebars_widgets) )
$_wp_sidebars_widgets = get_option('sidebars_widgets', array());
$sidebars_widgets = $_wp_sidebars_widgets;
} else {
$sidebars_widgets = get_option('sidebars_widgets', array());
$_sidebars_widgets = array();
if ( isset($sidebars_widgets['wp_inactive_widgets']) )
$sidebars_widgets['array_version'] = 3;
elseif ( !isset($sidebars_widgets['array_version']) )
$sidebars_widgets['array_version'] = 1;
switch ( $sidebars_widgets['array_version'] ) {
case 1 :
foreach ( (array) $sidebars_widgets as $index => $sidebar )
if ( is_array($sidebar) )
foreach ( (array) $sidebar as $i => $name ) {
$id = strtolower($name);
if ( isset($wp_registered_widgets[$id]) ) {
$_sidebars_widgets[$index][$i] = $id;
continue;
}
$id = sanitize_title($name);
if ( isset($wp_registered_widgets[$id]) ) {
$_sidebars_widgets[$index][$i] = $id;
continue;
}
$found = false;
foreach ( $wp_registered_widgets as $widget_id => $widget ) {
if ( strtolower($widget['name']) == strtolower($name) ) {
$_sidebars_widgets[$index][$i] = $widget['id'];
$found = true;
break;
} elseif ( sanitize_title($widget['name']) == sanitize_title($name) ) {
$_sidebars_widgets[$index][$i] = $widget['id'];
$found = true;
break;
}
}
if ( $found )
continue;
unset($_sidebars_widgets[$index][$i]);
}
$_sidebars_widgets['array_version'] = 2;
$sidebars_widgets = $_sidebars_widgets;
unset($_sidebars_widgets);
case 2 :
$sidebars = array_keys( $wp_registered_sidebars );
if ( !empty( $sidebars ) ) {
// Move the known-good ones first
foreach ( (array) $sidebars as $id ) {
if ( array_key_exists( $id, $sidebars_widgets ) ) {
$_sidebars_widgets[$id] = $sidebars_widgets[$id];
unset($sidebars_widgets[$id], $sidebars[$id]);
}
}
// move the rest to wp_inactive_widgets
if ( !isset($_sidebars_widgets['wp_inactive_widgets']) )
$_sidebars_widgets['wp_inactive_widgets'] = array();
if ( !empty($sidebars_widgets) ) {
foreach ( $sidebars_widgets as $lost => $val ) {
if ( is_array($val) )
$_sidebars_widgets['wp_inactive_widgets'] = array_merge( (array) $_sidebars_widgets['wp_inactive_widgets'], $val );
}
}
$sidebars_widgets = $_sidebars_widgets;
unset($_sidebars_widgets);
}
}
}
if ( isset($sidebars_widgets['array_version']) )
unset($sidebars_widgets['array_version']);
$sidebars_widgets = apply_filters('sidebars_widgets', $sidebars_widgets);
return $sidebars_widgets;
}
/**
* Set the sidebar widget option to update sidebars.
*
* @since 2.2.0
* @access private
*
* @param array $sidebars_widgets Sidebar widgets and their settings.
*/
function wp_set_sidebars_widgets( $sidebars_widgets ) {
if ( !isset( $sidebars_widgets['array_version'] ) )
$sidebars_widgets['array_version'] = 3;
update_option( 'sidebars_widgets', $sidebars_widgets );
}
/**
* Retrieve default registered sidebars list.
*
* @since 2.2.0
* @access private
*
* @return array
*/
function wp_get_widget_defaults() {
global $wp_registered_sidebars;
$defaults = array();
foreach ( (array) $wp_registered_sidebars as $index => $sidebar )
$defaults[$index] = array();
return $defaults;
}
/**
* Convert the widget settings from single to multi-widget format.
*
* @since 2.8.0
*
* @return array
*/
function wp_convert_widget_settings($base_name, $option_name, $settings) {
// This test may need expanding.
$single = $changed = false;
if ( empty($settings) ) {
$single = true;
} else {
foreach ( array_keys($settings) as $number ) {
if ( 'number' == $number )
continue;
if ( !is_numeric($number) ) {
$single = true;
break;
}
}
}
if ( $single ) {
$settings = array( 2 => $settings );
// If loading from the front page, update sidebar in memory but don't save to options
if ( is_admin() ) {
$sidebars_widgets = get_option('sidebars_widgets');
} else {
if ( empty($GLOBALS['_wp_sidebars_widgets']) )
$GLOBALS['_wp_sidebars_widgets'] = get_option('sidebars_widgets', array());
$sidebars_widgets = &$GLOBALS['_wp_sidebars_widgets'];
}
foreach ( (array) $sidebars_widgets as $index => $sidebar ) {
if ( is_array($sidebar) ) {
foreach ( $sidebar as $i => $name ) {
if ( $base_name == $name ) {
$sidebars_widgets[$index][$i] = "$name-2";
$changed = true;
break 2;
}
}
}
}
if ( is_admin() && $changed )
update_option('sidebars_widgets', $sidebars_widgets);
}
$settings['_multiwidget'] = 1;
if ( is_admin() )
update_option( $option_name, $settings );
return $settings;
}
/**
* Deprecated API
*/
/**
* Register widget for sidebar with backwards compatibility.
*
* Allows $name to be an array that accepts either three elements to grab the
* first element and the third for the name or just uses the first element of
* the array for the name.
*
* Passes to {@link wp_register_sidebar_widget()} after argument list and
* backwards compatibility is complete.
*
* @since 2.2.0
* @uses wp_register_sidebar_widget() Passes the compiled arguments.
*
* @param string|int $name Widget ID.
* @param callback $output_callback Run when widget is called.
* @param string $classname Classname widget option.
* @param mixed $params,... Widget parameters.
*/
function register_sidebar_widget($name, $output_callback, $classname = '') {
// Compat
if ( is_array($name) ) {
if ( count($name) == 3 )
$name = sprintf($name[0], $name[2]);
else
$name = $name[0];
}
$id = sanitize_title($name);
$options = array();
if ( !empty($classname) && is_string($classname) )
$options['classname'] = $classname;
$params = array_slice(func_get_args(), 2);
$args = array($id, $name, $output_callback, $options);
if ( !empty($params) )
$args = array_merge($args, $params);
call_user_func_array('wp_register_sidebar_widget', $args);
}
/**
* Alias of {@link wp_unregister_sidebar_widget()}.
*
* @see wp_unregister_sidebar_widget()
*
* @since 2.2.0
*
* @param int|string $id Widget ID.
*/
function unregister_sidebar_widget($id) {
return wp_unregister_sidebar_widget($id);
}
/**
* Registers widget control callback for customizing options.
*
* Allows $name to be an array that accepts either three elements to grab the
* first element and the third for the name or just uses the first element of
* the array for the name.
*
* Passes to {@link wp_register_widget_control()} after the argument list has
* been compiled.
*
* @since 2.2.0
*
* @param int|string $name Sidebar ID.
* @param callback $control_callback Widget control callback to display and process form.
* @param int $width Widget width.
* @param int $height Widget height.
*/
function register_widget_control($name, $control_callback, $width = '', $height = '') {
// Compat
if ( is_array($name) ) {
if ( count($name) == 3 )
$name = sprintf($name[0], $name[2]);
else
$name = $name[0];
}
$id = sanitize_title($name);
$options = array();
if ( !empty($width) )
$options['width'] = $width;
if ( !empty($height) )
$options['height'] = $height;
$params = array_slice(func_get_args(), 4);
$args = array($id, $name, $control_callback, $options);
if ( !empty($params) )
$args = array_merge($args, $params);
call_user_func_array('wp_register_widget_control', $args);
}
/**
* Alias of {@link wp_unregister_widget_control()}.
*
* @since 2.2.0
* @see wp_unregister_widget_control()
*
* @param int|string $id Widget ID.
*/
function unregister_widget_control($id) {
return wp_unregister_widget_control($id);
}
/**
* Output an arbitrary widget as a template tag
*
* @since 2.8
*
* @param string $widget the widget's PHP class name (see default-widgets.php)
* @param array $instance the widget's instance settings
* @param array $args the widget's sidebar args
* @return void
**/
function the_widget($widget, $instance = array(), $args = array()) {
global $wp_widget_factory;
$widget_obj = $wp_widget_factory->widgets[$widget];
if ( !is_a($widget_obj, 'WP_Widget') )
return;
$before_widget = sprintf('
' . get_comment_author_link() . '', $comment_post_link." ".$comment_link, ' ' . __( '[Pending]' ) . '' ); ?>
comment_type ) : case 'pingback' : $type = __( 'Pingback' ); break; case 'trackback' : $type = __( 'Trackback' ); break; default : $type = ucwords( $comment->comment_type ); endswitch; $type = esc_html( $type ); ?>$type", $comment_post_link ); ?>
' . __('This widget requires JavaScript.') . '
'; } /** * Display incoming links dashboard widget content. * * @since unknown */ function wp_dashboard_incoming_links_output() { $widgets = get_option( 'dashboard_widget_options' ); @extract( @$widgets['dashboard_incoming_links'], EXTR_SKIP ); $rss = fetch_feed( $url ); if ( is_wp_error($rss) ) { if ( is_admin() || current_user_can('manage_options') ) { echo ''; printf(__('RSS Error: %s'), $rss->get_error_message()); echo '
'; } return; } if ( !$rss->get_item_quantity() ) { echo '' . __('This dashboard widget queries Google Blog Search so that when another blog links to your site it will show up here. It has found no incoming links… yet. It’s okay — there is no rush.') . "
\n"; return; } echo "\n"; if ( !isset($items) ) $items = 10; foreach ( $rss->get_items(0, $items) as $item ) { $publisher = ''; $site_link = ''; $link = ''; $content = ''; $date = ''; $link = esc_url( strip_tags( $item->get_link() ) ); $author = $item->get_author(); if ( $author ) { $site_link = esc_url( strip_tags( $author->get_link() ) ); if ( !$publisher = esc_html( strip_tags( $author->get_name() ) ) ) $publisher = __( 'Somebody' ); } else { $publisher = __( 'Somebody' ); } if ( $site_link ) $publisher = "$publisher"; else $publisher = "$publisher"; $content = $item->get_content(); $content = wp_html_excerpt($content, 50) . ' ...'; if ( $link ) /* translators: incoming links feed, %1$s is other person, %3$s is content */ $text = __( '%1$s linked here saying, "%3$s"' ); else /* translators: incoming links feed, %1$s is other person, %3$s is content */ $text = __( '%1$s linked here saying, "%3$s"' ); if ( $show_date ) { if ( $show_author || $show_summary ) /* translators: incoming links feed, %4$s is the date */ $text .= ' ' . __( 'on %4$s' ); $date = esc_html( strip_tags( $item->get_date() ) ); $date = strtotime( $date ); $date = gmdate( get_option( 'date_format' ), $date ); } echo "\t- " . sprintf( $text, $publisher, $link, $content, $date ) . "
\n";
}
echo "
\n"; } function wp_dashboard_incoming_links_control() { wp_dashboard_rss_control( 'dashboard_incoming_links', array( 'title' => false, 'show_summary' => false, 'show_author' => false ) ); } function wp_dashboard_primary() { echo '' . __( 'Loading…' ) . '
' . __('This widget requires JavaScript.') . '
'; } function wp_dashboard_primary_control() { wp_dashboard_rss_control( 'dashboard_primary' ); } /** * {@internal Missing Short Description}} * * @since unknown * * @param int $widget_id */ function wp_dashboard_rss_output( $widget_id ) { $widgets = get_option( 'dashboard_widget_options' ); echo "' . __( 'Loading…' ) . '
' . __('This widget requires JavaScript.') . '
'; } function wp_dashboard_secondary_control() { wp_dashboard_rss_control( 'dashboard_secondary' ); } /** * Display secondary dashboard RSS widget feed. * * @since unknown * * @return unknown */ function wp_dashboard_secondary_output() { $widgets = get_option( 'dashboard_widget_options' ); @extract( @$widgets['dashboard_secondary'], EXTR_SKIP ); $rss = @fetch_feed( $url ); if ( is_wp_error($rss) ) { if ( is_admin() || current_user_can('manage_options') ) { echo ''; printf(__('RSS Error: %s'), $rss->get_error_message()); echo '
' . __( 'Loading…' ) . '
' . __('This widget requires JavaScript.') . '
'; } /** * Display plugins most popular, newest plugins, and recently updated widget text. * * @since unknown */ function wp_dashboard_plugins_output() { $popular = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/popular/' ); $new = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/new/' ); $updated = fetch_feed( 'http://wordpress.org/extend/plugins/rss/browse/updated/' ); if ( false === $plugin_slugs = get_transient( 'plugin_slugs' ) ) { $plugin_slugs = array_keys( get_plugins() ); set_transient( 'plugin_slugs', $plugin_slugs, 86400 ); } foreach ( array( 'popular' => __('Most Popular'), 'new' => __('Newest Plugins'), 'updated' => __('Recently Updated') ) as $feed => $label ) { if ( is_wp_error($$feed) || !$$feed->get_item_quantity() ) continue; $items = $$feed->get_items(0, 5); // Pick a random, non-installed plugin while ( true ) { // Abort this foreach loop iteration if there's no plugins left of this type if ( 0 == count($items) ) continue 2; $item_key = array_rand($items); $item = $items[$item_key]; list($link, $frag) = explode( '#', $item->get_link() ); $link = esc_url($link); if ( preg_match( '|/([^/]+?)/?$|', $link, $matches ) ) $slug = $matches[1]; else { unset( $items[$item_key] ); continue; } // Is this random plugin's slug already installed? If so, try again. reset( $plugin_slugs ); foreach ( $plugin_slugs as $plugin_slug ) { if ( $slug == substr( $plugin_slug, 0, strlen( $slug ) ) ) { unset( $items[$item_key] ); continue 2; } } // If we get to this point, then the random plugin isn't installed and we can stop the while(). break; } // Eliminate some common badly formed plugin descriptions while ( ( null !== $item_key = array_rand($items) ) && false !== strpos( $items[$item_key]->get_description(), 'Plugin Name:' ) ) unset($items[$item_key]); if ( !isset($items[$item_key]) ) continue; // current bbPress feed item titles are: user on "topic title" if ( preg_match( '/"(.*)"/s', $item->get_title(), $matches ) ) $title = $matches[1]; else // but let's make it forward compatible if things change $title = $item->get_title(); $title = esc_html( $title ); $description = esc_html( strip_tags(@html_entity_decode($item->get_description(), ENT_QUOTES, get_option('blog_charset'))) ); $ilink = wp_nonce_url('plugin-install.php?tab=plugin-information&plugin=' . $slug, 'install-plugin_' . $slug) . '&TB_iframe=true&width=600&height=800'; echo "$label
\n"; echo "$title
(" . __( 'Install' ) . ")\n"; echo "$description
\n"; } } /** * Checks to see if all of the feed url in $check_urls are cached. * * If $check_urls is empty, look for the rss feed url found in the dashboard * widget optios of $widget_id. If cached, call $callback, a function that * echoes out output for this widget. If not cache, echo a "Loading..." stub * which is later replaced by AJAX call (see top of /wp-admin/index.php) * * @since unknown * * @param int $widget_id * @param callback $callback * @param array $check_urls RSS feeds * @return bool False on failure. True on success. */ function wp_dashboard_cached_rss_widget( $widget_id, $callback, $check_urls = array() ) { $loading = '' . __( 'Loading…' ) . '
'; if ( empty($check_urls) ) { $widgets = get_option( 'dashboard_widget_options' ); if ( empty($widgets[$widget_id]['url']) ) { echo $loading; return false; } $check_urls = array( $widgets[$widget_id]['url'] ); } include_once ABSPATH . WPINC . '/class-feed.php'; foreach ( $check_urls as $check_url ) { $cache = new WP_Feed_Cache_Transient('', md5($check_url), ''); if ( ! $cache->load() ) { echo $loading; return false; } } if ( $callback && is_callable( $callback ) ) { $args = array_slice( func_get_args(), 2 ); array_unshift( $args, $widget_id ); call_user_func_array( $callback, $args ); } return true; } /* Dashboard Widgets Controls */ // Calls widget_control callback /** * Calls widget control callback. * * @since unknown * * @param int $widget_control_id Registered Widget ID. */ function wp_dashboard_trigger_widget_control( $widget_control_id = false ) { global $wp_dashboard_control_callbacks; if ( is_scalar($widget_control_id) && $widget_control_id && isset($wp_dashboard_control_callbacks[$widget_control_id]) && is_callable($wp_dashboard_control_callbacks[$widget_control_id]) ) { call_user_func( $wp_dashboard_control_callbacks[$widget_control_id], '', array( 'id' => $widget_control_id, 'callback' => $wp_dashboard_control_callbacks[$widget_control_id] ) ); } } /** * The RSS dashboard widget control. * * Sets up $args to be used as input to wp_widget_rss_form(). Handles POST data * from RSS-type widgets. * * @since unknown * * @param string widget_id * @param array form_inputs */ function wp_dashboard_rss_control( $widget_id, $form_inputs = array() ) { if ( !$widget_options = get_option( 'dashboard_widget_options' ) ) $widget_options = array(); if ( !isset($widget_options[$widget_id]) ) $widget_options[$widget_id] = array(); $number = 1; // Hack to use wp_widget_rss_form() $widget_options[$widget_id]['number'] = $number; if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['widget-rss'][$number]) ) { $_POST['widget-rss'][$number] = stripslashes_deep( $_POST['widget-rss'][$number] ); $widget_options[$widget_id] = wp_widget_rss_process( $_POST['widget-rss'][$number] ); // title is optional. If black, fill it if possible if ( !$widget_options[$widget_id]['title'] && isset($_POST['widget-rss'][$number]['title']) ) { $rss = fetch_feed($widget_options[$widget_id]['url']); if ( ! is_wp_error($rss) ) $widget_options[$widget_id]['title'] = htmlentities(strip_tags($rss->get_title())); else $widget_options[$widget_id]['title'] = htmlentities(__('Unknown Feed')); } update_option( 'dashboard_widget_options', $widget_options ); } wp_widget_rss_form( $widget_options[$widget_id], $form_inputs ); } /** * Empty function usable by plugins to output empty dashboard widget (to be populated later by JS). */ function wp_dashboard_empty() {} ?> larscapo/wp-admin/includes/update-core.php 0000644 0041054 0041055 00000021723 11225447103 021344 0 ustar lacunaus lacunaus exists($from . '/wordpress/wp-settings.php') || !$wp_filesystem->exists($from . '/wordpress/wp-admin/admin.php') || !$wp_filesystem->exists($from . '/wordpress/wp-includes/functions.php') ) { $wp_filesystem->delete($from, true); return new WP_Error('insane_distro', __('The update could not be unpacked') ); } apply_filters('update_feedback', __('Installing the latest version')); // Create maintenance file to signal that we are upgrading $maintenance_string = ''; $maintenance_file = $to . '.maintenance'; $wp_filesystem->delete($maintenance_file); $wp_filesystem->put_contents($maintenance_file, $maintenance_string, FS_CHMOD_FILE); // Copy new versions of WP files into place. $result = copy_dir($from . '/wordpress', $to); if ( is_wp_error($result) ) { $wp_filesystem->delete($maintenance_file); $wp_filesystem->delete($from, true); return $result; } // Remove old files foreach ( $_old_files as $old_file ) { $old_file = $to . $old_file; if ( !$wp_filesystem->exists($old_file) ) continue; $wp_filesystem->delete($old_file, true); } // Upgrade DB with separate request apply_filters('update_feedback', __('Upgrading database')); $db_upgrade_url = admin_url('upgrade.php?step=upgrade_db'); wp_remote_post($db_upgrade_url, array('timeout' => 60)); // Remove working directory $wp_filesystem->delete($from, true); // Force refresh of update information if ( function_exists('delete_transient') ) delete_transient('update_core'); else delete_option('update_core'); // Remove maintenance file, we're done. $wp_filesystem->delete($maintenance_file); } ?> larscapo/wp-admin/includes/template.php 0000644 0041054 0041055 00000367604 11225447103 020762 0 ustar lacunaus lacunaus 0); if ( !empty($_GET['s']) ) $args['search'] = $_GET['s']; $categories = get_categories( $args ); if ( empty($categories) ) return false; } $children = _get_term_hierarchy('category'); _cat_rows( $parent, $level, $categories, $children, $page, $per_page, $count ); } /** * {@internal Missing Short Description}} * * @since unknown * * @param unknown_type $categories * @param unknown_type $count * @param unknown_type $parent * @param unknown_type $level * @param unknown_type $page * @param unknown_type $per_page * @return unknown */ function _cat_rows( $parent = 0, $level = 0, $categories, &$children, $page = 1, $per_page = 20, &$count ) { $start = ($page - 1) * $per_page; $end = $start + $per_page; ob_start(); foreach ( $categories as $key => $category ) { if ( $count >= $end ) break; if ( $category->parent != $parent && empty($_GET['s']) ) continue; // If the page starts in a subtree, print the parents. if ( $count == $start && $category->parent > 0 ) { $my_parents = array(); $p = $category->parent; while ( $p ) { $my_parent = get_category( $p ); $my_parents[] = $my_parent; if ( $my_parent->parent == 0 ) break; $p = $my_parent->parent; } $num_parents = count($my_parents); while( $my_parent = array_pop($my_parents) ) { echo "\t" . _cat_row( $my_parent, $level - $num_parents ); $num_parents--; } } if ( $count >= $start ) echo "\t" . _cat_row( $category, $level ); unset( $categories[ $key ] ); $count++; if ( isset($children[$category->term_id]) ) _cat_rows( $category->term_id, $level + 1, $categories, $children, $page, $per_page, $count ); } $output = ob_get_contents(); ob_end_clean(); echo $output; } /** * {@internal Missing Short Description}} * * @since unknown * * @param unknown_type $category * @param unknown_type $level * @param unknown_type $name_override * @return unknown */ function _cat_row( $category, $level, $name_override = false ) { static $row_class = ''; $category = get_category( $category, OBJECT, 'display' ); $default_cat_id = (int) get_option( 'default_category' ); $pad = str_repeat( '— ', max(0, $level) ); $name = ( $name_override ? $name_override : $pad . ' ' . $category->name ); $edit_link = "categories.php?action=edit&cat_ID=$category->term_id"; if ( current_user_can( 'manage_categories' ) ) { $edit = "name)) . "'>" . esc_attr( $name ) . ''; $actions = array(); $actions['edit'] = '' . __('Edit') . ''; $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; if ( $default_cat_id != $category->term_id ) $actions['delete'] = "term_id) . "'>" . __('Delete') . ""; $actions = apply_filters('cat_row_actions', $actions, $category); $action_count = count($actions); $i = 0; $edit .= '
"; $actions = array(); $actions['edit'] = '' . __('Edit') . ''; $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; if ( $default_cat_id != $category->term_id ) $actions['delete'] = "term_id) . "'>" . __('Delete') . ""; $actions = apply_filters('link_cat_row_actions', $actions, $category); $action_count = count($actions); $i = 0; $edit .= '
\n"; } function end_lvl(&$output, $depth, $args) { $indent = str_repeat("\t", $depth); $output .= "$indent
\n"; } function start_el(&$output, $category, $depth, $args) { extract($args); $class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : ''; $output .= "\n'; $actions = array(); $actions['edit'] = '' . __('Edit') . ''; $actions['inline hide-if-no-js'] = '' . __('Quick Edit') . ''; $actions['delete'] = "term_id) . "'>" . __('Delete') . ""; $actions = apply_filters('tag_row_actions', $actions, $tag); $action_count = count($actions); $i = 0; $out .= '
'; if ( 'publish' == $post->post_status ) { _e('Published'); } elseif ( 'future' == $post->post_status ) { if ( $time_diff > 0 ) echo '' . __('Missed schedule') . ''; else _e('Scheduled'); } else { _e('Last Modified'); } echo '
'; if ( 'publish' == $page->post_status ) { _e('Published'); } elseif ( 'future' == $page->post_status ) { if ( $time_diff > 0 ) echo '' . __('Missed schedule') . ''; else _e('Scheduled'); } else { _e('Last Modified'); } echo '
"; // Set up the hover actions for this user $actions = array(); $actions['edit'] = '' . __('Edit') . ''; if ( $current_user->ID != $user_object->ID ) $actions['delete'] = "" . __('Delete') . ""; $actions = apply_filters('user_row_actions', $actions, $user_object); $action_count = count($actions); $i = 0; $edit .= '
'; if ( !empty($author_url) ) echo "$author_url_display
"; if ( $user_can ) { if ( !empty($comment->comment_author_email) ) { comment_author_email_link(); echo '
'; } echo ''; comment_author_IP(); echo ''; } //current_user_can echo '
'; $pending_phrase = sprintf( __('%s pending'), number_format( $pending_comments ) ); if ( $pending_comments ) echo ''; comments_number("" . /* translators: comment count link */ _x('0', 'comment count') . '', "" . /* translators: comment count link */ _x('1', 'comment count') . '', "" . /* translators: comment count link: % will be substituted by comment count */ _x('%', 'comment count') . ''); if ( $pending_comments ) echo ''; echo ' '; echo "#"; echo '